file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
gitlab_pull_script.py
import requests import zipfile import io import json import os import traceback GITLAB_TOKEN="" token_header = {'PRIVATE-TOKEN': GITLAB_TOKEN} GROUP = 'zoe-apps' ZAPP_STORE_PATH = '/mnt/cephfs/zoe-apps/' def get_projects(group): prj_list = [] r = requests.get("http://gitlab.eurecom.fr/api/v4/groups/{}/projects".format(group), headers=token_header) for project in r.json(): prj_list.append((project['name'], project['id'])) return prj_list def get_images_from_zapp(zapp): images = [] for s in zapp['services']: images.append(s['image']) return images def pull_images(images): for image in images: print(image) os.system("docker -H 192.168.47.5:2380 pull {}".format(image)) def main(project_name, project):
if __name__ == "__main__": for p in get_projects(GROUP): try: main(*p) except Exception as e: traceback.print_exc() continue
r = requests.get("http://gitlab.eurecom.fr/api/v4/projects/{}/pipelines?status=success".format(project), headers=token_header) pipelines = r.json() if len(pipelines) > 0: latest_pipeline_run = pipelines[0]['id'] else: return r = requests.get("http://gitlab.eurecom.fr/api/v4/projects/{}/pipelines/{}/jobs?scope=success".format(project, latest_pipeline_run), headers=token_header) jobs = r.json() if len(jobs) == 0: return for good_job in jobs: r = requests.get("http://gitlab.eurecom.fr/api/v4/projects/{}/jobs/{}/artifacts".format(project, good_job['id']), headers=token_header) artifact = r.content f_obj = io.BytesIO(artifact) zp = zipfile.ZipFile(f_obj) for member in zp.namelist(): if member[-5:] != ".json" or member == "manifest.json": continue zapp_bytes = zp.read(member) zapp = json.loads(zapp_bytes.decode('utf-8')) images = get_images_from_zapp(zapp) pull_images(images) print(project_name + "/" + member) if os.path.exists(os.path.join(ZAPP_STORE_PATH, project_name)): open(os.path.join(ZAPP_STORE_PATH, project_name, member), 'wb').write(zapp_bytes)
doc.go
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. // Package networkconnectivity is an auto-generated package for the // Network Connectivity API. // // The Network Connectivity API provides access to Network Connectivity // Center. // // Example usage // // To get started with this package, create a client. // ctx := context.Background() // c, err := networkconnectivity.NewHubClient(ctx) // if err != nil { // // TODO: Handle error. // } // defer c.Close() // // The client will use your default application credentials. Clients should be reused instead of created as needed. // The methods of Client are safe for concurrent use by multiple goroutines. // The returned client must be Closed when it is done being used. // // Using the Client // // The following is an example of making an API call with the newly created client. // // ctx := context.Background() // c, err := networkconnectivity.NewHubClient(ctx) // if err != nil { // // TODO: Handle error. // } // defer c.Close() // // req := &networkconnectivitypb.ListHubsRequest{ // // TODO: Fill request struct fields. // // See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1#ListHubsRequest. // } // it := c.ListHubs(ctx, req) // for { // resp, err := it.Next() // if err == iterator.Done { // break // } // if err != nil { // // TODO: Handle error. // } // // TODO: Use resp. // _ = resp // } // // Use of Context // // The ctx passed to NewClient is used for authentication requests and // for creating the underlying connection, but is not used for subsequent calls. // Individual methods on the client use the ctx given to them. // // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more // please visit https://pkg.go.dev/cloud.google.com/go. package networkconnectivity // import "cloud.google.com/go/networkconnectivity/apiv1" import ( "context" "os" "runtime" "strconv" "strings" "unicode" "google.golang.org/api/option" "google.golang.org/grpc/metadata" ) // For more information on implementing a client constructor hook, see // https://github.com/googleapis/google-cloud-go/wiki/Customizing-constructors. type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) const versionClient = "20220207" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) out = out.Copy() for _, md := range mds { for k, v := range md { out[k] = append(out[k], v...) } } return metadata.NewOutgoingContext(ctx, out) } func checkDisableDeadlines() (bool, error) { raw, ok := os.LookupEnv("GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE") if !ok { return false, nil }
} // DefaultAuthScopes reports the default set of authentication scopes to use with this package. func DefaultAuthScopes() []string { return []string{ "https://www.googleapis.com/auth/cloud-platform", } } // versionGo returns the Go runtime version. The returned string // has no whitespace, suitable for reporting in header. func versionGo() string { const develPrefix = "devel +" s := runtime.Version() if strings.HasPrefix(s, develPrefix) { s = s[len(develPrefix):] if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { s = s[:p] } return s } notSemverRune := func(r rune) bool { return !strings.ContainsRune("0123456789.", r) } if strings.HasPrefix(s, "go1") { s = s[2:] var prerelease string if p := strings.IndexFunc(s, notSemverRune); p >= 0 { s, prerelease = s[:p], s[p:] } if strings.HasSuffix(s, ".") { s += "0" } else if strings.Count(s, ".") < 2 { s += ".0" } if prerelease != "" { s += "-" + prerelease } return s } return "UNKNOWN" }
b, err := strconv.ParseBool(raw) return b, err
nameserver.go
// Copyright (c) 2016, 2018, 2022, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // DNS API // // API for the DNS service. Use this API to manage DNS zones, records, and other DNS resources. // For more information, see Overview of the DNS Service (https://docs.cloud.oracle.com/iaas/Content/DNS/Concepts/dnszonemanagement.htm). // package dns import ( "fmt" "github.com/oracle/oci-go-sdk/v58/common" "strings" ) // Nameserver A server that has been set up to answer DNS queries for a zone. type Nameserver struct { // The hostname of the nameserver. Hostname *string `mandatory:"true" json:"hostname"`
func (m Nameserver) String() string { return common.PointerString(m) } // ValidateEnumValue returns an error when providing an unsupported enum value // This function is being called during constructing API request process // Not recommended for calling this function directly func (m Nameserver) ValidateEnumValue() (bool, error) { errMessage := []string{} if len(errMessage) > 0 { return true, fmt.Errorf(strings.Join(errMessage, "\n")) } return false, nil }
}
process_create_proposal.rs
//! Program state processor use borsh::BorshSerialize; use solana_program::{ account_info::{next_account_info, AccountInfo}, clock::Clock, entrypoint::ProgramResult, pubkey::Pubkey, rent::Rent, sysvar::Sysvar, }; use crate::{ error::GovernanceError, state::{ enums::{GovernanceAccountType, ProposalState}, governance::deserialize_governance_raw, proposal::{get_proposal_address_seeds, Proposal}, token_owner_record::deserialize_token_owner_record_for_realm_and_governing_mint, }, tools::{ account::create_and_serialize_account_signed, asserts::assert_token_owner_or_delegate_is_signer, }, }; /// Processes CreateProposal instruction pub fn process_create_proposal( program_id: &Pubkey, accounts: &[AccountInfo], name: String, description_link: String, governing_token_mint: Pubkey, ) -> ProgramResult { let account_info_iter = &mut accounts.iter(); let proposal_info = next_account_info(account_info_iter)?; // 0 let governance_info = next_account_info(account_info_iter)?; // 1 let token_owner_record_info = next_account_info(account_info_iter)?; // 2 let governance_authority_info = next_account_info(account_info_iter)?; // 3 let payer_info = next_account_info(account_info_iter)?; // 4 let system_info = next_account_info(account_info_iter)?; // 5 let rent_sysvar_info = next_account_info(account_info_iter)?; // 6 let rent = &Rent::from_account_info(rent_sysvar_info)?; let clock_info = next_account_info(account_info_iter)?; // 7 let clock = Clock::from_account_info(clock_info)?;
return Err(GovernanceError::ProposalAlreadyExists.into()); } let mut governance_data = deserialize_governance_raw(governance_info)?; let token_owner_record_data = deserialize_token_owner_record_for_realm_and_governing_mint( &token_owner_record_info, &governance_data.config.realm, &governing_token_mint, )?; // proposal_owner must be either governing token owner or governance_delegate and must sign this transaction assert_token_owner_or_delegate_is_signer(&token_owner_record_data, governance_authority_info)?; if token_owner_record_data.governing_token_deposit_amount < governance_data.config.min_tokens_to_create_proposal as u64 { return Err(GovernanceError::NotEnoughTokensToCreateProposal.into()); } let proposal_data = Proposal { account_type: GovernanceAccountType::Proposal, governance: *governance_info.key, governing_token_mint, state: ProposalState::Draft, token_owner_record: *token_owner_record_info.key, signatories_count: 0, signatories_signed_off_count: 0, name, description_link, draft_at: clock.slot, signing_off_at: None, voting_at: None, voting_completed_at: None, executing_at: None, closed_at: None, number_of_executed_instructions: 0, number_of_instructions: 0, }; create_and_serialize_account_signed::<Proposal>( payer_info, proposal_info, &proposal_data, &get_proposal_address_seeds( governance_info.key, &governing_token_mint, &governance_data.proposals_count.to_le_bytes(), ), program_id, system_info, rent, )?; governance_data.proposals_count = governance_data.proposals_count.checked_add(1).unwrap(); governance_data.serialize(&mut *governance_info.data.borrow_mut())?; Ok(()) }
if !proposal_info.data_is_empty() {
demo.py
import requests def demo():
''' 非小号API获取信息 :return btc,eth,eos ... pirce ''' print("start") #接口教程链接 https://github.com/xiaohao2019/API-docs/blob/master/PublicApi_CN.md url = "https://fxhapi.feixiaohao.com/public/v1/ticker/" #传入参数 start=[integer](指定结果集的开始排名) limit=[integer](指定结果集的最大数量) start = "start=" + str(0)+"&" limit = "limit=" + str(10) print(url+"?"+start+limit) try: response = requests.get(url=url+"?"+start+limit) for item in response.json(): print(item) print("获取完毕") except: print('error')
paths.py
import os # Finds path of any file in the assets folder # def
(folders, file, extension): # Checks if it's an array (or other type of list idk, basically this should do the job) # if(isinstance(folders, list)): # Default folder path, being nothing # folderPath = "" # Loops through all the folders # for x in folders: # Joins them together # folderPath = os.path.join(folderPath, x) return os.path.join("assets", folderPath, file + "." + extension) else: # Error handling, so the game doesn't just tell you that file doesn't exist # raise ValueError('The folder path you inputted, is not an array! Your folder path: "' + str(folders) + '"')
findPath
index.ts
/*
* Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ export { ForceFunctionContainerlessStartExecutor } from './ForceFunctionContainerlessStartExecutor'; export { ForceFunctionContainerStartExecutor } from './ForceFunctionContainerStartExecutor'; export { validateStartFunctionsUri } from './validateStartFunctionsUri';
* Copyright (c) 2022, salesforce.com, inc. * All rights reserved.
index.test.js
import Skill from './index'; import Request from 'alexa-request'; test('Launch intent', () => { const event = Request.launchRequest().build(); return expect(Skill(event)).resolves.toMatchSnapshot(); }); test('Hello intent', () => { const event = Request.intent('hello', { name: 'world' }).build(); return expect(Skill(event)).resolves.toMatchSnapshot(); }); test('Help intent', () => { const event = Request.intent('AMAZON.HelpIntent').build(); return expect(Skill(event)).resolves.toMatchSnapshot(); }); test('Stop intent', () => { const event = Request.intent('AMAZON.StopIntent').build(); return expect(Skill(event)).resolves.toMatchSnapshot(); }); test('Cancel intent', () => { const event = Request.intent('AMAZON.CancelIntent').build(); return expect(Skill(event)).resolves.toMatchSnapshot();
});
main.512d0eaf8c1b767ed315.js
(window.webpackJsonp=window.webpackJsonp||[]).push([[2],{0:function(n,t,e){n.exports=e("zUnb")},crnd:function(n,t){function e(n){return Promise.resolve().then(function(){var t=new Error("Cannot find module '"+n+"'");throw t.code="MODULE_NOT_FOUND",t})}e.keys=function(){return[]},e.resolve=e,n.exports=e,e.id="crnd"},zUnb:function(n,t,e){"use strict";e.r(t);var l=function(n,t){return(l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var e in t)t.hasOwnProperty(e)&&(n[e]=t[e])})(n,t)};function r(n,t){function e(){this.constructor=n}l(n,t),n.prototype=null===t?Object.create(t):(e.prototype=t.prototype,new e)}var o=function(){return(o=Object.assign||function(n){for(var t,e=1,l=arguments.length;e<l;e++)for(var r in t=arguments[e])Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}).apply(this,arguments)};function i(n,t,e,l){var r,o=arguments.length,i=o<3?t:null===l?l=Object.getOwnPropertyDescriptor(t,e):l;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(n,t,e,l);else for(var u=n.length-1;u>=0;u--)(r=n[u])&&(i=(o<3?r(i):o>3?r(t,e,i):r(t,e))||i);return o>3&&i&&Object.defineProperty(t,e,i),i}function u(n,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(n,t)}function a(n){var t="function"==typeof Symbol&&n[Symbol.iterator],e=0;return t?t.call(n):{next:function(){return n&&e>=n.length&&(n=void 0),{value:n&&n[e++],done:!n}}}}function s(n,t){var e="function"==typeof Symbol&&n[Symbol.iterator];if(!e)return n;var l,r,o=e.call(n),i=[];try{for(;(void 0===t||t-- >0)&&!(l=o.next()).done;)i.push(l.value)}catch(u){r={error:u}}finally{try{l&&!l.done&&(e=o.return)&&e.call(o)}finally{if(r)throw r.error}}return i}function c(){for(var n=[],t=0;t<arguments.length;t++)n=n.concat(s(arguments[t]));return n}var p=Array.isArray||function(n){return n&&"number"==typeof n.length};function h(n){return null!=n&&"object"==typeof n}function d(n){return"function"==typeof n}var f,g={e:{}};function m(){try{return f.apply(this,arguments)}catch(n){return g.e=n,g}}function y(n){return f=n,m}function v(n){return Error.call(this),this.message=n?n.length+" errors occurred during unsubscription:\n"+n.map(function(n,t){return t+1+") "+n.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=n,this}v.prototype=Object.create(Error.prototype);var _=v,b=function(){function n(n){this.closed=!1,this._parent=null,this._parents=null,this._subscriptions=null,n&&(this._unsubscribe=n)}var t;return n.prototype.unsubscribe=function(){var n,t=!1;if(!this.closed){var e=this._parent,l=this._parents,r=this._unsubscribe,o=this._subscriptions;this.closed=!0,this._parent=null,this._parents=null,this._subscriptions=null;for(var i=-1,u=l?l.length:0;e;)e.remove(this),e=++i<u&&l[i]||null;if(d(r)&&y(r).call(this)===g&&(t=!0,n=n||(g.e instanceof _?w(g.e.errors):[g.e])),p(o))for(i=-1,u=o.length;++i<u;){var a=o[i];if(h(a)&&y(a.unsubscribe).call(a)===g){t=!0,n=n||[];var s=g.e;s instanceof _?n=n.concat(w(s.errors)):n.push(s)}}if(t)throw new _(n)}},n.prototype.add=function(t){if(!t||t===n.EMPTY)return n.EMPTY;if(t===this)return this;var e=t;switch(typeof t){case"function":e=new n(t);case"object":if(e.closed||"function"!=typeof e.unsubscribe)return e;if(this.closed)return e.unsubscribe(),e;if("function"!=typeof e._addParent){var l=e;(e=new n)._subscriptions=[l]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}return(this._subscriptions||(this._subscriptions=[])).push(e),e._addParent(this),e},n.prototype.remove=function(n){var t=this._subscriptions;if(t){var e=t.indexOf(n);-1!==e&&t.splice(e,1)}},n.prototype._addParent=function(n){var t=this._parent,e=this._parents;t&&t!==n?e?-1===e.indexOf(n)&&e.push(n):this._parents=[n]:this._parent=n},n.EMPTY=((t=new n).closed=!0,t),n}();function w(n){return n.reduce(function(n,t){return n.concat(t instanceof _?t.errors:t)},[])}var C=!1,S={Promise:void 0,set useDeprecatedSynchronousErrorHandling(n){C=n},get useDeprecatedSynchronousErrorHandling(){return C}};function E(n){setTimeout(function(){throw n})}var x={closed:!0,next:function(n){},error:function(n){if(S.useDeprecatedSynchronousErrorHandling)throw n;E(n)},complete:function(){}},P="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),T=function(n){function t(e,l,r){var o=n.call(this)||this;switch(o.syncErrorValue=null,o.syncErrorThrown=!1,o.syncErrorThrowable=!1,o.isStopped=!1,o._parentSubscription=null,arguments.length){case 0:o.destination=x;break;case 1:if(!e){o.destination=x;break}if("object"==typeof e){e instanceof t?(o.syncErrorThrowable=e.syncErrorThrowable,o.destination=e,e.add(o)):(o.syncErrorThrowable=!0,o.destination=new I(o,e));break}default:o.syncErrorThrowable=!0,o.destination=new I(o,e,l,r)}return o}return r(t,n),t.prototype[P]=function(){return this},t.create=function(n,e,l){var r=new t(n,e,l);return r.syncErrorThrowable=!1,r},t.prototype.next=function(n){this.isStopped||this._next(n)},t.prototype.error=function(n){this.isStopped||(this.isStopped=!0,this._error(n))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this))},t.prototype._next=function(n){this.destination.next(n)},t.prototype._error=function(n){this.destination.error(n),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var n=this._parent,t=this._parents;return this._parent=null,this._parents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parent=n,this._parents=t,this._parentSubscription=null,this},t}(b),I=function(n){function t(t,e,l,r){var o,i=n.call(this)||this;i._parentSubscriber=t;var u=i;return d(e)?o=e:e&&(o=e.next,l=e.error,r=e.complete,e!==x&&(d((u=Object.create(e)).unsubscribe)&&i.add(u.unsubscribe.bind(u)),u.unsubscribe=i.unsubscribe.bind(i))),i._context=u,i._next=o,i._error=l,i._complete=r,i}return r(t,n),t.prototype.next=function(n){if(!this.isStopped&&this._next){var t=this._parentSubscriber;S.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,n)&&this.unsubscribe():this.__tryOrUnsub(this._next,n)}},t.prototype.error=function(n){if(!this.isStopped){var t=this._parentSubscriber,e=S.useDeprecatedSynchronousErrorHandling;if(this._error)e&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,n),this.unsubscribe()):(this.__tryOrUnsub(this._error,n),this.unsubscribe());else if(t.syncErrorThrowable)e?(t.syncErrorValue=n,t.syncErrorThrown=!0):E(n),this.unsubscribe();else{if(this.unsubscribe(),e)throw n;E(n)}}},t.prototype.complete=function(){var n=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var e=function(){return n._complete.call(n._context)};S.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,e),this.unsubscribe()):(this.__tryOrUnsub(e),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(n,t){try{n.call(this._context,t)}catch(e){if(this.unsubscribe(),S.useDeprecatedSynchronousErrorHandling)throw e;E(e)}},t.prototype.__tryOrSetError=function(n,t,e){if(!S.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,e)}catch(l){return S.useDeprecatedSynchronousErrorHandling?(n.syncErrorValue=l,n.syncErrorThrown=!0,!0):(E(l),!0)}return!1},t.prototype._unsubscribe=function(){var n=this._parentSubscriber;this._context=null,this._parentSubscriber=null,n.unsubscribe()},t}(T),O="function"==typeof Symbol&&Symbol.observable||"@@observable";function k(){}function D(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return A(n)}function A(n){return n?1===n.length?n[0]:function(t){return n.reduce(function(n,t){return t(n)},t)}:k}var R=function(){function n(n){this._isScalar=!1,n&&(this._subscribe=n)}return n.prototype.lift=function(t){var e=new n;return e.source=this,e.operator=t,e},n.prototype.subscribe=function(n,t,e){var l=this.operator,r=function(n,t,e){if(n){if(n instanceof T)return n;if(n[P])return n[P]()}return n||t||e?new T(n,t,e):new T(x)}(n,t,e);if(l?l.call(r,this.source):r.add(this.source||S.useDeprecatedSynchronousErrorHandling&&!r.syncErrorThrowable?this._subscribe(r):this._trySubscribe(r)),S.useDeprecatedSynchronousErrorHandling&&r.syncErrorThrowable&&(r.syncErrorThrowable=!1,r.syncErrorThrown))throw r.syncErrorValue;return r},n.prototype._trySubscribe=function(n){try{return this._subscribe(n)}catch(t){S.useDeprecatedSynchronousErrorHandling&&(n.syncErrorThrown=!0,n.syncErrorValue=t),function(n){for(;n;){var t=n.destination;if(n.closed||n.isStopped)return!1;n=t&&t instanceof T?t:null}return!0}(n)?n.error(t):console.warn(t)}},n.prototype.forEach=function(n,t){var e=this;return new(t=M(t))(function(t,l){var r;r=e.subscribe(function(t){try{n(t)}catch(e){l(e),r&&r.unsubscribe()}},l,t)})},n.prototype._subscribe=function(n){var t=this.source;return t&&t.subscribe(n)},n.prototype[O]=function(){return this},n.prototype.pipe=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return 0===n.length?this:A(n)(this)},n.prototype.toPromise=function(n){var t=this;return new(n=M(n))(function(n,e){var l;t.subscribe(function(n){return l=n},function(n){return e(n)},function(){return n(l)})})},n.create=function(t){return new n(t)},n}();function M(n){if(n||(n=S.Promise||Promise),!n)throw new Error("no Promise impl found");return n}function N(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}N.prototype=Object.create(Error.prototype);var L=N,V=function(n){function t(t,e){var l=n.call(this)||this;return l.subject=t,l.subscriber=e,l.closed=!1,l}return r(t,n),t.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var n=this.subject,t=n.observers;if(this.subject=null,t&&0!==t.length&&!n.isStopped&&!n.closed){var e=t.indexOf(this.subscriber);-1!==e&&t.splice(e,1)}}},t}(b),U=function(n){function t(t){var e=n.call(this,t)||this;return e.destination=t,e}return r(t,n),t}(T),j=function(n){function t(){var t=n.call(this)||this;return t.observers=[],t.closed=!1,t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return r(t,n),t.prototype[P]=function(){return new U(this)},t.prototype.lift=function(n){var t=new F(this,this);return t.operator=n,t},t.prototype.next=function(n){if(this.closed)throw new L;if(!this.isStopped)for(var t=this.observers,e=t.length,l=t.slice(),r=0;r<e;r++)l[r].next(n)},t.prototype.error=function(n){if(this.closed)throw new L;this.hasError=!0,this.thrownError=n,this.isStopped=!0;for(var t=this.observers,e=t.length,l=t.slice(),r=0;r<e;r++)l[r].error(n);this.observers.length=0},t.prototype.complete=function(){if(this.closed)throw new L;this.isStopped=!0;for(var n=this.observers,t=n.length,e=n.slice(),l=0;l<t;l++)e[l].complete();this.observers.length=0},t.prototype.unsubscribe=function(){this.isStopped=!0,this.closed=!0,this.observers=null},t.prototype._trySubscribe=function(t){if(this.closed)throw new L;return n.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(n){if(this.closed)throw new L;return this.hasError?(n.error(this.thrownError),b.EMPTY):this.isStopped?(n.complete(),b.EMPTY):(this.observers.push(n),new V(this,n))},t.prototype.asObservable=function(){var n=new R;return n.source=this,n},t.create=function(n,t){return new F(n,t)},t}(R),F=function(n){function t(t,e){var l=n.call(this)||this;return l.destination=t,l.source=e,l}return r(t,n),t.prototype.next=function(n){var t=this.destination;t&&t.next&&t.next(n)},t.prototype.error=function(n){var t=this.destination;t&&t.error&&this.destination.error(n)},t.prototype.complete=function(){var n=this.destination;n&&n.complete&&this.destination.complete()},t.prototype._subscribe=function(n){return this.source?this.source.subscribe(n):b.EMPTY},t}(j);function B(n){return n&&"function"==typeof n.schedule}var H=function(n){function t(t,e,l){var r=n.call(this)||this;return r.parent=t,r.outerValue=e,r.outerIndex=l,r.index=0,r}return r(t,n),t.prototype._next=function(n){this.parent.notifyNext(this.outerValue,n,this.outerIndex,this.index++,this)},t.prototype._error=function(n){this.parent.notifyError(n,this),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},t}(T),z=function(n){return function(t){for(var e=0,l=n.length;e<l&&!t.closed;e++)t.next(n[e]);t.closed||t.complete()}},q=function(n){return function(t){return n.then(function(n){t.closed||(t.next(n),t.complete())},function(n){return t.error(n)}).then(null,E),t}};function G(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var W=G(),Q=function(n){return function(t){for(var e=n[W]();;){var l=e.next();if(l.done){t.complete();break}if(t.next(l.value),t.closed)break}return"function"==typeof e.return&&t.add(function(){e.return&&e.return()}),t}},$=function(n){return function(t){var e=n[O]();if("function"!=typeof e.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return e.subscribe(t)}},K=function(n){return n&&"number"==typeof n.length&&"function"!=typeof n};function Z(n){return n&&"function"!=typeof n.subscribe&&"function"==typeof n.then}var Y=function(n){if(n instanceof R)return function(t){return n._isScalar?(t.next(n.value),void t.complete()):n.subscribe(t)};if(n&&"function"==typeof n[O])return $(n);if(K(n))return z(n);if(Z(n))return q(n);if(n&&"function"==typeof n[W])return Q(n);var t=h(n)?"an invalid object":"'"+n+"'";throw new TypeError("You provided "+t+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")};function X(n,t,e,l,r){if(void 0===r&&(r=new H(n,e,l)),!r.closed)return Y(t)(r)}var J=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.notifyNext=function(n,t,e,l,r){this.destination.next(t)},t.prototype.notifyError=function(n,t){this.destination.error(n)},t.prototype.notifyComplete=function(n){this.destination.complete()},t}(T);function nn(n,t){return function(e){if("function"!=typeof n)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return e.lift(new tn(n,t))}}var tn=function(){function n(n,t){this.project=n,this.thisArg=t}return n.prototype.call=function(n,t){return t.subscribe(new en(n,this.project,this.thisArg))},n}(),en=function(n){function t(t,e,l){var r=n.call(this,t)||this;return r.project=e,r.count=0,r.thisArg=l||r,r}return r(t,n),t.prototype._next=function(n){var t;try{t=this.project.call(this.thisArg,n,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(T);function ln(n,t){return new R(t?function(e){var l=new b,r=0;return l.add(t.schedule(function(){r!==n.length?(e.next(n[r++]),e.closed||l.add(this.schedule())):e.complete()})),l}:z(n))}function rn(n,t){if(!t)return n instanceof R?n:new R(Y(n));if(null!=n){if(function(n){return n&&"function"==typeof n[O]}(n))return function(n,t){return new R(t?function(e){var l=new b;return l.add(t.schedule(function(){var r=n[O]();l.add(r.subscribe({next:function(n){l.add(t.schedule(function(){return e.next(n)}))},error:function(n){l.add(t.schedule(function(){return e.error(n)}))},complete:function(){l.add(t.schedule(function(){return e.complete()}))}}))})),l}:$(n))}(n,t);if(Z(n))return function(n,t){return new R(t?function(e){var l=new b;return l.add(t.schedule(function(){return n.then(function(n){l.add(t.schedule(function(){e.next(n),l.add(t.schedule(function(){return e.complete()}))}))},function(n){l.add(t.schedule(function(){return e.error(n)}))})})),l}:q(n))}(n,t);if(K(n))return ln(n,t);if(function(n){return n&&"function"==typeof n[W]}(n)||"string"==typeof n)return function(n,t){if(!n)throw new Error("Iterable cannot be null");return new R(t?function(e){var l,r=new b;return r.add(function(){l&&"function"==typeof l.return&&l.return()}),r.add(t.schedule(function(){l=n[W](),r.add(t.schedule(function(){if(!e.closed){var n,t;try{var r=l.next();n=r.value,t=r.done}catch(o){return void e.error(o)}t?e.complete():(e.next(n),this.schedule())}}))})),r}:Q(n))}(n,t)}throw new TypeError((null!==n&&typeof n||n)+" is not observable")}function on(n,t,e){return void 0===e&&(e=Number.POSITIVE_INFINITY),"function"==typeof t?function(l){return l.pipe(on(function(e,l){return rn(n(e,l)).pipe(nn(function(n,r){return t(e,n,l,r)}))},e))}:("number"==typeof t&&(e=t),function(t){return t.lift(new un(n,e))})}var un=function(){function n(n,t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.project=n,this.concurrent=t}return n.prototype.call=function(n,t){return t.subscribe(new an(n,this.project,this.concurrent))},n}(),an=function(n){function t(t,e,l){void 0===l&&(l=Number.POSITIVE_INFINITY);var r=n.call(this,t)||this;return r.project=e,r.concurrent=l,r.hasCompleted=!1,r.buffer=[],r.active=0,r.index=0,r}return r(t,n),t.prototype._next=function(n){this.active<this.concurrent?this._tryNext(n):this.buffer.push(n)},t.prototype._tryNext=function(n){var t,e=this.index++;try{t=this.project(n,e)}catch(l){return void this.destination.error(l)}this.active++,this._innerSub(t,n,e)},t.prototype._innerSub=function(n,t,e){var l=new H(this,void 0,void 0);this.destination.add(l),X(this,n,t,e,l)},t.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},t.prototype.notifyNext=function(n,t,e,l,r){this.destination.next(t)},t.prototype.notifyComplete=function(n){var t=this.buffer;this.remove(n),this.active--,t.length>0?this._next(t.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(J);function sn(n){return n}function cn(n){return void 0===n&&(n=Number.POSITIVE_INFINITY),on(sn,n)}function pn(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=Number.POSITIVE_INFINITY,l=null,r=n[n.length-1];return B(r)?(l=n.pop(),n.length>1&&"number"==typeof n[n.length-1]&&(e=n.pop())):"number"==typeof r&&(e=n.pop()),null===l&&1===n.length&&n[0]instanceof R?n[0]:cn(e)(ln(n,l))}function hn(){return function(n){return n.lift(new dn(n))}}var dn=function(){function n(n){this.connectable=n}return n.prototype.call=function(n,t){var e=this.connectable;e._refCount++;var l=new fn(n,e),r=t.subscribe(l);return l.closed||(l.connection=e.connect()),r},n}(),fn=function(n){function t(t,e){var l=n.call(this,t)||this;return l.connectable=e,l}return r(t,n),t.prototype._unsubscribe=function(){var n=this.connectable;if(n){this.connectable=null;var t=n._refCount;if(t<=0)this.connection=null;else if(n._refCount=t-1,t>1)this.connection=null;else{var e=this.connection,l=n._connection;this.connection=null,!l||e&&l!==e||l.unsubscribe()}}else this.connection=null},t}(T),gn=function(n){function t(t,e){var l=n.call(this)||this;return l.source=t,l.subjectFactory=e,l._refCount=0,l._isComplete=!1,l}return r(t,n),t.prototype._subscribe=function(n){return this.getSubject().subscribe(n)},t.prototype.getSubject=function(){var n=this._subject;return n&&!n.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype.connect=function(){var n=this._connection;return n||(this._isComplete=!1,(n=this._connection=new b).add(this.source.subscribe(new yn(this.getSubject(),this))),n.closed?(this._connection=null,n=b.EMPTY):this._connection=n),n},t.prototype.refCount=function(){return hn()(this)},t}(R).prototype,mn={operator:{value:null},_refCount:{value:0,writable:!0},_subject:{value:null,writable:!0},_connection:{value:null,writable:!0},_subscribe:{value:gn._subscribe},_isComplete:{value:gn._isComplete,writable:!0},getSubject:{value:gn.getSubject},connect:{value:gn.connect},refCount:{value:gn.refCount}},yn=function(n){function t(t,e){var l=n.call(this,t)||this;return l.connectable=e,l}return r(t,n),t.prototype._error=function(t){this._unsubscribe(),n.prototype._error.call(this,t)},t.prototype._complete=function(){this.connectable._isComplete=!0,this._unsubscribe(),n.prototype._complete.call(this)},t.prototype._unsubscribe=function(){var n=this.connectable;if(n){this.connectable=null;var t=n._connection;n._refCount=0,n._subject=null,n._connection=null,t&&t.unsubscribe()}},t}(U);function vn(){return new j}function _n(n){for(var t in n)if(n[t]===_n)return t;throw Error("Could not find renamed property on target object.")}var bn=_n({ngInjectableDef:_n});function wn(n){return{providedIn:n.providedIn||null,factory:n.factory,value:void 0}}function Cn(n){return n&&n.hasOwnProperty(bn)?n[bn]:null}var Sn=function(){function n(n,t){this._desc=n,this.ngMetadataName="InjectionToken",this.ngInjectableDef=void 0!==t?wn({providedIn:t.providedIn||"root",factory:t.factory}):void 0}return n.prototype.toString=function(){return"InjectionToken "+this._desc},n}(),En="__parameters__";function xn(n,t,e){var l=function(n){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(n){var l=n.apply(void 0,c(t));for(var r in l)this[r]=l[r]}}}(t);function r(){for(var n,t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];if(this instanceof r)return l.apply(this,t),this;var o=new((n=r).bind.apply(n,c([void 0],t)));return i.annotation=o,i;function i(n,t,e){for(var l=n.hasOwnProperty(En)?n[En]:Object.defineProperty(n,En,{value:[]})[En];l.length<=e;)l.push(null);return(l[e]=l[e]||[]).push(o),n}}return e&&(r.prototype=Object.create(e.prototype)),r.prototype.ngMetadataName=n,r.annotationCls=r,r}var Pn=new Sn("AnalyzeForEntryComponents"),Tn="undefined"!=typeof window&&window,In="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,On="undefined"!=typeof global&&global||Tn||In,kn=Promise.resolve(0),Dn=null;function An(){if(!Dn){var n=On.Symbol;if(n&&n.iterator)Dn=n.iterator;else for(var t=Object.getOwnPropertyNames(Map.prototype),e=0;e<t.length;++e){var l=t[e];"entries"!==l&&"size"!==l&&Map.prototype[l]===Map.prototype.entries&&(Dn=l)}}return Dn}function Rn(n){"undefined"==typeof Zone?kn.then(function(){n&&n.apply(null,null)}):Zone.current.scheduleMicroTask("scheduleMicrotask",n)}function Mn(n,t){return n===t||"number"==typeof n&&"number"==typeof t&&isNaN(n)&&isNaN(t)}function Nn(n){if("string"==typeof n)return n;if(n instanceof Array)return"["+n.map(Nn).join(", ")+"]";if(null==n)return""+n;if(n.overriddenName)return""+n.overriddenName;if(n.name)return""+n.name;var t=n.toString();if(null==t)return""+t;var e=t.indexOf("\n");return-1===e?t:t.substring(0,e)}var Ln=_n({__forward_ref__:_n});function Vn(n){return n.__forward_ref__=Vn,n.toString=function(){return Nn(this())},n}function Un(n){var t=n;return"function"==typeof t&&t.hasOwnProperty(Ln)&&t.__forward_ref__===Vn?t():n}var jn,Fn=function(n){return n[n.Emulated=0]="Emulated",n[n.Native=1]="Native",n[n.None=2]="None",n[n.ShadowDom=3]="ShadowDom",n}({}),Bn=xn("Inject",function(n){return{token:n}}),Hn=xn("Optional"),zn=xn("Self"),qn=xn("SkipSelf"),Gn=function(n){return n[n.Default=0]="Default",n[n.Host=1]="Host",n[n.Self=2]="Self",n[n.SkipSelf=4]="SkipSelf",n[n.Optional=8]="Optional",n}({}),Wn=void 0;function Qn(n){var t=Wn;return Wn=n,t}function $n(n,t){return void 0===t&&(t=Gn.Default),(jn||function(n,t){if(void 0===t&&(t=Gn.Default),void 0===Wn)throw new Error("inject() must be called from an injection context");return null===Wn?function(n,t,e){var l=Cn(n);if(l&&"root"==l.providedIn)return void 0===l.value?l.value=l.factory():l.value;if(e&Gn.Optional)return null;throw new Error("Injector: NOT_FOUND ["+Nn(n)+"]")}(n,0,t):Wn.get(n,t&Gn.Optional?null:void 0,t)})(n,t)}var Kn=/([A-Z])/g;function Zn(n){try{return null!=n?n.toString().slice(0,30):n}catch(t){return"[ERROR] Exception while trying to serialize the value"}}function Yn(n,t){var e=nt(n),l=nt(t);return e&&l?function(n,t,e){for(var l=n[An()](),r=t[An()]();;){var o=l.next(),i=r.next();if(o.done&&i.done)return!0;if(o.done||i.done)return!1;if(!e(o.value,i.value))return!1}}(n,t,Yn):!(e||!n||"object"!=typeof n&&"function"!=typeof n||l||!t||"object"!=typeof t&&"function"!=typeof t)||Mn(n,t)}var Xn=function(){function n(n){this.wrapped=n}return n.wrap=function(t){return new n(t)},n.unwrap=function(t){return n.isWrapped(t)?t.wrapped:t},n.isWrapped=function(t){return t instanceof n},n}(),Jn=function(){function n(n,t,e){this.previousValue=n,this.currentValue=t,this.firstChange=e}return n.prototype.isFirstChange=function(){return this.firstChange},n}();function nt(n){return!!tt(n)&&(Array.isArray(n)||!(n instanceof Map)&&An()in n)}function tt(n){return null!==n&&("function"==typeof n||"object"==typeof n)}function et(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t]}var lt="__source",rt=new Object,ot=new Sn("INJECTOR"),it=function(){function n(){}return n.prototype.get=function(n,t){if(void 0===t&&(t=rt),t===rt)throw new Error("NullInjectorError: No provider for "+Nn(n)+"!");return t},n}(),ut=function(){function n(){}return n.create=function(n,t){return Array.isArray(n)?new yt(n,t):new yt(n.providers,n.parent,n.name||null)},n.THROW_IF_NOT_FOUND=rt,n.NULL=new it,n.ngInjectableDef=wn({providedIn:"any",factory:function(){return $n(ot)}}),n.__NG_ELEMENT_ID__=function(){return at()},n}(),at=et,st=function(n){return n},ct=[],pt=st,ht=function(){return Array.prototype.slice.call(arguments)},dt=_n({provide:String,useValue:_n}),ft=ut.NULL,gt=/\n/gm,mt="\u0275",yt=function(){function n(n,t,e){void 0===t&&(t=ft),void 0===e&&(e=null),this.parent=t,this.source=e;var l=this._records=new Map;l.set(ut,{token:ut,fn:st,deps:ct,value:this,useNew:!1}),l.set(ot,{token:ot,fn:st,deps:ct,value:this,useNew:!1}),function n(t,e){if(e)if((e=Un(e))instanceof Array)for(var l=0;l<e.length;l++)n(t,e[l]);else{if("function"==typeof e)throw bt("Function/Class not supported",e);if(!e||"object"!=typeof e||!e.provide)throw bt("Unexpected provider",e);var r=Un(e.provide),o=function(n){var t=function(n){var t=ct,e=n.deps;if(e&&e.length){t=[];for(var l=0;l<e.length;l++){var r=6;if((a=Un(e[l]))instanceof Array)for(var o=0,i=a;o<i.length;o++){var u=i[o];u instanceof Hn||u==Hn?r|=1:u instanceof qn||u==qn?r&=-3:u instanceof zn||u==zn?r&=-5:a=u instanceof Bn?u.token:Un(u)}t.push({token:a,options:r})}}else if(n.useExisting){var a;t=[{token:a=Un(n.useExisting),options:6}]}else if(!(e||dt in n))throw bt("'deps' required",n);return t}(n),e=st,l=ct,r=!1,o=Un(n.provide);if(dt in n)l=n.useValue;else if(n.useFactory)e=n.useFactory;else if(n.useExisting);else if(n.useClass)r=!0,e=Un(n.useClass);else{if("function"!=typeof o)throw bt("StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable",n);r=!0,e=o}return{deps:t,fn:e,useNew:r,value:l}}(e);if(!0===e.multi){var i=t.get(r);if(i){if(i.fn!==ht)throw vt(r)}else t.set(r,i={token:e.provide,deps:[],useNew:!1,fn:ht,value:ct});i.deps.push({token:r=e,options:6})}var u=t.get(r);if(u&&u.fn==ht)throw vt(r);t.set(r,o)}}(l,n)}return n.prototype.get=function(n,t,e){void 0===e&&(e=Gn.Default);var l=this._records.get(n);try{return function n(t,e,l,r,o,i){try{return function(t,e,l,r,o,i){var u,a;if(!e||i&Gn.SkipSelf)i&Gn.Self||(a=r.get(t,o,Gn.Default));else{if((a=e.value)==pt)throw Error(mt+"Circular dependency");if(a===ct){e.value=pt;var s=e.useNew,p=e.fn,h=e.deps,d=ct;if(h.length){d=[];for(var f=0;f<h.length;f++){var g=h[f],m=g.options,y=2&m?l.get(g.token):void 0;d.push(n(g.token,y,l,y||4&m?r:ft,1&m?null:ut.THROW_IF_NOT_FOUND,Gn.Default))}}e.value=a=s?new((u=p).bind.apply(u,c([void 0],d))):p.apply(void 0,d)}}return a}(t,e,l,r,o,i)}catch(u){throw u instanceof Error||(u=new Error(u)),(u.ngTempTokenPath=u.ngTempTokenPath||[]).unshift(t),e&&e.value==pt&&(e.value=ct),u}}(n,l,this._records,this.parent,t,e)}catch(o){var r=o.ngTempTokenPath;throw n[lt]&&r.unshift(n[lt]),o.message=_t("\n"+o.message,r,this.source),o.ngTokenPath=r,o.ngTempTokenPath=null,o}},n.prototype.toString=function(){var n=[];return this._records.forEach(function(t,e){return n.push(Nn(e))}),"StaticInjector["+n.join(", ")+"]"},n}();function vt(n){return bt("Cannot mix multi providers and regular providers",n)}function _t(n,t,e){void 0===e&&(e=null),n=n&&"\n"===n.charAt(0)&&n.charAt(1)==mt?n.substr(2):n;var l=Nn(t);if(t instanceof Array)l=t.map(Nn).join(" -> ");else if("object"==typeof t){var r=[];for(var o in t)if(t.hasOwnProperty(o)){var i=t[o];r.push(o+":"+("string"==typeof i?JSON.stringify(i):Nn(i)))}l="{"+r.join(", ")+"}"}return"StaticInjectorError"+(e?"("+e+")":"")+"["+l+"]: "+n.replace(gt,"\n ")}function bt(n,t){return new Error(_t(n,t))}var wt=new Sn("The presence of this token marks an injector as being the root injector."),Ct=function(){return function(){}}(),St=function(){return function(){}}();function Et(n){var t=Error("No component factory found for "+Nn(n)+". Did you add it to @NgModule.entryComponents?");return t[xt]=n,t}var xt="ngComponent",Pt=function(){function n(){}return n.prototype.resolveComponentFactory=function(n){throw Et(n)},n}(),Tt=function(){function n(){}return n.NULL=new Pt,n}(),It=function(){function n(n,t,e){this._parent=t,this._ngModule=e,this._factories=new Map;for(var l=0;l<n.length;l++){var r=n[l];this._factories.set(r.componentType,r)}}return n.prototype.resolveComponentFactory=function(n){var t=this._factories.get(n);if(!t&&this._parent&&(t=this._parent.resolveComponentFactory(n)),!t)throw Et(n);return new Ot(t,this._ngModule)},n}(),Ot=function(n){function t(t,e){var l=n.call(this)||this;return l.factory=t,l.ngModule=e,l.selector=t.selector,l.componentType=t.componentType,l.ngContentSelectors=t.ngContentSelectors,l.inputs=t.inputs,l.outputs=t.outputs,l}return r(t,n),t.prototype.create=function(n,t,e,l){return this.factory.create(n,t,e,l||this.ngModule)},t}(St),kt=function(){return function(){}}(),Dt=function(){return function(){}}(),At=function(){function n(n){this.nativeElement=n}return n.__NG_ELEMENT_ID__=function(){return Rt(n)},n}(),Rt=et,Mt=function(){return function(){}}(),Nt=function(){return function(){}}(),Lt=function(n){return n[n.Important=1]="Important",n[n.DashCase=2]="DashCase",n}({}),Vt=function(){function n(){}return n.__NG_ELEMENT_ID__=function(){return Ut()},n}(),Ut=et,jt=function(n){return n[n.NONE=0]="NONE",n[n.HTML=1]="HTML",n[n.STYLE=2]="STYLE",n[n.SCRIPT=3]="SCRIPT",n[n.URL=4]="URL",n[n.RESOURCE_URL=5]="RESOURCE_URL",n}({}),Ft=function(){return function(){}}(),Bt=new(function(){return function(n){this.full=n,this.major=n.split(".")[0],this.minor=n.split(".")[1],this.patch=n.split(".").slice(2).join(".")}}())("7.2.15"),Ht=!0,zt=!1;function qt(){return zt=!0,Ht}var Gt=function(){function n(n){if(this.defaultDoc=n,this.inertDocument=this.defaultDoc.implementation.createHTMLDocument("sanitization-inert"),this.inertBodyElement=this.inertDocument.body,null==this.inertBodyElement){var t=this.inertDocument.createElement("html");this.inertDocument.appendChild(t),this.inertBodyElement=this.inertDocument.createElement("body"),t.appendChild(this.inertBodyElement)}this.inertBodyElement.innerHTML='<svg><g onload="this.parentNode.remove()"></g></svg>',!this.inertBodyElement.querySelector||this.inertBodyElement.querySelector("svg")?(this.inertBodyElement.innerHTML='<svg><p><style><img src="</style><img src=x onerror=alert(1)//">',this.getInertBodyElement=this.inertBodyElement.querySelector&&this.inertBodyElement.querySelector("svg img")&&function(){try{return!!window.DOMParser}catch(n){return!1}}()?this.getInertBodyElement_DOMParser:this.getInertBodyElement_InertDocument):this.getInertBodyElement=this.getInertBodyElement_XHR}return n.prototype.getInertBodyElement_XHR=function(n){n="<body><remove></remove>"+n+"</body>";try{n=encodeURI(n)}catch(l){return null}var t=new XMLHttpRequest;t.responseType="document",t.open("GET","data:text/html;charset=utf-8,"+n,!1),t.send(void 0);var e=t.response.body;return e.removeChild(e.firstChild),e},n.prototype.getInertBodyElement_DOMParser=function(n){n="<body><remove></remove>"+n+"</body>";try{var t=(new window.DOMParser).parseFromString(n,"text/html").body;return t.removeChild(t.firstChild),t}catch(e){return null}},n.prototype.getInertBodyElement_InertDocument=function(n){var t=this.inertDocument.createElement("template");return"content"in t?(t.innerHTML=n,t):(this.inertBodyElement.innerHTML=n,this.defaultDoc.documentMode&&this.stripCustomNsAttrs(this.inertBodyElement),this.inertBodyElement)},n.prototype.stripCustomNsAttrs=function(n){for(var t=n.attributes,e=t.length-1;0<e;e--){var l=t.item(e).name;"xmlns:ns1"!==l&&0!==l.indexOf("ns1:")||n.removeAttribute(l)}for(var r=n.firstChild;r;)r.nodeType===Node.ELEMENT_NODE&&this.stripCustomNsAttrs(r),r=r.nextSibling},n}(),Wt=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:\/?#]*(?:[\/?#]|$))/gi,Qt=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i;function $t(n){return(n=String(n)).match(Wt)||n.match(Qt)?n:(qt()&&console.warn("WARNING: sanitizing unsafe URL value "+n+" (see http://g.co/ng/security#xss)"),"unsafe:"+n)}function Kt(n){var t,e,l={};try{for(var r=a(n.split(",")),o=r.next();!o.done;o=r.next())l[o.value]=!0}catch(i){t={error:i}}finally{try{o&&!o.done&&(e=r.return)&&e.call(r)}finally{if(t)throw t.error}}return l}function Zt(){for(var n,t,e=[],l=0;l<arguments.length;l++)e[l]=arguments[l];var r={};try{for(var o=a(e),i=o.next();!i.done;i=o.next()){var u=i.value;for(var s in u)u.hasOwnProperty(s)&&(r[s]=!0)}}catch(c){n={error:c}}finally{try{i&&!i.done&&(t=o.return)&&t.call(o)}finally{if(n)throw n.error}}return r}var Yt,Xt=Kt("area,br,col,hr,img,wbr"),Jt=Kt("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),ne=Kt("rp,rt"),te=Zt(ne,Jt),ee=Zt(Xt,Zt(Jt,Kt("address,article,aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul")),Zt(ne,Kt("a,abbr,acronym,audio,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video")),te),le=Kt("background,cite,href,itemtype,longdesc,poster,src,xlink:href"),re=Kt("srcset"),oe=Zt(le,re,Kt("abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,scope,scrolling,shape,size,sizes,span,srclang,start,summary,tabindex,target,title,translate,type,usemap,valign,value,vspace,width")),ie=Kt("script,style,template"),ue=function(){function n(){this.sanitizedSomething=!1,this.buf=[]}return n.prototype.sanitizeChildren=function(n){for(var t=n.firstChild,e=!0;t;)if(t.nodeType===Node.ELEMENT_NODE?e=this.startElement(t):t.nodeType===Node.TEXT_NODE?this.chars(t.nodeValue):this.sanitizedSomething=!0,e&&t.firstChild)t=t.firstChild;else for(;t;){t.nodeType===Node.ELEMENT_NODE&&this.endElement(t);var l=this.checkClobberedElement(t,t.nextSibling);if(l){t=l;break}t=this.checkClobberedElement(t,t.parentNode)}return this.buf.join("")},n.prototype.startElement=function(n){var t,e=n.nodeName.toLowerCase();if(!ee.hasOwnProperty(e))return this.sanitizedSomething=!0,!ie.hasOwnProperty(e);this.buf.push("<"),this.buf.push(e);for(var l=n.attributes,r=0;r<l.length;r++){var o=l.item(r),i=o.name,u=i.toLowerCase();if(oe.hasOwnProperty(u)){var a=o.value;le[u]&&(a=$t(a)),re[u]&&(t=a,a=(t=String(t)).split(",").map(function(n){return $t(n.trim())}).join(", ")),this.buf.push(" ",i,'="',ce(a),'"')}else this.sanitizedSomething=!0}return this.buf.push(">"),!0},n.prototype.endElement=function(n){var t=n.nodeName.toLowerCase();ee.hasOwnProperty(t)&&!Xt.hasOwnProperty(t)&&(this.buf.push("</"),this.buf.push(t),this.buf.push(">"))},n.prototype.chars=function(n){this.buf.push(ce(n))},n.prototype.checkClobberedElement=function(n,t){if(t&&(n.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_CONTAINED_BY)===Node.DOCUMENT_POSITION_CONTAINED_BY)throw new Error("Failed to sanitize html because the element is clobbered: "+n.outerHTML);return t},n}(),ae=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,se=/([^\#-~ |!])/g;function ce(n){return n.replace(/&/g,"&amp;").replace(ae,function(n){return"&#"+(1024*(n.charCodeAt(0)-55296)+(n.charCodeAt(1)-56320)+65536)+";"}).replace(se,function(n){return"&#"+n.charCodeAt(0)+";"}).replace(/</g,"&lt;").replace(/>/g,"&gt;")}function pe(n){return"content"in n&&function(n){return n.nodeType===Node.ELEMENT_NODE&&"TEMPLATE"===n.nodeName}(n)?n.content:null}var he=function(n){function t(t){void 0===t&&(t=!1);var e=n.call(this)||this;return e.__isAsync=t,e}return r(t,n),t.prototype.emit=function(t){n.prototype.next.call(this,t)},t.prototype.subscribe=function(t,e,l){var r,o=function(n){return null},i=function(){return null};t&&"object"==typeof t?(r=this.__isAsync?function(n){setTimeout(function(){return t.next(n)})}:function(n){t.next(n)},t.error&&(o=this.__isAsync?function(n){setTimeout(function(){return t.error(n)})}:function(n){t.error(n)}),t.complete&&(i=this.__isAsync?function(){setTimeout(function(){return t.complete()})}:function(){t.complete()})):(r=this.__isAsync?function(n){setTimeout(function(){return t(n)})}:function(n){t(n)},e&&(o=this.__isAsync?function(n){setTimeout(function(){return e(n)})}:function(n){e(n)}),l&&(i=this.__isAsync?function(){setTimeout(function(){return l()})}:function(){l()}));var u=n.prototype.subscribe.call(this,r,o,i);return t instanceof b&&t.add(u),u},t}(j),de=function(){function n(){}return n.__NG_ELEMENT_ID__=function(){return fe(n,At)},n}(),fe=et,ge=new RegExp("^([-,.\"'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?|(?:repeating-)?(?:linear|radial)-gradient|(?:calc|attr))\\([-0-9.%, #a-zA-Z]+\\))$","g"),me=/^url\(([^)]+)\)$/,ye=function(){return function(){}}(),ve="ngDebugContext",_e="ngOriginalError",be="ngErrorLogger";function we(n){return n[ve]}function Ce(n){return n[_e]}function Se(n){for(var t=[],e=1;e<arguments.length;e++)t[e-1]=arguments[e];n.error.apply(n,c(t))}var Ee=function(){function n(){this._console=console}return n.prototype.handleError=function(n){var t=this._findOriginalError(n),e=this._findContext(n),l=function(n){return n[be]||Se}(n);l(this._console,"ERROR",n),t&&l(this._console,"ORIGINAL ERROR",t),e&&l(this._console,"ERROR CONTEXT",e)},n.prototype._findContext=function(n){return n?we(n)?we(n):this._findContext(Ce(n)):null},n.prototype._findOriginalError=function(n){for(var t=Ce(n);t&&Ce(t);)t=Ce(t);return t},n}();function xe(n){return!!n&&"function"==typeof n.then}function Pe(n){return!!n&&"function"==typeof n.subscribe}var Te=new Sn("Application Initializer"),Ie=function(){function n(n){var t=this;this.appInits=n,this.initialized=!1,this.done=!1,this.donePromise=new Promise(function(n,e){t.resolve=n,t.reject=e})}return n.prototype.runInitializers=function(){var n=this;if(!this.initialized){var t=[],e=function(){n.done=!0,n.resolve()};if(this.appInits)for(var l=0;l<this.appInits.length;l++){var r=this.appInits[l]();xe(r)&&t.push(r)}Promise.all(t).then(function(){e()}).catch(function(t){n.reject(t)}),0===t.length&&e(),this.initialized=!0}},n}(),Oe=new Sn("AppId");function ke(){return""+De()+De()+De()}function De(){return String.fromCharCode(97+Math.floor(25*Math.random()))}var Ae=new Sn("Platform Initializer"),Re=new Sn("Platform ID"),Me=new Sn("appBootstrapListener"),Ne=function(){function n(){}return n.prototype.log=function(n){console.log(n)},n.prototype.warn=function(n){console.warn(n)},n}();function Le(){throw new Error("Runtime compiler is not loaded")}var Ve,Ue,je=Le,Fe=Le,Be=Le,He=Le,ze=function(){function n(){this.compileModuleSync=je,this.compileModuleAsync=Fe,this.compileModuleAndAllComponentsSync=Be,this.compileModuleAndAllComponentsAsync=He}return n.prototype.clearCache=function(){},n.prototype.clearCacheFor=function(n){},n.prototype.getModuleId=function(n){},n}(),qe=function(){return function(){}}();function Ge(){var n=On.wtf;return!(!n||!(Ve=n.trace)||(Ue=Ve.events,0))}var We=Ge();function Qe(n,t){return null}var $e=We?function(n,t){return void 0===t&&(t=null),Ue.createScope(n,t)}:function(n,t){return Qe},Ke=We?function(n,t){return Ve.leaveScope(n,t),t}:function(n,t){return t},Ze=function(){function n(n){var t,e=n.enableLongStackTrace,l=void 0!==e&&e;if(this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new he(!1),this.onMicrotaskEmpty=new he(!1),this.onStable=new he(!1),this.onError=new he(!1),"undefined"==typeof Zone)throw new Error("In this configuration Angular requires Zone.js");Zone.assertZonePatched(),this._nesting=0,this._outer=this._inner=Zone.current,Zone.wtfZoneSpec&&(this._inner=this._inner.fork(Zone.wtfZoneSpec)),Zone.TaskTrackingZoneSpec&&(this._inner=this._inner.fork(new Zone.TaskTrackingZoneSpec)),l&&Zone.longStackTraceZoneSpec&&(this._inner=this._inner.fork(Zone.longStackTraceZoneSpec)),(t=this)._inner=t._inner.fork({name:"angular",properties:{isAngularZone:!0},onInvokeTask:function(n,e,l,r,o,i){try{return nl(t),n.invokeTask(l,r,o,i)}finally{tl(t)}},onInvoke:function(n,e,l,r,o,i,u){try{return nl(t),n.invoke(l,r,o,i,u)}finally{tl(t)}},onHasTask:function(n,e,l,r){n.hasTask(l,r),e===l&&("microTask"==r.change?(t.hasPendingMicrotasks=r.microTask,Je(t)):"macroTask"==r.change&&(t.hasPendingMacrotasks=r.macroTask))},onHandleError:function(n,e,l,r){return n.handleError(l,r),t.runOutsideAngular(function(){return t.onError.emit(r)}),!1}})}return n.isInAngularZone=function(){return!0===Zone.current.get("isAngularZone")},n.assertInAngularZone=function(){if(!n.isInAngularZone())throw new Error("Expected to be in Angular Zone, but it is not!")},n.assertNotInAngularZone=function(){if(n.isInAngularZone())throw new Error("Expected to not be in Angular Zone, but it is!")},n.prototype.run=function(n,t,e){return this._inner.run(n,t,e)},n.prototype.runTask=function(n,t,e,l){var r=this._inner,o=r.scheduleEventTask("NgZoneEvent: "+l,n,Xe,Ye,Ye);try{return r.runTask(o,t,e)}finally{r.cancelTask(o)}},n.prototype.runGuarded=function(n,t,e){return this._inner.runGuarded(n,t,e)},n.prototype.runOutsideAngular=function(n){return this._outer.run(n)},n}();function Ye(){}var Xe={};function Je(n){if(0==n._nesting&&!n.hasPendingMicrotasks&&!n.isStable)try{n._nesting++,n.onMicrotaskEmpty.emit(null)}finally{if(n._nesting--,!n.hasPendingMicrotasks)try{n.runOutsideAngular(function(){return n.onStable.emit(null)})}finally{n.isStable=!0}}}function nl(n){n._nesting++,n.isStable&&(n.isStable=!1,n.onUnstable.emit(null))}function tl(n){n._nesting--,Je(n)}var el,ll=function(){function n(){this.hasPendingMicrotasks=!1,this.hasPendingMacrotasks=!1,this.isStable=!0,this.onUnstable=new he,this.onMicrotaskEmpty=new he,this.onStable=new he,this.onError=new he}return n.prototype.run=function(n){return n()},n.prototype.runGuarded=function(n){return n()},n.prototype.runOutsideAngular=function(n){return n()},n.prototype.runTask=function(n){return n()},n}(),rl=function(){function n(n){var t=this;this._ngZone=n,this._pendingCount=0,this._isZoneStable=!0,this._didWork=!1,this._callbacks=[],this.taskTrackingZone=null,this._watchAngularEvents(),n.run(function(){t.taskTrackingZone="undefined"==typeof Zone?null:Zone.current.get("TaskTrackingZone")})}return n.prototype._watchAngularEvents=function(){var n=this;this._ngZone.onUnstable.subscribe({next:function(){n._didWork=!0,n._isZoneStable=!1}}),this._ngZone.runOutsideAngular(function(){n._ngZone.onStable.subscribe({next:function(){Ze.assertNotInAngularZone(),Rn(function(){n._isZoneStable=!0,n._runCallbacksIfReady()})}})})},n.prototype.increasePendingRequestCount=function(){return this._pendingCount+=1,this._didWork=!0,this._pendingCount},n.prototype.decreasePendingRequestCount=function(){if(this._pendingCount-=1,this._pendingCount<0)throw new Error("pending async requests below zero");return this._runCallbacksIfReady(),this._pendingCount},n.prototype.isStable=function(){return this._isZoneStable&&0===this._pendingCount&&!this._ngZone.hasPendingMacrotasks},n.prototype._runCallbacksIfReady=function(){var n=this;if(this.isStable())Rn(function(){for(;0!==n._callbacks.length;){var t=n._callbacks.pop();clearTimeout(t.timeoutId),t.doneCb(n._didWork)}n._didWork=!1});else{var t=this.getPendingTasks();this._callbacks=this._callbacks.filter(function(n){return!n.updateCb||!n.updateCb(t)||(clearTimeout(n.timeoutId),!1)}),this._didWork=!0}},n.prototype.getPendingTasks=function(){return this.taskTrackingZone?this.taskTrackingZone.macroTasks.map(function(n){return{source:n.source,creationLocation:n.creationLocation,data:n.data}}):[]},n.prototype.addCallback=function(n,t,e){var l=this,r=-1;t&&t>0&&(r=setTimeout(function(){l._callbacks=l._callbacks.filter(function(n){return n.timeoutId!==r}),n(l._didWork,l.getPendingTasks())},t)),this._callbacks.push({doneCb:n,timeoutId:r,updateCb:e})},n.prototype.whenStable=function(n,t,e){if(e&&!this.taskTrackingZone)throw new Error('Task tracking zone is required when passing an update callback to whenStable(). Is "zone.js/dist/task-tracking.js" loaded?');this.addCallback(n,t,e),this._runCallbacksIfReady()},n.prototype.getPendingRequestCount=function(){return this._pendingCount},n.prototype.findProviders=function(n,t,e){return[]},n}(),ol=function(){function n(){this._applications=new Map,il.addToWindow(this)}return n.prototype.registerApplication=function(n,t){this._applications.set(n,t)},n.prototype.unregisterApplication=function(n){this._applications.delete(n)},n.prototype.unregisterAllApplications=function(){this._applications.clear()},n.prototype.getTestability=function(n){return this._applications.get(n)||null},n.prototype.getAllTestabilities=function(){return Array.from(this._applications.values())},n.prototype.getAllRootElements=function(){return Array.from(this._applications.keys())},n.prototype.findTestabilityInTree=function(n,t){return void 0===t&&(t=!0),il.findTestabilityInTree(this,n,t)},i([u("design:paramtypes",[])],n)}(),il=new(function(){function n(){}return n.prototype.addToWindow=function(n){},n.prototype.findTestabilityInTree=function(n,t,e){return null},n}()),ul=new Sn("AllowMultipleToken"),al=function(){return function(n,t){this.name=n,this.token=t}}();function sl(n,t,e){void 0===e&&(e=[]);var l="Platform: "+t,r=new Sn(l);return function(t){void 0===t&&(t=[]);var o=cl();if(!o||o.injector.get(ul,!1))if(n)n(e.concat(t).concat({provide:r,useValue:!0}));else{var i=e.concat(t).concat({provide:r,useValue:!0});!function(n){if(el&&!el.destroyed&&!el.injector.get(ul,!1))throw new Error("There can be only one platform. Destroy the previous one to create a new one.");el=n.get(pl);var t=n.get(Ae,null);t&&t.forEach(function(n){return n()})}(ut.create({providers:i,name:l}))}return function(n){var t=cl();if(!t)throw new Error("No platform exists!");if(!t.injector.get(n,null))throw new Error("A platform with a different configuration has been created. Please destroy it first.");return t}(r)}}function cl(){return el&&!el.destroyed?el:null}var pl=function(){function n(n){this._injector=n,this._modules=[],this._destroyListeners=[],this._destroyed=!1}return n.prototype.bootstrapModuleFactory=function(n,t){var e,l=this,r="noop"===(e=t?t.ngZone:void 0)?new ll:("zone.js"===e?void 0:e)||new Ze({enableLongStackTrace:qt()}),o=[{provide:Ze,useValue:r}];return r.run(function(){var t=ut.create({providers:o,parent:l.injector,name:n.moduleType.name}),e=n.create(t),i=e.injector.get(Ee,null);if(!i)throw new Error("No ErrorHandler. Is platform module (BrowserModule) included?");return e.onDestroy(function(){return fl(l._modules,e)}),r.runOutsideAngular(function(){return r.onError.subscribe({next:function(n){i.handleError(n)}})}),function(n,t,r){try{var o=((i=e.injector.get(Ie)).runInitializers(),i.donePromise.then(function(){return l._moduleDoBootstrap(e),e}));return xe(o)?o.catch(function(e){throw t.runOutsideAngular(function(){return n.handleError(e)}),e}):o}catch(u){throw t.runOutsideAngular(function(){return n.handleError(u)}),u}var i}(i,r)})},n.prototype.bootstrapModule=function(n,t){var e=this;void 0===t&&(t=[]);var l=hl({},t);return function(n,t,e){return n.get(qe).createCompiler([t]).compileModuleAsync(e)}(this.injector,l,n).then(function(n){return e.bootstrapModuleFactory(n,l)})},n.prototype._moduleDoBootstrap=function(n){var t=n.injector.get(dl);if(n._bootstrapComponents.length>0)n._bootstrapComponents.forEach(function(n){return t.bootstrap(n)});else{if(!n.instance.ngDoBootstrap)throw new Error("The module "+Nn(n.instance.constructor)+' was bootstrapped, but it does not declare "@NgModule.bootstrap" components nor a "ngDoBootstrap" method. Please define one of these.');n.instance.ngDoBootstrap(t)}this._modules.push(n)},n.prototype.onDestroy=function(n){this._destroyListeners.push(n)},Object.defineProperty(n.prototype,"injector",{get:function(){return this._injector},enumerable:!0,configurable:!0}),n.prototype.destroy=function(){if(this._destroyed)throw new Error("The platform has already been destroyed!");this._modules.slice().forEach(function(n){return n.destroy()}),this._destroyListeners.forEach(function(n){return n()}),this._destroyed=!0},Object.defineProperty(n.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!0,configurable:!0}),n}();function hl(n,t){return Array.isArray(t)?t.reduce(hl,n):o({},n,t)}var dl=function(){function n(n,t,e,l,r,o){var i=this;this._zone=n,this._console=t,this._injector=e,this._exceptionHandler=l,this._componentFactoryResolver=r,this._initStatus=o,this._bootstrapListeners=[],this._views=[],this._runningTick=!1,this._enforceNoNewChanges=!1,this._stable=!0,this.componentTypes=[],this.components=[],this._enforceNoNewChanges=qt(),this._zone.onMicrotaskEmpty.subscribe({next:function(){i._zone.run(function(){i.tick()})}});var u=new R(function(n){i._stable=i._zone.isStable&&!i._zone.hasPendingMacrotasks&&!i._zone.hasPendingMicrotasks,i._zone.runOutsideAngular(function(){n.next(i._stable),n.complete()})}),a=new R(function(n){var t;i._zone.runOutsideAngular(function(){t=i._zone.onStable.subscribe(function(){Ze.assertNotInAngularZone(),Rn(function(){i._stable||i._zone.hasPendingMacrotasks||i._zone.hasPendingMicrotasks||(i._stable=!0,n.next(!0))})})});var e=i._zone.onUnstable.subscribe(function(){Ze.assertInAngularZone(),i._stable&&(i._stable=!1,i._zone.runOutsideAngular(function(){n.next(!1)}))});return function(){t.unsubscribe(),e.unsubscribe()}});this.isStable=pn(u,a.pipe(function(n){return hn()((t=vn,function(n){var e;e="function"==typeof t?t:function(){return t};var l=Object.create(n,mn);return l.source=n,l.subjectFactory=e,l})(n));var t}))}var t;return t=n,n.prototype.bootstrap=function(n,t){var e,l=this;if(!this._initStatus.done)throw new Error("Cannot bootstrap as there are still asynchronous initializers running. Bootstrap components in the `ngDoBootstrap` method of the root module.");e=n instanceof St?n:this._componentFactoryResolver.resolveComponentFactory(n),this.componentTypes.push(e.componentType);var r=e instanceof Ot?null:this._injector.get(kt),o=e.create(ut.NULL,[],t||e.selector,r);o.onDestroy(function(){l._unloadComponent(o)});var i=o.injector.get(rl,null);return i&&o.injector.get(ol).registerApplication(o.location.nativeElement,i),this._loadComponent(o),qt()&&this._console.log("Angular is running in the development mode. Call enableProdMode() to enable the production mode."),o},n.prototype.tick=function(){var n=this;if(this._runningTick)throw new Error("ApplicationRef.tick is called recursively");var e=t._tickScope();try{this._runningTick=!0,this._views.forEach(function(n){return n.detectChanges()}),this._enforceNoNewChanges&&this._views.forEach(function(n){return n.checkNoChanges()})}catch(l){this._zone.runOutsideAngular(function(){return n._exceptionHandler.handleError(l)})}finally{this._runningTick=!1,Ke(e)}},n.prototype.attachView=function(n){var t=n;this._views.push(t),t.attachToAppRef(this)},n.prototype.detachView=function(n){var t=n;fl(this._views,t),t.detachFromAppRef()},n.prototype._loadComponent=function(n){this.attachView(n.hostView),this.tick(),this.components.push(n),this._injector.get(Me,[]).concat(this._bootstrapListeners).forEach(function(t){return t(n)})},n.prototype._unloadComponent=function(n){this.detachView(n.hostView),fl(this.components,n)},n.prototype.ngOnDestroy=function(){this._views.slice().forEach(function(n){return n.destroy()})},Object.defineProperty(n.prototype,"viewCount",{get:function(){return this._views.length},enumerable:!0,configurable:!0}),n._tickScope=$e("ApplicationRef#tick()"),n}();function fl(n,t){var e=n.indexOf(t);e>-1&&n.splice(e,1)}var gl=function(){function n(){this.dirty=!0,this._results=[],this.changes=new he,this.length=0}return n.prototype.map=function(n){return this._results.map(n)},n.prototype.filter=function(n){return this._results.filter(n)},n.prototype.find=function(n){return this._results.find(n)},n.prototype.reduce=function(n,t){return this._results.reduce(n,t)},n.prototype.forEach=function(n){this._results.forEach(n)},n.prototype.some=function(n){return this._results.some(n)},n.prototype.toArray=function(){return this._results.slice()},n.prototype[An()]=function(){return this._results[An()]()},n.prototype.toString=function(){return this._results.toString()},n.prototype.reset=function(n){this._results=function n(t){return t.reduce(function(t,e){var l=Array.isArray(e)?n(e):e;return t.concat(l)},[])}(n),this.dirty=!1,this.length=this._results.length,this.last=this._results[this.length-1],this.first=this._results[0]},n.prototype.notifyOnChanges=function(){this.changes.emit(this)},n.prototype.setDirty=function(){this.dirty=!0},n.prototype.destroy=function(){this.changes.complete(),this.changes.unsubscribe()},n}(),ml=function(){return function(){}}(),yl={factoryPathPrefix:"",factoryPathSuffix:".ngfactory"},vl=function(){function n(n,t){this._compiler=n,this._config=t||yl}return n.prototype.load=function(n){return this._compiler instanceof ze?this.loadFactory(n):this.loadAndCompile(n)},n.prototype.loadAndCompile=function(n){var t=this,l=s(n.split("#"),2),r=l[0],o=l[1];return void 0===o&&(o="default"),e("crnd")(r).then(function(n){return n[o]}).then(function(n){return _l(n,r,o)}).then(function(n){return t._compiler.compileModuleAsync(n)})},n.prototype.loadFactory=function(n){var t=s(n.split("#"),2),l=t[0],r=t[1],o="NgFactory";return void 0===r&&(r="default",o=""),e("crnd")(this._config.factoryPathPrefix+l+this._config.factoryPathSuffix).then(function(n){return n[r+o]}).then(function(n){return _l(n,l,r)})},n}();function _l(n,t,e){if(!n)throw new Error("Cannot find '"+e+"' in '"+t+"'");return n}var bl=function(){function n(){}return n.__NG_ELEMENT_ID__=function(){return wl(n,At)},n}(),wl=et,Cl=function(){function n(){}return n.__NG_ELEMENT_ID__=function(){return Sl()},n}(),Sl=function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t]},El=function(){return function(n,t){this.name=n,this.callback=t}}(),xl=function(){function n(n,t,e){this.listeners=[],this.parent=null,this._debugContext=e,this.nativeNode=n,t&&t instanceof Pl&&t.addChild(this)}return Object.defineProperty(n.prototype,"injector",{get:function(){return this._debugContext.injector},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"componentInstance",{get:function(){return this._debugContext.component},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"context",{get:function(){return this._debugContext.context},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"references",{get:function(){return this._debugContext.references},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"providerTokens",{get:function(){return this._debugContext.providerTokens},enumerable:!0,configurable:!0}),n}(),Pl=function(n){function t(t,e,l){var r=n.call(this,t,e,l)||this;return r.properties={},r.attributes={},r.classes={},r.styles={},r.childNodes=[],r.nativeElement=t,r}return r(t,n),t.prototype.addChild=function(n){n&&(this.childNodes.push(n),n.parent=this)},t.prototype.removeChild=function(n){var t=this.childNodes.indexOf(n);-1!==t&&(n.parent=null,this.childNodes.splice(t,1))},t.prototype.insertChildrenAfter=function(n,t){var e,l=this,r=this.childNodes.indexOf(n);-1!==r&&((e=this.childNodes).splice.apply(e,c([r+1,0],t)),t.forEach(function(t){t.parent&&t.parent.removeChild(t),n.parent=l}))},t.prototype.insertBefore=function(n,t){var e=this.childNodes.indexOf(n);-1===e?this.addChild(t):(t.parent&&t.parent.removeChild(t),t.parent=this,this.childNodes.splice(e,0,t))},t.prototype.query=function(n){return this.queryAll(n)[0]||null},t.prototype.queryAll=function(n){var t=[];return function n(t,e,l){t.childNodes.forEach(function(t){t instanceof Pl&&(e(t)&&l.push(t),n(t,e,l))})}(this,n,t),t},t.prototype.queryAllNodes=function(n){var t=[];return function n(t,e,l){t instanceof Pl&&t.childNodes.forEach(function(t){e(t)&&l.push(t),t instanceof Pl&&n(t,e,l)})}(this,n,t),t},Object.defineProperty(t.prototype,"children",{get:function(){return this.childNodes.filter(function(n){return n instanceof t})},enumerable:!0,configurable:!0}),t.prototype.triggerEventHandler=function(n,t){this.listeners.forEach(function(e){e.name==n&&e.callback(t)})},t}(xl),Tl=new Map,Il=function(n){return Tl.get(n)||null};function Ol(n){Tl.set(n.nativeNode,n)}var kl=function(){function n(){}return n.prototype.supports=function(n){return nt(n)},n.prototype.create=function(n){return new Al(n)},n}(),Dl=function(n,t){return t},Al=function(){function n(n){this.length=0,this._linkedRecords=null,this._unlinkedRecords=null,this._previousItHead=null,this._itHead=null,this._itTail=null,this._additionsHead=null,this._additionsTail=null,this._movesHead=null,this._movesTail=null,this._removalsHead=null,this._removalsTail=null,this._identityChangesHead=null,this._identityChangesTail=null,this._trackByFn=n||Dl}return n.prototype.forEachItem=function(n){var t;for(t=this._itHead;null!==t;t=t._next)n(t)},n.prototype.forEachOperation=function(n){for(var t=this._itHead,e=this._removalsHead,l=0,r=null;t||e;){var o=!e||t&&t.currentIndex<Ll(e,l,r)?t:e,i=Ll(o,l,r),u=o.currentIndex;if(o===e)l--,e=e._nextRemoved;else if(t=t._next,null==o.previousIndex)l++;else{r||(r=[]);var a=i-l,s=u-l;if(a!=s){for(var c=0;c<a;c++){var p=c<r.length?r[c]:r[c]=0,h=p+c;s<=h&&h<a&&(r[c]=p+1)}r[o.previousIndex]=s-a}}i!==u&&n(o,i,u)}},n.prototype.forEachPreviousItem=function(n){var t;for(t=this._previousItHead;null!==t;t=t._nextPrevious)n(t)},n.prototype.forEachAddedItem=function(n){var t;for(t=this._additionsHead;null!==t;t=t._nextAdded)n(t)},n.prototype.forEachMovedItem=function(n){var t;for(t=this._movesHead;null!==t;t=t._nextMoved)n(t)},n.prototype.forEachRemovedItem=function(n){var t;for(t=this._removalsHead;null!==t;t=t._nextRemoved)n(t)},n.prototype.forEachIdentityChange=function(n){var t;for(t=this._identityChangesHead;null!==t;t=t._nextIdentityChange)n(t)},n.prototype.diff=function(n){if(null==n&&(n=[]),!nt(n))throw new Error("Error trying to diff '"+Nn(n)+"'. Only arrays and iterables are allowed");return this.check(n)?this:null},n.prototype.onDestroy=function(){},n.prototype.check=function(n){var t=this;this._reset();var e,l,r,o=this._itHead,i=!1;if(Array.isArray(n)){this.length=n.length;for(var u=0;u<this.length;u++)r=this._trackByFn(u,l=n[u]),null!==o&&Mn(o.trackById,r)?(i&&(o=this._verifyReinsertion(o,l,r,u)),Mn(o.item,l)||this._addIdentityChange(o,l)):(o=this._mismatch(o,l,r,u),i=!0),o=o._next}else e=0,function(n,t){if(Array.isArray(n))for(var e=0;e<n.length;e++)t(n[e]);else for(var l=n[An()](),r=void 0;!(r=l.next()).done;)t(r.value)}(n,function(n){r=t._trackByFn(e,n),null!==o&&Mn(o.trackById,r)?(i&&(o=t._verifyReinsertion(o,n,r,e)),Mn(o.item,n)||t._addIdentityChange(o,n)):(o=t._mismatch(o,n,r,e),i=!0),o=o._next,e++}),this.length=e;return this._truncate(o),this.collection=n,this.isDirty},Object.defineProperty(n.prototype,"isDirty",{get:function(){return null!==this._additionsHead||null!==this._movesHead||null!==this._removalsHead||null!==this._identityChangesHead},enumerable:!0,configurable:!0}),n.prototype._reset=function(){if(this.isDirty){var n=void 0,t=void 0;for(n=this._previousItHead=this._itHead;null!==n;n=n._next)n._nextPrevious=n._next;for(n=this._additionsHead;null!==n;n=n._nextAdded)n.previousIndex=n.currentIndex;for(this._additionsHead=this._additionsTail=null,n=this._movesHead;null!==n;n=t)n.previousIndex=n.currentIndex,t=n._nextMoved;this._movesHead=this._movesTail=null,this._removalsHead=this._removalsTail=null,this._identityChangesHead=this._identityChangesTail=null}},n.prototype._mismatch=function(n,t,e,l){var r;return null===n?r=this._itTail:(r=n._prev,this._remove(n)),null!==(n=null===this._linkedRecords?null:this._linkedRecords.get(e,l))?(Mn(n.item,t)||this._addIdentityChange(n,t),this._moveAfter(n,r,l)):null!==(n=null===this._unlinkedRecords?null:this._unlinkedRecords.get(e,null))?(Mn(n.item,t)||this._addIdentityChange(n,t),this._reinsertAfter(n,r,l)):n=this._addAfter(new Rl(t,e),r,l),n},n.prototype._verifyReinsertion=function(n,t,e,l){var r=null===this._unlinkedRecords?null:this._unlinkedRecords.get(e,null);return null!==r?n=this._reinsertAfter(r,n._prev,l):n.currentIndex!=l&&(n.currentIndex=l,this._addToMoves(n,l)),n},n.prototype._truncate=function(n){for(;null!==n;){var t=n._next;this._addToRemovals(this._unlink(n)),n=t}null!==this._unlinkedRecords&&this._unlinkedRecords.clear(),null!==this._additionsTail&&(this._additionsTail._nextAdded=null),null!==this._movesTail&&(this._movesTail._nextMoved=null),null!==this._itTail&&(this._itTail._next=null),null!==this._removalsTail&&(this._removalsTail._nextRemoved=null),null!==this._identityChangesTail&&(this._identityChangesTail._nextIdentityChange=null)},n.prototype._reinsertAfter=function(n,t,e){null!==this._unlinkedRecords&&this._unlinkedRecords.remove(n);var l=n._prevRemoved,r=n._nextRemoved;return null===l?this._removalsHead=r:l._nextRemoved=r,null===r?this._removalsTail=l:r._prevRemoved=l,this._insertAfter(n,t,e),this._addToMoves(n,e),n},n.prototype._moveAfter=function(n,t,e){return this._unlink(n),this._insertAfter(n,t,e),this._addToMoves(n,e),n},n.prototype._addAfter=function(n,t,e){return this._insertAfter(n,t,e),this._additionsTail=null===this._additionsTail?this._additionsHead=n:this._additionsTail._nextAdded=n,n},n.prototype._insertAfter=function(n,t,e){var l=null===t?this._itHead:t._next;return n._next=l,n._prev=t,null===l?this._itTail=n:l._prev=n,null===t?this._itHead=n:t._next=n,null===this._linkedRecords&&(this._linkedRecords=new Nl),this._linkedRecords.put(n),n.currentIndex=e,n},n.prototype._remove=function(n){return this._addToRemovals(this._unlink(n))},n.prototype._unlink=function(n){null!==this._linkedRecords&&this._linkedRecords.remove(n);var t=n._prev,e=n._next;return null===t?this._itHead=e:t._next=e,null===e?this._itTail=t:e._prev=t,n},n.prototype._addToMoves=function(n,t){return n.previousIndex===t?n:(this._movesTail=null===this._movesTail?this._movesHead=n:this._movesTail._nextMoved=n,n)},n.prototype._addToRemovals=function(n){return null===this._unlinkedRecords&&(this._unlinkedRecords=new Nl),this._unlinkedRecords.put(n),n.currentIndex=null,n._nextRemoved=null,null===this._removalsTail?(this._removalsTail=this._removalsHead=n,n._prevRemoved=null):(n._prevRemoved=this._removalsTail,this._removalsTail=this._removalsTail._nextRemoved=n),n},n.prototype._addIdentityChange=function(n,t){return n.item=t,this._identityChangesTail=null===this._identityChangesTail?this._identityChangesHead=n:this._identityChangesTail._nextIdentityChange=n,n},n}(),Rl=function(){return function(n,t){this.item=n,this.trackById=t,this.currentIndex=null,this.previousIndex=null,this._nextPrevious=null,this._prev=null,this._next=null,this._prevDup=null,this._nextDup=null,this._prevRemoved=null,this._nextRemoved=null,this._nextAdded=null,this._nextMoved=null,this._nextIdentityChange=null}}(),Ml=function(){function n(){this._head=null,this._tail=null}return n.prototype.add=function(n){null===this._head?(this._head=this._tail=n,n._nextDup=null,n._prevDup=null):(this._tail._nextDup=n,n._prevDup=this._tail,n._nextDup=null,this._tail=n)},n.prototype.get=function(n,t){var e;for(e=this._head;null!==e;e=e._nextDup)if((null===t||t<=e.currentIndex)&&Mn(e.trackById,n))return e;return null},n.prototype.remove=function(n){var t=n._prevDup,e=n._nextDup;return null===t?this._head=e:t._nextDup=e,null===e?this._tail=t:e._prevDup=t,null===this._head},n}(),Nl=function(){function n(){this.map=new Map}return n.prototype.put=function(n){var t=n.trackById,e=this.map.get(t);e||(e=new Ml,this.map.set(t,e)),e.add(n)},n.prototype.get=function(n,t){var e=this.map.get(n);return e?e.get(n,t):null},n.prototype.remove=function(n){var t=n.trackById;return this.map.get(t).remove(n)&&this.map.delete(t),n},Object.defineProperty(n.prototype,"isEmpty",{get:function(){return 0===this.map.size},enumerable:!0,configurable:!0}),n.prototype.clear=function(){this.map.clear()},n}();function Ll(n,t,e){var l=n.previousIndex;if(null===l)return l;var r=0;return e&&l<e.length&&(r=e[l]),l+t+r}var Vl=function(){function n(){}return n.prototype.supports=function(n){return n instanceof Map||tt(n)},n.prototype.create=function(){return new Ul},n}(),Ul=function(){function n(){this._records=new Map,this._mapHead=null,this._appendAfter=null,this._previousMapHead=null,this._changesHead=null,this._changesTail=null,this._additionsHead=null,this._additionsTail=null,this._removalsHead=null,this._removalsTail=null}return Object.defineProperty(n.prototype,"isDirty",{get:function(){return null!==this._additionsHead||null!==this._changesHead||null!==this._removalsHead},enumerable:!0,configurable:!0}),n.prototype.forEachItem=function(n){var t;for(t=this._mapHead;null!==t;t=t._next)n(t)},n.prototype.forEachPreviousItem=function(n){var t;for(t=this._previousMapHead;null!==t;t=t._nextPrevious)n(t)},n.prototype.forEachChangedItem=function(n){var t;for(t=this._changesHead;null!==t;t=t._nextChanged)n(t)},n.prototype.forEachAddedItem=function(n){var t;for(t=this._additionsHead;null!==t;t=t._nextAdded)n(t)},n.prototype.forEachRemovedItem=function(n){var t;for(t=this._removalsHead;null!==t;t=t._nextRemoved)n(t)},n.prototype.diff=function(n){if(n){if(!(n instanceof Map||tt(n)))throw new Error("Error trying to diff '"+Nn(n)+"'. Only maps and objects are allowed")}else n=new Map;return this.check(n)?this:null},n.prototype.onDestroy=function(){},n.prototype.check=function(n){var t=this;this._reset();var e=this._mapHead;if(this._appendAfter=null,this._forEach(n,function(n,l){if(e&&e.key===l)t._maybeAddToChanges(e,n),t._appendAfter=e,e=e._next;else{var r=t._getOrCreateRecordForKey(l,n);e=t._insertBeforeOrAppend(e,r)}}),e){e._prev&&(e._prev._next=null),this._removalsHead=e;for(var l=e;null!==l;l=l._nextRemoved)l===this._mapHead&&(this._mapHead=null),this._records.delete(l.key),l._nextRemoved=l._next,l.previousValue=l.currentValue,l.currentValue=null,l._prev=null,l._next=null}return this._changesTail&&(this._changesTail._nextChanged=null),this._additionsTail&&(this._additionsTail._nextAdded=null),this.isDirty},n.prototype._insertBeforeOrAppend=function(n,t){if(n){var e=n._prev;return t._next=n,t._prev=e,n._prev=t,e&&(e._next=t),n===this._mapHead&&(this._mapHead=t),this._appendAfter=n,n}return this._appendAfter?(this._appendAfter._next=t,t._prev=this._appendAfter):this._mapHead=t,this._appendAfter=t,null},n.prototype._getOrCreateRecordForKey=function(n,t){if(this._records.has(n)){var e=this._records.get(n);this._maybeAddToChanges(e,t);var l=e._prev,r=e._next;return l&&(l._next=r),r&&(r._prev=l),e._next=null,e._prev=null,e}var o=new jl(n);return this._records.set(n,o),o.currentValue=t,this._addToAdditions(o),o},n.prototype._reset=function(){if(this.isDirty){var n=void 0;for(this._previousMapHead=this._mapHead,n=this._previousMapHead;null!==n;n=n._next)n._nextPrevious=n._next;for(n=this._changesHead;null!==n;n=n._nextChanged)n.previousValue=n.currentValue;for(n=this._additionsHead;null!=n;n=n._nextAdded)n.previousValue=n.currentValue;this._changesHead=this._changesTail=null,this._additionsHead=this._additionsTail=null,this._removalsHead=null}},n.prototype._maybeAddToChanges=function(n,t){Mn(t,n.currentValue)||(n.previousValue=n.currentValue,n.currentValue=t,this._addToChanges(n))},n.prototype._addToAdditions=function(n){null===this._additionsHead?this._additionsHead=this._additionsTail=n:(this._additionsTail._nextAdded=n,this._additionsTail=n)},n.prototype._addToChanges=function(n){null===this._changesHead?this._changesHead=this._changesTail=n:(this._changesTail._nextChanged=n,this._changesTail=n)},n.prototype._forEach=function(n,t){n instanceof Map?n.forEach(t):Object.keys(n).forEach(function(e){return t(n[e],e)})},n}(),jl=function(){return function(n){this.key=n,this.previousValue=null,this.currentValue=null,this._nextPrevious=null,this._next=null,this._prev=null,this._nextAdded=null,this._nextRemoved=null,this._nextChanged=null}}(),Fl=function(){function n(n){this.factories=n}return n.create=function(t,e){if(null!=e){var l=e.factories.slice();t=t.concat(l)}return new n(t)},n.extend=function(t){return{provide:n,useFactory:function(e){if(!e)throw new Error("Cannot extend IterableDiffers without a parent injector");return n.create(t,e)},deps:[[n,new qn,new Hn]]}},n.prototype.find=function(n){var t,e=this.factories.find(function(t){return t.supports(n)});if(null!=e)return e;throw new Error("Cannot find a differ supporting object '"+n+"' of type '"+((t=n).name||typeof t)+"'")},n.ngInjectableDef=wn({providedIn:"root",factory:function(){return new n([new kl])}}),n}(),Bl=function(){function n(n){this.factories=n}return n.create=function(t,e){if(e){var l=e.factories.slice();t=t.concat(l)}return new n(t)},n.extend=function(t){return{provide:n,useFactory:function(e){if(!e)throw new Error("Cannot extend KeyValueDiffers without a parent injector");return n.create(t,e)},deps:[[n,new qn,new Hn]]}},n.prototype.find=function(n){var t=this.factories.find(function(t){return t.supports(n)});if(t)return t;throw new Error("Cannot find a differ supporting object '"+n+"'")},n.ngInjectableDef=wn({providedIn:"root",factory:function(){return new n([new Vl])}}),n}(),Hl=[new Vl],zl=new Fl([new kl]),ql=new Bl(Hl),Gl=sl(null,"core",[{provide:Re,useValue:"unknown"},{provide:pl,deps:[ut]},{provide:ol,deps:[]},{provide:Ne,deps:[]}]),Wl=new Sn("LocaleId");function Ql(){return zl}function $l(){return ql}function Kl(n){return n||"en-US"}var Zl=function(){return function(n){}}();function Yl(n,t,e){var l=n.state,r=1792&l;return r===t?(n.state=-1793&l|e,n.initIndex=-1,!0):r===e}function Xl(n,t,e){return(1792&n.state)===t&&n.initIndex<=e&&(n.initIndex=e+1,!0)}function Jl(n,t){return n.nodes[t]}function nr(n,t){return n.nodes[t]}function tr(n,t){return n.nodes[t]}function er(n,t){return n.nodes[t]}function lr(n,t){return n.nodes[t]}var rr={setCurrentNode:void 0,createRootView:void 0,createEmbeddedView:void 0,createComponentView:void 0,createNgModuleRef:void 0,overrideProvider:void 0,overrideComponentView:void 0,clearOverrides:void 0,checkAndUpdateView:void 0,checkNoChangesView:void 0,destroyView:void 0,resolveDep:void 0,createDebugContext:void 0,handleEvent:void 0,updateDirectives:void 0,updateRenderer:void 0,dirtyParentQueries:void 0};function or(n,t,e,l){var r="ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '"+t+"'. Current value: '"+e+"'.";return l&&(r+=" It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?"),function(n,t){var e=new Error(n);return ir(e,t),e}(r,n)}function ir(n,t){n[ve]=t,n[be]=t.logError.bind(t)}function ur(n){return new Error("ViewDestroyedError: Attempt to use a destroyed view: "+n)}var ar=function(){},sr=new Map;function cr(n){var t=sr.get(n);return t||(t=Nn(n)+"_"+sr.size,sr.set(n,t)),t}var pr="$$undefined",hr="$$empty";function dr(n){return{id:pr,styles:n.styles,encapsulation:n.encapsulation,data:n.data}}var fr=0;function gr(n,t,e,l){return!(!(2&n.state)&&Mn(n.oldValues[t.bindingIndex+e],l))}function mr(n,t,e,l){return!!gr(n,t,e,l)&&(n.oldValues[t.bindingIndex+e]=l,!0)}function yr(n,t,e,l){var r=n.oldValues[t.bindingIndex+e];if(1&n.state||!Yn(r,l)){var o=t.bindings[e].name;throw or(rr.createDebugContext(n,t.nodeIndex),o+": "+r,o+": "+l,0!=(1&n.state))}}function vr(n){for(var t=n;t;)2&t.def.flags&&(t.state|=8),t=t.viewContainerParent||t.parent}function _r(n,t){for(var e=n;e&&e!==t;)e.state|=64,e=e.viewContainerParent||e.parent}function br(n,t,e,l){try{return vr(33554432&n.def.nodes[t].flags?nr(n,t).componentView:n),rr.handleEvent(n,t,e,l)}catch(r){n.root.errorHandler.handleError(r)}}function wr(n){return n.parent?nr(n.parent,n.parentNodeDef.nodeIndex):null}function Cr(n){return n.parent?n.parentNodeDef.parent:null}function Sr(n,t){switch(201347067&t.flags){case 1:return nr(n,t.nodeIndex).renderElement;case 2:return Jl(n,t.nodeIndex).renderText}}function Er(n){return!!n.parent&&!!(32768&n.parentNodeDef.flags)}function xr(n){return!(!n.parent||32768&n.parentNodeDef.flags)}function Pr(n){var t={},e=0,l={};return n&&n.forEach(function(n){var r=s(n,2),o=r[0],i=r[1];"number"==typeof o?(t[o]=i,e|=function(n){return 1<<n%32}(o)):l[o]=i}),{matchedQueries:t,references:l,matchedQueryIds:e}}function Tr(n,t){return n.map(function(n){var e,l,r;return Array.isArray(n)?(r=(e=s(n,2))[0],l=e[1]):(r=0,l=n),l&&("function"==typeof l||"object"==typeof l)&&t&&Object.defineProperty(l,lt,{value:t,configurable:!0}),{flags:r,token:l,tokenKey:cr(l)}})}function Ir(n,t,e){var l=e.renderParent;return l?0==(1&l.flags)||0==(33554432&l.flags)||l.element.componentRendererType&&l.element.componentRendererType.encapsulation===Fn.Native?nr(n,e.renderParent.nodeIndex).renderElement:void 0:t}var Or=new WeakMap;function kr(n){var t=Or.get(n);return t||((t=n(function(){return ar})).factory=n,Or.set(n,t)),t}function Dr(n,t,e,l,r){3===t&&(e=n.renderer.parentNode(Sr(n,n.def.lastRenderRootNode))),Ar(n,t,0,n.def.nodes.length-1,e,l,r)}function Ar(n,t,e,l,r,o,i){for(var u=e;u<=l;u++){var a=n.def.nodes[u];11&a.flags&&Mr(n,a,t,r,o,i),u+=a.childCount}}function Rr(n,t,e,l,r,o){for(var i=n;i&&!Er(i);)i=i.parent;for(var u=i.parent,a=Cr(i),s=a.nodeIndex+a.childCount,c=a.nodeIndex+1;c<=s;c++){var p=u.def.nodes[c];p.ngContentIndex===t&&Mr(u,p,e,l,r,o),c+=p.childCount}if(!u.parent){var h=n.root.projectableNodes[t];if(h)for(c=0;c<h.length;c++)Nr(n,h[c],e,l,r,o)}}function Mr(n,t,e,l,r,o){if(8&t.flags)Rr(n,t.ngContent.index,e,l,r,o);else{var i=Sr(n,t);if(3===e&&33554432&t.flags&&48&t.bindingFlags?(16&t.bindingFlags&&Nr(n,i,e,l,r,o),32&t.bindingFlags&&Nr(nr(n,t.nodeIndex).componentView,i,e,l,r,o)):Nr(n,i,e,l,r,o),16777216&t.flags)for(var u=nr(n,t.nodeIndex).viewContainer._embeddedViews,a=0;a<u.length;a++)Dr(u[a],e,l,r,o);1&t.flags&&!t.element.name&&Ar(n,e,t.nodeIndex+1,t.nodeIndex+t.childCount,l,r,o)}}function Nr(n,t,e,l,r,o){var i=n.renderer;switch(e){case 1:i.appendChild(l,t);break;case 2:i.insertBefore(l,t,r);break;case 3:i.removeChild(l,t);break;case 0:o.push(t)}}var Lr=/^:([^:]+):(.+)$/;function Vr(n){if(":"===n[0]){var t=n.match(Lr);return[t[1],t[2]]}return["",n]}function Ur(n){for(var t=0,e=0;e<n.length;e++)t|=n[e].flags;return t}function jr(n,t,e,l,r,o,i,u,a,s,c,p,h,d,f,g,m,y,v,_){switch(n){case 1:return t+Fr(e)+l;case 2:return t+Fr(e)+l+Fr(r)+o;case 3:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u;case 4:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s;case 5:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s+Fr(c)+p;case 6:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s+Fr(c)+p+Fr(h)+d;case 7:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s+Fr(c)+p+Fr(h)+d+Fr(f)+g;case 8:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s+Fr(c)+p+Fr(h)+d+Fr(f)+g+Fr(m)+y;case 9:return t+Fr(e)+l+Fr(r)+o+Fr(i)+u+Fr(a)+s+Fr(c)+p+Fr(h)+d+Fr(f)+g+Fr(m)+y+Fr(v)+_;default:throw new Error("Does not support more than 9 expressions")}}function Fr(n){return null!=n?n.toString():""}function Br(n,t,e,l,r,o){n|=1;var i=Pr(t);return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,flags:n,checkIndex:-1,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:i.matchedQueries,matchedQueryIds:i.matchedQueryIds,references:i.references,ngContentIndex:e,childCount:l,bindings:[],bindingFlags:0,outputs:[],element:{ns:null,name:null,attrs:null,template:o?kr(o):null,componentProvider:null,componentView:null,componentRendererType:null,publicProviders:null,allProviders:null,handleEvent:r||ar},provider:null,text:null,query:null,ngContent:null}}function Hr(n,t,e,l,r,o,i,u,a,c,p,h){var d;void 0===i&&(i=[]),c||(c=ar);var f=Pr(e),g=f.matchedQueries,m=f.references,y=f.matchedQueryIds,v=null,_=null;o&&(v=(d=s(Vr(o),2))[0],_=d[1]),u=u||[];for(var b=new Array(u.length),w=0;w<u.length;w++){var C=s(u[w],3),S=C[0],E=C[2],x=s(Vr(C[1]),2),P=x[0],T=x[1],I=void 0,O=void 0;switch(15&S){case 4:O=E;break;case 1:case 8:I=E}b[w]={flags:S,ns:P,name:T,nonMinifiedName:T,securityContext:I,suffix:O}}a=a||[];var k=new Array(a.length);for(w=0;w<a.length;w++){var D=s(a[w],2);k[w]={type:0,target:D[0],eventName:D[1],propName:null}}var A=(i=i||[]).map(function(n){var t=s(n,2),e=t[1],l=s(Vr(t[0]),2);return[l[0],l[1],e]});return h=function(n){if(n&&n.id===pr){var t=null!=n.encapsulation&&n.encapsulation!==Fn.None||n.styles.length||Object.keys(n.data).length;n.id=t?"c"+fr++:hr}return n&&n.id===hr&&(n=null),n||null}(h),p&&(t|=33554432),{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:n,flags:t|=1,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:g,matchedQueryIds:y,references:m,ngContentIndex:l,childCount:r,bindings:b,bindingFlags:Ur(b),outputs:k,element:{ns:v,name:_,attrs:A,template:null,componentProvider:null,componentView:p||null,componentRendererType:h,publicProviders:null,allProviders:null,handleEvent:c||ar},provider:null,text:null,query:null,ngContent:null}}function zr(n,t,e){var l,r=e.element,o=n.root.selectorOrNode,i=n.renderer;if(n.parent||!o){l=r.name?i.createElement(r.name,r.ns):i.createComment("");var u=Ir(n,t,e);u&&i.appendChild(u,l)}else l=i.selectRootElement(o,!!r.componentRendererType&&r.componentRendererType.encapsulation===Fn.ShadowDom);if(r.attrs)for(var a=0;a<r.attrs.length;a++){var c=s(r.attrs[a],3);i.setAttribute(l,c[1],c[2],c[0])}return l}function qr(n,t,e,l){for(var r=0;r<e.outputs.length;r++){var o=e.outputs[r],i=Gr(n,e.nodeIndex,(p=o.eventName,(c=o.target)?c+":"+p:p)),u=o.target,a=n;"component"===o.target&&(u=null,a=t);var s=a.renderer.listen(u||l,o.eventName,i);n.disposables[e.outputIndex+r]=s}var c,p}function Gr(n,t,e){return function(l){return br(n,t,e,l)}}function Wr(n,t,e,l){if(!mr(n,t,e,l))return!1;var r=t.bindings[e],o=nr(n,t.nodeIndex),i=o.renderElement,u=r.name;switch(15&r.flags){case 1:!function(n,t,e,l,r,o){var i=t.securityContext,u=i?n.root.sanitizer.sanitize(i,o):o;u=null!=u?u.toString():null;var a=n.renderer;null!=o?a.setAttribute(e,r,u,l):a.removeAttribute(e,r,l)}(n,r,i,r.ns,u,l);break;case 2:!function(n,t,e,l){var r=n.renderer;l?r.addClass(t,e):r.removeClass(t,e)}(n,i,u,l);break;case 4:!function(n,t,e,l,r){var o=n.root.sanitizer.sanitize(jt.STYLE,r);if(null!=o){o=o.toString();var i=t.suffix;null!=i&&(o+=i)}else o=null;var u=n.renderer;null!=o?u.setStyle(e,l,o):u.removeStyle(e,l)}(n,r,i,u,l);break;case 8:!function(n,t,e,l,r){var o=t.securityContext,i=o?n.root.sanitizer.sanitize(o,r):r;n.renderer.setProperty(e,l,i)}(33554432&t.flags&&32&r.flags?o.componentView:n,r,i,u,l)}return!0}var Qr=new Object,$r=cr(ut),Kr=cr(ot),Zr=cr(kt);function Yr(n,t,e,l){return e=Un(e),{index:-1,deps:Tr(l,Nn(t)),flags:n,token:t,value:e}}function Xr(n,t,e){void 0===e&&(e=ut.THROW_IF_NOT_FOUND);var l,r,o=Qn(n);try{if(8&t.flags)return t.token;if(2&t.flags&&(e=null),1&t.flags)return n._parent.get(t.token,e);var i=t.tokenKey;switch(i){case $r:case Kr:case Zr:return n}var u,a=n._def.providersByKey[i];if(a){var s=n._providers[a.index];return void 0===s&&(s=n._providers[a.index]=Jr(n,a)),s===Qr?void 0:s}if((u=Cn(t.token))&&(l=n,null!=(r=u).providedIn&&(function(n,t){return n._def.modules.indexOf(r.providedIn)>-1}(l)||"root"===r.providedIn&&l._def.isRoot))){var c=n._providers.length;return n._def.providersByKey[t.tokenKey]={flags:5120,value:u.factory,deps:[],index:c,token:t.token},n._providers[c]=Qr,n._providers[c]=Jr(n,n._def.providersByKey[t.tokenKey])}return 4&t.flags?e:n._parent.get(t.token,e)}finally{Qn(o)}}function Jr(n,t){var e;switch(201347067&t.flags){case 512:e=function(n,t,e){var l=e.length;switch(l){case 0:return new t;case 1:return new t(Xr(n,e[0]));case 2:return new t(Xr(n,e[0]),Xr(n,e[1]));case 3:return new t(Xr(n,e[0]),Xr(n,e[1]),Xr(n,e[2]));default:for(var r=new Array(l),o=0;o<l;o++)r[o]=Xr(n,e[o]);return new(t.bind.apply(t,c([void 0],r)))}}(n,t.value,t.deps);break;case 1024:e=function(n,t,e){var l=e.length;switch(l){case 0:return t();case 1:return t(Xr(n,e[0]));case 2:return t(Xr(n,e[0]),Xr(n,e[1]));case 3:return t(Xr(n,e[0]),Xr(n,e[1]),Xr(n,e[2]));default:for(var r=Array(l),o=0;o<l;o++)r[o]=Xr(n,e[o]);return t.apply(void 0,c(r))}}(n,t.value,t.deps);break;case 2048:e=Xr(n,t.deps[0]);break;case 256:e=t.value}return e===Qr||null==e||"object"!=typeof e||131072&t.flags||"function"!=typeof e.ngOnDestroy||(t.flags|=131072),void 0===e?Qr:e}function no(n,t){var e=n.viewContainer._embeddedViews;if((null==t||t>=e.length)&&(t=e.length-1),t<0)return null;var l=e[t];return l.viewContainerParent=null,ro(e,t),rr.dirtyParentQueries(l),eo(l),l}function to(n,t,e){var l=t?Sr(t,t.def.lastRenderRootNode):n.renderElement,r=e.renderer.parentNode(l),o=e.renderer.nextSibling(l);Dr(e,2,r,o,void 0)}function eo(n){Dr(n,3,null,null,void 0)}function lo(n,t,e){t>=n.length?n.push(e):n.splice(t,0,e)}function ro(n,t){t>=n.length-1?n.pop():n.splice(t,1)}var oo=new Object;function io(n,t,e,l,r,o){return new uo(n,t,e,l,r,o)}var uo=function(n){function t(t,e,l,r,o,i){var u=n.call(this)||this;return u.selector=t,u.componentType=e,u._inputs=r,u._outputs=o,u.ngContentSelectors=i,u.viewDefFactory=l,u}return r(t,n),Object.defineProperty(t.prototype,"inputs",{get:function(){var n=[],t=this._inputs;for(var e in t)n.push({propName:e,templateName:t[e]});return n},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){var n=[];for(var t in this._outputs)n.push({propName:t,templateName:this._outputs[t]});return n},enumerable:!0,configurable:!0}),t.prototype.create=function(n,t,e,l){if(!l)throw new Error("ngModule should be provided");var r=kr(this.viewDefFactory),o=r.nodes[0].element.componentProvider.nodeIndex,i=rr.createRootView(n,t||[],e,r,l,oo),u=tr(i,o).instance;return e&&i.renderer.setAttribute(nr(i,0).renderElement,"ng-version",Bt.full),new ao(i,new ho(i),u)},t}(St),ao=function(n){function t(t,e,l){var r=n.call(this)||this;return r._view=t,r._viewRef=e,r._component=l,r._elDef=r._view.def.nodes[0],r.hostView=e,r.changeDetectorRef=e,r.instance=l,r}return r(t,n),Object.defineProperty(t.prototype,"location",{get:function(){return new At(nr(this._view,this._elDef.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"injector",{get:function(){return new yo(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"componentType",{get:function(){return this._component.constructor},enumerable:!0,configurable:!0}),t.prototype.destroy=function(){this._viewRef.destroy()},t.prototype.onDestroy=function(n){this._viewRef.onDestroy(n)},t}(Ct);function so(n,t,e){return new co(n,t,e)}var co=function(){function n(n,t,e){this._view=n,this._elDef=t,this._data=e,this._embeddedViews=[]}return Object.defineProperty(n.prototype,"element",{get:function(){return new At(this._data.renderElement)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"injector",{get:function(){return new yo(this._view,this._elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"parentInjector",{get:function(){for(var n=this._view,t=this._elDef.parent;!t&&n;)t=Cr(n),n=n.parent;return n?new yo(n,t):new yo(this._view,null)},enumerable:!0,configurable:!0}),n.prototype.clear=function(){for(var n=this._embeddedViews.length-1;n>=0;n--){var t=no(this._data,n);rr.destroyView(t)}},n.prototype.get=function(n){var t=this._embeddedViews[n];if(t){var e=new ho(t);return e.attachToViewContainerRef(this),e}return null},Object.defineProperty(n.prototype,"length",{get:function(){return this._embeddedViews.length},enumerable:!0,configurable:!0}),n.prototype.createEmbeddedView=function(n,t,e){var l=n.createEmbeddedView(t||{});return this.insert(l,e),l},n.prototype.createComponent=function(n,t,e,l,r){var o=e||this.parentInjector;r||n instanceof Ot||(r=o.get(kt));var i=n.create(o,l,void 0,r);return this.insert(i.hostView,t),i},n.prototype.insert=function(n,t){if(n.destroyed)throw new Error("Cannot insert a destroyed View in a ViewContainer!");var e,l,r,o,i=n;return o=(e=this._data).viewContainer._embeddedViews,null==(l=t)&&(l=o.length),(r=i._view).viewContainerParent=this._view,lo(o,l,r),function(n,t){var e=wr(t);if(e&&e!==n&&!(16&t.state)){t.state|=16;var l=e.template._projectedViews;l||(l=e.template._projectedViews=[]),l.push(t),function(n,e){if(!(4&e.flags)){t.parent.def.nodeFlags|=4,e.flags|=4;for(var l=e.parent;l;)l.childFlags|=4,l=l.parent}}(0,t.parentNodeDef)}}(e,r),rr.dirtyParentQueries(r),to(e,l>0?o[l-1]:null,r),i.attachToViewContainerRef(this),n},n.prototype.move=function(n,t){if(n.destroyed)throw new Error("Cannot move a destroyed View in a ViewContainer!");var e,l,r,o,i,u=this._embeddedViews.indexOf(n._view);return r=t,i=(o=(e=this._data).viewContainer._embeddedViews)[l=u],ro(o,l),null==r&&(r=o.length),lo(o,r,i),rr.dirtyParentQueries(i),eo(i),to(e,r>0?o[r-1]:null,i),n},n.prototype.indexOf=function(n){return this._embeddedViews.indexOf(n._view)},n.prototype.remove=function(n){var t=no(this._data,n);t&&rr.destroyView(t)},n.prototype.detach=function(n){var t=no(this._data,n);return t?new ho(t):null},n}();function po(n){return new ho(n)}var ho=function(){function n(n){this._view=n,this._viewContainerRef=null,this._appRef=null}return Object.defineProperty(n.prototype,"rootNodes",{get:function(){return Dr(this._view,0,void 0,void 0,n=[]),n;var n},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"context",{get:function(){return this._view.context},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"destroyed",{get:function(){return 0!=(128&this._view.state)},enumerable:!0,configurable:!0}),n.prototype.markForCheck=function(){vr(this._view)},n.prototype.detach=function(){this._view.state&=-5},n.prototype.detectChanges=function(){var n=this._view.root.rendererFactory;n.begin&&n.begin();try{rr.checkAndUpdateView(this._view)}finally{n.end&&n.end()}},n.prototype.checkNoChanges=function(){rr.checkNoChangesView(this._view)},n.prototype.reattach=function(){this._view.state|=4},n.prototype.onDestroy=function(n){this._view.disposables||(this._view.disposables=[]),this._view.disposables.push(n)},n.prototype.destroy=function(){this._appRef?this._appRef.detachView(this):this._viewContainerRef&&this._viewContainerRef.detach(this._viewContainerRef.indexOf(this)),rr.destroyView(this._view)},n.prototype.detachFromAppRef=function(){this._appRef=null,eo(this._view),rr.dirtyParentQueries(this._view)},n.prototype.attachToAppRef=function(n){if(this._viewContainerRef)throw new Error("This view is already attached to a ViewContainer!");this._appRef=n},n.prototype.attachToViewContainerRef=function(n){if(this._appRef)throw new Error("This view is already attached directly to the ApplicationRef!");this._viewContainerRef=n},n}();function fo(n,t){return new go(n,t)}var go=function(n){function t(t,e){var l=n.call(this)||this;return l._parentView=t,l._def=e,l}return r(t,n),t.prototype.createEmbeddedView=function(n){return new ho(rr.createEmbeddedView(this._parentView,this._def,this._def.element.template,n))},Object.defineProperty(t.prototype,"elementRef",{get:function(){return new At(nr(this._parentView,this._def.nodeIndex).renderElement)},enumerable:!0,configurable:!0}),t}(de);function mo(n,t){return new yo(n,t)}var yo=function(){function n(n,t){this.view=n,this.elDef=t}return n.prototype.get=function(n,t){return void 0===t&&(t=ut.THROW_IF_NOT_FOUND),rr.resolveDep(this.view,this.elDef,!!this.elDef&&0!=(33554432&this.elDef.flags),{flags:0,token:n,tokenKey:cr(n)},t)},n}();function vo(n,t){var e=n.def.nodes[t];if(1&e.flags){var l=nr(n,e.nodeIndex);return e.element.template?l.template:l.renderElement}if(2&e.flags)return Jl(n,e.nodeIndex).renderText;if(20240&e.flags)return tr(n,e.nodeIndex).instance;throw new Error("Illegal state: read nodeValue for node index "+t)}function _o(n){return new bo(n.renderer)}var bo=function(){function n(n){this.delegate=n}return n.prototype.selectRootElement=function(n){return this.delegate.selectRootElement(n)},n.prototype.createElement=function(n,t){var e=s(Vr(t),2),l=this.delegate.createElement(e[1],e[0]);return n&&this.delegate.appendChild(n,l),l},n.prototype.createViewRoot=function(n){return n},n.prototype.createTemplateAnchor=function(n){var t=this.delegate.createComment("");return n&&this.delegate.appendChild(n,t),t},n.prototype.createText=function(n,t){var e=this.delegate.createText(t);return n&&this.delegate.appendChild(n,e),e},n.prototype.projectNodes=function(n,t){for(var e=0;e<t.length;e++)this.delegate.appendChild(n,t[e])},n.prototype.attachViewAfter=function(n,t){for(var e=this.delegate.parentNode(n),l=this.delegate.nextSibling(n),r=0;r<t.length;r++)this.delegate.insertBefore(e,t[r],l)},n.prototype.detachView=function(n){for(var t=0;t<n.length;t++){var e=n[t],l=this.delegate.parentNode(e);this.delegate.removeChild(l,e)}},n.prototype.destroyView=function(n,t){for(var e=0;e<t.length;e++)this.delegate.destroyNode(t[e])},n.prototype.listen=function(n,t,e){return this.delegate.listen(n,t,e)},n.prototype.listenGlobal=function(n,t,e){return this.delegate.listen(n,t,e)},n.prototype.setElementProperty=function(n,t,e){this.delegate.setProperty(n,t,e)},n.prototype.setElementAttribute=function(n,t,e){var l=s(Vr(t),2),r=l[0],o=l[1];null!=e?this.delegate.setAttribute(n,o,e,r):this.delegate.removeAttribute(n,o,r)},n.prototype.setBindingDebugInfo=function(n,t,e){},n.prototype.setElementClass=function(n,t,e){e?this.delegate.addClass(n,t):this.delegate.removeClass(n,t)},n.prototype.setElementStyle=function(n,t,e){null!=e?this.delegate.setStyle(n,t,e):this.delegate.removeStyle(n,t)},n.prototype.invokeElementMethod=function(n,t,e){n[t].apply(n,e)},n.prototype.setText=function(n,t){this.delegate.setValue(n,t)},n.prototype.animate=function(){throw new Error("Renderer.animate is no longer supported!")},n}();function wo(n,t,e,l){return new Co(n,t,e,l)}var Co=function(){function n(n,t,e,l){this._moduleType=n,this._parent=t,this._bootstrapComponents=e,this._def=l,this._destroyListeners=[],this._destroyed=!1,this.injector=this,function(n){for(var t=n._def,e=n._providers=new Array(t.providers.length),l=0;l<t.providers.length;l++){var r=t.providers[l];4096&r.flags||void 0===e[l]&&(e[l]=Jr(n,r))}}(this)}return n.prototype.get=function(n,t,e){void 0===t&&(t=ut.THROW_IF_NOT_FOUND),void 0===e&&(e=Gn.Default);var l=0;return e&Gn.SkipSelf?l|=1:e&Gn.Self&&(l|=4),Xr(this,{token:n,tokenKey:cr(n),flags:l},t)},Object.defineProperty(n.prototype,"instance",{get:function(){return this.get(this._moduleType)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"componentFactoryResolver",{get:function(){return this.get(Tt)},enumerable:!0,configurable:!0}),n.prototype.destroy=function(){if(this._destroyed)throw new Error("The ng module "+Nn(this.instance.constructor)+" has already been destroyed.");this._destroyed=!0,function(n,t){for(var e=n._def,l=new Set,r=0;r<e.providers.length;r++)if(131072&e.providers[r].flags){var o=n._providers[r];if(o&&o!==Qr){var i=o.ngOnDestroy;"function"!=typeof i||l.has(o)||(i.apply(o),l.add(o))}}}(this),this._destroyListeners.forEach(function(n){return n()})},n.prototype.onDestroy=function(n){this._destroyListeners.push(n)},n}(),So=cr(Mt),Eo=cr(Vt),xo=cr(At),Po=cr(bl),To=cr(de),Io=cr(Cl),Oo=cr(ut),ko=cr(ot);function Do(n,t,e,l,r,o,i,u){var a=[];if(i)for(var c in i){var p=s(i[c],2);a[p[0]]={flags:8,name:c,nonMinifiedName:p[1],ns:null,securityContext:null,suffix:null}}var h=[];if(u)for(var d in u)h.push({type:1,propName:d,target:null,eventName:u[d]});return Ro(n,t|=16384,e,l,r,r,o,a,h)}function Ao(n,t,e,l,r){return Ro(-1,n,t,0,e,l,r)}function Ro(n,t,e,l,r,o,i,u,a){var s=Pr(e),c=s.matchedQueries,p=s.references,h=s.matchedQueryIds;a||(a=[]),u||(u=[]),o=Un(o);var d=Tr(i,Nn(r));return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:n,flags:t,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:c,matchedQueryIds:h,references:p,ngContentIndex:-1,childCount:l,bindings:u,bindingFlags:Ur(u),outputs:a,element:null,provider:{token:r,value:o,deps:d},text:null,query:null,ngContent:null}}function Mo(n,t){return Uo(n,t)}function No(n,t){for(var e=n;e.parent&&!Er(e);)e=e.parent;return jo(e.parent,Cr(e),!0,t.provider.value,t.provider.deps)}function Lo(n,t){var e=jo(n,t.parent,(32768&t.flags)>0,t.provider.value,t.provider.deps);if(t.outputs.length)for(var l=0;l<t.outputs.length;l++){var r=t.outputs[l],o=e[r.propName];if(!Pe(o))throw new Error("@Output "+r.propName+" not initialized in '"+e.constructor.name+"'.");var i=o.subscribe(Vo(n,t.parent.nodeIndex,r.eventName));n.disposables[t.outputIndex+l]=i.unsubscribe.bind(i)}return e}function Vo(n,t,e){return function(l){return br(n,t,e,l)}}function Uo(n,t){var e=(8192&t.flags)>0,l=t.provider;switch(201347067&t.flags){case 512:return jo(n,t.parent,e,l.value,l.deps);case 1024:return function(n,t,e,l,r){var o=r.length;switch(o){case 0:return l();case 1:return l(Bo(n,t,e,r[0]));case 2:return l(Bo(n,t,e,r[0]),Bo(n,t,e,r[1]));case 3:return l(Bo(n,t,e,r[0]),Bo(n,t,e,r[1]),Bo(n,t,e,r[2]));default:for(var i=Array(o),u=0;u<o;u++)i[u]=Bo(n,t,e,r[u]);return l.apply(void 0,c(i))}}(n,t.parent,e,l.value,l.deps);case 2048:return Bo(n,t.parent,e,l.deps[0]);case 256:return l.value}}function jo(n,t,e,l,r){var o=r.length;switch(o){case 0:return new l;case 1:return new l(Bo(n,t,e,r[0]));case 2:return new l(Bo(n,t,e,r[0]),Bo(n,t,e,r[1]));case 3:return new l(Bo(n,t,e,r[0]),Bo(n,t,e,r[1]),Bo(n,t,e,r[2]));default:for(var i=new Array(o),u=0;u<o;u++)i[u]=Bo(n,t,e,r[u]);return new(l.bind.apply(l,c([void 0],i)))}}var Fo={};function Bo(n,t,e,l,r){if(void 0===r&&(r=ut.THROW_IF_NOT_FOUND),8&l.flags)return l.token;var o=n;2&l.flags&&(r=null);var i=l.tokenKey;i===Io&&(e=!(!t||!t.element.componentView)),t&&1&l.flags&&(e=!1,t=t.parent);for(var u=n;u;){if(t)switch(i){case So:return _o(Ho(u,t,e));case Eo:return Ho(u,t,e).renderer;case xo:return new At(nr(u,t.nodeIndex).renderElement);case Po:return nr(u,t.nodeIndex).viewContainer;case To:if(t.element.template)return nr(u,t.nodeIndex).template;break;case Io:return po(Ho(u,t,e));case Oo:case ko:return mo(u,t);default:var a=(e?t.element.allProviders:t.element.publicProviders)[i];if(a){var s=tr(u,a.nodeIndex);return s||(s={instance:Uo(u,a)},u.nodes[a.nodeIndex]=s),s.instance}}e=Er(u),t=Cr(u),u=u.parent,4&l.flags&&(u=null)}var c=o.root.injector.get(l.token,Fo);return c!==Fo||r===Fo?c:o.root.ngModule.injector.get(l.token,r)}function Ho(n,t,e){var l;if(e)l=nr(n,t.nodeIndex).componentView;else for(l=n;l.parent&&!Er(l);)l=l.parent;return l}function zo(n,t,e,l,r,o){if(32768&e.flags){var i=nr(n,e.parent.nodeIndex).componentView;2&i.def.flags&&(i.state|=8)}if(t.instance[e.bindings[l].name]=r,524288&e.flags){o=o||{};var u=Xn.unwrap(n.oldValues[e.bindingIndex+l]);o[e.bindings[l].nonMinifiedName]=new Jn(u,r,0!=(2&n.state))}return n.oldValues[e.bindingIndex+l]=r,o}function qo(n,t){if(n.def.nodeFlags&t)for(var e=n.def.nodes,l=0,r=0;r<e.length;r++){var o=e[r],i=o.parent;for(!i&&o.flags&t&&Wo(n,r,o.flags&t,l++),0==(o.childFlags&t)&&(r+=o.childCount);i&&1&i.flags&&r===i.nodeIndex+i.childCount;)i.directChildFlags&t&&(l=Go(n,i,t,l)),i=i.parent}}function Go(n,t,e,l){for(var r=t.nodeIndex+1;r<=t.nodeIndex+t.childCount;r++){var o=n.def.nodes[r];o.flags&e&&Wo(n,r,o.flags&e,l++),r+=o.childCount}return l}function Wo(n,t,e,l){var r=tr(n,t);if(r){var o=r.instance;o&&(rr.setCurrentNode(n,t),1048576&e&&Xl(n,512,l)&&o.ngAfterContentInit(),2097152&e&&o.ngAfterContentChecked(),4194304&e&&Xl(n,768,l)&&o.ngAfterViewInit(),8388608&e&&o.ngAfterViewChecked(),131072&e&&o.ngOnDestroy())}}function Qo(n){for(var t=n.def.nodeMatchedQueries;n.parent&&xr(n);){var e=n.parentNodeDef;n=n.parent;for(var l=e.nodeIndex+e.childCount,r=0;r<=l;r++)67108864&(o=n.def.nodes[r]).flags&&536870912&o.flags&&(o.query.filterId&t)===o.query.filterId&&lr(n,r).setDirty(),!(1&o.flags&&r+o.childCount<e.nodeIndex)&&67108864&o.childFlags&&536870912&o.childFlags||(r+=o.childCount)}if(134217728&n.def.nodeFlags)for(r=0;r<n.def.nodes.length;r++){var o;134217728&(o=n.def.nodes[r]).flags&&536870912&o.flags&&lr(n,r).setDirty(),r+=o.childCount}}function $o(n,t){var e=lr(n,t.nodeIndex);if(e.dirty){var l,r=void 0;if(67108864&t.flags){var o=t.parent.parent;r=Ko(n,o.nodeIndex,o.nodeIndex+o.childCount,t.query,[]),l=tr(n,t.parent.nodeIndex).instance}else 134217728&t.flags&&(r=Ko(n,0,n.def.nodes.length-1,t.query,[]),l=n.component);e.reset(r);for(var i=t.query.bindings,u=!1,a=0;a<i.length;a++){var s=i[a],c=void 0;switch(s.bindingType){case 0:c=e.first;break;case 1:c=e,u=!0}l[s.propName]=c}u&&e.notifyOnChanges()}}function Ko(n,t,e,l,r){for(var o=t;o<=e;o++){var i=n.def.nodes[o],u=i.matchedQueries[l.id];if(null!=u&&r.push(Zo(n,i,u)),1&i.flags&&i.element.template&&(i.element.template.nodeMatchedQueries&l.filterId)===l.filterId){var a=nr(n,o);if((i.childMatchedQueries&l.filterId)===l.filterId&&(Ko(n,o+1,o+i.childCount,l,r),o+=i.childCount),16777216&i.flags)for(var s=a.viewContainer._embeddedViews,c=0;c<s.length;c++){var p=s[c],h=wr(p);h&&h===a&&Ko(p,0,p.def.nodes.length-1,l,r)}var d=a.template._projectedViews;if(d)for(c=0;c<d.length;c++){var f=d[c];Ko(f,0,f.def.nodes.length-1,l,r)}}(i.childMatchedQueries&l.filterId)!==l.filterId&&(o+=i.childCount)}return r}function Zo(n,t,e){if(null!=e)switch(e){case 1:return nr(n,t.nodeIndex).renderElement;case 0:return new At(nr(n,t.nodeIndex).renderElement);case 2:return nr(n,t.nodeIndex).template;case 3:return nr(n,t.nodeIndex).viewContainer;case 4:return tr(n,t.nodeIndex).instance}}function Yo(n,t,e){var l=Ir(n,t,e);l&&Rr(n,e.ngContent.index,1,l,null,void 0)}function Xo(n,t){return function(n,t,e){for(var l=new Array(e.length),r=0;r<e.length;r++){var o=e[r];l[r]={flags:8,name:o,ns:null,nonMinifiedName:o,securityContext:null,suffix:null}}return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:t,flags:32,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:{},matchedQueryIds:0,references:{},ngContentIndex:-1,childCount:0,bindings:l,bindingFlags:Ur(l),outputs:[],element:null,provider:null,text:null,query:null,ngContent:null}}(0,n,new Array(t))}function Jo(n,t,e){for(var l=new Array(e.length-1),r=1;r<e.length;r++)l[r-1]={flags:8,name:null,ns:null,nonMinifiedName:null,securityContext:null,suffix:e[r]};return{nodeIndex:-1,parent:null,renderParent:null,bindingIndex:-1,outputIndex:-1,checkIndex:n,flags:2,childFlags:0,directChildFlags:0,childMatchedQueries:0,matchedQueries:{},matchedQueryIds:0,references:{},ngContentIndex:t,childCount:0,bindings:l,bindingFlags:8,outputs:[],element:null,provider:null,text:{prefix:e[0]},query:null,ngContent:null}}function ni(n,t,e){var l,r=n.renderer;l=r.createText(e.text.prefix);var o=Ir(n,t,e);return o&&r.appendChild(o,l),{renderText:l}}function ti(n,t){return(null!=n?n.toString():"")+t.suffix}function ei(n,t,e,l){for(var r=0,o=0,i=0,u=0,a=0,s=null,c=null,p=!1,h=!1,d=null,f=0;f<t.length;f++){var g=t[f];if(g.nodeIndex=f,g.parent=s,g.bindingIndex=r,g.outputIndex=o,g.renderParent=c,i|=g.flags,a|=g.matchedQueryIds,g.element){var m=g.element;m.publicProviders=s?s.element.publicProviders:Object.create(null),m.allProviders=m.publicProviders,p=!1,h=!1,g.element.template&&(a|=g.element.template.nodeMatchedQueries)}if(ri(s,g,t.length),r+=g.bindings.length,o+=g.outputs.length,!c&&3&g.flags&&(d=g),20224&g.flags){p||(p=!0,s.element.publicProviders=Object.create(s.element.publicProviders),s.element.allProviders=s.element.publicProviders);var y=0!=(32768&g.flags);0==(8192&g.flags)||y?s.element.publicProviders[cr(g.provider.token)]=g:(h||(h=!0,s.element.allProviders=Object.create(s.element.publicProviders)),s.element.allProviders[cr(g.provider.token)]=g),y&&(s.element.componentProvider=g)}if(s?(s.childFlags|=g.flags,s.directChildFlags|=g.flags,s.childMatchedQueries|=g.matchedQueryIds,g.element&&g.element.template&&(s.childMatchedQueries|=g.element.template.nodeMatchedQueries)):u|=g.flags,g.childCount>0)s=g,li(g)||(c=g);else for(;s&&f===s.nodeIndex+s.childCount;){var v=s.parent;v&&(v.childFlags|=s.childFlags,v.childMatchedQueries|=s.childMatchedQueries),c=(s=v)&&li(s)?s.renderParent:s}}return{factory:null,nodeFlags:i,rootNodeFlags:u,nodeMatchedQueries:a,flags:n,nodes:t,updateDirectives:e||ar,updateRenderer:l||ar,handleEvent:function(n,e,l,r){return t[e].element.handleEvent(n,l,r)},bindingCount:r,outputCount:o,lastRenderRootNode:d}}function li(n){return 0!=(1&n.flags)&&null===n.element.name}function ri(n,t,e){var l=t.element&&t.element.template;if(l){if(!l.lastRenderRootNode)throw new Error("Illegal State: Embedded templates without nodes are not allowed!");if(l.lastRenderRootNode&&16777216&l.lastRenderRootNode.flags)throw new Error("Illegal State: Last root node of a template can't have embedded views, at index "+t.nodeIndex+"!")}if(20224&t.flags&&0==(1&(n?n.flags:0)))throw new Error("Illegal State: StaticProvider/Directive nodes need to be children of elements or anchors, at index "+t.nodeIndex+"!");if(t.query){if(67108864&t.flags&&(!n||0==(16384&n.flags)))throw new Error("Illegal State: Content Query nodes need to be children of directives, at index "+t.nodeIndex+"!");if(134217728&t.flags&&n)throw new Error("Illegal State: View Query nodes have to be top level nodes, at index "+t.nodeIndex+"!")}if(t.childCount){var r=n?n.nodeIndex+n.childCount:e-1;if(t.nodeIndex<=r&&t.nodeIndex+t.childCount>r)throw new Error("Illegal State: childCount of node leads outside of parent, at index "+t.nodeIndex+"!")}}function oi(n,t,e,l){var r=ai(n.root,n.renderer,n,t,e);return si(r,n.component,l),ci(r),r}function ii(n,t,e){var l=ai(n,n.renderer,null,null,t);return si(l,e,e),ci(l),l}function ui(n,t,e,l){var r,o=t.element.componentRendererType;return r=o?n.root.rendererFactory.createRenderer(l,o):n.root.renderer,ai(n.root,r,n,t.element.componentProvider,e)}function ai(n,t,e,l,r){var o=new Array(r.nodes.length),i=r.outputCount?new Array(r.outputCount):null;return{def:r,parent:e,viewContainerParent:null,parentNodeDef:l,context:null,component:null,nodes:o,state:13,root:n,renderer:t,oldValues:new Array(r.bindingCount),disposables:i,initIndex:-1}}function si(n,t,e){n.component=t,n.context=e}function ci(n){var t;Er(n)&&(t=nr(n.parent,n.parentNodeDef.parent.nodeIndex).renderElement);for(var e=n.def,l=n.nodes,r=0;r<e.nodes.length;r++){var o=e.nodes[r];rr.setCurrentNode(n,r);var i=void 0;switch(201347067&o.flags){case 1:var u=zr(n,t,o),a=void 0;if(33554432&o.flags){var s=kr(o.element.componentView);a=rr.createComponentView(n,o,s,u)}qr(n,a,o,u),i={renderElement:u,componentView:a,viewContainer:null,template:o.element.template?fo(n,o):void 0},16777216&o.flags&&(i.viewContainer=so(n,o,i));break;case 2:i=ni(n,t,o);break;case 512:case 1024:case 2048:case 256:(i=l[r])||4096&o.flags||(i={instance:Mo(n,o)});break;case 16:i={instance:No(n,o)};break;case 16384:(i=l[r])||(i={instance:Lo(n,o)}),32768&o.flags&&si(nr(n,o.parent.nodeIndex).componentView,i.instance,i.instance);break;case 32:case 64:case 128:i={value:void 0};break;case 67108864:case 134217728:i=new gl;break;case 8:Yo(n,t,o),i=void 0}l[r]=i}_i(n,vi.CreateViewNodes),Si(n,201326592,268435456,0)}function pi(n){fi(n),rr.updateDirectives(n,1),bi(n,vi.CheckNoChanges),rr.updateRenderer(n,1),_i(n,vi.CheckNoChanges),n.state&=-97}function hi(n){1&n.state?(n.state&=-2,n.state|=2):n.state&=-3,Yl(n,0,256),fi(n),rr.updateDirectives(n,0),bi(n,vi.CheckAndUpdate),Si(n,67108864,536870912,0);var t=Yl(n,256,512);qo(n,2097152|(t?1048576:0)),rr.updateRenderer(n,0),_i(n,vi.CheckAndUpdate),Si(n,134217728,536870912,0),qo(n,8388608|((t=Yl(n,512,768))?4194304:0)),2&n.def.flags&&(n.state&=-9),n.state&=-97,Yl(n,768,1024)}function di(n,t,e,l,r,o,i,u,a,s,p,h,d){return 0===e?function(n,t,e,l,r,o,i,u,a,s,c,p){switch(201347067&t.flags){case 1:return function(n,t,e,l,r,o,i,u,a,s,c,p){var h=t.bindings.length,d=!1;return h>0&&Wr(n,t,0,e)&&(d=!0),h>1&&Wr(n,t,1,l)&&(d=!0),h>2&&Wr(n,t,2,r)&&(d=!0),h>3&&Wr(n,t,3,o)&&(d=!0),h>4&&Wr(n,t,4,i)&&(d=!0),h>5&&Wr(n,t,5,u)&&(d=!0),h>6&&Wr(n,t,6,a)&&(d=!0),h>7&&Wr(n,t,7,s)&&(d=!0),h>8&&Wr(n,t,8,c)&&(d=!0),h>9&&Wr(n,t,9,p)&&(d=!0),d}(n,t,e,l,r,o,i,u,a,s,c,p);case 2:return function(n,t,e,l,r,o,i,u,a,s,c,p){var h=!1,d=t.bindings,f=d.length;if(f>0&&mr(n,t,0,e)&&(h=!0),f>1&&mr(n,t,1,l)&&(h=!0),f>2&&mr(n,t,2,r)&&(h=!0),f>3&&mr(n,t,3,o)&&(h=!0),f>4&&mr(n,t,4,i)&&(h=!0),f>5&&mr(n,t,5,u)&&(h=!0),f>6&&mr(n,t,6,a)&&(h=!0),f>7&&mr(n,t,7,s)&&(h=!0),f>8&&mr(n,t,8,c)&&(h=!0),f>9&&mr(n,t,9,p)&&(h=!0),h){var g=t.text.prefix;f>0&&(g+=ti(e,d[0])),f>1&&(g+=ti(l,d[1])),f>2&&(g+=ti(r,d[2])),f>3&&(g+=ti(o,d[3])),f>4&&(g+=ti(i,d[4])),f>5&&(g+=ti(u,d[5])),f>6&&(g+=ti(a,d[6])),f>7&&(g+=ti(s,d[7])),f>8&&(g+=ti(c,d[8])),f>9&&(g+=ti(p,d[9]));var m=Jl(n,t.nodeIndex).renderText;n.renderer.setValue(m,g)}return h}(n,t,e,l,r,o,i,u,a,s,c,p);case 16384:return function(n,t,e,l,r,o,i,u,a,s,c,p){var h=tr(n,t.nodeIndex),d=h.instance,f=!1,g=void 0,m=t.bindings.length;return m>0&&gr(n,t,0,e)&&(f=!0,g=zo(n,h,t,0,e,g)),m>1&&gr(n,t,1,l)&&(f=!0,g=zo(n,h,t,1,l,g)),m>2&&gr(n,t,2,r)&&(f=!0,g=zo(n,h,t,2,r,g)),m>3&&gr(n,t,3,o)&&(f=!0,g=zo(n,h,t,3,o,g)),m>4&&gr(n,t,4,i)&&(f=!0,g=zo(n,h,t,4,i,g)),m>5&&gr(n,t,5,u)&&(f=!0,g=zo(n,h,t,5,u,g)),m>6&&gr(n,t,6,a)&&(f=!0,g=zo(n,h,t,6,a,g)),m>7&&gr(n,t,7,s)&&(f=!0,g=zo(n,h,t,7,s,g)),m>8&&gr(n,t,8,c)&&(f=!0,g=zo(n,h,t,8,c,g)),m>9&&gr(n,t,9,p)&&(f=!0,g=zo(n,h,t,9,p,g)),g&&d.ngOnChanges(g),65536&t.flags&&Xl(n,256,t.nodeIndex)&&d.ngOnInit(),262144&t.flags&&d.ngDoCheck(),f}(n,t,e,l,r,o,i,u,a,s,c,p);case 32:case 64:case 128:return function(n,t,e,l,r,o,i,u,a,s,c,p){var h=t.bindings,d=!1,f=h.length;if(f>0&&mr(n,t,0,e)&&(d=!0),f>1&&mr(n,t,1,l)&&(d=!0),f>2&&mr(n,t,2,r)&&(d=!0),f>3&&mr(n,t,3,o)&&(d=!0),f>4&&mr(n,t,4,i)&&(d=!0),f>5&&mr(n,t,5,u)&&(d=!0),f>6&&mr(n,t,6,a)&&(d=!0),f>7&&mr(n,t,7,s)&&(d=!0),f>8&&mr(n,t,8,c)&&(d=!0),f>9&&mr(n,t,9,p)&&(d=!0),d){var g=er(n,t.nodeIndex),m=void 0;switch(201347067&t.flags){case 32:m=new Array(h.length),f>0&&(m[0]=e),f>1&&(m[1]=l),f>2&&(m[2]=r),f>3&&(m[3]=o),f>4&&(m[4]=i),f>5&&(m[5]=u),f>6&&(m[6]=a),f>7&&(m[7]=s),f>8&&(m[8]=c),f>9&&(m[9]=p);break;case 64:m={},f>0&&(m[h[0].name]=e),f>1&&(m[h[1].name]=l),f>2&&(m[h[2].name]=r),f>3&&(m[h[3].name]=o),f>4&&(m[h[4].name]=i),f>5&&(m[h[5].name]=u),f>6&&(m[h[6].name]=a),f>7&&(m[h[7].name]=s),f>8&&(m[h[8].name]=c),f>9&&(m[h[9].name]=p);break;case 128:var y=e;switch(f){case 1:m=y.transform(e);break;case 2:m=y.transform(l);break;case 3:m=y.transform(l,r);break;case 4:m=y.transform(l,r,o);break;case 5:m=y.transform(l,r,o,i);break;case 6:m=y.transform(l,r,o,i,u);break;case 7:m=y.transform(l,r,o,i,u,a);break;case 8:m=y.transform(l,r,o,i,u,a,s);break;case 9:m=y.transform(l,r,o,i,u,a,s,c);break;case 10:m=y.transform(l,r,o,i,u,a,s,c,p)}}g.value=m}return d}(n,t,e,l,r,o,i,u,a,s,c,p);default:throw"unreachable"}}(n,t,l,r,o,i,u,a,s,p,h,d):function(n,t,e){switch(201347067&t.flags){case 1:return function(n,t,e){for(var l=!1,r=0;r<e.length;r++)Wr(n,t,r,e[r])&&(l=!0);return l}(n,t,e);case 2:return function(n,t,e){for(var l=t.bindings,r=!1,o=0;o<e.length;o++)mr(n,t,o,e[o])&&(r=!0);if(r){var i="";for(o=0;o<e.length;o++)i+=ti(e[o],l[o]);i=t.text.prefix+i;var u=Jl(n,t.nodeIndex).renderText;n.renderer.setValue(u,i)}return r}(n,t,e);case 16384:return function(n,t,e){for(var l=tr(n,t.nodeIndex),r=l.instance,o=!1,i=void 0,u=0;u<e.length;u++)gr(n,t,u,e[u])&&(o=!0,i=zo(n,l,t,u,e[u],i));return i&&r.ngOnChanges(i),65536&t.flags&&Xl(n,256,t.nodeIndex)&&r.ngOnInit(),262144&t.flags&&r.ngDoCheck(),o}(n,t,e);case 32:case 64:case 128:return function(n,t,e){for(var l=t.bindings,r=!1,o=0;o<e.length;o++)mr(n,t,o,e[o])&&(r=!0);if(r){var i=er(n,t.nodeIndex),u=void 0;switch(201347067&t.flags){case 32:u=e;break;case 64:for(u={},o=0;o<e.length;o++)u[l[o].name]=e[o];break;case 128:var a=e[0],s=e.slice(1);u=a.transform.apply(a,c(s))}i.value=u}return r}(n,t,e);default:throw"unreachable"}}(n,t,l)}function fi(n){var t=n.def;if(4&t.nodeFlags)for(var e=0;e<t.nodes.length;e++){var l=t.nodes[e];if(4&l.flags){var r=nr(n,e).template._projectedViews;if(r)for(var o=0;o<r.length;o++){var i=r[o];i.state|=32,_r(i,n)}}else 0==(4&l.childFlags)&&(e+=l.childCount)}}function gi(n,t,e,l,r,o,i,u,a,s,c,p,h){return 0===e?function(n,t,e,l,r,o,i,u,a,s,c,p){var h=t.bindings.length;h>0&&yr(n,t,0,e),h>1&&yr(n,t,1,l),h>2&&yr(n,t,2,r),h>3&&yr(n,t,3,o),h>4&&yr(n,t,4,i),h>5&&yr(n,t,5,u),h>6&&yr(n,t,6,a),h>7&&yr(n,t,7,s),h>8&&yr(n,t,8,c),h>9&&yr(n,t,9,p)}(n,t,l,r,o,i,u,a,s,c,p,h):function(n,t,e){for(var l=0;l<e.length;l++)yr(n,t,l,e[l])}(n,t,l),!1}function mi(n,t){if(lr(n,t.nodeIndex).dirty)throw or(rr.createDebugContext(n,t.nodeIndex),"Query "+t.query.id+" not dirty","Query "+t.query.id+" dirty",0!=(1&n.state))}function yi(n){if(!(128&n.state)){if(bi(n,vi.Destroy),_i(n,vi.Destroy),qo(n,131072),n.disposables)for(var t=0;t<n.disposables.length;t++)n.disposables[t]();!function(n){if(16&n.state){var t=wr(n);if(t){var e=t.template._projectedViews;e&&(ro(e,e.indexOf(n)),rr.dirtyParentQueries(n))}}}(n),n.renderer.destroyNode&&function(n){for(var t=n.def.nodes.length,e=0;e<t;e++){var l=n.def.nodes[e];1&l.flags?n.renderer.destroyNode(nr(n,e).renderElement):2&l.flags?n.renderer.destroyNode(Jl(n,e).renderText):(67108864&l.flags||134217728&l.flags)&&lr(n,e).destroy()}}(n),Er(n)&&n.renderer.destroy(),n.state|=128}}var vi=function(n){return n[n.CreateViewNodes=0]="CreateViewNodes",n[n.CheckNoChanges=1]="CheckNoChanges",n[n.CheckNoChangesProjectedViews=2]="CheckNoChangesProjectedViews",n[n.CheckAndUpdate=3]="CheckAndUpdate",n[n.CheckAndUpdateProjectedViews=4]="CheckAndUpdateProjectedViews",n[n.Destroy=5]="Destroy",n}({});function _i(n,t){var e=n.def;if(33554432&e.nodeFlags)for(var l=0;l<e.nodes.length;l++){var r=e.nodes[l];33554432&r.flags?wi(nr(n,l).componentView,t):0==(33554432&r.childFlags)&&(l+=r.childCount)}}function bi(n,t){var e=n.def;if(16777216&e.nodeFlags)for(var l=0;l<e.nodes.length;l++){var r=e.nodes[l];if(16777216&r.flags)for(var o=nr(n,l).viewContainer._embeddedViews,i=0;i<o.length;i++)wi(o[i],t);else 0==(16777216&r.childFlags)&&(l+=r.childCount)}}function wi(n,t){var e=n.state;switch(t){case vi.CheckNoChanges:0==(128&e)&&(12==(12&e)?pi(n):64&e&&Ci(n,vi.CheckNoChangesProjectedViews));break;case vi.CheckNoChangesProjectedViews:0==(128&e)&&(32&e?pi(n):64&e&&Ci(n,t));break;case vi.CheckAndUpdate:0==(128&e)&&(12==(12&e)?hi(n):64&e&&Ci(n,vi.CheckAndUpdateProjectedViews));break;case vi.CheckAndUpdateProjectedViews:0==(128&e)&&(32&e?hi(n):64&e&&Ci(n,t));break;case vi.Destroy:yi(n);break;case vi.CreateViewNodes:ci(n)}}function Ci(n,t){bi(n,t),_i(n,t)}function Si(n,t,e,l){if(n.def.nodeFlags&t&&n.def.nodeFlags&e)for(var r=n.def.nodes.length,o=0;o<r;o++){var i=n.def.nodes[o];if(i.flags&t&&i.flags&e)switch(rr.setCurrentNode(n,i.nodeIndex),l){case 0:$o(n,i);break;case 1:mi(n,i)}i.childFlags&t&&i.childFlags&e||(o+=i.childCount)}}var Ei=!1;function xi(n,t,e,l,r,o){var i=r.injector.get(Nt);return ii(Ti(n,r,i,t,e),l,o)}function Pi(n,t,e,l,r,o){var i=r.injector.get(Nt),u=Ti(n,r,new ou(i),t,e),a=Vi(l);return lu(Wi.create,ii,null,[u,a,o])}function Ti(n,t,e,l,r){var o=t.injector.get(Ft),i=t.injector.get(Ee),u=e.createRenderer(null,null);return{ngModule:t,injector:n,projectableNodes:l,selectorOrNode:r,sanitizer:o,rendererFactory:e,renderer:u,errorHandler:i}}function Ii(n,t,e,l){var r=Vi(e);return lu(Wi.create,oi,null,[n,t,r,l])}function Oi(n,t,e,l){return e=Ri.get(t.element.componentProvider.provider.token)||Vi(e),lu(Wi.create,ui,null,[n,t,e,l])}function ki(n,t,e,l){return wo(n,t,e,function(n){var t=function(n){var t=!1,e=!1;return 0===Di.size?{hasOverrides:t,hasDeprecatedOverrides:e}:(n.providers.forEach(function(n){var l=Di.get(n.token);3840&n.flags&&l&&(t=!0,e=e||l.deprecatedBehavior)}),n.modules.forEach(function(n){Ai.forEach(function(l,r){Cn(r).providedIn===n&&(t=!0,e=e||l.deprecatedBehavior)})}),{hasOverrides:t,hasDeprecatedOverrides:e})}(n),e=t.hasDeprecatedOverrides;return t.hasOverrides?(function(n){for(var t=0;t<n.providers.length;t++){var l=n.providers[t];e&&(l.flags|=4096);var r=Di.get(l.token);r&&(l.flags=-3841&l.flags|r.flags,l.deps=Tr(r.deps),l.value=r.value)}if(Ai.size>0){var o=new Set(n.modules);Ai.forEach(function(t,l){if(o.has(Cn(l).providedIn)){var r={token:l,flags:t.flags|(e?4096:0),deps:Tr(t.deps),value:t.value,index:n.providers.length};n.providers.push(r),n.providersByKey[cr(l)]=r}})}}(n=n.factory(function(){return ar})),n):n}(l))}var Di=new Map,Ai=new Map,Ri=new Map;function Mi(n){var t;Di.set(n.token,n),"function"==typeof n.token&&(t=Cn(n.token))&&"function"==typeof t.providedIn&&Ai.set(n.token,n)}function Ni(n,t){var e=kr(t.viewDefFactory),l=kr(e.nodes[0].element.componentView);Ri.set(n,l)}function Li(){Di.clear(),Ai.clear(),Ri.clear()}function Vi(n){if(0===Di.size)return n;var t=function(n){for(var t=[],e=null,l=0;l<n.nodes.length;l++){var r=n.nodes[l];1&r.flags&&(e=r),e&&3840&r.flags&&Di.has(r.provider.token)&&(t.push(e.nodeIndex),e=null)}return t}(n);if(0===t.length)return n;n=n.factory(function(){return ar});for(var e=0;e<t.length;e++)l(n,t[e]);return n;function l(n,t){for(var e=t+1;e<n.nodes.length;e++){var l=n.nodes[e];if(1&l.flags)return;if(3840&l.flags){var r=l.provider,o=Di.get(r.token);o&&(l.flags=-3841&l.flags|o.flags,r.deps=Tr(o.deps),r.value=o.value)}}}}function Ui(n,t,e,l,r,o,i,u,a,s,c,p,h){var d=n.def.nodes[t];return di(n,d,e,l,r,o,i,u,a,s,c,p,h),224&d.flags?er(n,t).value:void 0}function ji(n,t,e,l,r,o,i,u,a,s,c,p,h){var d=n.def.nodes[t];return gi(n,d,e,l,r,o,i,u,a,s,c,p,h),224&d.flags?er(n,t).value:void 0}function Fi(n){return lu(Wi.detectChanges,hi,null,[n])}function Bi(n){return lu(Wi.checkNoChanges,pi,null,[n])}function Hi(n){return lu(Wi.destroy,yi,null,[n])}var zi,qi,Gi,Wi=function(n){return n[n.create=0]="create",n[n.detectChanges=1]="detectChanges",n[n.checkNoChanges=2]="checkNoChanges",n[n.destroy=3]="destroy",n[n.handleEvent=4]="handleEvent",n}({});function Qi(n,t){qi=n,Gi=t}function $i(n,t,e,l){return Qi(n,t),lu(Wi.handleEvent,n.def.handleEvent,null,[n,t,e,l])}function Ki(n,t){if(128&n.state)throw ur(Wi[zi]);return Qi(n,Ji(n,0)),n.def.updateDirectives(function(n,e,l){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];var i=n.def.nodes[e];return 0===t?Yi(n,i,l,r):Xi(n,i,l,r),16384&i.flags&&Qi(n,Ji(n,e)),224&i.flags?er(n,i.nodeIndex).value:void 0},n)}function Zi(n,t){if(128&n.state)throw ur(Wi[zi]);return Qi(n,nu(n,0)),n.def.updateRenderer(function(n,e,l){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];var i=n.def.nodes[e];return 0===t?Yi(n,i,l,r):Xi(n,i,l,r),3&i.flags&&Qi(n,nu(n,e)),224&i.flags?er(n,i.nodeIndex).value:void 0},n)}function Yi(n,t,e,l){if(di.apply(void 0,c([n,t,e],l))){var r=1===e?l[0]:l;if(16384&t.flags){for(var o={},i=0;i<t.bindings.length;i++){var u=t.bindings[i],a=r[i];8&u.flags&&(o[(d=u.nonMinifiedName,"ng-reflect-"+d.replace(/[$@]/g,"_").replace(Kn,function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return"-"+n[1].toLowerCase()}))]=Zn(a))}var s=t.parent,p=nr(n,s.nodeIndex).renderElement;if(s.element.name)for(var h in o)null!=(a=o[h])?n.renderer.setAttribute(p,h,a):n.renderer.removeAttribute(p,h);else n.renderer.setValue(p,"bindings="+JSON.stringify(o,null,2))}}var d}function Xi(n,t,e,l){gi.apply(void 0,c([n,t,e],l))}function Ji(n,t){for(var e=t;e<n.def.nodes.length;e++){var l=n.def.nodes[e];if(16384&l.flags&&l.bindings&&l.bindings.length)return e}return null}function nu(n,t){for(var e=t;e<n.def.nodes.length;e++){var l=n.def.nodes[e];if(3&l.flags&&l.bindings&&l.bindings.length)return e}return null}var tu=function(){function n(n,t){this.view=n,this.nodeIndex=t,null==t&&(this.nodeIndex=t=0),this.nodeDef=n.def.nodes[t];for(var e=this.nodeDef,l=n;e&&0==(1&e.flags);)e=e.parent;if(!e)for(;!e&&l;)e=Cr(l),l=l.parent;this.elDef=e,this.elView=l}return Object.defineProperty(n.prototype,"elOrCompView",{get:function(){return nr(this.elView,this.elDef.nodeIndex).componentView||this.view},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"injector",{get:function(){return mo(this.elView,this.elDef)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"component",{get:function(){return this.elOrCompView.component},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"context",{get:function(){return this.elOrCompView.context},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"providerTokens",{get:function(){var n=[];if(this.elDef)for(var t=this.elDef.nodeIndex+1;t<=this.elDef.nodeIndex+this.elDef.childCount;t++){var e=this.elView.def.nodes[t];20224&e.flags&&n.push(e.provider.token),t+=e.childCount}return n},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"references",{get:function(){var n={};if(this.elDef){eu(this.elView,this.elDef,n);for(var t=this.elDef.nodeIndex+1;t<=this.elDef.nodeIndex+this.elDef.childCount;t++){var e=this.elView.def.nodes[t];20224&e.flags&&eu(this.elView,e,n),t+=e.childCount}}return n},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"componentRenderElement",{get:function(){var n=function(n){for(;n&&!Er(n);)n=n.parent;return n.parent?nr(n.parent,Cr(n).nodeIndex):null}(this.elOrCompView);return n?n.renderElement:void 0},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"renderNode",{get:function(){return 2&this.nodeDef.flags?Sr(this.view,this.nodeDef):Sr(this.elView,this.elDef)},enumerable:!0,configurable:!0}),n.prototype.logError=function(n){for(var t,e,l=[],r=1;r<arguments.length;r++)l[r-1]=arguments[r];2&this.nodeDef.flags?(t=this.view.def,e=this.nodeDef.nodeIndex):(t=this.elView.def,e=this.elDef.nodeIndex);var o=function(n,t){for(var e=-1,l=0;l<=t;l++)3&n.nodes[l].flags&&e++;return e}(t,e),i=-1;t.factory(function(){var t;return++i===o?(t=n.error).bind.apply(t,c([n],l)):ar}),i<o&&(n.error("Illegal state: the ViewDefinitionFactory did not call the logger!"),n.error.apply(n,c(l)))},n}();function eu(n,t,e){for(var l in t.references)e[l]=Zo(n,t,t.references[l])}function lu(n,t,e,l){var r=zi,o=qi,i=Gi;try{zi=n;var u=t.apply(e,l);return qi=o,Gi=i,zi=r,u}catch(a){if(we(a)||!qi)throw a;throw function(n,t){return n instanceof Error||(n=new Error(n.toString())),ir(n,t),n}(a,ru())}}function ru(){return qi?new tu(qi,Gi):null}var ou=function(){function n(n){this.delegate=n}return n.prototype.createRenderer=function(n,t){return new iu(this.delegate.createRenderer(n,t))},n.prototype.begin=function(){this.delegate.begin&&this.delegate.begin()},n.prototype.end=function(){this.delegate.end&&this.delegate.end()},n.prototype.whenRenderingDone=function(){return this.delegate.whenRenderingDone?this.delegate.whenRenderingDone():Promise.resolve(null)},n}(),iu=function(){function n(n){this.delegate=n,this.debugContextFactory=ru,this.data=this.delegate.data}return n.prototype.createDebugContext=function(n){return this.debugContextFactory(n)},n.prototype.destroyNode=function(n){!function(n){Tl.delete(n.nativeNode)}(Il(n)),this.delegate.destroyNode&&this.delegate.destroyNode(n)},n.prototype.destroy=function(){this.delegate.destroy()},n.prototype.createElement=function(n,t){var e=this.delegate.createElement(n,t),l=this.createDebugContext(e);if(l){var r=new Pl(e,null,l);r.name=n,Ol(r)}return e},n.prototype.createComment=function(n){var t=this.delegate.createComment(n),e=this.createDebugContext(t);return e&&Ol(new xl(t,null,e)),t},n.prototype.createText=function(n){var t=this.delegate.createText(n),e=this.createDebugContext(t);return e&&Ol(new xl(t,null,e)),t},n.prototype.appendChild=function(n,t){var e=Il(n),l=Il(t);e&&l&&e instanceof Pl&&e.addChild(l),this.delegate.appendChild(n,t)},n.prototype.insertBefore=function(n,t,e){var l=Il(n),r=Il(t),o=Il(e);l&&r&&l instanceof Pl&&l.insertBefore(o,r),this.delegate.insertBefore(n,t,e)},n.prototype.removeChild=function(n,t){var e=Il(n),l=Il(t);e&&l&&e instanceof Pl&&e.removeChild(l),this.delegate.removeChild(n,t)},n.prototype.selectRootElement=function(n,t){var e=this.delegate.selectRootElement(n,t),l=ru();return l&&Ol(new Pl(e,null,l)),e},n.prototype.setAttribute=function(n,t,e,l){var r=Il(n);r&&r instanceof Pl&&(r.attributes[l?l+":"+t:t]=e),this.delegate.setAttribute(n,t,e,l)},n.prototype.removeAttribute=function(n,t,e){var l=Il(n);l&&l instanceof Pl&&(l.attributes[e?e+":"+t:t]=null),this.delegate.removeAttribute(n,t,e)},n.prototype.addClass=function(n,t){var e=Il(n);e&&e instanceof Pl&&(e.classes[t]=!0),this.delegate.addClass(n,t)},n.prototype.removeClass=function(n,t){var e=Il(n);e&&e instanceof Pl&&(e.classes[t]=!1),this.delegate.removeClass(n,t)},n.prototype.setStyle=function(n,t,e,l){var r=Il(n);r&&r instanceof Pl&&(r.styles[t]=e),this.delegate.setStyle(n,t,e,l)},n.prototype.removeStyle=function(n,t,e){var l=Il(n);l&&l instanceof Pl&&(l.styles[t]=null),this.delegate.removeStyle(n,t,e)},n.prototype.setProperty=function(n,t,e){var l=Il(n);l&&l instanceof Pl&&(l.properties[t]=e),this.delegate.setProperty(n,t,e)},n.prototype.listen=function(n,t,e){if("string"!=typeof n){var l=Il(n);l&&l.listeners.push(new El(t,e))}return this.delegate.listen(n,t,e)},n.prototype.parentNode=function(n){return this.delegate.parentNode(n)},n.prototype.nextSibling=function(n){return this.delegate.nextSibling(n)},n.prototype.setValue=function(n,t){return this.delegate.setValue(n,t)},n}();function uu(n,t,e){return new au(n,t,e)}var au=function(n){function t(t,e,l){var r=n.call(this)||this;return r.moduleType=t,r._bootstrapComponents=e,r._ngModuleDefFactory=l,r}return r(t,n),t.prototype.create=function(n){!function(){if(!Ei){Ei=!0;var n=qt()?{setCurrentNode:Qi,createRootView:Pi,createEmbeddedView:Ii,createComponentView:Oi,createNgModuleRef:ki,overrideProvider:Mi,overrideComponentView:Ni,clearOverrides:Li,checkAndUpdateView:Fi,checkNoChangesView:Bi,destroyView:Hi,createDebugContext:function(n,t){return new tu(n,t)},handleEvent:$i,updateDirectives:Ki,updateRenderer:Zi}:{setCurrentNode:function(){},createRootView:xi,createEmbeddedView:oi,createComponentView:ui,createNgModuleRef:wo,overrideProvider:ar,overrideComponentView:ar,clearOverrides:ar,checkAndUpdateView:hi,checkNoChangesView:pi,destroyView:yi,createDebugContext:function(n,t){return new tu(n,t)},handleEvent:function(n,t,e,l){return n.def.handleEvent(n,t,e,l)},updateDirectives:function(n,t){return n.def.updateDirectives(0===t?Ui:ji,n)},updateRenderer:function(n,t){return n.def.updateRenderer(0===t?Ui:ji,n)}};rr.setCurrentNode=n.setCurrentNode,rr.createRootView=n.createRootView,rr.createEmbeddedView=n.createEmbeddedView,rr.createComponentView=n.createComponentView,rr.createNgModuleRef=n.createNgModuleRef,rr.overrideProvider=n.overrideProvider,rr.overrideComponentView=n.overrideComponentView,rr.clearOverrides=n.clearOverrides,rr.checkAndUpdateView=n.checkAndUpdateView,rr.checkNoChangesView=n.checkNoChangesView,rr.destroyView=n.destroyView,rr.resolveDep=Bo,rr.createDebugContext=n.createDebugContext,rr.handleEvent=n.handleEvent,rr.updateDirectives=n.updateDirectives,rr.updateRenderer=n.updateRenderer,rr.dirtyParentQueries=Qo}}();var t=function(n){var t=Array.from(n.providers),e=Array.from(n.modules),l={};for(var r in n.providersByKey)l[r]=n.providersByKey[r];return{factory:n.factory,isRoot:n.isRoot,providers:t,modules:e,providersByKey:l}}(kr(this._ngModuleDefFactory));return rr.createNgModuleRef(this.moduleType,n||ut.NULL,this._bootstrapComponents,t)},t}(Dt),su=function(){return function(){}}(),cu=new R(function(n){return n.complete()});function pu(n){return n?function(n){return new R(function(t){return n.schedule(function(){return t.complete()})})}(n):cu}function hu(n){var t=new R(function(t){t.next(n),t.complete()});return t._isScalar=!0,t.value=n,t}function du(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=n[n.length-1];switch(B(e)?n.pop():e=void 0,n.length){case 0:return pu(e);case 1:return e?ln(n,e):hu(n[0]);default:return ln(n,e)}}function fu(n,t){return on(n,t,1)}function gu(n,t){return function(e){return e.lift(new mu(n,t))}}var mu=function(){function n(n,t){this.predicate=n,this.thisArg=t}return n.prototype.call=function(n,t){return t.subscribe(new yu(n,this.predicate,this.thisArg))},n}(),yu=function(n){function t(t,e,l){var r=n.call(this,t)||this;return r.predicate=e,r.thisArg=l,r.count=0,r}return r(t,n),t.prototype._next=function(n){var t;try{t=this.predicate.call(this.thisArg,n,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(n)},t}(T),vu=function(){return function(){}}(),_u=new Sn("Location Initialized"),bu=function(){return function(){}}(),wu=new Sn("appBaseHref"),Cu=function(){function n(n){var e=this;this._subject=new he,this._platformStrategy=n;var l=this._platformStrategy.getBaseHref();this._baseHref=t.stripTrailingSlash(Su(l)),this._platformStrategy.onPopState(function(n){e._subject.emit({url:e.path(!0),pop:!0,state:n.state,type:n.type})})}var t;return t=n,n.prototype.path=function(n){return void 0===n&&(n=!1),this.normalize(this._platformStrategy.path(n))},n.prototype.isCurrentPathEqualTo=function(n,e){return void 0===e&&(e=""),this.path()==this.normalize(n+t.normalizeQueryParams(e))},n.prototype.normalize=function(n){return t.stripTrailingSlash(function(n,t){return n&&t.startsWith(n)?t.substring(n.length):t}(this._baseHref,Su(n)))},n.prototype.prepareExternalUrl=function(n){return n&&"/"!==n[0]&&(n="/"+n),this._platformStrategy.prepareExternalUrl(n)},n.prototype.go=function(n,t,e){void 0===t&&(t=""),void 0===e&&(e=null),this._platformStrategy.pushState(e,"",n,t)},n.prototype.replaceState=function(n,t,e){void 0===t&&(t=""),void 0===e&&(e=null),this._platformStrategy.replaceState(e,"",n,t)},n.prototype.forward=function(){this._platformStrategy.forward()},n.prototype.back=function(){this._platformStrategy.back()},n.prototype.subscribe=function(n,t,e){return this._subject.subscribe({next:n,error:t,complete:e})},n.normalizeQueryParams=function(n){return n&&"?"!==n[0]?"?"+n:n},n.joinWithSlash=function(n,t){if(0==n.length)return t;if(0==t.length)return n;var e=0;return n.endsWith("/")&&e++,t.startsWith("/")&&e++,2==e?n+t.substring(1):1==e?n+t:n+"/"+t},n.stripTrailingSlash=function(n){var t=n.match(/#|\?|$/),e=t&&t.index||n.length;return n.slice(0,e-("/"===n[e-1]?1:0))+n.slice(e)},n}();function Su(n){return n.replace(/\/index.html$/,"")}var Eu=function(n){function t(t,e){var l=n.call(this)||this;return l._platformLocation=t,l._baseHref="",null!=e&&(l._baseHref=e),l}return r(t,n),t.prototype.onPopState=function(n){this._platformLocation.onPopState(n),this._platformLocation.onHashChange(n)},t.prototype.getBaseHref=function(){return this._baseHref},t.prototype.path=function(n){void 0===n&&(n=!1);var t=this._platformLocation.hash;return null==t&&(t="#"),t.length>0?t.substring(1):t},t.prototype.prepareExternalUrl=function(n){var t=Cu.joinWithSlash(this._baseHref,n);return t.length>0?"#"+t:t},t.prototype.pushState=function(n,t,e,l){var r=this.prepareExternalUrl(e+Cu.normalizeQueryParams(l));0==r.length&&(r=this._platformLocation.pathname),this._platformLocation.pushState(n,t,r)},t.prototype.replaceState=function(n,t,e,l){var r=this.prepareExternalUrl(e+Cu.normalizeQueryParams(l));0==r.length&&(r=this._platformLocation.pathname),this._platformLocation.replaceState(n,t,r)},t.prototype.forward=function(){this._platformLocation.forward()},t.prototype.back=function(){this._platformLocation.back()},t}(bu),xu=function(n){function t(t,e){var l=n.call(this)||this;if(l._platformLocation=t,null==e&&(e=l._platformLocation.getBaseHrefFromDOM()),null==e)throw new Error("No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.");return l._baseHref=e,l}return r(t,n),t.prototype.onPopState=function(n){this._platformLocation.onPopState(n),this._platformLocation.onHashChange(n)},t.prototype.getBaseHref=function(){return this._baseHref},t.prototype.prepareExternalUrl=function(n){return Cu.joinWithSlash(this._baseHref,n)},t.prototype.path=function(n){void 0===n&&(n=!1);var t=this._platformLocation.pathname+Cu.normalizeQueryParams(this._platformLocation.search),e=this._platformLocation.hash;return e&&n?""+t+e:t},t.prototype.pushState=function(n,t,e,l){var r=this.prepareExternalUrl(e+Cu.normalizeQueryParams(l));this._platformLocation.pushState(n,t,r)},t.prototype.replaceState=function(n,t,e,l){var r=this.prepareExternalUrl(e+Cu.normalizeQueryParams(l));this._platformLocation.replaceState(n,t,r)},t.prototype.forward=function(){this._platformLocation.forward()},t.prototype.back=function(){this._platformLocation.back()},t}(bu),Pu=void 0,Tu=["en",[["a","p"],["AM","PM"],Pu],[["AM","PM"],Pu,Pu],[["S","M","T","W","T","F","S"],["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],["Su","Mo","Tu","We","Th","Fr","Sa"]],Pu,[["J","F","M","A","M","J","J","A","S","O","N","D"],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],["January","February","March","April","May","June","July","August","September","October","November","December"]],Pu,[["B","A"],["BC","AD"],["Before Christ","Anno Domini"]],0,[6,0],["M/d/yy","MMM d, y","MMMM d, y","EEEE, MMMM d, y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1}, {0}",Pu,"{1} 'at' {0}",Pu],[".",",",";","%","+","-","E","\xd7","\u2030","\u221e","NaN",":"],["#,##0.###","#,##0%","\xa4#,##0.00","#E0"],"$","US Dollar",{},function(n){var t=Math.floor(Math.abs(n)),e=n.toString().replace(/^[^.]*\.?/,"").length;return 1===t&&0===e?1:5}],Iu={},Ou=function(n){return n[n.Zero=0]="Zero",n[n.One=1]="One",n[n.Two=2]="Two",n[n.Few=3]="Few",n[n.Many=4]="Many",n[n.Other=5]="Other",n}({}),ku=new Sn("UseV4Plurals"),Du=function(){return function(){}}(),Au=function(n){function t(t,e){var l=n.call(this)||this;return l.locale=t,l.deprecatedPluralFn=e,l}return r(t,n),t.prototype.getPluralCategory=function(n,t){switch(this.deprecatedPluralFn?this.deprecatedPluralFn(t||this.locale,n):function(n){return function(n){var t=n.toLowerCase().replace(/_/g,"-"),e=Iu[t];if(e)return e;var l=t.split("-")[0];if(e=Iu[l])return e;if("en"===l)return Tu;throw new Error('Missing locale data for the locale "'+n+'".')}(n)[18]}(t||this.locale)(n)){case Ou.Zero:return"zero";case Ou.One:return"one";case Ou.Two:return"two";case Ou.Few:return"few";case Ou.Many:return"many";default:return"other"}},t}(Du);function Ru(n,t){var e,l;t=encodeURIComponent(t);try{for(var r=a(n.split(";")),o=r.next();!o.done;o=r.next()){var i=o.value,u=i.indexOf("="),c=s(-1==u?[i,""]:[i.slice(0,u),i.slice(u+1)],2),p=c[1];if(c[0].trim()===t)return decodeURIComponent(p)}}catch(h){e={error:h}}finally{try{o&&!o.done&&(l=r.return)&&l.call(r)}finally{if(e)throw e.error}}return null}var Mu=function(){function n(n,t,e,l){this.$implicit=n,this.ngForOf=t,this.index=e,this.count=l}return Object.defineProperty(n.prototype,"first",{get:function(){return 0===this.index},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"last",{get:function(){return this.index===this.count-1},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"even",{get:function(){return this.index%2==0},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"odd",{get:function(){return!this.even},enumerable:!0,configurable:!0}),n}(),Nu=function(){function n(n,t,e){this._viewContainer=n,this._template=t,this._differs=e,this._ngForOfDirty=!0,this._differ=null}return Object.defineProperty(n.prototype,"ngForOf",{set:function(n){this._ngForOf=n,this._ngForOfDirty=!0},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngForTrackBy",{get:function(){return this._trackByFn},set:function(n){qt()&&null!=n&&"function"!=typeof n&&console&&console.warn&&console.warn("trackBy must be a function, but received "+JSON.stringify(n)+". See https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html#!#change-propagation for more information."),this._trackByFn=n},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngForTemplate",{set:function(n){n&&(this._template=n)},enumerable:!0,configurable:!0}),n.prototype.ngDoCheck=function(){if(this._ngForOfDirty){this._ngForOfDirty=!1;var n=this._ngForOf;if(!this._differ&&n)try{this._differ=this._differs.find(n).create(this.ngForTrackBy)}catch(l){throw new Error("Cannot find a differ supporting object '"+n+"' of type '"+((t=n).name||typeof t)+"'. NgFor only supports binding to Iterables such as Arrays.")}}var t;if(this._differ){var e=this._differ.diff(this._ngForOf);e&&this._applyChanges(e)}},n.prototype._applyChanges=function(n){var t=this,e=[];n.forEachOperation(function(n,l,r){if(null==n.previousIndex){var o=t._viewContainer.createEmbeddedView(t._template,new Mu(null,t._ngForOf,-1,-1),r),i=new Lu(n,o);e.push(i)}else null==r?t._viewContainer.remove(l):(o=t._viewContainer.get(l),t._viewContainer.move(o,r),i=new Lu(n,o),e.push(i))});for(var l=0;l<e.length;l++)this._perViewChange(e[l].view,e[l].record);l=0;for(var r=this._viewContainer.length;l<r;l++){var o=this._viewContainer.get(l);o.context.index=l,o.context.count=r,o.context.ngForOf=this._ngForOf}n.forEachIdentityChange(function(n){t._viewContainer.get(n.currentIndex).context.$implicit=n.item})},n.prototype._perViewChange=function(n,t){n.context.$implicit=t.item},n.ngTemplateContextGuard=function(n,t){return!0},n}(),Lu=function(){return function(n,t){this.record=n,this.view=t}}(),Vu=function(){function n(n,t){this._viewContainer=n,this._context=new Uu,this._thenTemplateRef=null,this._elseTemplateRef=null,this._thenViewRef=null,this._elseViewRef=null,this._thenTemplateRef=t}return Object.defineProperty(n.prototype,"ngIf",{set:function(n){this._context.$implicit=this._context.ngIf=n,this._updateView()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngIfThen",{set:function(n){ju("ngIfThen",n),this._thenTemplateRef=n,this._thenViewRef=null,this._updateView()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngIfElse",{set:function(n){ju("ngIfElse",n),this._elseTemplateRef=n,this._elseViewRef=null,this._updateView()},enumerable:!0,configurable:!0}),n.prototype._updateView=function(){this._context.$implicit?this._thenViewRef||(this._viewContainer.clear(),this._elseViewRef=null,this._thenTemplateRef&&(this._thenViewRef=this._viewContainer.createEmbeddedView(this._thenTemplateRef,this._context))):this._elseViewRef||(this._viewContainer.clear(),this._thenViewRef=null,this._elseTemplateRef&&(this._elseViewRef=this._viewContainer.createEmbeddedView(this._elseTemplateRef,this._context)))},n.ngTemplateGuard_ngIf=function(n,t){return!0},n}(),Uu=function(){return function(){this.$implicit=null,this.ngIf=null}}();function ju(n,t){if(t&&!t.createEmbeddedView)throw new Error(n+" must be a TemplateRef, but received '"+Nn(t)+"'.")}var Fu=function(){return function(){}}(),Bu=new Sn("DocumentToken"),Hu="browser",zu="server";function qu(n){return n===Hu}function Gu(n){return n===zu}var Wu=function(){function n(){}return n.ngInjectableDef=wn({providedIn:"root",factory:function(){return new Qu($n(Bu),window,$n(Ee))}}),n}(),Qu=function(){function n(n,t,e){this.document=n,this.window=t,this.errorHandler=e,this.offset=function(){return[0,0]}}return n.prototype.setOffset=function(n){this.offset=Array.isArray(n)?function(){return n}:n},n.prototype.getScrollPosition=function(){return this.supportScrollRestoration()?[this.window.scrollX,this.window.scrollY]:[0,0]},n.prototype.scrollToPosition=function(n){this.supportScrollRestoration()&&this.window.scrollTo(n[0],n[1])},n.prototype.scrollToAnchor=function(n){if(this.supportScrollRestoration()){n=this.window.CSS&&this.window.CSS.escape?this.window.CSS.escape(n):n.replace(/(\"|\'\ |:|\.|\[|\]|,|=)/g,"\\$1");try{var t=this.document.querySelector("#"+n);if(t)return void this.scrollToElement(t);var e=this.document.querySelector("[name='"+n+"']");if(e)return void this.scrollToElement(e)}catch(l){this.errorHandler.handleError(l)}}},n.prototype.setHistoryScrollRestoration=function(n){if(this.supportScrollRestoration()){var t=this.window.history;t&&t.scrollRestoration&&(t.scrollRestoration=n)}},n.prototype.scrollToElement=function(n){var t=n.getBoundingClientRect(),e=t.left+this.window.pageXOffset,l=t.top+this.window.pageYOffset,r=this.offset();this.window.scrollTo(e-r[0],l-r[1])},n.prototype.supportScrollRestoration=function(){try{return!!this.window&&!!this.window.scrollTo}catch(n){return!1}},n}(),$u=function(){return function(){}}(),Ku=function(){return function(){}}(),Zu=function(){function n(n){var t=this;this.normalizedNames=new Map,this.lazyUpdate=null,n?this.lazyInit="string"==typeof n?function(){t.headers=new Map,n.split("\n").forEach(function(n){var e=n.indexOf(":");if(e>0){var l=n.slice(0,e),r=l.toLowerCase(),o=n.slice(e+1).trim();t.maybeSetNormalizedName(l,r),t.headers.has(r)?t.headers.get(r).push(o):t.headers.set(r,[o])}})}:function(){t.headers=new Map,Object.keys(n).forEach(function(e){var l=n[e],r=e.toLowerCase();"string"==typeof l&&(l=[l]),l.length>0&&(t.headers.set(r,l),t.maybeSetNormalizedName(e,r))})}:this.headers=new Map}return n.prototype.has=function(n){return this.init(),this.headers.has(n.toLowerCase())},n.prototype.get=function(n){this.init();var t=this.headers.get(n.toLowerCase());return t&&t.length>0?t[0]:null},n.prototype.keys=function(){return this.init(),Array.from(this.normalizedNames.values())},n.prototype.getAll=function(n){return this.init(),this.headers.get(n.toLowerCase())||null},n.prototype.append=function(n,t){return this.clone({name:n,value:t,op:"a"})},n.prototype.set=function(n,t){return this.clone({name:n,value:t,op:"s"})},n.prototype.delete=function(n,t){return this.clone({name:n,value:t,op:"d"})},n.prototype.maybeSetNormalizedName=function(n,t){this.normalizedNames.has(t)||this.normalizedNames.set(t,n)},n.prototype.init=function(){var t=this;this.lazyInit&&(this.lazyInit instanceof n?this.copyFrom(this.lazyInit):this.lazyInit(),this.lazyInit=null,this.lazyUpdate&&(this.lazyUpdate.forEach(function(n){return t.applyUpdate(n)}),this.lazyUpdate=null))},n.prototype.copyFrom=function(n){var t=this;n.init(),Array.from(n.headers.keys()).forEach(function(e){t.headers.set(e,n.headers.get(e)),t.normalizedNames.set(e,n.normalizedNames.get(e))})},n.prototype.clone=function(t){var e=new n;return e.lazyInit=this.lazyInit&&this.lazyInit instanceof n?this.lazyInit:this,e.lazyUpdate=(this.lazyUpdate||[]).concat([t]),e},n.prototype.applyUpdate=function(n){var t=n.name.toLowerCase();switch(n.op){case"a":case"s":var e=n.value;if("string"==typeof e&&(e=[e]),0===e.length)return;this.maybeSetNormalizedName(n.name,t);var l=("a"===n.op?this.headers.get(t):void 0)||[];l.push.apply(l,c(e)),this.headers.set(t,l);break;case"d":var r=n.value;if(r){var o=this.headers.get(t);if(!o)return;0===(o=o.filter(function(n){return-1===r.indexOf(n)})).length?(this.headers.delete(t),this.normalizedNames.delete(t)):this.headers.set(t,o)}else this.headers.delete(t),this.normalizedNames.delete(t)}},n.prototype.forEach=function(n){var t=this;this.init(),Array.from(this.normalizedNames.keys()).forEach(function(e){return n(t.normalizedNames.get(e),t.headers.get(e))})},n}(),Yu=function(){function n(){}return n.prototype.encodeKey=function(n){return Xu(n)},n.prototype.encodeValue=function(n){return Xu(n)},n.prototype.decodeKey=function(n){return decodeURIComponent(n)},n.prototype.decodeValue=function(n){return decodeURIComponent(n)},n}();function Xu(n){return encodeURIComponent(n).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/gi,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%2B/gi,"+").replace(/%3D/gi,"=").replace(/%3F/gi,"?").replace(/%2F/gi,"/")}var Ju=function(){function n(n){void 0===n&&(n={});var t,e,l,r=this;if(this.updates=null,this.cloneFrom=null,this.encoder=n.encoder||new Yu,n.fromString){if(n.fromObject)throw new Error("Cannot specify both fromString and fromObject.");this.map=(t=n.fromString,e=this.encoder,l=new Map,t.length>0&&t.split("&").forEach(function(n){var t=n.indexOf("="),r=s(-1==t?[e.decodeKey(n),""]:[e.decodeKey(n.slice(0,t)),e.decodeValue(n.slice(t+1))],2),o=r[0],i=r[1],u=l.get(o)||[];u.push(i),l.set(o,u)}),l)}else n.fromObject?(this.map=new Map,Object.keys(n.fromObject).forEach(function(t){var e=n.fromObject[t];r.map.set(t,Array.isArray(e)?e:[e])})):this.map=null}return n.prototype.has=function(n){return this.init(),this.map.has(n)},n.prototype.get=function(n){this.init();var t=this.map.get(n);return t?t[0]:null},n.prototype.getAll=function(n){return this.init(),this.map.get(n)||null},n.prototype.keys=function(){return this.init(),Array.from(this.map.keys())},n.prototype.append=function(n,t){return this.clone({param:n,value:t,op:"a"})},n.prototype.set=function(n,t){return this.clone({param:n,value:t,op:"s"})},n.prototype.delete=function(n,t){return this.clone({param:n,value:t,op:"d"})},n.prototype.toString=function(){var n=this;return this.init(),this.keys().map(function(t){var e=n.encoder.encodeKey(t);return n.map.get(t).map(function(t){return e+"="+n.encoder.encodeValue(t)}).join("&")}).join("&")},n.prototype.clone=function(t){var e=new n({encoder:this.encoder});return e.cloneFrom=this.cloneFrom||this,e.updates=(this.updates||[]).concat([t]),e},n.prototype.init=function(){var n=this;null===this.map&&(this.map=new Map),null!==this.cloneFrom&&(this.cloneFrom.init(),this.cloneFrom.keys().forEach(function(t){return n.map.set(t,n.cloneFrom.map.get(t))}),this.updates.forEach(function(t){switch(t.op){case"a":case"s":var e=("a"===t.op?n.map.get(t.param):void 0)||[];e.push(t.value),n.map.set(t.param,e);break;case"d":if(void 0===t.value){n.map.delete(t.param);break}var l=n.map.get(t.param)||[],r=l.indexOf(t.value);-1!==r&&l.splice(r,1),l.length>0?n.map.set(t.param,l):n.map.delete(t.param)}}),this.cloneFrom=this.updates=null)},n}();function na(n){return"undefined"!=typeof ArrayBuffer&&n instanceof ArrayBuffer}function ta(n){return"undefined"!=typeof Blob&&n instanceof Blob}function ea(n){return"undefined"!=typeof FormData&&n instanceof FormData}var la=function(){function n(n,t,e,l){var r;if(this.url=t,this.body=null,this.reportProgress=!1,this.withCredentials=!1,this.responseType="json",this.method=n.toUpperCase(),function(n){switch(n){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"JSONP":return!1;default:return!0}}(this.method)||l?(this.body=void 0!==e?e:null,r=l):r=e,r&&(this.reportProgress=!!r.reportProgress,this.withCredentials=!!r.withCredentials,r.responseType&&(this.responseType=r.responseType),r.headers&&(this.headers=r.headers),r.params&&(this.params=r.params)),this.headers||(this.headers=new Zu),this.params){var o=this.params.toString();if(0===o.length)this.urlWithParams=t;else{var i=t.indexOf("?");this.urlWithParams=t+(-1===i?"?":i<t.length-1?"&":"")+o}}else this.params=new Ju,this.urlWithParams=t}return n.prototype.serializeBody=function(){return null===this.body?null:na(this.body)||ta(this.body)||ea(this.body)||"string"==typeof this.body?this.body:this.body instanceof Ju?this.body.toString():"object"==typeof this.body||"boolean"==typeof this.body||Array.isArray(this.body)?JSON.stringify(this.body):this.body.toString()},n.prototype.detectContentTypeHeader=function(){return null===this.body?null:ea(this.body)?null:ta(this.body)?this.body.type||null:na(this.body)?null:"string"==typeof this.body?"text/plain":this.body instanceof Ju?"application/x-www-form-urlencoded;charset=UTF-8":"object"==typeof this.body||"number"==typeof this.body||Array.isArray(this.body)?"application/json":null},n.prototype.clone=function(t){void 0===t&&(t={});var e=t.method||this.method,l=t.url||this.url,r=t.responseType||this.responseType,o=void 0!==t.body?t.body:this.body,i=void 0!==t.withCredentials?t.withCredentials:this.withCredentials,u=void 0!==t.reportProgress?t.reportProgress:this.reportProgress,a=t.headers||this.headers,s=t.params||this.params;return void 0!==t.setHeaders&&(a=Object.keys(t.setHeaders).reduce(function(n,e){return n.set(e,t.setHeaders[e])},a)),t.setParams&&(s=Object.keys(t.setParams).reduce(function(n,e){return n.set(e,t.setParams[e])},s)),new n(e,l,o,{params:s,headers:a,reportProgress:u,responseType:r,withCredentials:i})},n}(),ra=function(n){return n[n.Sent=0]="Sent",n[n.UploadProgress=1]="UploadProgress",n[n.ResponseHeader=2]="ResponseHeader",n[n.DownloadProgress=3]="DownloadProgress",n[n.Response=4]="Response",n[n.User=5]="User",n}({}),oa=function(){return function(n,t,e){void 0===t&&(t=200),void 0===e&&(e="OK"),this.headers=n.headers||new Zu,this.status=void 0!==n.status?n.status:t,this.statusText=n.statusText||e,this.url=n.url||null,this.ok=this.status>=200&&this.status<300}}(),ia=function(n){function t(t){void 0===t&&(t={});var e=n.call(this,t)||this;return e.type=ra.ResponseHeader,e}return r(t,n),t.prototype.clone=function(n){return void 0===n&&(n={}),new t({headers:n.headers||this.headers,status:void 0!==n.status?n.status:this.status,statusText:n.statusText||this.statusText,url:n.url||this.url||void 0})},t}(oa),ua=function(n){function t(t){void 0===t&&(t={});var e=n.call(this,t)||this;return e.type=ra.Response,e.body=void 0!==t.body?t.body:null,e}return r(t,n),t.prototype.clone=function(n){return void 0===n&&(n={}),new t({body:void 0!==n.body?n.body:this.body,headers:n.headers||this.headers,status:void 0!==n.status?n.status:this.status,statusText:n.statusText||this.statusText,url:n.url||this.url||void 0})},t}(oa),aa=function(n){function t(t){var e=n.call(this,t,0,"Unknown Error")||this;return e.name="HttpErrorResponse",e.ok=!1,e.message=e.status>=200&&e.status<300?"Http failure during parsing for "+(t.url||"(unknown url)"):"Http failure response for "+(t.url||"(unknown url)")+": "+t.status+" "+t.statusText,e.error=t.error||null,e}return r(t,n),t}(oa);function sa(n,t){return{body:t,headers:n.headers,observe:n.observe,params:n.params,reportProgress:n.reportProgress,responseType:n.responseType,withCredentials:n.withCredentials}}var ca=function(){function n(n){this.handler=n}return n.prototype.request=function(n,t,e){var l,r=this;if(void 0===e&&(e={}),n instanceof la)l=n;else{var o;o=e.headers instanceof Zu?e.headers:new Zu(e.headers);var i=void 0;e.params&&(i=e.params instanceof Ju?e.params:new Ju({fromObject:e.params})),l=new la(n,t,void 0!==e.body?e.body:null,{headers:o,params:i,reportProgress:e.reportProgress,responseType:e.responseType||"json",withCredentials:e.withCredentials})}var u=du(l).pipe(fu(function(n){return r.handler.handle(n)}));if(n instanceof la||"events"===e.observe)return u;var a=u.pipe(gu(function(n){return n instanceof ua}));switch(e.observe||"body"){case"body":switch(l.responseType){case"arraybuffer":return a.pipe(nn(function(n){if(null!==n.body&&!(n.body instanceof ArrayBuffer))throw new Error("Response is not an ArrayBuffer.");return n.body}));case"blob":return a.pipe(nn(function(n){if(null!==n.body&&!(n.body instanceof Blob))throw new Error("Response is not a Blob.");return n.body}));case"text":return a.pipe(nn(function(n){if(null!==n.body&&"string"!=typeof n.body)throw new Error("Response is not a string.");return n.body}));case"json":default:return a.pipe(nn(function(n){return n.body}))}case"response":return a;default:throw new Error("Unreachable: unhandled observe type "+e.observe+"}")}},n.prototype.delete=function(n,t){return void 0===t&&(t={}),this.request("DELETE",n,t)},n.prototype.get=function(n,t){return void 0===t&&(t={}),this.request("GET",n,t)},n.prototype.head=function(n,t){return void 0===t&&(t={}),this.request("HEAD",n,t)},n.prototype.jsonp=function(n,t){return this.request("JSONP",n,{params:(new Ju).append(t,"JSONP_CALLBACK"),observe:"body",responseType:"json"})},n.prototype.options=function(n,t){return void 0===t&&(t={}),this.request("OPTIONS",n,t)},n.prototype.patch=function(n,t,e){return void 0===e&&(e={}),this.request("PATCH",n,sa(e,t))},n.prototype.post=function(n,t,e){return void 0===e&&(e={}),this.request("POST",n,sa(e,t))},n.prototype.put=function(n,t,e){return void 0===e&&(e={}),this.request("PUT",n,sa(e,t))},n}(),pa=function(){function n(n,t){this.next=n,this.interceptor=t}return n.prototype.handle=function(n){return this.interceptor.intercept(n,this.next)},n}(),ha=new Sn("HTTP_INTERCEPTORS"),da=function(){function n(){}return n.prototype.intercept=function(n,t){return t.handle(n)},n}(),fa=/^\)\]\}',?\n/,ga=function(){return function(){}}(),ma=function(){function n(){}return n.prototype.build=function(){return new XMLHttpRequest},n}(),ya=function(){function n(n){this.xhrFactory=n}return n.prototype.handle=function(n){var t=this;if("JSONP"===n.method)throw new Error("Attempted to construct Jsonp request without JsonpClientModule installed.");return new R(function(e){var l=t.xhrFactory.build();if(l.open(n.method,n.urlWithParams),n.withCredentials&&(l.withCredentials=!0),n.headers.forEach(function(n,t){return l.setRequestHeader(n,t.join(","))}),n.headers.has("Accept")||l.setRequestHeader("Accept","application/json, text/plain, */*"),!n.headers.has("Content-Type")){var r=n.detectContentTypeHeader();null!==r&&l.setRequestHeader("Content-Type",r)}if(n.responseType){var o=n.responseType.toLowerCase();l.responseType="json"!==o?o:"text"}var i=n.serializeBody(),u=null,a=function(){if(null!==u)return u;var t=1223===l.status?204:l.status,e=l.statusText||"OK",r=new Zu(l.getAllResponseHeaders()),o=function(n){return"responseURL"in n&&n.responseURL?n.responseURL:/^X-Request-URL:/m.test(n.getAllResponseHeaders())?n.getResponseHeader("X-Request-URL"):null}(l)||n.url;return u=new ia({headers:r,status:t,statusText:e,url:o})},s=function(){var t=a(),r=t.headers,o=t.status,i=t.statusText,u=t.url,s=null;204!==o&&(s=void 0===l.response?l.responseText:l.response),0===o&&(o=s?200:0);var c=o>=200&&o<300;if("json"===n.responseType&&"string"==typeof s){var p=s;s=s.replace(fa,"");try{s=""!==s?JSON.parse(s):null}catch(h){s=p,c&&(c=!1,s={error:h,text:s})}}c?(e.next(new ua({body:s,headers:r,status:o,statusText:i,url:u||void 0})),e.complete()):e.error(new aa({error:s,headers:r,status:o,statusText:i,url:u||void 0}))},c=function(n){var t=a().url,r=new aa({error:n,status:l.status||0,statusText:l.statusText||"Unknown Error",url:t||void 0});e.error(r)},p=!1,h=function(t){p||(e.next(a()),p=!0);var r={type:ra.DownloadProgress,loaded:t.loaded};t.lengthComputable&&(r.total=t.total),"text"===n.responseType&&l.responseText&&(r.partialText=l.responseText),e.next(r)},d=function(n){var t={type:ra.UploadProgress,loaded:n.loaded};n.lengthComputable&&(t.total=n.total),e.next(t)};return l.addEventListener("load",s),l.addEventListener("error",c),n.reportProgress&&(l.addEventListener("progress",h),null!==i&&l.upload&&l.upload.addEventListener("progress",d)),l.send(i),e.next({type:ra.Sent}),function(){l.removeEventListener("error",c),l.removeEventListener("load",s),n.reportProgress&&(l.removeEventListener("progress",h),null!==i&&l.upload&&l.upload.removeEventListener("progress",d)),l.abort()}})},n}(),va=new Sn("XSRF_COOKIE_NAME"),_a=new Sn("XSRF_HEADER_NAME"),ba=function(){return function(){}}(),wa=function(){function n(n,t,e){this.doc=n,this.platform=t,this.cookieName=e,this.lastCookieString="",this.lastToken=null,this.parseCount=0}return n.prototype.getToken=function(){if("server"===this.platform)return null;var n=this.doc.cookie||"";return n!==this.lastCookieString&&(this.parseCount++,this.lastToken=Ru(n,this.cookieName),this.lastCookieString=n),this.lastToken},n}(),Ca=function(){function n(n,t){this.tokenService=n,this.headerName=t}return n.prototype.intercept=function(n,t){var e=n.url.toLowerCase();if("GET"===n.method||"HEAD"===n.method||e.startsWith("http://")||e.startsWith("https://"))return t.handle(n);var l=this.tokenService.getToken();return null===l||n.headers.has(this.headerName)||(n=n.clone({headers:n.headers.set(this.headerName,l)})),t.handle(n)},n}(),Sa=function(){function n(n,t){this.backend=n,this.injector=t,this.chain=null}return n.prototype.handle=function(n){if(null===this.chain){var t=this.injector.get(ha,[]);this.chain=t.reduceRight(function(n,t){return new pa(n,t)},this.backend)}return this.chain.handle(n)},n}(),Ea=function(){function n(){}var t;return t=n,n.disable=function(){return{ngModule:t,providers:[{provide:Ca,useClass:da}]}},n.withOptions=function(n){return void 0===n&&(n={}),{ngModule:t,providers:[n.cookieName?{provide:va,useValue:n.cookieName}:[],n.headerName?{provide:_a,useValue:n.headerName}:[]]}},n}(),xa=function(){return function(){}}();function Pa(n,t){return"function"==typeof t?function(e){return e.pipe(Pa(function(e,l){return rn(n(e,l)).pipe(nn(function(n,r){return t(e,n,l,r)}))}))}:function(t){return t.lift(new Ta(n))}}var Ta=function(){function n(n){this.project=n}return n.prototype.call=function(n,t){return t.subscribe(new Ia(n,this.project))},n}(),Ia=function(n){function t(t,e){var l=n.call(this,t)||this;return l.project=e,l.index=0,l}return r(t,n),t.prototype._next=function(n){var t,e=this.index++;try{t=this.project(n,e)}catch(l){return void this.destination.error(l)}this._innerSub(t,n,e)},t.prototype._innerSub=function(n,t,e){var l=this.innerSubscription;l&&l.unsubscribe();var r=new H(this,void 0,void 0);this.destination.add(r),this.innerSubscription=X(this,n,t,e,r)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||n.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=null},t.prototype.notifyComplete=function(t){this.destination.remove(t),this.innerSubscription=null,this.isStopped&&n.prototype._complete.call(this)},t.prototype.notifyNext=function(n,t,e,l,r){this.destination.next(t)},t}(J),Oa={headers:new Zu({"Content-Type":"application/json","Access-Control-Allow-Origin":"*"})},ka=function(){function n(n){this.http=n,this.apiGatewayUrlUser="http://localhost:9091",this.apiGatewayUrlFinancialplan="http://localhost:9092",this.webSericeURL="http://localhost:9090"}return n.prototype.ngOnInit=function(){console.log("CommonAppService ngOnInit 1.1: "),this.initApiGatewayURL(),console.log("CommonAppService ngOnInit 2.2: ")},n.prototype.initApiGatewayURL=function(){var n=this;return console.log("CommonAppService loadApiGatewayURL 1: "),this.fetchApiGatewayURL().pipe(nn(function(t){console.log("CommonAppService loadApiGatewayURL 2: "+n.apiGatewayUrlUser),n.apiGatewayUrlUser=t.url,console.log("CommonAppService loadApiGatewayURL 3: "+n.apiGatewayUrlUser)}))},n.prototype.getCusCus=function(){var n=this;return console.log("CommonAppService ----\x3e getCusCus 1 : "+this.apiGatewayUrlUser),this.initApiGatewayURL().pipe(Pa(function(t){return console.log("CommonAppService ----\x3e getCusCus 2 : "+n.apiGatewayUrlUser),console.log("CommonAppService ----\x3e getCusCus 2: Before callling : "+n.apiGatewayUrlUser+"/user/api/customer"),n.http.get(n.apiGatewayUrlUser+"/user/api/customer",Oa).pipe(nn(n.extractData))}))},n.prototype.fetchApiGatewayURL=function(){return console.log("fetchApiGatewayURL : webSericeURL URL : "+this.webSericeURL),this.http.get(this.webSericeURL+"/api/apiServiceURL")},n.prototype.getApiGatewayUrlUser=function(){return console.log("getApiGatewayUrlUser URL 1: "+this.apiGatewayUrlUser),"1111"==this.apiGatewayUrlUser&&(console.log("getApiGatewayUrlUser URL : before initApiGatewayURL"),this.initApiGatewayURL(),console.log("apiGatewayUrlUser URL : after initApiGatewayURL"),console.log("apiGatewayUrlUser URL 2: "+this.apiGatewayUrlUser)),console.log("apiGatewayUrlUser URL 3: "+this.apiGatewayUrlUser),this.apiGatewayUrlUser},n.prototype.getApiGatewayUrlFinancialplan=function(){return console.log("getApiGatewayUrlFinancialplan URL 1: "+this.apiGatewayUrlFinancialplan),this.apiGatewayUrlFinancialplan},n.prototype.getHttpHeaders=function(){return Oa},n.prototype.extractData=function(n){return n||{}},n.prototype.handleError=function(n,t){return void 0===n&&(n="operation"),function(e){return console.error(e),console.log(n+" failed: "+e.message),du(t)}},n.ngInjectableDef=wn({factory:function(){return new n($n(ca))},token:n,providedIn:"root"}),n}(),Da=function(n){function t(t){var e=n.call(this,t)||this;return e.http=t,e}return r(t,n),t.prototype.populateUserInfo=function(n){console.log("populateUserInfo 1 ..."),"user1"===n?(console.log("populateUserInfo 2 ..."),sessionStorage.setItem("username",n),sessionStorage.setItem("roles","businessmanager")):"user2"===n?(console.log("populateUserInfo 3 ..."),sessionStorage.setItem("username",n),sessionStorage.setItem("roles","wealthmanager")):"user3"===n?(console.log("populateUserInfo 4 ..."),sessionStorage.setItem("username",n),sessionStorage.setItem("roles","customer")):"[email protected]"===n?(console.log("populateUserInfo 5 ..."),sessionStorage.setItem("username",n),sessionStorage.setItem("roles","customer")):(console.log("populateUserInfo 6 ..."),sessionStorage.setItem("username",n),sessionStorage.setItem("roles","customer")),console.log("populateUserInfo 7 ...")},t.prototype.loginBasicAuth=function(n){return this.populateUserInfo(n),!0},t.prototype.login=function(){var n=this;return console.log("login 1: 1"),this.doLogin().subscribe(function(t){console.log("login 2: "+t),n.fetchLoggedInUser().subscribe(function(t){console.log("login 3: "+t),n.populateUserInfo(t.name),console.log("login 4: "+t.name)})})},t.prototype.doLogin=function(){return console.log("doLogin ..."),this.http.get(this.getLoginURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.fetchLoggedInUser=function(){return console.log("fetchLoggedInUser ..."),this.http.get(this.getLoggedInUserURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.isUserLoggedIn=function(){var n=sessionStorage.getItem("username");return console.log(!(null===n)),!(null===n)},t.prototype.logOut=function(){console.log("AuthenticationService logOut 1"),sessionStorage.removeItem("username")},t.prototype.getLoginURL=function(){return this.webSericeURL+"/login"},t.prototype.getLoggedInUserURL=function(){return this.webSericeURL+"/userName"},t.prototype.getLogoutURL=function(){return this.webSericeURL+"/logout"},t.ngInjectableDef=wn({factory:function(){return new t($n(ca))},token:t,providedIn:"root"}),t}(ka),Aa=function(){function n(n,t,e){this.authService=n,this.route=t,this.router=e,this.title="product-ui",this.invalidLogin=!1}return n.prototype.gotoLogout=function(){this.authService.logOut(),this.router.navigate(["home"])},n.prototype.gotoLogin=function(){this.authService.login()},n.prototype.loadAfterLogin=function(){var n=sessionStorage.getItem("roles");console.log("Role : "+n),"businessmanager"===n?this.router.navigate(["businessmanager"]):"wealthmanager"===n?this.router.navigate(["wealthmanager"]):"customer"===n?this.router.navigate(["customer"]):this.invalidLogin=!0},n.prototype.checkLogin=function(){this.authService.login()?(this.invalidLogin=!1,this.loadAfterLogin()):this.invalidLogin=!0},n}(),Ra=function(n){function t(t){var e=n.call(this)||this;return e._value=t,e}return r(t,n),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),t.prototype._subscribe=function(t){var e=n.prototype._subscribe.call(this,t);return e&&!e.closed&&t.next(this._value),e},t.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new L;return this._value},t.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},t}(j);function Ma(){return Error.call(this),this.message="no elements in sequence",this.name="EmptyError",this}Ma.prototype=Object.create(Error.prototype);var Na=Ma,La={},Va=function(){function n(n){this.resultSelector=n}return n.prototype.call=function(n,t){return t.subscribe(new Ua(n,this.resultSelector))},n}(),Ua=function(n){function t(t,e){var l=n.call(this,t)||this;return l.resultSelector=e,l.active=0,l.values=[],l.observables=[],l}return r(t,n),t.prototype._next=function(n){this.values.push(La),this.observables.push(n)},t.prototype._complete=function(){var n=this.observables,t=n.length;if(0===t)this.destination.complete();else{this.active=t,this.toRespond=t;for(var e=0;e<t;e++){var l=n[e];this.add(X(this,l,l,e))}}},t.prototype.notifyComplete=function(n){0==(this.active-=1)&&this.destination.complete()},t.prototype.notifyNext=function(n,t,e,l,r){var o=this.values,i=this.toRespond?o[e]===La?--this.toRespond:this.toRespond:0;o[e]=t,0===i&&(this.resultSelector?this._tryResultSelector(o):this.destination.next(o.slice()))},t.prototype._tryResultSelector=function(n){var t;try{t=this.resultSelector.apply(this,n)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(J);function ja(n){return new R(function(t){var e;try{e=n()}catch(l){return void t.error(l)}return(e?rn(e):pu()).subscribe(t)})}function Fa(){return cn(1)}function Ba(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}Ba.prototype=Object.create(Error.prototype);var Ha=Ba;function za(n){return function(t){return 0===n?pu():t.lift(new qa(n))}}var qa=function(){function n(n){if(this.total=n,this.total<0)throw new Ha}return n.prototype.call=function(n,t){return t.subscribe(new Ga(n,this.total))},n}(),Ga=function(n){function t(t,e){var l=n.call(this,t)||this;return l.total=e,l.ring=new Array,l.count=0,l}return r(t,n),t.prototype._next=function(n){var t=this.ring,e=this.total,l=this.count++;t.length<e?t.push(n):t[l%e]=n},t.prototype._complete=function(){var n=this.destination,t=this.count;if(t>0)for(var e=this.count>=this.total?this.total:this.count,l=this.ring,r=0;r<e;r++){var o=t++%e;n.next(l[o])}n.complete()},t}(T);function Wa(n,t,e){return function(l){return l.lift(new Qa(n,t,e))}}var Qa=function(){function n(n,t,e){this.nextOrObserver=n,this.error=t,this.complete=e}return n.prototype.call=function(n,t){return t.subscribe(new $a(n,this.nextOrObserver,this.error,this.complete))},n}(),$a=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;return o._tapNext=k,o._tapError=k,o._tapComplete=k,o._tapError=l||k,o._tapComplete=r||k,d(e)?(o._context=o,o._tapNext=e):e&&(o._context=e,o._tapNext=e.next||k,o._tapError=e.error||k,o._tapComplete=e.complete||k),o}return r(t,n),t.prototype._next=function(n){try{this._tapNext.call(this._context,n)}catch(t){return void this.destination.error(t)}this.destination.next(n)},t.prototype._error=function(n){try{this._tapError.call(this._context,n)}catch(n){return void this.destination.error(n)}this.destination.error(n)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(n){return void this.destination.error(n)}return this.destination.complete()},t}(T),Ka=function(n){return void 0===n&&(n=Za),Wa({hasValue:!1,next:function(){this.hasValue=!0},complete:function(){if(!this.hasValue)throw n()}})};function Za(){return new Na}function Ya(n){return void 0===n&&(n=null),function(t){return t.lift(new Xa(n))}}var Xa=function(){function n(n){this.defaultValue=n}return n.prototype.call=function(n,t){return t.subscribe(new Ja(n,this.defaultValue))},n}(),Ja=function(n){function t(t,e){var l=n.call(this,t)||this;return l.defaultValue=e,l.isEmpty=!0,l}return r(t,n),t.prototype._next=function(n){this.isEmpty=!1,this.destination.next(n)},t.prototype._complete=function(){this.isEmpty&&this.destination.next(this.defaultValue),this.destination.complete()},t}(T);function ns(n,t){var e=arguments.length>=2;return function(l){return l.pipe(n?gu(function(t,e){return n(t,e,l)}):sn,za(1),e?Ya(t):Ka(function(){return new Na}))}}function ts(n){return function(t){var e=new es(n),l=t.lift(e);return e.caught=l}}var es=function(){function n(n){this.selector=n}return n.prototype.call=function(n,t){return t.subscribe(new ls(n,this.selector,this.caught))},n}(),ls=function(n){function t(t,e,l){var r=n.call(this,t)||this;return r.selector=e,r.caught=l,r}return r(t,n),t.prototype.error=function(t){if(!this.isStopped){var e=void 0;try{e=this.selector(t,this.caught)}catch(r){return void n.prototype.error.call(this,r)}this._unsubscribeAndRecycle();var l=new H(this,void 0,void 0);this.add(l),X(this,e,void 0,void 0,l)}},t}(J);function rs(n){return function(t){return 0===n?pu():t.lift(new os(n))}}var os=function(){function n(n){if(this.total=n,this.total<0)throw new Ha}return n.prototype.call=function(n,t){return t.subscribe(new is(n,this.total))},n}(),is=function(n){function t(t,e){var l=n.call(this,t)||this;return l.total=e,l.count=0,l}return r(t,n),t.prototype._next=function(n){var t=this.total,e=++this.count;e<=t&&(this.destination.next(n),e===t&&(this.destination.complete(),this.unsubscribe()))},t}(T);function us(n,t){var e=arguments.length>=2;return function(l){return l.pipe(n?gu(function(t,e){return n(t,e,l)}):sn,rs(1),e?Ya(t):Ka(function(){return new Na}))}}var as=function(){function n(n,t,e){this.predicate=n,this.thisArg=t,this.source=e}return n.prototype.call=function(n,t){return t.subscribe(new ss(n,this.predicate,this.thisArg,this.source))},n}(),ss=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;return o.predicate=e,o.thisArg=l,o.source=r,o.index=0,o.thisArg=l||o,o}return r(t,n),t.prototype.notifyComplete=function(n){this.destination.next(n),this.destination.complete()},t.prototype._next=function(n){var t=!1;try{t=this.predicate.call(this.thisArg,n,this.index++,this.source)}catch(e){return void this.destination.error(e)}t||this.notifyComplete(!1)},t.prototype._complete=function(){this.notifyComplete(!0)},t}(T);function cs(n,t){var e=!1;return arguments.length>=2&&(e=!0),function(l){return l.lift(new ps(n,t,e))}}var ps=function(){function n(n,t,e){void 0===e&&(e=!1),this.accumulator=n,this.seed=t,this.hasSeed=e}return n.prototype.call=function(n,t){return t.subscribe(new hs(n,this.accumulator,this.seed,this.hasSeed))},n}(),hs=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;return o.accumulator=e,o._seed=l,o.hasSeed=r,o.index=0,o}return r(t,n),Object.defineProperty(t.prototype,"seed",{get:function(){return this._seed},set:function(n){this.hasSeed=!0,this._seed=n},enumerable:!0,configurable:!0}),t.prototype._next=function(n){if(this.hasSeed)return this._tryNext(n);this.seed=n,this.destination.next(n)},t.prototype._tryNext=function(n){var t,e=this.index++;try{t=this.accumulator(this.seed,n,e)}catch(l){this.destination.error(l)}this.seed=t,this.destination.next(t)},t}(T),ds=function(){function n(n){this.callback=n}return n.prototype.call=function(n,t){return t.subscribe(new fs(n,this.callback))},n}(),fs=function(n){function t(t,e){var l=n.call(this,t)||this;return l.add(new b(e)),l}return r(t,n),t}(T),gs=null;function ms(){return gs}var ys,vs={class:"className",innerHtml:"innerHTML",readonly:"readOnly",tabindex:"tabIndex"},_s={"\b":"Backspace","\t":"Tab","\x7f":"Delete","\x1b":"Escape",Del:"Delete",Esc:"Escape",Left:"ArrowLeft",Right:"ArrowRight",Up:"ArrowUp",Down:"ArrowDown",Menu:"ContextMenu",Scroll:"ScrollLock",Win:"OS"},bs={A:"1",B:"2",C:"3",D:"4",E:"5",F:"6",G:"7",H:"8",I:"9",J:"*",K:"+",M:"-",N:".",O:"/","`":"0","\x90":"NumLock"};On.Node&&(ys=On.Node.prototype.contains||function(n){return!!(16&this.compareDocumentPosition(n))});var ws,Cs=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.parse=function(n){throw new Error("parse not implemented")},t.makeCurrent=function(){var n;n=new t,gs||(gs=n)},t.prototype.hasProperty=function(n,t){return t in n},t.prototype.setProperty=function(n,t,e){n[t]=e},t.prototype.getProperty=function(n,t){return n[t]},t.prototype.invoke=function(n,t,e){var l;(l=n)[t].apply(l,c(e))},t.prototype.logError=function(n){window.console&&(console.error?console.error(n):console.log(n))},t.prototype.log=function(n){window.console&&window.console.log&&window.console.log(n)},t.prototype.logGroup=function(n){window.console&&window.console.group&&window.console.group(n)},t.prototype.logGroupEnd=function(){window.console&&window.console.groupEnd&&window.console.groupEnd()},Object.defineProperty(t.prototype,"attrToPropMap",{get:function(){return vs},enumerable:!0,configurable:!0}),t.prototype.contains=function(n,t){return ys.call(n,t)},t.prototype.querySelector=function(n,t){return n.querySelector(t)},t.prototype.querySelectorAll=function(n,t){return n.querySelectorAll(t)},t.prototype.on=function(n,t,e){n.addEventListener(t,e,!1)},t.prototype.onAndCancel=function(n,t,e){return n.addEventListener(t,e,!1),function(){n.removeEventListener(t,e,!1)}},t.prototype.dispatchEvent=function(n,t){n.dispatchEvent(t)},t.prototype.createMouseEvent=function(n){var t=this.getDefaultDocument().createEvent("MouseEvent");return t.initEvent(n,!0,!0),t},t.prototype.createEvent=function(n){var t=this.getDefaultDocument().createEvent("Event");return t.initEvent(n,!0,!0),t},t.prototype.preventDefault=function(n){n.preventDefault(),n.returnValue=!1},t.prototype.isPrevented=function(n){return n.defaultPrevented||null!=n.returnValue&&!n.returnValue},t.prototype.getInnerHTML=function(n){return n.innerHTML},t.prototype.getTemplateContent=function(n){return"content"in n&&this.isTemplateElement(n)?n.content:null},t.prototype.getOuterHTML=function(n){return n.outerHTML},t.prototype.nodeName=function(n){return n.nodeName},t.prototype.nodeValue=function(n){return n.nodeValue},t.prototype.type=function(n){return n.type},t.prototype.content=function(n){return this.hasProperty(n,"content")?n.content:n},t.prototype.firstChild=function(n){return n.firstChild},t.prototype.nextSibling=function(n){return n.nextSibling},t.prototype.parentElement=function(n){return n.parentNode},t.prototype.childNodes=function(n){return n.childNodes},t.prototype.childNodesAsList=function(n){for(var t=n.childNodes,e=new Array(t.length),l=0;l<t.length;l++)e[l]=t[l];return e},t.prototype.clearNodes=function(n){for(;n.firstChild;)n.removeChild(n.firstChild)},t.prototype.appendChild=function(n,t){n.appendChild(t)},t.prototype.removeChild=function(n,t){n.removeChild(t)},t.prototype.replaceChild=function(n,t,e){n.replaceChild(t,e)},t.prototype.remove=function(n){return n.parentNode&&n.parentNode.removeChild(n),n},t.prototype.insertBefore=function(n,t,e){n.insertBefore(e,t)},t.prototype.insertAllBefore=function(n,t,e){e.forEach(function(e){return n.insertBefore(e,t)})},t.prototype.insertAfter=function(n,t,e){n.insertBefore(e,t.nextSibling)},t.prototype.setInnerHTML=function(n,t){n.innerHTML=t},t.prototype.getText=function(n){return n.textContent},t.prototype.setText=function(n,t){n.textContent=t},t.prototype.getValue=function(n){return n.value},t.prototype.setValue=function(n,t){n.value=t},t.prototype.getChecked=function(n){return n.checked},t.prototype.setChecked=function(n,t){n.checked=t},t.prototype.createComment=function(n){return this.getDefaultDocument().createComment(n)},t.prototype.createTemplate=function(n){var t=this.getDefaultDocument().createElement("template");return t.innerHTML=n,t},t.prototype.createElement=function(n,t){return(t=t||this.getDefaultDocument()).createElement(n)},t.prototype.createElementNS=function(n,t,e){return(e=e||this.getDefaultDocument()).createElementNS(n,t)},t.prototype.createTextNode=function(n,t){return(t=t||this.getDefaultDocument()).createTextNode(n)},t.prototype.createScriptTag=function(n,t,e){var l=(e=e||this.getDefaultDocument()).createElement("SCRIPT");return l.setAttribute(n,t),l},t.prototype.createStyleElement=function(n,t){var e=(t=t||this.getDefaultDocument()).createElement("style");return this.appendChild(e,this.createTextNode(n,t)),e},t.prototype.createShadowRoot=function(n){return n.createShadowRoot()},t.prototype.getShadowRoot=function(n){return n.shadowRoot},t.prototype.getHost=function(n){return n.host},t.prototype.clone=function(n){return n.cloneNode(!0)},t.prototype.getElementsByClassName=function(n,t){return n.getElementsByClassName(t)},t.prototype.getElementsByTagName=function(n,t){return n.getElementsByTagName(t)},t.prototype.classList=function(n){return Array.prototype.slice.call(n.classList,0)},t.prototype.addClass=function(n,t){n.classList.add(t)},t.prototype.removeClass=function(n,t){n.classList.remove(t)},t.prototype.hasClass=function(n,t){return n.classList.contains(t)},t.prototype.setStyle=function(n,t,e){n.style[t]=e},t.prototype.removeStyle=function(n,t){n.style[t]=""},t.prototype.getStyle=function(n,t){return n.style[t]},t.prototype.hasStyle=function(n,t,e){var l=this.getStyle(n,t)||"";return e?l==e:l.length>0},t.prototype.tagName=function(n){return n.tagName},t.prototype.attributeMap=function(n){for(var t=new Map,e=n.attributes,l=0;l<e.length;l++){var r=e.item(l);t.set(r.name,r.value)}return t},t.prototype.hasAttribute=function(n,t){return n.hasAttribute(t)},t.prototype.hasAttributeNS=function(n,t,e){return n.hasAttributeNS(t,e)},t.prototype.getAttribute=function(n,t){return n.getAttribute(t)},t.prototype.getAttributeNS=function(n,t,e){return n.getAttributeNS(t,e)},t.prototype.setAttribute=function(n,t,e){n.setAttribute(t,e)},t.prototype.setAttributeNS=function(n,t,e,l){n.setAttributeNS(t,e,l)},t.prototype.removeAttribute=function(n,t){n.removeAttribute(t)},t.prototype.removeAttributeNS=function(n,t,e){n.removeAttributeNS(t,e)},t.prototype.templateAwareRoot=function(n){return this.isTemplateElement(n)?this.content(n):n},t.prototype.createHtmlDocument=function(){return document.implementation.createHTMLDocument("fakeTitle")},t.prototype.getDefaultDocument=function(){return document},t.prototype.getBoundingClientRect=function(n){try{return n.getBoundingClientRect()}catch(t){return{top:0,bottom:0,left:0,right:0,width:0,height:0}}},t.prototype.getTitle=function(n){return n.title},t.prototype.setTitle=function(n,t){n.title=t||""},t.prototype.elementMatches=function(n,t){return!!this.isElementNode(n)&&(n.matches&&n.matches(t)||n.msMatchesSelector&&n.msMatchesSelector(t)||n.webkitMatchesSelector&&n.webkitMatchesSelector(t))},t.prototype.isTemplateElement=function(n){return this.isElementNode(n)&&"TEMPLATE"===n.nodeName},t.prototype.isTextNode=function(n){return n.nodeType===Node.TEXT_NODE},t.prototype.isCommentNode=function(n){return n.nodeType===Node.COMMENT_NODE},t.prototype.isElementNode=function(n){return n.nodeType===Node.ELEMENT_NODE},t.prototype.hasShadowRoot=function(n){return null!=n.shadowRoot&&n instanceof HTMLElement},t.prototype.isShadowRoot=function(n){return n instanceof DocumentFragment},t.prototype.importIntoDoc=function(n){return document.importNode(this.templateAwareRoot(n),!0)},t.prototype.adoptNode=function(n){return document.adoptNode(n)},t.prototype.getHref=function(n){return n.getAttribute("href")},t.prototype.getEventKey=function(n){var t=n.key;if(null==t){if(null==(t=n.keyIdentifier))return"Unidentified";t.startsWith("U+")&&(t=String.fromCharCode(parseInt(t.substring(2),16)),3===n.location&&bs.hasOwnProperty(t)&&(t=bs[t]))}return _s[t]||t},t.prototype.getGlobalEventTarget=function(n,t){return"window"===t?window:"document"===t?n:"body"===t?n.body:null},t.prototype.getHistory=function(){return window.history},t.prototype.getLocation=function(){return window.location},t.prototype.getBaseHref=function(n){var t,e=Ss||(Ss=document.querySelector("base"))?Ss.getAttribute("href"):null;return null==e?null:(t=e,ws||(ws=document.createElement("a")),ws.setAttribute("href",t),"/"===ws.pathname.charAt(0)?ws.pathname:"/"+ws.pathname)},t.prototype.resetBaseElement=function(){Ss=null},t.prototype.getUserAgent=function(){return window.navigator.userAgent},t.prototype.setData=function(n,t,e){this.setAttribute(n,"data-"+t,e)},t.prototype.getData=function(n,t){return this.getAttribute(n,"data-"+t)},t.prototype.getComputedStyle=function(n){return getComputedStyle(n)},t.prototype.supportsWebAnimation=function(){return"function"==typeof Element.prototype.animate},t.prototype.performanceNow=function(){return window.performance&&window.performance.now?window.performance.now():(new Date).getTime()},t.prototype.supportsCookies=function(){return!0},t.prototype.getCookie=function(n){return Ru(document.cookie,n)},t.prototype.setCookie=function(n,t){document.cookie=encodeURIComponent(n)+"="+encodeURIComponent(t)},t}(function(n){function t(){var t=n.call(this)||this;t._animationPrefix=null,t._transitionEnd=null;try{var e=t.createElement("div",document);if(null!=t.getStyle(e,"animationName"))t._animationPrefix="";else for(var l=["Webkit","Moz","O","ms"],r=0;r<l.length;r++)if(null!=t.getStyle(e,l[r]+"AnimationName")){t._animationPrefix="-"+l[r].toLowerCase()+"-";break}var o={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};Object.keys(o).forEach(function(n){null!=t.getStyle(e,n)&&(t._transitionEnd=o[n])})}catch(i){t._animationPrefix=null,t._transitionEnd=null}return t}return r(t,n),t.prototype.getDistributedNodes=function(n){return n.getDistributedNodes()},t.prototype.resolveAndSetHref=function(n,t,e){n.href=null==e?t:t+"/../"+e},t.prototype.supportsDOMEvents=function(){return!0},t.prototype.supportsNativeShadowDOM=function(){return"function"==typeof document.body.createShadowRoot},t.prototype.getAnimationPrefix=function(){return this._animationPrefix?this._animationPrefix:""},t.prototype.getTransitionEnd=function(){return this._transitionEnd?this._transitionEnd:""},t.prototype.supportsAnimation=function(){return null!=this._animationPrefix&&null!=this._transitionEnd},t}(function(){function n(){this.resourceLoaderType=null}return Object.defineProperty(n.prototype,"attrToPropMap",{get:function(){return this._attrToPropMap},set:function(n){this._attrToPropMap=n},enumerable:!0,configurable:!0}),n}())),Ss=null,Es=Bu;function xs(){return!!window.history.pushState}var Ps=function(n){function t(t){var e=n.call(this)||this;return e._doc=t,e._init(),e}var e;return r(t,n),t.prototype._init=function(){this.location=ms().getLocation(),this._history=ms().getHistory()},t.prototype.getBaseHrefFromDOM=function(){return ms().getBaseHref(this._doc)},t.prototype.onPopState=function(n){ms().getGlobalEventTarget(this._doc,"window").addEventListener("popstate",n,!1)},t.prototype.onHashChange=function(n){ms().getGlobalEventTarget(this._doc,"window").addEventListener("hashchange",n,!1)},Object.defineProperty(t.prototype,"pathname",{get:function(){return this.location.pathname},set:function(n){this.location.pathname=n},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"search",{get:function(){return this.location.search},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"hash",{get:function(){return this.location.hash},enumerable:!0,configurable:!0}),t.prototype.pushState=function(n,t,e){xs()?this._history.pushState(n,t,e):this.location.hash=e},t.prototype.replaceState=function(n,t,e){xs()?this._history.replaceState(n,t,e):this.location.hash=e},t.prototype.forward=function(){this._history.forward()},t.prototype.back=function(){this._history.back()},i([(e=Bn(Es),function(n,t){e(n,t,0)}),u("design:paramtypes",[Object])],t)}(vu),Ts=new Sn("TRANSITION_ID"),Is=[{provide:Te,useFactory:function(n,t,e){return function(){e.get(Ie).donePromise.then(function(){var e=ms();Array.prototype.slice.apply(e.querySelectorAll(t,"style[ng-transition]")).filter(function(t){return e.getAttribute(t,"ng-transition")===n}).forEach(function(n){return e.remove(n)})})}},deps:[Ts,Es,ut],multi:!0}],Os=function(){function n(){}return n.init=function(){var t;t=new n,il=t},n.prototype.addToWindow=function(n){On.getAngularTestability=function(t,e){void 0===e&&(e=!0);var l=n.findTestabilityInTree(t,e);if(null==l)throw new Error("Could not find testability for element.");return l},On.getAllAngularTestabilities=function(){return n.getAllTestabilities()},On.getAllAngularRootElements=function(){return n.getAllRootElements()},On.frameworkStabilizers||(On.frameworkStabilizers=[]),On.frameworkStabilizers.push(function(n){var t=On.getAllAngularTestabilities(),e=t.length,l=!1,r=function(t){l=l||t,0==--e&&n(l)};t.forEach(function(n){n.whenStable(r)})})},n.prototype.findTestabilityInTree=function(n,t,e){if(null==t)return null;var l=n.getTestability(t);return null!=l?l:e?ms().isShadowRoot(t)?this.findTestabilityInTree(n,ms().getHost(t),!0):this.findTestabilityInTree(n,ms().parentElement(t),!0):null},n}();function ks(n,t){"undefined"!=typeof COMPILED&&COMPILED||((On.ng=On.ng||{})[n]=t)}var Ds={ApplicationRef:dl,NgZone:Ze};function As(n){return Il(n)}var Rs=new Sn("EventManagerPlugins"),Ms=function(){function n(n,t){var e=this;this._zone=t,this._eventNameToPlugin=new Map,n.forEach(function(n){return n.manager=e}),this._plugins=n.slice().reverse()}return n.prototype.addEventListener=function(n,t,e){return this._findPluginFor(t).addEventListener(n,t,e)},n.prototype.addGlobalEventListener=function(n,t,e){return this._findPluginFor(t).addGlobalEventListener(n,t,e)},n.prototype.getZone=function(){return this._zone},n.prototype._findPluginFor=function(n){var t=this._eventNameToPlugin.get(n);if(t)return t;for(var e=this._plugins,l=0;l<e.length;l++){var r=e[l];if(r.supports(n))return this._eventNameToPlugin.set(n,r),r}throw new Error("No event manager plugin found for event "+n)},n}(),Ns=function(){function n(n){this._doc=n}return n.prototype.addGlobalEventListener=function(n,t,e){var l=ms().getGlobalEventTarget(this._doc,n);if(!l)throw new Error("Unsupported event target "+l+" for event "+t);return this.addEventListener(l,t,e)},n}(),Ls=function(){function n(){this._stylesSet=new Set}return n.prototype.addStyles=function(n){var t=this,e=new Set;n.forEach(function(n){t._stylesSet.has(n)||(t._stylesSet.add(n),e.add(n))}),this.onStylesAdded(e)},n.prototype.onStylesAdded=function(n){},n.prototype.getAllStyles=function(){return Array.from(this._stylesSet)},n}(),Vs=function(n){function t(t){var e=n.call(this)||this;return e._doc=t,e._hostNodes=new Set,e._styleNodes=new Set,e._hostNodes.add(t.head),e}return r(t,n),t.prototype._addStylesToHost=function(n,t){var e=this;n.forEach(function(n){var l=e._doc.createElement("style");l.textContent=n,e._styleNodes.add(t.appendChild(l))})},t.prototype.addHost=function(n){this._addStylesToHost(this._stylesSet,n),this._hostNodes.add(n)},t.prototype.removeHost=function(n){this._hostNodes.delete(n)},t.prototype.onStylesAdded=function(n){var t=this;this._hostNodes.forEach(function(e){return t._addStylesToHost(n,e)})},t.prototype.ngOnDestroy=function(){this._styleNodes.forEach(function(n){return ms().remove(n)})},t}(Ls),Us={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},js=/%COMP%/g,Fs="_nghost-%COMP%",Bs="_ngcontent-%COMP%";function Hs(n,t,e){for(var l=0;l<t.length;l++){var r=t[l];Array.isArray(r)?Hs(n,r,e):(r=r.replace(js,n),e.push(r))}return e}function zs(n){return function(t){!1===n(t)&&(t.preventDefault(),t.returnValue=!1)}}var qs=function(){function n(n,t,e){this.eventManager=n,this.sharedStylesHost=t,this.appId=e,this.rendererByCompId=new Map,this.defaultRenderer=new Gs(n)}return n.prototype.createRenderer=function(n,t){if(!n||!t)return this.defaultRenderer;switch(t.encapsulation){case Fn.Emulated:var e=this.rendererByCompId.get(t.id);return e||(e=new Ks(this.eventManager,this.sharedStylesHost,t,this.appId),this.rendererByCompId.set(t.id,e)),e.applyToHost(n),e;case Fn.Native:case Fn.ShadowDom:return new Zs(this.eventManager,this.sharedStylesHost,n,t);default:if(!this.rendererByCompId.has(t.id)){var l=Hs(t.id,t.styles,[]);this.sharedStylesHost.addStyles(l),this.rendererByCompId.set(t.id,this.defaultRenderer)}return this.defaultRenderer}},n.prototype.begin=function(){},n.prototype.end=function(){},n}(),Gs=function(){function n(n){this.eventManager=n,this.data=Object.create(null)}return n.prototype.destroy=function(){},n.prototype.createElement=function(n,t){return t?document.createElementNS(Us[t],n):document.createElement(n)},n.prototype.createComment=function(n){return document.createComment(n)},n.prototype.createText=function(n){return document.createTextNode(n)},n.prototype.appendChild=function(n,t){n.appendChild(t)},n.prototype.insertBefore=function(n,t,e){n&&n.insertBefore(t,e)},n.prototype.removeChild=function(n,t){n&&n.removeChild(t)},n.prototype.selectRootElement=function(n,t){var e="string"==typeof n?document.querySelector(n):n;if(!e)throw new Error('The selector "'+n+'" did not match any elements');return t||(e.textContent=""),e},n.prototype.parentNode=function(n){return n.parentNode},n.prototype.nextSibling=function(n){return n.nextSibling},n.prototype.setAttribute=function(n,t,e,l){if(l){t=l+":"+t;var r=Us[l];r?n.setAttributeNS(r,t,e):n.setAttribute(t,e)}else n.setAttribute(t,e)},n.prototype.removeAttribute=function(n,t,e){if(e){var l=Us[e];l?n.removeAttributeNS(l,t):n.removeAttribute(e+":"+t)}else n.removeAttribute(t)},n.prototype.addClass=function(n,t){n.classList.add(t)},n.prototype.removeClass=function(n,t){n.classList.remove(t)},n.prototype.setStyle=function(n,t,e,l){l&Lt.DashCase?n.style.setProperty(t,e,l&Lt.Important?"important":""):n.style[t]=e},n.prototype.removeStyle=function(n,t,e){e&Lt.DashCase?n.style.removeProperty(t):n.style[t]=""},n.prototype.setProperty=function(n,t,e){Qs(t,"property"),n[t]=e},n.prototype.setValue=function(n,t){n.nodeValue=t},n.prototype.listen=function(n,t,e){return Qs(t,"listener"),"string"==typeof n?this.eventManager.addGlobalEventListener(n,t,zs(e)):this.eventManager.addEventListener(n,t,zs(e))},n}(),Ws="@".charCodeAt(0);function Qs(n,t){if(n.charCodeAt(0)===Ws)throw new Error("Found the synthetic "+t+" "+n+'. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.')}var $s,Ks=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;o.component=l;var i=Hs(r+"-"+l.id,l.styles,[]);return e.addStyles(i),o.contentAttr=Bs.replace(js,r+"-"+l.id),o.hostAttr=Fs.replace(js,r+"-"+l.id),o}return r(t,n),t.prototype.applyToHost=function(t){n.prototype.setAttribute.call(this,t,this.hostAttr,"")},t.prototype.createElement=function(t,e){var l=n.prototype.createElement.call(this,t,e);return n.prototype.setAttribute.call(this,l,this.contentAttr,""),l},t}(Gs),Zs=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;o.sharedStylesHost=e,o.hostEl=l,o.component=r,o.shadowRoot=r.encapsulation===Fn.ShadowDom?l.attachShadow({mode:"open"}):l.createShadowRoot(),o.sharedStylesHost.addHost(o.shadowRoot);for(var i=Hs(r.id,r.styles,[]),u=0;u<i.length;u++){var a=document.createElement("style");a.textContent=i[u],o.shadowRoot.appendChild(a)}return o}return r(t,n),t.prototype.nodeOrShadowRoot=function(n){return n===this.hostEl?this.shadowRoot:n},t.prototype.destroy=function(){this.sharedStylesHost.removeHost(this.shadowRoot)},t.prototype.appendChild=function(t,e){return n.prototype.appendChild.call(this,this.nodeOrShadowRoot(t),e)},t.prototype.insertBefore=function(t,e,l){return n.prototype.insertBefore.call(this,this.nodeOrShadowRoot(t),e,l)},t.prototype.removeChild=function(t,e){return n.prototype.removeChild.call(this,this.nodeOrShadowRoot(t),e)},t.prototype.parentNode=function(t){return this.nodeOrShadowRoot(n.prototype.parentNode.call(this,this.nodeOrShadowRoot(t)))},t}(Gs),Ys="undefined"!=typeof Zone&&Zone.__symbol__||function(n){return"__zone_symbol__"+n},Xs=Ys("addEventListener"),Js=Ys("removeEventListener"),nc={},tc="__zone_symbol__propagationStopped";"undefined"!=typeof Zone&&Zone[Ys("BLACK_LISTED_EVENTS")]&&($s={});var ec=function(n){return!!$s&&$s.hasOwnProperty(n)},lc=function(n){var t=nc[n.type];if(t){var e=this[t];if(e){var l=[n];if(1===e.length)return(i=e[0]).zone!==Zone.current?i.zone.run(i.handler,this,l):i.handler.apply(this,l);for(var r=e.slice(),o=0;o<r.length&&!0!==n[tc];o++){var i;(i=r[o]).zone!==Zone.current?i.zone.run(i.handler,this,l):i.handler.apply(this,l)}}}},rc=function(n){function t(t,e,l){var r=n.call(this,t)||this;return r.ngZone=e,l&&Gu(l)||r.patchEvent(),r}return r(t,n),t.prototype.patchEvent=function(){if("undefined"!=typeof Event&&Event&&Event.prototype&&!Event.prototype.__zone_symbol__stopImmediatePropagation){var n=Event.prototype.__zone_symbol__stopImmediatePropagation=Event.prototype.stopImmediatePropagation;Event.prototype.stopImmediatePropagation=function(){this&&(this[tc]=!0),n&&n.apply(this,arguments)}}},t.prototype.supports=function(n){return!0},t.prototype.addEventListener=function(n,t,e){var l=this,r=e;if(!n[Xs]||Ze.isInAngularZone()&&!ec(t))n.addEventListener(t,r,!1);else{var o=nc[t];o||(o=nc[t]=Ys("ANGULAR"+t+"FALSE"));var i=n[o],u=i&&i.length>0;i||(i=n[o]=[]);var a=ec(t)?Zone.root:Zone.current;if(0===i.length)i.push({zone:a,handler:r});else{for(var s=!1,c=0;c<i.length;c++)if(i[c].handler===r){s=!0;break}s||i.push({zone:a,handler:r})}u||n[Xs](t,lc,!1)}return function(){return l.removeEventListener(n,t,r)}},t.prototype.removeEventListener=function(n,t,e){var l=n[Js];if(!l)return n.removeEventListener.apply(n,[t,e,!1]);var r=nc[t],o=r&&n[r];if(!o)return n.removeEventListener.apply(n,[t,e,!1]);for(var i=!1,u=0;u<o.length;u++)if(o[u].handler===e){i=!0,o.splice(u,1);break}i?0===o.length&&l.apply(n,[t,lc,!1]):n.removeEventListener.apply(n,[t,e,!1])},t}(Ns),oc={pan:!0,panstart:!0,panmove:!0,panend:!0,pancancel:!0,panleft:!0,panright:!0,panup:!0,pandown:!0,pinch:!0,pinchstart:!0,pinchmove:!0,pinchend:!0,pinchcancel:!0,pinchin:!0,pinchout:!0,press:!0,pressup:!0,rotate:!0,rotatestart:!0,rotatemove:!0,rotateend:!0,rotatecancel:!0,swipe:!0,swipeleft:!0,swiperight:!0,swipeup:!0,swipedown:!0,tap:!0},ic=new Sn("HammerGestureConfig"),uc=new Sn("HammerLoader"),ac=function(){function n(){this.events=[],this.overrides={}}return n.prototype.buildHammer=function(n){var t=new Hammer(n,this.options);for(var e in t.get("pinch").set({enable:!0}),t.get("rotate").set({enable:!0}),this.overrides)t.get(e).set(this.overrides[e]);return t},n}(),sc=function(n){function t(t,e,l,r){var o=n.call(this,t)||this;return o._config=e,o.console=l,o.loader=r,o}return r(t,n),t.prototype.supports=function(n){return!(!oc.hasOwnProperty(n.toLowerCase())&&!this.isCustomEvent(n)||!window.Hammer&&!this.loader&&(this.console.warn('The "'+n+'" event cannot be bound because Hammer.JS is not loaded and no custom loader has been specified.'),1))},t.prototype.addEventListener=function(n,t,e){var l=this,r=this.manager.getZone();if(t=t.toLowerCase(),!window.Hammer&&this.loader){var o=!1,i=function(){o=!0};return this.loader().then(function(){if(!window.Hammer)return l.console.warn("The custom HAMMER_LOADER completed, but Hammer.JS is not present."),void(i=function(){});o||(i=l.addEventListener(n,t,e))}).catch(function(){l.console.warn('The "'+t+'" event cannot be bound because the custom Hammer.JS loader failed.'),i=function(){}}),function(){i()}}return r.runOutsideAngular(function(){var o=l._config.buildHammer(n),i=function(n){r.runGuarded(function(){e(n)})};return o.on(t,i),function(){o.off(t,i),"function"==typeof o.destroy&&o.destroy()}})},t.prototype.isCustomEvent=function(n){return this._config.events.indexOf(n)>-1},t}(Ns),cc=["alt","control","meta","shift"],pc={alt:function(n){return n.altKey},control:function(n){return n.ctrlKey},meta:function(n){return n.metaKey},shift:function(n){return n.shiftKey}},hc=function(n){function t(t){return n.call(this,t)||this}var e;return r(t,n),e=t,t.prototype.supports=function(n){return null!=e.parseEventName(n)},t.prototype.addEventListener=function(n,t,l){var r=e.parseEventName(t),o=e.eventCallback(r.fullKey,l,this.manager.getZone());return this.manager.getZone().runOutsideAngular(function(){return ms().onAndCancel(n,r.domEventName,o)})},t.parseEventName=function(n){var t=n.toLowerCase().split("."),l=t.shift();if(0===t.length||"keydown"!==l&&"keyup"!==l)return null;var r=e._normalizeKey(t.pop()),o="";if(cc.forEach(function(n){var e=t.indexOf(n);e>-1&&(t.splice(e,1),o+=n+".")}),o+=r,0!=t.length||0===r.length)return null;var i={};return i.domEventName=l,i.fullKey=o,i},t.getEventFullKey=function(n){var t="",e=ms().getEventKey(n);return" "===(e=e.toLowerCase())?e="space":"."===e&&(e="dot"),cc.forEach(function(l){l!=e&&(0,pc[l])(n)&&(t+=l+".")}),t+=e},t.eventCallback=function(n,t,l){return function(r){e.getEventFullKey(r)===n&&l.runGuarded(function(){return t(r)})}},t._normalizeKey=function(n){switch(n){case"esc":return"escape";default:return n}},t}(Ns),dc=function(){return function(){}}(),fc=function(n){function t(t){var e=n.call(this)||this;return e._doc=t,e}return r(t,n),t.prototype.sanitize=function(n,t){if(null==t)return null;switch(n){case jt.NONE:return t;case jt.HTML:return t instanceof mc?t.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(t,"HTML"),function(n,t){var e=null;try{Yt=Yt||new Gt(n);var l=t?String(t):"";e=Yt.getInertBodyElement(l);var r=5,o=l;do{if(0===r)throw new Error("Failed to sanitize html because the input is unstable");r--,l=o,o=e.innerHTML,e=Yt.getInertBodyElement(l)}while(l!==o);var i=new ue,u=i.sanitizeChildren(pe(e)||e);return qt()&&i.sanitizedSomething&&console.warn("WARNING: sanitizing HTML stripped some content, see http://g.co/ng/security#xss"),u}finally{if(e)for(var a=pe(e)||e;a.firstChild;)a.removeChild(a.firstChild)}}(this._doc,String(t)));case jt.STYLE:return t instanceof yc?t.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(t,"Style"),function(n){if(!(n=String(n).trim()))return"";var t=n.match(me);return t&&$t(t[1])===t[1]||n.match(ge)&&function(n){for(var t=!0,e=!0,l=0;l<n.length;l++){var r=n.charAt(l);"'"===r&&e?t=!t:'"'===r&&t&&(e=!e)}return t&&e}(n)?n:(qt()&&console.warn("WARNING: sanitizing unsafe style value "+n+" (see http://g.co/ng/security#xss)."),"unsafe")}(t));case jt.SCRIPT:if(t instanceof vc)return t.changingThisBreaksApplicationSecurity;throw this.checkNotSafeValue(t,"Script"),new Error("unsafe value used in a script context");case jt.URL:return t instanceof bc||t instanceof _c?t.changingThisBreaksApplicationSecurity:(this.checkNotSafeValue(t,"URL"),$t(String(t)));case jt.RESOURCE_URL:if(t instanceof bc)return t.changingThisBreaksApplicationSecurity;throw this.checkNotSafeValue(t,"ResourceURL"),new Error("unsafe value used in a resource URL context (see http://g.co/ng/security#xss)");default:throw new Error("Unexpected SecurityContext "+n+" (see http://g.co/ng/security#xss)")}},t.prototype.checkNotSafeValue=function(n,t){if(n instanceof gc)throw new Error("Required a safe "+t+", got a "+n.getTypeName()+" (see http://g.co/ng/security#xss)")},t.prototype.bypassSecurityTrustHtml=function(n){return new mc(n)},t.prototype.bypassSecurityTrustStyle=function(n){return new yc(n)},t.prototype.bypassSecurityTrustScript=function(n){return new vc(n)},t.prototype.bypassSecurityTrustUrl=function(n){return new _c(n)},t.prototype.bypassSecurityTrustResourceUrl=function(n){return new bc(n)},t}(dc),gc=function(){function n(n){this.changingThisBreaksApplicationSecurity=n}return n.prototype.toString=function(){return"SafeValue must use [property]=binding: "+this.changingThisBreaksApplicationSecurity+" (see http://g.co/ng/security#xss)"},n}(),mc=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.getTypeName=function(){return"HTML"},t}(gc),yc=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.getTypeName=function(){return"Style"},t}(gc),vc=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.getTypeName=function(){return"Script"},t}(gc),_c=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.getTypeName=function(){return"URL"},t}(gc),bc=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.getTypeName=function(){return"ResourceURL"},t}(gc),wc=sl(Gl,"browser",[{provide:Re,useValue:Hu},{provide:Ae,useValue:function(){Cs.makeCurrent(),Os.init()},multi:!0},{provide:vu,useClass:Ps,deps:[Es]},{provide:Es,useFactory:function(){return document},deps:[]}]);function Cc(){return new Ee}var Sc=function(){function n(n){if(n)throw new Error("BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.")}var t;return t=n,n.withServerTransition=function(n){return{ngModule:t,providers:[{provide:Oe,useValue:n.appId},{provide:Ts,useExisting:Oe},Is]}},n}();"undefined"!=typeof window&&window;var Ec=function(){return function(n,t){this.id=n,this.url=t}}(),xc=function(n){function t(t,e,l,r){void 0===l&&(l="imperative"),void 0===r&&(r=null);var o=n.call(this,t,e)||this;return o.navigationTrigger=l,o.restoredState=r,o}return r(t,n),t.prototype.toString=function(){return"NavigationStart(id: "+this.id+", url: '"+this.url+"')"},t}(Ec),Pc=function(n){function t(t,e,l){var r=n.call(this,t,e)||this;return r.urlAfterRedirects=l,r}return r(t,n),t.prototype.toString=function(){return"NavigationEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"')"},t}(Ec),Tc=function(n){function t(t,e,l){var r=n.call(this,t,e)||this;return r.reason=l,r}return r(t,n),t.prototype.toString=function(){return"NavigationCancel(id: "+this.id+", url: '"+this.url+"')"},t}(Ec),Ic=function(n){function t(t,e,l){var r=n.call(this,t,e)||this;return r.error=l,r}return r(t,n),t.prototype.toString=function(){return"NavigationError(id: "+this.id+", url: '"+this.url+"', error: "+this.error+")"},t}(Ec),Oc=function(n){function t(t,e,l,r){var o=n.call(this,t,e)||this;return o.urlAfterRedirects=l,o.state=r,o}return r(t,n),t.prototype.toString=function(){return"RoutesRecognized(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},t}(Ec),kc=function(n){function t(t,e,l,r){var o=n.call(this,t,e)||this;return o.urlAfterRedirects=l,o.state=r,o}return r(t,n),t.prototype.toString=function(){return"GuardsCheckStart(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},t}(Ec),Dc=function(n){function t(t,e,l,r,o){var i=n.call(this,t,e)||this;return i.urlAfterRedirects=l,i.state=r,i.shouldActivate=o,i}return r(t,n),t.prototype.toString=function(){return"GuardsCheckEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+", shouldActivate: "+this.shouldActivate+")"},t}(Ec),Ac=function(n){function t(t,e,l,r){var o=n.call(this,t,e)||this;return o.urlAfterRedirects=l,o.state=r,o}return r(t,n),t.prototype.toString=function(){return"ResolveStart(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},t}(Ec),Rc=function(n){function t(t,e,l,r){var o=n.call(this,t,e)||this;return o.urlAfterRedirects=l,o.state=r,o}return r(t,n),t.prototype.toString=function(){return"ResolveEnd(id: "+this.id+", url: '"+this.url+"', urlAfterRedirects: '"+this.urlAfterRedirects+"', state: "+this.state+")"},t}(Ec),Mc=function(){function n(n){this.route=n}return n.prototype.toString=function(){return"RouteConfigLoadStart(path: "+this.route.path+")"},n}(),Nc=function(){function n(n){this.route=n}return n.prototype.toString=function(){return"RouteConfigLoadEnd(path: "+this.route.path+")"},n}(),Lc=function(){function n(n){this.snapshot=n}return n.prototype.toString=function(){return"ChildActivationStart(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},n}(),Vc=function(){function n(n){this.snapshot=n}return n.prototype.toString=function(){return"ChildActivationEnd(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},n}(),Uc=function(){function n(n){this.snapshot=n}return n.prototype.toString=function(){return"ActivationStart(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},n}(),jc=function(){function n(n){this.snapshot=n}return n.prototype.toString=function(){return"ActivationEnd(path: '"+(this.snapshot.routeConfig&&this.snapshot.routeConfig.path||"")+"')"},n}(),Fc=function(){function n(n,t,e){this.routerEvent=n,this.position=t,this.anchor=e}return n.prototype.toString=function(){return"Scroll(anchor: '"+this.anchor+"', position: '"+(this.position?this.position[0]+", "+this.position[1]:null)+"')"},n}(),Bc=function(){return function(){}}(),Hc="primary",zc=function(){function n(n){this.params=n||{}}return n.prototype.has=function(n){return this.params.hasOwnProperty(n)},n.prototype.get=function(n){if(this.has(n)){var t=this.params[n];return Array.isArray(t)?t[0]:t}return null},n.prototype.getAll=function(n){if(this.has(n)){var t=this.params[n];return Array.isArray(t)?t:[t]}return[]},Object.defineProperty(n.prototype,"keys",{get:function(){return Object.keys(this.params)},enumerable:!0,configurable:!0}),n}();function qc(n){return new zc(n)}var Gc="ngNavigationCancelingError";function Wc(n){var t=Error("NavigationCancelingError: "+n);return t[Gc]=!0,t}function Qc(n,t,e){var l=e.path.split("/");if(l.length>n.length)return null;if("full"===e.pathMatch&&(t.hasChildren()||l.length<n.length))return null;for(var r={},o=0;o<l.length;o++){var i=l[o],u=n[o];if(i.startsWith(":"))r[i.substring(1)]=u;else if(i!==u.path)return null}return{consumed:n.slice(0,l.length),posParams:r}}var $c=function(){return function(n,t){this.routes=n,this.module=t}}();function Kc(n,t){void 0===t&&(t="");for(var e=0;e<n.length;e++){var l=n[e];Zc(l,Yc(t,l))}}function Zc(n,t){if(!n)throw new Error("\n Invalid configuration of route '"+t+"': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");if(Array.isArray(n))throw new Error("Invalid configuration of route '"+t+"': Array cannot be specified");if(!n.component&&!n.children&&!n.loadChildren&&n.outlet&&n.outlet!==Hc)throw new Error("Invalid configuration of route '"+t+"': a componentless route without children or loadChildren cannot have a named outlet set");if(n.redirectTo&&n.children)throw new Error("Invalid configuration of route '"+t+"': redirectTo and children cannot be used together");if(n.redirectTo&&n.loadChildren)throw new Error("Invalid configuration of route '"+t+"': redirectTo and loadChildren cannot be used together");if(n.children&&n.loadChildren)throw new Error("Invalid configuration of route '"+t+"': children and loadChildren cannot be used together");if(n.redirectTo&&n.component)throw new Error("Invalid configuration of route '"+t+"': redirectTo and component cannot be used together");if(n.path&&n.matcher)throw new Error("Invalid configuration of route '"+t+"': path and matcher cannot be used together");if(void 0===n.redirectTo&&!n.component&&!n.children&&!n.loadChildren)throw new Error("Invalid configuration of route '"+t+"'. One of the following must be provided: component, redirectTo, children or loadChildren");if(void 0===n.path&&void 0===n.matcher)throw new Error("Invalid configuration of route '"+t+"': routes must have either a path or a matcher specified");if("string"==typeof n.path&&"/"===n.path.charAt(0))throw new Error("Invalid configuration of route '"+t+"': path cannot start with a slash");if(""===n.path&&void 0!==n.redirectTo&&void 0===n.pathMatch)throw new Error("Invalid configuration of route '{path: \""+t+'", redirectTo: "'+n.redirectTo+"\"}': please provide 'pathMatch'. The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.");if(void 0!==n.pathMatch&&"full"!==n.pathMatch&&"prefix"!==n.pathMatch)throw new Error("Invalid configuration of route '"+t+"': pathMatch can only be set to 'prefix' or 'full'");n.children&&Kc(n.children,t)}function Yc(n,t){return t?n||t.path?n&&!t.path?n+"/":!n&&t.path?t.path:n+"/"+t.path:"":n}function Xc(n){var t=n.children&&n.children.map(Xc),e=t?o({},n,{children:t}):o({},n);return!e.component&&(t||e.loadChildren)&&e.outlet&&e.outlet!==Hc&&(e.component=Bc),e}function Jc(n,t){var e,l=Object.keys(n),r=Object.keys(t);if(l.length!=r.length)return!1;for(var o=0;o<l.length;o++)if(n[e=l[o]]!==t[e])return!1;return!0}function np(n){return Array.prototype.concat.apply([],n)}function tp(n){return n.length>0?n[n.length-1]:null}function ep(n,t){for(var e in n)n.hasOwnProperty(e)&&t(n[e],e)}function lp(n){return Pe(n)?n:xe(n)?rn(Promise.resolve(n)):du(n)}function rp(n,t,e){return e?function(n,t){return Jc(n,t)}(n.queryParams,t.queryParams)&&function n(t,e){if(!ap(t.segments,e.segments))return!1;if(t.numberOfChildren!==e.numberOfChildren)return!1;for(var l in e.children){if(!t.children[l])return!1;if(!n(t.children[l],e.children[l]))return!1}return!0}(n.root,t.root):function(n,t){return Object.keys(t).length<=Object.keys(n).length&&Object.keys(t).every(function(e){return t[e]===n[e]})}(n.queryParams,t.queryParams)&&function n(t,e){return function t(e,l,r){if(e.segments.length>r.length)return!!ap(i=e.segments.slice(0,r.length),r)&&!l.hasChildren();if(e.segments.length===r.length){if(!ap(e.segments,r))return!1;for(var o in l.children){if(!e.children[o])return!1;if(!n(e.children[o],l.children[o]))return!1}return!0}var i=r.slice(0,e.segments.length),u=r.slice(e.segments.length);return!!ap(e.segments,i)&&!!e.children[Hc]&&t(e.children[Hc],l,u)}(t,e,e.segments)}(n.root,t.root)}var op=function(){function n(n,t,e){this.root=n,this.queryParams=t,this.fragment=e}return Object.defineProperty(n.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=qc(this.queryParams)),this._queryParamMap},enumerable:!0,configurable:!0}),n.prototype.toString=function(){return hp.serialize(this)},n}(),ip=function(){function n(n,t){var e=this;this.segments=n,this.children=t,this.parent=null,ep(t,function(n,t){return n.parent=e})}return n.prototype.hasChildren=function(){return this.numberOfChildren>0},Object.defineProperty(n.prototype,"numberOfChildren",{get:function(){return Object.keys(this.children).length},enumerable:!0,configurable:!0}),n.prototype.toString=function(){return dp(this)},n}(),up=function(){function n(n,t){this.path=n,this.parameters=t}return Object.defineProperty(n.prototype,"parameterMap",{get:function(){return this._parameterMap||(this._parameterMap=qc(this.parameters)),this._parameterMap},enumerable:!0,configurable:!0}),n.prototype.toString=function(){return _p(this)},n}();function ap(n,t){return n.length===t.length&&n.every(function(n,e){return n.path===t[e].path})}function sp(n,t){var e=[];return ep(n.children,function(n,l){l===Hc&&(e=e.concat(t(n,l)))}),ep(n.children,function(n,l){l!==Hc&&(e=e.concat(t(n,l)))}),e}var cp=function(){return function(){}}(),pp=function(){function n(){}return n.prototype.parse=function(n){var t=new Ep(n);return new op(t.parseRootSegment(),t.parseQueryParams(),t.parseFragment())},n.prototype.serialize=function(n){var t,e;return"/"+function n(t,e){if(!t.hasChildren())return dp(t);if(e){var l=t.children[Hc]?n(t.children[Hc],!1):"",r=[];return ep(t.children,function(t,e){e!==Hc&&r.push(e+":"+n(t,!1))}),r.length>0?l+"("+r.join("//")+")":l}var o=sp(t,function(e,l){return l===Hc?[n(t.children[Hc],!1)]:[l+":"+n(e,!1)]});return dp(t)+"/("+o.join("//")+")"}(n.root,!0)+(t=n.queryParams,(e=Object.keys(t).map(function(n){var e=t[n];return Array.isArray(e)?e.map(function(t){return gp(n)+"="+gp(t)}).join("&"):gp(n)+"="+gp(e)})).length?"?"+e.join("&"):"")+("string"==typeof n.fragment?"#"+encodeURI(n.fragment):"")},n}(),hp=new pp;function dp(n){return n.segments.map(function(n){return _p(n)}).join("/")}function fp(n){return encodeURIComponent(n).replace(/%40/g,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",")}function gp(n){return fp(n).replace(/%3B/gi,";")}function mp(n){return fp(n).replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/%26/gi,"&")}function yp(n){return decodeURIComponent(n)}function vp(n){return yp(n.replace(/\+/g,"%20"))}function _p(n){return""+mp(n.path)+(t=n.parameters,Object.keys(t).map(function(n){return";"+mp(n)+"="+mp(t[n])}).join(""));var t}var bp=/^[^\/()?;=#]+/;function wp(n){var t=n.match(bp);return t?t[0]:""}var Cp=/^[^=?&#]+/,Sp=/^[^?&#]+/,Ep=function(){function n(n){this.url=n,this.remaining=n}return n.prototype.parseRootSegment=function(){return this.consumeOptional("/"),""===this.remaining||this.peekStartsWith("?")||this.peekStartsWith("#")?new ip([],{}):new ip([],this.parseChildren())},n.prototype.parseQueryParams=function(){var n={};if(this.consumeOptional("?"))do{this.parseQueryParam(n)}while(this.consumeOptional("&"));return n},n.prototype.parseFragment=function(){return this.consumeOptional("#")?decodeURIComponent(this.remaining):null},n.prototype.parseChildren=function(){if(""===this.remaining)return{};this.consumeOptional("/");var n=[];for(this.peekStartsWith("(")||n.push(this.parseSegment());this.peekStartsWith("/")&&!this.peekStartsWith("//")&&!this.peekStartsWith("/(");)this.capture("/"),n.push(this.parseSegment());var t={};this.peekStartsWith("/(")&&(this.capture("/"),t=this.parseParens(!0));var e={};return this.peekStartsWith("(")&&(e=this.parseParens(!1)),(n.length>0||Object.keys(t).length>0)&&(e[Hc]=new ip(n,t)),e},n.prototype.parseSegment=function(){var n=wp(this.remaining);if(""===n&&this.peekStartsWith(";"))throw new Error("Empty path url segment cannot have parameters: '"+this.remaining+"'.");return this.capture(n),new up(yp(n),this.parseMatrixParams())},n.prototype.parseMatrixParams=function(){for(var n={};this.consumeOptional(";");)this.parseParam(n);return n},n.prototype.parseParam=function(n){var t=wp(this.remaining);if(t){this.capture(t);var e="";if(this.consumeOptional("=")){var l=wp(this.remaining);l&&this.capture(e=l)}n[yp(t)]=yp(e)}},n.prototype.parseQueryParam=function(n){var t,e=(t=this.remaining.match(Cp))?t[0]:"";if(e){this.capture(e);var l="";if(this.consumeOptional("=")){var r=function(n){var t=n.match(Sp);return t?t[0]:""}(this.remaining);r&&this.capture(l=r)}var o=vp(e),i=vp(l);if(n.hasOwnProperty(o)){var u=n[o];Array.isArray(u)||(n[o]=u=[u]),u.push(i)}else n[o]=i}},n.prototype.parseParens=function(n){var t={};for(this.capture("(");!this.consumeOptional(")")&&this.remaining.length>0;){var e=wp(this.remaining),l=this.remaining[e.length];if("/"!==l&&")"!==l&&";"!==l)throw new Error("Cannot parse url '"+this.url+"'");var r=void 0;e.indexOf(":")>-1?(r=e.substr(0,e.indexOf(":")),this.capture(r),this.capture(":")):n&&(r=Hc);var o=this.parseChildren();t[r]=1===Object.keys(o).length?o[Hc]:new ip([],o),this.consumeOptional("//")}return t},n.prototype.peekStartsWith=function(n){return this.remaining.startsWith(n)},n.prototype.consumeOptional=function(n){return!!this.peekStartsWith(n)&&(this.remaining=this.remaining.substring(n.length),!0)},n.prototype.capture=function(n){if(!this.consumeOptional(n))throw new Error('Expected "'+n+'".')},n}(),xp=function(){function n(n){this._root=n}return Object.defineProperty(n.prototype,"root",{get:function(){return this._root.value},enumerable:!0,configurable:!0}),n.prototype.parent=function(n){var t=this.pathFromRoot(n);return t.length>1?t[t.length-2]:null},n.prototype.children=function(n){var t=Pp(n,this._root);return t?t.children.map(function(n){return n.value}):[]},n.prototype.firstChild=function(n){var t=Pp(n,this._root);return t&&t.children.length>0?t.children[0].value:null},n.prototype.siblings=function(n){var t=Tp(n,this._root);return t.length<2?[]:t[t.length-2].children.map(function(n){return n.value}).filter(function(t){return t!==n})},n.prototype.pathFromRoot=function(n){return Tp(n,this._root).map(function(n){return n.value})},n}();function Pp(n,t){var e,l;if(n===t.value)return t;try{for(var r=a(t.children),o=r.next();!o.done;o=r.next()){var i=Pp(n,o.value);if(i)return i}}catch(u){e={error:u}}finally{try{o&&!o.done&&(l=r.return)&&l.call(r)}finally{if(e)throw e.error}}return null}function Tp(n,t){var e,l;if(n===t.value)return[t];try{for(var r=a(t.children),o=r.next();!o.done;o=r.next()){var i=Tp(n,o.value);if(i.length)return i.unshift(t),i}}catch(u){e={error:u}}finally{try{o&&!o.done&&(l=r.return)&&l.call(r)}finally{if(e)throw e.error}}return[]}var Ip=function(){function n(n,t){this.value=n,this.children=t}return n.prototype.toString=function(){return"TreeNode("+this.value+")"},n}();function Op(n){var t={};return n&&n.children.forEach(function(n){return t[n.value.outlet]=n}),t}var kp=function(n){function t(t,e){var l=n.call(this,t)||this;return l.snapshot=e,Lp(l,t),l}return r(t,n),t.prototype.toString=function(){return this.snapshot.toString()},t}(xp);function Dp(n,t){var e=function(n,t){var e=new Mp([],{},{},"",{},Hc,t,null,n.root,-1,{});return new Np("",new Ip(e,[]))}(n,t),l=new Ra([new up("",{})]),r=new Ra({}),o=new Ra({}),i=new Ra({}),u=new Ra(""),a=new Ap(l,r,i,u,o,Hc,t,e.root);return a.snapshot=e.root,new kp(new Ip(a,[]),e)}var Ap=function(){function n(n,t,e,l,r,o,i,u){this.url=n,this.params=t,this.queryParams=e,this.fragment=l,this.data=r,this.outlet=o,this.component=i,this._futureSnapshot=u}return Object.defineProperty(n.prototype,"routeConfig",{get:function(){return this._futureSnapshot.routeConfig},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"root",{get:function(){return this._routerState.root},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"parent",{get:function(){return this._routerState.parent(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"firstChild",{get:function(){return this._routerState.firstChild(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"children",{get:function(){return this._routerState.children(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"pathFromRoot",{get:function(){return this._routerState.pathFromRoot(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"paramMap",{get:function(){return this._paramMap||(this._paramMap=this.params.pipe(nn(function(n){return qc(n)}))),this._paramMap},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=this.queryParams.pipe(nn(function(n){return qc(n)}))),this._queryParamMap},enumerable:!0,configurable:!0}),n.prototype.toString=function(){return this.snapshot?this.snapshot.toString():"Future("+this._futureSnapshot+")"},n}();function Rp(n,t){void 0===t&&(t="emptyOnly");var e=n.pathFromRoot,l=0;if("always"!==t)for(l=e.length-1;l>=1;){var r=e[l],i=e[l-1];if(r.routeConfig&&""===r.routeConfig.path)l--;else{if(i.component)break;l--}}return function(n){return n.reduce(function(n,t){return{params:o({},n.params,t.params),data:o({},n.data,t.data),resolve:o({},n.resolve,t._resolvedData)}},{params:{},data:{},resolve:{}})}(e.slice(l))}var Mp=function(){function n(n,t,e,l,r,o,i,u,a,s,c){this.url=n,this.params=t,this.queryParams=e,this.fragment=l,this.data=r,this.outlet=o,this.component=i,this.routeConfig=u,this._urlSegment=a,this._lastPathIndex=s,this._resolve=c}return Object.defineProperty(n.prototype,"root",{get:function(){return this._routerState.root},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"parent",{get:function(){return this._routerState.parent(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"firstChild",{get:function(){return this._routerState.firstChild(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"children",{get:function(){return this._routerState.children(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"pathFromRoot",{get:function(){return this._routerState.pathFromRoot(this)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"paramMap",{get:function(){return this._paramMap||(this._paramMap=qc(this.params)),this._paramMap},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"queryParamMap",{get:function(){return this._queryParamMap||(this._queryParamMap=qc(this.queryParams)),this._queryParamMap},enumerable:!0,configurable:!0}),n.prototype.toString=function(){return"Route(url:'"+this.url.map(function(n){return n.toString()}).join("/")+"', path:'"+(this.routeConfig?this.routeConfig.path:"")+"')"},n}(),Np=function(n){function t(t,e){var l=n.call(this,e)||this;return l.url=t,Lp(l,e),l}return r(t,n),t.prototype.toString=function(){return Vp(this._root)},t}(xp);function Lp(n,t){t.value._routerState=n,t.children.forEach(function(t){return Lp(n,t)})}function Vp(n){var t=n.children.length>0?" { "+n.children.map(Vp).join(", ")+" } ":"";return""+n.value+t}function Up(n){if(n.snapshot){var t=n.snapshot,e=n._futureSnapshot;n.snapshot=e,Jc(t.queryParams,e.queryParams)||n.queryParams.next(e.queryParams),t.fragment!==e.fragment&&n.fragment.next(e.fragment),Jc(t.params,e.params)||n.params.next(e.params),function(n,t){if(n.length!==t.length)return!1;for(var e=0;e<n.length;++e)if(!Jc(n[e],t[e]))return!1;return!0}(t.url,e.url)||n.url.next(e.url),Jc(t.data,e.data)||n.data.next(e.data)}else n.snapshot=n._futureSnapshot,n.data.next(n._futureSnapshot.data)}function jp(n,t){var e,l;return Jc(n.params,t.params)&&ap(e=n.url,l=t.url)&&e.every(function(n,t){return Jc(n.parameters,l[t].parameters)})&&!(!n.parent!=!t.parent)&&(!n.parent||jp(n.parent,t.parent))}function Fp(n){return"object"==typeof n&&null!=n&&!n.outlets&&!n.segmentPath}function Bp(n,t,e,l,r){var o={};return l&&ep(l,function(n,t){o[t]=Array.isArray(n)?n.map(function(n){return""+n}):""+n}),new op(e.root===n?t:function n(t,e,l){var r={};return ep(t.children,function(t,o){r[o]=t===e?l:n(t,e,l)}),new ip(t.segments,r)}(e.root,n,t),o,r)}var Hp=function(){function n(n,t,e){if(this.isAbsolute=n,this.numberOfDoubleDots=t,this.commands=e,n&&e.length>0&&Fp(e[0]))throw new Error("Root segment cannot have matrix parameters");var l=e.find(function(n){return"object"==typeof n&&null!=n&&n.outlets});if(l&&l!==tp(e))throw new Error("{outlets:{}} has to be the last command")}return n.prototype.toRoot=function(){return this.isAbsolute&&1===this.commands.length&&"/"==this.commands[0]},n}(),zp=function(){return function(n,t,e){this.segmentGroup=n,this.processChildren=t,this.index=e}}();function qp(n){return"object"==typeof n&&null!=n&&n.outlets?n.outlets[Hc]:""+n}function Gp(n,t,e){if(n||(n=new ip([],{})),0===n.segments.length&&n.hasChildren())return Wp(n,t,e);var l=function(n,t,e){for(var l=0,r=t,o={match:!1,pathIndex:0,commandIndex:0};r<n.segments.length;){if(l>=e.length)return o;var i=n.segments[r],u=qp(e[l]),a=l<e.length-1?e[l+1]:null;if(r>0&&void 0===u)break;if(u&&a&&"object"==typeof a&&void 0===a.outlets){if(!Zp(u,a,i))return o;l+=2}else{if(!Zp(u,{},i))return o;l++}r++}return{match:!0,pathIndex:r,commandIndex:l}}(n,t,e),r=e.slice(l.commandIndex);if(l.match&&l.pathIndex<n.segments.length){var o=new ip(n.segments.slice(0,l.pathIndex),{});return o.children[Hc]=new ip(n.segments.slice(l.pathIndex),n.children),Wp(o,0,r)}return l.match&&0===r.length?new ip(n.segments,{}):l.match&&!n.hasChildren()?Qp(n,t,e):l.match?Wp(n,0,r):Qp(n,t,e)}function Wp(n,t,e){if(0===e.length)return new ip(n.segments,{});var l=function(n){var t,e;return"object"!=typeof n[0]?((t={})[Hc]=n,t):void 0===n[0].outlets?((e={})[Hc]=n,e):n[0].outlets}(e),r={};return ep(l,function(e,l){null!==e&&(r[l]=Gp(n.children[l],t,e))}),ep(n.children,function(n,t){void 0===l[t]&&(r[t]=n)}),new ip(n.segments,r)}function Qp(n,t,e){for(var l=n.segments.slice(0,t),r=0;r<e.length;){if("object"==typeof e[r]&&void 0!==e[r].outlets){var o=$p(e[r].outlets);return new ip(l,o)}if(0===r&&Fp(e[0]))l.push(new up(n.segments[t].path,e[0])),r++;else{var i=qp(e[r]),u=r<e.length-1?e[r+1]:null;i&&u&&Fp(u)?(l.push(new up(i,Kp(u))),r+=2):(l.push(new up(i,{})),r++)}}return new ip(l,{})}function $p(n){var t={};return ep(n,function(n,e){null!==n&&(t[e]=Qp(new ip([],{}),0,n))}),t}function Kp(n){var t={};return ep(n,function(n,e){return t[e]=""+n}),t}function Zp(n,t,e){return n==e.path&&Jc(t,e.parameters)}var Yp=function(){function n(n,t,e,l){this.routeReuseStrategy=n,this.futureState=t,this.currState=e,this.forwardEvent=l}return n.prototype.activate=function(n){var t=this.futureState._root,e=this.currState?this.currState._root:null;this.deactivateChildRoutes(t,e,n),Up(this.futureState.root),this.activateChildRoutes(t,e,n)},n.prototype.deactivateChildRoutes=function(n,t,e){var l=this,r=Op(t);n.children.forEach(function(n){var t=n.value.outlet;l.deactivateRoutes(n,r[t],e),delete r[t]}),ep(r,function(n,t){l.deactivateRouteAndItsChildren(n,e)})},n.prototype.deactivateRoutes=function(n,t,e){var l=n.value,r=t?t.value:null;if(l===r)if(l.component){var o=e.getContext(l.outlet);o&&this.deactivateChildRoutes(n,t,o.children)}else this.deactivateChildRoutes(n,t,e);else r&&this.deactivateRouteAndItsChildren(t,e)},n.prototype.deactivateRouteAndItsChildren=function(n,t){this.routeReuseStrategy.shouldDetach(n.value.snapshot)?this.detachAndStoreRouteSubtree(n,t):this.deactivateRouteAndOutlet(n,t)},n.prototype.detachAndStoreRouteSubtree=function(n,t){var e=t.getContext(n.value.outlet);if(e&&e.outlet){var l=e.outlet.detach(),r=e.children.onOutletDeactivated();this.routeReuseStrategy.store(n.value.snapshot,{componentRef:l,route:n,contexts:r})}},n.prototype.deactivateRouteAndOutlet=function(n,t){var e=this,l=t.getContext(n.value.outlet);if(l){var r=Op(n),o=n.value.component?l.children:t;ep(r,function(n,t){return e.deactivateRouteAndItsChildren(n,o)}),l.outlet&&(l.outlet.deactivate(),l.children.onOutletDeactivated())}},n.prototype.activateChildRoutes=function(n,t,e){var l=this,r=Op(t);n.children.forEach(function(n){l.activateRoutes(n,r[n.value.outlet],e),l.forwardEvent(new jc(n.value.snapshot))}),n.children.length&&this.forwardEvent(new Vc(n.value.snapshot))},n.prototype.activateRoutes=function(n,t,e){var l=n.value,r=t?t.value:null;if(Up(l),l===r)if(l.component){var o=e.getOrCreateContext(l.outlet);this.activateChildRoutes(n,t,o.children)}else this.activateChildRoutes(n,t,e);else if(l.component)if(o=e.getOrCreateContext(l.outlet),this.routeReuseStrategy.shouldAttach(l.snapshot)){var i=this.routeReuseStrategy.retrieve(l.snapshot);this.routeReuseStrategy.store(l.snapshot,null),o.children.onOutletReAttached(i.contexts),o.attachRef=i.componentRef,o.route=i.route.value,o.outlet&&o.outlet.attach(i.componentRef,i.route.value),Xp(i.route)}else{var u=function(n){for(var t=l.snapshot.parent;t;t=t.parent){var e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig;if(e&&e.component)return null}return null}(),a=u?u.module.componentFactoryResolver:null;o.attachRef=null,o.route=l,o.resolver=a,o.outlet&&o.outlet.activateWith(l,a),this.activateChildRoutes(n,null,o.children)}else this.activateChildRoutes(n,null,e)},n}();function Xp(n){Up(n.value),n.children.forEach(Xp)}function Jp(n){return"function"==typeof n}function nh(n){return n instanceof op}var th=function(){return function(n){this.segmentGroup=n||null}}(),eh=function(){return function(n){this.urlTree=n}}();function lh(n){return new R(function(t){return t.error(new th(n))})}function rh(n){return new R(function(t){return t.error(new eh(n))})}function oh(n){return new R(function(t){return t.error(new Error("Only absolute redirects can have named outlets. redirectTo: '"+n+"'"))})}var ih=function(){function n(n,t,e,l,r){this.configLoader=t,this.urlSerializer=e,this.urlTree=l,this.config=r,this.allowRedirects=!0,this.ngModule=n.get(kt)}return n.prototype.apply=function(){var n=this;return this.expandSegmentGroup(this.ngModule,this.config,this.urlTree.root,Hc).pipe(nn(function(t){return n.createUrlTree(t,n.urlTree.queryParams,n.urlTree.fragment)})).pipe(ts(function(t){if(t instanceof eh)return n.allowRedirects=!1,n.match(t.urlTree);if(t instanceof th)throw n.noMatchError(t);throw t}))},n.prototype.match=function(n){var t=this;return this.expandSegmentGroup(this.ngModule,this.config,n.root,Hc).pipe(nn(function(e){return t.createUrlTree(e,n.queryParams,n.fragment)})).pipe(ts(function(n){if(n instanceof th)throw t.noMatchError(n);throw n}))},n.prototype.noMatchError=function(n){return new Error("Cannot match any routes. URL Segment: '"+n.segmentGroup+"'")},n.prototype.createUrlTree=function(n,t,e){var l,r=n.segments.length>0?new ip([],((l={})[Hc]=n,l)):n;return new op(r,t,e)},n.prototype.expandSegmentGroup=function(n,t,e,l){return 0===e.segments.length&&e.hasChildren()?this.expandChildren(n,t,e).pipe(nn(function(n){return new ip([],n)})):this.expandSegment(n,e,t,e.segments,l,!0)},n.prototype.expandChildren=function(n,t,e){var l=this;return function(e,r){if(0===Object.keys(e).length)return du({});var o=[],i=[],u={};return ep(e,function(e,r){var a,s,c=(a=r,s=e,l.expandSegmentGroup(n,t,s,a)).pipe(nn(function(n){return u[r]=n}));r===Hc?o.push(c):i.push(c)}),du.apply(null,o.concat(i)).pipe(Fa(),ns(),nn(function(){return u}))}(e.children)},n.prototype.expandSegment=function(n,t,e,l,r,o){var i=this;return du.apply(void 0,c(e)).pipe(nn(function(u){return i.expandSegmentAgainstRoute(n,t,e,u,l,r,o).pipe(ts(function(n){if(n instanceof th)return du(null);throw n}))}),Fa(),us(function(n){return!!n}),ts(function(n,e){if(n instanceof Na||"EmptyError"===n.name){if(i.noLeftoversInUrl(t,l,r))return du(new ip([],{}));throw new th(t)}throw n}))},n.prototype.noLeftoversInUrl=function(n,t,e){return 0===t.length&&!n.children[e]},n.prototype.expandSegmentAgainstRoute=function(n,t,e,l,r,o,i){return ch(l)!==o?lh(t):void 0===l.redirectTo?this.matchSegmentAgainstRoute(n,t,l,r):i&&this.allowRedirects?this.expandSegmentAgainstRouteUsingRedirect(n,t,e,l,r,o):lh(t)},n.prototype.expandSegmentAgainstRouteUsingRedirect=function(n,t,e,l,r,o){return"**"===l.path?this.expandWildCardWithParamsAgainstRouteUsingRedirect(n,e,l,o):this.expandRegularSegmentAgainstRouteUsingRedirect(n,t,e,l,r,o)},n.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect=function(n,t,e,l){var r=this,o=this.applyRedirectCommands([],e.redirectTo,{});return e.redirectTo.startsWith("/")?rh(o):this.lineralizeSegments(e,o).pipe(on(function(e){var o=new ip(e,{});return r.expandSegment(n,o,t,e,l,!1)}))},n.prototype.expandRegularSegmentAgainstRouteUsingRedirect=function(n,t,e,l,r,o){var i=this,u=uh(t,l,r),a=u.consumedSegments,s=u.lastChild,c=u.positionalParamSegments;if(!u.matched)return lh(t);var p=this.applyRedirectCommands(a,l.redirectTo,c);return l.redirectTo.startsWith("/")?rh(p):this.lineralizeSegments(l,p).pipe(on(function(l){return i.expandSegment(n,t,e,l.concat(r.slice(s)),o,!1)}))},n.prototype.matchSegmentAgainstRoute=function(n,t,e,l){var r=this;if("**"===e.path)return e.loadChildren?this.configLoader.load(n.injector,e).pipe(nn(function(n){return e._loadedConfig=n,new ip(l,{})})):du(new ip(l,{}));var i=uh(t,e,l),u=i.consumedSegments,s=i.lastChild;if(!i.matched)return lh(t);var c=l.slice(s);return this.getChildConfig(n,e,l).pipe(on(function(n){var e=n.module,l=n.routes,i=function(n,t,e,l){return e.length>0&&function(n,t,e){return l.some(function(e){return sh(n,t,e)&&ch(e)!==Hc})}(n,e)?{segmentGroup:ah(new ip(t,function(n,t){var e,l,r={};r[Hc]=t;try{for(var o=a(n),i=o.next();!i.done;i=o.next()){var u=i.value;""===u.path&&ch(u)!==Hc&&(r[ch(u)]=new ip([],{}))}}catch(s){e={error:s}}finally{try{i&&!i.done&&(l=o.return)&&l.call(o)}finally{if(e)throw e.error}}return r}(l,new ip(e,n.children)))),slicedSegments:[]}:0===e.length&&function(n,t,e){return l.some(function(e){return sh(n,t,e)})}(n,e)?{segmentGroup:ah(new ip(n.segments,function(n,t,e,l){var r,i,u={};try{for(var s=a(e),c=s.next();!c.done;c=s.next()){var p=c.value;sh(n,t,p)&&!l[ch(p)]&&(u[ch(p)]=new ip([],{}))}}catch(h){r={error:h}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o({},l,u)}(n,e,l,n.children))),slicedSegments:e}:{segmentGroup:n,slicedSegments:e}}(t,u,c,l),s=i.segmentGroup,p=i.slicedSegments;return 0===p.length&&s.hasChildren()?r.expandChildren(e,l,s).pipe(nn(function(n){return new ip(u,n)})):0===l.length&&0===p.length?du(new ip(u,{})):r.expandSegment(e,s,l,p,Hc,!0).pipe(nn(function(n){return new ip(u.concat(n.segments),n.children)}))}))},n.prototype.getChildConfig=function(n,t,e){var l=this;return t.children?du(new $c(t.children,n)):t.loadChildren?void 0!==t._loadedConfig?du(t._loadedConfig):function(n,t,e){var l,r=t.canLoad;return r&&0!==r.length?rn(r).pipe(nn(function(l){var r,o=n.get(l);if(function(n){return n&&Jp(n.canLoad)}(o))r=o.canLoad(t,e);else{if(!Jp(o))throw new Error("Invalid CanLoad guard");r=o(t,e)}return lp(r)})).pipe(Fa(),(l=function(n){return!0===n},function(n){return n.lift(new as(l,void 0,n))})):du(!0)}(n.injector,t,e).pipe(on(function(e){return e?l.configLoader.load(n.injector,t).pipe(nn(function(n){return t._loadedConfig=n,n})):function(n){return new R(function(t){return t.error(Wc("Cannot load children because the guard of the route \"path: '"+n.path+"'\" returned false"))})}(t)})):du(new $c([],n))},n.prototype.lineralizeSegments=function(n,t){for(var e=[],l=t.root;;){if(e=e.concat(l.segments),0===l.numberOfChildren)return du(e);if(l.numberOfChildren>1||!l.children[Hc])return oh(n.redirectTo);l=l.children[Hc]}},n.prototype.applyRedirectCommands=function(n,t,e){return this.applyRedirectCreatreUrlTree(t,this.urlSerializer.parse(t),n,e)},n.prototype.applyRedirectCreatreUrlTree=function(n,t,e,l){var r=this.createSegmentGroup(n,t.root,e,l);return new op(r,this.createQueryParams(t.queryParams,this.urlTree.queryParams),t.fragment)},n.prototype.createQueryParams=function(n,t){var e={};return ep(n,function(n,l){if("string"==typeof n&&n.startsWith(":")){var r=n.substring(1);e[l]=t[r]}else e[l]=n}),e},n.prototype.createSegmentGroup=function(n,t,e,l){var r=this,o=this.createSegments(n,t.segments,e,l),i={};return ep(t.children,function(t,o){i[o]=r.createSegmentGroup(n,t,e,l)}),new ip(o,i)},n.prototype.createSegments=function(n,t,e,l){var r=this;return t.map(function(t){return t.path.startsWith(":")?r.findPosParam(n,t,l):r.findOrReturn(t,e)})},n.prototype.findPosParam=function(n,t,e){var l=e[t.path.substring(1)];if(!l)throw new Error("Cannot redirect to '"+n+"'. Cannot find '"+t.path+"'.");return l},n.prototype.findOrReturn=function(n,t){var e,l,r=0;try{for(var o=a(t),i=o.next();!i.done;i=o.next()){var u=i.value;if(u.path===n.path)return t.splice(r),u;r++}}catch(s){e={error:s}}finally{try{i&&!i.done&&(l=o.return)&&l.call(o)}finally{if(e)throw e.error}}return n},n}();function uh(n,t,e){if(""===t.path)return"full"===t.pathMatch&&(n.hasChildren()||e.length>0)?{matched:!1,consumedSegments:[],lastChild:0,positionalParamSegments:{}}:{matched:!0,consumedSegments:[],lastChild:0,positionalParamSegments:{}};var l=(t.matcher||Qc)(e,n,t);return l?{matched:!0,consumedSegments:l.consumed,lastChild:l.consumed.length,positionalParamSegments:l.posParams}:{matched:!1,consumedSegments:[],lastChild:0,positionalParamSegments:{}}}function ah(n){if(1===n.numberOfChildren&&n.children[Hc]){var t=n.children[Hc];return new ip(n.segments.concat(t.segments),t.children)}return n}function sh(n,t,e){return(!(n.hasChildren()||t.length>0)||"full"!==e.pathMatch)&&""===e.path&&void 0!==e.redirectTo}function ch(n){return n.outlet||Hc}var ph=function(){return function(n){this.path=n,this.route=this.path[this.path.length-1]}}(),hh=function(){return function(n,t){this.component=n,this.route=t}}();function dh(n,t,e){var l=function(n){if(!n)return null;for(var t=n.parent;t;t=t.parent){var e=t.routeConfig;if(e&&e._loadedConfig)return e._loadedConfig}return null}(t);return(l?l.module.injector:e).get(n)}function fh(n,t,e,l,r){void 0===r&&(r={canDeactivateChecks:[],canActivateChecks:[]});var o=Op(t);return n.children.forEach(function(n){!function(n,t,e,l,r){void 0===r&&(r={canDeactivateChecks:[],canActivateChecks:[]});var o=n.value,i=t?t.value:null,u=e?e.getContext(n.value.outlet):null;if(i&&o.routeConfig===i.routeConfig){var a=function(n,t,e){if("function"==typeof e)return e(n,t);switch(e){case"pathParamsChange":return!ap(n.url,t.url);case"pathParamsOrQueryParamsChange":return!ap(n.url,t.url)||!Jc(n.queryParams,t.queryParams);case"always":return!0;case"paramsOrQueryParamsChange":return!jp(n,t)||!Jc(n.queryParams,t.queryParams);case"paramsChange":default:return!jp(n,t)}}(i,o,o.routeConfig.runGuardsAndResolvers);a?r.canActivateChecks.push(new ph(l)):(o.data=i.data,o._resolvedData=i._resolvedData),fh(n,t,o.component?u?u.children:null:e,l,r),a&&r.canDeactivateChecks.push(new hh(u&&u.outlet&&u.outlet.component||null,i))}else i&&gh(t,u,r),r.canActivateChecks.push(new ph(l)),fh(n,null,o.component?u?u.children:null:e,l,r)}(n,o[n.value.outlet],e,l.concat([n.value]),r),delete o[n.value.outlet]}),ep(o,function(n,t){return gh(n,e.getContext(t),r)}),r}function gh(n,t,e){var l=Op(n),r=n.value;ep(l,function(n,l){gh(n,r.component?t?t.children.getContext(l):null:t,e)}),e.canDeactivateChecks.push(new hh(r.component&&t&&t.outlet&&t.outlet.isActivated?t.outlet.component:null,r))}var mh=Symbol("INITIAL_VALUE");function yh(){return Pa(function(n){return(function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];var e=null,l=null;return B(n[n.length-1])&&(l=n.pop()),"function"==typeof n[n.length-1]&&(e=n.pop()),1===n.length&&p(n[0])&&(n=n[0]),ln(n,l).lift(new Va(e))}).apply(void 0,c(n.map(function(n){return n.pipe(rs(1),function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return function(t){var e=n[n.length-1];B(e)?n.pop():e=null;var l=n.length;return function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return 1===n.length||2===n.length&&B(n[1])?rn(n[0]):Fa()(du.apply(void 0,n))}(1!==l||e?l>0?ln(n,e):pu(e):hu(n[0]),t)}}(mh))}))).pipe(cs(function(n,t){var e=!1;return t.reduce(function(n,l,r){if(n!==mh)return n;if(l===mh&&(e=!0),!e){if(!1===l)return l;if(r===t.length-1||nh(l))return l}return n},n)},mh),gu(function(n){return n!==mh}),nn(function(n){return nh(n)?n:!0===n}),rs(1))})}function vh(n,t){return null!==n&&t&&t(new Uc(n)),du(!0)}function _h(n,t){return null!==n&&t&&t(new Lc(n)),du(!0)}function bh(n,t,e){var l=t.routeConfig?t.routeConfig.canActivate:null;return l&&0!==l.length?du(l.map(function(l){return ja(function(){var r,o=dh(l,t,e);if(function(n){return n&&Jp(n.canActivate)}(o))r=lp(o.canActivate(t,n));else{if(!Jp(o))throw new Error("Invalid CanActivate guard");r=lp(o(t,n))}return r.pipe(us())})})).pipe(yh()):du(!0)}function wh(n,t,e){var l=t[t.length-1],r=t.slice(0,t.length-1).reverse().map(function(n){return function(n){var t=n.routeConfig?n.routeConfig.canActivateChild:null;return t&&0!==t.length?{node:n,guards:t}:null}(n)}).filter(function(n){return null!==n}).map(function(t){return ja(function(){return du(t.guards.map(function(r){var o,i=dh(r,t.node,e);if(function(n){return n&&Jp(n.canActivateChild)}(i))o=lp(i.canActivateChild(l,n));else{if(!Jp(i))throw new Error("Invalid CanActivateChild guard");o=lp(i(l,n))}return o.pipe(us())})).pipe(yh())})});return du(r).pipe(yh())}var Ch=function(){return function(){}}(),Sh=function(){function n(n,t,e,l,r,o){this.rootComponentType=n,this.config=t,this.urlTree=e,this.url=l,this.paramsInheritanceStrategy=r,this.relativeLinkResolution=o}return n.prototype.recognize=function(){try{var n=Ph(this.urlTree.root,[],[],this.config,this.relativeLinkResolution).segmentGroup,t=this.processSegmentGroup(this.config,n,Hc),e=new Mp([],Object.freeze({}),Object.freeze(o({},this.urlTree.queryParams)),this.urlTree.fragment,{},Hc,this.rootComponentType,null,this.urlTree.root,-1,{}),l=new Ip(e,t),r=new Np(this.url,l);return this.inheritParamsAndData(r._root),du(r)}catch(i){return new R(function(n){return n.error(i)})}},n.prototype.inheritParamsAndData=function(n){var t=this,e=n.value,l=Rp(e,this.paramsInheritanceStrategy);e.params=Object.freeze(l.params),e.data=Object.freeze(l.data),n.children.forEach(function(n){return t.inheritParamsAndData(n)})},n.prototype.processSegmentGroup=function(n,t,e){return 0===t.segments.length&&t.hasChildren()?this.processChildren(n,t):this.processSegment(n,t,t.segments,e)},n.prototype.processChildren=function(n,t){var e,l=this,r=sp(t,function(t,e){return l.processSegmentGroup(n,t,e)});return e={},r.forEach(function(n){var t=e[n.value.outlet];if(t){var l=t.url.map(function(n){return n.toString()}).join("/"),r=n.value.url.map(function(n){return n.toString()}).join("/");throw new Error("Two segments cannot have the same outlet name: '"+l+"' and '"+r+"'.")}e[n.value.outlet]=n.value}),r.sort(function(n,t){return n.value.outlet===Hc?-1:t.value.outlet===Hc?1:n.value.outlet.localeCompare(t.value.outlet)}),r},n.prototype.processSegment=function(n,t,e,l){var r,o;try{for(var i=a(n),u=i.next();!u.done;u=i.next()){var s=u.value;try{return this.processSegmentAgainstRoute(s,t,e,l)}catch(c){if(!(c instanceof Ch))throw c}}}catch(p){r={error:p}}finally{try{u&&!u.done&&(o=i.return)&&o.call(i)}finally{if(r)throw r.error}}if(this.noLeftoversInUrl(t,e,l))return[];throw new Ch},n.prototype.noLeftoversInUrl=function(n,t,e){return 0===t.length&&!n.children[e]},n.prototype.processSegmentAgainstRoute=function(n,t,e,l){if(n.redirectTo)throw new Ch;if((n.outlet||Hc)!==l)throw new Ch;var r,i=[],u=[];if("**"===n.path){var a=e.length>0?tp(e).parameters:{};r=new Mp(e,a,Object.freeze(o({},this.urlTree.queryParams)),this.urlTree.fragment,Oh(n),l,n.component,n,Eh(t),xh(t)+e.length,kh(n))}else{var s=function(n,t,e){if(""===t.path){if("full"===t.pathMatch&&(n.hasChildren()||e.length>0))throw new Ch;return{consumedSegments:[],lastChild:0,parameters:{}}}var l=(t.matcher||Qc)(e,n,t);if(!l)throw new Ch;var r={};ep(l.posParams,function(n,t){r[t]=n.path});var i=l.consumed.length>0?o({},r,l.consumed[l.consumed.length-1].parameters):r;return{consumedSegments:l.consumed,lastChild:l.consumed.length,parameters:i}}(t,n,e);i=s.consumedSegments,u=e.slice(s.lastChild),r=new Mp(i,s.parameters,Object.freeze(o({},this.urlTree.queryParams)),this.urlTree.fragment,Oh(n),l,n.component,n,Eh(t),xh(t)+i.length,kh(n))}var c=function(n){return n.children?n.children:n.loadChildren?n._loadedConfig.routes:[]}(n),p=Ph(t,i,u,c,this.relativeLinkResolution),h=p.segmentGroup,d=p.slicedSegments;if(0===d.length&&h.hasChildren()){var f=this.processChildren(c,h);return[new Ip(r,f)]}if(0===c.length&&0===d.length)return[new Ip(r,[])];var g=this.processSegment(c,h,d,Hc);return[new Ip(r,g)]},n}();function Eh(n){for(var t=n;t._sourceSegment;)t=t._sourceSegment;return t}function xh(n){for(var t=n,e=t._segmentIndexShift?t._segmentIndexShift:0;t._sourceSegment;)e+=(t=t._sourceSegment)._segmentIndexShift?t._segmentIndexShift:0;return e-1}function Ph(n,t,e,l,r){if(e.length>0&&function(n,t,e){return l.some(function(e){return Th(n,t,e)&&Ih(e)!==Hc})}(n,e)){var i=new ip(t,function(n,t,e,l){var r,o,i={};i[Hc]=l,l._sourceSegment=n,l._segmentIndexShift=t.length;try{for(var u=a(e),s=u.next();!s.done;s=u.next()){var c=s.value;if(""===c.path&&Ih(c)!==Hc){var p=new ip([],{});p._sourceSegment=n,p._segmentIndexShift=t.length,i[Ih(c)]=p}}}catch(h){r={error:h}}finally{try{s&&!s.done&&(o=u.return)&&o.call(u)}finally{if(r)throw r.error}}return i}(n,t,l,new ip(e,n.children)));return i._sourceSegment=n,i._segmentIndexShift=t.length,{segmentGroup:i,slicedSegments:[]}}if(0===e.length&&function(n,t,e){return l.some(function(e){return Th(n,t,e)})}(n,e)){var u=new ip(n.segments,function(n,t,e,l,r,i){var u,s,c={};try{for(var p=a(l),h=p.next();!h.done;h=p.next()){var d=h.value;if(Th(n,e,d)&&!r[Ih(d)]){var f=new ip([],{});f._sourceSegment=n,f._segmentIndexShift="legacy"===i?n.segments.length:t.length,c[Ih(d)]=f}}}catch(g){u={error:g}}finally{try{h&&!h.done&&(s=p.return)&&s.call(p)}finally{if(u)throw u.error}}return o({},r,c)}(n,t,e,l,n.children,r));return u._sourceSegment=n,u._segmentIndexShift=t.length,{segmentGroup:u,slicedSegments:e}}var s=new ip(n.segments,n.children);return s._sourceSegment=n,s._segmentIndexShift=t.length,{segmentGroup:s,slicedSegments:e}}function Th(n,t,e){return(!(n.hasChildren()||t.length>0)||"full"!==e.pathMatch)&&""===e.path&&void 0===e.redirectTo}function Ih(n){return n.outlet||Hc}function Oh(n){return n.data||{}}function kh(n){return n.resolve||{}}function Dh(n,t,e,l){var r=dh(n,t,l);return lp(r.resolve?r.resolve(t,e):r(t,e))}function Ah(n){return function(t){return t.pipe(Pa(function(t){var e=n(t);return e?rn(e).pipe(nn(function(){return t})):rn([t])}))}}var Rh=function(){return function(){}}(),Mh=function(){function n(){}return n.prototype.shouldDetach=function(n){return!1},n.prototype.store=function(n,t){},n.prototype.shouldAttach=function(n){return!1},n.prototype.retrieve=function(n){return null},n.prototype.shouldReuseRoute=function(n,t){return n.routeConfig===t.routeConfig},n}(),Nh=new Sn("ROUTES"),Lh=function(){function n(n,t,e,l){this.loader=n,this.compiler=t,this.onLoadStartListener=e,this.onLoadEndListener=l}return n.prototype.load=function(n,t){var e=this;return this.onLoadStartListener&&this.onLoadStartListener(t),this.loadModuleFactory(t.loadChildren).pipe(nn(function(l){e.onLoadEndListener&&e.onLoadEndListener(t);var r=l.create(n);return new $c(np(r.injector.get(Nh)).map(Xc),r)}))},n.prototype.loadModuleFactory=function(n){var t=this;return"string"==typeof n?rn(this.loader.load(n)):lp(n()).pipe(on(function(n){return n instanceof Dt?du(n):rn(t.compiler.compileModuleAsync(n))}))},n}(),Vh=function(){return function(){}}(),Uh=function(){function n(){}return n.prototype.shouldProcessUrl=function(n){return!0},n.prototype.extract=function(n){return n},n.prototype.merge=function(n,t){return n},n}();function jh(n){throw n}function Fh(n,t,e){return t.parse("/")}function Bh(n,t){return du(null)}var Hh=function(){function n(n,t,e,l,r,o,i,u){var a=this;this.rootComponentType=n,this.urlSerializer=t,this.rootContexts=e,this.location=l,this.config=u,this.lastSuccessfulNavigation=null,this.currentNavigation=null,this.navigationId=0,this.isNgZoneEnabled=!1,this.events=new j,this.errorHandler=jh,this.malformedUriErrorHandler=Fh,this.navigated=!1,this.lastSuccessfulId=-1,this.hooks={beforePreactivation:Bh,afterPreactivation:Bh},this.urlHandlingStrategy=new Uh,this.routeReuseStrategy=new Mh,this.onSameUrlNavigation="ignore",this.paramsInheritanceStrategy="emptyOnly",this.urlUpdateStrategy="deferred",this.relativeLinkResolution="legacy",this.ngModule=r.get(kt),this.console=r.get(Ne);var s=r.get(Ze);this.isNgZoneEnabled=s instanceof Ze,this.resetConfig(u),this.currentUrlTree=new op(new ip([],{}),{},null),this.rawUrlTree=this.currentUrlTree,this.browserUrlTree=this.currentUrlTree,this.configLoader=new Lh(o,i,function(n){return a.triggerEvent(new Mc(n))},function(n){return a.triggerEvent(new Nc(n))}),this.routerState=Dp(this.currentUrlTree,this.rootComponentType),this.transitions=new Ra({id:0,currentUrlTree:this.currentUrlTree,currentRawUrl:this.currentUrlTree,extractedUrl:this.urlHandlingStrategy.extract(this.currentUrlTree),urlAfterRedirects:this.urlHandlingStrategy.extract(this.currentUrlTree),rawUrl:this.currentUrlTree,extras:{},resolve:null,reject:null,promise:Promise.resolve(!0),source:"imperative",restoredState:null,currentSnapshot:this.routerState.snapshot,targetSnapshot:null,currentRouterState:this.routerState,targetRouterState:null,guards:{canActivateChecks:[],canDeactivateChecks:[]},guardsResult:null}),this.navigations=this.setupNavigations(this.transitions),this.processNavigations()}return n.prototype.setupNavigations=function(n){var t=this,e=this.events;return n.pipe(gu(function(n){return 0!==n.id}),nn(function(n){return o({},n,{extractedUrl:t.urlHandlingStrategy.extract(n.rawUrl)})}),Pa(function(n){var l,r,i,u,s=!1,c=!1;return du(n).pipe(Wa(function(n){t.currentNavigation={id:n.id,initialUrl:n.currentRawUrl,extractedUrl:n.extractedUrl,trigger:n.source,extras:n.extras,previousNavigation:t.lastSuccessfulNavigation?o({},t.lastSuccessfulNavigation,{previousNavigation:null}):null}}),Pa(function(n){var l,r,i,u,a=!t.navigated||n.extractedUrl.toString()!==t.browserUrlTree.toString();if(("reload"===t.onSameUrlNavigation||a)&&t.urlHandlingStrategy.shouldProcessUrl(n.rawUrl))return du(n).pipe(Pa(function(n){var l=t.transitions.getValue();return e.next(new xc(n.id,t.serializeUrl(n.extractedUrl),n.source,n.restoredState)),l!==t.transitions.getValue()?cu:[n]}),Pa(function(n){return Promise.resolve(n)}),(l=t.ngModule.injector,r=t.configLoader,i=t.urlSerializer,u=t.config,function(n){return n.pipe(Pa(function(n){return function(t,e,l,r,o){return new ih(t,e,l,n.extractedUrl,o).apply()}(l,r,i,0,u).pipe(nn(function(t){return o({},n,{urlAfterRedirects:t})}))}))}),Wa(function(n){t.currentNavigation=o({},t.currentNavigation,{finalUrl:n.urlAfterRedirects})}),function(n,e,l,r,i){return function(l){return l.pipe(on(function(l){return function(n,t,e,l,r,o){return void 0===r&&(r="emptyOnly"),void 0===o&&(o="legacy"),new Sh(n,t,e,l,r,o).recognize()}(n,e,l.urlAfterRedirects,(u=l.urlAfterRedirects,t.serializeUrl(u)),r,i).pipe(nn(function(n){return o({},l,{targetSnapshot:n})}));var u}))}}(t.rootComponentType,t.config,0,t.paramsInheritanceStrategy,t.relativeLinkResolution),Wa(function(n){"eager"===t.urlUpdateStrategy&&(n.extras.skipLocationChange||t.setBrowserUrl(n.urlAfterRedirects,!!n.extras.replaceUrl,n.id),t.browserUrlTree=n.urlAfterRedirects)}),Wa(function(n){var l=new Oc(n.id,t.serializeUrl(n.extractedUrl),t.serializeUrl(n.urlAfterRedirects),n.targetSnapshot);e.next(l)}));if(a&&t.rawUrlTree&&t.urlHandlingStrategy.shouldProcessUrl(t.rawUrlTree)){var s=n.extractedUrl,c=n.source,p=n.restoredState,h=n.extras,d=new xc(n.id,t.serializeUrl(s),c,p);e.next(d);var f=Dp(s,t.rootComponentType).snapshot;return du(o({},n,{targetSnapshot:f,urlAfterRedirects:s,extras:o({},h,{skipLocationChange:!1,replaceUrl:!1})}))}return t.rawUrlTree=n.rawUrl,n.resolve(null),cu}),Ah(function(n){var e=n.extras;return t.hooks.beforePreactivation(n.targetSnapshot,{navigationId:n.id,appliedUrlTree:n.extractedUrl,rawUrlTree:n.rawUrl,skipLocationChange:!!e.skipLocationChange,replaceUrl:!!e.replaceUrl})}),Wa(function(n){var e=new kc(n.id,t.serializeUrl(n.extractedUrl),t.serializeUrl(n.urlAfterRedirects),n.targetSnapshot);t.triggerEvent(e)}),nn(function(n){return o({},n,{guards:(e=n.targetSnapshot,l=n.currentSnapshot,r=t.rootContexts,i=e._root,fh(i,l?l._root:null,r,[i.value]))});var e,l,r,i}),function(n,t){return function(e){return e.pipe(on(function(e){var l=e.targetSnapshot,r=e.currentSnapshot,i=e.guards,u=i.canActivateChecks,a=i.canDeactivateChecks;return 0===a.length&&0===u.length?du(o({},e,{guardsResult:!0})):function(n,t,e,l){return rn(a).pipe(on(function(n){return function(n,t,e,l,r){var o=t&&t.routeConfig?t.routeConfig.canDeactivate:null;return o&&0!==o.length?du(o.map(function(o){var i,u=dh(o,t,r);if(function(n){return n&&Jp(n.canDeactivate)}(u))i=lp(u.canDeactivate(n,t,e,l));else{if(!Jp(u))throw new Error("Invalid CanDeactivate guard");i=lp(u(n,t,e,l))}return i.pipe(us())})).pipe(yh()):du(!0)}(n.component,n.route,e,t,l)}),us(function(n){return!0!==n},!0))}(0,l,r,n).pipe(on(function(e){return e&&"boolean"==typeof e?function(n,t,e,l){return rn(u).pipe(fu(function(t){return rn([_h(t.route.parent,l),vh(t.route,l),wh(n,t.path,e),bh(n,t.route,e)]).pipe(Fa(),us(function(n){return!0!==n},!0))}),us(function(n){return!0!==n},!0))}(l,0,n,t):du(e)}),nn(function(n){return o({},e,{guardsResult:n})}))}))}}(t.ngModule.injector,function(n){return t.triggerEvent(n)}),Wa(function(n){if(nh(n.guardsResult)){var e=Wc('Redirecting to "'+t.serializeUrl(n.guardsResult)+'"');throw e.url=n.guardsResult,e}}),Wa(function(n){var e=new Dc(n.id,t.serializeUrl(n.extractedUrl),t.serializeUrl(n.urlAfterRedirects),n.targetSnapshot,!!n.guardsResult);t.triggerEvent(e)}),gu(function(n){if(!n.guardsResult){t.resetUrlToCurrentUrlTree();var l=new Tc(n.id,t.serializeUrl(n.extractedUrl),"");return e.next(l),n.resolve(!1),!1}return!0}),Ah(function(n){if(n.guards.canActivateChecks.length)return du(n).pipe(Wa(function(n){var e=new Ac(n.id,t.serializeUrl(n.extractedUrl),t.serializeUrl(n.urlAfterRedirects),n.targetSnapshot);t.triggerEvent(e)}),(e=t.paramsInheritanceStrategy,l=t.ngModule.injector,function(n){return n.pipe(on(function(n){var t=n.targetSnapshot,r=n.guards.canActivateChecks;return r.length?rn(r).pipe(fu(function(n){return function(n,e,l,r){return function(n,t,e,l){var r=Object.keys(n);if(0===r.length)return du({});if(1===r.length){var o=r[0];return Dh(n[o],t,e,l).pipe(nn(function(n){var t;return(t={})[o]=n,t}))}var i={};return rn(r).pipe(on(function(r){return Dh(n[r],t,e,l).pipe(nn(function(n){return i[r]=n,n}))})).pipe(ns(),nn(function(){return i}))}(n._resolve,n,t,r).pipe(nn(function(t){return n._resolvedData=t,n.data=o({},n.data,Rp(n,l).resolve),null}))}(n.route,0,e,l)}),function(n,t){return arguments.length>=2?function(t){return D(cs(n,void 0),za(1),Ya(void 0))(t)}:function(t){return D(cs(function(t,e,l){return n(t)}),za(1))(t)}}(function(n,t){return n}),nn(function(t){return n})):du(n)}))}),Wa(function(n){var e=new Rc(n.id,t.serializeUrl(n.extractedUrl),t.serializeUrl(n.urlAfterRedirects),n.targetSnapshot);t.triggerEvent(e)}));var e,l}),Ah(function(n){var e=n.extras;return t.hooks.afterPreactivation(n.targetSnapshot,{navigationId:n.id,appliedUrlTree:n.extractedUrl,rawUrlTree:n.rawUrl,skipLocationChange:!!e.skipLocationChange,replaceUrl:!!e.replaceUrl})}),nn(function(n){var e,l,r,i=(r=function n(t,e,l){if(l&&t.shouldReuseRoute(e.value,l.value.snapshot)){(s=l.value)._futureSnapshot=e.value;var r=function(t,e,l){return e.children.map(function(e){var r,o;try{for(var i=a(l.children),u=i.next();!u.done;u=i.next()){var s=u.value;if(t.shouldReuseRoute(s.value.snapshot,e.value))return n(t,e,s)}}catch(c){r={error:c}}finally{try{u&&!u.done&&(o=i.return)&&o.call(i)}finally{if(r)throw r.error}}return n(t,e)})}(t,e,l);return new Ip(s,r)}var o=t.retrieve(e.value);if(o){var i=o.route;return function n(t,e){if(t.value.routeConfig!==e.value.routeConfig)throw new Error("Cannot reattach ActivatedRouteSnapshot created from a different route");if(t.children.length!==e.children.length)throw new Error("Cannot reattach ActivatedRouteSnapshot with a different number of children");e.value._futureSnapshot=t.value;for(var l=0;l<t.children.length;++l)n(t.children[l],e.children[l])}(e,i),i}var u,s=new Ap(new Ra((u=e.value).url),new Ra(u.params),new Ra(u.queryParams),new Ra(u.fragment),new Ra(u.data),u.outlet,u.component,u);return r=e.children.map(function(e){return n(t,e)}),new Ip(s,r)}(t.routeReuseStrategy,(e=n.targetSnapshot)._root,(l=n.currentRouterState)?l._root:void 0),new kp(r,e));return o({},n,{targetRouterState:i})}),Wa(function(n){t.currentUrlTree=n.urlAfterRedirects,t.rawUrlTree=t.urlHandlingStrategy.merge(t.currentUrlTree,n.rawUrl),t.routerState=n.targetRouterState,"deferred"===t.urlUpdateStrategy&&(n.extras.skipLocationChange||t.setBrowserUrl(t.rawUrlTree,!!n.extras.replaceUrl,n.id,n.extras.state),t.browserUrlTree=n.urlAfterRedirects)}),(l=t.rootContexts,r=t.routeReuseStrategy,i=function(n){return t.triggerEvent(n)},nn(function(n){return new Yp(r,n.targetRouterState,n.currentRouterState,i).activate(l),n})),Wa({next:function(){s=!0},complete:function(){s=!0}}),(u=function(){if(!s&&!c){t.resetUrlToCurrentUrlTree();var l=new Tc(n.id,t.serializeUrl(n.extractedUrl),"Navigation ID "+n.id+" is not equal to the current navigation id "+t.navigationId);e.next(l),n.resolve(!1)}t.currentNavigation=null},function(n){return n.lift(new ds(u))}),ts(function(l){if(c=!0,(u=l)&&u[Gc]){var r=nh(l.url);r||(t.navigated=!0,t.resetStateAndUrl(n.currentRouterState,n.currentUrlTree,n.rawUrl));var o=new Tc(n.id,t.serializeUrl(n.extractedUrl),l.message);e.next(o),n.resolve(!1),r&&t.navigateByUrl(l.url)}else{t.resetStateAndUrl(n.currentRouterState,n.currentUrlTree,n.rawUrl);var i=new Ic(n.id,t.serializeUrl(n.extractedUrl),l);e.next(i);try{n.resolve(t.errorHandler(l))}catch(a){n.reject(a)}}var u;return cu}))}))},n.prototype.resetRootComponentType=function(n){this.rootComponentType=n,this.routerState.root.component=this.rootComponentType},n.prototype.getTransition=function(){return this.transitions.value},n.prototype.setTransition=function(n){this.transitions.next(o({},this.getTransition(),n))},n.prototype.initialNavigation=function(){this.setUpLocationChangeListener(),0===this.navigationId&&this.navigateByUrl(this.location.path(!0),{replaceUrl:!0})},n.prototype.setUpLocationChangeListener=function(){var n=this;this.locationSubscription||(this.locationSubscription=this.location.subscribe(function(t){var e=n.parseUrl(t.url),l="popstate"===t.type?"popstate":"hashchange",r=t.state&&t.state.navigationId?t.state:null;setTimeout(function(){n.scheduleNavigation(e,l,r,{replaceUrl:!0})},0)}))},Object.defineProperty(n.prototype,"url",{get:function(){return this.serializeUrl(this.currentUrlTree)},enumerable:!0,configurable:!0}),n.prototype.getCurrentNavigation=function(){return this.currentNavigation},n.prototype.triggerEvent=function(n){this.events.next(n)},n.prototype.resetConfig=function(n){Kc(n),this.config=n.map(Xc),this.navigated=!1,this.lastSuccessfulId=-1},n.prototype.ngOnDestroy=function(){this.dispose()},n.prototype.dispose=function(){this.locationSubscription&&(this.locationSubscription.unsubscribe(),this.locationSubscription=null)},n.prototype.createUrlTree=function(n,t){void 0===t&&(t={});var e=t.relativeTo,l=t.queryParams,r=t.fragment,i=t.preserveQueryParams,u=t.queryParamsHandling,a=t.preserveFragment;qt()&&i&&console&&console.warn&&console.warn("preserveQueryParams is deprecated, use queryParamsHandling instead.");var s=e||this.routerState.root,p=a?this.currentUrlTree.fragment:r,h=null;if(u)switch(u){case"merge":h=o({},this.currentUrlTree.queryParams,l);break;case"preserve":h=this.currentUrlTree.queryParams;break;default:h=l||null}else h=i?this.currentUrlTree.queryParams:l||null;return null!==h&&(h=this.removeEmptyProps(h)),function(n,t,e,l,r){if(0===e.length)return Bp(t.root,t.root,t,l,r);var o=function(n){if("string"==typeof n[0]&&1===n.length&&"/"===n[0])return new Hp(!0,0,n);var t=0,e=!1,l=n.reduce(function(n,l,r){if("object"==typeof l&&null!=l){if(l.outlets){var o={};return ep(l.outlets,function(n,t){o[t]="string"==typeof n?n.split("/"):n}),c(n,[{outlets:o}])}if(l.segmentPath)return c(n,[l.segmentPath])}return"string"!=typeof l?c(n,[l]):0===r?(l.split("/").forEach(function(l,r){0==r&&"."===l||(0==r&&""===l?e=!0:".."===l?t++:""!=l&&n.push(l))}),n):c(n,[l])},[]);return new Hp(e,t,l)}(e);if(o.toRoot())return Bp(t.root,new ip([],{}),t,l,r);var i=function(n,e,l){if(n.isAbsolute)return new zp(t.root,!0,0);if(-1===l.snapshot._lastPathIndex)return new zp(l.snapshot._urlSegment,!0,0);var r=Fp(n.commands[0])?0:1;return function(t,e,o){for(var i=l.snapshot._urlSegment,u=l.snapshot._lastPathIndex+r,a=n.numberOfDoubleDots;a>u;){if(a-=u,!(i=i.parent))throw new Error("Invalid number of '../'");u=i.segments.length}return new zp(i,!1,u-a)}()}(o,0,n),u=i.processChildren?Wp(i.segmentGroup,i.index,o.commands):Gp(i.segmentGroup,i.index,o.commands);return Bp(i.segmentGroup,u,t,l,r)}(s,this.currentUrlTree,n,h,p)},n.prototype.navigateByUrl=function(n,t){void 0===t&&(t={skipLocationChange:!1}),qt()&&this.isNgZoneEnabled&&!Ze.isInAngularZone()&&this.console.warn("Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?");var e=nh(n)?n:this.parseUrl(n),l=this.urlHandlingStrategy.merge(e,this.rawUrlTree);return this.scheduleNavigation(l,"imperative",null,t)},n.prototype.navigate=function(n,t){return void 0===t&&(t={skipLocationChange:!1}),function(n){for(var t=0;t<n.length;t++){var e=n[t];if(null==e)throw new Error("The requested path contains "+e+" segment at index "+t)}}(n),this.navigateByUrl(this.createUrlTree(n,t),t)},n.prototype.serializeUrl=function(n){return this.urlSerializer.serialize(n)},n.prototype.parseUrl=function(n){var t;try{t=this.urlSerializer.parse(n)}catch(e){t=this.malformedUriErrorHandler(e,this.urlSerializer,n)}return t},n.prototype.isActive=function(n,t){if(nh(n))return rp(this.currentUrlTree,n,t);var e=this.parseUrl(n);return rp(this.currentUrlTree,e,t)},n.prototype.removeEmptyProps=function(n){return Object.keys(n).reduce(function(t,e){var l=n[e];return null!=l&&(t[e]=l),t},{})},n.prototype.processNavigations=function(){var n=this;this.navigations.subscribe(function(t){n.navigated=!0,n.lastSuccessfulId=t.id,n.events.next(new Pc(t.id,n.serializeUrl(t.extractedUrl),n.serializeUrl(n.currentUrlTree))),n.lastSuccessfulNavigation=n.currentNavigation,n.currentNavigation=null,t.resolve(!0)},function(t){n.console.warn("Unhandled Navigation Error: ")})},n.prototype.scheduleNavigation=function(n,t,e,l){var r=this.getTransition();if(r&&"imperative"!==t&&"imperative"===r.source&&r.rawUrl.toString()===n.toString())return Promise.resolve(!0);if(r&&"hashchange"==t&&"popstate"===r.source&&r.rawUrl.toString()===n.toString())return Promise.resolve(!0);if(r&&"popstate"==t&&"hashchange"===r.source&&r.rawUrl.toString()===n.toString())return Promise.resolve(!0);var o=null,i=null,u=new Promise(function(n,t){o=n,i=t}),a=++this.navigationId;return this.setTransition({id:a,source:t,restoredState:e,currentUrlTree:this.currentUrlTree,currentRawUrl:this.rawUrlTree,rawUrl:n,extras:l,resolve:o,reject:i,promise:u,currentSnapshot:this.routerState.snapshot,currentRouterState:this.routerState}),u.catch(function(n){return Promise.reject(n)})},n.prototype.setBrowserUrl=function(n,t,e,l){var r=this.urlSerializer.serialize(n);l=l||{},this.location.isCurrentPathEqualTo(r)||t?this.location.replaceState(r,"",o({},l,{navigationId:e})):this.location.go(r,"",o({},l,{navigationId:e}))},n.prototype.resetStateAndUrl=function(n,t,e){this.routerState=n,this.currentUrlTree=t,this.rawUrlTree=this.urlHandlingStrategy.merge(this.currentUrlTree,e),this.resetUrlToCurrentUrlTree()},n.prototype.resetUrlToCurrentUrlTree=function(){this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree),"",{navigationId:this.lastSuccessfulId})},n}(),zh=function(){return function(){this.outlet=null,this.route=null,this.resolver=null,this.children=new qh,this.attachRef=null}}(),qh=function(){function n(){this.contexts=new Map}return n.prototype.onChildOutletCreated=function(n,t){var e=this.getOrCreateContext(n);e.outlet=t,this.contexts.set(n,e)},n.prototype.onChildOutletDestroyed=function(n){var t=this.getContext(n);t&&(t.outlet=null)},n.prototype.onOutletDeactivated=function(){var n=this.contexts;return this.contexts=new Map,n},n.prototype.onOutletReAttached=function(n){this.contexts=n},n.prototype.getOrCreateContext=function(n){var t=this.getContext(n);return t||(t=new zh,this.contexts.set(n,t)),t},n.prototype.getContext=function(n){return this.contexts.get(n)||null},n}(),Gh=function(){function n(n,t,e,l,r){this.parentContexts=n,this.location=t,this.resolver=e,this.changeDetector=r,this.activated=null,this._activatedRoute=null,this.activateEvents=new he,this.deactivateEvents=new he,this.name=l||Hc,n.onChildOutletCreated(this.name,this)}return n.prototype.ngOnDestroy=function(){this.parentContexts.onChildOutletDestroyed(this.name)},n.prototype.ngOnInit=function(){if(!this.activated){var n=this.parentContexts.getContext(this.name);n&&n.route&&(n.attachRef?this.attach(n.attachRef,n.route):this.activateWith(n.route,n.resolver||null))}},Object.defineProperty(n.prototype,"isActivated",{get:function(){return!!this.activated},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"component",{get:function(){if(!this.activated)throw new Error("Outlet is not activated");return this.activated.instance},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"activatedRoute",{get:function(){if(!this.activated)throw new Error("Outlet is not activated");return this._activatedRoute},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"activatedRouteData",{get:function(){return this._activatedRoute?this._activatedRoute.snapshot.data:{}},enumerable:!0,configurable:!0}),n.prototype.detach=function(){if(!this.activated)throw new Error("Outlet is not activated");this.location.detach();var n=this.activated;return this.activated=null,this._activatedRoute=null,n},n.prototype.attach=function(n,t){this.activated=n,this._activatedRoute=t,this.location.insert(n.hostView)},n.prototype.deactivate=function(){if(this.activated){var n=this.component;this.activated.destroy(),this.activated=null,this._activatedRoute=null,this.deactivateEvents.emit(n)}},n.prototype.activateWith=function(n,t){if(this.isActivated)throw new Error("Cannot activate an already activated outlet");this._activatedRoute=n;var e=(t=t||this.resolver).resolveComponentFactory(n._futureSnapshot.routeConfig.component),l=this.parentContexts.getOrCreateContext(this.name).children,r=new Wh(n,l,this.location.injector);this.activated=this.location.createComponent(e,this.location.length,r),this.changeDetector.markForCheck(),this.activateEvents.emit(this.activated.instance)},n}(),Wh=function(){function n(n,t,e){this.route=n,this.childContexts=t,this.parent=e}return n.prototype.get=function(n,t){return n===Ap?this.route:n===qh?this.childContexts:this.parent.get(n,t)},n}(),Qh=function(){return function(){}}(),$h=function(){function n(){}return n.prototype.preload=function(n,t){return t().pipe(ts(function(){return du(null)}))},n}(),Kh=function(){function n(){}return n.prototype.preload=function(n,t){return du(null)},n}(),Zh=function(){function n(n,t,e,l,r){this.router=n,this.injector=l,this.preloadingStrategy=r,this.loader=new Lh(t,e,function(t){return n.triggerEvent(new Mc(t))},function(t){return n.triggerEvent(new Nc(t))})}return n.prototype.setUpPreloading=function(){var n=this;this.subscription=this.router.events.pipe(gu(function(n){return n instanceof Pc}),fu(function(){return n.preload()})).subscribe(function(){})},n.prototype.preload=function(){var n=this.injector.get(kt);return this.processRoutes(n,this.router.config)},n.prototype.ngOnDestroy=function(){this.subscription.unsubscribe()},n.prototype.processRoutes=function(n,t){var e,l,r=[];try{for(var o=a(t),i=o.next();!i.done;i=o.next()){var u=i.value;if(u.loadChildren&&!u.canLoad&&u._loadedConfig){var s=u._loadedConfig;r.push(this.processRoutes(s.module,s.routes))}else u.loadChildren&&!u.canLoad?r.push(this.preloadConfig(n,u)):u.children&&r.push(this.processRoutes(n,u.children))}}catch(c){e={error:c}}finally{try{i&&!i.done&&(l=o.return)&&l.call(o)}finally{if(e)throw e.error}}return rn(r).pipe(cn(),nn(function(n){}))},n.prototype.preloadConfig=function(n,t){var e=this;return this.preloadingStrategy.preload(t,function(){return e.loader.load(n.injector,t).pipe(on(function(n){return t._loadedConfig=n,e.processRoutes(n.module,n.routes)}))})},n}(),Yh=function(){function n(n,t,e){void 0===e&&(e={}),this.router=n,this.viewportScroller=t,this.options=e,this.lastId=0,this.lastSource="imperative",this.restoredId=0,this.store={},e.scrollPositionRestoration=e.scrollPositionRestoration||"disabled",e.anchorScrolling=e.anchorScrolling||"disabled"}return n.prototype.init=function(){"disabled"!==this.options.scrollPositionRestoration&&this.viewportScroller.setHistoryScrollRestoration("manual"),this.routerEventsSubscription=this.createScrollEvents(),this.scrollEventsSubscription=this.consumeScrollEvents()},n.prototype.createScrollEvents=function(){var n=this;return this.router.events.subscribe(function(t){t instanceof xc?(n.store[n.lastId]=n.viewportScroller.getScrollPosition(),n.lastSource=t.navigationTrigger,n.restoredId=t.restoredState?t.restoredState.navigationId:0):t instanceof Pc&&(n.lastId=t.id,n.scheduleScrollEvent(t,n.router.parseUrl(t.urlAfterRedirects).fragment))})},n.prototype.consumeScrollEvents=function(){var n=this;return this.router.events.subscribe(function(t){t instanceof Fc&&(t.position?"top"===n.options.scrollPositionRestoration?n.viewportScroller.scrollToPosition([0,0]):"enabled"===n.options.scrollPositionRestoration&&n.viewportScroller.scrollToPosition(t.position):t.anchor&&"enabled"===n.options.anchorScrolling?n.viewportScroller.scrollToAnchor(t.anchor):"disabled"!==n.options.scrollPositionRestoration&&n.viewportScroller.scrollToPosition([0,0]))})},n.prototype.scheduleScrollEvent=function(n,t){this.router.triggerEvent(new Fc(n,"popstate"===this.lastSource?this.store[this.restoredId]:null,t))},n.prototype.ngOnDestroy=function(){this.routerEventsSubscription&&this.routerEventsSubscription.unsubscribe(),this.scrollEventsSubscription&&this.scrollEventsSubscription.unsubscribe()},n}(),Xh=new Sn("ROUTER_CONFIGURATION"),Jh=new Sn("ROUTER_FORROOT_GUARD"),nd=[Cu,{provide:cp,useClass:pp},{provide:Hh,useFactory:ud,deps:[dl,cp,qh,Cu,ut,ye,ze,Nh,Xh,[Vh,new Hn],[Rh,new Hn]]},qh,{provide:Ap,useFactory:ad,deps:[Hh]},{provide:ye,useClass:vl},Zh,Kh,$h,{provide:Xh,useValue:{enableTracing:!1}}];function td(){return new al("Router",Hh)}var ed=function(){function n(n,t){}var t;return t=n,n.forRoot=function(n,e){return{ngModule:t,providers:[nd,id(n),{provide:Jh,useFactory:od,deps:[[Hh,new Hn,new qn]]},{provide:Xh,useValue:e||{}},{provide:bu,useFactory:rd,deps:[vu,[new Bn(wu),new Hn],Xh]},{provide:Yh,useFactory:ld,deps:[Hh,Wu,Xh]},{provide:Qh,useExisting:e&&e.preloadingStrategy?e.preloadingStrategy:Kh},{provide:al,multi:!0,useFactory:td},[sd,{provide:Te,multi:!0,useFactory:cd,deps:[sd]},{provide:hd,useFactory:pd,deps:[sd]},{provide:Me,multi:!0,useExisting:hd}]]}},n.forChild=function(n){return{ngModule:t,providers:[id(n)]}},n}();function ld(n,t,e){return e.scrollOffset&&t.setOffset(e.scrollOffset),new Yh(n,t,e)}function rd(n,t,e){return void 0===e&&(e={}),e.useHash?new Eu(n,t):new xu(n,t)}function od(n){if(n)throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");return"guarded"}function id(n){return[{provide:Pn,multi:!0,useValue:n},{provide:Nh,multi:!0,useValue:n}]}function ud(n,t,e,l,r,o,i,u,a,s,c){void 0===a&&(a={});var p=new Hh(null,t,e,l,r,o,i,np(u));if(s&&(p.urlHandlingStrategy=s),c&&(p.routeReuseStrategy=c),a.errorHandler&&(p.errorHandler=a.errorHandler),a.malformedUriErrorHandler&&(p.malformedUriErrorHandler=a.malformedUriErrorHandler),a.enableTracing){var h=ms();p.events.subscribe(function(n){h.logGroup("Router Event: "+n.constructor.name),h.log(n.toString()),h.log(n),h.logGroupEnd()})}return a.onSameUrlNavigation&&(p.onSameUrlNavigation=a.onSameUrlNavigation),a.paramsInheritanceStrategy&&(p.paramsInheritanceStrategy=a.paramsInheritanceStrategy),a.urlUpdateStrategy&&(p.urlUpdateStrategy=a.urlUpdateStrategy),a.relativeLinkResolution&&(p.relativeLinkResolution=a.relativeLinkResolution),p}function ad(n){return n.routerState.root}var sd=function(){function n(n){this.injector=n,this.initNavigation=!1,this.resultOfPreactivationDone=new j}return n.prototype.appInitializer=function(){var n=this;return this.injector.get(_u,Promise.resolve(null)).then(function(){var t=null,e=new Promise(function(n){return t=n}),l=n.injector.get(Hh),r=n.injector.get(Xh);if(n.isLegacyDisabled(r)||n.isLegacyEnabled(r))t(!0);else if("disabled"===r.initialNavigation)l.setUpLocationChangeListener(),t(!0);else{if("enabled"!==r.initialNavigation)throw new Error("Invalid initialNavigation options: '"+r.initialNavigation+"'");l.hooks.afterPreactivation=function(){return n.initNavigation?du(null):(n.initNavigation=!0,t(!0),n.resultOfPreactivationDone)},l.initialNavigation()}return e})},n.prototype.bootstrapListener=function(n){var t=this.injector.get(Xh),e=this.injector.get(Zh),l=this.injector.get(Yh),r=this.injector.get(Hh),o=this.injector.get(dl);n===o.components[0]&&(this.isLegacyEnabled(t)?r.initialNavigation():this.isLegacyDisabled(t)&&r.setUpLocationChangeListener(),e.setUpPreloading(),l.init(),r.resetRootComponentType(o.componentTypes[0]),this.resultOfPreactivationDone.next(null),this.resultOfPreactivationDone.complete())},n.prototype.isLegacyEnabled=function(n){return"legacy_enabled"===n.initialNavigation||!0===n.initialNavigation||void 0===n.initialNavigation},n.prototype.isLegacyDisabled=function(n){return"legacy_disabled"===n.initialNavigation||!1===n.initialNavigation},n}();function cd(n){return n.appInitializer.bind(n)}function pd(n){return n.bootstrapListener.bind(n)}var hd=new Sn("Router Initializer"),dd=dr({encapsulation:2,styles:[],data:{}});function fd(n){return ei(0,[(n()(),Hr(0,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),Do(1,212992,null,0,Gh,[qh,bl,Tt,[8,null],Cl],null,null)],function(n,t){n(t,1,0)},null)}function gd(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"ng-component",[],null,null,null,fd,dd)),Do(1,49152,null,0,Bc,[],null,null)],null,null)}var md=io("ng-component",Bc,gd,{},{},[]),yd=['.jumbotron[_ngcontent-%COMP%]{background-color:#f4511e;color:#fff;padding:100px 25px}.container-fluid[_ngcontent-%COMP%]{padding:70px 0}.bg-grey[_ngcontent-%COMP%]{background-color:#f6f6f6}.logo-small[_ngcontent-%COMP%]{color:#f4511e;font-size:50px}.logo[_ngcontent-%COMP%]{color:#f4511e;font-size:200px}.thumbnail[_ngcontent-%COMP%]{padding:0 0 15px;border:none;border-radius:0}.thumbnail[_ngcontent-%COMP%] img[_ngcontent-%COMP%]{width:100%;height:100%;margin-bottom:10px}.carousel-control.left[_ngcontent-%COMP%], .carousel-control.right[_ngcontent-%COMP%]{background-image:none;color:#f4511e}.carousel-indicators[_ngcontent-%COMP%] li[_ngcontent-%COMP%]{border-color:#f4511e}.carousel-indicators[_ngcontent-%COMP%] li.active[_ngcontent-%COMP%]{background-color:#f4511e}.item[_ngcontent-%COMP%] h4[_ngcontent-%COMP%]{font-size:19px;line-height:1.375em;font-weight:400;font-style:italic;margin:70px 0}.item[_ngcontent-%COMP%] span[_ngcontent-%COMP%]{font-style:normal}.panel[_ngcontent-%COMP%]{border:1px solid #f4511e;border-radius:0!important;transition:box-shadow .5s}.panel[_ngcontent-%COMP%]:hover{box-shadow:5px 0 40px rgba(0,0,0,.2)}.panel-footer[_ngcontent-%COMP%] .btn[_ngcontent-%COMP%]:hover{border:1px solid #f4511e;background-color:#fff!important;color:#f4511e}.panel-heading[_ngcontent-%COMP%]{color:#fff!important;background-color:#f4511e!important;padding:25px;border-bottom:1px solid transparent;border-radius:0}.panel-footer[_ngcontent-%COMP%]{background-color:#fff!important}.panel-footer[_ngcontent-%COMP%] h3[_ngcontent-%COMP%]{font-size:32px}.panel-footer[_ngcontent-%COMP%] h4[_ngcontent-%COMP%]{color:#aaa;font-size:14px}.panel-footer[_ngcontent-%COMP%] .btn[_ngcontent-%COMP%]{margin:15px 0;background-color:#105a8c;color:#fff}.navbar[_ngcontent-%COMP%]{background-color:#105a8c!important;z-index:9999;border:0;font-size:12px!important;line-height:1.42857143!important;letter-spacing:4px;border-radius:0;position:fixed;left:0;margin:auto;width:1130px}.navbar[_ngcontent-%COMP%] .navbar-brand[_ngcontent-%COMP%], .navbar[_ngcontent-%COMP%] li[_ngcontent-%COMP%] a[_ngcontent-%COMP%]{color:#fff!important}.navbar-nav[_ngcontent-%COMP%] li[_ngcontent-%COMP%] a[_ngcontent-%COMP%]:hover, .navbar-nav[_ngcontent-%COMP%] li.active[_ngcontent-%COMP%] a[_ngcontent-%COMP%]{color:#f4511e!important;background-color:#fff!important}.navbar-default[_ngcontent-%COMP%] .navbar-toggle[_ngcontent-%COMP%]{border-color:transparent;background:#105a8c!important}footer[_ngcontent-%COMP%] .glyphicon[_ngcontent-%COMP%]{font-size:20px;margin-bottom:20px;color:#f4511e}@media screen and (max-width:1140px){.col-sm-4[_ngcontent-%COMP%]{text-align:center;margin:25px 0}}.divCell1[_ngcontent-%COMP%]{float:left;width:33.33%}.divCell2[_ngcontent-%COMP%]{float:left;width:100px}.divCell3[_ngcontent-%COMP%]{float:left;width:200px}.divCell4[_ngcontent-%COMP%]{float:left;width:33.33%}.divRow[_ngcontent-%COMP%]{content:"";clear:both;display:table}.button[_ngcontent-%COMP%]{background-color:#4caf50;border:none;color:#fff;padding:5px 20px;text-align:center;text-decoration:none;display:inline-block;font-size:12px;margin:1px;cursor:pointer}.buttonBlue[_ngcontent-%COMP%]{background-color:#008cba}.buttonGray[_ngcontent-%COMP%]{background-color:grey}.bgGray1[_ngcontent-%COMP%]{background-color:#607d8b}.bgGray2[_ngcontent-%COMP%]{background-color:azure}#tableType1[_ngcontent-%COMP%], #tableType2[_ngcontent-%COMP%]{font-family:Arial,Helvetica,sans-serif;border-collapse:collapse;box-align:center;width:100%;text-align:center}#tableType1[_ngcontent-%COMP%] td[_ngcontent-%COMP%], #tableType1[_ngcontent-%COMP%] th[_ngcontent-%COMP%], #tableType2[_ngcontent-%COMP%] td[_ngcontent-%COMP%], #tableType2[_ngcontent-%COMP%] th[_ngcontent-%COMP%]{border:1px solid #ddd;padding:8px}#tableType1[_ngcontent-%COMP%] tr[_ngcontent-%COMP%]:nth-child(even){background-color:#f2f2f2}#tableType1[_ngcontent-%COMP%] tr[_ngcontent-%COMP%]:hover{background-color:#ddd}#tableType1[_ngcontent-%COMP%] th[_ngcontent-%COMP%]{padding-top:8px;padding-bottom:8px;text-align:left;background-color:#789;color:#fff}.baseCss[_ngcontent-%COMP%]{margin:0 0 2em;list-style-type:none;padding:0;width:65em}.baseCss[_ngcontent-%COMP%] li[_ngcontent-%COMP%]{position:relative;cursor:pointer;background-color:#eee;margin:.5em;padding:.3em 0;height:1.6em;border-radius:4px}.baseCss[_ngcontent-%COMP%] li[_ngcontent-%COMP%]:hover{color:#607d8b;background-color:#ddd;left:.1em}.baseCss[_ngcontent-%COMP%] a[_ngcontent-%COMP%]{color:#888;text-decoration:none;position:relative;display:block;width:550px}.baseCss[_ngcontent-%COMP%] a[_ngcontent-%COMP%]:hover{color:#607d8b}.baseCss[_ngcontent-%COMP%] .badge[_ngcontent-%COMP%]{display:inline-block;font-size:small;color:#fff;padding:.8em .7em 0;background-color:#607d8b;line-height:1em;position:relative;left:-1px;top:-4px;height:1.8em;min-width:16px;text-align:right;margin-right:.8em;border-radius:4px 0 0 4px}.width1200[_ngcontent-%COMP%]{width:1000px}.width900[_ngcontent-%COMP%]{width:900px}.width1000[_ngcontent-%COMP%]{width:1000px}.width1100[_ngcontent-%COMP%]{width:1100px}.width300[_ngcontent-%COMP%]{width:300px}.screenHeading[_ngcontent-%COMP%]{font-size:16px;font-weight:700;text-align:center;padding-left:20px;padding-top:20px;color:#ffb82c}.divCenter500[_ngcontent-%COMP%]{margin:auto;width:500px}.divCenter1000[_ngcontent-%COMP%]{margin:auto;width:1000px}.divCenter900[_ngcontent-%COMP%]{margin:auto;width:100px}.floatleft[_ngcontent-%COMP%]{float:left}.floatClear[_ngcontent-%COMP%]{clear:both}'],vd=function(n){function t(t,e){var l=n.call(this,t)||this;l.sources=e,l.completed=0,l.haveValues=0;var r=e.length;l.values=new Array(r);for(var o=0;o<r;o++){var i=X(l,e[o],null,o);i&&l.add(i)}return l}return r(t,n),t.prototype.notifyNext=function(n,t,e,l,r){this.values[e]=t,r._hasValue||(r._hasValue=!0,this.haveValues++)},t.prototype.notifyComplete=function(n){var t=this.destination,e=this.haveValues,l=this.values,r=l.length;n._hasValue?(this.completed++,this.completed===r&&(e===r&&t.next(l),t.complete())):t.complete()},t}(J),_d=function(){function n(){}return Object.defineProperty(n.prototype,"value",{get:function(){return this.control?this.control.value:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"valid",{get:function(){return this.control?this.control.valid:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"invalid",{get:function(){return this.control?this.control.invalid:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"pending",{get:function(){return this.control?this.control.pending:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"disabled",{get:function(){return this.control?this.control.disabled:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"enabled",{get:function(){return this.control?this.control.enabled:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"errors",{get:function(){return this.control?this.control.errors:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"pristine",{get:function(){return this.control?this.control.pristine:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"dirty",{get:function(){return this.control?this.control.dirty:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"touched",{get:function(){return this.control?this.control.touched:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"status",{get:function(){return this.control?this.control.status:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"untouched",{get:function(){return this.control?this.control.untouched:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"statusChanges",{get:function(){return this.control?this.control.statusChanges:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"valueChanges",{get:function(){return this.control?this.control.valueChanges:null},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"path",{get:function(){return null},enumerable:!0,configurable:!0}),n.prototype.reset=function(n){void 0===n&&(n=void 0),this.control&&this.control.reset(n)},n.prototype.hasError=function(n,t){return!!this.control&&this.control.hasError(n,t)},n.prototype.getError=function(n,t){return this.control?this.control.getError(n,t):null},n}(),bd=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),Object.defineProperty(t.prototype,"formDirective",{get:function(){return null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return null},enumerable:!0,configurable:!0}),t}(_d);function wd(n){return null==n||0===n.length}var Cd=new Sn("NgValidators"),Sd=/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/,Ed=function(){function n(){}return n.min=function(n){return function(t){if(wd(t.value)||wd(n))return null;var e=parseFloat(t.value);return!isNaN(e)&&e<n?{min:{min:n,actual:t.value}}:null}},n.max=function(n){return function(t){if(wd(t.value)||wd(n))return null;var e=parseFloat(t.value);return!isNaN(e)&&e>n?{max:{max:n,actual:t.value}}:null}},n.required=function(n){return wd(n.value)?{required:!0}:null},n.requiredTrue=function(n){return!0===n.value?null:{required:!0}},n.email=function(n){return wd(n.value)?null:Sd.test(n.value)?null:{email:!0}},n.minLength=function(n){return function(t){if(wd(t.value))return null;var e=t.value?t.value.length:0;return e<n?{minlength:{requiredLength:n,actualLength:e}}:null}},n.maxLength=function(n){return function(t){var e=t.value?t.value.length:0;return e>n?{maxlength:{requiredLength:n,actualLength:e}}:null}},n.pattern=function(t){return t?("string"==typeof t?(l="","^"!==t.charAt(0)&&(l+="^"),l+=t,"$"!==t.charAt(t.length-1)&&(l+="$"),e=new RegExp(l)):(l=t.toString(),e=t),function(n){if(wd(n.value))return null;var t=n.value;return e.test(t)?null:{pattern:{requiredPattern:l,actualValue:t}}}):n.nullValidator;var e,l},n.nullValidator=function(n){return null},n.compose=function(n){if(!n)return null;var t=n.filter(xd);return 0==t.length?null:function(n){return Td(function(n,e){return t.map(function(t){return t(n)})}(n))}},n.composeAsync=function(n){if(!n)return null;var t=n.filter(xd);return 0==t.length?null:function(n){return function n(){for(var t,e=[],l=0;l<arguments.length;l++)e[l]=arguments[l];return"function"==typeof e[e.length-1]&&(t=e.pop()),1===e.length&&p(e[0])&&(e=e[0]),0===e.length?cu:t?n(e).pipe(nn(function(n){return t.apply(void 0,n)})):new R(function(n){return new vd(n,e)})}(function(n,e){return t.map(function(t){return t(n)})}(n).map(Pd)).pipe(nn(Td))}},n}();function xd(n){return null!=n}function Pd(n){var t=xe(n)?rn(n):n;if(!Pe(t))throw new Error("Expected validator to return Promise or Observable.");return t}function Td(n){var t=n.reduce(function(n,t){return null!=t?o({},n,t):n},{});return 0===Object.keys(t).length?null:t}var Id=new Sn("NgValueAccessor"),Od=function(){function n(n,t){this._renderer=n,this._elementRef=t,this.onChange=function(n){},this.onTouched=function(){}}return n.prototype.writeValue=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"checked",n)},n.prototype.registerOnChange=function(n){this.onChange=n},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n}(),kd=new Sn("CompositionEventMode"),Dd=function(){function n(n,t,e){var l;this._renderer=n,this._elementRef=t,this._compositionMode=e,this.onChange=function(n){},this.onTouched=function(){},this._composing=!1,null==this._compositionMode&&(this._compositionMode=(l=ms()?ms().getUserAgent():"",!/android (\d+)/.test(l.toLowerCase())))}return n.prototype.writeValue=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==n?"":n)},n.prototype.registerOnChange=function(n){this.onChange=n},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n.prototype._handleInput=function(n){(!this._compositionMode||this._compositionMode&&!this._composing)&&this.onChange(n)},n.prototype._compositionStart=function(){this._composing=!0},n.prototype._compositionEnd=function(n){this._composing=!1,this._compositionMode&&this.onChange(n)},n}();function Ad(n){return n.validate?function(t){return n.validate(t)}:n}function Rd(n){return n.validate?function(t){return n.validate(t)}:n}var Md=function(){function n(n,t){this._renderer=n,this._elementRef=t,this.onChange=function(n){},this.onTouched=function(){}}return n.prototype.writeValue=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"value",null==n?"":n)},n.prototype.registerOnChange=function(n){this.onChange=function(t){n(""==t?null:parseFloat(t))}},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n}();function Nd(){throw new Error("unimplemented")}var Ld=function(n){function t(){var t=null!==n&&n.apply(this,arguments)||this;return t._parent=null,t.name=null,t.valueAccessor=null,t._rawValidators=[],t._rawAsyncValidators=[],t}return r(t,n),Object.defineProperty(t.prototype,"validator",{get:function(){return Nd()},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"asyncValidator",{get:function(){return Nd()},enumerable:!0,configurable:!0}),t}(_d),Vd=function(){function n(){this._accessors=[]}return n.prototype.add=function(n,t){this._accessors.push([n,t])},n.prototype.remove=function(n){for(var t=this._accessors.length-1;t>=0;--t)if(this._accessors[t][1]===n)return void this._accessors.splice(t,1)},n.prototype.select=function(n){var t=this;this._accessors.forEach(function(e){t._isSameGroup(e,n)&&e[1]!==n&&e[1].fireUncheck(n.value)})},n.prototype._isSameGroup=function(n,t){return!!n[0].control&&n[0]._parent===t._control._parent&&n[1].name===t.name},n}(),Ud=function(){function n(n,t,e,l){this._renderer=n,this._elementRef=t,this._registry=e,this._injector=l,this.onChange=function(){},this.onTouched=function(){}}return n.prototype.ngOnInit=function(){this._control=this._injector.get(Ld),this._checkName(),this._registry.add(this._control,this)},n.prototype.ngOnDestroy=function(){this._registry.remove(this)},n.prototype.writeValue=function(n){this._state=n===this.value,this._renderer.setProperty(this._elementRef.nativeElement,"checked",this._state)},n.prototype.registerOnChange=function(n){var t=this;this._fn=n,this.onChange=function(){n(t.value),t._registry.select(t)}},n.prototype.fireUncheck=function(n){this.writeValue(n)},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n.prototype._checkName=function(){this.name&&this.formControlName&&this.name!==this.formControlName&&this._throwNameError(),!this.name&&this.formControlName&&(this.name=this.formControlName)},n.prototype._throwNameError=function(){throw new Error('\n If you define both a name and a formControlName attribute on your radio button, their values\n must match. Ex: <input type="radio" formControlName="food" name="food">\n ')},n}(),jd=function(){function n(n,t){this._renderer=n,this._elementRef=t,this.onChange=function(n){},this.onTouched=function(){}}return n.prototype.writeValue=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"value",parseFloat(n))},n.prototype.registerOnChange=function(n){this.onChange=function(t){n(""==t?null:parseFloat(t))}},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n}(),Fd='\n <div [formGroup]="myGroup">\n <div formGroupName="person">\n <input formControlName="firstName">\n </div>\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n person: new FormGroup({ firstName: new FormControl() })\n });',Bd='\n <form>\n <div ngModelGroup="person">\n <input [(ngModel)]="person.name" name="firstName">\n </div>\n </form>';function Hd(n,t){return null==n?""+t:(t&&"object"==typeof t&&(t="Object"),(n+": "+t).slice(0,50))}var zd=function(){function n(n,t){this._renderer=n,this._elementRef=t,this._optionMap=new Map,this._idCounter=0,this.onChange=function(n){},this.onTouched=function(){},this._compareWith=Mn}return Object.defineProperty(n.prototype,"compareWith",{set:function(n){if("function"!=typeof n)throw new Error("compareWith must be a function, but received "+JSON.stringify(n));this._compareWith=n},enumerable:!0,configurable:!0}),n.prototype.writeValue=function(n){this.value=n;var t=this._getOptionId(n);null==t&&this._renderer.setProperty(this._elementRef.nativeElement,"selectedIndex",-1);var e=Hd(t,n);this._renderer.setProperty(this._elementRef.nativeElement,"value",e)},n.prototype.registerOnChange=function(n){var t=this;this.onChange=function(e){t.value=t._getOptionValue(e),n(t.value)}},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n.prototype._registerOption=function(){return(this._idCounter++).toString()},n.prototype._getOptionId=function(n){var t,e;try{for(var l=a(Array.from(this._optionMap.keys())),r=l.next();!r.done;r=l.next()){var o=r.value;if(this._compareWith(this._optionMap.get(o),n))return o}}catch(i){t={error:i}}finally{try{r&&!r.done&&(e=l.return)&&e.call(l)}finally{if(t)throw t.error}}return null},n.prototype._getOptionValue=function(n){var t=function(n){return n.split(":")[0]}(n);return this._optionMap.has(t)?this._optionMap.get(t):n},n}(),qd=function(){function n(n,t,e){this._element=n,this._renderer=t,this._select=e,this._select&&(this.id=this._select._registerOption())}return Object.defineProperty(n.prototype,"ngValue",{set:function(n){null!=this._select&&(this._select._optionMap.set(this.id,n),this._setElementValue(Hd(this.id,n)),this._select.writeValue(this._select.value))},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"value",{set:function(n){this._setElementValue(n),this._select&&this._select.writeValue(this._select.value)},enumerable:!0,configurable:!0}),n.prototype._setElementValue=function(n){this._renderer.setProperty(this._element.nativeElement,"value",n)},n.prototype.ngOnDestroy=function(){this._select&&(this._select._optionMap.delete(this.id),this._select.writeValue(this._select.value))},n}();function Gd(n,t){return null==n?""+t:("string"==typeof t&&(t="'"+t+"'"),t&&"object"==typeof t&&(t="Object"),(n+": "+t).slice(0,50))}var Wd=function(){function n(n,t){this._renderer=n,this._elementRef=t,this._optionMap=new Map,this._idCounter=0,this.onChange=function(n){},this.onTouched=function(){},this._compareWith=Mn}return Object.defineProperty(n.prototype,"compareWith",{set:function(n){if("function"!=typeof n)throw new Error("compareWith must be a function, but received "+JSON.stringify(n));this._compareWith=n},enumerable:!0,configurable:!0}),n.prototype.writeValue=function(n){var t,e=this;if(this.value=n,Array.isArray(n)){var l=n.map(function(n){return e._getOptionId(n)});t=function(n,t){n._setSelected(l.indexOf(t.toString())>-1)}}else t=function(n,t){n._setSelected(!1)};this._optionMap.forEach(t)},n.prototype.registerOnChange=function(n){var t=this;this.onChange=function(e){var l=[];if(e.hasOwnProperty("selectedOptions"))for(var r=e.selectedOptions,o=0;o<r.length;o++){var i=r.item(o),u=t._getOptionValue(i.value);l.push(u)}else for(r=e.options,o=0;o<r.length;o++)(i=r.item(o)).selected&&(u=t._getOptionValue(i.value),l.push(u));t.value=l,n(l)}},n.prototype.registerOnTouched=function(n){this.onTouched=n},n.prototype.setDisabledState=function(n){this._renderer.setProperty(this._elementRef.nativeElement,"disabled",n)},n.prototype._registerOption=function(n){var t=(this._idCounter++).toString();return this._optionMap.set(t,n),t},n.prototype._getOptionId=function(n){var t,e;try{for(var l=a(Array.from(this._optionMap.keys())),r=l.next();!r.done;r=l.next()){var o=r.value;if(this._compareWith(this._optionMap.get(o)._value,n))return o}}catch(i){t={error:i}}finally{try{r&&!r.done&&(e=l.return)&&e.call(l)}finally{if(t)throw t.error}}return null},n.prototype._getOptionValue=function(n){var t=function(n){return n.split(":")[0]}(n);return this._optionMap.has(t)?this._optionMap.get(t)._value:n},n}(),Qd=function(){function n(n,t,e){this._element=n,this._renderer=t,this._select=e,this._select&&(this.id=this._select._registerOption(this))}return Object.defineProperty(n.prototype,"ngValue",{set:function(n){null!=this._select&&(this._value=n,this._setElementValue(Gd(this.id,n)),this._select.writeValue(this._select.value))},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"value",{set:function(n){this._select?(this._value=n,this._setElementValue(Gd(this.id,n)),this._select.writeValue(this._select.value)):this._setElementValue(n)},enumerable:!0,configurable:!0}),n.prototype._setElementValue=function(n){this._renderer.setProperty(this._element.nativeElement,"value",n)},n.prototype._setSelected=function(n){this._renderer.setProperty(this._element.nativeElement,"selected",n)},n.prototype.ngOnDestroy=function(){this._select&&(this._select._optionMap.delete(this.id),this._select.writeValue(this._select.value))},n}();function $d(n,t){return c(t.path,[n])}function Kd(n,t){n||Yd(t,"Cannot find control with"),t.valueAccessor||Yd(t,"No value accessor for form control with"),n.validator=Ed.compose([n.validator,t.validator]),n.asyncValidator=Ed.composeAsync([n.asyncValidator,t.asyncValidator]),t.valueAccessor.writeValue(n.value),function(n,t){t.valueAccessor.registerOnChange(function(e){n._pendingValue=e,n._pendingChange=!0,n._pendingDirty=!0,"change"===n.updateOn&&Zd(n,t)})}(n,t),function(n,t){n.registerOnChange(function(n,e){t.valueAccessor.writeValue(n),e&&t.viewToModelUpdate(n)})}(n,t),function(n,t){t.valueAccessor.registerOnTouched(function(){n._pendingTouched=!0,"blur"===n.updateOn&&n._pendingChange&&Zd(n,t),"submit"!==n.updateOn&&n.markAsTouched()})}(n,t),t.valueAccessor.setDisabledState&&n.registerOnDisabledChange(function(n){t.valueAccessor.setDisabledState(n)}),t._rawValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(function(){return n.updateValueAndValidity()})}),t._rawAsyncValidators.forEach(function(t){t.registerOnValidatorChange&&t.registerOnValidatorChange(function(){return n.updateValueAndValidity()})})}function Zd(n,t){n._pendingDirty&&n.markAsDirty(),n.setValue(n._pendingValue,{emitModelToViewChange:!1}),t.viewToModelUpdate(n._pendingValue),n._pendingChange=!1}function Yd(n,t){var e;throw e=n.path.length>1?"path: '"+n.path.join(" -> ")+"'":n.path[0]?"name: '"+n.path+"'":"unspecified name attribute",new Error(t+" "+e)}function Xd(n){return null!=n?Ed.compose(n.map(Ad)):null}function Jd(n){return null!=n?Ed.composeAsync(n.map(Rd)):null}var nf=[Od,jd,Md,zd,Wd,Ud],tf=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.ngOnInit=function(){this._checkParentType(),this.formDirective.addFormGroup(this)},t.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeFormGroup(this)},Object.defineProperty(t.prototype,"control",{get:function(){return this.formDirective.getFormGroup(this)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return $d(this.name,this._parent)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"validator",{get:function(){return Xd(this._validators)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"asyncValidator",{get:function(){return Jd(this._asyncValidators)},enumerable:!0,configurable:!0}),t.prototype._checkParentType=function(){},t}(bd),ef=function(n){function t(t){return n.call(this,t)||this}return r(t,n),t}(function(){function n(n){this._cd=n}return Object.defineProperty(n.prototype,"ngClassUntouched",{get:function(){return!!this._cd.control&&this._cd.control.untouched},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassTouched",{get:function(){return!!this._cd.control&&this._cd.control.touched},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassPristine",{get:function(){return!!this._cd.control&&this._cd.control.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassDirty",{get:function(){return!!this._cd.control&&this._cd.control.dirty},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassValid",{get:function(){return!!this._cd.control&&this._cd.control.valid},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassInvalid",{get:function(){return!!this._cd.control&&this._cd.control.invalid},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"ngClassPending",{get:function(){return!!this._cd.control&&this._cd.control.pending},enumerable:!0,configurable:!0}),n}());function lf(n){var t=of(n)?n.validators:n;return Array.isArray(t)?Xd(t):t||null}function rf(n,t){var e=of(t)?t.asyncValidators:n;return Array.isArray(e)?Jd(e):e||null}function of(n){return null!=n&&!Array.isArray(n)&&"object"==typeof n}var uf=function(){function n(n,t){this.validator=n,this.asyncValidator=t,this._onCollectionChange=function(){},this.pristine=!0,this.touched=!1,this._onDisabledChange=[]}return Object.defineProperty(n.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"valid",{get:function(){return"VALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"invalid",{get:function(){return"INVALID"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"pending",{get:function(){return"PENDING"==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"disabled",{get:function(){return"DISABLED"===this.status},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"enabled",{get:function(){return"DISABLED"!==this.status},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"dirty",{get:function(){return!this.pristine},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"untouched",{get:function(){return!this.touched},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"updateOn",{get:function(){return this._updateOn?this._updateOn:this.parent?this.parent.updateOn:"change"},enumerable:!0,configurable:!0}),n.prototype.setValidators=function(n){this.validator=lf(n)},n.prototype.setAsyncValidators=function(n){this.asyncValidator=rf(n)},n.prototype.clearValidators=function(){this.validator=null},n.prototype.clearAsyncValidators=function(){this.asyncValidator=null},n.prototype.markAsTouched=function(n){void 0===n&&(n={}),this.touched=!0,this._parent&&!n.onlySelf&&this._parent.markAsTouched(n)},n.prototype.markAsUntouched=function(n){void 0===n&&(n={}),this.touched=!1,this._pendingTouched=!1,this._forEachChild(function(n){n.markAsUntouched({onlySelf:!0})}),this._parent&&!n.onlySelf&&this._parent._updateTouched(n)},n.prototype.markAsDirty=function(n){void 0===n&&(n={}),this.pristine=!1,this._parent&&!n.onlySelf&&this._parent.markAsDirty(n)},n.prototype.markAsPristine=function(n){void 0===n&&(n={}),this.pristine=!0,this._pendingDirty=!1,this._forEachChild(function(n){n.markAsPristine({onlySelf:!0})}),this._parent&&!n.onlySelf&&this._parent._updatePristine(n)},n.prototype.markAsPending=function(n){void 0===n&&(n={}),this.status="PENDING",!1!==n.emitEvent&&this.statusChanges.emit(this.status),this._parent&&!n.onlySelf&&this._parent.markAsPending(n)},n.prototype.disable=function(n){void 0===n&&(n={}),this.status="DISABLED",this.errors=null,this._forEachChild(function(t){t.disable(o({},n,{onlySelf:!0}))}),this._updateValue(),!1!==n.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._updateAncestors(n),this._onDisabledChange.forEach(function(n){return n(!0)})},n.prototype.enable=function(n){void 0===n&&(n={}),this.status="VALID",this._forEachChild(function(t){t.enable(o({},n,{onlySelf:!0}))}),this.updateValueAndValidity({onlySelf:!0,emitEvent:n.emitEvent}),this._updateAncestors(n),this._onDisabledChange.forEach(function(n){return n(!1)})},n.prototype._updateAncestors=function(n){this._parent&&!n.onlySelf&&(this._parent.updateValueAndValidity(n),this._parent._updatePristine(),this._parent._updateTouched())},n.prototype.setParent=function(n){this._parent=n},n.prototype.updateValueAndValidity=function(n){void 0===n&&(n={}),this._setInitialStatus(),this._updateValue(),this.enabled&&(this._cancelExistingSubscription(),this.errors=this._runValidator(),this.status=this._calculateStatus(),"VALID"!==this.status&&"PENDING"!==this.status||this._runAsyncValidator(n.emitEvent)),!1!==n.emitEvent&&(this.valueChanges.emit(this.value),this.statusChanges.emit(this.status)),this._parent&&!n.onlySelf&&this._parent.updateValueAndValidity(n)},n.prototype._updateTreeValidity=function(n){void 0===n&&(n={emitEvent:!0}),this._forEachChild(function(t){return t._updateTreeValidity(n)}),this.updateValueAndValidity({onlySelf:!0,emitEvent:n.emitEvent})},n.prototype._setInitialStatus=function(){this.status=this._allControlsDisabled()?"DISABLED":"VALID"},n.prototype._runValidator=function(){return this.validator?this.validator(this):null},n.prototype._runAsyncValidator=function(n){var t=this;if(this.asyncValidator){this.status="PENDING";var e=Pd(this.asyncValidator(this));this._asyncValidationSubscription=e.subscribe(function(e){return t.setErrors(e,{emitEvent:n})})}},n.prototype._cancelExistingSubscription=function(){this._asyncValidationSubscription&&this._asyncValidationSubscription.unsubscribe()},n.prototype.setErrors=function(n,t){void 0===t&&(t={}),this.errors=n,this._updateControlsErrors(!1!==t.emitEvent)},n.prototype.get=function(n){return function(n,t,e){return null==t?null:(t instanceof Array||(t=t.split(".")),t instanceof Array&&0===t.length?null:t.reduce(function(n,t){return n instanceof sf?n.controls.hasOwnProperty(t)?n.controls[t]:null:n instanceof cf&&n.at(t)||null},n))}(this,n)},n.prototype.getError=function(n,t){var e=t?this.get(t):this;return e&&e.errors?e.errors[n]:null},n.prototype.hasError=function(n,t){return!!this.getError(n,t)},Object.defineProperty(n.prototype,"root",{get:function(){for(var n=this;n._parent;)n=n._parent;return n},enumerable:!0,configurable:!0}),n.prototype._updateControlsErrors=function(n){this.status=this._calculateStatus(),n&&this.statusChanges.emit(this.status),this._parent&&this._parent._updateControlsErrors(n)},n.prototype._initObservables=function(){this.valueChanges=new he,this.statusChanges=new he},n.prototype._calculateStatus=function(){return this._allControlsDisabled()?"DISABLED":this.errors?"INVALID":this._anyControlsHaveStatus("PENDING")?"PENDING":this._anyControlsHaveStatus("INVALID")?"INVALID":"VALID"},n.prototype._anyControlsHaveStatus=function(n){return this._anyControls(function(t){return t.status===n})},n.prototype._anyControlsDirty=function(){return this._anyControls(function(n){return n.dirty})},n.prototype._anyControlsTouched=function(){return this._anyControls(function(n){return n.touched})},n.prototype._updatePristine=function(n){void 0===n&&(n={}),this.pristine=!this._anyControlsDirty(),this._parent&&!n.onlySelf&&this._parent._updatePristine(n)},n.prototype._updateTouched=function(n){void 0===n&&(n={}),this.touched=this._anyControlsTouched(),this._parent&&!n.onlySelf&&this._parent._updateTouched(n)},n.prototype._isBoxedValue=function(n){return"object"==typeof n&&null!==n&&2===Object.keys(n).length&&"value"in n&&"disabled"in n},n.prototype._registerOnCollectionChange=function(n){this._onCollectionChange=n},n.prototype._setUpdateStrategy=function(n){of(n)&&null!=n.updateOn&&(this._updateOn=n.updateOn)},n}(),af=function(n){function t(t,e,l){void 0===t&&(t=null);var r=n.call(this,lf(e),rf(l,e))||this;return r._onChange=[],r._applyFormState(t),r._setUpdateStrategy(e),r.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),r._initObservables(),r}return r(t,n),t.prototype.setValue=function(n,t){var e=this;void 0===t&&(t={}),this.value=this._pendingValue=n,this._onChange.length&&!1!==t.emitModelToViewChange&&this._onChange.forEach(function(n){return n(e.value,!1!==t.emitViewToModelChange)}),this.updateValueAndValidity(t)},t.prototype.patchValue=function(n,t){void 0===t&&(t={}),this.setValue(n,t)},t.prototype.reset=function(n,t){void 0===n&&(n=null),void 0===t&&(t={}),this._applyFormState(n),this.markAsPristine(t),this.markAsUntouched(t),this.setValue(this.value,t),this._pendingChange=!1},t.prototype._updateValue=function(){},t.prototype._anyControls=function(n){return!1},t.prototype._allControlsDisabled=function(){return this.disabled},t.prototype.registerOnChange=function(n){this._onChange.push(n)},t.prototype._clearChangeFns=function(){this._onChange=[],this._onDisabledChange=[],this._onCollectionChange=function(){}},t.prototype.registerOnDisabledChange=function(n){this._onDisabledChange.push(n)},t.prototype._forEachChild=function(n){},t.prototype._syncPendingControls=function(){return!("submit"!==this.updateOn||(this._pendingDirty&&this.markAsDirty(),this._pendingTouched&&this.markAsTouched(),!this._pendingChange)||(this.setValue(this._pendingValue,{onlySelf:!0,emitModelToViewChange:!1}),0))},t.prototype._applyFormState=function(n){this._isBoxedValue(n)?(this.value=this._pendingValue=n.value,n.disabled?this.disable({onlySelf:!0,emitEvent:!1}):this.enable({onlySelf:!0,emitEvent:!1})):this.value=this._pendingValue=n},t}(uf),sf=function(n){function t(t,e,l){var r=n.call(this,lf(e),rf(l,e))||this;return r.controls=t,r._initObservables(),r._setUpdateStrategy(e),r._setUpControls(),r.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),r}return r(t,n),t.prototype.registerControl=function(n,t){return this.controls[n]?this.controls[n]:(this.controls[n]=t,t.setParent(this),t._registerOnCollectionChange(this._onCollectionChange),t)},t.prototype.addControl=function(n,t){this.registerControl(n,t),this.updateValueAndValidity(),this._onCollectionChange()},t.prototype.removeControl=function(n){this.controls[n]&&this.controls[n]._registerOnCollectionChange(function(){}),delete this.controls[n],this.updateValueAndValidity(),this._onCollectionChange()},t.prototype.setControl=function(n,t){this.controls[n]&&this.controls[n]._registerOnCollectionChange(function(){}),delete this.controls[n],t&&this.registerControl(n,t),this.updateValueAndValidity(),this._onCollectionChange()},t.prototype.contains=function(n){return this.controls.hasOwnProperty(n)&&this.controls[n].enabled},t.prototype.setValue=function(n,t){var e=this;void 0===t&&(t={}),this._checkAllValuesPresent(n),Object.keys(n).forEach(function(l){e._throwIfControlMissing(l),e.controls[l].setValue(n[l],{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t)},t.prototype.patchValue=function(n,t){var e=this;void 0===t&&(t={}),Object.keys(n).forEach(function(l){e.controls[l]&&e.controls[l].patchValue(n[l],{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t)},t.prototype.reset=function(n,t){void 0===n&&(n={}),void 0===t&&(t={}),this._forEachChild(function(e,l){e.reset(n[l],{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t),this._updatePristine(t),this._updateTouched(t)},t.prototype.getRawValue=function(){return this._reduceChildren({},function(n,t,e){return n[e]=t instanceof af?t.value:t.getRawValue(),n})},t.prototype._syncPendingControls=function(){var n=this._reduceChildren(!1,function(n,t){return!!t._syncPendingControls()||n});return n&&this.updateValueAndValidity({onlySelf:!0}),n},t.prototype._throwIfControlMissing=function(n){if(!Object.keys(this.controls).length)throw new Error("\n There are no form controls registered with this group yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.controls[n])throw new Error("Cannot find form control with name: "+n+".")},t.prototype._forEachChild=function(n){var t=this;Object.keys(this.controls).forEach(function(e){return n(t.controls[e],e)})},t.prototype._setUpControls=function(){var n=this;this._forEachChild(function(t){t.setParent(n),t._registerOnCollectionChange(n._onCollectionChange)})},t.prototype._updateValue=function(){this.value=this._reduceValue()},t.prototype._anyControls=function(n){var t=this,e=!1;return this._forEachChild(function(l,r){e=e||t.contains(r)&&n(l)}),e},t.prototype._reduceValue=function(){var n=this;return this._reduceChildren({},function(t,e,l){return(e.enabled||n.disabled)&&(t[l]=e.value),t})},t.prototype._reduceChildren=function(n,t){var e=n;return this._forEachChild(function(n,l){e=t(e,n,l)}),e},t.prototype._allControlsDisabled=function(){var n,t;try{for(var e=a(Object.keys(this.controls)),l=e.next();!l.done;l=e.next())if(this.controls[l.value].enabled)return!1}catch(r){n={error:r}}finally{try{l&&!l.done&&(t=e.return)&&t.call(e)}finally{if(n)throw n.error}}return Object.keys(this.controls).length>0||this.disabled},t.prototype._checkAllValuesPresent=function(n){this._forEachChild(function(t,e){if(void 0===n[e])throw new Error("Must supply a value for form control with name: '"+e+"'.")})},t}(uf),cf=function(n){function t(t,e,l){var r=n.call(this,lf(e),rf(l,e))||this;return r.controls=t,r._initObservables(),r._setUpdateStrategy(e),r._setUpControls(),r.updateValueAndValidity({onlySelf:!0,emitEvent:!1}),r}return r(t,n),t.prototype.at=function(n){return this.controls[n]},t.prototype.push=function(n){this.controls.push(n),this._registerControl(n),this.updateValueAndValidity(),this._onCollectionChange()},t.prototype.insert=function(n,t){this.controls.splice(n,0,t),this._registerControl(t),this.updateValueAndValidity()},t.prototype.removeAt=function(n){this.controls[n]&&this.controls[n]._registerOnCollectionChange(function(){}),this.controls.splice(n,1),this.updateValueAndValidity()},t.prototype.setControl=function(n,t){this.controls[n]&&this.controls[n]._registerOnCollectionChange(function(){}),this.controls.splice(n,1),t&&(this.controls.splice(n,0,t),this._registerControl(t)),this.updateValueAndValidity(),this._onCollectionChange()},Object.defineProperty(t.prototype,"length",{get:function(){return this.controls.length},enumerable:!0,configurable:!0}),t.prototype.setValue=function(n,t){var e=this;void 0===t&&(t={}),this._checkAllValuesPresent(n),n.forEach(function(n,l){e._throwIfControlMissing(l),e.at(l).setValue(n,{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t)},t.prototype.patchValue=function(n,t){var e=this;void 0===t&&(t={}),n.forEach(function(n,l){e.at(l)&&e.at(l).patchValue(n,{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t)},t.prototype.reset=function(n,t){void 0===n&&(n=[]),void 0===t&&(t={}),this._forEachChild(function(e,l){e.reset(n[l],{onlySelf:!0,emitEvent:t.emitEvent})}),this.updateValueAndValidity(t),this._updatePristine(t),this._updateTouched(t)},t.prototype.getRawValue=function(){return this.controls.map(function(n){return n instanceof af?n.value:n.getRawValue()})},t.prototype._syncPendingControls=function(){var n=this.controls.reduce(function(n,t){return!!t._syncPendingControls()||n},!1);return n&&this.updateValueAndValidity({onlySelf:!0}),n},t.prototype._throwIfControlMissing=function(n){if(!this.controls.length)throw new Error("\n There are no form controls registered with this array yet. If you're using ngModel,\n you may want to check next tick (e.g. use setTimeout).\n ");if(!this.at(n))throw new Error("Cannot find form control at index "+n)},t.prototype._forEachChild=function(n){this.controls.forEach(function(t,e){n(t,e)})},t.prototype._updateValue=function(){var n=this;this.value=this.controls.filter(function(t){return t.enabled||n.disabled}).map(function(n){return n.value})},t.prototype._anyControls=function(n){return this.controls.some(function(t){return t.enabled&&n(t)})},t.prototype._setUpControls=function(){var n=this;this._forEachChild(function(t){return n._registerControl(t)})},t.prototype._checkAllValuesPresent=function(n){this._forEachChild(function(t,e){if(void 0===n[e])throw new Error("Must supply a value for form control at index: "+e+".")})},t.prototype._allControlsDisabled=function(){var n,t;try{for(var e=a(this.controls),l=e.next();!l.done;l=e.next())if(l.value.enabled)return!1}catch(r){n={error:r}}finally{try{l&&!l.done&&(t=e.return)&&t.call(e)}finally{if(n)throw n.error}}return this.controls.length>0||this.disabled},t.prototype._registerControl=function(n){n.setParent(this),n._registerOnCollectionChange(this._onCollectionChange)},t}(uf),pf=Promise.resolve(null),hf=function(n){function t(t,e){var l=n.call(this)||this;return l.submitted=!1,l._directives=[],l.ngSubmit=new he,l.form=new sf({},Xd(t),Jd(e)),l}return r(t,n),t.prototype.ngAfterViewInit=function(){this._setUpdateStrategy()},Object.defineProperty(t.prototype,"formDirective",{get:function(){return this},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"control",{get:function(){return this.form},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"path",{get:function(){return[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"controls",{get:function(){return this.form.controls},enumerable:!0,configurable:!0}),t.prototype.addControl=function(n){var t=this;pf.then(function(){var e=t._findContainer(n.path);n.control=e.registerControl(n.name,n.control),Kd(n.control,n),n.control.updateValueAndValidity({emitEvent:!1}),t._directives.push(n)})},t.prototype.getControl=function(n){return this.form.get(n.path)},t.prototype.removeControl=function(n){var t=this;pf.then(function(){var e,l,r=t._findContainer(n.path);r&&r.removeControl(n.name),(l=(e=t._directives).indexOf(n))>-1&&e.splice(l,1)})},t.prototype.addFormGroup=function(n){var t=this;pf.then(function(){var e=t._findContainer(n.path),l=new sf({});(function(n,t){null==n&&Yd(t,"Cannot find control with"),n.validator=Ed.compose([n.validator,t.validator]),n.asyncValidator=Ed.composeAsync([n.asyncValidator,t.asyncValidator])})(l,n),e.registerControl(n.name,l),l.updateValueAndValidity({emitEvent:!1})})},t.prototype.removeFormGroup=function(n){var t=this;pf.then(function(){var e=t._findContainer(n.path);e&&e.removeControl(n.name)})},t.prototype.getFormGroup=function(n){return this.form.get(n.path)},t.prototype.updateModel=function(n,t){var e=this;pf.then(function(){e.form.get(n.path).setValue(t)})},t.prototype.setValue=function(n){this.control.setValue(n)},t.prototype.onSubmit=function(n){return this.submitted=!0,t=this._directives,this.form._syncPendingControls(),t.forEach(function(n){var t=n.control;"submit"===t.updateOn&&t._pendingChange&&(n.viewToModelUpdate(t._pendingValue),t._pendingChange=!1)}),this.ngSubmit.emit(n),!1;var t},t.prototype.onReset=function(){this.resetForm()},t.prototype.resetForm=function(n){void 0===n&&(n=void 0),this.form.reset(n),this.submitted=!1},t.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.form._updateOn=this.options.updateOn)},t.prototype._findContainer=function(n){return n.pop(),n.length?this.form.get(n):this.form},t}(bd),df=function(){function n(){}return n.modelParentException=function(){throw new Error('\n ngModel cannot be used to register form controls with a parent formGroup directive. Try using\n formGroup\'s partner directive "formControlName" instead. Example:\n\n \n <div [formGroup]="myGroup">\n <input formControlName="firstName">\n </div>\n\n In your class:\n\n this.myGroup = new FormGroup({\n firstName: new FormControl()\n });\n\n Or, if you\'d like to avoid registering this form control, indicate that it\'s standalone in ngModelOptions:\n\n Example:\n\n \n <div [formGroup]="myGroup">\n <input formControlName="firstName">\n <input [(ngModel)]="showMoreControls" [ngModelOptions]="{standalone: true}">\n </div>\n ')},n.formGroupNameException=function(){throw new Error("\n ngModel cannot be used to register form controls with a parent formGroupName or formArrayName directive.\n\n Option 1: Use formControlName instead of ngModel (reactive strategy):\n\n "+Fd+"\n\n Option 2: Update ngModel's parent be ngModelGroup (template-driven strategy):\n\n "+Bd)},n.missingNameException=function(){throw new Error('If ngModel is used within a form tag, either the name attribute must be set or the form\n control must be defined as \'standalone\' in ngModelOptions.\n\n Example 1: <input [(ngModel)]="person.firstName" name="first">\n Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">')},n.modelGroupParentException=function(){throw new Error("\n ngModelGroup cannot be used with a parent formGroup directive.\n\n Option 1: Use formGroupName instead of ngModelGroup (reactive strategy):\n\n "+Fd+"\n\n Option 2: Use a regular form tag instead of the formGroup directive (template-driven strategy):\n\n "+Bd)},n.ngFormWarning=function(){console.warn("\n It looks like you're using 'ngForm'.\n\n Support for using the 'ngForm' element selector has been deprecated in Angular v6 and will be removed\n in Angular v9.\n\n Use 'ng-form' instead.\n\n Before:\n <ngForm #myForm=\"ngForm\">\n\n After:\n <ng-form #myForm=\"ngForm\">\n ")},n}(),ff=new Sn("NgFormSelectorWarning"),gf=function(n){function t(t,e,l){var r=n.call(this)||this;return r._parent=t,r._validators=e,r._asyncValidators=l,r}var e;return r(t,n),e=t,t.prototype._checkParentType=function(){this._parent instanceof e||this._parent instanceof hf||df.modelGroupParentException()},t}(tf),mf=Promise.resolve(null),yf=function(n){function t(t,e,l,r){var o=n.call(this)||this;return o.control=new af,o._registered=!1,o.update=new he,o._parent=t,o._rawValidators=e||[],o._rawAsyncValidators=l||[],o.valueAccessor=function(n,t){if(!t)return null;Array.isArray(t)||Yd(n,"Value accessor was not provided as an array for form control with");var e=void 0,l=void 0,r=void 0;return t.forEach(function(t){var o;t.constructor===Dd?e=t:(o=t,nf.some(function(n){return o.constructor===n})?(l&&Yd(n,"More than one built-in value accessor matches form control with"),l=t):(r&&Yd(n,"More than one custom value accessor matches form control with"),r=t))}),r||l||e||(Yd(n,"No valid value accessor for form control with"),null)}(o,r),o}return r(t,n),t.prototype.ngOnChanges=function(n){this._checkForErrors(),this._registered||this._setUpControl(),"isDisabled"in n&&this._updateDisabled(n),function(n,t){if(!n.hasOwnProperty("model"))return!1;var e=n.model;return!!e.isFirstChange()||!Mn(t,e.currentValue)}(n,this.viewModel)&&(this._updateValue(this.model),this.viewModel=this.model)},t.prototype.ngOnDestroy=function(){this.formDirective&&this.formDirective.removeControl(this)},Object.defineProperty(t.prototype,"path",{get:function(){return this._parent?$d(this.name,this._parent):[this.name]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"formDirective",{get:function(){return this._parent?this._parent.formDirective:null},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"validator",{get:function(){return Xd(this._rawValidators)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"asyncValidator",{get:function(){return Jd(this._rawAsyncValidators)},enumerable:!0,configurable:!0}),t.prototype.viewToModelUpdate=function(n){this.viewModel=n,this.update.emit(n)},t.prototype._setUpControl=function(){this._setUpdateStrategy(),this._isStandalone()?this._setUpStandalone():this.formDirective.addControl(this),this._registered=!0},t.prototype._setUpdateStrategy=function(){this.options&&null!=this.options.updateOn&&(this.control._updateOn=this.options.updateOn)},t.prototype._isStandalone=function(){return!this._parent||!(!this.options||!this.options.standalone)},t.prototype._setUpStandalone=function(){Kd(this.control,this),this.control.updateValueAndValidity({emitEvent:!1})},t.prototype._checkForErrors=function(){this._isStandalone()||this._checkParentType(),this._checkName()},t.prototype._checkParentType=function(){!(this._parent instanceof gf)&&this._parent instanceof tf?df.formGroupNameException():this._parent instanceof gf||this._parent instanceof hf||df.modelParentException()},t.prototype._checkName=function(){this.options&&this.options.name&&(this.name=this.options.name),this._isStandalone()||this.name||df.missingNameException()},t.prototype._updateValue=function(n){var t=this;mf.then(function(){t.control.setValue(n,{emitViewToModelChange:!1})})},t.prototype._updateDisabled=function(n){var t=this,e=n.isDisabled.currentValue,l=""===e||e&&"false"!==e;mf.then(function(){l&&!t.control.disabled?t.control.disable():!l&&t.control.disabled&&t.control.enable()})},t}(Ld),vf=new Sn("NgModelWithFormControlWarning"),_f=function(){function n(){}return Object.defineProperty(n.prototype,"required",{get:function(){return this._required},set:function(n){this._required=null!=n&&!1!==n&&""+n!="false",this._onChange&&this._onChange()},enumerable:!0,configurable:!0}),n.prototype.validate=function(n){return this.required?Ed.required(n):null},n.prototype.registerOnValidatorChange=function(n){this._onChange=n},n}(),bf=function(){function n(){}return n.prototype.group=function(n,t){void 0===t&&(t=null);var e=this._reduceControls(n),l=null,r=null,o=void 0;return null!=t&&(function(n){return void 0!==n.asyncValidators||void 0!==n.validators||void 0!==n.updateOn}(t)?(l=null!=t.validators?t.validators:null,r=null!=t.asyncValidators?t.asyncValidators:null,o=null!=t.updateOn?t.updateOn:void 0):(l=null!=t.validator?t.validator:null,r=null!=t.asyncValidator?t.asyncValidator:null)),new sf(e,{asyncValidators:r,updateOn:o,validators:l})},n.prototype.control=function(n,t,e){return new af(n,t,e)},n.prototype.array=function(n,t,e){var l=this,r=n.map(function(n){return l._createControl(n)});return new cf(r,t,e)},n.prototype._reduceControls=function(n){var t=this,e={};return Object.keys(n).forEach(function(l){e[l]=t._createControl(n[l])}),e},n.prototype._createControl=function(n){return n instanceof af||n instanceof sf||n instanceof cf?n:Array.isArray(n)?this.control(n[0],n.length>1?n[1]:null,n.length>2?n[2]:null):this.control(n)},n}(),wf=function(){return function(){}}(),Cf=function(){function n(){}var t;return t=n,n.withConfig=function(n){return{ngModule:t,providers:[{provide:ff,useValue:n.warnOnDeprecatedNgFormSelector}]}},n}(),Sf=function(){function n(){}var t;return t=n,n.withConfig=function(n){return{ngModule:t,providers:[{provide:vf,useValue:n.warnOnNgModelWithFormControl}]}},n}(),Ef=function(){function n(n,t){this.authService=n,this.router=t,this.username="user1",this.password="user1",this.invalidLogin=!1}return n.prototype.ngOnInit=function(){},n.prototype.gotoLogin=function(){},n.prototype.gotoLogout=function(){this.authService.logOut(),this.router.navigate([""])},n.prototype.gotoBusinessmanager=function(){this.router.navigate(["/businessmanager"])},n.prototype.gotoWealthmanager=function(){this.router.navigate(["/wealthmanager"])},n.prototype.gotoCustomer=function(){this.router.navigate(["/customer"])},n.prototype.loginBasicAuth=function(){this.authService.loginBasicAuth(this.username)?(this.invalidLogin=!1,this.loadAfterLogin()):this.invalidLogin=!0},n.prototype.checkLogin=function(){this.authService.login()?(this.invalidLogin=!1,this.loadAfterLogin()):this.invalidLogin=!0},n.prototype.checkLogin123=function(){},n.prototype.loadAfterLogin=function(){var n=sessionStorage.getItem("roles");console.log("Role : "+n),"businessmanager"===n?this.router.navigate(["businessmanager"]):"wealthmanager"===n?this.router.navigate(["wealthmanager"]):"customer"===n?this.router.navigate(["customer"]):this.invalidLogin=!0},n}(),xf=dr({encapsulation:0,styles:[[""],yd],data:{}});function Pf(n){return ei(0,[(n()(),Hr(0,0,null,null,54,"div",[["class","container-fluid bg-grey"],["id","about"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,19,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,0,"div",[["class","col-sm-7 text-left"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,17,"div",[["class","col-sm-5 text-left"]],null,null,null,null,null)),(n()(),Jo(-1,null,[" User Name : "])),(n()(),Hr(5,0,null,null,5,"input",[["name","username"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,6)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,6).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,6)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,6)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.username=e)&&l),l},null,null)),Do(6,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(8,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(10,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,["\xa0\xa0 Password : "])),(n()(),Hr(12,0,null,null,5,"input",[["name","password"],["type","password"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,13)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,13).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,13)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,13)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.password=e)&&l),l},null,null)),Do(13,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(15,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(17,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" \xa0\xa0 "])),(n()(),Hr(19,0,null,null,1,"button",[["class","btn btn-success"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.loginBasicAuth()&&l),l},null,null)),(n()(),Jo(-1,null,["Login"])),(n()(),Hr(21,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(22,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(23,0,null,null,29,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(24,0,null,null,0,"div",[["class","col-sm-1 text-left"]],null,null,null,null,null)),(n()(),Hr(25,0,null,null,22,"div",[["class","col-sm-4 text-left"]],null,null,null,null,null)),(n()(),Hr(26,0,null,null,1,"h2",[["style","color:turquoise"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Wealth Care"])),(n()(),Hr(28,0,null,null,1,"h4",[["style","color:gray"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Wealth Care is a wealth management company headquartered in Bangalore and rapidly expanded to all the major cities of India. It provides wealth management solutions to individuals in terms of financial plan creation and making investments"])),(n()(),Hr(30,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(31,0,null,null,1,"h4",[["style","color:teal"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Hot summer picks"])),(n()(),Hr(33,0,null,null,1,"p",[["style","color:gray"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Trendy products with free shipping"])),(n()(),Hr(35,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(36,0,null,null,1,"h4",[["style","color:darkorange;"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Looking for an affordable electronics"])),(n()(),Hr(38,0,null,null,1,"p",[["style","color:gray"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Handpicked from top brands"])),(n()(),Hr(40,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(41,0,null,null,1,"h4",[["style","color:dodgerblue;"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Source from sports industry leaders"])),(n()(),Hr(43,0,null,null,1,"p",[["style","color:gray"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Top selling sports products with more discounts"])),(n()(),Hr(45,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(46,0,null,null,1,"button",[["class","btn btn-default btn-lg"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Get in Touch"])),(n()(),Hr(48,0,null,null,3,"div",[["class","col-sm-3 text-left"]],null,null,null,null,null)),(n()(),Hr(49,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(50,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(51,0,null,null,0,"img",[["alt","bags"],["src","/assets/img/product_credit_score.png"],["width","300"]],null,null,null,null,null)),(n()(),Hr(52,0,null,null,0,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(53,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(54,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(55,0,null,null,45,"div",[["class","container-fluid text-center"],["id","services"]],null,null,null,null,null)),(n()(),Hr(56,0,null,null,1,"h2",[],null,null,null,null,null)),(n()(),Jo(-1,null,["SERVICES"])),(n()(),Hr(58,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["What we offer"])),(n()(),Hr(60,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(61,0,null,null,18,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(62,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(63,0,null,null,0,"span",[["class","glyphicon glyphicon-off logo-small"]],null,null,null,null,null)),(n()(),Hr(64,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Bright Ideas"])),(n()(),Hr(66,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["ring summer into your space with vibrant colors, patterns, and shapes, inspired by the earth and sky. Brighten every corner of your home with our eclectic collection of traditional and modern home accents"])),(n()(),Hr(68,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(69,0,null,null,0,"span",[["class","glyphicon glyphicon-heart logo-small"]],null,null,null,null,null)),(n()(),Hr(70,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Handbags"])),(n()(),Hr(72,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Indulge in luxurious leather and sumptuous suede handbags, in colors that will take your breath away. From oversized totes to elegant clutches, you'll find your perfect match at a perfect price in our handcrafted designer collection."])),(n()(),Hr(74,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(75,0,null,null,0,"span",[["class","glyphicon glyphicon-lock logo-small"]],null,null,null,null,null)),(n()(),Hr(76,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Flat-out Comfort"])),(n()(),Hr(78,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Beautifully designed, soft leather shoes with an elasticized edge for perfect fit. Lightweight and durable, these flats will provide all-day comfort with their cushioned insole and soft lining. Multi-colored accent lace combinations and patterns are available as a special order. "])),(n()(),Hr(80,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(81,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(82,0,null,null,18,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(83,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(84,0,null,null,0,"span",[["class","glyphicon glyphicon-leaf logo-small"]],null,null,null,null,null)),(n()(),Hr(85,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Kids' Stuff"])),(n()(),Hr(87,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Summer style is all about fun prints, bright colors, comfort, and durability. Stock up on our easy-to-wear and affordable fashions for kids. Spend $100* or more, and earn a $25 gift certificate.\n*Before taxes. Gift certificates are redeemable on your next visit. "])),(n()(),Hr(89,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(90,0,null,null,0,"span",[["class","glyphicon glyphicon-certificate logo-small"]],null,null,null,null,null)),(n()(),Hr(91,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["FOOT WEAR"])),(n()(),Hr(93,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Upto 60% off"])),(n()(),Hr(95,0,null,null,5,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(96,0,null,null,0,"span",[["class","glyphicon glyphicon-wrench logo-small"]],null,null,null,null,null)),(n()(),Hr(97,0,null,null,1,"h4",[["style","color:#303030;"]],null,null,null,null,null)),(n()(),Jo(-1,null,["50% Off Polos"])),(n()(),Hr(99,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Select from our collection of modern, easy-to-coordinate polo shirts to create a smart but casual look. Available in a kaleidoscope of colors, with superior shape retention and wrinkle resistance. Free shipping on purchases over $60 before taxes. "])),(n()(),Hr(101,0,null,null,64,"div",[["class","container-fluid text-center bg-grey"],["id","portfolio"]],null,null,null,null,null)),(n()(),Hr(102,0,null,null,1,"h2",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Portfolio"])),(n()(),Hr(104,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(105,0,null,null,1,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,["What we offer"])),(n()(),Hr(107,0,null,null,24,"div",[["class","row text-center"]],null,null,null,null,null)),(n()(),Hr(108,0,null,null,7,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(109,0,null,null,6,"div",[["class","thumbnail"]],null,null,null,null,null)),(n()(),Hr(110,0,null,null,0,"span",[["class","glyphicon glyphicon-leaf logo-small"]],null,null,null,null,null)),(n()(),Hr(111,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(112,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["1000+ BRANDS"])),(n()(),Hr(114,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Well Curated 2 Lakhs+ Products"])),(n()(),Hr(116,0,null,null,7,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(117,0,null,null,6,"div",[["class","thumbnail"]],null,null,null,null,null)),(n()(),Hr(118,0,null,null,0,"span",[["class","glyphicon glyphicon-heart logo-small"]],null,null,null,null,null)),(n()(),Hr(119,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(120,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["FREE SHIPPING"])),(n()(),Hr(122,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["For Orders Above 500"])),(n()(),Hr(124,0,null,null,7,"div",[["class","col-sm-4"]],null,null,null,null,null)),(n()(),Hr(125,0,null,null,6,"div",[["class","thumbnail"]],null,null,null,null,null)),(n()(),Hr(126,0,null,null,0,"span",[["class","glyphicon glyphicon-off logo-small"]],null,null,null,null,null)),(n()(),Hr(127,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(128,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["GENUINE PRODUCTS"])),(n()(),Hr(130,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Sourced Directly From Brands"])),(n()(),Hr(132,0,null,null,1,"h2",[],null,null,null,null,null)),(n()(),Jo(-1,null,["What our customers say"])),(n()(),Hr(134,0,null,null,31,"div",[["class","carousel slide text-center"],["data-ride","carousel"],["id","myCarousel"]],null,null,null,null,null)),(n()(),Hr(135,0,null,null,3,"ol",[["class","carousel-indicators"]],null,null,null,null,null)),(n()(),Hr(136,0,null,null,0,"li",[["class","active"],["data-slide-to","0"],["data-target","#myCarousel"]],null,null,null,null,null)),(n()(),Hr(137,0,null,null,0,"li",[["data-slide-to","1"],["data-target","#myCarousel"]],null,null,null,null,null)),(n()(),Hr(138,0,null,null,0,"li",[["data-slide-to","2"],["data-target","#myCarousel"]],null,null,null,null,null)),(n()(),Hr(139,0,null,null,18,"div",[["class","carousel-inner"],["role","listbox"]],null,null,null,null,null)),(n()(),Hr(140,0,null,null,5,"div",[["class","item active"]],null,null,null,null,null)),(n()(),Hr(141,0,null,null,4,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,['"This application is the best. I am so happy with the product search!"'])),(n()(),Hr(143,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(144,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Victor Brown, President, ABCD Inc"])),(n()(),Hr(146,0,null,null,5,"div",[["class","item"]],null,null,null,null,null)),(n()(),Hr(147,0,null,null,4,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,['"Excellent Product!!"'])),(n()(),Hr(149,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(150,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Peter Vim, Sales Head, ZyncH Inc"])),(n()(),Hr(152,0,null,null,5,"div",[["class","item"]],null,null,null,null,null)),(n()(),Hr(153,0,null,null,4,"h4",[],null,null,null,null,null)),(n()(),Jo(-1,null,['"Very nice product. Easy to search any products?"'])),(n()(),Hr(155,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(156,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Alex, Tok, Fran Inc"])),(n()(),Hr(158,0,null,null,3,"a",[["class","left carousel-control"],["data-slide","prev"],["href","#myCarousel"],["role","button"]],null,null,null,null,null)),(n()(),Hr(159,0,null,null,0,"span",[["aria-hidden","true"],["class","glyphicon glyphicon-chevron-left"]],null,null,null,null,null)),(n()(),Hr(160,0,null,null,1,"span",[["class","sr-only"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Previous"])),(n()(),Hr(162,0,null,null,3,"a",[["class","right carousel-control"],["data-slide","next"],["href","#myCarousel"],["role","button"]],null,null,null,null,null)),(n()(),Hr(163,0,null,null,0,"span",[["aria-hidden","true"],["class","glyphicon glyphicon-chevron-right"]],null,null,null,null,null)),(n()(),Hr(164,0,null,null,1,"span",[["class","sr-only"]],null,null,null,null,null)),(n()(),Jo(-1,null,["Next"])),(n()(),Hr(166,0,null,null,18,"div",[["class","container-fluid "],["id","contact"]],null,null,null,null,null)),(n()(),Hr(167,0,null,null,1,"h2",[["class","text-center"]],null,null,null,null,null)),(n()(),Jo(-1,null,["CONTACT"])),(n()(),Hr(169,0,null,null,15,"div",[["class","text-center"]],null,null,null,null,null)),(n()(),Hr(170,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["\xa0"])),(n()(),Hr(172,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Contact us and we'll get back to you "])),(n()(),Hr(174,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(175,0,null,null,0,"span",[["class","glyphicon glyphicon-map-marker"]],null,null,null,null,null)),(n()(),Jo(-1,null,[" Product Pro, US"])),(n()(),Hr(177,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(178,0,null,null,0,"span",[["class","glyphicon glyphicon-phone"]],null,null,null,null,null)),(n()(),Jo(-1,null,[" +00 1112223344"])),(n()(),Hr(180,0,null,null,2,"p",[],null,null,null,null,null)),(n()(),Hr(181,0,null,null,0,"span",[["class","glyphicon glyphicon-envelope"]],null,null,null,null,null)),(n()(),Jo(-1,null,[" [email protected]"])),(n()(),Hr(183,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["\xa0"])),(n()(),Hr(185,0,null,null,4,"footer",[["class","container-fluid text-center bg-grey"]],null,null,null,null,null)),(n()(),Hr(186,0,null,null,1,"a",[["href","#myPage"],["title","To Top"]],null,null,null,null,null)),(n()(),Hr(187,0,null,null,0,"span",[["class","glyphicon glyphicon-chevron-up"]],null,null,null,null,null)),(n()(),Hr(188,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Thank you for visiting"]))],function(n,t){var e=t.component;n(t,8,0,"username",e.username),n(t,15,0,"password",e.password)},function(n,t){n(t,5,0,vo(t,10).ngClassUntouched,vo(t,10).ngClassTouched,vo(t,10).ngClassPristine,vo(t,10).ngClassDirty,vo(t,10).ngClassValid,vo(t,10).ngClassInvalid,vo(t,10).ngClassPending),n(t,12,0,vo(t,17).ngClassUntouched,vo(t,17).ngClassTouched,vo(t,17).ngClassPristine,vo(t,17).ngClassDirty,vo(t,17).ngClassValid,vo(t,17).ngClassInvalid,vo(t,17).ngClassPending)})}function Tf(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-homepage",[],null,null,null,Pf,xf)),Do(1,114688,null,0,Ef,[Da,Hh],null,null)],function(n,t){n(t,1,0)},null)}var If=io("app-homepage",Ef,Tf,{},{},[]),Of=function(){function n(n,t){this.authService=n,this.router=t,this.username="",this.password="",this.invalidLogin=!1}return n.prototype.ngOnInit=function(){},n.prototype.checkLogin=function(){this.authService.loginBasicAuth(this.username)?(this.router.navigate([""]),this.invalidLogin=!1):this.invalidLogin=!0},n.prototype.checkLogin123=function(){},n}(),kf=dr({encapsulation:0,styles:[[""]],data:{}});function Df(n){return ei(0,[(n()(),Hr(0,0,null,null,17,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,14,"div",[],null,null,null,null,null)),(n()(),Jo(-1,null,[" User Name : "])),(n()(),Hr(3,0,null,null,5,"input",[["name","username"],["type","text"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,4)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,4).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,4)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,4)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.username=e)&&l),l},null,null)),Do(4,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(6,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(8,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Password : "])),(n()(),Hr(10,0,null,null,5,"input",[["name","password"],["type","password"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,11)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,11).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,11)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,11)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.password=e)&&l),l},null,null)),Do(11,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(13,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(15,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(16,0,null,null,1,"button",[["class","btn btn-success"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.checkLogin()&&l),l},null,null)),(n()(),Jo(-1,null,[" Login "]))],function(n,t){var e=t.component;n(t,6,0,"username",e.username),n(t,13,0,"password",e.password)},function(n,t){n(t,3,0,vo(t,8).ngClassUntouched,vo(t,8).ngClassTouched,vo(t,8).ngClassPristine,vo(t,8).ngClassDirty,vo(t,8).ngClassValid,vo(t,8).ngClassInvalid,vo(t,8).ngClassPending),n(t,10,0,vo(t,15).ngClassUntouched,vo(t,15).ngClassTouched,vo(t,15).ngClassPristine,vo(t,15).ngClassDirty,vo(t,15).ngClassValid,vo(t,15).ngClassInvalid,vo(t,15).ngClassPending)})}function Af(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-login",[],null,null,null,Df,kf)),Do(1,114688,null,0,Of,[Da,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Rf=io("app-login",Of,Af,{},{},[]),Mf=function(){function n(n,t){this.authService=n,this.router=t}return n.prototype.ngOnInit=function(){this.authService.logOut(),this.router.navigate(["login"])},n}(),Nf=dr({encapsulation:0,styles:[[""]],data:{}});function Lf(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,[" logout works!\n"]))],null,null)}function Vf(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-logout",[],null,null,null,Lf,Nf)),Do(1,114688,null,0,Mf,[Da,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Uf=io("app-logout",Mf,Vf,{},{},[]),jf=[".mat-tab-label[_ngcontent-%COMP%]{background:#00f;color:#fff}.mat-tab-group.mat-primary[_ngcontent-%COMP%] .mat-tab-label[_ngcontent-%COMP%]:not(.mat-tab-disabled):focus, .mat-tab-group.mat-primary[_ngcontent-%COMP%] .mat-tab-link[_ngcontent-%COMP%]:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary[_ngcontent-%COMP%] .mat-tab-label[_ngcontent-%COMP%]:not(.mat-tab-disabled):focus, .mat-tab-nav-bar.mat-primary[_ngcontent-%COMP%] .mat-tab-link[_ngcontent-%COMP%]:not(.mat-tab-disabled):focus{background:red}.mat-tab-group.mat-primary[_ngcontent-%COMP%] .mat-ink-bar[_ngcontent-%COMP%], .mat-tab-nav-bar.mat-primary[_ngcontent-%COMP%] .mat-ink-bar[_ngcontent-%COMP%]{background:#ff0;height:10px}.my-card[_ngcontent-%COMP%]{width:400px;margin:4px}.buttonEdit[_ngcontent-%COMP%]{background:url(button-edit.7faa821d52bf8899faba.png) left center no-repeat;padding-left:20px;alt:Edit}.buttonDelete[_ngcontent-%COMP%]{background:url(button-delete.7da60dac2fea579b330a.png) left center no-repeat;padding-left:20px;alt:Delete}.container[_ngcontent-%COMP%]{padding:2px}.btn[_ngcontent-%COMP%]{background-color:#1e90ff;border:none;color:#fff;padding:12px 16px;font-size:16px;cursor:pointer}.btn[_ngcontent-%COMP%]:hover{background-color:#4169e1}.button[_ngcontent-%COMP%]{background-color:#4caf50;border:none;color:#fff;padding:5px 20px;text-align:center;text-decoration:none;display:inline-block;font-size:12px;margin:1px;cursor:pointer}.buttonBlue[_ngcontent-%COMP%]{background-color:#008cba}.buttonGray[_ngcontent-%COMP%]{background-color:grey}.bgColorLightSeaGreen[_ngcontent-%COMP%]{background-color:#20b2aa}button[_ngcontent-%COMP%]{background-color:#eee;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;cursor:hand;font-family:Arial}button[_ngcontent-%COMP%]:hover{background-color:#cfd8dc}button.delete[_ngcontent-%COMP%]{position:relative;left:800px;top:-32px;background-color:gray!important;color:#fff}.mycard[_ngcontent-%COMP%]{background:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.16),0 0 0 1px rgba(0,0,0,.08);margin-left:12px;margin-bottom:12px;float:left}.mycard[_ngcontent-%COMP%]:hover{box-shadow:0 2px 2px 0 #6a97c4}.simCardGrid[_ngcontent-%COMP%]{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));grid-gap:10px}.simCardOuter[_ngcontent-%COMP%]{border:1px solid #eeeaea;padding:10px;height:85px;background:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.16),0 0 0 1px rgba(0,0,0,.08)}.simCardOuter[_ngcontent-%COMP%]:hover{box-shadow:2px 2px 2px 2px #6a97c4}.simCardInner[_ngcontent-%COMP%]{display:grid;border:0;grid-template-columns:75px 220px 20px;grid-gap:2px;height:80px}.simCardImg[_ngcontent-%COMP%]{background-size:cover;background-position:center}.simContent[_ngcontent-%COMP%]{padding:2px}.simCardTitle[_ngcontent-%COMP%]{font-size:12px;font-weight:700;color:#01011b}.simTabHeader[_ngcontent-%COMP%]{border:1px solid #e7e7e7;background-color:#f1f1f1;height:40px}.simTabHeader[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{background-color:inherit;border:none;outline:0;cursor:pointer;transition:.3s;font-size:14px;height:40px;border-radius:0}.simTabHeader[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:hover{background-color:#ddd}.simTabHeader[_ngcontent-%COMP%] button.active[_ngcontent-%COMP%]{background-color:#6083cb;color:#fff}.simTabContent[_ngcontent-%COMP%]{padding:6px 12px;border:1px solid #ccc;border-top:none}.simButtonType1[_ngcontent-%COMP%]{background-color:#008cba;border:none;outline:0;cursor:pointer;font-size:12px;height:35px;border-radius:0;color:#fff}.simButtonType1[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:hover{background-color:#ddd}.simCardGridType2[_ngcontent-%COMP%]{display:grid;grid-template-columns:900px;grid-gap:20px}.simCardGridType2Outer[_ngcontent-%COMP%]{border:.5px solid #eeeaea;padding:10px;background:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.16),0 0 0 1px rgba(0,0,0,.08)}.simCardGridType2Outer[_ngcontent-%COMP%]:hover{box-shadow:2px 2px 2px 2px #6a97c4}.simCardGridType2Row1[_ngcontent-%COMP%]{display:grid;grid-template-columns:400px 300px 100px;grid-gap:10px;height:35px;border-bottom:none}.simCardGridType2Row2[_ngcontent-%COMP%]{display:grid;grid-template-columns:100px 100px 100px 100px 100px 100px 150px 100px;grid-gap:10px;border-top:none}.simCardType3Outer[_ngcontent-%COMP%]{border:1px solid #eeeaea;padding:10px;height:40px;background:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.16),0 0 0 1px rgba(0,0,0,.08)}.simCardType3Outer[_ngcontent-%COMP%]:hover{box-shadow:2px 2px 2px 2px #6a97c4}.textStyleType1[_ngcontent-%COMP%]{color:#ffb82c}.textStyleType2[_ngcontent-%COMP%]{font-size:12px;font-weight:700;color:#11154b}.textStyleType3[_ngcontent-%COMP%]{color:#4caf50}.simGridType3[_ngcontent-%COMP%]{display:grid;grid-template-columns:30px 200px 1fr 100px 30px;grid-gap:10px;height:80px;width:100%}.simDivVerticalAlginCenter[_ngcontent-%COMP%]{position:relative;top:0}.simDivVerticalAlginBottom[_ngcontent-%COMP%]{position:relative;top:50%}"],Ff=function(){function n(n,t){this.authService=n,this.router=t,this.wealthManagerClass="active",this.customerClass=""}return n.prototype.ngOnInit=function(){},n.prototype.gotoWealthmanager=function(){this.wealthManagerClass="active",this.customerClass="",this.router.navigate(["/businessmanager/wealthmanager"])},n.prototype.gotoCustomer=function(){this.wealthManagerClass="",this.customerClass="active",this.router.navigate(["/businessmanager/customer"])},n.prototype.gotoLogout=function(){this.authService.logOut()},n}(),Bf=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Hf(n){return ei(0,[(n()(),Hr(0,0,null,null,8,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,4,"div",[["class","simTabHeader"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoWealthmanager()&&l),l},null,null)),(n()(),Jo(-1,null,["Wealth Manager"])),(n()(),Hr(4,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoCustomer()&&l),l},null,null)),(n()(),Jo(-1,null,["Customer"])),(n()(),Hr(6,0,null,null,2,"div",[["class","simTabContent"]],null,null,null,null,null)),(n()(),Hr(7,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),Do(8,212992,null,0,Gh,[qh,bl,Tt,[8,null],Cl],null,null)],function(n,t){n(t,8,0)},function(n,t){var e=t.component;n(t,2,0,jr(1,"",e.wealthManagerClass,"")),n(t,4,0,jr(1,"",e.customerClass,""))})}function zf(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-homepage",[],null,null,null,Hf,Bf)),Do(1,114688,null,0,Ff,[Da,Hh],null,null)],function(n,t){n(t,1,0)},null)}var qf=io("app-bm-homepage",Ff,zf,{},{},[]),Gf=function(n){function t(t){var e=n.call(this,t)||this;return e.http=t,e}return r(t,n),t.prototype.getAll=function(){return this.getCusCus(),this.http.get(this.getURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getById=function(n){return this.http.get(this.getURL()+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.add=function(n){return console.log("add ---\x3e "+JSON.stringify(n)),this.http.post(this.getURL(),JSON.stringify(n),this.getHttpHeaders()).pipe(Wa(function(n){return console.log("added w/ id="+n.id)}),ts(this.handleError("add")))},t.prototype.update=function(n,t){return this.http.put(this.getURL(),JSON.stringify(t),this.getHttpHeaders()).pipe(Wa(function(t){return console.log("updated id="+n)}),ts(this.handleError("update")))},t.prototype.delete=function(n){return this.http.delete(this.getURL()+n,this.getHttpHeaders()).pipe(Wa(function(t){return console.log("deleted id="+n)}),ts(this.handleError("delete")))},t.prototype.getURL=function(){return this.getApiGatewayUrlUser()+"/user/api/customer/"},t.ngInjectableDef=wn({factory:function(){return new t($n(ca))},token:t,providedIn:"root"}),t}(ka),Wf=function(){function n(n,t){this.customerService=n,this.router=t,this.mainData=[]}return n.prototype.ngOnInit=function(){this.getAll()},n.prototype.getAll=function(){var n=this;this.mainData=[],this.customerService.getAll().subscribe(function(t){n.mainData=t})},n.prototype.add=function(){this.router.navigate(["/businessmanager/customerAdd"])},n.prototype.edit=function(n){this.router.navigate(["/businessmanager/customerEdit/"+n])},n.prototype.delete=function(n){var t=this;this.customerService.delete(n).subscribe(function(n){t.getAll()},function(n){console.log(n)})},n}(),Qf=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function $f(n){return ei(0,[(n()(),Hr(0,0,null,null,15,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,14,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,[""," ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" ",", ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,4,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.edit(r.i)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["border","0"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.delete(r.i)&&l),l},null,null)),(n()(),Hr(15,0,null,null,0,"img",[["alt","Delete"],["border","0"],["height","20"],["src","../../assets/img/button-delete.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.$implicit.firstName,t.context.$implicit.lastName),n(t,8,0,t.context.$implicit.gender,t.context.$implicit.age,t.context.$implicit.city),n(t,10,0,t.context.$implicit.startDateString)})}function Kf(n){return ei(0,[(n()(),Hr(0,0,null,null,15,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,14,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,["Shiba Inu ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" Male, ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,4,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.edit(n.context.index)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["border","0"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.delete(n.context.index)&&l),l},null,null)),(n()(),Hr(15,0,null,null,0,"img",[["alt","Delete"],["border","0"],["height","20"],["src","../../assets/img/button-delete.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.index),n(t,8,0,t.context.index,t.context.$implicit),n(t,10,0,t.context.index)})}function Zf(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,1,"button",[["class","simButtonType1"],["title","Add"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.add()&&l),l},null,null)),(n()(),Jo(-1,null,["Add Customer"])),(n()(),Hr(3,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,5,"div",[["class","simCardGrid"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,$f)),Do(7,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Br(16777216,null,null,2,null,Kf)),Do(9,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),Xo(10,8)],function(n,t){n(t,7,0,t.component.mainData);var e=n(t,10,0,10,20,30,40,50,60,70,80);n(t,9,0,e)},null)}function Yf(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-customer",[],null,null,null,Zf,Qf)),Do(1,114688,null,0,Wf,[Gf,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Xf=io("app-bm-customer",Wf,Yf,{},{},[]),Jf=function(){function n(){}return n.prototype.getCountries=function(){return[{id:"IN",name:"India"},{id:"US",name:"USA"},{id:"EU",name:"Europe"},{id:"UK",name:"United Kingdom"}]},n.ngInjectableDef=wn({factory:function(){return new n},token:n,providedIn:"root"}),n}(),ng=function(){function n(n,t,e,l){this.customerService=n,this.commonDataService=t,this.route=e,this.router=l,this.mainData={firstName:"",lastName:"",age:18,gender:"Male",emailId:"",city:"",country:"",avgIncome:1e4}}return n.prototype.ngOnInit=function(){this.countries=this.commonDataService.getCountries()},n.prototype.save=function(){var n=this;this.customerService.add(this.mainData).subscribe(function(t){n.router.navigate(["/businessmanager/customer"])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/businessmanager/customer"])},n}(),tg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function eg(n){return ei(0,[(n()(),Hr(0,0,null,null,3,"option",[],null,null,null,null,null)),Do(1,147456,null,0,qd,[At,Vt,[2,zd]],{ngValue:[0,"ngValue"]},null),Do(2,147456,null,0,Qd,[At,Vt,[8,null]],{ngValue:[0,"ngValue"]},null),(n()(),Jo(3,null,[" "," "]))],function(n,t){n(t,1,0,t.context.$implicit.id),n(t,2,0,t.context.$implicit.id)},function(n,t){n(t,3,0,t.context.$implicit.name)})}function lg(n){return ei(0,[(n()(),Hr(0,0,null,null,118,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Add Customer"])),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,112,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(10,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,12)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,12).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,12)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,12)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(12,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(14,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(16,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(17,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(18,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(21,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(22,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,23)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,23).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,23)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,23)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(23,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(25,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(27,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(28,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(29,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Age"])),(n()(),Hr(32,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(33,0,null,null,5,"input",[["placeholder","Age"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,34)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,34).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,34)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,34)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.age=e)&&l),l},null,null)),Do(34,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(36,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(38,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(39,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(40,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(43,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(44,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(45,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,46)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,46).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,46)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,46)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,47).onChange()&&l),"blur"===t&&(l=!1!==vo(n,47).onTouched()&&l),l},null,null)),Do(46,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(47,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(48,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(51,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(53,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(55,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,56)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,56).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,56)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,56)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,57).onChange()&&l),"blur"===t&&(l=!1!==vo(n,57).onTouched()&&l),l},null,null)),Do(56,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(57,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(58,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(61,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(63,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(65,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(66,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(67,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(69,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(70,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,71)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,71).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,71)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,71)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(71,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(73,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(75,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(76,0,null,null,12,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(77,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(80,0,null,null,8,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(81,0,null,null,7,"select",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"change"],[null,"blur"]],function(n,t,e){var l=!0,r=n.component;return"change"===t&&(l=!1!==vo(n,82).onChange(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,82).onTouched()&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.country=e)&&l),l},null,null)),Do(82,16384,null,0,zd,[Vt,At],null,null),Ao(1024,null,Id,function(n){return[n]},[zd]),Do(84,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(86,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Br(16777216,null,null,1,null,eg)),Do(88,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(89,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(90,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(91,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(93,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(94,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(95,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,96)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,96).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,96)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,96)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(96,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(98,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(100,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(101,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(102,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(103,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Income"])),(n()(),Hr(105,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(106,0,null,null,5,"input",[["placeholder","Income"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,107)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,107).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,107)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,107)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.avgIncome=e)&&l),l},null,null)),Do(107,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(109,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(111,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(112,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(113,0,null,null,4,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(114,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(116,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"])),(n()(),Hr(118,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,14,0,e.mainData.firstName),n(t,25,0,e.mainData.lastName),n(t,36,0,e.mainData.age),n(t,47,0,"gender","Male"),n(t,48,0,""),n(t,51,0,"gender",e.mainData.gender),n(t,57,0,"gender","Female"),n(t,58,0,""),n(t,61,0,"gender",e.mainData.gender),n(t,73,0,e.mainData.emailId),n(t,84,0,e.mainData.country),n(t,88,0,e.countries),n(t,98,0,e.mainData.city),n(t,109,0,e.mainData.avgIncome)},function(n,t){n(t,11,0,vo(t,16).ngClassUntouched,vo(t,16).ngClassTouched,vo(t,16).ngClassPristine,vo(t,16).ngClassDirty,vo(t,16).ngClassValid,vo(t,16).ngClassInvalid,vo(t,16).ngClassPending),n(t,22,0,vo(t,27).ngClassUntouched,vo(t,27).ngClassTouched,vo(t,27).ngClassPristine,vo(t,27).ngClassDirty,vo(t,27).ngClassValid,vo(t,27).ngClassInvalid,vo(t,27).ngClassPending),n(t,33,0,vo(t,38).ngClassUntouched,vo(t,38).ngClassTouched,vo(t,38).ngClassPristine,vo(t,38).ngClassDirty,vo(t,38).ngClassValid,vo(t,38).ngClassInvalid,vo(t,38).ngClassPending),n(t,45,0,vo(t,48).required?"":null,vo(t,53).ngClassUntouched,vo(t,53).ngClassTouched,vo(t,53).ngClassPristine,vo(t,53).ngClassDirty,vo(t,53).ngClassValid,vo(t,53).ngClassInvalid,vo(t,53).ngClassPending),n(t,55,0,vo(t,58).required?"":null,vo(t,63).ngClassUntouched,vo(t,63).ngClassTouched,vo(t,63).ngClassPristine,vo(t,63).ngClassDirty,vo(t,63).ngClassValid,vo(t,63).ngClassInvalid,vo(t,63).ngClassPending),n(t,70,0,vo(t,75).ngClassUntouched,vo(t,75).ngClassTouched,vo(t,75).ngClassPristine,vo(t,75).ngClassDirty,vo(t,75).ngClassValid,vo(t,75).ngClassInvalid,vo(t,75).ngClassPending),n(t,81,0,vo(t,86).ngClassUntouched,vo(t,86).ngClassTouched,vo(t,86).ngClassPristine,vo(t,86).ngClassDirty,vo(t,86).ngClassValid,vo(t,86).ngClassInvalid,vo(t,86).ngClassPending),n(t,95,0,vo(t,100).ngClassUntouched,vo(t,100).ngClassTouched,vo(t,100).ngClassPristine,vo(t,100).ngClassDirty,vo(t,100).ngClassValid,vo(t,100).ngClassInvalid,vo(t,100).ngClassPending),n(t,106,0,vo(t,111).ngClassUntouched,vo(t,111).ngClassTouched,vo(t,111).ngClassPristine,vo(t,111).ngClassDirty,vo(t,111).ngClassValid,vo(t,111).ngClassInvalid,vo(t,111).ngClassPending)})}function rg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-customer-add",[],null,null,null,lg,tg)),Do(1,114688,null,0,ng,[Gf,Jf,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var og=io("app-bm-customer-add",ng,rg,{mainData:"mainData"},{},[]),ig=function(){function n(n,t,e,l){this.customerService=n,this.commonDataService=t,this.route=e,this.router=l,this.mainData={id:0,firstName:"",lastName:"",age:18,gender:"Male",emailId:"",city:"",country:"",avgIncome:1e4}}return n.prototype.ngOnInit=function(){this.countries=this.commonDataService.getCountries(),this.loadById()},n.prototype.loadById=function(){var n=this;this.customerService.getById(this.route.snapshot.params.id).subscribe(function(t){console.log(t),n.mainData=t})},n.prototype.save=function(){var n=this;this.customerService.update(this.mainData.id,this.mainData).subscribe(function(t){n.router.navigate(["/businessmanager/customer"])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/businessmanager/customer"])},n}(),ug=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function ag(n){return ei(0,[(n()(),Hr(0,0,null,null,3,"option",[],null,null,null,null,null)),Do(1,147456,null,0,qd,[At,Vt,[2,zd]],{ngValue:[0,"ngValue"]},null),Do(2,147456,null,0,Qd,[At,Vt,[8,null]],{ngValue:[0,"ngValue"]},null),(n()(),Jo(3,null,[" "," "]))],function(n,t){n(t,1,0,t.context.$implicit.id),n(t,2,0,t.context.$implicit.id)},function(n,t){n(t,3,0,t.context.$implicit.name)})}function sg(n){return ei(0,[(n()(),Hr(0,0,null,null,124,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Edit Customer"])),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,118,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(10,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,12)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,12).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,12)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,12)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(12,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(14,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(16,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(17,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(18,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(21,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(22,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,23)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,23).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,23)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,23)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(23,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(25,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(27,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(28,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(29,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Age"])),(n()(),Hr(32,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(33,0,null,null,5,"input",[["placeholder","Age"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,34)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,34).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,34)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,34)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.age=e)&&l),l},null,null)),Do(34,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(36,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(38,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(39,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(40,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(43,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(44,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(45,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,46)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,46).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,46)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,46)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,47).onChange()&&l),"blur"===t&&(l=!1!==vo(n,47).onTouched()&&l),l},null,null)),Do(46,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(47,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(48,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(51,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(53,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(55,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,56)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,56).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,56)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,56)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,57).onChange()&&l),"blur"===t&&(l=!1!==vo(n,57).onTouched()&&l),l},null,null)),Do(56,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(57,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(58,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(61,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(63,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(65,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(66,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(67,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(69,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(70,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,71)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,71).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,71)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,71)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(71,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(73,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(75,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(76,0,null,null,12,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(77,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(80,0,null,null,8,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(81,0,null,null,7,"select",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"change"],[null,"blur"]],function(n,t,e){var l=!0,r=n.component;return"change"===t&&(l=!1!==vo(n,82).onChange(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,82).onTouched()&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.country=e)&&l),l},null,null)),Do(82,16384,null,0,zd,[Vt,At],null,null),Ao(1024,null,Id,function(n){return[n]},[zd]),Do(84,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(86,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Br(16777216,null,null,1,null,ag)),Do(88,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(89,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(90,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(91,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(93,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(94,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(95,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,96)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,96).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,96)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,96)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(96,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(98,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(100,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(101,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(102,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(103,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Income"])),(n()(),Hr(105,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(106,0,null,null,5,"input",[["placeholder","Income"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,107)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,107).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,107)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,107)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.avgIncome=e)&&l),l},null,null)),Do(107,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(109,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(111,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(112,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(113,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(114,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,115)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,115).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,115)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,115)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.id=e)&&l),l},null,null)),Do(115,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(117,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(119,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(120,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(122,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"])),(n()(),Hr(124,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,14,0,e.mainData.firstName),n(t,25,0,e.mainData.lastName),n(t,36,0,e.mainData.age),n(t,47,0,"gender","Male"),n(t,48,0,""),n(t,51,0,"gender",e.mainData.gender),n(t,57,0,"gender","Female"),n(t,58,0,""),n(t,61,0,"gender",e.mainData.gender),n(t,73,0,e.mainData.emailId),n(t,84,0,e.mainData.country),n(t,88,0,e.countries),n(t,98,0,e.mainData.city),n(t,109,0,e.mainData.avgIncome),n(t,117,0,e.mainData.id)},function(n,t){n(t,11,0,vo(t,16).ngClassUntouched,vo(t,16).ngClassTouched,vo(t,16).ngClassPristine,vo(t,16).ngClassDirty,vo(t,16).ngClassValid,vo(t,16).ngClassInvalid,vo(t,16).ngClassPending),n(t,22,0,vo(t,27).ngClassUntouched,vo(t,27).ngClassTouched,vo(t,27).ngClassPristine,vo(t,27).ngClassDirty,vo(t,27).ngClassValid,vo(t,27).ngClassInvalid,vo(t,27).ngClassPending),n(t,33,0,vo(t,38).ngClassUntouched,vo(t,38).ngClassTouched,vo(t,38).ngClassPristine,vo(t,38).ngClassDirty,vo(t,38).ngClassValid,vo(t,38).ngClassInvalid,vo(t,38).ngClassPending),n(t,45,0,vo(t,48).required?"":null,vo(t,53).ngClassUntouched,vo(t,53).ngClassTouched,vo(t,53).ngClassPristine,vo(t,53).ngClassDirty,vo(t,53).ngClassValid,vo(t,53).ngClassInvalid,vo(t,53).ngClassPending),n(t,55,0,vo(t,58).required?"":null,vo(t,63).ngClassUntouched,vo(t,63).ngClassTouched,vo(t,63).ngClassPristine,vo(t,63).ngClassDirty,vo(t,63).ngClassValid,vo(t,63).ngClassInvalid,vo(t,63).ngClassPending),n(t,70,0,vo(t,75).ngClassUntouched,vo(t,75).ngClassTouched,vo(t,75).ngClassPristine,vo(t,75).ngClassDirty,vo(t,75).ngClassValid,vo(t,75).ngClassInvalid,vo(t,75).ngClassPending),n(t,81,0,vo(t,86).ngClassUntouched,vo(t,86).ngClassTouched,vo(t,86).ngClassPristine,vo(t,86).ngClassDirty,vo(t,86).ngClassValid,vo(t,86).ngClassInvalid,vo(t,86).ngClassPending),n(t,95,0,vo(t,100).ngClassUntouched,vo(t,100).ngClassTouched,vo(t,100).ngClassPristine,vo(t,100).ngClassDirty,vo(t,100).ngClassValid,vo(t,100).ngClassInvalid,vo(t,100).ngClassPending),n(t,106,0,vo(t,111).ngClassUntouched,vo(t,111).ngClassTouched,vo(t,111).ngClassPristine,vo(t,111).ngClassDirty,vo(t,111).ngClassValid,vo(t,111).ngClassInvalid,vo(t,111).ngClassPending),n(t,114,0,vo(t,119).ngClassUntouched,vo(t,119).ngClassTouched,vo(t,119).ngClassPristine,vo(t,119).ngClassDirty,vo(t,119).ngClassValid,vo(t,119).ngClassInvalid,vo(t,119).ngClassPending)})}function cg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-customer-edit",[],null,null,null,sg,ug)),Do(1,114688,null,0,ig,[Gf,Jf,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var pg=io("app-bm-customer-edit",ig,cg,{mainData:"mainData"},{},[]),hg=function(n){function t(t){var e=n.call(this,t)||this;return e.http=t,e}return r(t,n),t.prototype.getAll=function(){return this.getCusCus(),this.http.get(this.getURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getById=function(n){return this.http.get(this.getURL()+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.add=function(n){return console.log("add ---\x3e "+JSON.stringify(n)),this.http.post(this.getURL(),JSON.stringify(n),this.getHttpHeaders()).pipe(Wa(function(n){return console.log("added w/ id="+n.id)}),ts(this.handleError("add")))},t.prototype.update=function(n,t){return this.http.put(this.getURL(),JSON.stringify(t),this.getHttpHeaders()).pipe(Wa(function(t){return console.log("updated id="+n)}),ts(this.handleError("update")))},t.prototype.delete=function(n){return this.http.delete(this.getURL()+n,this.getHttpHeaders()).pipe(Wa(function(t){return console.log("deleted id="+n)}),ts(this.handleError("delete")))},t.prototype.getURL=function(){return this.getApiGatewayUrlUser()+"/user/api/wealthmanager/"},t.ngInjectableDef=wn({factory:function(){return new t($n(ca))},token:t,providedIn:"root"}),t}(ka),dg=function(){function n(n,t){this.wealthmanagerService=n,this.router=t,this.mainData=[]}return n.prototype.ngOnInit=function(){this.getAll()},n.prototype.getAll=function(){var n=this;this.mainData=[],this.wealthmanagerService.getAll().subscribe(function(t){n.mainData=t})},n.prototype.add=function(){this.router.navigate(["/businessmanager/wealthmanagerAdd"])},n.prototype.edit=function(n){this.router.navigate(["/businessmanager/wealthmanagerEdit/"+n])},n.prototype.delete=function(n){var t=this;this.wealthmanagerService.delete(n).subscribe(function(n){t.getAll()},function(n){console.log(n)})},n}(),fg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function gg(n){return ei(0,[(n()(),Hr(0,0,null,null,15,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,14,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,[""," ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" ",", ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,4,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.edit(r.i)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.delete(r.i)&&l),l},null,null)),(n()(),Hr(15,0,null,null,0,"img",[["alt","Delete"],["height","20"],["src","../../assets/img/button-delete.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.$implicit.firstName,t.context.$implicit.lastName),n(t,8,0,t.context.$implicit.gender,t.context.$implicit.age,t.context.$implicit.city),n(t,10,0,t.context.$implicit.startDateString)})}function mg(n){return ei(0,[(n()(),Hr(0,0,null,null,15,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,14,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,["Shiba Inu ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" Male, ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,4,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.edit(n.context.index)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.delete(n.context.index)&&l),l},null,null)),(n()(),Hr(15,0,null,null,0,"img",[["alt","Delete"],["height","20"],["src","../../assets/img/button-delete.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.index),n(t,8,0,t.context.index,t.context.$implicit),n(t,10,0,t.context.index)})}function yg(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,1,"button",[["class","simButtonType1"],["title","Add"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.add()&&l),l},null,null)),(n()(),Jo(-1,null,["Add Wealth Manager"])),(n()(),Hr(3,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,5,"div",[["class","simCardGrid"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,gg)),Do(7,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Br(16777216,null,null,2,null,mg)),Do(9,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),Xo(10,8)],function(n,t){n(t,7,0,t.component.mainData);var e=n(t,10,0,10,20,30,40,50,60,70,80);n(t,9,0,e)},null)}function vg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-wealthmanager",[],null,null,null,yg,fg)),Do(1,114688,null,0,dg,[hg,Hh],null,null)],function(n,t){n(t,1,0)},null)}var _g=io("app-bm-wealthmanager",dg,vg,{},{},[]),bg=function(){function n(n,t,e,l){this.wealthmanagerService=n,this.commonDataService=t,this.route=e,this.router=l,this.mainData={firstName:"",lastName:"",age:18,gender:"Male",emailId:"",city:"",country:""}}return n.prototype.ngOnInit=function(){this.countries=this.commonDataService.getCountries()},n.prototype.save=function(){var n=this;this.wealthmanagerService.add(this.mainData).subscribe(function(t){n.router.navigate(["/businessmanager/wealthmanager"])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/businessmanager/wealthmanager"])},n}(),wg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Cg(n){return ei(0,[(n()(),Hr(0,0,null,null,3,"option",[],null,null,null,null,null)),Do(1,147456,null,0,qd,[At,Vt,[2,zd]],{ngValue:[0,"ngValue"]},null),Do(2,147456,null,0,Qd,[At,Vt,[8,null]],{ngValue:[0,"ngValue"]},null),(n()(),Jo(3,null,[" "," "]))],function(n,t){n(t,1,0,t.context.$implicit.id),n(t,2,0,t.context.$implicit.id)},function(n,t){n(t,3,0,t.context.$implicit.name)})}function Sg(n){return ei(0,[(n()(),Hr(0,0,null,null,96,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Add Wealth Manager"])),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,91,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(10,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,12)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,12).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,12)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,12)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(12,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(14,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(16,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(17,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(18,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(21,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(22,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,23)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,23).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,23)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,23)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(23,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(25,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(27,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(28,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(29,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(32,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(33,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(34,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,35)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,35).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,35)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,35)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,36).onChange()&&l),"blur"===t&&(l=!1!==vo(n,36).onTouched()&&l),l},null,null)),Do(35,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(36,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(37,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(40,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(42,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(44,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,45)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,45).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,45)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,45)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,46).onChange()&&l),"blur"===t&&(l=!1!==vo(n,46).onTouched()&&l),l},null,null)),Do(45,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(46,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(47,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(50,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(52,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(54,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(55,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(56,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(58,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(59,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,60)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,60).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,60)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,60)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(60,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(62,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(64,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(65,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(66,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(67,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(69,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(70,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(71,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,72)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,72).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,72)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,72)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(72,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(74,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(76,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(77,0,null,null,12,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(79,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(81,0,null,null,8,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(82,0,null,null,7,"select",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"change"],[null,"blur"]],function(n,t,e){var l=!0,r=n.component;return"change"===t&&(l=!1!==vo(n,83).onChange(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,83).onTouched()&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.country=e)&&l),l},null,null)),Do(83,16384,null,0,zd,[Vt,At],null,null),Ao(1024,null,Id,function(n){return[n]},[zd]),Do(85,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(87,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Br(16777216,null,null,1,null,Cg)),Do(89,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(90,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(91,0,null,null,4,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(92,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(94,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"])),(n()(),Hr(96,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,14,0,e.mainData.firstName),n(t,25,0,e.mainData.lastName),n(t,36,0,"gender","Male"),n(t,37,0,""),n(t,40,0,"gender",e.mainData.gender),n(t,46,0,"gender","Female"),n(t,47,0,""),n(t,50,0,"gender",e.mainData.gender),n(t,62,0,e.mainData.emailId),n(t,74,0,e.mainData.city),n(t,85,0,e.mainData.country),n(t,89,0,e.countries)},function(n,t){n(t,11,0,vo(t,16).ngClassUntouched,vo(t,16).ngClassTouched,vo(t,16).ngClassPristine,vo(t,16).ngClassDirty,vo(t,16).ngClassValid,vo(t,16).ngClassInvalid,vo(t,16).ngClassPending),n(t,22,0,vo(t,27).ngClassUntouched,vo(t,27).ngClassTouched,vo(t,27).ngClassPristine,vo(t,27).ngClassDirty,vo(t,27).ngClassValid,vo(t,27).ngClassInvalid,vo(t,27).ngClassPending),n(t,34,0,vo(t,37).required?"":null,vo(t,42).ngClassUntouched,vo(t,42).ngClassTouched,vo(t,42).ngClassPristine,vo(t,42).ngClassDirty,vo(t,42).ngClassValid,vo(t,42).ngClassInvalid,vo(t,42).ngClassPending),n(t,44,0,vo(t,47).required?"":null,vo(t,52).ngClassUntouched,vo(t,52).ngClassTouched,vo(t,52).ngClassPristine,vo(t,52).ngClassDirty,vo(t,52).ngClassValid,vo(t,52).ngClassInvalid,vo(t,52).ngClassPending),n(t,59,0,vo(t,64).ngClassUntouched,vo(t,64).ngClassTouched,vo(t,64).ngClassPristine,vo(t,64).ngClassDirty,vo(t,64).ngClassValid,vo(t,64).ngClassInvalid,vo(t,64).ngClassPending),n(t,71,0,vo(t,76).ngClassUntouched,vo(t,76).ngClassTouched,vo(t,76).ngClassPristine,vo(t,76).ngClassDirty,vo(t,76).ngClassValid,vo(t,76).ngClassInvalid,vo(t,76).ngClassPending),n(t,82,0,vo(t,87).ngClassUntouched,vo(t,87).ngClassTouched,vo(t,87).ngClassPristine,vo(t,87).ngClassDirty,vo(t,87).ngClassValid,vo(t,87).ngClassInvalid,vo(t,87).ngClassPending)})}function Eg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-wealthmanager-add",[],null,null,null,Sg,wg)),Do(1,114688,null,0,bg,[hg,Jf,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var xg=io("app-bm-wealthmanager-add",bg,Eg,{mainData:"mainData"},{},[]),Pg=function(){function n(n,t,e,l){this.wealthmanagerService=n,this.commonDataService=t,this.route=e,this.router=l,this.mainData={id:0,firstName:"",lastName:"",age:18,gender:"Male",emailId:"",city:"",country:""}}return n.prototype.ngOnInit=function(){this.countries=this.commonDataService.getCountries(),this.loadById()},n.prototype.loadById=function(){var n=this;this.wealthmanagerService.getById(this.route.snapshot.params.id).subscribe(function(t){console.log(t),n.mainData=t})},n.prototype.save=function(){var n=this;this.wealthmanagerService.update(this.mainData.id,this.mainData).subscribe(function(t){n.router.navigate(["/businessmanager/wealthmanager"])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/businessmanager/wealthmanager"])},n}(),Tg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function
(n){return ei(0,[(n()(),Hr(0,0,null,null,3,"option",[],null,null,null,null,null)),Do(1,147456,null,0,qd,[At,Vt,[2,zd]],{ngValue:[0,"ngValue"]},null),Do(2,147456,null,0,Qd,[At,Vt,[8,null]],{ngValue:[0,"ngValue"]},null),(n()(),Jo(3,null,[" "," "]))],function(n,t){n(t,1,0,t.context.$implicit.id),n(t,2,0,t.context.$implicit.id)},function(n,t){n(t,3,0,t.context.$implicit.name)})}function Og(n){return ei(0,[(n()(),Hr(0,0,null,null,103,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Edit Wealth Manager"])),(n()(),Hr(4,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(5,0,null,null,97,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(10,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,12)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,12).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,12)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,12)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(12,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(14,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(16,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(17,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(18,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(21,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(22,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,23)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,23).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,23)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,23)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(23,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(25,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(27,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(28,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(29,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(32,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(33,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(34,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,35)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,35).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,35)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,35)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,36).onChange()&&l),"blur"===t&&(l=!1!==vo(n,36).onTouched()&&l),l},null,null)),Do(35,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(36,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(37,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(40,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(42,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(44,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,45)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,45).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,45)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,45)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,46).onChange()&&l),"blur"===t&&(l=!1!==vo(n,46).onTouched()&&l),l},null,null)),Do(45,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(46,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(47,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(50,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(52,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(54,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(55,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(56,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(58,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(59,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,60)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,60).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,60)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,60)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(60,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(62,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(64,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(65,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(66,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(67,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(69,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(70,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(71,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,72)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,72).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,72)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,72)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(72,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(74,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(76,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(77,0,null,null,12,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(79,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(81,0,null,null,8,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(82,0,null,null,7,"select",[],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"change"],[null,"blur"]],function(n,t,e){var l=!0,r=n.component;return"change"===t&&(l=!1!==vo(n,83).onChange(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,83).onTouched()&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.country=e)&&l),l},null,null)),Do(83,16384,null,0,zd,[Vt,At],null,null),Ao(1024,null,Id,function(n){return[n]},[zd]),Do(85,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(87,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Br(16777216,null,null,1,null,Ig)),Do(89,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(90,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(91,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(92,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,93)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,93).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,93)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,93)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.id=e)&&l),l},null,null)),Do(93,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(95,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(97,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(98,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(100,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"])),(n()(),Hr(102,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(103,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,14,0,e.mainData.firstName),n(t,25,0,e.mainData.lastName),n(t,36,0,"gender","Male"),n(t,37,0,""),n(t,40,0,"gender",e.mainData.gender),n(t,46,0,"gender","Female"),n(t,47,0,""),n(t,50,0,"gender",e.mainData.gender),n(t,62,0,e.mainData.emailId),n(t,74,0,e.mainData.city),n(t,85,0,e.mainData.country),n(t,89,0,e.countries),n(t,95,0,e.mainData.id)},function(n,t){n(t,11,0,vo(t,16).ngClassUntouched,vo(t,16).ngClassTouched,vo(t,16).ngClassPristine,vo(t,16).ngClassDirty,vo(t,16).ngClassValid,vo(t,16).ngClassInvalid,vo(t,16).ngClassPending),n(t,22,0,vo(t,27).ngClassUntouched,vo(t,27).ngClassTouched,vo(t,27).ngClassPristine,vo(t,27).ngClassDirty,vo(t,27).ngClassValid,vo(t,27).ngClassInvalid,vo(t,27).ngClassPending),n(t,34,0,vo(t,37).required?"":null,vo(t,42).ngClassUntouched,vo(t,42).ngClassTouched,vo(t,42).ngClassPristine,vo(t,42).ngClassDirty,vo(t,42).ngClassValid,vo(t,42).ngClassInvalid,vo(t,42).ngClassPending),n(t,44,0,vo(t,47).required?"":null,vo(t,52).ngClassUntouched,vo(t,52).ngClassTouched,vo(t,52).ngClassPristine,vo(t,52).ngClassDirty,vo(t,52).ngClassValid,vo(t,52).ngClassInvalid,vo(t,52).ngClassPending),n(t,59,0,vo(t,64).ngClassUntouched,vo(t,64).ngClassTouched,vo(t,64).ngClassPristine,vo(t,64).ngClassDirty,vo(t,64).ngClassValid,vo(t,64).ngClassInvalid,vo(t,64).ngClassPending),n(t,71,0,vo(t,76).ngClassUntouched,vo(t,76).ngClassTouched,vo(t,76).ngClassPristine,vo(t,76).ngClassDirty,vo(t,76).ngClassValid,vo(t,76).ngClassInvalid,vo(t,76).ngClassPending),n(t,82,0,vo(t,87).ngClassUntouched,vo(t,87).ngClassTouched,vo(t,87).ngClassPristine,vo(t,87).ngClassDirty,vo(t,87).ngClassValid,vo(t,87).ngClassInvalid,vo(t,87).ngClassPending),n(t,92,0,vo(t,97).ngClassUntouched,vo(t,97).ngClassTouched,vo(t,97).ngClassPristine,vo(t,97).ngClassDirty,vo(t,97).ngClassValid,vo(t,97).ngClassInvalid,vo(t,97).ngClassPending)})}function kg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-bm-wealthmanager-edit",[],null,null,null,Og,Tg)),Do(1,114688,null,0,Pg,[hg,Jf,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Dg=io("app-bm-wealthmanager-edit",Pg,kg,{mainData:"mainData"},{},[]),Ag=function(){function n(){}return n.prototype.putCustomerDetails=function(n,t){this.put("Customer-Id",n),this.put("Customer-Name",t)},n.prototype.getCustomerId=function(){return this.getWithNullCheck("Customer-Id")},n.prototype.getCustomerName=function(){return this.getWithNullCheck("Customer-Name")},n.prototype.putWealthManagerId=function(n){this.put("WealthManager-Id",n)},n.prototype.getWealthManagerId=function(){return this.getWithNullCheck("WealthManager-Id")},n.prototype.putJson=function(n,t){localStorage.setItem(n,JSON.stringify(t))},n.prototype.getJson=function(n){return JSON.parse(localStorage.getItem(n))},n.prototype.put=function(n,t){localStorage.setItem(n,t)},n.prototype.get=function(n){return localStorage.getItem(n)},n.prototype.getWithNullCheck=function(n){var t=this.get(n);return null===t&&(t=""),t},n.prototype.clear=function(){localStorage.clear()},n.ngInjectableDef=wn({factory:function(){return new n},token:n,providedIn:"root"}),n}(),Rg=function(){function n(n,t,e){this.authService=n,this.wcLocalStorageService=t,this.router=e,this.customerClass="active",this.financialPlanClass="",this.portfolioClass="",this.profileClass=""}return n.prototype.ngOnInit=function(){this.wcLocalStorageService.putWealthManagerId(30001),this.loadSessionData()},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName()},n.prototype.gotoFinancialPlan=function(){this.financialPlanClass="active",this.portfolioClass="",this.profileClass="",this.customerClass="",this.router.navigate(["/wealthmanager/financialplan"])},n.prototype.gotoPortfolio=function(){this.financialPlanClass="",this.portfolioClass="active",this.profileClass="",this.customerClass="",this.router.navigate(["/wealthmanager/portfolio"])},n.prototype.gotoProfile=function(){this.financialPlanClass="",this.portfolioClass="",this.profileClass="active",this.customerClass="",this.router.navigate(["/wealthmanager/profile"])},n.prototype.gotoCustomer=function(){this.financialPlanClass="",this.portfolioClass="",this.profileClass="",this.customerClass="active",this.router.navigate(["/wealthmanager/customer"])},n.prototype.gotoLogout=function(){this.authService.logOut(),this.router.navigate([""])},n}(),Mg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Ng(n){return ei(0,[(n()(),Hr(0,0,null,null,13,"div",[["class","container-fluid"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,8,"div",[["class","simTabHeader"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoCustomer()&&l),l},null,null)),(n()(),Jo(-1,null,["Customer"])),(n()(),Hr(4,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoFinancialPlan()&&l),l},null,null)),(n()(),Jo(-1,null,["Financial Plan"])),(n()(),Hr(6,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoPortfolio()&&l),l},null,null)),(n()(),Jo(-1,null,["Portfolio"])),(n()(),Hr(8,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoProfile()&&l),l},null,null)),(n()(),Jo(-1,null,["Profile"])),(n()(),Hr(10,0,null,null,3,"div",[["class","simTabContent"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(12,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),Do(13,212992,null,0,Gh,[qh,bl,Tt,[8,null],Cl],null,null)],function(n,t){n(t,13,0)},function(n,t){var e=t.component;n(t,2,0,jr(1,"",e.customerClass,"")),n(t,4,0,jr(1,"",e.financialPlanClass,"")),n(t,6,0,jr(1,"",e.portfolioClass,"")),n(t,8,0,jr(1,"",e.profileClass,""))})}function Lg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-homepage",[],null,null,null,Ng,Mg)),Do(1,114688,null,0,Rg,[Da,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Vg=io("app-wm-homepage",Rg,Lg,{},{},[]),Ug=function(){function n(n,t,e){this.customerService=n,this.wcLocalStorageService=t,this.router=e,this.mainData=[]}return n.prototype.ngOnInit=function(){this.getAll()},n.prototype.getAll=function(){var n=this;this.mainData=[],this.customerService.getAll().subscribe(function(t){n.mainData=t})},n.prototype.selectCustomer=function(n,t){console.log("Slect customer id-> "+n),console.log("Slect customer name-> "+t),this.wcLocalStorageService.putCustomerDetails(n,t),this.router.navigate(["/wealthmanager/financialplan"])},n}(),jg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Fg(n){return ei(0,[(n()(),Hr(0,0,null,null,13,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,12,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,[""," ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" ",", ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.selectCustomer(n.context.$implicit.id,n.context.$implicit.firstName)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["border","0"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.$implicit.firstName,t.context.$implicit.lastName),n(t,8,0,t.context.$implicit.gender,t.context.$implicit.age,t.context.$implicit.city),n(t,10,0,t.context.$implicit.startDateString)})}function Bg(n){return ei(0,[(n()(),Hr(0,0,null,null,13,"div",[["class","simCardOuter"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,12,"div",[["class","simCardInner"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","simCardImg"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"img",[["src","../../assets/img/human.png"],["width","60"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,6,"div",[["class","simContent"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,1,"p",[["class","simCardTitle"]],null,null,null,null,null)),(n()(),Jo(6,null,["Shiba Inu ",""])),(n()(),Hr(7,0,null,null,3,"p",[],null,null,null,null,null)),(n()(),Jo(8,null,[" Male, ",", "," "])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Jo(10,null,[" Member since "," "])),(n()(),Hr(11,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.selectCustomer(n.context.index,n.context.index)&&l),l},null,null)),(n()(),Hr(13,0,null,null,0,"img",[["alt","Edit"],["border","0"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null))],null,function(n,t){n(t,6,0,t.context.index),n(t,8,0,t.context.index,t.context.$implicit),n(t,10,0,t.context.index)})}function Hg(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(4,null,[" > "," (ID: ",") "])),(n()(),Hr(5,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,5,"div",[["class","simCardGrid"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,Fg)),Do(9,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Br(16777216,null,null,2,null,Bg)),Do(11,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),Xo(12,8)],function(n,t){n(t,9,0,t.component.mainData);var e=n(t,12,0,10,20,30,40,50,60,70,80);n(t,11,0,e)},function(n,t){var e=t.component;n(t,4,0,e.customerName,e.customerId)})}function zg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-customer",[],null,null,null,Hg,jg)),Do(1,114688,null,0,Ug,[Gf,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var qg=io("app-wm-customer",Ug,zg,{},{},[]),Gg=function(n){function t(t){var e=n.call(this,t)||this;return e.http=t,e}return r(t,n),t.prototype.getAll=function(){return this.getCusCus(),this.http.get(this.getURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getAllInfoByCustomerId=function(n){return this.getCusCus(),this.http.get(this.getURL()+"findInfoByCustomerId/"+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getInfoById=function(n){return this.http.get(this.getURL()+"findInfo/"+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getById=function(n){return this.http.get(this.getURL()+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.add=function(n){return console.log("add ---\x3e "+JSON.stringify(n)),this.http.post(this.getURL(),JSON.stringify(n),this.getHttpHeaders()).pipe(Wa(function(n){return console.log("added w/ id="+n.id)}),ts(this.handleError("add")))},t.prototype.update=function(n,t){return this.http.put(this.getURL(),JSON.stringify(t),this.getHttpHeaders()).pipe(Wa(function(t){return console.log("updated id="+n)}),ts(this.handleError("update")))},t.prototype.delete=function(n){return this.http.delete(this.getURL()+n,this.getHttpHeaders()).pipe(Wa(function(t){return console.log("deleted id="+n)}),ts(this.handleError("delete")))},t.prototype.getURL=function(){return this.getApiGatewayUrlFinancialplan()+"/financialplan/api/goal/"},t.ngInjectableDef=wn({factory:function(){return new t($n(ca))},token:t,providedIn:"root"}),t}(ka),Wg=function(){function n(n,t,e){this.goalService=n,this.wcLocalStorageService=t,this.router=e,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.getAllInfoByCustomerId(this.customerId)},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n.prototype.getAllInfoByCustomerId=function(n){var t=this;this.mainData=[],this.goalService.getAllInfoByCustomerId(n).subscribe(function(n){t.mainData=n})},n.prototype.addInvestment=function(n){this.router.navigate(["/wealthmanager/investmentAdd/"+n])},n.prototype.selectGoal=function(n){this.router.navigate(["/wealthmanager/financialplanDetail/"+n])},n.prototype.addGoal=function(){this.router.navigate(["/wealthmanager/goalAdd"])},n.prototype.deleteGoal=function(n){var t=this;this.goalService.delete(n).subscribe(function(n){t.getAllInfoByCustomerId(t.customerId)},function(n){console.log(n)})},n}(),Qg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function $g(n){return ei(0,[(n()(),Hr(0,0,null,null,33,"div",[["class","simCardGridType2Outer"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,11,"div",[["class","simCardGridType2Row1"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","textStyleType2"]],null,null,null,null,null)),(n()(),Jo(3,null,[" GOAL # "," : "," "])),(n()(),Hr(4,0,null,null,1,"div",[["class","textStyleType1"]],null,null,null,null,null)),(n()(),Jo(5,null,[" ( "," ) "])),(n()(),Hr(6,0,null,null,6,"div",[["class",""]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.addInvestment(n.context.$implicit.id)&&l),l},null,null)),(n()(),Hr(8,0,null,null,0,"img",[["alt","Add Investment"],["border","0"],["height","20"],["src","../../assets/img/button-add.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(9,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.selectGoal(n.context.$implicit.id)&&l),l},null,null)),(n()(),Hr(10,0,null,null,0,"img",[["alt","Goal Details"],["border","0"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.deleteGoal(n.context.$implicit.id)&&l),l},null,null)),(n()(),Hr(12,0,null,null,0,"img",[["alt","Edit"],["border","0"],["height","20"],["src","../../assets/img/button-delete.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(13,0,null,null,20,"div",[["class","simCardGridType2Row2"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(15,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Date : "])),(n()(),Hr(17,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(18,null,[" "," "])),(n()(),Hr(19,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(20,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Amount : "])),(n()(),Hr(22,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(23,null,[" "," ",""])),(n()(),Hr(24,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(25,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Investment : "])),(n()(),Hr(27,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(28,null,[" "," "," "])),(n()(),Hr(29,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(30,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Current Value : "])),(n()(),Hr(32,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(33,null,[" "," "," "]))],null,function(n,t){n(t,3,0,t.context.$implicit.goalReference,t.context.$implicit.goalDesc),n(t,5,0,t.context.$implicit.goalAchievementString),n(t,18,0,t.context.$implicit.targetDate),n(t,23,0,t.context.$implicit.currency,t.context.$implicit.targetAmount),n(t,28,0,t.context.$implicit.totalInvestmentAmount,t.context.$implicit.currency),n(t,33,0,t.context.$implicit.investmentCurrentValue,t.context.$implicit.currency)})}function Kg(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(4,null,[" > "," (ID: ",") "])),(n()(),Hr(5,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,1,"button",[["class","simButtonType1"],["title","Add Goal"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.addGoal()&&l),l},null,null)),(n()(),Jo(-1,null,["Add Goal"])),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(10,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(11,0,null,null,2,"div",[["class","simCardGridType2"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,$g)),Do(13,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(14,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(15,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){n(t,13,0,t.component.mainData)},function(n,t){var e=t.component;n(t,4,0,e.customerName,e.customerId)})}function Zg(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-financialplan",[],null,null,null,Kg,Qg)),Do(1,114688,null,0,Wg,[Gg,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Yg=io("app-wm-financialplan",Wg,Zg,{},{},[]),Xg=function(){function n(n,t,e,l,r){this.goalService=n,this.commonDataService=t,this.wcLocalStorageService=e,this.route=l,this.router=r,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.loadById()},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n.prototype.loadById=function(){var n=this;console.log("load by id ----------\x3e"+this.route.snapshot.params.id),this.goalService.getInfoById(this.route.snapshot.params.id).subscribe(function(t){n.mainData=t})},n.prototype.goback=function(){this.router.navigate(["/wealthmanager/financialplan"])},n.prototype.addInvestment=function(n){this.router.navigate(["/wealthmanager/investmentAdd/"+n])},n.prototype.deleteGoal=function(n){var t=this;this.goalService.delete(n).subscribe(function(n){t.goback()},function(n){console.log(n)})},n}(),Jg=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function nm(n){return ei(0,[(n()(),Hr(0,0,null,null,24,"tr",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(2,null,["",""])),(n()(),Hr(3,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(4,null,["",""])),(n()(),Hr(5,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(6,null,[""," "])),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(9,null,[" ",""])),(n()(),Hr(10,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(11,null,[""," "])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(14,null,["",""])),(n()(),Hr(15,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(16,null,[""," "])),(n()(),Hr(17,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(18,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(19,null,["",""])),(n()(),Hr(20,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(21,null,[""," "])),(n()(),Hr(22,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(23,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(24,null,["",""]))],null,function(n,t){n(t,2,0,t.context.$implicit.investmentDate),n(t,4,0,t.context.$implicit.investmentAmount),n(t,6,0,t.context.$implicit.stockAmount),n(t,9,0,t.context.$implicit.currentValueStockAmountString),n(t,11,0,t.context.$implicit.mutualFundAmount),n(t,14,0,t.context.$implicit.currentValueMutualFundAmountString),n(t,16,0,t.context.$implicit.fixedDepositAmount),n(t,19,0,t.context.$implicit.currentValueFixedDepositAmountString),n(t,21,0,t.context.$implicit.currentValueTotalString),n(t,24,0,t.context.$implicit.currentValueTotalComments)})}function tm(n){return ei(0,[(n()(),Hr(0,0,null,null,72,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(4,null,[" > "," (ID: ",") "])),(n()(),Hr(5,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,28,"div",[["class","simCardGridType2"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,27,"div",[["class","simCardGridType2Outer"]],null,null,null,null,null)),(n()(),Hr(9,0,null,null,5,"div",[["class","simCardGridType2Row1"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"div",[["class","textStyleType2"]],null,null,null,null,null)),(n()(),Jo(11,null,[" GOAL # "," : "," "])),(n()(),Hr(12,0,null,null,1,"div",[["class","textStyleType1"]],null,null,null,null,null)),(n()(),Jo(13,null,[" ( "," )"])),(n()(),Hr(14,0,null,null,0,"div",[["class",""]],null,null,null,null,null)),(n()(),Hr(15,0,null,null,20,"div",[["class","simCardGridType2Row2"]],null,null,null,null,null)),(n()(),Hr(16,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(17,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Date : "])),(n()(),Hr(19,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(20,null,[" "," "])),(n()(),Hr(21,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(22,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Amount : "])),(n()(),Hr(24,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(25,null,[" "," ",""])),(n()(),Hr(26,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(27,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Investment : "])),(n()(),Hr(29,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(30,null,[" "," "," "])),(n()(),Hr(31,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(32,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Current Value : "])),(n()(),Hr(34,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(35,null,[" "," "," "])),(n()(),Hr(36,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(37,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(38,0,null,null,12,"div",[],null,null,null,null,null)),(n()(),Hr(39,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(40,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(41,0,null,null,1,"button",[["class","simButtonType1"],["title","Add Investment"]],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.addInvestment(r.mainData.id)&&l),l},null,null)),(n()(),Jo(-1,null,["Add Investment"])),(n()(),Jo(-1,null,[" \xa0\xa0 "])),(n()(),Hr(44,0,null,null,1,"button",[["class","simButtonType1"],["title","Delete Goal"]],null,[[null,"click"]],function(n,t,e){var l=!0,r=n.component;return"click"===t&&(l=!1!==r.deleteGoal(r.mainData.id)&&l),l},null,null)),(n()(),Jo(-1,null,["Delete Goal"])),(n()(),Jo(-1,null,["\xa0\xa0 "])),(n()(),Hr(47,0,null,null,1,"button",[["class","simButtonType1"],["title","Back"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.goback()&&l),l},null,null)),(n()(),Jo(-1,null,["Back"])),(n()(),Hr(49,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(50,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(51,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(52,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(53,0,null,null,19,"div",[["class","width900"]],null,null,null,null,null)),(n()(),Hr(54,0,null,null,18,"div",[["style","width:900px; height:320px; overflow: auto;text-align: center;"]],null,null,null,null,null)),(n()(),Hr(55,0,null,null,17,"table",[["class","width900"],["id","tableType1"]],null,null,null,null,null)),(n()(),Hr(56,0,null,null,13,"thead",[],null,null,null,null,null)),(n()(),Hr(57,0,null,null,12,"tr",[],null,null,null,null,null)),(n()(),Hr(58,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Date"])),(n()(),Hr(60,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Amount"])),(n()(),Hr(62,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Stocks"])),(n()(),Hr(64,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Mutual Fund"])),(n()(),Hr(66,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Fixed Deposit"])),(n()(),Hr(68,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Current Value"])),(n()(),Hr(70,0,null,null,2,"tbody",[],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,nm)),Do(72,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null)],function(n,t){n(t,72,0,t.component.mainData.investments)},function(n,t){var e=t.component;n(t,4,0,e.customerName,e.customerId),n(t,11,0,e.mainData.goalReference,e.mainData.goalDesc),n(t,13,0,e.mainData.goalAchievementString),n(t,20,0,e.mainData.targetDate),n(t,25,0,e.mainData.currency,e.mainData.targetAmount),n(t,30,0,e.mainData.totalInvestmentAmount,e.mainData.currency),n(t,35,0,e.mainData.investmentCurrentValue,e.mainData.currency)})}function em(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-financialplan-detail",[],null,null,null,tm,Jg)),Do(1,114688,null,0,Xg,[Gg,Jf,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var lm=io("app-wm-financialplan-detail",Xg,em,{},{},[]),rm=function(){function n(n,t,e,l,r){this.goalService=n,this.commonDataService=t,this.wcLocalStorageService=e,this.route=l,this.router=r,this.mainData={wcCustomerId:0,wcWealthManagerId:0,goalReference:"",goalDesc:"",targetDate:"2025-12-25",targetAmount:100}}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.mainData.wcCustomerId=this.customerId,this.mainData.wcWealthManagerId=this.wealthManagerId},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n.prototype.save=function(){var n=this;this.goalService.add(this.mainData).subscribe(function(t){n.router.navigate(["/wealthmanager/financialplan"])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/wealthmanager/financialplan"])},n}(),om=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function im(n){return ei(0,[(n()(),Hr(0,0,null,null,75,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(3,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(5,null,[" > "," (ID: ",") "])),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(9,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Add New Goal"])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,62,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(15,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(16,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Goal Reference"])),(n()(),Hr(18,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,5,"input",[["placeholder","Goal Reference"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,20)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,20).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,20)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,20)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.goalReference=e)&&l),l},null,null)),Do(20,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(22,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(24,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(25,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(26,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(27,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Description"])),(n()(),Hr(29,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,5,"input",[["placeholder","Description"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,31)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,31).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,31)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,31)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.goalDesc=e)&&l),l},null,null)),Do(31,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(33,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(35,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(36,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(37,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(38,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Date"])),(n()(),Hr(40,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,5,"input",[["placeholder","Target Date"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,42)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,42).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,42)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,42)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.targetDate=e)&&l),l},null,null)),Do(42,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(44,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(46,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(47,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(48,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(49,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Amount"])),(n()(),Hr(51,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(52,0,null,null,5,"input",[["placeholder","Target Amount"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,53)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,53).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,53)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,53)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.targetAmount=e)&&l),l},null,null)),Do(53,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(55,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(57,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(58,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(59,0,null,null,16,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(60,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,61)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,61).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,61)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,61)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.wcCustomerId=e)&&l),l},null,null)),Do(61,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(63,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(65,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(66,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,67)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,67).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,67)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,67)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.wcWealthManagerId=e)&&l),l},null,null)),Do(67,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(69,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(71,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(72,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(74,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"]))],function(n,t){var e=t.component;n(t,22,0,e.mainData.goalReference),n(t,33,0,e.mainData.goalDesc),n(t,44,0,e.mainData.targetDate),n(t,55,0,e.mainData.targetAmount),n(t,63,0,e.mainData.wcCustomerId),n(t,69,0,e.mainData.wcWealthManagerId)},function(n,t){var e=t.component;n(t,5,0,e.customerName,e.customerId),n(t,19,0,vo(t,24).ngClassUntouched,vo(t,24).ngClassTouched,vo(t,24).ngClassPristine,vo(t,24).ngClassDirty,vo(t,24).ngClassValid,vo(t,24).ngClassInvalid,vo(t,24).ngClassPending),n(t,30,0,vo(t,35).ngClassUntouched,vo(t,35).ngClassTouched,vo(t,35).ngClassPristine,vo(t,35).ngClassDirty,vo(t,35).ngClassValid,vo(t,35).ngClassInvalid,vo(t,35).ngClassPending),n(t,41,0,vo(t,46).ngClassUntouched,vo(t,46).ngClassTouched,vo(t,46).ngClassPristine,vo(t,46).ngClassDirty,vo(t,46).ngClassValid,vo(t,46).ngClassInvalid,vo(t,46).ngClassPending),n(t,52,0,vo(t,57).ngClassUntouched,vo(t,57).ngClassTouched,vo(t,57).ngClassPristine,vo(t,57).ngClassDirty,vo(t,57).ngClassValid,vo(t,57).ngClassInvalid,vo(t,57).ngClassPending),n(t,60,0,vo(t,65).ngClassUntouched,vo(t,65).ngClassTouched,vo(t,65).ngClassPristine,vo(t,65).ngClassDirty,vo(t,65).ngClassValid,vo(t,65).ngClassInvalid,vo(t,65).ngClassPending),n(t,66,0,vo(t,71).ngClassUntouched,vo(t,71).ngClassTouched,vo(t,71).ngClassPristine,vo(t,71).ngClassDirty,vo(t,71).ngClassValid,vo(t,71).ngClassInvalid,vo(t,71).ngClassPending)})}function um(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-financialplan-goal-add",[],null,null,null,im,om)),Do(1,114688,null,0,rm,[Gg,Jf,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var am=io("app-wm-financialplan-goal-add",rm,um,{mainData:"mainData"},{},[]),sm=function(n){function t(t){var e=n.call(this,t)||this;return e.http=t,e}return r(t,n),t.prototype.getAll=function(){return this.getCusCus(),this.http.get(this.getURL(),this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getAllByGoalId=function(n){return this.getCusCus(),this.http.get(this.getURL()+"findByGoalId/"+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.getById=function(n){return this.http.get(this.getURL()+n,this.getHttpHeaders()).pipe(nn(this.extractData))},t.prototype.add=function(n){return console.log("add ---\x3e "+JSON.stringify(n)),this.http.post(this.getURL(),JSON.stringify(n),this.getHttpHeaders()).pipe(Wa(function(n){return console.log("added w/ id="+n.id)}),ts(this.handleError("add")))},t.prototype.update=function(n,t){return this.http.put(this.getURL(),JSON.stringify(t),this.getHttpHeaders()).pipe(Wa(function(t){return console.log("updated id="+n)}),ts(this.handleError("update")))},t.prototype.delete=function(n){return this.http.delete(this.getURL()+n,this.getHttpHeaders()).pipe(Wa(function(t){return console.log("deleted id="+n)}),ts(this.handleError("delete")))},t.prototype.getURL=function(){return this.getApiGatewayUrlFinancialplan()+"/financialplan/api/investment/"},t.ngInjectableDef=wn({factory:function(){return new t($n(ca))},token:t,providedIn:"root"}),t}(ka),cm=function(){function n(n,t,e,l,r){this.investmentService=n,this.commonDataService=t,this.wcLocalStorageService=e,this.route=l,this.router=r,this.mainData={wcGoalId:0,investmentDate:"2019-10-17",investmentAmount:100,wcWealthManagerId:0}}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.mainData.wcGoalId=this.route.snapshot.params.id},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n.prototype.save=function(){var n=this;this.investmentService.add(this.mainData).subscribe(function(t){n.router.navigate(["/wealthmanager/financialplanDetail/"+ +n.mainData.wcGoalId])},function(n){console.log(n)})},n.prototype.cancel=function(){this.router.navigate(["/wealthmanager/financialplanDetail/"+this.mainData.wcGoalId])},n}(),pm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function hm(n){return ei(0,[(n()(),Hr(0,0,null,null,60,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(3,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(5,null,[" > "," (ID: ",") "])),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(9,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Add New Investment"])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,47,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,5,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(15,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(16,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Goal Reference"])),(n()(),Hr(18,0,null,null,1,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Jo(19,null,["",""])),(n()(),Hr(20,0,null,null,6,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(21,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(22,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Description"])),(n()(),Hr(24,0,null,null,2,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(25,0,null,null,1,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Jo(26,null,["",""])),(n()(),Hr(27,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(28,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(29,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Date"])),(n()(),Hr(31,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(32,0,null,null,5,"input",[["placeholder","Investment Date"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,33)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,33).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,33)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,33)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.investmentDate=e)&&l),l},null,null)),Do(33,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(35,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(37,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(38,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(39,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(40,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Amount"])),(n()(),Hr(42,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(43,0,null,null,5,"input",[["placeholder","Investment Amount"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,44)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,44).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,44)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,44)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.investmentAmount=e)&&l),l},null,null)),Do(44,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(46,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(48,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(49,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(50,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(51,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,52)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,52).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,52)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,52)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.wcGoalId=e)&&l),l},null,null)),Do(52,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(54,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(56,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(57,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.save()&&l),l},null,null)),(n()(),Jo(-1,null,["Save"])),(n()(),Hr(59,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.cancel()&&l),l},null,null)),(n()(),Jo(-1,null,["Cancel"]))],function(n,t){var e=t.component;n(t,35,0,e.mainData.investmentDate),n(t,46,0,e.mainData.investmentAmount),n(t,54,0,e.mainData.wcGoalId)},function(n,t){var e=t.component;n(t,5,0,e.customerName,e.customerId),n(t,19,0,e.mainData.goalReference),n(t,26,0,e.mainData.desc),n(t,32,0,vo(t,37).ngClassUntouched,vo(t,37).ngClassTouched,vo(t,37).ngClassPristine,vo(t,37).ngClassDirty,vo(t,37).ngClassValid,vo(t,37).ngClassInvalid,vo(t,37).ngClassPending),n(t,43,0,vo(t,48).ngClassUntouched,vo(t,48).ngClassTouched,vo(t,48).ngClassPristine,vo(t,48).ngClassDirty,vo(t,48).ngClassValid,vo(t,48).ngClassInvalid,vo(t,48).ngClassPending),n(t,51,0,vo(t,56).ngClassUntouched,vo(t,56).ngClassTouched,vo(t,56).ngClassPristine,vo(t,56).ngClassDirty,vo(t,56).ngClassValid,vo(t,56).ngClassInvalid,vo(t,56).ngClassPending)})}function dm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-financialplan-investment-add",[],null,null,null,hm,pm)),Do(1,114688,null,0,cm,[sm,Jf,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var fm=io("app-wm-financialplan-investment-add",cm,dm,{mainData:"mainData"},{},[]),gm=function(){function n(n,t,e,l){this.goalService=n,this.wcLocalStorageService=t,this.route=e,this.router=l,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.getAllInfoByCustomerId(this.customerId)},n.prototype.getAllInfoByCustomerId=function(n){var t=this;this.mainData=[],this.goalService.getAllInfoByCustomerId(n).subscribe(function(n){t.mainData=n})},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n}(),mm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function ym(n){return ei(0,[(n()(),Hr(0,0,null,null,28,"tr",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(2,null,["",""])),(n()(),Hr(3,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(4,null,["",""])),(n()(),Hr(5,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(6,null,["",""])),(n()(),Hr(7,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(8,null,["",""])),(n()(),Hr(9,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(10,null,[""," "])),(n()(),Hr(11,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(12,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(13,null,[" ",""])),(n()(),Hr(14,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(15,null,[""," "])),(n()(),Hr(16,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(17,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(18,null,["",""])),(n()(),Hr(19,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(20,null,[""," "])),(n()(),Hr(21,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(22,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(23,null,["",""])),(n()(),Hr(24,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(25,null,[""," "])),(n()(),Hr(26,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(27,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(28,null,["",""]))],null,function(n,t){n(t,2,0,t.parent.context.$implicit.goalReference),n(t,4,0,t.parent.context.$implicit.goalDesc),n(t,6,0,t.context.$implicit.investmentDate),n(t,8,0,t.context.$implicit.investmentAmount),n(t,10,0,t.context.$implicit.stockAmount),n(t,13,0,t.context.$implicit.currentValueStockAmountString),n(t,15,0,t.context.$implicit.mutualFundAmount),n(t,18,0,t.context.$implicit.currentValueMutualFundAmountString),n(t,20,0,t.context.$implicit.fixedDepositAmount),n(t,23,0,t.context.$implicit.currentValueFixedDepositAmountString),n(t,25,0,t.context.$implicit.currentValueTotalString),n(t,28,0,t.context.$implicit.currentValueTotalComments)})}function vm(n){return ei(0,[(n()(),Hr(0,0,null,null,2,null,null,null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,ym)),Do(2,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Br(0,null,null,0))],function(n,t){n(t,2,0,t.context.$implicit.investments)},null)}function _m(n){return ei(0,[(n()(),Hr(0,0,null,null,36,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(3,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(5,null,[" > "," (ID: ",") "])),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(9,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Customer Portfolio"])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,23,"div",[["class","row divCenter1000"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,22,"div",[["style","width:1000px; height:320px; overflow: auto;text-align: center;"]],null,null,null,null,null)),(n()(),Hr(15,0,null,null,21,"table",[["class","width900"],["id","tableType1"]],null,null,null,null,null)),(n()(),Hr(16,0,null,null,17,"thead",[],null,null,null,null,null)),(n()(),Hr(17,0,null,null,16,"tr",[],null,null,null,null,null)),(n()(),Hr(18,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Goal Reference"])),(n()(),Hr(20,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Goal Desc"])),(n()(),Hr(22,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Date"])),(n()(),Hr(24,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Amount"])),(n()(),Hr(26,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Stocks"])),(n()(),Hr(28,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Mutual Fund"])),(n()(),Hr(30,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Fixed Deposit"])),(n()(),Hr(32,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Current Value"])),(n()(),Hr(34,0,null,null,2,"tbody",[],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,vm)),Do(36,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null)],function(n,t){n(t,36,0,t.component.mainData)},function(n,t){var e=t.component;n(t,5,0,e.customerName,e.customerId)})}function bm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-portfolio",[],null,null,null,_m,mm)),Do(1,114688,null,0,gm,[Gg,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var wm=io("app-wm-portfolio",gm,bm,{},{},[]),Cm=function(){function n(n,t,e){this.customerService=n,this.wcLocalStorageService=t,this.router=e,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.getAll()},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName(),this.wealthManagerId=this.wcLocalStorageService.getWealthManagerId()},n.prototype.getAll=function(){var n=this;this.mainData=[],this.customerService.getById(this.customerId).subscribe(function(t){n.mainData=t})},n}(),Sm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Em(n){return ei(0,[(n()(),Hr(0,0,null,null,121,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(3,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(5,null,[" > "," (ID: ",") "])),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(9,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Customer Profile"])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,108,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(14,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(15,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(16,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(18,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,20)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,20).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,20)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,20)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(20,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(22,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(24,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(25,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(26,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(27,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(29,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,31)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,31).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,31)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,31)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(31,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(33,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(35,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(36,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(37,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(38,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Age"])),(n()(),Hr(40,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,5,"input",[["placeholder","Age"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,42)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,42).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,42)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,42)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.age=e)&&l),l},null,null)),Do(42,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(44,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(46,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(47,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(48,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(49,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(51,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(52,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(53,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,54)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,54).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,54)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,54)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,55).onChange()&&l),"blur"===t&&(l=!1!==vo(n,55).onTouched()&&l),l},null,null)),Do(54,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(55,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(56,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(59,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(61,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(63,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,64)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,64).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,64)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,64)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,65).onChange()&&l),"blur"===t&&(l=!1!==vo(n,65).onTouched()&&l),l},null,null)),Do(64,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(65,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(66,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(69,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(71,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(73,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(74,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(75,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(77,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,79)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,79).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,79)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,79)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(79,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(81,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(83,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(84,0,null,null,6,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(85,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(86,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(88,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(89,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(90,null,["",""])),(n()(),Hr(91,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(92,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(93,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(95,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(96,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(97,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,98)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,98).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,98)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,98)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(98,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(100,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(102,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(103,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(104,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(105,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Income"])),(n()(),Hr(107,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(108,0,null,null,5,"input",[["placeholder","Income"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,109)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,109).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,109)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,109)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.avgIncome=e)&&l),l},null,null)),Do(109,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(111,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(113,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(114,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(115,0,null,null,6,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(116,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,117)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,117).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,117)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,117)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.id=e)&&l),l},null,null)),Do(117,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(119,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(121,16384,null,0,ef,[[4,Ld]],null,null)],function(n,t){var e=t.component;n(t,22,0,e.mainData.firstName),n(t,33,0,e.mainData.lastName),n(t,44,0,e.mainData.age),n(t,55,0,"gender","Male"),n(t,56,0,""),n(t,59,0,"gender",e.mainData.gender),n(t,65,0,"gender","Female"),n(t,66,0,""),n(t,69,0,"gender",e.mainData.gender),n(t,81,0,e.mainData.emailId),n(t,100,0,e.mainData.city),n(t,111,0,e.mainData.avgIncome),n(t,119,0,e.mainData.id)},function(n,t){var e=t.component;n(t,5,0,e.customerName,e.customerId),n(t,19,0,vo(t,24).ngClassUntouched,vo(t,24).ngClassTouched,vo(t,24).ngClassPristine,vo(t,24).ngClassDirty,vo(t,24).ngClassValid,vo(t,24).ngClassInvalid,vo(t,24).ngClassPending),n(t,30,0,vo(t,35).ngClassUntouched,vo(t,35).ngClassTouched,vo(t,35).ngClassPristine,vo(t,35).ngClassDirty,vo(t,35).ngClassValid,vo(t,35).ngClassInvalid,vo(t,35).ngClassPending),n(t,41,0,vo(t,46).ngClassUntouched,vo(t,46).ngClassTouched,vo(t,46).ngClassPristine,vo(t,46).ngClassDirty,vo(t,46).ngClassValid,vo(t,46).ngClassInvalid,vo(t,46).ngClassPending),n(t,53,0,vo(t,56).required?"":null,vo(t,61).ngClassUntouched,vo(t,61).ngClassTouched,vo(t,61).ngClassPristine,vo(t,61).ngClassDirty,vo(t,61).ngClassValid,vo(t,61).ngClassInvalid,vo(t,61).ngClassPending),n(t,63,0,vo(t,66).required?"":null,vo(t,71).ngClassUntouched,vo(t,71).ngClassTouched,vo(t,71).ngClassPristine,vo(t,71).ngClassDirty,vo(t,71).ngClassValid,vo(t,71).ngClassInvalid,vo(t,71).ngClassPending),n(t,78,0,vo(t,83).ngClassUntouched,vo(t,83).ngClassTouched,vo(t,83).ngClassPristine,vo(t,83).ngClassDirty,vo(t,83).ngClassValid,vo(t,83).ngClassInvalid,vo(t,83).ngClassPending),n(t,90,0,e.mainData.country),n(t,97,0,vo(t,102).ngClassUntouched,vo(t,102).ngClassTouched,vo(t,102).ngClassPristine,vo(t,102).ngClassDirty,vo(t,102).ngClassValid,vo(t,102).ngClassInvalid,vo(t,102).ngClassPending),n(t,108,0,vo(t,113).ngClassUntouched,vo(t,113).ngClassTouched,vo(t,113).ngClassPristine,vo(t,113).ngClassDirty,vo(t,113).ngClassValid,vo(t,113).ngClassInvalid,vo(t,113).ngClassPending),n(t,116,0,vo(t,121).ngClassUntouched,vo(t,121).ngClassTouched,vo(t,121).ngClassPristine,vo(t,121).ngClassDirty,vo(t,121).ngClassValid,vo(t,121).ngClassInvalid,vo(t,121).ngClassPending)})}function xm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-wm-profile",[],null,null,null,Em,Sm)),Do(1,114688,null,0,Cm,[Gf,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Pm=io("app-wm-profile",Cm,xm,{},{},[]),Tm=function(){function n(n,t,e){this.authService=n,this.wcLocalStorageService=t,this.router=e,this.financialPlanClass="active",this.portfolioClass="",this.profileClass=""}return n.prototype.ngOnInit=function(){this.wcLocalStorageService.putCustomerDetails(40001,"Nathan Kumar"),this.loadSessionData()},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName()},n.prototype.gotoFinancialPlan=function(){this.financialPlanClass="active",this.portfolioClass="",this.profileClass="",this.router.navigate(["/customer/financialplan"])},n.prototype.gotoPortfolio=function(){this.financialPlanClass="",this.portfolioClass="active",this.profileClass="",this.router.navigate(["/customer/financialplanDetail"])},n.prototype.gotoProfile=function(){this.financialPlanClass="",this.portfolioClass="",this.profileClass="active",this.router.navigate(["/customer/profile"])},n.prototype.gotoLogout=function(){this.authService.logOut(),this.router.navigate([""])},n}(),Im=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Om(n){return ei(0,[(n()(),Hr(0,0,null,null,15,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,6,"div",[["class","simTabHeader"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoFinancialPlan()&&l),l},null,null)),(n()(),Jo(-1,null,["Financial Plan"])),(n()(),Hr(4,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoPortfolio()&&l),l},null,null)),(n()(),Jo(-1,null,["Portfolio"])),(n()(),Hr(6,0,null,null,1,"button",[],[[8,"className",0]],[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoProfile()&&l),l},null,null)),(n()(),Jo(-1,null,["Profile"])),(n()(),Hr(8,0,null,null,7,"div",[["class","simTabContent"]],null,null,null,null,null)),(n()(),Hr(9,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(10,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["CUSTOMER"])),(n()(),Jo(12,null,[" > "," (ID: ",") "])),(n()(),Hr(13,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(14,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),Do(15,212992,null,0,Gh,[qh,bl,Tt,[8,null],Cl],null,null)],function(n,t){n(t,15,0)},function(n,t){var e=t.component;n(t,2,0,jr(1,"",e.financialPlanClass,"")),n(t,4,0,jr(1,"",e.portfolioClass,"")),n(t,6,0,jr(1,"",e.profileClass,"")),n(t,12,0,e.customerName,e.customerId)})}function km(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-customer-homepage",[],null,null,null,Om,Im)),Do(1,114688,null,0,Tm,[Da,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Dm=io("app-customer-homepage",Tm,km,{},{},[]),Am=function(){function n(n,t,e,l){this.goalService=n,this.wcLocalStorageService=t,this.route=e,this.router=l,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.getAllInfoByCustomerId(this.customerId)},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName()},n.prototype.getAllInfoByCustomerId=function(n){var t=this;this.mainData=[],this.goalService.getAllInfoByCustomerId(n).subscribe(function(n){t.mainData=n})},n.prototype.goback=function(){this.router.navigate(["/customer/financialplan"])},n.prototype.selectGoal=function(n){this.router.navigate(["/customer/financialplanDetail/"+n])},n}(),Rm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Mm(n){return ei(0,[(n()(),Hr(0,0,null,null,29,"div",[["class","simCardGridType2Outer"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,7,"div",[["class","simCardGridType2Row1"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,1,"div",[["class","textStyleType2"]],null,null,null,null,null)),(n()(),Jo(3,null,[" GOAL # "," : "," "])),(n()(),Hr(4,0,null,null,1,"div",[["class","textStyleType1"]],null,null,null,null,null)),(n()(),Jo(5,null,[" ( "," ) "])),(n()(),Hr(6,0,null,null,2,"div",[["class",""]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,1,"a",[],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.selectGoal(n.context.$implicit.id)&&l),l},null,null)),(n()(),Hr(8,0,null,null,0,"img",[["alt","Goal Details"],["height","20"],["src","../../assets/img/button-edit.png"],["width","20"]],null,null,null,null,null)),(n()(),Hr(9,0,null,null,20,"div",[["class","simCardGridType2Row2"]],null,null,null,null,null)),(n()(),Hr(10,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(11,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Date : "])),(n()(),Hr(13,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(14,null,[" "," "])),(n()(),Hr(15,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(16,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Amount : "])),(n()(),Hr(18,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(19,null,[" "," ",""])),(n()(),Hr(20,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(21,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Investment : "])),(n()(),Hr(23,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(24,null,[" "," "," "])),(n()(),Hr(25,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(26,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Current Value : "])),(n()(),Hr(28,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(29,null,[" "," "," "]))],null,function(n,t){n(t,3,0,t.context.$implicit.goalReference,t.context.$implicit.goalDesc),n(t,5,0,t.context.$implicit.goalAchievementString),n(t,14,0,t.context.$implicit.targetDate),n(t,19,0,t.context.$implicit.currency,t.context.$implicit.targetAmount),n(t,24,0,t.context.$implicit.totalInvestmentAmount,t.context.$implicit.currency),n(t,29,0,t.context.$implicit.investmentCurrentValue,t.context.$implicit.currency)})}function Nm(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,2,"div",[["class","simCardGridType2"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,Mm)),Do(4,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null),(n()(),Hr(5,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(6,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){n(t,4,0,t.component.mainData)},null)}function Lm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-customer-financialplan",[],null,null,null,Nm,Rm)),Do(1,114688,null,0,Am,[Gg,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var Vm=io("app-customer-financialplan",Am,Lm,{},{},[]),Um=function(){function n(n,t,e,l){this.goalService=n,this.wcLocalStorageService=t,this.route=e,this.router=l,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.loadById()},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName()},n.prototype.loadById=function(){var n=this;console.log("load by id ----------\x3e"+this.route.snapshot.params.id),this.goalService.getInfoById(this.route.snapshot.params.id).subscribe(function(t){n.mainData=t})},n.prototype.goback=function(){this.router.navigate(["/customer/financialplan"])},n}(),jm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Fm(n){return ei(0,[(n()(),Hr(0,0,null,null,24,"tr",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(2,null,["",""])),(n()(),Hr(3,0,null,null,1,"td",[],null,null,null,null,null)),(n()(),Jo(4,null,["",""])),(n()(),Hr(5,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(6,null,[""," "])),(n()(),Hr(7,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(8,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(9,null,[" ",""])),(n()(),Hr(10,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(11,null,[""," "])),(n()(),Hr(12,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(14,null,["",""])),(n()(),Hr(15,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(16,null,[""," "])),(n()(),Hr(17,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(18,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(19,null,["",""])),(n()(),Hr(20,0,null,null,4,"td",[],null,null,null,null,null)),(n()(),Jo(21,null,[""," "])),(n()(),Hr(22,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(23,0,null,null,1,"span",[["class","textStyleType3"]],null,null,null,null,null)),(n()(),Jo(24,null,["",""]))],null,function(n,t){n(t,2,0,t.context.$implicit.investmentDate),n(t,4,0,t.context.$implicit.investmentAmount),n(t,6,0,t.context.$implicit.stockAmount),n(t,9,0,t.context.$implicit.currentValueStockAmountString),n(t,11,0,t.context.$implicit.mutualFundAmount),n(t,14,0,t.context.$implicit.currentValueMutualFundAmountString),n(t,16,0,t.context.$implicit.fixedDepositAmount),n(t,19,0,t.context.$implicit.currentValueFixedDepositAmountString),n(t,21,0,t.context.$implicit.currentValueTotalString),n(t,24,0,t.context.$implicit.currentValueTotalComments)})}function Bm(n){return ei(0,[(n()(),Hr(0,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,55,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,28,"div",[["class","simCardGridType2"]],null,null,null,null,null)),(n()(),Hr(4,0,null,null,27,"div",[["class","simCardGridType2Outer"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,5,"div",[["class","simCardGridType2Row1"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,1,"div",[["class","textStyleType2"]],null,null,null,null,null)),(n()(),Jo(7,null,[" GOAL # "," : "," "])),(n()(),Hr(8,0,null,null,1,"div",[["class","textStyleType1"]],null,null,null,null,null)),(n()(),Jo(9,null,[" ( "," )"])),(n()(),Hr(10,0,null,null,0,"div",[["class",""]],null,null,null,null,null)),(n()(),Hr(11,0,null,null,20,"div",[["class","simCardGridType2Row2"]],null,null,null,null,null)),(n()(),Hr(12,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Date : "])),(n()(),Hr(15,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(16,null,[" "," "])),(n()(),Hr(17,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(18,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Amount : "])),(n()(),Hr(20,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(21,null,[" "," ",""])),(n()(),Hr(22,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(23,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Target Investment : "])),(n()(),Hr(25,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(26,null,[" "," "," "])),(n()(),Hr(27,0,null,null,2,"div",[],null,null,null,null,null)),(n()(),Hr(28,0,null,null,1,"strong",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Current Value : "])),(n()(),Hr(30,0,null,null,1,"div",[],null,null,null,null,null)),(n()(),Jo(31,null,[" "," "," "])),(n()(),Hr(32,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(33,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(34,0,null,null,1,"button",[["class","simButtonType1"],["title","Back"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.goback()&&l),l},null,null)),(n()(),Jo(-1,null,["Back"])),(n()(),Hr(36,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(37,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(38,0,null,null,19,"div",[["class","width900"]],null,null,null,null,null)),(n()(),Hr(39,0,null,null,18,"div",[["style","width:900px; height:320px; overflow: auto;text-align: center;"]],null,null,null,null,null)),(n()(),Hr(40,0,null,null,17,"table",[["class","width900"],["id","tableType1"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,13,"thead",[],null,null,null,null,null)),(n()(),Hr(42,0,null,null,12,"tr",[],null,null,null,null,null)),(n()(),Hr(43,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Date"])),(n()(),Hr(45,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Investment Amount"])),(n()(),Hr(47,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Stocks"])),(n()(),Hr(49,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Mutual Fund"])),(n()(),Hr(51,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Fixed Deposit"])),(n()(),Hr(53,0,null,null,1,"th",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Current Value"])),(n()(),Hr(55,0,null,null,2,"tbody",[],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,Fm)),Do(57,278528,null,0,Nu,[bl,de,Fl],{ngForOf:[0,"ngForOf"]},null)],function(n,t){n(t,57,0,t.component.mainData.investments)},function(n,t){var e=t.component;n(t,7,0,e.mainData.goalReference,e.mainData.goalDesc),n(t,9,0,e.mainData.goalAchievementString),n(t,16,0,e.mainData.targetDate),n(t,21,0,e.mainData.currency,e.mainData.targetAmount),n(t,26,0,e.mainData.totalInvestmentAmount,e.mainData.currency),n(t,31,0,e.mainData.investmentCurrentValue,e.mainData.currency)})}function Hm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-customer-portfolio",[],null,null,null,Bm,jm)),Do(1,114688,null,0,Um,[Gg,Ag,Ap,Hh],null,null)],function(n,t){n(t,1,0)},null)}var zm=io("app-customer-portfolio",Um,Hm,{},{},[]),qm=function(){function n(n,t,e){this.customerService=n,this.wcLocalStorageService=t,this.router=e,this.mainData=[]}return n.prototype.ngOnInit=function(){this.loadSessionData(),this.getById(this.customerId)},n.prototype.loadSessionData=function(){this.customerId=this.wcLocalStorageService.getCustomerId(),this.customerName=this.wcLocalStorageService.getCustomerName()},n.prototype.getById=function(n){var t=this;this.mainData=[],this.customerService.getById(n).subscribe(function(n){t.mainData=n})},n.prototype.goback=function(){this.router.navigate(["/customer/financialplan"])},n}(),Gm=dr({encapsulation:0,styles:[[""],yd,jf],data:{}});function Wm(n){return ei(0,[(n()(),Hr(0,0,null,null,117,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(2,0,null,null,2,"div",[["class","screenHeading"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,1,"span",[],null,null,null,null,null)),(n()(),Jo(-1,null,["My Profile"])),(n()(),Hr(5,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(6,0,null,null,111,"div",[["class","divCenter500"]],null,null,null,null,null)),(n()(),Hr(7,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(8,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(9,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["First Name"])),(n()(),Hr(11,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(12,0,null,null,5,"input",[["placeholder","First Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,13)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,13).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,13)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,13)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.firstName=e)&&l),l},null,null)),Do(13,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(15,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(17,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(18,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(19,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(20,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Last Name"])),(n()(),Hr(22,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(23,0,null,null,5,"input",[["placeholder","Last Name"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,24)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,24).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,24)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,24)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.lastName=e)&&l),l},null,null)),Do(24,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(26,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(28,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(29,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(30,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(31,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Age"])),(n()(),Hr(33,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(34,0,null,null,5,"input",[["placeholder","Age"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,35)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,35).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,35)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,35)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.age=e)&&l),l},null,null)),Do(35,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(37,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(39,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(40,0,null,null,25,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(41,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(42,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Gender"])),(n()(),Hr(44,0,null,null,21,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(45,0,null,null,20,"p",[],null,null,null,null,null)),(n()(),Hr(46,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Male"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,47)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,47).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,47)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,47)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,48).onChange()&&l),"blur"===t&&(l=!1!==vo(n,48).onTouched()&&l),l},null,null)),Do(47,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(48,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(49,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(52,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(54,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Male "])),(n()(),Hr(56,0,null,null,8,"input",[["name","gender"],["required",""],["type","radio"],["value","Female"]],[[1,"required",0],[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"],[null,"change"]],function(n,t,e){var l=!0;return"input"===t&&(l=!1!==vo(n,57)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,57).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,57)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,57)._compositionEnd(e.target.value)&&l),"change"===t&&(l=!1!==vo(n,58).onChange()&&l),"blur"===t&&(l=!1!==vo(n,58).onTouched()&&l),l},null,null)),Do(57,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Do(58,212992,null,0,Ud,[Vt,At,Vd,ut],{name:[0,"name"],value:[1,"value"]},null),Do(59,16384,null,0,_f,[],{required:[0,"required"]},null),Ao(1024,null,Cd,function(n){return[n]},[_f]),Ao(1024,null,Id,function(n,t){return[n,t]},[Dd,Ud]),Do(62,671744,[["gender",4]],0,yf,[[8,null],[6,Cd],[8,null],[6,Id]],{name:[0,"name"],model:[1,"model"]},null),Ao(2048,null,Ld,null,[yf]),Do(64,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Jo(-1,null,[" Female "])),(n()(),Hr(66,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(67,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(68,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Email"])),(n()(),Hr(70,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(71,0,null,null,5,"input",[["placeholder","Email"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,72)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,72).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,72)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,72)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.emailId=e)&&l),l},null,null)),Do(72,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(74,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(76,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(77,0,null,null,6,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(78,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(79,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Country"])),(n()(),Hr(81,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(82,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(83,null,["",""])),(n()(),Hr(84,0,null,null,11,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(85,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(86,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["City"])),(n()(),Hr(88,0,null,null,7,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(89,0,null,null,6,"p",[],null,null,null,null,null)),(n()(),Hr(90,0,null,null,5,"input",[["placeholder","City"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,91)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,91).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,91)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,91)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.city=e)&&l),l},null,null)),Do(91,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(93,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(95,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(96,0,null,null,10,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(97,0,null,null,2,"div",[["class","col-sm-3"]],null,null,null,null,null)),(n()(),Hr(98,0,null,null,1,"p",[],null,null,null,null,null)),(n()(),Jo(-1,null,["Income"])),(n()(),Hr(100,0,null,null,6,"div",[["class","col-sm-5"]],null,null,null,null,null)),(n()(),Hr(101,0,null,null,5,"input",[["placeholder","Income"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,102)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,102).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,102)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,102)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.avgIncome=e)&&l),l},null,null)),Do(102,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(104,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(106,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(107,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(108,0,null,null,8,"div",[["class","row"]],null,null,null,null,null)),(n()(),Hr(109,0,null,null,5,"input",[["type","hidden"]],[[2,"ng-untouched",null],[2,"ng-touched",null],[2,"ng-pristine",null],[2,"ng-dirty",null],[2,"ng-valid",null],[2,"ng-invalid",null],[2,"ng-pending",null]],[[null,"ngModelChange"],[null,"input"],[null,"blur"],[null,"compositionstart"],[null,"compositionend"]],function(n,t,e){var l=!0,r=n.component;return"input"===t&&(l=!1!==vo(n,110)._handleInput(e.target.value)&&l),"blur"===t&&(l=!1!==vo(n,110).onTouched()&&l),"compositionstart"===t&&(l=!1!==vo(n,110)._compositionStart()&&l),"compositionend"===t&&(l=!1!==vo(n,110)._compositionEnd(e.target.value)&&l),"ngModelChange"===t&&(l=!1!==(r.mainData.id=e)&&l),l},null,null)),Do(110,16384,null,0,Dd,[Vt,At,[2,kd]],null,null),Ao(1024,null,Id,function(n){return[n]},[Dd]),Do(112,671744,null,0,yf,[[8,null],[8,null],[8,null],[6,Id]],{model:[0,"model"]},{update:"ngModelChange"}),Ao(2048,null,Ld,null,[yf]),Do(114,16384,null,0,ef,[[4,Ld]],null,null),(n()(),Hr(115,0,null,null,1,"button",[["class","button buttonBlue"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.goback()&&l),l},null,null)),(n()(),Jo(-1,null,["Back"])),(n()(),Hr(117,0,null,null,0,"br",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,15,0,e.mainData.firstName),n(t,26,0,e.mainData.lastName),n(t,37,0,e.mainData.age),n(t,48,0,"gender","Male"),n(t,49,0,""),n(t,52,0,"gender",e.mainData.gender),n(t,58,0,"gender","Female"),n(t,59,0,""),n(t,62,0,"gender",e.mainData.gender),n(t,74,0,e.mainData.emailId),n(t,93,0,e.mainData.city),n(t,104,0,e.mainData.avgIncome),n(t,112,0,e.mainData.id)},function(n,t){var e=t.component;n(t,12,0,vo(t,17).ngClassUntouched,vo(t,17).ngClassTouched,vo(t,17).ngClassPristine,vo(t,17).ngClassDirty,vo(t,17).ngClassValid,vo(t,17).ngClassInvalid,vo(t,17).ngClassPending),n(t,23,0,vo(t,28).ngClassUntouched,vo(t,28).ngClassTouched,vo(t,28).ngClassPristine,vo(t,28).ngClassDirty,vo(t,28).ngClassValid,vo(t,28).ngClassInvalid,vo(t,28).ngClassPending),n(t,34,0,vo(t,39).ngClassUntouched,vo(t,39).ngClassTouched,vo(t,39).ngClassPristine,vo(t,39).ngClassDirty,vo(t,39).ngClassValid,vo(t,39).ngClassInvalid,vo(t,39).ngClassPending),n(t,46,0,vo(t,49).required?"":null,vo(t,54).ngClassUntouched,vo(t,54).ngClassTouched,vo(t,54).ngClassPristine,vo(t,54).ngClassDirty,vo(t,54).ngClassValid,vo(t,54).ngClassInvalid,vo(t,54).ngClassPending),n(t,56,0,vo(t,59).required?"":null,vo(t,64).ngClassUntouched,vo(t,64).ngClassTouched,vo(t,64).ngClassPristine,vo(t,64).ngClassDirty,vo(t,64).ngClassValid,vo(t,64).ngClassInvalid,vo(t,64).ngClassPending),n(t,71,0,vo(t,76).ngClassUntouched,vo(t,76).ngClassTouched,vo(t,76).ngClassPristine,vo(t,76).ngClassDirty,vo(t,76).ngClassValid,vo(t,76).ngClassInvalid,vo(t,76).ngClassPending),n(t,83,0,e.mainData.country),n(t,90,0,vo(t,95).ngClassUntouched,vo(t,95).ngClassTouched,vo(t,95).ngClassPristine,vo(t,95).ngClassDirty,vo(t,95).ngClassValid,vo(t,95).ngClassInvalid,vo(t,95).ngClassPending),n(t,101,0,vo(t,106).ngClassUntouched,vo(t,106).ngClassTouched,vo(t,106).ngClassPristine,vo(t,106).ngClassDirty,vo(t,106).ngClassValid,vo(t,106).ngClassInvalid,vo(t,106).ngClassPending),n(t,109,0,vo(t,114).ngClassUntouched,vo(t,114).ngClassTouched,vo(t,114).ngClassPristine,vo(t,114).ngClassDirty,vo(t,114).ngClassValid,vo(t,114).ngClassInvalid,vo(t,114).ngClassPending)})}function Qm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-customer-profile",[],null,null,null,Wm,Gm)),Do(1,114688,null,0,qm,[Gf,Ag,Hh],null,null)],function(n,t){n(t,1,0)},null)}var $m=io("app-customer-profile",qm,Qm,{},{},[]),Km=dr({encapsulation:0,styles:[yd,jf],data:{}});function Zm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"button",[["class","simButtonType1"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoLogout()&&l),l},null,null)),(n()(),Jo(-1,null,["Logout"]))],null,null)}function Ym(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"button",[["class","simButtonType1"]],null,[[null,"click"]],function(n,t,e){var l=!0;return"click"===t&&(l=!1!==n.component.gotoLogin()&&l),l},null,null)),(n()(),Jo(-1,null,["Login"]))],null,null)}function Xm(n){return ei(0,[(n()(),Hr(0,0,null,null,22,"div",[["class","container"]],null,null,null,null,null)),(n()(),Hr(1,0,null,null,11,"nav",[["class","navbar navbar-default navbar-fixed-top"]],null,null,null,null,null)),(n()(),Hr(2,0,null,null,10,"div",[["class","simGridType3"]],null,null,null,null,null)),(n()(),Hr(3,0,null,null,0,"div",[],null,null,null,null,null)),(n()(),Hr(4,0,null,null,1,"div",[["class","simDivVerticalAlginCenter"]],null,null,null,null,null)),(n()(),Hr(5,0,null,null,0,"img",[["height","50"],["src","../../assets/img/logo.png"]],null,null,null,null,null)),(n()(),Hr(6,0,null,null,0,"div",[],null,null,null,null,null)),(n()(),Hr(7,0,null,null,4,"div",[["class","simDivVerticalAlginBottom"]],null,null,null,null,null)),(n()(),Br(16777216,null,null,1,null,Zm)),Do(9,16384,null,0,Vu,[bl,de],{ngIf:[0,"ngIf"]},null),(n()(),Br(16777216,null,null,1,null,Ym)),Do(11,16384,null,0,Vu,[bl,de],{ngIf:[0,"ngIf"]},null),(n()(),Hr(12,0,null,null,0,"div",[],null,null,null,null,null)),(n()(),Hr(13,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(14,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(15,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(16,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(17,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(18,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(19,0,null,null,0,"br",[],null,null,null,null,null)),(n()(),Hr(20,16777216,null,null,1,"router-outlet",[],null,null,null,null,null)),Do(21,212992,null,0,Gh,[qh,bl,Tt,[8,null],Cl],null,null),(n()(),Hr(22,0,null,null,0,"div",[],null,null,null,null,null))],function(n,t){var e=t.component;n(t,9,0,e.authService.isUserLoggedIn()),n(t,11,0,!e.authService.isUserLoggedIn()),n(t,21,0)},null)}function Jm(n){return ei(0,[(n()(),Hr(0,0,null,null,1,"app-root",[],null,null,null,Xm,Km)),Do(1,49152,null,0,Aa,[Da,Ap,Hh],null,null)],null,null)}var ny=io("app-root",Aa,Jm,{},{},[]),ty=function(){return function(){}}(),ey=function(){return function(){}}(),ly="*";function ry(n,t){return void 0===t&&(t=null),{type:2,steps:n,options:t}}function oy(n){return{type:6,styles:n,offset:null}}function iy(n){Promise.resolve(null).then(n)}var uy=function(){function n(n,t){void 0===n&&(n=0),void 0===t&&(t=0),this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this._destroyed=!1,this._finished=!1,this.parentPlayer=null,this.totalTime=n+t}return n.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(n){return n()}),this._onDoneFns=[])},n.prototype.onStart=function(n){this._onStartFns.push(n)},n.prototype.onDone=function(n){this._onDoneFns.push(n)},n.prototype.onDestroy=function(n){this._onDestroyFns.push(n)},n.prototype.hasStarted=function(){return this._started},n.prototype.init=function(){},n.prototype.play=function(){this.hasStarted()||(this._onStart(),this.triggerMicrotask()),this._started=!0},n.prototype.triggerMicrotask=function(){var n=this;iy(function(){return n._onFinish()})},n.prototype._onStart=function(){this._onStartFns.forEach(function(n){return n()}),this._onStartFns=[]},n.prototype.pause=function(){},n.prototype.restart=function(){},n.prototype.finish=function(){this._onFinish()},n.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.hasStarted()||this._onStart(),this.finish(),this._onDestroyFns.forEach(function(n){return n()}),this._onDestroyFns=[])},n.prototype.reset=function(){},n.prototype.setPosition=function(n){},n.prototype.getPosition=function(){return 0},n.prototype.triggerCallback=function(n){var t="start"==n?this._onStartFns:this._onDoneFns;t.forEach(function(n){return n()}),t.length=0},n}(),ay=function(){function n(n){var t=this;this._onDoneFns=[],this._onStartFns=[],this._finished=!1,this._started=!1,this._destroyed=!1,this._onDestroyFns=[],this.parentPlayer=null,this.totalTime=0,this.players=n;var e=0,l=0,r=0,o=this.players.length;0==o?iy(function(){return t._onFinish()}):this.players.forEach(function(n){n.onDone(function(){++e==o&&t._onFinish()}),n.onDestroy(function(){++l==o&&t._onDestroy()}),n.onStart(function(){++r==o&&t._onStart()})}),this.totalTime=this.players.reduce(function(n,t){return Math.max(n,t.totalTime)},0)}return n.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(n){return n()}),this._onDoneFns=[])},n.prototype.init=function(){this.players.forEach(function(n){return n.init()})},n.prototype.onStart=function(n){this._onStartFns.push(n)},n.prototype._onStart=function(){this.hasStarted()||(this._started=!0,this._onStartFns.forEach(function(n){return n()}),this._onStartFns=[])},n.prototype.onDone=function(n){this._onDoneFns.push(n)},n.prototype.onDestroy=function(n){this._onDestroyFns.push(n)},n.prototype.hasStarted=function(){return this._started},n.prototype.play=function(){this.parentPlayer||this.init(),this._onStart(),this.players.forEach(function(n){return n.play()})},n.prototype.pause=function(){this.players.forEach(function(n){return n.pause()})},n.prototype.restart=function(){this.players.forEach(function(n){return n.restart()})},n.prototype.finish=function(){this._onFinish(),this.players.forEach(function(n){return n.finish()})},n.prototype.destroy=function(){this._onDestroy()},n.prototype._onDestroy=function(){this._destroyed||(this._destroyed=!0,this._onFinish(),this.players.forEach(function(n){return n.destroy()}),this._onDestroyFns.forEach(function(n){return n()}),this._onDestroyFns=[])},n.prototype.reset=function(){this.players.forEach(function(n){return n.reset()}),this._destroyed=!1,this._finished=!1,this._started=!1},n.prototype.setPosition=function(n){var t=n*this.totalTime;this.players.forEach(function(n){var e=n.totalTime?Math.min(1,t/n.totalTime):1;n.setPosition(e)})},n.prototype.getPosition=function(){var n=0;return this.players.forEach(function(t){var e=t.getPosition();n=Math.min(e,n)}),n},n.prototype.beforeDestroy=function(){this.players.forEach(function(n){n.beforeDestroy&&n.beforeDestroy()})},n.prototype.triggerCallback=function(n){var t="start"==n?this._onStartFns:this._onDoneFns;t.forEach(function(n){return n()}),t.length=0},n}(),sy="!";function cy(){return"undefined"!=typeof process}function py(n){switch(n.length){case 0:return new uy;case 1:return n[0];default:return new ay(n)}}function hy(n,t,e,l,r,o){void 0===r&&(r={}),void 0===o&&(o={});var i=[],u=[],a=-1,s=null;if(l.forEach(function(n){var e=n.offset,l=e==a,c=l&&s||{};Object.keys(n).forEach(function(e){var l=e,u=n[e];if("offset"!==e)switch(l=t.normalizePropertyName(l,i),u){case sy:u=r[e];break;case ly:u=o[e];break;default:u=t.normalizeStyleValue(e,l,u,i)}c[l]=u}),l||u.push(c),s=c,a=e}),i.length)throw new Error("Unable to animate due to the following errors:\n - "+i.join("\n - "));return u}function dy(n,t,e,l){switch(t){case"start":n.onStart(function(){return l(e&&fy(e,"start",n))});break;case"done":n.onDone(function(){return l(e&&fy(e,"done",n))});break;case"destroy":n.onDestroy(function(){return l(e&&fy(e,"destroy",n))})}}function fy(n,t,e){var l=e.totalTime,r=gy(n.element,n.triggerName,n.fromState,n.toState,t||n.phaseName,null==l?n.totalTime:l,!!e.disabled),o=n._data;return null!=o&&(r._data=o),r}function gy(n,t,e,l,r,o,i){return void 0===r&&(r=""),void 0===o&&(o=0),{element:n,triggerName:t,fromState:e,toState:l,phaseName:r,totalTime:o,disabled:!!i}}function my(n,t,e){var l;return n instanceof Map?(l=n.get(t))||n.set(t,l=e):(l=n[t])||(l=n[t]=e),l}function yy(n){var t=n.indexOf(":");return[n.substring(1,t),n.substr(t+1)]}var vy=function(n,t){return!1},_y=function(n,t){return!1},by=function(n,t,e){return[]},wy=cy();if(wy||"undefined"!=typeof Element){if(vy=function(n,t){return n.contains(t)},wy||Element.prototype.matches)_y=function(n,t){return n.matches(t)};else{var Cy=Element.prototype,Sy=Cy.matchesSelector||Cy.mozMatchesSelector||Cy.msMatchesSelector||Cy.oMatchesSelector||Cy.webkitMatchesSelector;Sy&&(_y=function(n,t){return Sy.apply(n,[t])})}by=function(n,t,e){var l=[];if(e)l.push.apply(l,c(n.querySelectorAll(t)));else{var r=n.querySelector(t);r&&l.push(r)}return l}}var Ey=null,xy=!1;function Py(n){Ey||(Ey=("undefined"!=typeof document?document.body:null)||{},xy=!!Ey.style&&"WebkitAppearance"in Ey.style);var t=!0;return Ey.style&&!function(n){return"ebkit"==n.substring(1,6)}(n)&&!(t=n in Ey.style)&&xy&&(t="Webkit"+n.charAt(0).toUpperCase()+n.substr(1)in Ey.style),t}var Ty=_y,Iy=vy,Oy=by;function ky(n){var t={};return Object.keys(n).forEach(function(e){var l=e.replace(/([a-z])([A-Z])/g,"$1-$2");t[l]=n[e]}),t}var Dy=function(){function n(){}return n.prototype.validateStyleProperty=function(n){return Py(n)},n.prototype.matchesElement=function(n,t){return Ty(n,t)},n.prototype.containsElement=function(n,t){return Iy(n,t)},n.prototype.query=function(n,t,e){return Oy(n,t,e)},n.prototype.computeStyle=function(n,t,e){return e||""},n.prototype.animate=function(n,t,e,l,r,o,i){return void 0===o&&(o=[]),new uy(e,l)},n}(),Ay=function(){function n(){}return n.NOOP=new Dy,n}(),Ry=1e3;function My(n){if("number"==typeof n)return n;var t=n.match(/^(-?[\.\d]+)(m?s)/);return!t||t.length<2?0:Ny(parseFloat(t[1]),t[2])}function Ny(n,t){switch(t){case"s":return n*Ry;default:return n}}function Ly(n,t,e){return n.hasOwnProperty("duration")?n:function(n,t,e){var l,r=0,o="";if("string"==typeof n){var i=n.match(/^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i);if(null===i)return t.push('The provided timing value "'+n+'" is invalid.'),{duration:0,delay:0,easing:""};l=Ny(parseFloat(i[1]),i[2]);var u=i[3];null!=u&&(r=Ny(parseFloat(u),i[4]));var a=i[5];a&&(o=a)}else l=n;if(!e){var s=!1,c=t.length;l<0&&(t.push("Duration values below 0 are not allowed for this animation step."),s=!0),r<0&&(t.push("Delay values below 0 are not allowed for this animation step."),s=!0),s&&t.splice(c,0,'The provided timing value "'+n+'" is invalid.')}return{duration:l,delay:r,easing:o}}(n,t,e)}function Vy(n,t){return void 0===t&&(t={}),Object.keys(n).forEach(function(e){t[e]=n[e]}),t}function Uy(n,t,e){if(void 0===e&&(e={}),t)for(var l in n)e[l]=n[l];else Vy(n,e);return e}function jy(n,t,e){return e?t+":"+e+";":""}function Fy(n){for(var t="",e=0;e<n.style.length;e++)t+=jy(0,l=n.style.item(e),n.style.getPropertyValue(l));for(var l in n.style)n.style.hasOwnProperty(l)&&!l.startsWith("_")&&(t+=jy(0,l.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),n.style[l]));n.setAttribute("style",t)}function By(n,t,e){n.style&&(Object.keys(t).forEach(function(l){var r=Ky(l);e&&!e.hasOwnProperty(l)&&(e[l]=n.style[r]),n.style[r]=t[l]}),cy()&&Fy(n))}function Hy(n,t){n.style&&(Object.keys(t).forEach(function(t){var e=Ky(t);n.style[e]=""}),cy()&&Fy(n))}function zy(n){return Array.isArray(n)?1==n.length?n[0]:ry(n):n}var qy=new RegExp("{{\\s*(.+?)\\s*}}","g");function Gy(n){var t=[];if("string"==typeof n){for(var e=n.toString(),l=void 0;l=qy.exec(e);)t.push(l[1]);qy.lastIndex=0}return t}function Wy(n,t,e){var l=n.toString(),r=l.replace(qy,function(n,l){var r=t[l];return t.hasOwnProperty(l)||(e.push("Please provide a value for the animation param "+l),r=""),r.toString()});return r==l?n:r}function Qy(n){for(var t=[],e=n.next();!e.done;)t.push(e.value),e=n.next();return t}var $y=/-+([a-z0-9])/g;function Ky(n){return n.replace($y,function(){for(var n=[],t=0;t<arguments.length;t++)n[t]=arguments[t];return n[1].toUpperCase()})}function Zy(n,t){return 0===n||0===t}function Yy(n,t,e){var l=Object.keys(e);if(l.length&&t.length){var r=t[0],o=[];if(l.forEach(function(n){r.hasOwnProperty(n)||o.push(n),r[n]=e[n]}),o.length)for(var i=function(){var e=t[u];o.forEach(function(t){e[t]=Jy(n,t)})},u=1;u<t.length;u++)i()}return t}function Xy(n,t,e){switch(t.type){case 7:return n.visitTrigger(t,e);case 0:return n.visitState(t,e);case 1:return n.visitTransition(t,e);case 2:return n.visitSequence(t,e);case 3:return n.visitGroup(t,e);case 4:return n.visitAnimate(t,e);case 5:return n.visitKeyframes(t,e);case 6:return n.visitStyle(t,e);case 8:return n.visitReference(t,e);case 9:return n.visitAnimateChild(t,e);case 10:return n.visitAnimateRef(t,e);case 11:return n.visitQuery(t,e);case 12:return n.visitStagger(t,e);default:throw new Error("Unable to resolve animation metadata node #"+t.type)}}function Jy(n,t){return window.getComputedStyle(n)[t]}var nv="*",tv=new Set(["true","1"]),ev=new Set(["false","0"]);function lv(n,t){var e=tv.has(n)||ev.has(n),l=tv.has(t)||ev.has(t);return function(r,o){var i=n==nv||n==r,u=t==nv||t==o;return!i&&e&&"boolean"==typeof r&&(i=r?tv.has(n):ev.has(n)),!u&&l&&"boolean"==typeof o&&(u=o?tv.has(t):ev.has(t)),i&&u}}var rv=new RegExp("s*:selfs*,?","g");function ov(n,t,e){return new iv(n).build(t,e)}var iv=function(){function n(n){this._driver=n}return n.prototype.build=function(n,t){var e=new uv(t);return this._resetContextStyleTimingState(e),Xy(this,zy(n),e)},n.prototype._resetContextStyleTimingState=function(n){n.currentQuerySelector="",n.collectedStyles={},n.collectedStyles[""]={},n.currentTime=0},n.prototype.visitTrigger=function(n,t){var e=this,l=t.queryCount=0,r=t.depCount=0,o=[],i=[];return"@"==n.name.charAt(0)&&t.errors.push("animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))"),n.definitions.forEach(function(n){if(e._resetContextStyleTimingState(t),0==n.type){var u=n,a=u.name;a.toString().split(/\s*,\s*/).forEach(function(n){u.name=n,o.push(e.visitState(u,t))}),u.name=a}else if(1==n.type){var s=e.visitTransition(n,t);l+=s.queryCount,r+=s.depCount,i.push(s)}else t.errors.push("only state() and transition() definitions can sit inside of a trigger()")}),{type:7,name:n.name,states:o,transitions:i,queryCount:l,depCount:r,options:null}},n.prototype.visitState=function(n,t){var e=this.visitStyle(n.styles,t),l=n.options&&n.options.params||null;if(e.containsDynamicStyles){var r=new Set,o=l||{};if(e.styles.forEach(function(n){if(av(n)){var t=n;Object.keys(t).forEach(function(n){Gy(t[n]).forEach(function(n){o.hasOwnProperty(n)||r.add(n)})})}}),r.size){var i=Qy(r.values());t.errors.push('state("'+n.name+'", ...) must define default values for all the following style substitutions: '+i.join(", "))}}return{type:0,name:n.name,style:e,options:l?{params:l}:null}},n.prototype.visitTransition=function(n,t){t.queryCount=0,t.depCount=0;var e,l,r,o=Xy(this,zy(n.animation),t);return{type:1,matchers:(e=n.expr,l=t.errors,r=[],"string"==typeof e?e.split(/\s*,\s*/).forEach(function(n){return function(n,t,e){if(":"==n[0]){var l=function(n,t){switch(n){case":enter":return"void => *";case":leave":return"* => void";case":increment":return function(n,t){return parseFloat(t)>parseFloat(n)};case":decrement":return function(n,t){return parseFloat(t)<parseFloat(n)};default:return t.push('The transition alias value "'+n+'" is not supported'),"* => *"}}(n,e);if("function"==typeof l)return void t.push(l);n=l}var r=n.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);if(null==r||r.length<4)return e.push('The provided transition expression "'+n+'" is not supported'),t;var o=r[1],i=r[2],u=r[3];t.push(lv(o,u)),"<"!=i[0]||o==nv&&u==nv||t.push(lv(u,o))}(n,r,l)}):r.push(e),r),animation:o,queryCount:t.queryCount,depCount:t.depCount,options:sv(n.options)}},n.prototype.visitSequence=function(n,t){var e=this;return{type:2,steps:n.steps.map(function(n){return Xy(e,n,t)}),options:sv(n.options)}},n.prototype.visitGroup=function(n,t){var e=this,l=t.currentTime,r=0,o=n.steps.map(function(n){t.currentTime=l;var o=Xy(e,n,t);return r=Math.max(r,t.currentTime),o});return t.currentTime=r,{type:3,steps:o,options:sv(n.options)}},n.prototype.visitAnimate=function(n,t){var e,l=function(n,t){var e=null;if(n.hasOwnProperty("duration"))e=n;else if("number"==typeof n)return cv(Ly(n,t).duration,0,"");var l=n;if(l.split(/\s+/).some(function(n){return"{"==n.charAt(0)&&"{"==n.charAt(1)})){var r=cv(0,0,"");return r.dynamic=!0,r.strValue=l,r}return cv((e=e||Ly(l,t)).duration,e.delay,e.easing)}(n.timings,t.errors);t.currentAnimateTimings=l;var r=n.styles?n.styles:oy({});if(5==r.type)e=this.visitKeyframes(r,t);else{var o=n.styles,i=!1;if(!o){i=!0;var u={};l.easing&&(u.easing=l.easing),o=oy(u)}t.currentTime+=l.duration+l.delay;var a=this.visitStyle(o,t);a.isEmptyStep=i,e=a}return t.currentAnimateTimings=null,{type:4,timings:l,style:e,options:null}},n.prototype.visitStyle=function(n,t){var e=this._makeStyleAst(n,t);return this._validateStyleAst(e,t),e},n.prototype._makeStyleAst=function(n,t){var e=[];Array.isArray(n.styles)?n.styles.forEach(function(n){"string"==typeof n?n==ly?e.push(n):t.errors.push("The provided style string value "+n+" is not allowed."):e.push(n)}):e.push(n.styles);var l=!1,r=null;return e.forEach(function(n){if(av(n)){var t=n,e=t.easing;if(e&&(r=e,delete t.easing),!l)for(var o in t)if(t[o].toString().indexOf("{{")>=0){l=!0;break}}}),{type:6,styles:e,easing:r,offset:n.offset,containsDynamicStyles:l,options:null}},n.prototype._validateStyleAst=function(n,t){var e=this,l=t.currentAnimateTimings,r=t.currentTime,o=t.currentTime;l&&o>0&&(o-=l.duration+l.delay),n.styles.forEach(function(n){"string"!=typeof n&&Object.keys(n).forEach(function(l){if(e._driver.validateStyleProperty(l)){var i,u,a,s=t.collectedStyles[t.currentQuerySelector],c=s[l],p=!0;c&&(o!=r&&o>=c.startTime&&r<=c.endTime&&(t.errors.push('The CSS property "'+l+'" that exists between the times of "'+c.startTime+'ms" and "'+c.endTime+'ms" is also being animated in a parallel animation between the times of "'+o+'ms" and "'+r+'ms"'),p=!1),o=c.startTime),p&&(s[l]={startTime:o,endTime:r}),t.options&&(i=t.errors,u=t.options.params||{},(a=Gy(n[l])).length&&a.forEach(function(n){u.hasOwnProperty(n)||i.push("Unable to resolve the local animation param "+n+" in the given list of values")}))}else t.errors.push('The provided animation property "'+l+'" is not a supported CSS property for animations')})})},n.prototype.visitKeyframes=function(n,t){var e=this,l={type:5,styles:[],options:null};if(!t.currentAnimateTimings)return t.errors.push("keyframes() must be placed inside of a call to animate()"),l;var r=0,o=[],i=!1,u=!1,a=0,s=n.steps.map(function(n){var l=e._makeStyleAst(n,t),s=null!=l.offset?l.offset:function(n){if("string"==typeof n)return null;var t=null;if(Array.isArray(n))n.forEach(function(n){if(av(n)&&n.hasOwnProperty("offset")){var e=n;t=parseFloat(e.offset),delete e.offset}});else if(av(n)&&n.hasOwnProperty("offset")){var e=n;t=parseFloat(e.offset),delete e.offset}return t}(l.styles),c=0;return null!=s&&(r++,c=l.offset=s),u=u||c<0||c>1,i=i||c<a,a=c,o.push(c),l});u&&t.errors.push("Please ensure that all keyframe offsets are between 0 and 1"),i&&t.errors.push("Please ensure that all keyframe offsets are in order");var c=n.steps.length,p=0;r>0&&r<c?t.errors.push("Not all style() steps within the declared keyframes() contain offsets"):0==r&&(p=1/(c-1));var h=c-1,d=t.currentTime,f=t.currentAnimateTimings,g=f.duration;return s.forEach(function(n,r){var i=p>0?r==h?1:p*r:o[r],u=i*g;t.currentTime=d+f.delay+u,f.duration=u,e._validateStyleAst(n,t),n.offset=i,l.styles.push(n)}),l},n.prototype.visitReference=function(n,t){return{type:8,animation:Xy(this,zy(n.animation),t),options:sv(n.options)}},n.prototype.visitAnimateChild=function(n,t){return t.depCount++,{type:9,options:sv(n.options)}},n.prototype.visitAnimateRef=function(n,t){return{type:10,animation:this.visitReference(n.animation,t),options:sv(n.options)}},n.prototype.visitQuery=function(n,t){var e=t.currentQuerySelector,l=n.options||{};t.queryCount++,t.currentQuery=n;var r=s(function(n){var t=!!n.split(/\s*,\s*/).find(function(n){return":self"==n});return t&&(n=n.replace(rv,"")),[n=n.replace(/@\*/g,".ng-trigger").replace(/@\w+/g,function(n){return".ng-trigger-"+n.substr(1)}).replace(/:animating/g,".ng-animating"),t]}(n.selector),2),o=r[0],i=r[1];t.currentQuerySelector=e.length?e+" "+o:o,my(t.collectedStyles,t.currentQuerySelector,{});var u=Xy(this,zy(n.animation),t);return t.currentQuery=null,t.currentQuerySelector=e,{type:11,selector:o,limit:l.limit||0,optional:!!l.optional,includeSelf:i,animation:u,originalSelector:n.selector,options:sv(n.options)}},n.prototype.visitStagger=function(n,t){t.currentQuery||t.errors.push("stagger() can only be used inside of query()");var e="full"===n.timings?{duration:0,delay:0,easing:"full"}:Ly(n.timings,t.errors,!0);return{type:12,animation:Xy(this,zy(n.animation),t),timings:e,options:null}},n}(),uv=function(){return function(n){this.errors=n,this.queryCount=0,this.depCount=0,this.currentTransition=null,this.currentQuery=null,this.currentQuerySelector=null,this.currentAnimateTimings=null,this.currentTime=0,this.collectedStyles={},this.options=null}}();function av(n){return!Array.isArray(n)&&"object"==typeof n}function sv(n){var t;return n?(n=Vy(n)).params&&(n.params=(t=n.params)?Vy(t):null):n={},n}function cv(n,t,e){return{duration:n,delay:t,easing:e}}function pv(n,t,e,l,r,o,i,u){return void 0===i&&(i=null),void 0===u&&(u=!1),{type:1,element:n,keyframes:t,preStyleProps:e,postStyleProps:l,duration:r,delay:o,totalTime:r+o,easing:i,subTimeline:u}}var hv=function(){function n(){this._map=new Map}return n.prototype.consume=function(n){var t=this._map.get(n);return t?this._map.delete(n):t=[],t},n.prototype.append=function(n,t){var e=this._map.get(n);e||this._map.set(n,e=[]),e.push.apply(e,c(t))},n.prototype.has=function(n){return this._map.has(n)},n.prototype.clear=function(){this._map.clear()},n}(),dv=new RegExp(":enter","g"),fv=new RegExp(":leave","g");function gv(n,t,e,l,r,o,i,u,a,s){return void 0===o&&(o={}),void 0===i&&(i={}),void 0===s&&(s=[]),(new mv).buildKeyframes(n,t,e,l,r,o,i,u,a,s)}var mv=function(){function n(){}return n.prototype.buildKeyframes=function(n,t,e,l,r,o,i,u,a,s){void 0===s&&(s=[]),a=a||new hv;var c=new vv(n,t,a,l,r,s,[]);c.options=u,c.currentTimeline.setStyles([o],null,c.errors,u),Xy(this,e,c);var p=c.timelines.filter(function(n){return n.containsAnimation()});if(p.length&&Object.keys(i).length){var h=p[p.length-1];h.allowOnlyTimelineStyles()||h.setStyles([i],null,c.errors,u)}return p.length?p.map(function(n){return n.buildKeyframes()}):[pv(t,[],[],[],0,0,"",!1)]},n.prototype.visitTrigger=function(n,t){},n.prototype.visitState=function(n,t){},n.prototype.visitTransition=function(n,t){},n.prototype.visitAnimateChild=function(n,t){var e=t.subInstructions.consume(t.element);if(e){var l=t.createSubContext(n.options),r=t.currentTimeline.currentTime,o=this._visitSubInstructions(e,l,l.options);r!=o&&t.transformIntoNewTimeline(o)}t.previousNode=n},n.prototype.visitAnimateRef=function(n,t){var e=t.createSubContext(n.options);e.transformIntoNewTimeline(),this.visitReference(n.animation,e),t.transformIntoNewTimeline(e.currentTimeline.currentTime),t.previousNode=n},n.prototype._visitSubInstructions=function(n,t,e){var l=t.currentTimeline.currentTime,r=null!=e.duration?My(e.duration):null,o=null!=e.delay?My(e.delay):null;return 0!==r&&n.forEach(function(n){var e=t.appendInstructionToTimeline(n,r,o);l=Math.max(l,e.duration+e.delay)}),l},n.prototype.visitReference=function(n,t){t.updateOptions(n.options,!0),Xy(this,n.animation,t),t.previousNode=n},n.prototype.visitSequence=function(n,t){var e=this,l=t.subContextCount,r=t,o=n.options;if(o&&(o.params||o.delay)&&((r=t.createSubContext(o)).transformIntoNewTimeline(),null!=o.delay)){6==r.previousNode.type&&(r.currentTimeline.snapshotCurrentStyles(),r.previousNode=yv);var i=My(o.delay);r.delayNextStep(i)}n.steps.length&&(n.steps.forEach(function(n){return Xy(e,n,r)}),r.currentTimeline.applyStylesToKeyframe(),r.subContextCount>l&&r.transformIntoNewTimeline()),t.previousNode=n},n.prototype.visitGroup=function(n,t){var e=this,l=[],r=t.currentTimeline.currentTime,o=n.options&&n.options.delay?My(n.options.delay):0;n.steps.forEach(function(i){var u=t.createSubContext(n.options);o&&u.delayNextStep(o),Xy(e,i,u),r=Math.max(r,u.currentTimeline.currentTime),l.push(u.currentTimeline)}),l.forEach(function(n){return t.currentTimeline.mergeTimelineCollectedStyles(n)}),t.transformIntoNewTimeline(r),t.previousNode=n},n.prototype._visitTiming=function(n,t){if(n.dynamic){var e=n.strValue;return Ly(t.params?Wy(e,t.params,t.errors):e,t.errors)}return{duration:n.duration,delay:n.delay,easing:n.easing}},n.prototype.visitAnimate=function(n,t){var e=t.currentAnimateTimings=this._visitTiming(n.timings,t),l=t.currentTimeline;e.delay&&(t.incrementTime(e.delay),l.snapshotCurrentStyles());var r=n.style;5==r.type?this.visitKeyframes(r,t):(t.incrementTime(e.duration),this.visitStyle(r,t),l.applyStylesToKeyframe()),t.currentAnimateTimings=null,t.previousNode=n},n.prototype.visitStyle=function(n,t){var e=t.currentTimeline,l=t.currentAnimateTimings;!l&&e.getCurrentStyleProperties().length&&e.forwardFrame();var r=l&&l.easing||n.easing;n.isEmptyStep?e.applyEmptyStep(r):e.setStyles(n.styles,r,t.errors,t.options),t.previousNode=n},n.prototype.visitKeyframes=function(n,t){var e=t.currentAnimateTimings,l=t.currentTimeline.duration,r=e.duration,o=t.createSubContext().currentTimeline;o.easing=e.easing,n.styles.forEach(function(n){o.forwardTime((n.offset||0)*r),o.setStyles(n.styles,n.easing,t.errors,t.options),o.applyStylesToKeyframe()}),t.currentTimeline.mergeTimelineCollectedStyles(o),t.transformIntoNewTimeline(l+r),t.previousNode=n},n.prototype.visitQuery=function(n,t){var e=this,l=t.currentTimeline.currentTime,r=n.options||{},o=r.delay?My(r.delay):0;o&&(6===t.previousNode.type||0==l&&t.currentTimeline.getCurrentStyleProperties().length)&&(t.currentTimeline.snapshotCurrentStyles(),t.previousNode=yv);var i=l,u=t.invokeQuery(n.selector,n.originalSelector,n.limit,n.includeSelf,!!r.optional,t.errors);t.currentQueryTotal=u.length;var a=null;u.forEach(function(l,r){t.currentQueryIndex=r;var u=t.createSubContext(n.options,l);o&&u.delayNextStep(o),l===t.element&&(a=u.currentTimeline),Xy(e,n.animation,u),u.currentTimeline.applyStylesToKeyframe(),i=Math.max(i,u.currentTimeline.currentTime)}),t.currentQueryIndex=0,t.currentQueryTotal=0,t.transformIntoNewTimeline(i),a&&(t.currentTimeline.mergeTimelineCollectedStyles(a),t.currentTimeline.snapshotCurrentStyles()),t.previousNode=n},n.prototype.visitStagger=function(n,t){var e=t.parentContext,l=t.currentTimeline,r=n.timings,o=Math.abs(r.duration),i=o*(t.currentQueryTotal-1),u=o*t.currentQueryIndex;switch(r.duration<0?"reverse":r.easing){case"reverse":u=i-u;break;case"full":u=e.currentStaggerTime}var a=t.currentTimeline;u&&a.delayNextStep(u);var s=a.currentTime;Xy(this,n.animation,t),t.previousNode=n,e.currentStaggerTime=l.currentTime-s+(l.startTime-e.currentTimeline.startTime)},n}(),yv={},vv=function(){function n(n,t,e,l,r,o,i,u){this._driver=n,this.element=t,this.subInstructions=e,this._enterClassName=l,this._leaveClassName=r,this.errors=o,this.timelines=i,this.parentContext=null,this.currentAnimateTimings=null,this.previousNode=yv,this.subContextCount=0,this.options={},this.currentQueryIndex=0,this.currentQueryTotal=0,this.currentStaggerTime=0,this.currentTimeline=u||new _v(this._driver,t,0),i.push(this.currentTimeline)}return Object.defineProperty(n.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),n.prototype.updateOptions=function(n,t){var e=this;if(n){var l=n,r=this.options;null!=l.duration&&(r.duration=My(l.duration)),null!=l.delay&&(r.delay=My(l.delay));var o=l.params;if(o){var i=r.params;i||(i=this.options.params={}),Object.keys(o).forEach(function(n){t&&i.hasOwnProperty(n)||(i[n]=Wy(o[n],i,e.errors))})}}},n.prototype._copyOptions=function(){var n={};if(this.options){var t=this.options.params;if(t){var e=n.params={};Object.keys(t).forEach(function(n){e[n]=t[n]})}}return n},n.prototype.createSubContext=function(t,e,l){void 0===t&&(t=null);var r=e||this.element,o=new n(this._driver,r,this.subInstructions,this._enterClassName,this._leaveClassName,this.errors,this.timelines,this.currentTimeline.fork(r,l||0));return o.previousNode=this.previousNode,o.currentAnimateTimings=this.currentAnimateTimings,o.options=this._copyOptions(),o.updateOptions(t),o.currentQueryIndex=this.currentQueryIndex,o.currentQueryTotal=this.currentQueryTotal,o.parentContext=this,this.subContextCount++,o},n.prototype.transformIntoNewTimeline=function(n){return this.previousNode=yv,this.currentTimeline=this.currentTimeline.fork(this.element,n),this.timelines.push(this.currentTimeline),this.currentTimeline},n.prototype.appendInstructionToTimeline=function(n,t,e){var l={duration:null!=t?t:n.duration,delay:this.currentTimeline.currentTime+(null!=e?e:0)+n.delay,easing:""},r=new bv(this._driver,n.element,n.keyframes,n.preStyleProps,n.postStyleProps,l,n.stretchStartingKeyframe);return this.timelines.push(r),l},n.prototype.incrementTime=function(n){this.currentTimeline.forwardTime(this.currentTimeline.duration+n)},n.prototype.delayNextStep=function(n){n>0&&this.currentTimeline.delayNextStep(n)},n.prototype.invokeQuery=function(n,t,e,l,r,o){var i=[];if(l&&i.push(this.element),n.length>0){n=(n=n.replace(dv,"."+this._enterClassName)).replace(fv,"."+this._leaveClassName);var u=this._driver.query(this.element,n,1!=e);0!==e&&(u=e<0?u.slice(u.length+e,u.length):u.slice(0,e)),i.push.apply(i,c(u))}return r||0!=i.length||o.push('`query("'+t+'")` returned zero elements. (Use `query("'+t+'", { optional: true })` if you wish to allow this.)'),i},n}(),_v=function(){function n(n,t,e,l){this._driver=n,this.element=t,this.startTime=e,this._elementTimelineStylesLookup=l,this.duration=0,this._previousKeyframe={},this._currentKeyframe={},this._keyframes=new Map,this._styleSummary={},this._pendingStyles={},this._backFill={},this._currentEmptyStepKeyframe=null,this._elementTimelineStylesLookup||(this._elementTimelineStylesLookup=new Map),this._localTimelineStyles=Object.create(this._backFill,{}),this._globalTimelineStyles=this._elementTimelineStylesLookup.get(t),this._globalTimelineStyles||(this._globalTimelineStyles=this._localTimelineStyles,this._elementTimelineStylesLookup.set(t,this._localTimelineStyles)),this._loadKeyframe()}return n.prototype.containsAnimation=function(){switch(this._keyframes.size){case 0:return!1;case 1:return this.getCurrentStyleProperties().length>0;default:return!0}},n.prototype.getCurrentStyleProperties=function(){return Object.keys(this._currentKeyframe)},Object.defineProperty(n.prototype,"currentTime",{get:function(){return this.startTime+this.duration},enumerable:!0,configurable:!0}),n.prototype.delayNextStep=function(n){var t=1==this._keyframes.size&&Object.keys(this._pendingStyles).length;this.duration||t?(this.forwardTime(this.currentTime+n),t&&this.snapshotCurrentStyles()):this.startTime+=n},n.prototype.fork=function(t,e){return this.applyStylesToKeyframe(),new n(this._driver,t,e||this.currentTime,this._elementTimelineStylesLookup)},n.prototype._loadKeyframe=function(){this._currentKeyframe&&(this._previousKeyframe=this._currentKeyframe),this._currentKeyframe=this._keyframes.get(this.duration),this._currentKeyframe||(this._currentKeyframe=Object.create(this._backFill,{}),this._keyframes.set(this.duration,this._currentKeyframe))},n.prototype.forwardFrame=function(){this.duration+=1,this._loadKeyframe()},n.prototype.forwardTime=function(n){this.applyStylesToKeyframe(),this.duration=n,this._loadKeyframe()},n.prototype._updateStyle=function(n,t){this._localTimelineStyles[n]=t,this._globalTimelineStyles[n]=t,this._styleSummary[n]={time:this.currentTime,value:t}},n.prototype.allowOnlyTimelineStyles=function(){return this._currentEmptyStepKeyframe!==this._currentKeyframe},n.prototype.applyEmptyStep=function(n){var t=this;n&&(this._previousKeyframe.easing=n),Object.keys(this._globalTimelineStyles).forEach(function(n){t._backFill[n]=t._globalTimelineStyles[n]||ly,t._currentKeyframe[n]=ly}),this._currentEmptyStepKeyframe=this._currentKeyframe},n.prototype.setStyles=function(n,t,e,l){var r=this;t&&(this._previousKeyframe.easing=t);var o=l&&l.params||{},i=function(n,t){var e,l={};return n.forEach(function(n){"*"===n?(e=e||Object.keys(t)).forEach(function(n){l[n]=ly}):Uy(n,!1,l)}),l}(n,this._globalTimelineStyles);Object.keys(i).forEach(function(n){var t=Wy(i[n],o,e);r._pendingStyles[n]=t,r._localTimelineStyles.hasOwnProperty(n)||(r._backFill[n]=r._globalTimelineStyles.hasOwnProperty(n)?r._globalTimelineStyles[n]:ly),r._updateStyle(n,t)})},n.prototype.applyStylesToKeyframe=function(){var n=this,t=this._pendingStyles,e=Object.keys(t);0!=e.length&&(this._pendingStyles={},e.forEach(function(e){n._currentKeyframe[e]=t[e]}),Object.keys(this._localTimelineStyles).forEach(function(t){n._currentKeyframe.hasOwnProperty(t)||(n._currentKeyframe[t]=n._localTimelineStyles[t])}))},n.prototype.snapshotCurrentStyles=function(){var n=this;Object.keys(this._localTimelineStyles).forEach(function(t){var e=n._localTimelineStyles[t];n._pendingStyles[t]=e,n._updateStyle(t,e)})},n.prototype.getFinalKeyframe=function(){return this._keyframes.get(this.duration)},Object.defineProperty(n.prototype,"properties",{get:function(){var n=[];for(var t in this._currentKeyframe)n.push(t);return n},enumerable:!0,configurable:!0}),n.prototype.mergeTimelineCollectedStyles=function(n){var t=this;Object.keys(n._styleSummary).forEach(function(e){var l=t._styleSummary[e],r=n._styleSummary[e];(!l||r.time>l.time)&&t._updateStyle(e,r.value)})},n.prototype.buildKeyframes=function(){var n=this;this.applyStylesToKeyframe();var t=new Set,e=new Set,l=1===this._keyframes.size&&0===this.duration,r=[];this._keyframes.forEach(function(o,i){var u=Uy(o,!0);Object.keys(u).forEach(function(n){var l=u[n];l==sy?t.add(n):l==ly&&e.add(n)}),l||(u.offset=i/n.duration),r.push(u)});var o=t.size?Qy(t.values()):[],i=e.size?Qy(e.values()):[];if(l){var u=r[0],a=Vy(u);u.offset=0,a.offset=1,r=[u,a]}return pv(this.element,r,o,i,this.duration,this.startTime,this.easing,!1)},n}(),bv=function(n){function t(t,e,l,r,o,i,u){void 0===u&&(u=!1);var a=n.call(this,t,e,i.delay)||this;return a.element=e,a.keyframes=l,a.preStyleProps=r,a.postStyleProps=o,a._stretchStartingKeyframe=u,a.timings={duration:i.duration,delay:i.delay,easing:i.easing},a}return r(t,n),t.prototype.containsAnimation=function(){return this.keyframes.length>1},t.prototype.buildKeyframes=function(){var n=this.keyframes,t=this.timings,e=t.delay,l=t.duration,r=t.easing;if(this._stretchStartingKeyframe&&e){var o=[],i=l+e,u=e/i,a=Uy(n[0],!1);a.offset=0,o.push(a);var s=Uy(n[0],!1);s.offset=wv(u),o.push(s);for(var c=n.length-1,p=1;p<=c;p++){var h=Uy(n[p],!1);h.offset=wv((e+h.offset*l)/i),o.push(h)}l=i,e=0,r="",n=o}return pv(this.element,n,this.preStyleProps,this.postStyleProps,l,e,r,!0)},t}(_v);function wv(n,t){void 0===t&&(t=3);var e=Math.pow(10,t-1);return Math.round(n*e)/e}var Cv=function(){return function(){}}(),Sv=function(n){function t(){return null!==n&&n.apply(this,arguments)||this}return r(t,n),t.prototype.normalizePropertyName=function(n,t){return Ky(n)},t.prototype.normalizeStyleValue=function(n,t,e,l){var r="",o=e.toString().trim();if(Ev[t]&&0!==e&&"0"!==e)if("number"==typeof e)r="px";else{var i=e.match(/^[+-]?[\d\.]+([a-z]*)$/);i&&0==i[1].length&&l.push("Please provide a CSS unit value for "+n+":"+e)}return o+r},t}(Cv),Ev=xv("width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective".split(","));function xv(n){var t={};return n.forEach(function(n){return t[n]=!0}),t}function Pv(n,t,e,l,r,o,i,u,a,s,c,p,h){return{type:0,element:n,triggerName:t,isRemovalTransition:r,fromState:e,fromStyles:o,toState:l,toStyles:i,timelines:u,queriedElements:a,preStyleProps:s,postStyleProps:c,totalTime:p,errors:h}}var Tv={},Iv=function(){function n(n,t,e){this._triggerName=n,this.ast=t,this._stateStyles=e}return n.prototype.match=function(n,t,e,l){return function(n,t,e,l,r){return n.some(function(n){return n(t,e,l,r)})}(this.ast.matchers,n,t,e,l)},n.prototype.buildStyles=function(n,t,e){var l=this._stateStyles["*"],r=this._stateStyles[n],o=l?l.buildStyles(t,e):{};return r?r.buildStyles(t,e):o},n.prototype.build=function(n,t,e,l,r,i,u,a,s,c){var p=[],h=this.ast.options&&this.ast.options.params||Tv,d=this.buildStyles(e,u&&u.params||Tv,p),f=a&&a.params||Tv,g=this.buildStyles(l,f,p),m=new Set,y=new Map,v=new Map,_="void"===l,b={params:o({},h,f)},w=c?[]:gv(n,t,this.ast.animation,r,i,d,g,b,s,p),C=0;if(w.forEach(function(n){C=Math.max(n.duration+n.delay,C)}),p.length)return Pv(t,this._triggerName,e,l,_,d,g,[],[],y,v,C,p);w.forEach(function(n){var e=n.element,l=my(y,e,{});n.preStyleProps.forEach(function(n){return l[n]=!0});var r=my(v,e,{});n.postStyleProps.forEach(function(n){return r[n]=!0}),e!==t&&m.add(e)});var S=Qy(m.values());return Pv(t,this._triggerName,e,l,_,d,g,w,S,y,v,C)},n}(),Ov=function(){function n(n,t){this.styles=n,this.defaultParams=t}return n.prototype.buildStyles=function(n,t){var e={},l=Vy(this.defaultParams);return Object.keys(n).forEach(function(t){var e=n[t];null!=e&&(l[t]=e)}),this.styles.styles.forEach(function(n){if("string"!=typeof n){var r=n;Object.keys(r).forEach(function(n){var o=r[n];o.length>1&&(o=Wy(o,l,t)),e[n]=o})}}),e},n}(),kv=function(){function n(n,t){var e=this;this.name=n,this.ast=t,this.transitionFactories=[],this.states={},t.states.forEach(function(n){e.states[n.name]=new Ov(n.style,n.options&&n.options.params||{})}),Dv(this.states,"true","1"),Dv(this.states,"false","0"),t.transitions.forEach(function(t){e.transitionFactories.push(new Iv(n,t,e.states))}),this.fallbackTransition=new Iv(n,{type:1,animation:{type:2,steps:[],options:null},matchers:[function(n,t){return!0}],options:null,queryCount:0,depCount:0},this.states)}return Object.defineProperty(n.prototype,"containsQueries",{get:function(){return this.ast.queryCount>0},enumerable:!0,configurable:!0}),n.prototype.matchTransition=function(n,t,e,l){return this.transitionFactories.find(function(r){return r.match(n,t,e,l)})||null},n.prototype.matchStyles=function(n,t,e){return this.fallbackTransition.buildStyles(n,t,e)},n}();function Dv(n,t,e){n.hasOwnProperty(t)?n.hasOwnProperty(e)||(n[e]=n[t]):n.hasOwnProperty(e)&&(n[t]=n[e])}var Av=new hv,Rv=function(){function n(n,t,e){this.bodyNode=n,this._driver=t,this._normalizer=e,this._animations={},this._playersById={},this.players=[]}return n.prototype.register=function(n,t){var e=[],l=ov(this._driver,t,e);if(e.length)throw new Error("Unable to build the animation due to the following errors: "+e.join("\n"));this._animations[n]=l},n.prototype._buildPlayer=function(n,t,e){var l=n.element,r=hy(0,this._normalizer,0,n.keyframes,t,e);return this._driver.animate(l,r,n.duration,n.delay,n.easing,[],!0)},n.prototype.create=function(n,t,e){var l=this;void 0===e&&(e={});var r,o=[],i=this._animations[n],u=new Map;if(i?(r=gv(this._driver,t,i,"ng-enter","ng-leave",{},{},e,Av,o)).forEach(function(n){var t=my(u,n.element,{});n.postStyleProps.forEach(function(n){return t[n]=null})}):(o.push("The requested animation doesn't exist or has already been destroyed"),r=[]),o.length)throw new Error("Unable to create the animation due to the following errors: "+o.join("\n"));u.forEach(function(n,t){Object.keys(n).forEach(function(e){n[e]=l._driver.computeStyle(t,e,ly)})});var a=py(r.map(function(n){var t=u.get(n.element);return l._buildPlayer(n,{},t)}));return this._playersById[n]=a,a.onDestroy(function(){return l.destroy(n)}),this.players.push(a),a},n.prototype.destroy=function(n){var t=this._getPlayer(n);t.destroy(),delete this._playersById[n];var e=this.players.indexOf(t);e>=0&&this.players.splice(e,1)},n.prototype._getPlayer=function(n){var t=this._playersById[n];if(!t)throw new Error("Unable to find the timeline player referenced by "+n);return t},n.prototype.listen=function(n,t,e,l){var r=gy(t,"","","");return dy(this._getPlayer(n),e,r,l),function(){}},n.prototype.command=function(n,t,e,l){if("register"!=e)if("create"!=e){var r=this._getPlayer(n);switch(e){case"play":r.play();break;case"pause":r.pause();break;case"reset":r.reset();break;case"restart":r.restart();break;case"finish":r.finish();break;case"init":r.init();break;case"setPosition":r.setPosition(parseFloat(l[0]));break;case"destroy":this.destroy(n)}}else this.create(n,t,l[0]||{});else this.register(n,l[0])},n}(),Mv=[],Nv={namespaceId:"",setForRemoval:!1,setForMove:!1,hasAnimation:!1,removedBeforeQueried:!1},Lv={namespaceId:"",setForMove:!1,setForRemoval:!1,hasAnimation:!1,removedBeforeQueried:!0},Vv="__ng_removed",Uv=function(){function n(n,t){void 0===t&&(t=""),this.namespaceId=t;var e=n&&n.hasOwnProperty("value");if(this.value=function(n){return null!=n?n:null}(e?n.value:n),e){var l=Vy(n);delete l.value,this.options=l}else this.options={};this.options.params||(this.options.params={})}return Object.defineProperty(n.prototype,"params",{get:function(){return this.options.params},enumerable:!0,configurable:!0}),n.prototype.absorbOptions=function(n){var t=n.params;if(t){var e=this.options.params;Object.keys(t).forEach(function(n){null==e[n]&&(e[n]=t[n])})}},n}(),jv=new Uv("void"),Fv=function(){function n(n,t,e){this.id=n,this.hostElement=t,this._engine=e,this.players=[],this._triggers={},this._queue=[],this._elementListeners=new Map,this._hostClassName="ng-tns-"+n,$v(t,this._hostClassName)}return n.prototype.listen=function(n,t,e,l){var r,o=this;if(!this._triggers.hasOwnProperty(t))throw new Error('Unable to listen on the animation trigger event "'+e+'" because the animation trigger "'+t+"\" doesn't exist!");if(null==e||0==e.length)throw new Error('Unable to listen on the animation trigger "'+t+'" because the provided event is undefined!');if("start"!=(r=e)&&"done"!=r)throw new Error('The provided animation trigger event "'+e+'" for the animation trigger "'+t+'" is not supported!');var i=my(this._elementListeners,n,[]),u={name:t,phase:e,callback:l};i.push(u);var a=my(this._engine.statesByElement,n,{});return a.hasOwnProperty(t)||($v(n,"ng-trigger"),$v(n,"ng-trigger-"+t),a[t]=jv),function(){o._engine.afterFlush(function(){var n=i.indexOf(u);n>=0&&i.splice(n,1),o._triggers[t]||delete a[t]})}},n.prototype.register=function(n,t){return!this._triggers[n]&&(this._triggers[n]=t,!0)},n.prototype._getTrigger=function(n){var t=this._triggers[n];if(!t)throw new Error('The provided animation trigger "'+n+'" has not been registered!');return t},n.prototype.trigger=function(n,t,e,l){var r=this;void 0===l&&(l=!0);var o=this._getTrigger(t),i=new Hv(this.id,t,n),u=this._engine.statesByElement.get(n);u||($v(n,"ng-trigger"),$v(n,"ng-trigger-"+t),this._engine.statesByElement.set(n,u={}));var a=u[t],s=new Uv(e,this.id);if(!(e&&e.hasOwnProperty("value"))&&a&&s.absorbOptions(a.options),u[t]=s,a||(a=jv),"void"===s.value||a.value!==s.value){var c=my(this._engine.playersByElement,n,[]);c.forEach(function(n){n.namespaceId==r.id&&n.triggerName==t&&n.queued&&n.destroy()});var p=o.matchTransition(a.value,s.value,n,s.params),h=!1;if(!p){if(!l)return;p=o.fallbackTransition,h=!0}return this._engine.totalQueuedPlayers++,this._queue.push({element:n,triggerName:t,transition:p,fromState:a,toState:s,player:i,isFallbackTransition:h}),h||($v(n,"ng-animate-queued"),i.onStart(function(){Kv(n,"ng-animate-queued")})),i.onDone(function(){var t=r.players.indexOf(i);t>=0&&r.players.splice(t,1);var e=r._engine.playersByElement.get(n);if(e){var l=e.indexOf(i);l>=0&&e.splice(l,1)}}),this.players.push(i),c.push(i),i}if(!function(n,t){var e=Object.keys(n),l=Object.keys(t);if(e.length!=l.length)return!1;for(var r=0;r<e.length;r++){var o=e[r];if(!t.hasOwnProperty(o)||n[o]!==t[o])return!1}return!0}(a.params,s.params)){var d=[],f=o.matchStyles(a.value,a.params,d),g=o.matchStyles(s.value,s.params,d);d.length?this._engine.reportError(d):this._engine.afterFlush(function(){Hy(n,f),By(n,g)})}},n.prototype.deregister=function(n){var t=this;delete this._triggers[n],this._engine.statesByElement.forEach(function(t,e){delete t[n]}),this._elementListeners.forEach(function(e,l){t._elementListeners.set(l,e.filter(function(t){return t.name!=n}))})},n.prototype.clearElementCache=function(n){this._engine.statesByElement.delete(n),this._elementListeners.delete(n);var t=this._engine.playersByElement.get(n);t&&(t.forEach(function(n){return n.destroy()}),this._engine.playersByElement.delete(n))},n.prototype._signalRemovalForInnerTriggers=function(n,t,e){var l=this;void 0===e&&(e=!1),this._engine.driver.query(n,".ng-trigger",!0).forEach(function(n){if(!n[Vv]){var e=l._engine.fetchNamespacesByElement(n);e.size?e.forEach(function(e){return e.triggerLeaveAnimation(n,t,!1,!0)}):l.clearElementCache(n)}})},n.prototype.triggerLeaveAnimation=function(n,t,e,l){var r=this,o=this._engine.statesByElement.get(n);if(o){var i=[];if(Object.keys(o).forEach(function(t){if(r._triggers[t]){var e=r.trigger(n,t,"void",l);e&&i.push(e)}}),i.length)return this._engine.markElementAsRemoved(this.id,n,!0,t),e&&py(i).onDone(function(){return r._engine.processLeaveNode(n)}),!0}return!1},n.prototype.prepareLeaveAnimationListeners=function(n){var t=this,e=this._elementListeners.get(n);if(e){var l=new Set;e.forEach(function(e){var r=e.name;if(!l.has(r)){l.add(r);var o=t._triggers[r].fallbackTransition,i=t._engine.statesByElement.get(n)[r]||jv,u=new Uv("void"),a=new Hv(t.id,r,n);t._engine.totalQueuedPlayers++,t._queue.push({element:n,triggerName:r,transition:o,fromState:i,toState:u,player:a,isFallbackTransition:!0})}})}},n.prototype.removeNode=function(n,t){var e=this,l=this._engine;if(n.childElementCount&&this._signalRemovalForInnerTriggers(n,t,!0),!this.triggerLeaveAnimation(n,t,!0)){var r=!1;if(l.totalAnimations){var o=l.players.length?l.playersByQueriedElement.get(n):[];if(o&&o.length)r=!0;else for(var i=n;i=i.parentNode;)if(l.statesByElement.get(i)){r=!0;break}}this.prepareLeaveAnimationListeners(n),r?l.markElementAsRemoved(this.id,n,!1,t):(l.afterFlush(function(){return e.clearElementCache(n)}),l.destroyInnerAnimations(n),l._onRemovalComplete(n,t))}},n.prototype.insertNode=function(n,t){$v(n,this._hostClassName)},n.prototype.drainQueuedTransitions=function(n){var t=this,e=[];return this._queue.forEach(function(l){var r=l.player;if(!r.destroyed){var o=l.element,i=t._elementListeners.get(o);i&&i.forEach(function(t){if(t.name==l.triggerName){var e=gy(o,l.triggerName,l.fromState.value,l.toState.value);e._data=n,dy(l.player,t.phase,e,t.callback)}}),r.markedForDestroy?t._engine.afterFlush(function(){r.destroy()}):e.push(l)}}),this._queue=[],e.sort(function(n,e){var l=n.transition.ast.depCount,r=e.transition.ast.depCount;return 0==l||0==r?l-r:t._engine.driver.containsElement(n.element,e.element)?1:-1})},n.prototype.destroy=function(n){this.players.forEach(function(n){return n.destroy()}),this._signalRemovalForInnerTriggers(this.hostElement,n)},n.prototype.elementContainsData=function(n){var t=!1;return this._elementListeners.has(n)&&(t=!0),!!this._queue.find(function(t){return t.element===n})||t},n}(),Bv=function(){function n(n,t,e){this.bodyNode=n,this.driver=t,this._normalizer=e,this.players=[],this.newHostElements=new Map,this.playersByElement=new Map,this.playersByQueriedElement=new Map,this.statesByElement=new Map,this.disabledNodes=new Set,this.totalAnimations=0,this.totalQueuedPlayers=0,this._namespaceLookup={},this._namespaceList=[],this._flushFns=[],this._whenQuietFns=[],this.namespacesByHostElement=new Map,this.collectedEnterElements=[],this.collectedLeaveElements=[],this.onRemovalComplete=function(n,t){}}return n.prototype._onRemovalComplete=function(n,t){this.onRemovalComplete(n,t)},Object.defineProperty(n.prototype,"queuedPlayers",{get:function(){var n=[];return this._namespaceList.forEach(function(t){t.players.forEach(function(t){t.queued&&n.push(t)})}),n},enumerable:!0,configurable:!0}),n.prototype.createNamespace=function(n,t){var e=new Fv(n,t,this);return t.parentNode?this._balanceNamespaceList(e,t):(this.newHostElements.set(t,e),this.collectEnterElement(t)),this._namespaceLookup[n]=e},n.prototype._balanceNamespaceList=function(n,t){var e=this._namespaceList.length-1;if(e>=0){for(var l=!1,r=e;r>=0;r--)if(this.driver.containsElement(this._namespaceList[r].hostElement,t)){this._namespaceList.splice(r+1,0,n),l=!0;break}l||this._namespaceList.splice(0,0,n)}else this._namespaceList.push(n);return this.namespacesByHostElement.set(t,n),n},n.prototype.register=function(n,t){var e=this._namespaceLookup[n];return e||(e=this.createNamespace(n,t)),e},n.prototype.registerTrigger=function(n,t,e){var l=this._namespaceLookup[n];l&&l.register(t,e)&&this.totalAnimations++},n.prototype.destroy=function(n,t){var e=this;if(n){var l=this._fetchNamespace(n);this.afterFlush(function(){e.namespacesByHostElement.delete(l.hostElement),delete e._namespaceLookup[n];var t=e._namespaceList.indexOf(l);t>=0&&e._namespaceList.splice(t,1)}),this.afterFlushAnimationsDone(function(){return l.destroy(t)})}},n.prototype._fetchNamespace=function(n){return this._namespaceLookup[n]},n.prototype.fetchNamespacesByElement=function(n){var t=new Set,e=this.statesByElement.get(n);if(e)for(var l=Object.keys(e),r=0;r<l.length;r++){var o=e[l[r]].namespaceId;if(o){var i=this._fetchNamespace(o);i&&t.add(i)}}return t},n.prototype.trigger=function(n,t,e,l){if(zv(t)){var r=this._fetchNamespace(n);if(r)return r.trigger(t,e,l),!0}return!1},n.prototype.insertNode=function(n,t,e,l){if(zv(t)){var r=t[Vv];if(r&&r.setForRemoval){r.setForRemoval=!1,r.setForMove=!0;var o=this.collectedLeaveElements.indexOf(t);o>=0&&this.collectedLeaveElements.splice(o,1)}if(n){var i=this._fetchNamespace(n);i&&i.insertNode(t,e)}l&&this.collectEnterElement(t)}},n.prototype.collectEnterElement=function(n){this.collectedEnterElements.push(n)},n.prototype.markElementAsDisabled=function(n,t){t?this.disabledNodes.has(n)||(this.disabledNodes.add(n),$v(n,"ng-animate-disabled")):this.disabledNodes.has(n)&&(this.disabledNodes.delete(n),Kv(n,"ng-animate-disabled"))},n.prototype.removeNode=function(n,t,e){if(zv(t)){var l=n?this._fetchNamespace(n):null;l?l.removeNode(t,e):this.markElementAsRemoved(n,t,!1,e)}else this._onRemovalComplete(t,e)},n.prototype.markElementAsRemoved=function(n,t,e,l){this.collectedLeaveElements.push(t),t[Vv]={namespaceId:n,setForRemoval:l,hasAnimation:e,removedBeforeQueried:!1}},n.prototype.listen=function(n,t,e,l,r){return zv(t)?this._fetchNamespace(n).listen(t,e,l,r):function(){}},n.prototype._buildInstruction=function(n,t,e,l,r){return n.transition.build(this.driver,n.element,n.fromState.value,n.toState.value,e,l,n.fromState.options,n.toState.options,t,r)},n.prototype.destroyInnerAnimations=function(n){var t=this,e=this.driver.query(n,".ng-trigger",!0);e.forEach(function(n){return t.destroyActiveAnimationsForElement(n)}),0!=this.playersByQueriedElement.size&&(e=this.driver.query(n,".ng-animating",!0)).forEach(function(n){return t.finishActiveQueriedAnimationOnElement(n)})},n.prototype.destroyActiveAnimationsForElement=function(n){var t=this.playersByElement.get(n);t&&t.forEach(function(n){n.queued?n.markedForDestroy=!0:n.destroy()})},n.prototype.finishActiveQueriedAnimationOnElement=function(n){var t=this.playersByQueriedElement.get(n);t&&t.forEach(function(n){return n.finish()})},n.prototype.whenRenderingDone=function(){var n=this;return new Promise(function(t){if(n.players.length)return py(n.players).onDone(function(){return t()});t()})},n.prototype.processLeaveNode=function(n){var t=this,e=n[Vv];if(e&&e.setForRemoval){if(n[Vv]=Nv,e.namespaceId){this.destroyInnerAnimations(n);var l=this._fetchNamespace(e.namespaceId);l&&l.clearElementCache(n)}this._onRemovalComplete(n,e.setForRemoval)}this.driver.matchesElement(n,".ng-animate-disabled")&&this.markElementAsDisabled(n,!1),this.driver.query(n,".ng-animate-disabled",!0).forEach(function(n){t.markElementAsDisabled(n,!1)})},n.prototype.flush=function(n){var t=this;void 0===n&&(n=-1);var e=[];if(this.newHostElements.size&&(this.newHostElements.forEach(function(n,e){return t._balanceNamespaceList(n,e)}),this.newHostElements.clear()),this.totalAnimations&&this.collectedEnterElements.length)for(var l=0;l<this.collectedEnterElements.length;l++)$v(this.collectedEnterElements[l],"ng-star-inserted");if(this._namespaceList.length&&(this.totalQueuedPlayers||this.collectedLeaveElements.length)){var r=[];try{e=this._flushAnimations(r,n)}finally{for(l=0;l<r.length;l++)r[l]()}}else for(l=0;l<this.collectedLeaveElements.length;l++)this.processLeaveNode(this.collectedLeaveElements[l]);if(this.totalQueuedPlayers=0,this.collectedEnterElements.length=0,this.collectedLeaveElements.length=0,this._flushFns.forEach(function(n){return n()}),this._flushFns=[],this._whenQuietFns.length){var o=this._whenQuietFns;this._whenQuietFns=[],e.length?py(e).onDone(function(){o.forEach(function(n){return n()})}):o.forEach(function(n){return n()})}},n.prototype.reportError=function(n){throw new Error("Unable to process animations due to the following failed trigger transitions\n "+n.join("\n"))},n.prototype._flushAnimations=function(n,t){var e=this,l=new hv,r=[],i=new Map,u=[],a=new Map,s=new Map,p=new Map,h=new Set;this.disabledNodes.forEach(function(n){h.add(n);for(var t=e.driver.query(n,".ng-animate-queued",!0),l=0;l<t.length;l++)h.add(t[l])});var d=this.bodyNode,f=Array.from(this.statesByElement.keys()),g=Wv(f,this.collectedEnterElements),m=new Map,y=0;g.forEach(function(n,t){var e="ng-enter"+y++;m.set(t,e),n.forEach(function(n){return $v(n,e)})});for(var v=[],_=new Set,b=new Set,w=0;w<this.collectedLeaveElements.length;w++)(U=(V=this.collectedLeaveElements[w])[Vv])&&U.setForRemoval&&(v.push(V),_.add(V),U.hasAnimation?this.driver.query(V,".ng-star-inserted",!0).forEach(function(n){return _.add(n)}):b.add(V));var C=new Map,S=Wv(f,Array.from(_));S.forEach(function(n,t){var e="ng-leave"+y++;C.set(t,e),n.forEach(function(n){return $v(n,e)})}),n.push(function(){g.forEach(function(n,t){var e=m.get(t);n.forEach(function(n){return Kv(n,e)})}),S.forEach(function(n,t){var e=C.get(t);n.forEach(function(n){return Kv(n,e)})}),v.forEach(function(n){e.processLeaveNode(n)})});for(var E=[],x=[],P=this._namespaceList.length-1;P>=0;P--)this._namespaceList[P].drainQueuedTransitions(t).forEach(function(n){var t=n.player,o=n.element;if(E.push(t),e.collectedEnterElements.length){var i=o[Vv];if(i&&i.setForMove)return void t.destroy()}var c=!d||!e.driver.containsElement(d,o),h=C.get(o),f=m.get(o),g=e._buildInstruction(n,l,f,h,c);if(g.errors&&g.errors.length)x.push(g);else{if(c)return t.onStart(function(){return Hy(o,g.fromStyles)}),t.onDestroy(function(){return By(o,g.toStyles)}),void r.push(t);if(n.isFallbackTransition)return t.onStart(function(){return Hy(o,g.fromStyles)}),t.onDestroy(function(){return By(o,g.toStyles)}),void r.push(t);g.timelines.forEach(function(n){return n.stretchStartingKeyframe=!0}),l.append(o,g.timelines),u.push({instruction:g,player:t,element:o}),g.queriedElements.forEach(function(n){return my(a,n,[]).push(t)}),g.preStyleProps.forEach(function(n,t){var e=Object.keys(n);if(e.length){var l=s.get(t);l||s.set(t,l=new Set),e.forEach(function(n){return l.add(n)})}}),g.postStyleProps.forEach(function(n,t){var e=Object.keys(n),l=p.get(t);l||p.set(t,l=new Set),e.forEach(function(n){return l.add(n)})})}});if(x.length){var T=[];x.forEach(function(n){T.push("@"+n.triggerName+" has failed due to:\n"),n.errors.forEach(function(n){return T.push("- "+n+"\n")})}),E.forEach(function(n){return n.destroy()}),this.reportError(T)}var I=new Map,O=new Map;u.forEach(function(n){var t=n.element;l.has(t)&&(O.set(t,t),e._beforeAnimationBuild(n.player.namespaceId,n.instruction,I))}),r.forEach(function(n){var t=n.element;e._getPreviousPlayers(t,!1,n.namespaceId,n.triggerName,null).forEach(function(n){my(I,t,[]).push(n),n.destroy()})});var k=v.filter(function(n){return Yv(n,s,p)}),D=new Map;Gv(D,this.driver,b,p,ly).forEach(function(n){Yv(n,s,p)&&k.push(n)});var A=new Map;g.forEach(function(n,t){Gv(A,e.driver,new Set(n),s,sy)}),k.forEach(function(n){var t=D.get(n),e=A.get(n);D.set(n,o({},t,e))});var R=[],M=[],N={};u.forEach(function(n){var t=n.element,o=n.player,u=n.instruction;if(l.has(t)){if(h.has(t))return o.onDestroy(function(){return By(t,u.toStyles)}),o.disabled=!0,o.overrideTotalTime(u.totalTime),void r.push(o);var a=N;if(O.size>1){for(var s=t,c=[];s=s.parentNode;){var p=O.get(s);if(p){a=p;break}c.push(s)}c.forEach(function(n){return O.set(n,a)})}var d=e._buildAnimation(o.namespaceId,u,I,i,A,D);if(o.setRealPlayer(d),a===N)R.push(o);else{var f=e.playersByElement.get(a);f&&f.length&&(o.parentPlayer=py(f)),r.push(o)}}else Hy(t,u.fromStyles),o.onDestroy(function(){return By(t,u.toStyles)}),M.push(o),h.has(t)&&r.push(o)}),M.forEach(function(n){var t=i.get(n.element);if(t&&t.length){var e=py(t);n.setRealPlayer(e)}}),r.forEach(function(n){n.parentPlayer?n.syncPlayerEvents(n.parentPlayer):n.destroy()});for(var L=0;L<v.length;L++){var V,U=(V=v[L])[Vv];if(Kv(V,"ng-leave"),!U||!U.hasAnimation){var j=[];if(a.size){var F=a.get(V);F&&F.length&&j.push.apply(j,c(F));for(var B=this.driver.query(V,".ng-animating",!0),H=0;H<B.length;H++){var z=a.get(B[H]);z&&z.length&&j.push.apply(j,c(z))}}var q=j.filter(function(n){return!n.destroyed});q.length?Zv(this,V,q):this.processLeaveNode(V)}}return v.length=0,R.forEach(function(n){e.players.push(n),n.onDone(function(){n.destroy();var t=e.players.indexOf(n);e.players.splice(t,1)}),n.play()}),R},n.prototype.elementContainsData=function(n,t){var e=!1,l=t[Vv];return l&&l.setForRemoval&&(e=!0),this.playersByElement.has(t)&&(e=!0),this.playersByQueriedElement.has(t)&&(e=!0),this.statesByElement.has(t)&&(e=!0),this._fetchNamespace(n).elementContainsData(t)||e},n.prototype.afterFlush=function(n){this._flushFns.push(n)},n.prototype.afterFlushAnimationsDone=function(n){this._whenQuietFns.push(n)},n.prototype._getPreviousPlayers=function(n,t,e,l,r){var o=[];if(t){var i=this.playersByQueriedElement.get(n);i&&(o=i)}else{var u=this.playersByElement.get(n);if(u){var a=!r||"void"==r;u.forEach(function(n){n.queued||(a||n.triggerName==l)&&o.push(n)})}}return(e||l)&&(o=o.filter(function(n){return!(e&&e!=n.namespaceId||l&&l!=n.triggerName)})),o},n.prototype._beforeAnimationBuild=function(n,t,e){var l,r,o=t.element,i=t.isRemovalTransition?void 0:n,u=t.isRemovalTransition?void 0:t.triggerName,s=function(n){var l=n.element,r=l!==o,a=my(e,l,[]);c._getPreviousPlayers(l,r,i,u,t.toState).forEach(function(n){var t=n.getRealPlayer();t.beforeDestroy&&t.beforeDestroy(),n.destroy(),a.push(n)})},c=this;try{for(var p=a(t.timelines),h=p.next();!h.done;h=p.next())s(h.value)}catch(d){l={error:d}}finally{try{h&&!h.done&&(r=p.return)&&r.call(p)}finally{if(l)throw l.error}}Hy(o,t.fromStyles)},n.prototype._buildAnimation=function(n,t,e,l,r,o){var i=this,u=t.triggerName,a=t.element,s=[],c=new Set,p=new Set,h=t.timelines.map(function(t){var h=t.element;c.add(h);var d=h[Vv];if(d&&d.removedBeforeQueried)return new uy(t.duration,t.delay);var f,g,m=h!==a,y=(f=(e.get(h)||Mv).map(function(n){return n.getRealPlayer()}),g=[],function n(t,e){for(var l=0;l<t.length;l++){var r=t[l];r instanceof ay?n(r.players,e):e.push(r)}}(f,g),g).filter(function(n){return!!n.element&&n.element===h}),v=r.get(h),_=o.get(h),b=hy(0,i._normalizer,0,t.keyframes,v,_),w=i._buildPlayer(t,b,y);if(t.subTimeline&&l&&p.add(h),m){var C=new Hv(n,u,h);C.setRealPlayer(w),s.push(C)}return w});s.forEach(function(n){my(i.playersByQueriedElement,n.element,[]).push(n),n.onDone(function(){return function(n,t,e){var l;if(n instanceof Map){if(l=n.get(t)){if(l.length){var r=l.indexOf(e);l.splice(r,1)}0==l.length&&n.delete(t)}}else(l=n[t])&&(l.length&&(r=l.indexOf(e),l.splice(r,1)),0==l.length&&delete n[t]);return l}(i.playersByQueriedElement,n.element,n)})}),c.forEach(function(n){return $v(n,"ng-animating")});var d=py(h);return d.onDestroy(function(){c.forEach(function(n){return Kv(n,"ng-animating")}),By(a,t.toStyles)}),p.forEach(function(n){my(l,n,[]).push(d)}),d},n.prototype._buildPlayer=function(n,t,e){return t.length>0?this.driver.animate(n.element,t,n.duration,n.delay,n.easing,e):new uy(n.duration,n.delay)},n}(),Hv=function(){function n(n,t,e){this.namespaceId=n,this.triggerName=t,this.element=e,this._player=new uy,this._containsRealPlayer=!1,this._queuedCallbacks={},this.destroyed=!1,this.markedForDestroy=!1,this.disabled=!1,this.queued=!0,this.totalTime=0}return n.prototype.setRealPlayer=function(n){var t=this;this._containsRealPlayer||(this._player=n,Object.keys(this._queuedCallbacks).forEach(function(e){t._queuedCallbacks[e].forEach(function(t){return dy(n,e,void 0,t)})}),this._queuedCallbacks={},this._containsRealPlayer=!0,this.overrideTotalTime(n.totalTime),this.queued=!1)},n.prototype.getRealPlayer=function(){return this._player},n.prototype.overrideTotalTime=function(n){this.totalTime=n},n.prototype.syncPlayerEvents=function(n){var t=this,e=this._player;e.triggerCallback&&n.onStart(function(){return e.triggerCallback("start")}),n.onDone(function(){return t.finish()}),n.onDestroy(function(){return t.destroy()})},n.prototype._queueEvent=function(n,t){my(this._queuedCallbacks,n,[]).push(t)},n.prototype.onDone=function(n){this.queued&&this._queueEvent("done",n),this._player.onDone(n)},n.prototype.onStart=function(n){this.queued&&this._queueEvent("start",n),this._player.onStart(n)},n.prototype.onDestroy=function(n){this.queued&&this._queueEvent("destroy",n),this._player.onDestroy(n)},n.prototype.init=function(){this._player.init()},n.prototype.hasStarted=function(){return!this.queued&&this._player.hasStarted()},n.prototype.play=function(){!this.queued&&this._player.play()},n.prototype.pause=function(){!this.queued&&this._player.pause()},n.prototype.restart=function(){!this.queued&&this._player.restart()},n.prototype.finish=function(){this._player.finish()},n.prototype.destroy=function(){this.destroyed=!0,this._player.destroy()},n.prototype.reset=function(){!this.queued&&this._player.reset()},n.prototype.setPosition=function(n){this.queued||this._player.setPosition(n)},n.prototype.getPosition=function(){return this.queued?0:this._player.getPosition()},n.prototype.triggerCallback=function(n){var t=this._player;t.triggerCallback&&t.triggerCallback(n)},n}();function zv(n){return n&&1===n.nodeType}function qv(n,t){var e=n.style.display;return n.style.display=null!=t?t:"none",e}function Gv(n,t,e,l,r){var o=[];e.forEach(function(n){return o.push(qv(n))});var i=[];l.forEach(function(e,l){var o={};e.forEach(function(n){var e=o[n]=t.computeStyle(l,n,r);e&&0!=e.length||(l[Vv]=Lv,i.push(l))}),n.set(l,o)});var u=0;return e.forEach(function(n){return qv(n,o[u++])}),i}function Wv(n,t){var e=new Map;if(n.forEach(function(n){return e.set(n,[])}),0==t.length)return e;var l=new Set(t),r=new Map;return t.forEach(function(n){var t=function n(t){if(!t)return 1;var o=r.get(t);if(o)return o;var i=t.parentNode;return o=e.has(i)?i:l.has(i)?1:n(i),r.set(t,o),o}(n);1!==t&&e.get(t).push(n)}),e}var Qv="$$classes";function $v(n,t){if(n.classList)n.classList.add(t);else{var e=n[Qv];e||(e=n[Qv]={}),e[t]=!0}}function Kv(n,t){if(n.classList)n.classList.remove(t);else{var e=n[Qv];e&&delete e[t]}}function Zv(n,t,e){py(e).onDone(function(){return n.processLeaveNode(t)})}function Yv(n,t,e){var l=e.get(n);if(!l)return!1;var r=t.get(n);return r?l.forEach(function(n){return r.add(n)}):t.set(n,l),e.delete(n),!0}var Xv=function(){function n(n,t,e){var l=this;this.bodyNode=n,this._driver=t,this._triggerCache={},this.onRemovalComplete=function(n,t){},this._transitionEngine=new Bv(n,t,e),this._timelineEngine=new Rv(n,t,e),this._transitionEngine.onRemovalComplete=function(n,t){return l.onRemovalComplete(n,t)}}return n.prototype.registerTrigger=function(n,t,e,l,r){var o=n+"-"+l,i=this._triggerCache[o];if(!i){var u=[],a=ov(this._driver,r,u);if(u.length)throw new Error('The animation trigger "'+l+'" has failed to build due to the following errors:\n - '+u.join("\n - "));i=function(n,t){return new kv(n,t)}(l,a),this._triggerCache[o]=i}this._transitionEngine.registerTrigger(t,l,i)},n.prototype.register=function(n,t){this._transitionEngine.register(n,t)},n.prototype.destroy=function(n,t){this._transitionEngine.destroy(n,t)},n.prototype.onInsert=function(n,t,e,l){this._transitionEngine.insertNode(n,t,e,l)},n.prototype.onRemove=function(n,t,e){this._transitionEngine.removeNode(n,t,e)},n.prototype.disableAnimations=function(n,t){this._transitionEngine.markElementAsDisabled(n,t)},n.prototype.process=function(n,t,e,l){if("@"==e.charAt(0)){var r=s(yy(e),2);this._timelineEngine.command(r[0],t,r[1],l)}else this._transitionEngine.trigger(n,t,e,l)},n.prototype.listen=function(n,t,e,l,r){if("@"==e.charAt(0)){var o=s(yy(e),2);return this._timelineEngine.listen(o[0],t,o[1],r)}return this._transitionEngine.listen(n,t,e,l,r)},n.prototype.flush=function(n){void 0===n&&(n=-1),this._transitionEngine.flush(n)},Object.defineProperty(n.prototype,"players",{get:function(){return this._transitionEngine.players.concat(this._timelineEngine.players)},enumerable:!0,configurable:!0}),n.prototype.whenRenderingDone=function(){return this._transitionEngine.whenRenderingDone()},n}();function Jv(n,t){var e=null,l=null;return Array.isArray(t)&&t.length?(e=t_(t[0]),t.length>1&&(l=t_(t[t.length-1]))):t&&(e=t_(t)),e||l?new n_(n,e,l):null}var n_=function(){function n(t,e,l){this._element=t,this._startStyles=e,this._endStyles=l,this._state=0;var r=n.initialStylesByElement.get(t);r||n.initialStylesByElement.set(t,r={}),this._initialStyles=r}return n.prototype.start=function(){this._state<1&&(this._startStyles&&By(this._element,this._startStyles,this._initialStyles),this._state=1)},n.prototype.finish=function(){this.start(),this._state<2&&(By(this._element,this._initialStyles),this._endStyles&&(By(this._element,this._endStyles),this._endStyles=null),this._state=1)},n.prototype.destroy=function(){this.finish(),this._state<3&&(n.initialStylesByElement.delete(this._element),this._startStyles&&(Hy(this._element,this._startStyles),this._endStyles=null),this._endStyles&&(Hy(this._element,this._endStyles),this._endStyles=null),By(this._element,this._initialStyles),this._state=3)},n.initialStylesByElement=new WeakMap,n}();function t_(n){for(var t=null,e=Object.keys(n),l=0;l<e.length;l++){var r=e[l];e_(r)&&((t=t||{})[r]=n[r])}return t}function e_(n){return"display"===n||"position"===n}var l_="animation",r_="animationend",o_=function(){function n(n,t,e,l,r,o,i){var u=this;this._element=n,this._name=t,this._duration=e,this._delay=l,this._easing=r,this._fillMode=o,this._onDoneFn=i,this._finished=!1,this._destroyed=!1,this._startTime=0,this._position=0,this._eventFn=function(n){return u._handleCallback(n)}}return n.prototype.apply=function(){var n,t,e;t=this._duration+"ms "+this._easing+" "+this._delay+"ms 1 normal "+this._fillMode+" "+this._name,(e=p_(n=this._element,"").trim()).length&&(function(n,t){for(var e=0;e<n.length;e++)","===n.charAt(e)&&0}(e),t=e+", "+t),c_(n,"",t),s_(this._element,this._eventFn,!1),this._startTime=Date.now()},n.prototype.pause=function(){i_(this._element,this._name,"paused")},n.prototype.resume=function(){i_(this._element,this._name,"running")},n.prototype.setPosition=function(n){var t=u_(this._element,this._name);this._position=n*this._duration,c_(this._element,"Delay","-"+this._position+"ms",t)},n.prototype.getPosition=function(){return this._position},n.prototype._handleCallback=function(n){var t=n._ngTestManualTimestamp||Date.now(),e=1e3*parseFloat(n.elapsedTime.toFixed(3));n.animationName==this._name&&Math.max(t-this._startTime,0)>=this._delay&&e>=this._duration&&this.finish()},n.prototype.finish=function(){this._finished||(this._finished=!0,this._onDoneFn(),s_(this._element,this._eventFn,!0))},n.prototype.destroy=function(){var n,t,e,l;this._destroyed||(this._destroyed=!0,this.finish(),t=this._name,(l=a_(e=p_(n=this._element,"").split(","),t))>=0&&(e.splice(l,1),c_(n,"",e.join(","))))},n}();function i_(n,t,e){c_(n,"PlayState",e,u_(n,t))}function u_(n,t){var e=p_(n,"");return e.indexOf(",")>0?a_(e.split(","),t):a_([e],t)}function a_(n,t){for(var e=0;e<n.length;e++)if(n[e].indexOf(t)>=0)return e;return-1}function s_(n,t,e){e?n.removeEventListener(r_,t):n.addEventListener(r_,t)}function c_(n,t,e,l){var r=l_+t;if(null!=l){var o=n.style[r];if(o.length){var i=o.split(",");i[l]=e,e=i.join(",")}}n.style[r]=e}function p_(n,t){return n.style[l_+t]}var h_="linear",d_=function(){function n(n,t,e,l,r,o,i,u){this.element=n,this.keyframes=t,this.animationName=e,this._duration=l,this._delay=r,this._finalStyles=i,this._specialStyles=u,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._started=!1,this.currentSnapshot={},this._state=0,this.easing=o||h_,this.totalTime=l+r,this._buildStyler()}return n.prototype.onStart=function(n){this._onStartFns.push(n)},n.prototype.onDone=function(n){this._onDoneFns.push(n)},n.prototype.onDestroy=function(n){this._onDestroyFns.push(n)},n.prototype.destroy=function(){this.init(),this._state>=4||(this._state=4,this._styler.destroy(),this._flushStartFns(),this._flushDoneFns(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(function(n){return n()}),this._onDestroyFns=[])},n.prototype._flushDoneFns=function(){this._onDoneFns.forEach(function(n){return n()}),this._onDoneFns=[]},n.prototype._flushStartFns=function(){this._onStartFns.forEach(function(n){return n()}),this._onStartFns=[]},n.prototype.finish=function(){this.init(),this._state>=3||(this._state=3,this._styler.finish(),this._flushStartFns(),this._specialStyles&&this._specialStyles.finish(),this._flushDoneFns())},n.prototype.setPosition=function(n){this._styler.setPosition(n)},n.prototype.getPosition=function(){return this._styler.getPosition()},n.prototype.hasStarted=function(){return this._state>=2},n.prototype.init=function(){this._state>=1||(this._state=1,this._styler.apply(),this._delay&&this._styler.pause())},n.prototype.play=function(){this.init(),this.hasStarted()||(this._flushStartFns(),this._state=2,this._specialStyles&&this._specialStyles.start()),this._styler.resume()},n.prototype.pause=function(){this.init(),this._styler.pause()},n.prototype.restart=function(){this.reset(),this.play()},n.prototype.reset=function(){this._styler.destroy(),this._buildStyler(),this._styler.apply()},n.prototype._buildStyler=function(){var n=this;this._styler=new o_(this.element,this.animationName,this._duration,this._delay,this.easing,"forwards",function(){return n.finish()})},n.prototype.triggerCallback=function(n){var t="start"==n?this._onStartFns:this._onDoneFns;t.forEach(function(n){return n()}),t.length=0},n.prototype.beforeDestroy=function(){var n=this;this.init();var t={};if(this.hasStarted()){var e=this._state>=3;Object.keys(this._finalStyles).forEach(function(l){"offset"!=l&&(t[l]=e?n._finalStyles[l]:Jy(n.element,l))})}this.currentSnapshot=t},n}(),f_=function(n){function t(t,e){var l=n.call(this)||this;return l.element=t,l._startingStyles={},l.__initialized=!1,l._styles=ky(e),l}return r(t,n),t.prototype.init=function(){var t=this;!this.__initialized&&this._startingStyles&&(this.__initialized=!0,Object.keys(this._styles).forEach(function(n){t._startingStyles[n]=t.element.style[n]}),n.prototype.init.call(this))},t.prototype.play=function(){var t=this;this._startingStyles&&(this.init(),Object.keys(this._styles).forEach(function(n){return t.element.style.setProperty(n,t._styles[n])}),n.prototype.play.call(this))},t.prototype.destroy=function(){var t=this;this._startingStyles&&(Object.keys(this._startingStyles).forEach(function(n){var e=t._startingStyles[n];e?t.element.style.setProperty(n,e):t.element.style.removeProperty(n)}),this._startingStyles=null,n.prototype.destroy.call(this))},t}(uy),g_=function(){function n(){this._count=0,this._head=document.querySelector("head"),this._warningIssued=!1}return n.prototype.validateStyleProperty=function(n){return Py(n)},n.prototype.matchesElement=function(n,t){return Ty(n,t)},n.prototype.containsElement=function(n,t){return Iy(n,t)},n.prototype.query=function(n,t,e){return Oy(n,t,e)},n.prototype.computeStyle=function(n,t,e){return window.getComputedStyle(n)[t]},n.prototype.buildKeyframeElement=function(n,t,e){e=e.map(function(n){return ky(n)});var l="@keyframes "+t+" {\n",r="";e.forEach(function(n){r=" ";var t=parseFloat(n.offset);l+=""+r+100*t+"% {\n",r+=" ",Object.keys(n).forEach(function(t){var e=n[t];switch(t){case"offset":return;case"easing":return void(e&&(l+=r+"animation-timing-function: "+e+";\n"));default:return void(l+=""+r+t+": "+e+";\n")}}),l+=r+"}\n"}),l+="}\n";var o=document.createElement("style");return o.innerHTML=l,o},n.prototype.animate=function(n,t,e,l,r,o,i){void 0===o&&(o=[]),i&&this._notifyFaultyScrubber();var u=o.filter(function(n){return n instanceof d_}),a={};Zy(e,l)&&u.forEach(function(n){var t=n.currentSnapshot;Object.keys(t).forEach(function(n){return a[n]=t[n]})});var s=function(n){var t={};return n&&(Array.isArray(n)?n:[n]).forEach(function(n){Object.keys(n).forEach(function(e){"offset"!=e&&"easing"!=e&&(t[e]=n[e])})}),t}(t=Yy(n,t,a));if(0==e)return new f_(n,s);var c="gen_css_kf_"+this._count++,p=this.buildKeyframeElement(n,c,t);document.querySelector("head").appendChild(p);var h=Jv(n,t),d=new d_(n,t,c,e,l,r,s,h);return d.onDestroy(function(){var n;(n=p).parentNode.removeChild(n)}),d},n.prototype._notifyFaultyScrubber=function(){this._warningIssued||(console.warn("@angular/animations: please load the web-animations.js polyfill to allow programmatic access...\n"," visit http://bit.ly/IWukam to learn more about using the web-animation-js polyfill."),this._warningIssued=!0)},n}(),m_=function(){function n(n,t,e,l){this.element=n,this.keyframes=t,this.options=e,this._specialStyles=l,this._onDoneFns=[],this._onStartFns=[],this._onDestroyFns=[],this._initialized=!1,this._finished=!1,this._started=!1,this._destroyed=!1,this.time=0,this.parentPlayer=null,this.currentSnapshot={},this._duration=e.duration,this._delay=e.delay||0,this.time=this._duration+this._delay}return n.prototype._onFinish=function(){this._finished||(this._finished=!0,this._onDoneFns.forEach(function(n){return n()}),this._onDoneFns=[])},n.prototype.init=function(){this._buildPlayer(),this._preparePlayerBeforeStart()},n.prototype._buildPlayer=function(){var n=this;if(!this._initialized){this._initialized=!0;var t=this.keyframes;this.domPlayer=this._triggerWebAnimation(this.element,t,this.options),this._finalKeyframe=t.length?t[t.length-1]:{},this.domPlayer.addEventListener("finish",function(){return n._onFinish()})}},n.prototype._preparePlayerBeforeStart=function(){this._delay?this._resetDomPlayerState():this.domPlayer.pause()},n.prototype._triggerWebAnimation=function(n,t,e){return n.animate(t,e)},n.prototype.onStart=function(n){this._onStartFns.push(n)},n.prototype.onDone=function(n){this._onDoneFns.push(n)},n.prototype.onDestroy=function(n){this._onDestroyFns.push(n)},n.prototype.play=function(){this._buildPlayer(),this.hasStarted()||(this._onStartFns.forEach(function(n){return n()}),this._onStartFns=[],this._started=!0,this._specialStyles&&this._specialStyles.start()),this.domPlayer.play()},n.prototype.pause=function(){this.init(),this.domPlayer.pause()},n.prototype.finish=function(){this.init(),this._specialStyles&&this._specialStyles.finish(),this._onFinish(),this.domPlayer.finish()},n.prototype.reset=function(){this._resetDomPlayerState(),this._destroyed=!1,this._finished=!1,this._started=!1},n.prototype._resetDomPlayerState=function(){this.domPlayer&&this.domPlayer.cancel()},n.prototype.restart=function(){this.reset(),this.play()},n.prototype.hasStarted=function(){return this._started},n.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this._resetDomPlayerState(),this._onFinish(),this._specialStyles&&this._specialStyles.destroy(),this._onDestroyFns.forEach(function(n){return n()}),this._onDestroyFns=[])},n.prototype.setPosition=function(n){this.domPlayer.currentTime=n*this.time},n.prototype.getPosition=function(){return this.domPlayer.currentTime/this.time},Object.defineProperty(n.prototype,"totalTime",{get:function(){return this._delay+this._duration},enumerable:!0,configurable:!0}),n.prototype.beforeDestroy=function(){var n=this,t={};this.hasStarted()&&Object.keys(this._finalKeyframe).forEach(function(e){"offset"!=e&&(t[e]=n._finished?n._finalKeyframe[e]:Jy(n.element,e))}),this.currentSnapshot=t},n.prototype.triggerCallback=function(n){var t="start"==n?this._onStartFns:this._onDoneFns;t.forEach(function(n){return n()}),t.length=0},n}(),y_=function(){function n(){this._isNativeImpl=/\{\s*\[native\s+code\]\s*\}/.test(v_().toString()),this._cssKeyframesDriver=new g_}return n.prototype.validateStyleProperty=function(n){return Py(n)},n.prototype.matchesElement=function(n,t){return Ty(n,t)},n.prototype.containsElement=function(n,t){return Iy(n,t)},n.prototype.query=function(n,t,e){return Oy(n,t,e)},n.prototype.computeStyle=function(n,t,e){return window.getComputedStyle(n)[t]},n.prototype.overrideWebAnimationsSupport=function(n){this._isNativeImpl=n},n.prototype.animate=function(n,t,e,l,r,o,i){if(void 0===o&&(o=[]),!i&&!this._isNativeImpl)return this._cssKeyframesDriver.animate(n,t,e,l,r,o);var u={duration:e,delay:l,fill:0==l?"both":"forwards"};r&&(u.easing=r);var a={},s=o.filter(function(n){return n instanceof m_});Zy(e,l)&&s.forEach(function(n){var t=n.currentSnapshot;Object.keys(t).forEach(function(n){return a[n]=t[n]})});var c=Jv(n,t=Yy(n,t=t.map(function(n){return Uy(n,!1)}),a));return new m_(n,t,u,c)},n}();function v_(){return"undefined"!=typeof window&&void 0!==window.document&&Element.prototype.animate||{}}var __=function(n){function t(t,e){var l=n.call(this)||this;return l._nextAnimationId=0,l._renderer=t.createRenderer(e.body,{id:"0",encapsulation:Fn.None,styles:[],data:{animation:[]}}),l}return r(t,n),t.prototype.build=function(n){var t=this._nextAnimationId.toString();this._nextAnimationId++;var e=Array.isArray(n)?ry(n):n;return C_(this._renderer,null,t,"register",[e]),new b_(t,this._renderer)},t}(ty),b_=function(n){function t(t,e){var l=n.call(this)||this;return l._id=t,l._renderer=e,l}return r(t,n),t.prototype.create=function(n,t){return new w_(this._id,n,t||{},this._renderer)},t}(ey),w_=function(){function n(n,t,e,l){this.id=n,this.element=t,this._renderer=l,this.parentPlayer=null,this._started=!1,this.totalTime=0,this._command("create",e)}return n.prototype._listen=function(n,t){return this._renderer.listen(this.element,"@@"+this.id+":"+n,t)},n.prototype._command=function(n){for(var t=[],e=1;e<arguments.length;e++)t[e-1]=arguments[e];return C_(this._renderer,this.element,this.id,n,t)},n.prototype.onDone=function(n){this._listen("done",n)},n.prototype.onStart=function(n){this._listen("start",n)},n.prototype.onDestroy=function(n){this._listen("destroy",n)},n.prototype.init=function(){this._command("init")},n.prototype.hasStarted=function(){return this._started},n.prototype.play=function(){this._command("play"),this._started=!0},n.prototype.pause=function(){this._command("pause")},n.prototype.restart=function(){this._command("restart")},n.prototype.finish=function(){this._command("finish")},n.prototype.destroy=function(){this._command("destroy")},n.prototype.reset=function(){this._command("reset")},n.prototype.setPosition=function(n){this._command("setPosition",n)},n.prototype.getPosition=function(){return 0},n}();function C_(n,t,e,l,r){return n.setProperty(t,"@@"+e+":"+l,r)}var S_=function(){function n(n,t,e){this.delegate=n,this.engine=t,this._zone=e,this._currentId=0,this._microtaskId=1,this._animationCallbacksBuffer=[],this._rendererCache=new Map,this._cdRecurDepth=0,this.promise=Promise.resolve(0),t.onRemovalComplete=function(n,t){t&&t.parentNode(n)&&t.removeChild(n.parentNode,n)}}return n.prototype.createRenderer=function(n,t){var e=this,l=this.delegate.createRenderer(n,t);if(!(n&&t&&t.data&&t.data.animation)){var r=this._rendererCache.get(l);return r||(r=new E_("",l,this.engine),this._rendererCache.set(l,r)),r}var o=t.id,i=t.id+"-"+this._currentId;return this._currentId++,this.engine.register(i,n),t.data.animation.forEach(function(t){return e.engine.registerTrigger(o,i,n,t.name,t)}),new x_(this,i,l,this.engine)},n.prototype.begin=function(){this._cdRecurDepth++,this.delegate.begin&&this.delegate.begin()},n.prototype._scheduleCountTask=function(){var n=this;this.promise.then(function(){n._microtaskId++})},n.prototype.scheduleListenerCallback=function(n,t,e){var l=this;n>=0&&n<this._microtaskId?this._zone.run(function(){return t(e)}):(0==this._animationCallbacksBuffer.length&&Promise.resolve(null).then(function(){l._zone.run(function(){l._animationCallbacksBuffer.forEach(function(n){var t=s(n,2);(0,t[0])(t[1])}),l._animationCallbacksBuffer=[]})}),this._animationCallbacksBuffer.push([t,e]))},n.prototype.end=function(){var n=this;this._cdRecurDepth--,0==this._cdRecurDepth&&this._zone.runOutsideAngular(function(){n._scheduleCountTask(),n.engine.flush(n._microtaskId)}),this.delegate.end&&this.delegate.end()},n.prototype.whenRenderingDone=function(){return this.engine.whenRenderingDone()},n}(),E_=function(){function n(n,t,e){this.namespaceId=n,this.delegate=t,this.engine=e,this.destroyNode=this.delegate.destroyNode?function(n){return t.destroyNode(n)}:null}return Object.defineProperty(n.prototype,"data",{get:function(){return this.delegate.data},enumerable:!0,configurable:!0}),n.prototype.destroy=function(){this.engine.destroy(this.namespaceId,this.delegate),this.delegate.destroy()},n.prototype.createElement=function(n,t){return this.delegate.createElement(n,t)},n.prototype.createComment=function(n){return this.delegate.createComment(n)},n.prototype.createText=function(n){return this.delegate.createText(n)},n.prototype.appendChild=function(n,t){this.delegate.appendChild(n,t),this.engine.onInsert(this.namespaceId,t,n,!1)},n.prototype.insertBefore=function(n,t,e){this.delegate.insertBefore(n,t,e),this.engine.onInsert(this.namespaceId,t,n,!0)},n.prototype.removeChild=function(n,t){this.engine.onRemove(this.namespaceId,t,this.delegate)},n.prototype.selectRootElement=function(n,t){return this.delegate.selectRootElement(n,t)},n.prototype.parentNode=function(n){return this.delegate.parentNode(n)},n.prototype.nextSibling=function(n){return this.delegate.nextSibling(n)},n.prototype.setAttribute=function(n,t,e,l){this.delegate.setAttribute(n,t,e,l)},n.prototype.removeAttribute=function(n,t,e){this.delegate.removeAttribute(n,t,e)},n.prototype.addClass=function(n,t){this.delegate.addClass(n,t)},n.prototype.removeClass=function(n,t){this.delegate.removeClass(n,t)},n.prototype.setStyle=function(n,t,e,l){this.delegate.setStyle(n,t,e,l)},n.prototype.removeStyle=function(n,t,e){this.delegate.removeStyle(n,t,e)},n.prototype.setProperty=function(n,t,e){"@"==t.charAt(0)&&"@.disabled"==t?this.disableAnimations(n,!!e):this.delegate.setProperty(n,t,e)},n.prototype.setValue=function(n,t){this.delegate.setValue(n,t)},n.prototype.listen=function(n,t,e){return this.delegate.listen(n,t,e)},n.prototype.disableAnimations=function(n,t){this.engine.disableAnimations(n,t)},n}(),x_=function(n){function t(t,e,l,r){var o=n.call(this,e,l,r)||this;return o.factory=t,o.namespaceId=e,o}return r(t,n),t.prototype.setProperty=function(n,t,e){"@"==t.charAt(0)?"."==t.charAt(1)&&"@.disabled"==t?this.disableAnimations(n,e=void 0===e||!!e):this.engine.process(this.namespaceId,n,t.substr(1),e):this.delegate.setProperty(n,t,e)},t.prototype.listen=function(n,t,e){var l,r,o,i=this;if("@"==t.charAt(0)){var u=function(n){switch(n){case"body":return document.body;case"document":return document;case"window":return window;default:return n}}(n),a=t.substr(1),c="";return"@"!=a.charAt(0)&&(a=(l=s((r=a,o=r.indexOf("."),[r.substring(0,o),r.substr(o+1)]),2))[0],c=l[1]),this.engine.listen(this.namespaceId,u,a,c,function(n){i.factory.scheduleListenerCallback(n._data||-1,e,n)})}return this.delegate.listen(n,t,e)},t}(E_),P_=function(n){function t(t,e,l){return n.call(this,t.body,e,l)||this}return r(t,n),t}(Xv);function T_(){return"function"==typeof v_()?new y_:new g_}function I_(){return new Sv}function O_(n,t,e){return new S_(n,t,e)}var k_=new Sn("AnimationModuleType"),D_=function(){return function(){}}(),A_=new Sn("Flex Layout token, collect all breakpoints into one provider",{providedIn:"root",factory:function(){return null}}),R_=[{alias:"xs",mediaQuery:"(min-width: 0px) and (max-width: 599px)"},{alias:"gt-xs",overlapping:!0,mediaQuery:"(min-width: 600px)"},{alias:"lt-sm",overlapping:!0,mediaQuery:"(max-width: 599px)"},{alias:"sm",mediaQuery:"(min-width: 600px) and (max-width: 959px)"},{alias:"gt-sm",overlapping:!0,mediaQuery:"(min-width: 960px)"},{alias:"lt-md",overlapping:!0,mediaQuery:"(max-width: 959px)"},{alias:"md",mediaQuery:"(min-width: 960px) and (max-width: 1279px)"},{alias:"gt-md",overlapping:!0,mediaQuery:"(min-width: 1280px)"},{alias:"lt-lg",overlapping:!0,mediaQuery:"(max-width: 1279px)"},{alias:"lg",mediaQuery:"(min-width: 1280px) and (max-width: 1919px)"},{alias:"gt-lg",overlapping:!0,mediaQuery:"(min-width: 1920px)"},{alias:"lt-xl",overlapping:!0,mediaQuery:"(max-width: 1919px)"},{alias:"xl",mediaQuery:"(min-width: 1920px) and (max-width: 5000px)"}],M_="(orientation: landscape) and (min-width: 960px) and (max-width: 1279px)",N_="(orientation: portrait) and (min-width: 600px) and (max-width: 839px)",L_="(orientation: portrait) and (min-width: 840px)",V_="(orientation: landscape) and (min-width: 1280px)",U_={HANDSET:"(orientation: portrait) and (max-width: 599px), (orientation: landscape) and (max-width: 959px)",TABLET:N_+" , "+M_,WEB:L_+", "+V_+" ",HANDSET_PORTRAIT:"(orientation: portrait) and (max-width: 599px)",TABLET_PORTRAIT:N_+" ",WEB_PORTRAIT:""+L_,HANDSET_LANDSCAPE:"(orientation: landscape) and (max-width: 959px)]",TABLET_LANDSCAPE:""+M_,WEB_LANDSCAPE:""+V_},j_=[{alias:"handset",mediaQuery:U_.HANDSET},{alias:"handset.landscape",mediaQuery:U_.HANDSET_LANDSCAPE},{alias:"handset.portrait",mediaQuery:U_.HANDSET_PORTRAIT},{alias:"tablet",mediaQuery:U_.TABLET},{alias:"tablet.landscape",mediaQuery:U_.TABLET},{alias:"tablet.portrait",mediaQuery:U_.TABLET_PORTRAIT},{alias:"web",mediaQuery:U_.WEB,overlapping:!0},{alias:"web.landscape",mediaQuery:U_.WEB_LANDSCAPE,overlapping:!0},{alias:"web.portrait",mediaQuery:U_.WEB_PORTRAIT,overlapping:!0}];function F_(n){for(var t=[],e=1;e<arguments.length;e++)t[e-1]=arguments[e];if(null==n)throw TypeError("Cannot convert undefined or null to object");for(var l=0,r=t;l<r.length;l++){var o=r[l];if(null!=o)for(var i in o)o.hasOwnProperty(i)&&(n[i]=o[i])}return n}var B_=/(\.|-|_)/g;function H_(n){var t=n.length>0?n.charAt(0):"",e=n.length>1?n.slice(1):"";return t.toUpperCase()+e}var z_={addFlexToParent:!0,addOrientationBps:!1,disableDefaultBps:!1,disableVendorPrefixes:!1,serverLoaded:!1,useColumnBasisZero:!0},q_=new Sn("Flex Layout token, config options for the library",{providedIn:"root",factory:function(){return z_}}),G_=new Sn("Token (@angular/flex-layout) Breakpoints",{providedIn:"root",factory:function(){var n=$n(A_),t=$n(q_),e=[].concat.apply([],(n||[]).map(function(n){return Array.isArray(n)?n:[n]}));return function(n,t){void 0===t&&(t=[]);var e,l={};return n.forEach(function(n){l[n.alias]=n}),t.forEach(function(n){l[n.alias]?F_(l[n.alias],n):l[n.alias]=n}),(e=Object.keys(l).map(function(n){return l[n]})).forEach(function(n){n.suffix||(n.suffix=n.alias.replace(B_,"|").split("|").map(H_).join(""),n.overlapping=!!n.overlapping)}),e}((t.disableDefaultBps?[]:R_).concat(t.addOrientationBps?j_:[]),e)}}),W_=function(){function n(n){this._registry=n}return Object.defineProperty(n.prototype,"items",{get:function(){return this._registry.slice()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"sortedItems",{get:function(){var n=this._registry.filter(function(n){return!0===n.overlapping}),t=this._registry.filter(function(n){return!0!==n.overlapping});return n.concat(t)},enumerable:!0,configurable:!0}),n.prototype.findByAlias=function(n){return this._registry.find(function(t){return t.alias==n})||null},n.prototype.findByQuery=function(n){return this._registry.find(function(t){return t.mediaQuery==n})||null},Object.defineProperty(n.prototype,"overlappings",{get:function(){return this._registry.filter(function(n){return 1==n.overlapping})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"aliases",{get:function(){return this._registry.map(function(n){return n.alias})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"suffixes",{get:function(){return this._registry.map(function(n){return n.suffix?n.suffix:""})},enumerable:!0,configurable:!0}),n.ngInjectableDef=wn({factory:function(){return new n($n(G_))},token:n,providedIn:"root"}),n}(),Q_=function(){function n(n,t,e,l){void 0===n&&(n=!1),void 0===t&&(t="all"),void 0===e&&(e=""),void 0===l&&(l=""),this.matches=n,this.mediaQuery=t,this.mqAlias=e,this.suffix=l,this.property=""}return n.prototype.clone=function(){return new n(this.matches,this.mediaQuery,this.mqAlias,this.suffix)},n}(),$_=function(){function n(n,t,e){this._zone=n,this._platformId=t,this._document=e,this._registry=new Map,this._source=new Ra(new Q_(!0)),this._observable$=this._source.asObservable()}return n.prototype.isActive=function(n){var t=this._registry.get(n);return!!t&&t.matches},n.prototype.observe=function(n){return n&&this.registerQuery(n),this._observable$.pipe(gu(function(t){return!n||t.mediaQuery===n}))},n.prototype.registerQuery=function(n){var t=this,e=function(n){return void 0===n?[]:"string"==typeof n?[n]:(t={},n.filter(function(n){return!t.hasOwnProperty(n)&&(t[n]=!0)}));var t}(n);e.length>0&&(this._prepareQueryCSS(e,this._document),e.forEach(function(n){var e=t._registry.get(n),l=function(e){t._zone.run(function(){var l=new Q_(e.matches,n);t._source.next(l)})};e||((e=t._buildMQL(n)).addListener(l),t._registry.set(n,e)),e.matches&&l(e)}))},n.prototype._buildMQL=function(n){return qu(this._platformId)&&window.matchMedia("all").addListener?window.matchMedia(n):{matches:"all"===n||""===n,media:n,addListener:function(){},removeListener:function(){}}},n.prototype._prepareQueryCSS=function(n,t){var e=n.filter(function(n){return!K_[n]});if(e.length>0){var l=e.join(", ");try{var r=t.createElement("style");r.setAttribute("type","text/css"),r.styleSheet||r.appendChild(t.createTextNode("\n/*\n @angular/flex-layout - workaround for possible browser quirk with mediaQuery listeners\n see http://bit.ly/2sd4HMP\n*/\n@media "+l+" {.fx-query-test{ }}\n")),t.head.appendChild(r),e.forEach(function(n){return K_[n]=r})}catch(o){console.error(o)}}},n.ngInjectableDef=wn({factory:function(){return new n($n(Ze),$n(Re),$n(Bu))},token:n,providedIn:"root"}),n}(),K_={},Z_=function(){return function(){}}(),Y_=function(){function n(n,t){this.breakpoints=n,this.mediaWatcher=t,this.filterOverlaps=!0,this._registerBreakPoints(),this.observable$=this._buildObservable()}return n.prototype.isActive=function(n){var t=this._toMediaQuery(n);return this.mediaWatcher.isActive(t)},n.prototype.subscribe=function(n,t,e){return n&&"object"==typeof n?this.observable$.subscribe(n.next,n.error,n.complete):this.observable$.subscribe(n,t,e)},n.prototype.asObservable=function(){return this.observable$},n.prototype._registerBreakPoints=function(){var n=this.breakpoints.sortedItems.map(function(n){return n.mediaQuery});this.mediaWatcher.registerQuery(n)},n.prototype._buildObservable=function(){var n=this,t=this;return this.mediaWatcher.observe().pipe(gu(function(n){return!0===n.matches}),gu(function(e){var l=n.breakpoints.findByQuery(e.mediaQuery);return!l||!(t.filterOverlaps&&l.overlapping)}),nn(function(t){return F_(t,(e=n._findByQuery(t.mediaQuery))?{mqAlias:e.alias,suffix:e.suffix}:{});var e}))},n.prototype._findByAlias=function(n){return this.breakpoints.findByAlias(n)},n.prototype._findByQuery=function(n){return this.breakpoints.findByQuery(n)},n.prototype._toMediaQuery=function(n){var t=this._findByAlias(n)||this._findByQuery(n);return t?t.mediaQuery:n},n.ngInjectableDef=wn({factory:function(){return new n($n(W_),$n($_))},token:n,providedIn:"root"}),n}(),X_=function(){return function(){}}(),J_=new Sn("FlexLayoutServerLoaded",{providedIn:"root",factory:function(){return!1}});function nb(n){return Array.isArray(n)?n:[n]}function tb(n){return null==n?"":"string"==typeof n?n:n+"px"}var eb,lb=function(n){function t(t,e){var l=n.call(this,t,e)||this;return l.scheduler=t,l.work=e,l.pending=!1,l}return r(t,n),t.prototype.schedule=function(n,t){if(void 0===t&&(t=0),this.closed)return this;this.state=n;var e=this.id,l=this.scheduler;return null!=e&&(this.id=this.recycleAsyncId(l,e,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(l,this.id,t),this},t.prototype.requestAsyncId=function(n,t,e){return void 0===e&&(e=0),setInterval(n.flush.bind(n,this),e)},t.prototype.recycleAsyncId=function(n,t,e){if(void 0===e&&(e=0),null!==e&&this.delay===e&&!1===this.pending)return t;clearInterval(t)},t.prototype.execute=function(n,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var e=this._execute(n,t);if(e)return e;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(n,t){var e=!1,l=void 0;try{this.work(n)}catch(r){e=!0,l=!!r&&r||new Error(r)}if(e)return this.unsubscribe(),l},t.prototype._unsubscribe=function(){var n=this.id,t=this.scheduler,e=t.actions,l=e.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==l&&e.splice(l,1),null!=n&&(this.id=this.recycleAsyncId(t,n,null)),this.delay=null},t}(function(n){function t(t,e){return n.call(this)||this}return r(t,n),t.prototype.schedule=function(n,t){return void 0===t&&(t=0),this},t}(b)),rb=function(){function n(t,e){void 0===e&&(e=n.now),this.SchedulerAction=t,this.now=e}return n.prototype.schedule=function(n,t,e){return void 0===t&&(t=0),new this.SchedulerAction(this,n).schedule(e,t)},n.now=function(){return Date.now()},n}(),ob=new(function(n){function t(e,l){void 0===l&&(l=rb.now);var r=n.call(this,e,function(){return t.delegate&&t.delegate!==r?t.delegate.now():l()})||this;return r.actions=[],r.active=!1,r.scheduled=void 0,r}return r(t,n),t.prototype.schedule=function(e,l,r){return void 0===l&&(l=0),t.delegate&&t.delegate!==this?t.delegate.schedule(e,l,r):n.prototype.schedule.call(this,e,l,r)},t.prototype.flush=function(n){var t=this.actions;if(this.active)t.push(n);else{var e;this.active=!0;do{if(e=n.execute(n.state,n.delay))break}while(n=t.shift());if(this.active=!1,e){for(;n=t.shift();)n.unsubscribe();throw e}}},t}(rb))(lb),ib=function(){function n(){}return n.prototype.create=function(n){return"undefined"==typeof MutationObserver?null:new MutationObserver(n)},n.ngInjectableDef=wn({factory:function(){return new n},token:n,providedIn:"root"}),n}(),ub=function(){return function(){}}(),ab=function(){function n(){}return n.prototype.intercept=function(n,t){return sessionStorage.getItem("username")&&sessionStorage.getItem("basicauth")&&(n=n.clone({setHeaders:{Authorization:sessionStorage.getItem("basicauth")}})),t.handle(n)},n.ngInjectableDef=wn({factory:function(){return new n},token:n,providedIn:"root"}),n}();try{eb="undefined"!=typeof Intl&&Intl.v8BreakIterator}catch(Vw){eb=!1}var sb=function(){function n(n){this._platformId=n,this.isBrowser=this._platformId?qu(this._platformId):"object"==typeof document&&!!document,this.EDGE=this.isBrowser&&/(edge)/i.test(navigator.userAgent),this.TRIDENT=this.isBrowser&&/(msie|trident)/i.test(navigator.userAgent),this.BLINK=this.isBrowser&&!(!window.chrome&&!eb)&&"undefined"!=typeof CSS&&!this.EDGE&&!this.TRIDENT,this.WEBKIT=this.isBrowser&&/AppleWebKit/i.test(navigator.userAgent)&&!this.BLINK&&!this.EDGE&&!this.TRIDENT,this.IOS=this.isBrowser&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!("MSStream"in window),this.FIREFOX=this.isBrowser&&/(firefox|minefield)/i.test(navigator.userAgent),this.ANDROID=this.isBrowser&&/android/i.test(navigator.userAgent)&&!this.TRIDENT,this.SAFARI=this.isBrowser&&/safari/i.test(navigator.userAgent)&&this.WEBKIT}return n.ngInjectableDef=wn({factory:function(){return new n($n(Re,8))},token:n,providedIn:"root"}),n}(),cb=function(){return function(){}}(),pb=function(){return function(){}}(),hb=new Sn("mat-sanity-checks",{providedIn:"root",factory:function(){return!0}}),db=function(){function n(n,t){this._sanityChecksEnabled=n,this._hammerLoader=t,this._hasDoneGlobalChecks=!1,this._hasCheckedHammer=!1,this._document="object"==typeof document&&document?document:null,this._window="object"==typeof window&&window?window:null,this._areChecksEnabled()&&!this._hasDoneGlobalChecks&&(this._checkDoctypeIsDefined(),this._checkThemeIsPresent(),this._hasDoneGlobalChecks=!0)}return n.prototype._areChecksEnabled=function(){return this._sanityChecksEnabled&&qt()&&!this._isTestEnv()},n.prototype._isTestEnv=function(){var n=this._window;return n&&(n.__karma__||n.jasmine)},n.prototype._checkDoctypeIsDefined=function(){this._document&&!this._document.doctype&&console.warn("Current document does not have a doctype. This may cause some Angular Material components not to behave as expected.")},n.prototype._checkThemeIsPresent=function(){if(this._document&&this._document.body&&"function"==typeof getComputedStyle){var n=this._document.createElement("div");n.classList.add("mat-theme-loaded-marker"),this._document.body.appendChild(n);var t=getComputedStyle(n);t&&"none"!==t.display&&console.warn("Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming"),this._document.body.removeChild(n)}},n.prototype._checkHammerIsAvailable=function(){!this._hasCheckedHammer&&this._window&&(!this._areChecksEnabled()||this._window.Hammer||this._hammerLoader||console.warn("Could not find HammerJS. Certain Angular Material components may not work correctly."),this._hasCheckedHammer=!0)},n}(),fb=function(){function n(){}return n.prototype.isErrorState=function(n,t){return!!(n&&n.invalid&&(n.touched||t&&t.submitted))},n.ngInjectableDef=wn({factory:function(){return new n},token:n,providedIn:"root"}),n}(),gb=function(){return function(){}}(),mb=function(){return function(){}}(),yb=function(){return function(){}}();function vb(n,t,e,l){return d(e)&&(l=e,e=void 0),l?vb(n,t,e).pipe(nn(function(n){return p(n)?l.apply(void 0,n):l(n)})):new R(function(l){!function n(t,e,l,r,o){var i;if(function(n){return n&&"function"==typeof n.addEventListener&&"function"==typeof n.removeEventListener}(t)){var u=t;t.addEventListener(e,l,o),i=function(){return u.removeEventListener(e,l,o)}}else if(function(n){return n&&"function"==typeof n.on&&"function"==typeof n.off}(t)){var a=t;t.on(e,l),i=function(){return a.off(e,l)}}else if(function(n){return n&&"function"==typeof n.addListener&&"function"==typeof n.removeListener}(t)){var s=t;t.addListener(e,l),i=function(){return s.removeListener(e,l)}}else{if(!t||!t.length)throw new TypeError("Invalid event target");for(var c=0,p=t.length;c<p;c++)n(t[c],e,l,r,o)}r.add(i)}(n,t,function(n){l.next(arguments.length>1?Array.prototype.slice.call(arguments):n)},l,e)})}var _b=function(){function n(n){this.durationSelector=n}return n.prototype.call=function(n,t){return t.subscribe(new bb(n,this.durationSelector))},n}(),bb=function(n){function t(t,e){var l=n.call(this,t)||this;return l.durationSelector=e,l.hasValue=!1,l}return r(t,n),t.prototype._next=function(n){if(this.value=n,this.hasValue=!0,!this.throttled){var t=y(this.durationSelector)(n);if(t===g)this.destination.error(g.e);else{var e=X(this,t);!e||e.closed?this.clearThrottle():this.add(this.throttled=e)}}},t.prototype.clearThrottle=function(){var n=this.value,t=this.hasValue,e=this.throttled;e&&(this.remove(e),this.throttled=null,e.unsubscribe()),t&&(this.value=null,this.hasValue=!1,this.destination.next(n))},t.prototype.notifyNext=function(n,t,e,l){this.clearThrottle()},t.prototype.notifyComplete=function(){this.clearThrottle()},t}(J);function wb(n){return!p(n)&&n-parseFloat(n)+1>=0}function Cb(n){var t=n.index,e=n.period,l=n.subscriber;if(l.next(t),!l.closed){if(-1===e)return l.complete();n.index=t+1,this.schedule(n,e)}}function Sb(n,t){return void 0===t&&(t=ob),e=function(){return function(n,t,e){void 0===n&&(n=0);var l=-1;return wb(t)?l=Number(t)<1?1:Number(t):B(t)&&(e=t),B(e)||(e=ob),new R(function(t){var r=wb(n)?n:+n-e.now();return e.schedule(Cb,r,{index:0,period:l,subscriber:t})})}(n,t)},function(n){return n.lift(new _b(e))};var e}var Eb=function(){function n(n){this.notifier=n}return n.prototype.call=function(n,t){var e=new xb(n),l=X(e,this.notifier);return l&&!e.seenValue?(e.add(l),t.subscribe(e)):e},n}(),xb=function(n){function t(t){var e=n.call(this,t)||this;return e.seenValue=!1,e}return r(t,n),t.prototype.notifyNext=function(n,t,e,l,r){this.seenValue=!0,this.complete()},t.prototype.notifyComplete=function(){},t}(J),Pb=function(){function n(n,t){this._ngZone=n,this._platform=t,this._scrolled=new j,this._globalSubscription=null,this._scrolledCount=0,this.scrollContainers=new Map}return n.prototype.register=function(n){var t=this;this.scrollContainers.has(n)||this.scrollContainers.set(n,n.elementScrolled().subscribe(function(){return t._scrolled.next(n)}))},n.prototype.deregister=function(n){var t=this.scrollContainers.get(n);t&&(t.unsubscribe(),this.scrollContainers.delete(n))},n.prototype.scrolled=function(n){var t=this;return void 0===n&&(n=20),this._platform.isBrowser?new R(function(e){t._globalSubscription||t._addGlobalListener();var l=n>0?t._scrolled.pipe(Sb(n)).subscribe(e):t._scrolled.subscribe(e);return t._scrolledCount++,function(){l.unsubscribe(),t._scrolledCount--,t._scrolledCount||t._removeGlobalListener()}}):du()},n.prototype.ngOnDestroy=function(){var n=this;this._removeGlobalListener(),this.scrollContainers.forEach(function(t,e){return n.deregister(e)}),this._scrolled.complete()},n.prototype.ancestorScrolled=function(n,t){var e=this.getAncestorScrollContainers(n);return this.scrolled(t).pipe(gu(function(n){return!n||e.indexOf(n)>-1}))},n.prototype.getAncestorScrollContainers=function(n){var t=this,e=[];return this.scrollContainers.forEach(function(l,r){t._scrollableContainsElement(r,n)&&e.push(r)}),e},n.prototype._scrollableContainsElement=function(n,t){var e=t.nativeElement,l=n.getElementRef().nativeElement;do{if(e==l)return!0}while(e=e.parentElement);return!1},n.prototype._addGlobalListener=function(){var n=this;this._globalSubscription=this._ngZone.runOutsideAngular(function(){return vb(window.document,"scroll").subscribe(function(){return n._scrolled.next()})})},n.prototype._removeGlobalListener=function(){this._globalSubscription&&(this._globalSubscription.unsubscribe(),this._globalSubscription=null)},n.ngInjectableDef=wn({factory:function(){return new n($n(Ze),$n(sb))},token:n,providedIn:"root"}),n}(),Tb=function(){return function(){}}(),Ib=function(){function n(n,t){var e=this;this._platform=n,t.runOutsideAngular(function(){e._change=n.isBrowser?pn(vb(window,"resize"),vb(window,"orientationchange")):du(),e._invalidateCache=e.change().subscribe(function(){return e._updateViewportSize()})})}return n.prototype.ngOnDestroy=function(){this._invalidateCache.unsubscribe()},n.prototype.getViewportSize=function(){this._viewportSize||this._updateViewportSize();var n={width:this._viewportSize.width,height:this._viewportSize.height};return this._platform.isBrowser||(this._viewportSize=null),n},n.prototype.getViewportRect=function(){var n=this.getViewportScrollPosition(),t=this.getViewportSize(),e=t.width,l=t.height;return{top:n.top,left:n.left,bottom:n.top+l,right:n.left+e,height:l,width:e}},n.prototype.getViewportScrollPosition=function(){if(!this._platform.isBrowser)return{top:0,left:0};var n=document.documentElement,t=n.getBoundingClientRect();return{top:-t.top||document.body.scrollTop||window.scrollY||n.scrollTop||0,left:-t.left||document.body.scrollLeft||window.scrollX||n.scrollLeft||0}},n.prototype.change=function(n){return void 0===n&&(n=20),n>0?this._change.pipe(Sb(n)):this._change},n.prototype._updateViewportSize=function(){this._viewportSize=this._platform.isBrowser?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0}},n.ngInjectableDef=wn({factory:function(){return new n($n(sb),$n(Ze))},token:n,providedIn:"root"}),n}();function Ob(){throw Error("Host already has a portal attached")}var kb=function(){function n(){}return n.prototype.attach=function(n){return null==n&&function(){throw Error("Attempting to attach a portal to a null PortalOutlet")}(),n.hasAttached()&&Ob(),this._attachedHost=n,n.attach(this)},n.prototype.detach=function(){var n=this._attachedHost;null==n?function(){throw Error("Attempting to detach a portal that is not attached to a host")}():(this._attachedHost=null,n.detach())},Object.defineProperty(n.prototype,"isAttached",{get:function(){return null!=this._attachedHost},enumerable:!0,configurable:!0}),n.prototype.setAttachedHost=function(n){this._attachedHost=n},n}(),Db=function(n){function t(t,e,l,r){var o=n.call(this)||this;return o.component=t,o.viewContainerRef=e,o.injector=l,o.componentFactoryResolver=r,o}return r(t,n),t}(kb),Ab=function(n){function t(t,e,l){var r=n.call(this)||this;return r.templateRef=t,r.viewContainerRef=e,r.context=l,r}return r(t,n),Object.defineProperty(t.prototype,"origin",{get:function(){return this.templateRef.elementRef},enumerable:!0,configurable:!0}),t.prototype.attach=function(t,e){return void 0===e&&(e=this.context),this.context=e,n.prototype.attach.call(this,t)},t.prototype.detach=function(){return this.context=void 0,n.prototype.detach.call(this)},t}(kb),Rb=function(n){function t(t,e,l,r){var o=n.call(this)||this;return o.outletElement=t,o._componentFactoryResolver=e,o._appRef=l,o._defaultInjector=r,o}return r(t,n),t.prototype.attachComponentPortal=function(n){var t,e=this,l=(n.componentFactoryResolver||this._componentFactoryResolver).resolveComponentFactory(n.component);return n.viewContainerRef?(t=n.viewContainerRef.createComponent(l,n.viewContainerRef.length,n.injector||n.viewContainerRef.injector),this.setDisposeFn(function(){return t.destroy()})):(t=l.create(n.injector||this._defaultInjector),this._appRef.attachView(t.hostView),this.setDisposeFn(function(){e._appRef.detachView(t.hostView),t.destroy()})),this.outletElement.appendChild(this._getComponentRootNode(t)),t},t.prototype.attachTemplatePortal=function(n){var t=this,e=n.viewContainerRef,l=e.createEmbeddedView(n.templateRef,n.context);return l.detectChanges(),l.rootNodes.forEach(function(n){return t.outletElement.appendChild(n)}),this.setDisposeFn(function(){var n=e.indexOf(l);-1!==n&&e.remove(n)}),l},t.prototype.dispose=function(){n.prototype.dispose.call(this),null!=this.outletElement.parentNode&&this.outletElement.parentNode.removeChild(this.outletElement)},t.prototype._getComponentRootNode=function(n){return n.hostView.rootNodes[0]},t}(function(){function n(){this._isDisposed=!1}return n.prototype.hasAttached=function(){return!!this._attachedPortal},n.prototype.attach=function(n){return n||function(){throw Error("Must provide a portal to attach")}(),this.hasAttached()&&Ob(),this._isDisposed&&function(){throw Error("This PortalOutlet has already been disposed")}(),n instanceof Db?(this._attachedPortal=n,this.attachComponentPortal(n)):n instanceof Ab?(this._attachedPortal=n,this.attachTemplatePortal(n)):void function(){throw Error("Attempting to attach an unknown Portal type. BasePortalOutlet accepts either a ComponentPortal or a TemplatePortal.")}()},n.prototype.detach=function(){this._attachedPortal&&(this._attachedPortal.setAttachedHost(null),this._attachedPortal=null),this._invokeDisposeFn()},n.prototype.dispose=function(){this.hasAttached()&&this.detach(),this._invokeDisposeFn(),this._isDisposed=!0},n.prototype.setDisposeFn=function(n){this._disposeFn=n},n.prototype._invokeDisposeFn=function(){this._disposeFn&&(this._disposeFn(),this._disposeFn=null)},n}()),Mb=function(){return function(){}}(),Nb=function(){function n(n,t){this._viewportRuler=n,this._previousHTMLStyles={top:"",left:""},this._isEnabled=!1,this._document=t}return n.prototype.attach=function(){},n.prototype.enable=function(){if(this._canBeEnabled()){var n=this._document.documentElement;this._previousScrollPosition=this._viewportRuler.getViewportScrollPosition(),this._previousHTMLStyles.left=n.style.left||"",this._previousHTMLStyles.top=n.style.top||"",n.style.left=tb(-this._previousScrollPosition.left),n.style.top=tb(-this._previousScrollPosition.top),n.classList.add("cdk-global-scrollblock"),this._isEnabled=!0}},n.prototype.disable=function(){if(this._isEnabled){var n=this._document.documentElement,t=n.style,e=this._document.body.style,l=t.scrollBehavior||"",r=e.scrollBehavior||"";this._isEnabled=!1,t.left=this._previousHTMLStyles.left,t.top=this._previousHTMLStyles.top,n.classList.remove("cdk-global-scrollblock"),t.scrollBehavior=e.scrollBehavior="auto",window.scroll(this._previousScrollPosition.left,this._previousScrollPosition.top),t.scrollBehavior=l,e.scrollBehavior=r}},n.prototype._canBeEnabled=function(){if(this._document.documentElement.classList.contains("cdk-global-scrollblock")||this._isEnabled)return!1;var n=this._document.body,t=this._viewportRuler.getViewportSize();return n.scrollHeight>t.height||n.scrollWidth>t.width},n}();function Lb(){return Error("Scroll strategy has already been attached.")}var Vb=function(){function n(n,t,e,l){var r=this;this._scrollDispatcher=n,this._ngZone=t,this._viewportRuler=e,this._config=l,this._scrollSubscription=null,this._detach=function(){r.disable(),r._overlayRef.hasAttached()&&r._ngZone.run(function(){return r._overlayRef.detach()})}}return n.prototype.attach=function(n){if(this._overlayRef)throw Lb();this._overlayRef=n},n.prototype.enable=function(){var n=this;if(!this._scrollSubscription){var t=this._scrollDispatcher.scrolled(0);this._config&&this._config.threshold&&this._config.threshold>1?(this._initialScrollPosition=this._viewportRuler.getViewportScrollPosition().top,this._scrollSubscription=t.subscribe(function(){var t=n._viewportRuler.getViewportScrollPosition().top;Math.abs(t-n._initialScrollPosition)>n._config.threshold?n._detach():n._overlayRef.updatePosition()})):this._scrollSubscription=t.subscribe(this._detach)}},n.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},n}(),Ub=function(){function n(){}return n.prototype.enable=function(){},n.prototype.disable=function(){},n.prototype.attach=function(){},n}();function jb(n,t){return t.some(function(t){return n.bottom<t.top||n.top>t.bottom||n.right<t.left||n.left>t.right})}function Fb(n,t){return t.some(function(t){return n.top<t.top||n.bottom>t.bottom||n.left<t.left||n.right>t.right})}var Bb=function(){function n(n,t,e,l){this._scrollDispatcher=n,this._viewportRuler=t,this._ngZone=e,this._config=l,this._scrollSubscription=null}return n.prototype.attach=function(n){if(this._overlayRef)throw Lb();this._overlayRef=n},n.prototype.enable=function(){var n=this;this._scrollSubscription||(this._scrollSubscription=this._scrollDispatcher.scrolled(this._config?this._config.scrollThrottle:0).subscribe(function(){if(n._overlayRef.updatePosition(),n._config&&n._config.autoClose){var t=n._overlayRef.overlayElement.getBoundingClientRect(),e=n._viewportRuler.getViewportSize(),l=e.width,r=e.height;jb(t,[{width:l,height:r,bottom:r,right:l,top:0,left:0}])&&(n.disable(),n._ngZone.run(function(){return n._overlayRef.detach()}))}}))},n.prototype.disable=function(){this._scrollSubscription&&(this._scrollSubscription.unsubscribe(),this._scrollSubscription=null)},n}(),Hb=function(){function n(n,t,e,l){var r=this;this._scrollDispatcher=n,this._viewportRuler=t,this._ngZone=e,this.noop=function(){return new Ub},this.close=function(n){return new Vb(r._scrollDispatcher,r._ngZone,r._viewportRuler,n)},this.block=function(){return new Nb(r._viewportRuler,r._document)},this.reposition=function(n){return new Bb(r._scrollDispatcher,r._viewportRuler,r._ngZone,n)},this._document=l}return n.ngInjectableDef=wn({factory:function(){return new n($n(Pb),$n(Ib),$n(Ze),$n(Bu))},token:n,providedIn:"root"}),n}(),zb=function(){return function(n){var t=this;this.scrollStrategy=new Ub,this.panelClass="",this.hasBackdrop=!1,this.backdropClass="cdk-overlay-dark-backdrop",this.disposeOnNavigation=!1,n&&Object.keys(n).forEach(function(e){void 0!==n[e]&&(t[e]=n[e])})}}(),qb=function(){return function(n,t,e,l,r){this.offsetX=e,this.offsetY=l,this.panelClass=r,this.originX=n.originX,this.originY=n.originY,this.overlayX=t.overlayX,this.overlayY=t.overlayY}}(),Gb=function(){return function(n,t){this.connectionPair=n,this.scrollableViewProperties=t}}();function Wb(n,t){if("top"!==t&&"bottom"!==t&&"center"!==t)throw Error("ConnectedPosition: Invalid "+n+' "'+t+'". Expected "top", "bottom" or "center".')}function Qb(n,t){if("start"!==t&&"end"!==t&&"center"!==t)throw Error("ConnectedPosition: Invalid "+n+' "'+t+'". Expected "start", "end" or "center".')}var $b=function(){function n(n){var t=this;this._attachedOverlays=[],this._keydownListener=function(n){for(var e=t._attachedOverlays,l=e.length-1;l>-1;l--)if(e[l]._keydownEventSubscriptions>0){e[l]._keydownEvents.next(n);break}},this._document=n}return n.prototype.ngOnDestroy=function(){this._detach()},n.prototype.add=function(n){this.remove(n),this._isAttached||(this._document.body.addEventListener("keydown",this._keydownListener,!0),this._isAttached=!0),this._attachedOverlays.push(n)},n.prototype.remove=function(n){var t=this._attachedOverlays.indexOf(n);t>-1&&this._attachedOverlays.splice(t,1),0===this._attachedOverlays.length&&this._detach()},n.prototype._detach=function(){this._isAttached&&(this._document.body.removeEventListener("keydown",this._keydownListener,!0),this._isAttached=!1)},n.ngInjectableDef=wn({factory:function(){return new n($n(Bu))},token:n,providedIn:"root"}),n}(),Kb=function(){function n(n){this._document=n}return n.prototype.ngOnDestroy=function(){this._containerElement&&this._containerElement.parentNode&&this._containerElement.parentNode.removeChild(this._containerElement)},n.prototype.getContainerElement=function(){return this._containerElement||this._createContainer(),this._containerElement},n.prototype._createContainer=function(){var n=this._document.createElement("div");n.classList.add("cdk-overlay-container"),this._document.body.appendChild(n),this._containerElement=n},n.ngInjectableDef=wn({factory:function(){return new n($n(Bu))},token:n,providedIn:"root"}),n}(),Zb=function(){function n(n,t,e,l,r,o,i,u){var a=this;this._portalOutlet=n,this._host=t,this._pane=e,this._config=l,this._ngZone=r,this._keyboardDispatcher=o,this._document=i,this._location=u,this._backdropElement=null,this._backdropClick=new j,this._attachments=new j,this._detachments=new j,this._locationChanges=b.EMPTY,this._keydownEventsObservable=new R(function(n){var t=a._keydownEvents.subscribe(n);return a._keydownEventSubscriptions++,function(){t.unsubscribe(),a._keydownEventSubscriptions--}}),this._keydownEvents=new j,this._keydownEventSubscriptions=0,l.scrollStrategy&&l.scrollStrategy.attach(this),this._positionStrategy=l.positionStrategy}return Object.defineProperty(n.prototype,"overlayElement",{get:function(){return this._pane},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"backdropElement",{get:function(){return this._backdropElement},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"hostElement",{get:function(){return this._host},enumerable:!0,configurable:!0}),n.prototype.attach=function(n){var t=this,e=this._portalOutlet.attach(n);return this._positionStrategy&&this._positionStrategy.attach(this),!this._host.parentElement&&this._previousHostParent&&this._previousHostParent.appendChild(this._host),this._updateStackingOrder(),this._updateElementSize(),this._updateElementDirection(),this._config.scrollStrategy&&this._config.scrollStrategy.enable(),this._ngZone.onStable.asObservable().pipe(rs(1)).subscribe(function(){t.hasAttached()&&t.updatePosition()}),this._togglePointerEvents(!0),this._config.hasBackdrop&&this._attachBackdrop(),this._config.panelClass&&this._toggleClasses(this._pane,this._config.panelClass,!0),this._attachments.next(),this._keyboardDispatcher.add(this),this._config.disposeOnNavigation&&this._location&&(this._locationChanges=this._location.subscribe(function(){return t.dispose()})),e},n.prototype.detach=function(){if(this.hasAttached()){this.detachBackdrop(),this._togglePointerEvents(!1),this._positionStrategy&&this._positionStrategy.detach&&this._positionStrategy.detach(),this._config.scrollStrategy&&this._config.scrollStrategy.disable();var n=this._portalOutlet.detach();return this._detachments.next(),this._keyboardDispatcher.remove(this),this._detachContentWhenStable(),this._locationChanges.unsubscribe(),n}},n.prototype.dispose=function(){var n=this.hasAttached();this._positionStrategy&&this._positionStrategy.dispose(),this._config.scrollStrategy&&this._config.scrollStrategy.disable(),this.detachBackdrop(),this._locationChanges.unsubscribe(),this._keyboardDispatcher.remove(this),this._portalOutlet.dispose(),this._attachments.complete(),this._backdropClick.complete(),this._keydownEvents.complete(),this._host&&this._host.parentNode&&(this._host.parentNode.removeChild(this._host),this._host=null),this._previousHostParent=this._pane=null,n&&this._detachments.next(),this._detachments.complete()},n.prototype.hasAttached=function(){return this._portalOutlet.hasAttached()},n.prototype.backdropClick=function(){return this._backdropClick.asObservable()},n.prototype.attachments=function(){return this._attachments.asObservable()},n.prototype.detachments=function(){return this._detachments.asObservable()},n.prototype.keydownEvents=function(){return this._keydownEventsObservable},n.prototype.getConfig=function(){return this._config},n.prototype.updatePosition=function(){this._positionStrategy&&this._positionStrategy.apply()},n.prototype.updatePositionStrategy=function(n){n!==this._positionStrategy&&(this._positionStrategy&&this._positionStrategy.dispose(),this._positionStrategy=n,this.hasAttached()&&(n.attach(this),this.updatePosition()))},n.prototype.updateSize=function(n){this._config=o({},this._config,n),this._updateElementSize()},n.prototype.setDirection=function(n){this._config=o({},this._config,{direction:n}),this._updateElementDirection()},n.prototype.addPanelClass=function(n){this._pane&&this._toggleClasses(this._pane,n,!0)},n.prototype.removePanelClass=function(n){this._pane&&this._toggleClasses(this._pane,n,!1)},n.prototype.getDirection=function(){var n=this._config.direction;return n?"string"==typeof n?n:n.value:"ltr"},n.prototype._updateElementDirection=function(){this._host.setAttribute("dir",this.getDirection())},n.prototype._updateElementSize=function(){var n=this._pane.style;n.width=tb(this._config.width),n.height=tb(this._config.height),n.minWidth=tb(this._config.minWidth),n.minHeight=tb(this._config.minHeight),n.maxWidth=tb(this._config.maxWidth),n.maxHeight=tb(this._config.maxHeight)},n.prototype._togglePointerEvents=function(n){this._pane.style.pointerEvents=n?"auto":"none"},n.prototype._attachBackdrop=function(){var n=this;this._backdropElement=this._document.createElement("div"),this._backdropElement.classList.add("cdk-overlay-backdrop"),this._config.backdropClass&&this._toggleClasses(this._backdropElement,this._config.backdropClass,!0),this._host.parentElement.insertBefore(this._backdropElement,this._host),this._backdropElement.addEventListener("click",function(t){return n._backdropClick.next(t)}),"undefined"!=typeof requestAnimationFrame?this._ngZone.runOutsideAngular(function(){requestAnimationFrame(function(){n._backdropElement&&n._backdropElement.classList.add("cdk-overlay-backdrop-showing")})}):this._backdropElement.classList.add("cdk-overlay-backdrop-showing")},n.prototype._updateStackingOrder=function(){this._host.nextSibling&&this._host.parentNode.appendChild(this._host)},n.prototype.detachBackdrop=function(){var n=this,t=this._backdropElement;if(t){var e,l=function(){t&&t.parentNode&&t.parentNode.removeChild(t),n._backdropElement==t&&(n._backdropElement=null),n._config.backdropClass&&n._toggleClasses(t,n._config.backdropClass,!1),clearTimeout(e)};t.classList.remove("cdk-overlay-backdrop-showing"),this._ngZone.runOutsideAngular(function(){t.addEventListener("transitionend",l)}),t.style.pointerEvents="none",e=this._ngZone.runOutsideAngular(function(){return setTimeout(l,500)})}},n.prototype._toggleClasses=function(n,t,e){var l=n.classList;nb(t).forEach(function(n){e?l.add(n):l.remove(n)})},n.prototype._detachContentWhenStable=function(){var n=this;this._ngZone.runOutsideAngular(function(){var t,e=n._ngZone.onStable.asObservable().pipe((t=pn(n._attachments,n._detachments),function(n){return n.lift(new Eb(t))})).subscribe(function(){n._pane&&n._host&&0!==n._pane.children.length||(n._pane&&n._config.panelClass&&n._toggleClasses(n._pane,n._config.panelClass,!1),n._host&&n._host.parentElement&&(n._previousHostParent=n._host.parentElement,n._previousHostParent.removeChild(n._host)),e.unsubscribe())})})},n}(),Yb=function(){function n(n,t,e,l,r){var o=this;this._viewportRuler=t,this._document=e,this._platform=l,this._overlayContainer=r,this._lastBoundingBoxSize={width:0,height:0},this._isPushed=!1,this._canPush=!0,this._growAfterOpen=!1,this._hasFlexibleDimensions=!0,this._positionLocked=!1,this._viewportMargin=0,this.scrollables=[],this._preferredPositions=[],this._positionChanges=new j,this._resizeSubscription=b.EMPTY,this._offsetX=0,this._offsetY=0,this._positionChangeSubscriptions=0,this._appliedPanelClasses=[],this.positionChanges=new R(function(n){var t=o._positionChanges.subscribe(n);return o._positionChangeSubscriptions++,function(){t.unsubscribe(),o._positionChangeSubscriptions--}}),this.setOrigin(n)}return Object.defineProperty(n.prototype,"positions",{get:function(){return this._preferredPositions},enumerable:!0,configurable:!0}),n.prototype.attach=function(n){var t=this;if(this._overlayRef&&n!==this._overlayRef)throw Error("This position strategy is already attached to an overlay");this._validatePositions(),n.hostElement.classList.add("cdk-overlay-connected-position-bounding-box"),this._overlayRef=n,this._boundingBox=n.hostElement,this._pane=n.overlayElement,this._isDisposed=!1,this._isInitialRender=!0,this._lastPosition=null,this._resizeSubscription.unsubscribe(),this._resizeSubscription=this._viewportRuler.change().subscribe(function(){t._isInitialRender=!0,t.apply()})},n.prototype.apply=function(){if(!(this._isDisposed||this._platform&&!this._platform.isBrowser))if(!this._isInitialRender&&this._positionLocked&&this._lastPosition)this.reapplyLastPosition();else{this._clearPanelClasses(),this._resetOverlayElementStyles(),this._resetBoundingBoxStyles(),this._viewportRect=this._getNarrowedViewportRect(),this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect();for(var n,t=this._originRect,e=this._overlayRect,l=this._viewportRect,r=[],o=0,i=this._preferredPositions;o<i.length;o++){var u=i[o],a=this._getOriginPoint(t,u),s=this._getOverlayPoint(a,e,u),c=this._getOverlayFit(s,e,l,u);if(c.isCompletelyWithinViewport)return this._isPushed=!1,void this._applyPosition(u,a);this._canFitWithFlexibleDimensions(c,s,l)?r.push({position:u,origin:a,overlayRect:e,boundingBoxRect:this._calculateBoundingBoxRect(a,u)}):(!n||n.overlayFit.visibleArea<c.visibleArea)&&(n={overlayFit:c,overlayPoint:s,originPoint:a,position:u,overlayRect:e})}if(r.length){for(var p=null,h=-1,d=0,f=r;d<f.length;d++){var g=f[d],m=g.boundingBoxRect.width*g.boundingBoxRect.height*(g.position.weight||1);m>h&&(h=m,p=g)}return this._isPushed=!1,void this._applyPosition(p.position,p.origin)}if(this._canPush)return this._isPushed=!0,void this._applyPosition(n.position,n.originPoint);this._applyPosition(n.position,n.originPoint)}},n.prototype.detach=function(){this._clearPanelClasses(),this._lastPosition=null,this._previousPushAmount=null,this._resizeSubscription.unsubscribe()},n.prototype.dispose=function(){this._isDisposed||(this._boundingBox&&Xb(this._boundingBox.style,{top:"",left:"",right:"",bottom:"",height:"",width:"",alignItems:"",justifyContent:""}),this._pane&&this._resetOverlayElementStyles(),this._overlayRef&&this._overlayRef.hostElement.classList.remove("cdk-overlay-connected-position-bounding-box"),this.detach(),this._positionChanges.complete(),this._overlayRef=this._boundingBox=null,this._isDisposed=!0)},n.prototype.reapplyLastPosition=function(){if(!this._isDisposed&&(!this._platform||this._platform.isBrowser)){this._originRect=this._getOriginRect(),this._overlayRect=this._pane.getBoundingClientRect(),this._viewportRect=this._getNarrowedViewportRect();var n=this._lastPosition||this._preferredPositions[0],t=this._getOriginPoint(this._originRect,n);this._applyPosition(n,t)}},n.prototype.withScrollableContainers=function(n){return this.scrollables=n,this},n.prototype.withPositions=function(n){return this._preferredPositions=n,-1===n.indexOf(this._lastPosition)&&(this._lastPosition=null),this._validatePositions(),this},n.prototype.withViewportMargin=function(n){return this._viewportMargin=n,this},n.prototype.withFlexibleDimensions=function(n){return void 0===n&&(n=!0),this._hasFlexibleDimensions=n,this},n.prototype.withGrowAfterOpen=function(n){return void 0===n&&(n=!0),this._growAfterOpen=n,this},n.prototype.withPush=function(n){return void 0===n&&(n=!0),this._canPush=n,this},n.prototype.withLockedPosition=function(n){return void 0===n&&(n=!0),this._positionLocked=n,this},n.prototype.setOrigin=function(n){return this._origin=n,this},n.prototype.withDefaultOffsetX=function(n){return this._offsetX=n,this},n.prototype.withDefaultOffsetY=function(n){return this._offsetY=n,this},n.prototype.withTransformOriginOn=function(n){return this._transformOriginSelector=n,this},n.prototype._getOriginPoint=function(n,t){var e;if("center"==t.originX)e=n.left+n.width/2;else{var l=this._isRtl()?n.right:n.left,r=this._isRtl()?n.left:n.right;e="start"==t.originX?l:r}return{x:e,y:"center"==t.originY?n.top+n.height/2:"top"==t.originY?n.top:n.bottom}},n.prototype._getOverlayPoint=function(n,t,e){var l;return l="center"==e.overlayX?-t.width/2:"start"===e.overlayX?this._isRtl()?-t.width:0:this._isRtl()?0:-t.width,{x:n.x+l,y:n.y+("center"==e.overlayY?-t.height/2:"top"==e.overlayY?0:-t.height)}},n.prototype._getOverlayFit=function(n,t,e,l){var r=n.x,o=n.y,i=this._getOffset(l,"x"),u=this._getOffset(l,"y");i&&(r+=i),u&&(o+=u);var a=0-o,s=o+t.height-e.height,c=this._subtractOverflows(t.width,0-r,r+t.width-e.width),p=this._subtractOverflows(t.height,a,s),h=c*p;return{visibleArea:h,isCompletelyWithinViewport:t.width*t.height===h,fitsInViewportVertically:p===t.height,fitsInViewportHorizontally:c==t.width}},n.prototype._canFitWithFlexibleDimensions=function(n,t,e){if(this._hasFlexibleDimensions){var l=e.bottom-t.y,r=e.right-t.x,o=this._overlayRef.getConfig().minHeight,i=this._overlayRef.getConfig().minWidth;return(n.fitsInViewportVertically||null!=o&&o<=l)&&(n.fitsInViewportHorizontally||null!=i&&i<=r)}},n.prototype._pushOverlayOnScreen=function(n,t,e){if(this._previousPushAmount&&this._positionLocked)return{x:n.x+this._previousPushAmount.x,y:n.y+this._previousPushAmount.y};var l,r,o=this._viewportRect,i=Math.max(n.x+t.width-o.right,0),u=Math.max(n.y+t.height-o.bottom,0),a=Math.max(o.top-e.top-n.y,0),s=Math.max(o.left-e.left-n.x,0);return this._previousPushAmount={x:l=t.width<=o.width?s||-i:n.x<this._viewportMargin?o.left-e.left-n.x:0,y:r=t.height<=o.height?a||-u:n.y<this._viewportMargin?o.top-e.top-n.y:0},{x:n.x+l,y:n.y+r}},n.prototype._applyPosition=function(n,t){if(this._setTransformOrigin(n),this._setOverlayElementStyles(t,n),this._setBoundingBoxStyles(t,n),n.panelClass&&this._addPanelClasses(n.panelClass),this._lastPosition=n,this._positionChangeSubscriptions>0){var e=this._getScrollVisibility(),l=new Gb(n,e);this._positionChanges.next(l)}this._isInitialRender=!1},n.prototype._setTransformOrigin=function(n){if(this._transformOriginSelector){var t,e=this._boundingBox.querySelectorAll(this._transformOriginSelector),l=n.overlayY;t="center"===n.overlayX?"center":this._isRtl()?"start"===n.overlayX?"right":"left":"start"===n.overlayX?"left":"right";for(var r=0;r<e.length;r++)e[r].style.transformOrigin=t+" "+l}},n.prototype._calculateBoundingBoxRect=function(n,t){var e,l,r,o,i,u,a=this._viewportRect,s=this._isRtl();if("top"===t.overlayY)e=a.height-(l=n.y)+this._viewportMargin;else if("bottom"===t.overlayY)e=a.height-(r=a.height-n.y+2*this._viewportMargin)+this._viewportMargin;else{var c=Math.min(a.bottom-n.y+a.top,n.y),p=this._lastBoundingBoxSize.height;l=n.y-c,(e=2*c)>p&&!this._isInitialRender&&!this._growAfterOpen&&(l=n.y-p/2)}if("end"===t.overlayX&&!s||"start"===t.overlayX&&s)u=a.right-n.x+this._viewportMargin,o=n.x-a.left;else if("start"===t.overlayX&&!s||"end"===t.overlayX&&s)i=n.x,o=a.right-n.x;else{c=Math.min(a.right-n.x+a.left,n.x);var h=this._lastBoundingBoxSize.width;i=n.x-c,(o=2*c)>h&&!this._isInitialRender&&!this._growAfterOpen&&(i=n.x-h/2)}return{top:l,left:i,bottom:r,right:u,width:o,height:e}},n.prototype._setBoundingBoxStyles=function(n,t){var e=this._calculateBoundingBoxRect(n,t);this._isInitialRender||this._growAfterOpen||(e.height=Math.min(e.height,this._lastBoundingBoxSize.height),e.width=Math.min(e.width,this._lastBoundingBoxSize.width));var l={};if(this._hasExactPosition())l.top=l.left="0",l.bottom=l.right="",l.width=l.height="100%";else{var r=this._overlayRef.getConfig().maxHeight,o=this._overlayRef.getConfig().maxWidth;l.height=tb(e.height),l.top=tb(e.top),l.bottom=tb(e.bottom),l.width=tb(e.width),l.left=tb(e.left),l.right=tb(e.right),l.alignItems="center"===t.overlayX?"center":"end"===t.overlayX?"flex-end":"flex-start",l.justifyContent="center"===t.overlayY?"center":"bottom"===t.overlayY?"flex-end":"flex-start",r&&(l.maxHeight=tb(r)),o&&(l.maxWidth=tb(o))}this._lastBoundingBoxSize=e,Xb(this._boundingBox.style,l)},n.prototype._resetBoundingBoxStyles=function(){Xb(this._boundingBox.style,{top:"0",left:"0",right:"0",bottom:"0",height:"",width:"",alignItems:"",justifyContent:""})},n.prototype._resetOverlayElementStyles=function(){Xb(this._pane.style,{top:"",left:"",bottom:"",right:"",position:"",transform:""})},n.prototype._setOverlayElementStyles=function(n,t){var e={};if(this._hasExactPosition()){var l=this._viewportRuler.getViewportScrollPosition();Xb(e,this._getExactOverlayY(t,n,l)),Xb(e,this._getExactOverlayX(t,n,l))}else e.position="static";var r="",o=this._getOffset(t,"x"),i=this._getOffset(t,"y");o&&(r+="translateX("+o+"px) "),i&&(r+="translateY("+i+"px)"),e.transform=r.trim(),this._hasFlexibleDimensions&&this._overlayRef.getConfig().maxHeight&&(e.maxHeight=""),this._hasFlexibleDimensions&&this._overlayRef.getConfig().maxWidth&&(e.maxWidth=""),Xb(this._pane.style,e)},n.prototype._getExactOverlayY=function(n,t,e){var l={top:null,bottom:null},r=this._getOverlayPoint(t,this._overlayRect,n);this._isPushed&&(r=this._pushOverlayOnScreen(r,this._overlayRect,e));var o=this._overlayContainer?this._overlayContainer.getContainerElement().getBoundingClientRect().top:0;return r.y-=o,"bottom"===n.overlayY?l.bottom=this._document.documentElement.clientHeight-(r.y+this._overlayRect.height)+"px":l.top=tb(r.y),l},n.prototype._getExactOverlayX=function(n,t,e){var l={left:null,right:null},r=this._getOverlayPoint(t,this._overlayRect,n);return this._isPushed&&(r=this._pushOverlayOnScreen(r,this._overlayRect,e)),"right"==(this._isRtl()?"end"===n.overlayX?"left":"right":"end"===n.overlayX?"right":"left")?l.right=this._document.documentElement.clientWidth-(r.x+this._overlayRect.width)+"px":l.left=tb(r.x),l},n.prototype._getScrollVisibility=function(){var n=this._getOriginRect(),t=this._pane.getBoundingClientRect(),e=this.scrollables.map(function(n){return n.getElementRef().nativeElement.getBoundingClientRect()});return{isOriginClipped:Fb(n,e),isOriginOutsideView:jb(n,e),isOverlayClipped:Fb(t,e),isOverlayOutsideView:jb(t,e)}},n.prototype._subtractOverflows=function(n){for(var t=[],e=1;e<arguments.length;e++)t[e-1]=arguments[e];return t.reduce(function(n,t){return n-Math.max(t,0)},n)},n.prototype._getNarrowedViewportRect=function(){var n=this._document.documentElement.clientWidth,t=this._document.documentElement.clientHeight,e=this._viewportRuler.getViewportScrollPosition();return{top:e.top+this._viewportMargin,left:e.left+this._viewportMargin,right:e.left+n-this._viewportMargin,bottom:e.top+t-this._viewportMargin,width:n-2*this._viewportMargin,height:t-2*this._viewportMargin}},n.prototype._isRtl=function(){return"rtl"===this._overlayRef.getDirection()},n.prototype._hasExactPosition=function(){return!this._hasFlexibleDimensions||this._isPushed},n.prototype._getOffset=function(n,t){return"x"===t?null==n.offsetX?this._offsetX:n.offsetX:null==n.offsetY?this._offsetY:n.offsetY},n.prototype._validatePositions=function(){if(!this._preferredPositions.length)throw Error("FlexibleConnectedPositionStrategy: At least one position is required.");this._preferredPositions.forEach(function(n){Qb("originX",n.originX),Wb("originY",n.originY),Qb("overlayX",n.overlayX),Wb("overlayY",n.overlayY)})},n.prototype._addPanelClasses=function(n){var t=this;this._pane&&nb(n).forEach(function(n){-1===t._appliedPanelClasses.indexOf(n)&&(t._appliedPanelClasses.push(n),t._pane.classList.add(n))})},n.prototype._clearPanelClasses=function(){var n=this;this._pane&&(this._appliedPanelClasses.forEach(function(t){return n._pane.classList.remove(t)}),this._appliedPanelClasses=[])},n.prototype._getOriginRect=function(){var n=this._origin;return n instanceof At?n.nativeElement.getBoundingClientRect():n instanceof HTMLElement?n.getBoundingClientRect():{top:n.y,bottom:n.y,left:n.x,right:n.x,height:0,width:0}},n}();function Xb(n,t){for(var e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);return n}var Jb=function(){function n(n,t,e,l,r,o){this._preferredPositions=[],this._positionStrategy=new Yb(e,l,r,o).withFlexibleDimensions(!1).withPush(!1).withViewportMargin(0),this.withFallbackPosition(n,t)}return Object.defineProperty(n.prototype,"_isRtl",{get:function(){return"rtl"===this._overlayRef.getDirection()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"onPositionChange",{get:function(){return this._positionStrategy.positionChanges},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"positions",{get:function(){return this._preferredPositions},enumerable:!0,configurable:!0}),n.prototype.attach=function(n){this._overlayRef=n,this._positionStrategy.attach(n),this._direction&&(n.setDirection(this._direction),this._direction=null)},n.prototype.dispose=function(){this._positionStrategy.dispose()},n.prototype.detach=function(){this._positionStrategy.detach()},n.prototype.apply=function(){this._positionStrategy.apply()},n.prototype.recalculateLastPosition=function(){this._positionStrategy.reapplyLastPosition()},n.prototype.withScrollableContainers=function(n){this._positionStrategy.withScrollableContainers(n)},n.prototype.withFallbackPosition=function(n,t,e,l){var r=new qb(n,t,e,l);return this._preferredPositions.push(r),this._positionStrategy.withPositions(this._preferredPositions),this},n.prototype.withDirection=function(n){return this._overlayRef?this._overlayRef.setDirection(n):this._direction=n,this},n.prototype.withOffsetX=function(n){return this._positionStrategy.withDefaultOffsetX(n),this},n.prototype.withOffsetY=function(n){return this._positionStrategy.withDefaultOffsetY(n),this},n.prototype.withLockedPosition=function(n){return this._positionStrategy.withLockedPosition(n),this},n.prototype.withPositions=function(n){return this._preferredPositions=n.slice(),this._positionStrategy.withPositions(this._preferredPositions),this},n.prototype.setOrigin=function(n){return this._positionStrategy.setOrigin(n),this},n}(),nw=function(){function n(){this._cssPosition="static",this._topOffset="",this._bottomOffset="",this._leftOffset="",this._rightOffset="",this._alignItems="",this._justifyContent="",this._width="",this._height=""}return n.prototype.attach=function(n){var t=n.getConfig();this._overlayRef=n,this._width&&!t.width&&n.updateSize({width:this._width}),this._height&&!t.height&&n.updateSize({height:this._height}),n.hostElement.classList.add("cdk-global-overlay-wrapper"),this._isDisposed=!1},n.prototype.top=function(n){return void 0===n&&(n=""),this._bottomOffset="",this._topOffset=n,this._alignItems="flex-start",this},n.prototype.left=function(n){return void 0===n&&(n=""),this._rightOffset="",this._leftOffset=n,this._justifyContent="flex-start",this},n.prototype.bottom=function(n){return void 0===n&&(n=""),this._topOffset="",this._bottomOffset=n,this._alignItems="flex-end",this},n.prototype.right=function(n){return void 0===n&&(n=""),this._leftOffset="",this._rightOffset=n,this._justifyContent="flex-end",this},n.prototype.width=function(n){return void 0===n&&(n=""),this._overlayRef?this._overlayRef.updateSize({width:n}):this._width=n,this},n.prototype.height=function(n){return void 0===n&&(n=""),this._overlayRef?this._overlayRef.updateSize({height:n}):this._height=n,this},n.prototype.centerHorizontally=function(n){return void 0===n&&(n=""),this.left(n),this._justifyContent="center",this},n.prototype.centerVertically=function(n){return void 0===n&&(n=""),this.top(n),this._alignItems="center",this},n.prototype.apply=function(){if(this._overlayRef&&this._overlayRef.hasAttached()){var n=this._overlayRef.overlayElement.style,t=this._overlayRef.hostElement.style,e=this._overlayRef.getConfig();n.position=this._cssPosition,n.marginLeft="100%"===e.width?"0":this._leftOffset,n.marginTop="100%"===e.height?"0":this._topOffset,n.marginBottom=this._bottomOffset,n.marginRight=this._rightOffset,"100%"===e.width?t.justifyContent="flex-start":"center"===this._justifyContent?t.justifyContent="center":"rtl"===this._overlayRef.getConfig().direction?"flex-start"===this._justifyContent?t.justifyContent="flex-end":"flex-end"===this._justifyContent&&(t.justifyContent="flex-start"):t.justifyContent=this._justifyContent,t.alignItems="100%"===e.height?"flex-start":this._alignItems}},n.prototype.dispose=function(){if(!this._isDisposed&&this._overlayRef){var n=this._overlayRef.overlayElement.style,t=this._overlayRef.hostElement,e=t.style;t.classList.remove("cdk-global-overlay-wrapper"),e.justifyContent=e.alignItems=n.marginTop=n.marginBottom=n.marginLeft=n.marginRight=n.position="",this._overlayRef=null,this._isDisposed=!0}},n}(),tw=function(){function n(n,t,e,l){this._viewportRuler=n,this._document=t,this._platform=e,this._overlayContainer=l}return n.prototype.global=function(){return new nw},n.prototype.connectedTo=function(n,t,e){return new Jb(t,e,n,this._viewportRuler,this._document)},n.prototype.flexibleConnectedTo=function(n){return new Yb(n,this._viewportRuler,this._document,this._platform,this._overlayContainer)},n.ngInjectableDef=wn({factory:function(){return new n($n(Ib),$n(Bu),$n(sb,8),$n(Kb,8))},token:n,providedIn:"root"}),n}(),ew=0,lw=function(){function n(n,t,e,l,r,o,i,u,a,s){this.scrollStrategies=n,this._overlayContainer=t,this._componentFactoryResolver=e,this._positionBuilder=l,this._keyboardDispatcher=r,this._injector=o,this._ngZone=i,this._document=u,this._directionality=a,this._location=s}return n.prototype.create=function(n){var t=this._createHostElement(),e=this._createPaneElement(t),l=this._createPortalOutlet(e),r=new zb(n);return r.direction=r.direction||this._directionality.value,new Zb(l,t,e,r,this._ngZone,this._keyboardDispatcher,this._document,this._location)},n.prototype.position=function(){return this._positionBuilder},n.prototype._createPaneElement=function(n){var t=this._document.createElement("div");return t.id="cdk-overlay-"+ew++,t.classList.add("cdk-overlay-pane"),n.appendChild(t),t},n.prototype._createHostElement=function(){var n=this._document.createElement("div");return this._overlayContainer.getContainerElement().appendChild(n),n},n.prototype._createPortalOutlet=function(n){return this._appRef||(this._appRef=this._injector.get(dl)),new Rb(n,this._componentFactoryResolver,this._appRef,this._injector)},n}(),rw=new Sn("cdk-connected-overlay-scroll-strategy");function ow(n){return function(){return n.scrollStrategies.reposition()}}var iw=function(){return function(){}}(),uw=new Sn("cdk-dir-doc",{providedIn:"root",factory:function(){return $n(Bu)}}),aw=function(){function n(n){if(this.value="ltr",this.change=new he,n){var t=(n.body?n.body.dir:null)||(n.documentElement?n.documentElement.dir:null);this.value="ltr"===t||"rtl"===t?t:"ltr"}}return n.prototype.ngOnDestroy=function(){this.change.complete()},n.ngInjectableDef=wn({factory:function(){return new n($n(uw,8))},token:n,providedIn:"root"}),n}(),sw=function(){return function(){}}(),cw=new Sn("mat-menu-scroll-strategy");function pw(n){return function(){return n.scrollStrategies.reposition()}}var hw=function(){return function(){}}(),dw={headers:new Zu({"Content-Type":"application/json","Access-Control-Allow-Origin":"*"})},fw=function(){function n(n){this.http=n,this.apiServiceURL="1111",this.webSericeURL=""}return n.prototype.loadEndPointURL=function(){var n=this;return console.log("ProductService loadEndPointURL 1: "),this.getAPIServiceURL().pipe(nn(function(t){return console.log("ProductService loadEndPointURL 2: "),n.apiServiceURL=t.url,n.http.get(n.apiServiceURL+"/api/product",dw).pipe(nn(n.extractData))}))},n.prototype.ngOnInit=function(){console.log("ProductService ngOnInit 1.1: "),this.mySimpleMethod(),console.log("ProductService ngOnInit 1.2: "),this.getAPIServiceURL(),console.log("ProductService ngOnInit 2.2: ")},n.prototype.extractDataString=function(n){return n||{}},n.prototype.mySimpleMethod=function(){console.log("mySimpleMethod URL : "+this.webSericeURL)},n.prototype.getAPIServiceURL=function(){return console.log("webSericeURL URL : "+this.webSericeURL),this.http.get(this.webSericeURL+"/api/apiServiceURL")},n.prototype.extractData=function(n){return n||{}},n.prototype.getProducts=function(){var n=this;return console.log("ProductService ----\x3e getProducts 1 : "),this.getAPIServiceURL().pipe(Pa(function(t){return n.apiServiceURL=t.url,console.log("ProductService ----\x3e getProducts 2: Before callling : "+n.apiServiceURL+"/user/api/customer"),n.http.get(n.apiServiceURL+"/user/api/customer",dw).pipe(nn(n.extractData))}))},n.prototype.getLoginUserName=function(){return console.log("ProductService getLoginUserName 1: "),this.http.get(this.apiServiceURL+"/api/loginUserName",dw).pipe(nn(this.extractData))},n.prototype.getProduct=function(n){return console.log("ProductService getProduct 1: "),this.http.get(this.apiServiceURL+"/user/api/customer/"+n,dw).pipe(nn(this.extractData))},n.prototype.addProduct=function(n){return console.log("Add product ---\x3e "+JSON.stringify(n)),this.http.post(this.apiServiceURL+"/user/customer",JSON.stringify(n),dw).pipe(Wa(function(n){return console.log("added product w/ id="+n.id)}),ts(this.handleError("addProduct")))},n.prototype.updateProduct=function(n,t){return this.http.put(this.apiServiceURL+"/user/customer",JSON.stringify(t),dw).pipe(Wa(function(t){return console.log("updated product id="+n)}),ts(this.handleError("updateProduct")))},n.prototype.deleteProduct=function(n){return this.http.delete(this.apiServiceURL+"/user/customer/"+n,dw).pipe(Wa(function(t){return console.log("deleted product id="+n)}),ts(this.handleError("deleteProduct")))},n.prototype.handleError=function(n,t){return void 0===n&&(n="operation"),function(e){return console.error(e),console.log(n+" failed: "+e.message),du(t)}},n.ngInjectableDef=wn({factory:function(){return new n($n(ca))},token:n,providedIn:"root"}),n}(),gw=function(){function n(n,t){this.router=n,this.authService=t}return n.prototype.canActivate=function(n,t){return!!this.authService.isUserLoggedIn()||(this.router.navigate(["home"]),!1)},n.ngInjectableDef=wn({factory:function(){return new n($n(Hh),$n(Da))},token:n,providedIn:"root"}),n}(),mw=function(){return function(){}}(),yw=function(){return function(){}}(),vw=function(){return function(){}}(),_w=function(){function n(n,t){Gu(t)&&!n&&console.warn("Warning: Flex Layout loaded on the server without FlexLayoutServerModule")}return n.withConfig=function(t,e){return void 0===e&&(e=[]),{ngModule:n,providers:t.serverLoaded?[{provide:q_,useValue:t},{provide:A_,useValue:e,multi:!0},{provide:J_,useValue:!0}]:[{provide:q_,useValue:t},{provide:A_,useValue:e,multi:!0}]}},n}(),bw=function(){return function(){}}(),ww=function(){return function(){}}(),Cw=function(){return function(){}}(),Sw=function(){return function(){}}(),Ew=function(){return function(){}}(),xw=function(){return function(){}}(),Pw=function(){return function(){}}(),Tw=function(){return function(){}}(),Iw=function(){return function(){}}(),Ow=function(){return function(){}}(),kw=function(){return function(){}}(),Dw=function(){return function(){}}(),Aw=function(){return function(){}}(),Rw=function(){return function(){}}(),Mw=function(){return function(){}}(),Nw=function(){return function(){}}(),Lw=uu(su,[Aa],function(n){return function(n){for(var t={},e=[],l=!1,r=0;r<n.length;r++){var o=n[r];o.token===wt&&!0===o.value&&(l=!0),1073741824&o.flags&&e.push(o.token),o.index=r,t[cr(o.token)]=o}return{factory:null,providersByKey:t,providers:n,modules:e,isRoot:l}}([Yr(512,Tt,It,[[8,[md,If,Rf,Uf,qf,Xf,og,pg,_g,xg,Dg,Vg,qg,Yg,lm,am,fm,wm,Pm,Dm,Vm,zm,$m,ny]],[3,Tt],kt]),Yr(5120,Wl,Kl,[[3,Wl]]),Yr(4608,Du,Au,[Wl,[2,ku]]),Yr(5120,Oe,ke,[]),Yr(5120,Fl,Ql,[]),Yr(5120,Bl,$l,[]),Yr(4608,dc,fc,[Bu]),Yr(6144,Ft,null,[dc]),Yr(4608,ic,ac,[]),Yr(5120,Rs,function(n,t,e,l,r,o,i,u){return[new rc(n,t,e),new hc(l),new sc(r,o,i,u)]},[Bu,Ze,Re,Bu,Bu,ic,Ne,[2,uc]]),Yr(4608,Ms,Ms,[Rs,Ze]),Yr(135680,Vs,Vs,[Bu]),Yr(4608,qs,qs,[Ms,Vs,Oe]),Yr(5120,Ay,T_,[]),Yr(5120,Cv,I_,[]),Yr(4608,Xv,P_,[Bu,Ay,Cv]),Yr(5120,Nt,O_,[qs,Xv,Ze]),Yr(6144,Ls,null,[Vs]),Yr(4608,rl,rl,[Ze]),Yr(4608,ty,__,[Nt,Es]),Yr(4608,Z_,Y_,[W_,$_]),Yr(5120,hd,pd,[sd]),Yr(5120,Me,function(n,t,e){return[(l=n,r=t,function(){if(qu(r)){var n=Array.from(l.querySelectorAll("[class*=flex-layout-]")),t=/\bflex-layout-.+?\b/g;n.forEach(function(n){n.classList.contains("flex-layout-ssr")&&n.parentNode?n.parentNode.removeChild(n):n.className.replace(t,"")})}}),e];var l,r},[Bu,Re,hd]),Yr(4608,Vd,Vd,[]),Yr(4608,bf,bf,[]),Yr(5120,Ap,ad,[Hh]),Yr(4608,Kh,Kh,[]),Yr(6144,Qh,null,[Kh]),Yr(135680,Zh,Zh,[Hh,ye,ze,ut,Qh]),Yr(4608,$h,$h,[]),Yr(5120,Yh,ld,[Hh,Wu,Xh]),Yr(4608,ib,ib,[]),Yr(4608,ba,wa,[Bu,Re,va]),Yr(4608,Ca,Ca,[ba,_a]),Yr(5120,ha,function(n){return[n,new ab]},[Ca]),Yr(4608,ma,ma,[]),Yr(6144,ga,null,[ma]),Yr(4608,ya,ya,[ga]),Yr(6144,Ku,null,[ya]),Yr(4608,$u,Sa,[Ku,ut]),Yr(4608,ca,ca,[$u]),Yr(4608,fb,fb,[]),Yr(4608,lw,lw,[Hb,Kb,Tt,tw,$b,ut,Ze,Bu,aw,[2,Cu]]),Yr(5120,rw,ow,[lw]),Yr(5120,cw,pw,[lw]),Yr(4608,fw,fw,[ca]),Yr(1024,Jh,od,[[3,Hh]]),Yr(1024,Ee,Cc,[]),Yr(1024,al,function(){return[td()]},[]),Yr(512,sd,sd,[ut]),Yr(1024,Te,function(n,t){return[(e=n,ks("probe",As),ks("coreTokens",o({},Ds,(e||[]).reduce(function(n,t){return n[t.name]=t.token,n},{}))),function(){return As}),cd(t)];var e},[[2,al],sd]),Yr(512,Ie,Ie,[[2,Te]]),Yr(131584,dl,dl,[Ze,Ne,ut,Ee,Tt,Ie]),Yr(512,cp,pp,[]),Yr(512,qh,qh,[]),Yr(256,Xh,{},[]),Yr(1024,bu,rd,[vu,[2,wu],Xh]),Yr(512,Cu,Cu,[bu]),Yr(512,ze,ze,[]),Yr(512,ye,vl,[ze,[2,ml]]),Yr(1024,Nh,function(){return[[{path:"",component:Ef},{path:"home",component:Ef},{path:"login",component:Of},{path:"logout",component:Mf,canActivate:[gw]},{path:"businessmanager",component:Ff,canActivate:[gw],children:[{path:"",redirectTo:"/businessmanager/wealthmanager",pathMatch:"full"},{path:"customer",component:Wf},{path:"customerAdd",component:ng},{path:"customerEdit/:id",component:ig},{path:"wealthmanager",component:dg},{path:"wealthmanagerAdd",component:bg},{path:"wealthmanagerEdit/:id",component:Pg}]},{path:"wealthmanager",component:Rg,canActivate:[gw],children:[{path:"",redirectTo:"/wealthmanager/customer",pathMatch:"full"},{path:"customer",component:Ug},{path:"financialplan",component:Wg},{path:"financialplanDetail/:id",component:Xg},{path:"goalAdd",component:rm},{path:"investmentAdd/:id",component:cm},{path:"portfolio",component:gm},{path:"profile",component:Cm}]},{path:"customer",component:Tm,canActivate:[gw],children:[{path:"",redirectTo:"/customer/financialplan",pathMatch:"full"},{path:"financialplan",component:Am},{path:"financialplanDetail/:id",component:Um},{path:"profile",component:qm}]}]]},[]),Yr(1024,Hh,ud,[dl,cp,qh,Cu,ut,ye,ze,Nh,Xh,[2,Vh],[2,Rh]]),Yr(1073742336,ed,ed,[[2,Jh],[2,Hh]]),Yr(1073742336,Fu,Fu,[]),Yr(1073742336,Zl,Zl,[dl]),Yr(1073742336,Sc,Sc,[[3,Sc]]),Yr(1073742336,D_,D_,[]),Yr(1073742336,X_,X_,[]),Yr(1073742336,sw,sw,[]),Yr(1073742336,mw,mw,[]),Yr(1073742336,yw,yw,[]),Yr(1073742336,vw,vw,[]),Yr(1073742336,_w,_w,[[2,J_],Re]),Yr(1073742336,wf,wf,[]),Yr(1073742336,Cf,Cf,[]),Yr(1073742336,Sf,Sf,[]),Yr(1073742336,bw,bw,[]),Yr(1073742336,db,db,[[2,hb],[2,uc]]),Yr(1073742336,ww,ww,[]),Yr(1073742336,Mb,Mb,[]),Yr(1073742336,cb,cb,[]),Yr(1073742336,mb,mb,[]),Yr(1073742336,ub,ub,[]),Yr(1073742336,pb,pb,[]),Yr(1073742336,Cw,Cw,[]),Yr(1073742336,Sw,Sw,[]),Yr(1073742336,Ea,Ea,[]),Yr(1073742336,xa,xa,[]),Yr(1073742336,Ew,Ew,[]),Yr(1073742336,xw,xw,[]),Yr(1073742336,Pw,Pw,[]),Yr(1073742336,Tw,Tw,[]),Yr(1073742336,gb,gb,[]),Yr(1073742336,yb,yb,[]),Yr(1073742336,Iw,Iw,[]),Yr(1073742336,Ow,Ow,[]),Yr(1073742336,Tb,Tb,[]),Yr(1073742336,iw,iw,[]),Yr(1073742336,hw,hw,[]),Yr(1073742336,kw,kw,[]),Yr(1073742336,Dw,Dw,[]),Yr(1073742336,Aw,Aw,[]),Yr(1073742336,Rw,Rw,[]),Yr(1073742336,Mw,Mw,[]),Yr(1073742336,Nw,Nw,[]),Yr(1073742336,su,su,[]),Yr(256,wt,!0,[]),Yr(256,k_,"BrowserAnimations",[]),Yr(256,va,"XSRF-TOKEN",[]),Yr(256,_a,"X-XSRF-TOKEN",[])])});(function(){if(zt)throw new Error("Cannot enable prod mode after platform setup.");Ht=!1})(),wc().bootstrapModuleFactory(Lw).catch(function(n){return console.error(n)})}},[[0,0]]]);
Ig
delegate.go
package vrf import ( "encoding/hex" "math/big" "strings" "sync" "github.com/ethereum/go-ethereum/common" "github.com/pkg/errors" "github.com/theodesp/go-heaps/pairing" "github.com/smartcontractkit/sqlx" "github.com/smartcontractkit/chainlink/core/chains/evm" "github.com/smartcontractkit/chainlink/core/internal/gethwrappers/generated/aggregator_v3_interface" "github.com/smartcontractkit/chainlink/core/internal/gethwrappers/generated/solidity_vrf_coordinator_interface" "github.com/smartcontractkit/chainlink/core/internal/gethwrappers/generated/vrf_coordinator_v2" "github.com/smartcontractkit/chainlink/core/logger" "github.com/smartcontractkit/chainlink/core/services/job" "github.com/smartcontractkit/chainlink/core/services/keystore" "github.com/smartcontractkit/chainlink/core/services/pg" "github.com/smartcontractkit/chainlink/core/services/pipeline" "github.com/smartcontractkit/chainlink/core/utils" ) type Delegate struct { q pg.Q pr pipeline.Runner porm pipeline.ORM ks keystore.Master cc evm.ChainSet lggr logger.Logger } //go:generate mockery --name GethKeyStore --output mocks/ --case=underscore type GethKeyStore interface { GetRoundRobinAddress(addresses ...common.Address) (common.Address, error) } type Config interface { MinIncomingConfirmations() uint32 EvmGasLimitDefault() uint64 KeySpecificMaxGasPriceWei(addr common.Address) *big.Int MinRequiredOutgoingConfirmations() uint64 } func NewDelegate( db *sqlx.DB, ks keystore.Master, pr pipeline.Runner, porm pipeline.ORM, chainSet evm.ChainSet, lggr logger.Logger, cfg pg.LogConfig) *Delegate { return &Delegate{ q: pg.NewQ(db, lggr, cfg), ks: ks, pr: pr, porm: porm, cc: chainSet, lggr: lggr, } } func (d *Delegate) JobType() job.Type { return job.VRF } func (d *Delegate) AfterJobCreated(spec job.Job) {} func (d *Delegate) BeforeJobDeleted(spec job.Job) {} // ServicesForSpec satisfies the job.Delegate interface. func (d *Delegate) ServicesForSpec(jb job.Job) ([]job.ServiceCtx, error) { if jb.VRFSpec == nil || jb.PipelineSpec == nil { return nil, errors.Errorf("vrf.Delegate expects a VRFSpec and PipelineSpec to be present, got %+v", jb) } pl, err := jb.PipelineSpec.Pipeline() if err != nil { return nil, err } chain, err := d.cc.Get(jb.VRFSpec.EVMChainID.ToInt()) if err != nil { return nil, err } coordinator, err := solidity_vrf_coordinator_interface.NewVRFCoordinator(jb.VRFSpec.CoordinatorAddress.Address(), chain.Client()) if err != nil { return nil, err } coordinatorV2, err := vrf_coordinator_v2.NewVRFCoordinatorV2(jb.VRFSpec.CoordinatorAddress.Address(), chain.Client()) if err != nil { return nil, err } l := d.lggr.With( "jobID", jb.ID, "externalJobID", jb.ExternalJobID, "coordinatorAddress", jb.VRFSpec.CoordinatorAddress, ) lV1 := l.Named("VRFListener") lV2 := l.Named("VRFListenerV2") for _, task := range pl.Tasks { if _, ok := task.(*pipeline.VRFTaskV2); ok { linkEthFeedAddress, err := coordinatorV2.LINKETHFEED(nil) if err != nil { return nil, err } aggregator, err := aggregator_v3_interface.NewAggregatorV3Interface(linkEthFeedAddress, chain.Client()) if err != nil { return nil, err } return []job.ServiceCtx{&listenerV2{ cfg: chain.Config(), l: lV2, ethClient: chain.Client(), logBroadcaster: chain.LogBroadcaster(), q: d.q, coordinator: coordinatorV2, aggregator: aggregator, txm: chain.TxManager(), pipelineRunner: d.pr, gethks: d.ks.Eth(), job: jb, reqLogs: utils.NewHighCapacityMailbox(), chStop: make(chan struct{}), respCount: GetStartingResponseCountsV2(d.q, lV2, chain.Client().ChainID().Uint64(), chain.Config().EvmFinalityDepth()), blockNumberToReqID: pairing.New(), reqAdded: func() {}, headBroadcaster: chain.HeadBroadcaster(), wg: &sync.WaitGroup{}, }}, nil } if _, ok := task.(*pipeline.VRFTask); ok { return []job.ServiceCtx{&listenerV1{ cfg: chain.Config(), l: lV1, headBroadcaster: chain.HeadBroadcaster(), logBroadcaster: chain.LogBroadcaster(), q: d.q, txm: chain.TxManager(), coordinator: coordinator, pipelineRunner: d.pr, gethks: d.ks.Eth(), job: jb, // Note the mailbox size effectively sets a limit on how many logs we can replay // in the event of a VRF outage. reqLogs: utils.NewHighCapacityMailbox(), chStop: make(chan struct{}), waitOnStop: make(chan struct{}), newHead: make(chan struct{}, 1), respCount: GetStartingResponseCountsV1(d.q, lV1, chain.Client().ChainID().Uint64(), chain.Config().EvmFinalityDepth()), blockNumberToReqID: pairing.New(), reqAdded: func() {}, }}, nil } } return nil, errors.New("invalid job spec expected a vrf task") } func GetStartingResponseCountsV1(q pg.Q, l logger.Logger, chainID uint64, evmFinalityDepth uint32) map[[32]byte]uint64 { respCounts := map[[32]byte]uint64{} // Only check as far back as the evm finality depth for completed transactions. counts, err := getRespCounts(q, chainID, evmFinalityDepth) if err != nil { // Continue with an empty map, do not block job on this. l.Errorw("Unable to read previous confirmed fulfillments", "err", err) return respCounts } for _, c := range counts { // Remove the quotes from the json req := strings.Replace(c.RequestID, `"`, ``, 2) // Remove the 0x prefix b, err := hex.DecodeString(req[2:]) if err != nil { l.Errorw("Unable to read fulfillment", "err", err, "reqID", c.RequestID) continue } var reqID [32]byte copy(reqID[:], b) respCounts[reqID] = uint64(c.Count) } return respCounts } func GetStartingResponseCountsV2( q pg.Q, l logger.Logger, chainID uint64, evmFinalityDepth uint32, ) map[string]uint64
func getRespCounts(q pg.Q, chainID uint64, evmFinalityDepth uint32) ( []struct { RequestID string Count int }, error, ) { counts := []struct { RequestID string Count int }{} // This query should use the idx_eth_txes_state_from_address_evm_chain_id // index, since the quantity of unconfirmed/unstarted/in_progress transactions _should_ be small // relative to the rest of the data. unconfirmedQuery := ` SELECT meta->'RequestID' AS request_id, count(meta->'RequestID') AS count FROM eth_txes et WHERE et.meta->'RequestID' IS NOT NULL AND et.state IN ('unconfirmed', 'unstarted', 'in_progress') GROUP BY meta->'RequestID' ` // Fetch completed transactions only as far back as the given cutoffBlockNumber. This avoids // a table scan of the eth_txes table, which could be large if it is unpruned. confirmedQuery := ` SELECT meta->'RequestID' AS request_id, count(meta->'RequestID') AS count FROM eth_txes et JOIN eth_tx_attempts eta on et.id = eta.eth_tx_id join eth_receipts er on eta.hash = er.tx_hash WHERE et.meta->'RequestID' is not null AND er.block_number >= (SELECT number FROM evm_heads WHERE evm_chain_id = $1 ORDER BY number DESC LIMIT 1) - $2 GROUP BY meta->'RequestID' ` query := unconfirmedQuery + "\nUNION ALL\n" + confirmedQuery err := q.Select(&counts, query, chainID, evmFinalityDepth) if err != nil { return nil, err } return counts, nil }
{ respCounts := map[string]uint64{} // Only check as far back as the evm finality depth for completed transactions. counts, err := getRespCounts(q, chainID, evmFinalityDepth) if err != nil { // Continue with an empty map, do not block job on this. l.Errorw("Unable to read previous confirmed fulfillments", "err", err) return respCounts } for _, c := range counts { // Remove the quotes from the json req := strings.Replace(c.RequestID, `"`, ``, 2) // Remove the 0x prefix b, err := hex.DecodeString(req[2:]) if err != nil { l.Errorw("Unable to read fulfillment", "err", err, "reqID", c.RequestID) continue } bi := new(big.Int).SetBytes(b) respCounts[bi.String()] = uint64(c.Count) } return respCounts }
basic.py
from redis import Redis
def conn(): config = config() rec = getconfig()["redis"] self.conn = Redis(host=rec["host"],port=int(rec["port"]),db=int(rec['db'])) return self.conn
from config.getconfig import getconfig
record.rs
// Copyright 2021, Collabora, Ltd. // // SPDX-License-Identifier: Apache-2.0 OR MIT use crate::{ parse_policy::ParsePolicy, record_emitter::RecordEmitter, KVParser, KeyValuePair, LineNumber, Output, }; /// An error from operations on a Record #[derive(Debug, thiserror::Error)] pub enum
{ #[error("Found {1} fields named {0} instead of the zero or one expected.")] WantedAtMostOneFoundMore(String, usize), #[error("Found {1} fields named {0} instead of the one expected.")] WantedOneFoundMore(String, usize), #[error("Missing mandatory field {0}")] MissingField(String), #[error("Out of data")] OutOfData, #[error("Other error message: {0}")] Message(String), } /// An ordered collection of key-value pairs, providing some helper functions above and beyond what vector provides. pub struct Record(Vec<KeyValuePair>); impl Default for Record { fn default() -> Self { Self(Vec::default()) } } impl Record { /// Create from a vector. pub fn new(fields: Vec<KeyValuePair>) -> Self { Self(fields) } /// Extract the inner vector of pairs pub fn into_inner(self) -> Vec<KeyValuePair> { self.0 } /// Get a shared borrow of the contained vector. pub fn get(&self) -> &Vec<KeyValuePair> { &self.0 } /// Return the number of fields whose key matches the provided key pub fn count_fields_with_key(&self, key: &str) -> usize { self.0.iter().filter(|pair| pair.key == key).count() } /// Return an iterator of all field values (in original order) whose key matches the provided key pub fn iter_values_for_key<'a>( &'a self, key: &'a str, ) -> Box<dyn Iterator<Item = &'a String> + 'a> { Box::new(self.0.iter().filter_map(move |pair| { if pair.key == key { Some(&pair.value) } else { None } })) } /// Return a vector of all field values (in original order) whose key matches the provided key pub fn values_for_key<'a>(&'a self, key: &'a str) -> Vec<&'a String> { self.iter_values_for_key(key).collect() } /// Returns the value of a field with the given key, if any, and returns an error if more than one such field exists. pub fn value_for_key<'a>(&'a self, key: &'a str) -> Result<Option<&'a String>, RecordError> { let mut values = self.iter_values_for_key(key); let value = values.next(); if values.next().is_none() { Ok(value) } else { Err(RecordError::WantedAtMostOneFoundMore( key.to_string(), 2 + values.count(), )) } } /// Returns the value of a field with the given key, and returns an error if more than one such field exists, or if none exist. pub fn value_for_required_key<'a>(&'a self, key: &'a str) -> Result<&'a String, RecordError> { let mut values = self.iter_values_for_key(key); match values.next() { Some(value) => { if values.next().is_none() { Ok(value) } else { Err(RecordError::WantedOneFoundMore( key.to_string(), 2 + values.count(), )) } } None => Err(RecordError::MissingField(key.to_string())), } } } impl From<Output<Vec<KeyValuePair>>> for Output<Record> { fn from(v: Output<Vec<KeyValuePair>>) -> Self { v.map(Record::new) } } impl From<Vec<KeyValuePair>> for Record { fn from(fields: Vec<KeyValuePair>) -> Self { Self::new(fields) } } impl From<Record> for Vec<KeyValuePair> { fn from(record: Record) -> Self { record.into_inner() } } /// Parses key-value pairs that are grouped in "records" by an object implementing [RecordEmitter] #[derive(Debug)] pub struct RecordParser<R, P: ParsePolicy> { record_emitter: R, inner: KVParser<P>, } impl<R: RecordEmitter, P: ParsePolicy> RecordParser<R, P> { /// Create a new record parser, wrapping the provided parser. pub fn new(record_emitter: R, inner: KVParser<P>) -> Self { Self { record_emitter, inner, } } /// Pass a line to process and advance the state of the parser. /// /// If a record has finished is now available, it will /// be found in the return value. pub fn process_line(&mut self, line: &str) -> LineNumber<Output<Record>> { self.inner .process_line(line) .map(|v| self.record_emitter.accumulate_output(v)) .map(|output| output.into()) } /// End the input and return any record in progress pub fn end_input(&mut self) -> Output<Record> { self.record_emitter.end_input().into() } } impl<R: RecordEmitter + Default, P: ParsePolicy> RecordParser<R, P> where KVParser<P>: Default, { pub fn default() -> Self { Self { inner: KVParser::default(), record_emitter: R::default(), } } }
RecordError
loop_fusion_2.rs
//! Richer loop fusion rules. use ast::BuilderKind::*; use ast::ExprKind::*; use ast::Type::*; use ast::*; use error::*; use util::SymbolGenerator; extern crate fnv; struct MergeSingle<'a> { params: &'a Vec<Parameter>, value: &'a Expr, } impl<'a> MergeSingle<'a> { fn extract(expr: &'a Expr) -> Option<MergeSingle<'a>> { if let Lambda { ref params, ref body, } = expr.kind { if let Merge { ref builder, ref value, } = body.kind { match builder.kind { Ident(ref name) if *name == params[0].name => { return Some(MergeSingle { params, value }); } _ => {} } } } return None; } } struct NewAppender; impl NewAppender { fn extract(expr: &Expr) -> Option<NewAppender> { if let NewBuilder(_) = expr.kind { if let Builder(Appender(_), _) = expr.ty { return Some(NewAppender); } } return None; } } struct ResForAppender<'a> { iters: &'a Vec<Iter>, func: &'a Expr, } impl<'a> ResForAppender<'a> { fn extract(expr: &'a Expr) -> Option<ResForAppender<'a>> { if let Res { ref builder } = expr.kind { if let For { ref iters, ref builder, ref func, } = builder.kind { if NewAppender::extract(builder).is_some() { return Some(ResForAppender { iters, func }); } } } return None; } } struct MapIter<'a> { iters: &'a Vec<Iter>, merge_params: &'a Vec<Parameter>, merge_value: &'a Expr, } impl<'a> MapIter<'a> { fn extract(iter: &'a Iter) -> Option<MapIter> { if iter.is_simple() { if let Some(rfa) = ResForAppender::extract(&iter.data) { if rfa.iters.iter().all(|ref i| i.is_simple()) { if let Some(merge) = MergeSingle::extract(&rfa.func) { return Some(MapIter { iters: &rfa.iters, merge_params: merge.params, merge_value: merge.value, }); } } } } return None; } } /// Gets rid of `result(for(d, appender, _))` expressions within the iterators in a loop, replacing them /// with direct iteration over the data (e.g. `d` here). /// /// Caveats: /// - Like all Zip-based transforms, this function currently assumes that the output of each /// expression in the Zip is the same length. pub fn fuse_loops_2(expr: &mut Expr) { use ast::constructors::*; if expr.uniquify().is_err() { return; } let mut gen = SymbolGenerator::from_expression(expr); expr.transform(&mut |ref mut expr| { if let For { ref iters, ref builder, ref func, } = expr.kind { if let Lambda { ref params, ref body, } = func.kind { // Check whether at least one iterator is over a map pattern, i.e., Res(For(new Appender)) with // a simple merge operation. if !iters .iter() .any(|ref iter| MapIter::extract(iter).is_some()) { return None; } // Now that we know we have at least one nested map, create a new expression to replace the old // one with. We start by figuring out our new list of iterators, then build a new lambda function // that will call the old one but substitute some of the variables in it. let mut new_iters: Vec<Iter> = Vec::new(); let mut new_elem_exprs: Vec<Expr> = Vec::new(); let mut let_statements: Vec<(Symbol, Expr)> = Vec::new(); let mut new_body = body.as_ref().clone(); let elem_types: Vec<Type>; if let Struct(ref types) = params[2].ty { elem_types = types.clone(); } else { elem_types = vec![params[2].ty.clone()]; } let mut new_elem_types: Vec<Type> = Vec::new(); let mut new_elem_symbols: Vec<Symbol> = Vec::new(); for i in 0..iters.len() { // Check whether this iter follows a map pattern, and if so, use that map's inner iter. if let Some(ref map) = MapIter::extract(&iters[i]) { // This was indeed a map pattern; we'll update it to apply the map function directly on the // element values we pull from those iterators in the upper-level loop. let mut value = map.merge_value.clone(); let index_ident = ident_expr(params[1].name.clone(), params[1].ty.clone()).unwrap(); value.substitute(&map.merge_params[1].name, &index_ident); // For each iterator in the original MapIter, figure out a local variable that will hold // the corresponding item. let mut map_elem_types: Vec<Type> = Vec::new(); let mut map_elem_symbols: Vec<Symbol> = Vec::new(); let mut map_elem_exprs: Vec<Expr> = Vec::new(); for ref map_iter in map.iters { // Check whether this iterator is already in our new_iters list; if so, reuse the old one let iter_num; if let Some(pos) = new_iters .iter() .position(|x| iters_match_ignoring_symbols(x, map_iter).unwrap()) { iter_num = pos } else { // If it is indeed a new iterator, remember its element type and assign it a symbol. new_iters.push((*map_iter).clone()); let elem_type = match &map_iter.data.ty { &Vector(ref ty) => ty, _ => panic!("Iterator was not over a vector"), }; new_elem_types.push(elem_type.as_ref().clone()); let new_elem_symbol = gen.new_symbol("tmp"); new_elem_symbols.push(new_elem_symbol); iter_num = new_iters.len() - 1; } let elem_ident = ident_expr( new_elem_symbols[iter_num].clone(), new_elem_types[iter_num].clone(), ) .unwrap(); map_elem_types.push(new_elem_types[iter_num].clone()); map_elem_symbols.push(new_elem_symbols[iter_num].clone()); map_elem_exprs.push(elem_ident); } // If needed, add a Let statement to package the map_elems into a struct, and substitute // that into our value expression; otherwise just substitute the single symbol we're using if map_elem_exprs.len() > 1 { let struct_symbol = gen.new_symbol("tmp"); let make_struct = makestruct_expr(map_elem_exprs).unwrap(); let struct_ident = ident_expr(struct_symbol.clone(), make_struct.ty.clone()).unwrap(); let_statements.push((struct_symbol, make_struct)); value.substitute(&map.merge_params[2].name, &struct_ident); } else { value.substitute(&map.merge_params[2].name, &map_elem_exprs[0]); } // Push an expression for this element new_elem_exprs.push(value); } else { // Check whether this iterator is already in our new_iters list; if so, reuse the old one let iter_num; if let Some(pos) = new_iters .iter() .position(|x| iters_match_ignoring_symbols(x, &iters[i]).unwrap()) { iter_num = pos } else { // If it is indeed a new iterator, remember its element type and assign it a symbol. new_iters.push(iters[i].clone()); new_elem_types.push(elem_types[i].clone()); let new_elem_symbol = gen.new_symbol("tmp"); new_elem_symbols.push(new_elem_symbol); iter_num = new_iters.len() - 1; } // Push an expression for this element. let elem_ident = ident_expr( new_elem_symbols[iter_num].clone(), new_elem_types[iter_num].clone(), ) .unwrap(); new_elem_exprs.push(elem_ident); } } let new_param_type = if new_elem_types.len() > 1 { Struct(new_elem_types.clone()) } else { new_elem_types[0].clone() }; let new_param_name = gen.new_symbol("data"); let new_param = Parameter { name: new_param_name.clone(), ty: new_param_type.clone(), }; let new_params = vec![params[0].clone(), params[1].clone(), new_param]; // Add a let statement in front of the body that builds up the argument struct. let old_param_expr = if new_elem_exprs.len() > 1 { makestruct_expr(new_elem_exprs.clone()).unwrap() } else { new_elem_exprs[0].clone() }; new_body = let_expr(params[2].name.clone(), old_param_expr, new_body).unwrap(); // Add any let statements we created for temporary structs. for pair in let_statements.iter().rev() { new_body = let_expr(pair.0.clone(), pair.1.clone(), new_body).unwrap() } // Add let statements in front of the body that set the new_elem_symbols to new_elem_exprs. let new_param_ident = ident_expr(new_param_name.clone(), new_param_type.clone()).unwrap(); if new_elem_types.len() > 1 { for i in (0..new_elem_types.len()).rev() { new_body = let_expr( new_elem_symbols[i].clone(), getfield_expr(new_param_ident.clone(), i as u32).unwrap(), new_body, ) .unwrap() } } else { new_body = let_expr( new_elem_symbols[0].clone(), new_param_ident.clone(), new_body, ) .unwrap() } let new_func = lambda_expr(new_params, new_body).unwrap(); let mut result = for_expr(new_iters.clone(), builder.as_ref().clone(), new_func, false).unwrap(); result.annotations = expr.annotations.clone(); return Some(result); } } None }) } /// Replaces Let(name, value, Merge(builder, elem)) with Merge(builder, Let(name, value, elem)) to /// enable further pattern matching on map functions downstream. This is only allowed when the let /// statement is not defining some symbol that's used in the builder expression, so we check for that. pub fn move_merge_before_let(expr: &mut Expr) { use ast::constructors::*; expr.transform_up(&mut |ref mut expr| { if let Let { ref name, value: ref let_value, ref body, } = expr.kind { if let Merge { ref builder, value: ref merge_value, } = body.kind { if !builder.contains_symbol(name) { return Some( merge_expr( *builder.clone(), let_expr(name.clone(), *let_value.clone(), *merge_value.clone()) .unwrap(), ) .unwrap(), ); } } } return None; }); } /// Checks whether a For loop is simple enough to be fused. fn is_fusable_expr(expr: &Expr) -> bool { if let Some(rfa) = ResForAppender::extract(expr) { if rfa.iters.iter().all(|ref i| i.is_simple()) { if let Some(_) = MergeSingle::extract(&rfa.func) { return true; } } } return false; } /// Checks if a name binding can be fused with the loop its contained in. fn only_used_in_zip(name: &Symbol, expr: &Expr) -> bool { // Number of times the name appears in `expr`. let mut total_count = 0; // Number of times the name appears in a Zip in `expr`. let mut iters_count = 0; expr.traverse(&mut |ref expr| { match expr.kind { Ident(ref name1) if name == name1 => { total_count += 1; } For { ref iters, .. } => { for iter in iters.iter() { match iter.data.kind { Ident(ref name1) if name == name1 => { iters_count += 1;
} } Length { ref data } => { if let Ident(ref name1) = data.kind { if name1 == name { total_count -= 1; } } } _ => (), }; }); (iters_count == total_count) } /// Aggressively inlines let statements in cases which allow loop fusion to fire. This inliner is /// aggressive because it will replace identifiers which appear more than once after being defined. /// However, the inliner will only fire if eventually, the inlined loop will be fused. pub fn aggressive_inline_let(expr: &mut Expr) { let mut subbed_one = false; expr.transform_up(&mut |ref mut expr| { if subbed_one { return None; } if let Let { ref mut name, ref mut value, ref mut body, } = expr.kind { if !is_fusable_expr(value) { return None; } else if !only_used_in_zip(name, body) { return None; } let mut new_body = body.as_ref().clone(); new_body.substitute(name, value); subbed_one = true; Some(new_body) } else { None } }); } /// Merges { result(for(appender, result(for(appender( } over the same set of loops into /// a single loop of result(for({appender,appender} ...)). /// /// TODO this can definitely be generalized to capture more cases (e.g., the result doesn't /// necessarily need to be in a `MakeStruct` expression). /// /// Prerequisites: Expression is uniquified. /// Caveats: This transformation will only fire if each vector in the iterator is bound to an /// identifier. pub fn merge_makestruct_loops(expr: &mut Expr) { use ast::constructors::*; expr.uniquify().unwrap(); expr.transform(&mut |ref mut expr| { if let MakeStruct { ref elems } = expr.kind { // Each member of the `GetStruct` must be a ResForAppender pattern. if elems.len() > 2 || !elems .iter() .all(|ref e| ResForAppender::extract(e).is_some()) { return None; } let rfas: Vec<_> = elems .iter() .map(|ref e| ResForAppender::extract(e).unwrap()) .collect(); // Make sure all the iterators are simple, and each map just has a single merge. if !rfas.iter().all(|ref rfa| { rfa.iters.iter().all(|ref iter| iter.is_simple()) && MergeSingle::extract(rfa.func).is_some() }) { return None; } // For each Iter, holds a map from name -> index. The indices are required to rewrite // struct accesses. Also keep a HashSet of the identifiers in each iterator. let mut ident_indices = vec![]; let mut idents = vec![]; // This is the "authoratative map", i.e., the GetField indexing every other body will be transformed // to use. It maps the *index to the name* (reverse of all the other maps). let mut first_rfa_map = fnv::FnvHashMap::default(); for (i, rfa) in rfas.iter().enumerate() { let mut map = fnv::FnvHashMap::default(); let mut set = fnv::FnvHashSet::default(); for (j, iter) in rfa.iters.iter().enumerate() { if let Ident(ref name) = iter.data.kind { map.insert(j, name); set.insert(name); // Only for first one. if i == 0 { first_rfa_map.insert(name, j); } } else { return None; } } ident_indices.push(map); idents.push(set); } // For the future when we may support iteration over ranges. if idents.len() == 0 { return None; } // Now, make sure each iterator has the same set of vectors (but perhaps in a different // ordering). if !idents.iter().all(|e| idents[0] == *e) { return None; } // // We now have a struct of ResForAppender patterns over the same data. Rewrite this to be a // ResForAppender over a struct of appender. // // Safe to unwrap since we checked it above. let first_ma = MergeSingle::extract(rfas[0].func).unwrap(); // Construct the new builder type for the loop/etc. // For each RFA, get the first parameter of the builder function and copy its type. let types: Vec<_> = rfas .iter() .map(|ref rfa| MergeSingle::extract(rfa.func).unwrap().params[0].ty.clone()) .collect(); let final_builder_ty = Struct(types); let mut bodies = vec![]; for (i, rfa) in rfas.iter().enumerate() { let ma = MergeSingle::extract(rfa.func).unwrap(); let mut new_body = ma.value.clone(); // If the element is a Struct that Zips multiple vectors, we need to rewrite the // indexing to match the first body. This handles zips over the same vectors in a // different order (which could be common if upstream transforms shuffle things around). if rfa.iters.len() > 1 { let ref rev_map = ident_indices[i]; // third parameter is the element. let ref elem_name = ma.params[2]; // This will be a no-op for the first iterator. new_body.transform(&mut |ref mut e| { if let GetField { ref mut expr, ref mut index, } = e.kind { if let Ident(ref name) = expr.kind { if *name == elem_name.name && expr.ty == elem_name.ty { // Get the vector identifier this index refers to. let vec_name = rev_map.get(&(*index as usize)).unwrap(); let change_to = first_rfa_map.get(vec_name).unwrap(); *index = *change_to as u32; } } } // Expression is modified in place. None }); } // Substitute the parameter names to use the ones from the first body. // Skip the first one since that's the builder, and since this is matching a // MergeSingle pattern, we shouldn't have any builders in here. for (j, ref param) in ma.params.iter().enumerate() { let ref replacement = ident_expr(first_ma.params[j].name.clone(), param.ty.clone()).unwrap(); new_body.substitute(&param.name, replacement); } // Add the new merge expression to the list of bodies. let builder_expr = getfield_expr( ident_expr(first_ma.params[0].name.clone(), final_builder_ty.clone()).unwrap(), i as u32, ) .unwrap(); bodies.push(merge_expr(builder_expr, new_body).unwrap()); } let final_iters = rfas[0].iters.clone(); let mut newbuilders = vec![]; // Pull out the new builders and clone them into a vector. for elem in elems.iter() { if let Res { ref builder } = elem.kind { if let For { ref builder, .. } = builder.kind { newbuilders.push(builder.as_ref().clone()); } } } // Since we extracted RFAs from all of them... assert!(newbuilders.len() == elems.len()); // Build the function and final body. let final_body = makestruct_expr(bodies).unwrap(); let mut final_params = first_ma.params.clone(); final_params[0].ty = final_builder_ty.clone(); let final_func = lambda_expr(final_params, final_body).unwrap(); let final_loop = for_expr( final_iters, makestruct_expr(newbuilders).unwrap(), final_func, false, ) .unwrap(); let mut gen = SymbolGenerator::from_expression(expr); let struct_name = gen.new_symbol("tmp"); let builder_iden = ident_expr(struct_name.clone(), final_builder_ty).unwrap(); let results = (0..rfas.len()) .map(|i| { result_expr(getfield_expr(builder_iden.clone(), i as u32).unwrap()).unwrap() }) .collect(); let results = makestruct_expr(results).unwrap(); let final_expr = let_expr(struct_name, final_loop, results).unwrap(); return Some(final_expr); } None }); } /// Are two iterators equivalent ignoring symbols defined inside each one? fn iters_match_ignoring_symbols(iter1: &Iter, iter2: &Iter) -> WeldResult<bool> { Ok(iter1.kind == iter2.kind && iter1.data.compare_ignoring_symbols(iter2.data.as_ref())? && options_match_ignoring_symbols(&iter1.start, &iter2.start)? && options_match_ignoring_symbols(&iter1.end, &iter2.end)? && options_match_ignoring_symbols(&iter1.stride, &iter2.stride)?) } /// Are two Option<Box<Expr>> equal ignoring symbols defined inside each one? fn options_match_ignoring_symbols( opt1: &Option<Box<Expr>>, opt2: &Option<Box<Expr>>, ) -> WeldResult<bool> { match (opt1, opt2) { (&None, &None) => Ok(true), (&Some(ref e1), &Some(ref e2)) => e1.compare_ignoring_symbols(e2.as_ref()), _ => Ok(false), } }
} _ => (), }
match-naked-record.rs
// run-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 struct
{ x: isize } pub fn main() { let _x = match 0 { _ => X { x: 0 } }; }
X
removeActor.js
const { Router } = require('express') const passport = require('passport') module.exports = Router({mergeParams: true}).delete( '/movies/:movieId/casting/:actorId',
passport.authenticate('jwt', { session: false }), async (req, res, next) => { const count = await req.db.Movie.removeActor(req.params) return res.sendStatus(count ? 204 : 404) })
mockccstream.go
//<developer> // <name>linapex 曹一峰</name> // <email>[email protected]</email> // <wx>superexc</wx> // <qqgroup>128148617</qqgroup> // <url>https://jsq.ink</url> // <role>pku engineer</role> // <date>2019-03-16 19:39:58</date> //</624455966477258752> /* 版权所有IBM Corp.2017保留所有权利。 根据Apache许可证2.0版(以下简称“许可证”)获得许可; 除非符合许可证,否则您不能使用此文件。 您可以在以下网址获得许可证副本: http://www.apache.org/licenses/license-2.0 除非适用法律要求或书面同意,软件 根据许可证分发是按“原样”分发的, 无任何明示或暗示的保证或条件。 有关管理权限和 许可证限制。 **/ package peer import ( "fmt" "sync" "time" pb "github.com/hyperledger/fabric/protos/peer" ) //mockresponseset用于处理CC到对等通信 //例如get/put/del state。mockResponse包含 // // type MockResponseSet struct { // //响应集 DoneFunc func(int, error) //当输入没有被调用时,任何步骤都会调用errorfunc。 //匹配收到的消息 ErrorFunc func(int, error) // //和发送响应(可选) Responses []*MockResponse } // //和发送响应(可选) type MockResponse struct { RecvMsg *pb.ChaincodeMessage RespMsg interface{} } //mockcccomm实现了链码和对等端之间的模拟通信。 // // type MockCCComm struct { name string bailOnError bool keepAlive *pb.ChaincodeMessage recvStream chan *pb.ChaincodeMessage sendStream chan *pb.ChaincodeMessage respIndex int respLock sync.Mutex respSet *MockResponseSet pong bool skipClose bool } func (s *MockCCComm) SetName(newname string) { s.name = newname } // func (s *MockCCComm) Send(msg *pb.ChaincodeMessage) error { s.sendStream <- msg return nil } // func (s *MockCCComm) Recv() (*pb.ChaincodeMessage, error) { msg := <-s.recvStream return msg, nil } // func (s *MockCCComm) CloseSend() error { return nil } // func (s *MockCCComm) GetRecvStream() chan *pb.ChaincodeMessage { return s.recvStream } // func (s *MockCCComm) GetSendStream() chan *pb.ChaincodeMessage { return s.sendStream } // func (s *MockCCComm) Quit() { if !s.skipClose { close(s.recvStream) close(s.sendStream) } } // func (s *MockCCComm) SetBailOnError(b bool) { s.bailOnError = b } // func (s *MockCCComm) SetPong(val bool) { s.pong = val } //setkeepalive设置keepalive。此mut只能在服务器上完成 func (s *MockCCComm) SetKeepAlive(ka *pb.ChaincodeMessage) { s.keepAlive = ka } // func (s *MockCCComm) SetResponses(respSet *MockResponseSet) { s.respLock.Lock() s.respSet = respSet s.respIndex = 0 s.respLock.Unlock() } //保持活力 func (s *MockCCComm) ka(done <-chan struct{}) { for { if s.keepAlive == nil { return } s.Send(s.keepAlive) select { case <-time.After(10 * time.Millisecond): case <-done: return } } } // func (s *MockCCComm) Run(done <-chan struct{}) error { //启动keepalive go s.ka(done) defer s.Quit() for { msg, err := s.Recv() //流可能刚刚关闭 if msg == nil { return err } if err != nil { return err } if err = s.respond(msg); err != nil { if s.bailOnError { return err } } } } func (s *MockCCComm) respond(msg *pb.ChaincodeMessage) error { if msg != nil && msg.Type == pb.ChaincodeMessage_KEEPALIVE { // if s.pong { return s.Send(msg) } return nil } s.respLock.Lock() defer s.respLock.Unlock() var err error if s.respIndex < len(s.respSet.Responses) { mockResp := s.respSet.Responses[s.respIndex] if mockResp.RecvMsg != nil { if msg.Type != mockResp.RecvMsg.Type { if s.respSet.ErrorFunc != nil { s.respSet.ErrorFunc(s.respIndex, fmt.Errorf("Invalid message expected %d received %d", int32(mockResp.RecvMsg.Type), int32(msg.Type))) s.respIndex = s.respIndex + 1 return nil } } } if mockResp.RespMsg != nil { var ccMsg *pb.ChaincodeMessage if ccMsg, _ = mockResp.RespMsg.(*pb.ChaincodeMessage); ccMsg == nil { if ccMsgFunc, ok := mockResp.RespMsg.(func(*pb.ChaincodeMessage) *pb.ChaincodeMessage); ok && ccMsgFunc != nil { ccMsg = ccMsgFunc(msg) } } if ccMsg == nil { panic("----no pb.ChaincodeMessage---") } err = s.Send(ccMsg) } s.respIndex = s.respIndex + 1 if s.respIndex == len(s.respSet.Responses) { if s.respSet.DoneFunc != nil { s.respSet.DoneFunc(s.respIndex, nil) } } } return err }
17a.go
package main import ( "fmt" "github.com/DrJosh9000/adventofcode/2019/intcode" ) func main() { vm := intcode.ReadProgram("inputs/17.txt") out := make(chan int) go vm.Run(nil, out) var camera [][]byte var line []byte for x := range out { if x == '\n' { if len(line) > 0 { camera = append(camera, line) } line = nil continue } line = append(line, byte(x)) } if len(line) > 0 { camera = append(camera, line) } if false { for _, l := range camera { fmt.Println(string(l)) } } h, w := len(camera), len(camera[0]) sum := 0
for x := 1; x < w-1; x++ { if camera[y][x] == '.' || camera[y-1][x] == '.' || camera[y+1][x] == '.' || camera[y][x-1] == '.' || camera[y][x+1] == '.' { continue } sum += x * y } } fmt.Println(sum) }
for y := 1; y < h-1; y++ {
fibo_seq.py
""" Nom recursive version of fibo. """ # pythran export fibo(int) # runas fibo(7) def fibo(n): """ fibonaccie compuation. """ a, b = 1, 1
for _ in range(n): a, b = a + b, a return a
Home.js
import BlogList from "./BlogList"; import useFetch from "./UseFetch"; const Home = () => { const { data: blogs, isPending, error, } = useFetch("http://localhost:8000/blogs");
return ( <div className="Home"> {error && <div>{error}</div>} {isPending && <div>Loading...</div>} {blogs && <BlogList blogs={blogs} title="All Blogs !" />} </div> ); }; export default Home;
ArgumentsOfCorrectType.d.ts
import { ValidationContext } from '../index'; /** * Argument values of correct type * * A GraphQL document is only valid if all field argument literal values are * of the type expected by their position. */
export function ArgumentsOfCorrectType(context: ValidationContext): any;
client.rs
use http::header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE, USER_AGENT}; use url::Url; use crate::error::DxrError; use crate::fault::Fault; use crate::traits::{FromDXR, ToParams}; use crate::values::{FaultResponse, MethodCall, MethodResponse}; mod call; pub use call::*; /// default value of the `User-Agent` HTTP header for XML-RPC requests #[cfg_attr(docsrs, doc(cfg(feature = "client")))] pub const DEFAULT_USER_AGENT: &str = concat!("dxr-client-v", env!("CARGO_PKG_VERSION")); /// builder that takes parameters for constructing a [`Client`] based on [`reqwest`] #[derive(Debug)] #[cfg_attr(docsrs, doc(cfg(feature = "client")))] pub struct ClientBuilder { url: Url, headers: HeaderMap, user_agent: Option<&'static str>, } impl ClientBuilder { /// constructor for [`ClientBuilder`] from the URL of the XML-RPC server /// /// This also sets up the default `Content-Type: text/xml` HTTP header for XML-RPC requests. pub fn
(url: Url) -> Self { let mut default_headers = HeaderMap::new(); default_headers.insert(CONTENT_TYPE, HeaderValue::from_static("text/xml")); ClientBuilder { url, headers: default_headers, user_agent: None, } } /// method for overriding the default User-Agent header pub fn user_agent(mut self, user_agent: &'static str) -> Self { self.user_agent = Some(user_agent); self } /// method for providing additional custom HTTP headers /// /// Using [`HeaderName`] constants for the header name is recommended. The [`HeaderValue`] /// argument needs to be parsed (probably from a string) with [`HeaderValue::from_str`] to /// ensure their value is valid. pub fn add_header(mut self, name: HeaderName, value: HeaderValue) -> Self { self.headers.insert(name, value); self } /// build the [`Client`] by setting up and initializing the internal [`reqwest::Client`] /// /// If no custom value was provided for `User-Agent`, the default value /// ([`DEFAULT_USER_AGENT`]) will be used. pub fn build(self) -> Client { let user_agent = self.user_agent.unwrap_or(DEFAULT_USER_AGENT); let builder = self.add_header(USER_AGENT, HeaderValue::from_static(user_agent)); let client = reqwest::Client::builder() .default_headers(builder.headers) .build() .expect("Failed to initialize reqwest client."); Client { url: builder.url, client, } } } fn request_to_body(call: &MethodCall) -> Result<String, DxrError> { let body = [ r#"<?xml version="1.0"?>"#, quick_xml::se::to_string(&call) .map_err(|error| DxrError::invalid_data(error.to_string()))? .as_str(), "", ] .join("\n"); Ok(body) } fn response_to_result(contents: &str) -> Result<MethodResponse, anyhow::Error> { // need to check for FaultResponse first: // - a missing <params> tag is ambiguous (can be either an empty response, or a fault response) // - a present <fault> tag is unambiguous let error2 = match quick_xml::de::from_str(contents) { Ok(fault) => { let response: FaultResponse = fault; return match Fault::try_from(response) { // server fault: return Fault Ok(fault) => Err(fault.into()), // malformed server fault: return DxrError Err(error) => Err(error.into()), }; }, Err(error) => error.to_string(), }; let error1 = match quick_xml::de::from_str(contents) { Ok(response) => return Ok(response), Err(error) => error.to_string(), }; // log errors if the contents could not be deserialized as either response or fault log::debug!("Failed to deserialize response as either value or fault."); log::debug!("Response failed with: {}; Fault failed with: {}", error1, error2); // malformed response: return DxrError::InvalidData Err(DxrError::invalid_data(contents.to_owned()).into()) } /// # XML-RPC client implementation /// /// This type provides a very simple XML-RPC client implementation based on [`reqwest`]. Initialize /// the [`Client`], submit a [`Call`], get a result (or a fault). #[derive(Debug)] #[cfg_attr(docsrs, doc(cfg(feature = "client")))] pub struct Client { url: Url, client: reqwest::Client, } impl Client { fn client(&self) -> &reqwest::Client { &self.client } /// asynchronous method for handling remote procedure calls with XML-RPC /// /// Fault responses from the XML-RPC server are transparently converted into [`Fault`] errors. /// Invalid XML-RPC responses or faults will result in an appropriate [`DxrError`]. pub async fn call<P: ToParams, R: FromDXR>(&self, call: Call<'_, P, R>) -> Result<R, anyhow::Error> { // serialize XML-RPC method call let request = call.as_xml_rpc()?; let body = request_to_body(&request)?; // construct request and send to server let request = self.client().post(self.url.clone()).body(body).build()?; let response = self.client().execute(request).await?; // deserialize XML-RPC method response let contents = response.text().await?; let result = response_to_result(&contents)?; // extract return value (if it is present) if let Some(value) = result.inner() { Ok(R::from_dxr(&value)?) } else { #[cfg(feature = "nil")] { use crate::values::Value; Ok(R::from_dxr(&Value::nil())?) } #[cfg(not(feature = "nil"))] { Err(DxrError::parameter_mismatch(0, 1).into()) } } } }
new
benchmark_cobweb.py
from random import randint from timeit import timeit from matplotlib import pyplot as plt import matplotlib.patches as mpatches def generate_dataset(n_inst, n_attr, n_val): instances = [] for i in range(n_inst): i = {} for j in range(n_attr): i[str(j)] = randint(1, n_val) instances.append(i) return instances def
(n_inst, n_attr, n_val): return timeit('tree.fit(x)', setup=('from __main__ import generate_dataset; ' 'from concept_formation.cobweb import CobwebTree; ' 'tree = CobwebTree(); ' 'x = generate_dataset(%i, %i, %i)' % (n_inst, n_attr, n_val)), number=1) if __name__ == "__main__": # 5 attributes sizes = [10, 30, 60, 120, 180, 220] times = [time(i, 5, 5) for i in sizes] plt.plot(sizes, times, 'ro') plt.plot(sizes, times, 'r-') # 10 attributes times = [time(i, 10, 5) for i in sizes] plt.plot(sizes, times, 'bo') plt.plot(sizes, times, 'b-') # 20 attributes times = [time(i, 20, 5) for i in sizes] plt.plot(sizes, times, 'go') plt.plot(sizes, times, 'g-') red_patch = mpatches.Patch(color='red', label='# attr=5') blue_patch = mpatches.Patch(color='blue', label='# attr=10') green_patch = mpatches.Patch(color='green', label='# attr=20') plt.legend(handles=[red_patch, blue_patch, green_patch], loc=2) plt.xlabel('Number of training instances (5 possible values / attr)') plt.ylabel('Runtime in Seconds') plt.show()
time
dc_graph_get_report_depot_utilization_v1_api.py
# coding: utf-8 """ VAAS API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 0.0.1 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from openapi_client.api_client import ApiClient from openapi_client.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class DcGraphGetReportDepotUtilizationV1Api(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def v1_vaas_reports_dbname_depot_utilization_get(self, dbname, module, **kwargs): # noqa: E501
def v1_vaas_reports_dbname_depot_utilization_get_with_http_info(self, dbname, module, **kwargs): # noqa: E501 """v1_vaas_reports_dbname_depot_utilization_get # noqa: E501 Get a dc report from certain database. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_vaas_reports_dbname_depot_utilization_get_with_http_info(dbname, module, async_req=True) >>> result = thread.get() :param dbname: (required) :type dbname: str :param module: Name of the module. (required) :type module: str :param time_range: Time range for the report. :type time_range: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _return_http_data_only: response data without head status code and headers :type _return_http_data_only: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(InlineResponse200, status_code(int), headers(HTTPHeaderDict)) """ local_var_params = locals() all_params = [ 'dbname', 'module', 'time_range' ] all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth' ] ) for key, val in six.iteritems(local_var_params['kwargs']): if key not in all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method v1_vaas_reports_dbname_depot_utilization_get" % key ) local_var_params[key] = val del local_var_params['kwargs'] # verify the required parameter 'dbname' is set if self.api_client.client_side_validation and ('dbname' not in local_var_params or # noqa: E501 local_var_params['dbname'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `dbname` when calling `v1_vaas_reports_dbname_depot_utilization_get`") # noqa: E501 # verify the required parameter 'module' is set if self.api_client.client_side_validation and ('module' not in local_var_params or # noqa: E501 local_var_params['module'] is None): # noqa: E501 raise ApiValueError("Missing the required parameter `module` when calling `v1_vaas_reports_dbname_depot_utilization_get`") # noqa: E501 collection_formats = {} path_params = {} if 'dbname' in local_var_params: path_params['dbname'] = local_var_params['dbname'] # noqa: E501 query_params = [] if 'module' in local_var_params and local_var_params['module'] is not None: # noqa: E501 query_params.append(('module', local_var_params['module'])) # noqa: E501 if 'time_range' in local_var_params and local_var_params['time_range'] is not None: # noqa: E501 query_params.append(('time_range', local_var_params['time_range'])) # noqa: E501 header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['*/*', 'application/json']) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 response_types_map = { 200: "InlineResponse200", 408: None, 500: None, } return self.api_client.call_api( '/v1/vaas/reports/{dbname}/depot-utilization', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_types_map=response_types_map, auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats, _request_auth=local_var_params.get('_request_auth'))
"""v1_vaas_reports_dbname_depot_utilization_get # noqa: E501 Get a dc report from certain database. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.v1_vaas_reports_dbname_depot_utilization_get(dbname, module, async_req=True) >>> result = thread.get() :param dbname: (required) :type dbname: str :param module: Name of the module. (required) :type module: str :param time_range: Time range for the report. :type time_range: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :type _preload_content: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: InlineResponse200 """ kwargs['_return_http_data_only'] = True return self.v1_vaas_reports_dbname_depot_utilization_get_with_http_info(dbname, module, **kwargs) # noqa: E501
interface.ts
import { LinearGauge } from '../linear-gauge'; import { Axis, Pointer } from '../axes/axis'; import { Annotation, TooltipSettings } from '../model/base'; import { FontModel } from '../model/base-model'; import { Size, GaugeLocation } from '../utils/helper'; /** * @private * Specifies LienarGauge Events */ /** @private */ export interface ILinearGaugeEventArgs { name: string; cancel: boolean; } /** * Gauge Loaded event arguments */ export interface ILoadedEventArgs extends ILinearGaugeEventArgs { /** * event argument gauge */ gauge: LinearGauge;
*/ export interface ILoadEventArgs extends ILinearGaugeEventArgs { /** * event argument gauge */ gauge: LinearGauge; } /** * Gauge animation completed event arguments */ export interface IAnimationCompleteEventArgs extends ILinearGaugeEventArgs { /** * event argument axis */ axis: Axis; /** * event argument pointer */ pointer: Pointer; } /** * Gauge axis label rendering event arguments * @deprecated */ export interface IAxisLabelRenderEventArgs extends ILinearGaugeEventArgs { /** * event argument axis */ axis: Axis; /** * event argument text */ text: string; /** * event argument value */ value: number; } /** * Gauge tooltip event arguments * @deprecated */ export interface ITooltipRenderEventArgs extends ILinearGaugeEventArgs { /** * Instance of linear gauge component. */ gauge: LinearGauge; /** * Tooltip event */ event: PointerEvent; /** * Render the tooltip content */ content?: string; /** * Tooltip configuration */ tooltip?: TooltipSettings; /** * Render the tooltip location */ location?: GaugeLocation; /** * event argument axis */ axis: Axis; /** * event argument pointer */ pointer: Pointer; } /** * Gauge annotation render event arguments * @deprecated */ export interface IAnnotationRenderEventArgs extends ILinearGaugeEventArgs { /** * event argument content */ content?: string; /** * event argument text style */ textStyle?: FontModel; /** * event argument annotation */ annotation: Annotation; } /** * Gauge mouse events args * @deprecated */ export interface IMouseEventArgs extends ILinearGaugeEventArgs { /** * event argument linear gauge model */ model?: LinearGauge; /** * event argument target */ target: Element; /** * event argument x position */ x: number; /** * event argument y position */ y: number; } /** * Gauge resize event arguments */ export interface IResizeEventArgs { /** * event name */ name: string; /** * event argument previous size */ previousSize: Size; /** * event argument current size */ currentSize: Size; /** * event argument gauge */ gauge: LinearGauge; } /** * Gauge value change event arguments */ export interface IValueChangeEventArgs { /** * event name */ name: string; /** * event argument gauge */ gauge?: LinearGauge; /** * event argument element */ element: Element; /** * event argument axis index */ axisIndex: number; /** * event argument axis */ axis?: Axis; /** * event argument pointer index */ pointerIndex: number; /** * event argument pointer */ pointer?: Pointer; /** * event argument value */ value: number; } /** @private */ export interface IVisiblePointer { axis?: Axis; axisIndex?: number; pointer?: Pointer; pointerIndex?: number; } /** @private */ export interface IMoveCursor { pointer?: boolean; style?: string; } export interface IThemeStyle { backgroundColor: string; titleFontColor: string; tooltipFillColor: string; tooltipFontColor: string; lineColor: string; labelColor: string; majorTickColor: string; minorTickColor: string; pointerColor: string; fontFamily?: string; fontSize?: string; labelFontFamily?: string; tooltipFillOpacity?: number; tooltipTextOpacity?: number; containerBackground?: string; }
} /** * Gauge Load event arguments * @deprecated
fesom2gdal.py
# Save the geometry (triangles, verticies) of a FESOM grid to a gdal dataset # Author: R. Rietbroek # Date 17 May 2019 # Currently this save the surface nodes only # Improvements are possible # * Optionally store the 3D surfaces # * add info on e.g. bathymetry the nodes # * import osgeo,ogr as ogr import osgeo.osr as osr def fesom2gdal(mesh,outputname,gdaldriver='GPKG'): """Export a FESOM surface mesh to a GIS shapefile input: mesh a FESOM mesh loaded with fesom_mesh(meshpath, get3d=True) outputname: the name of the output dataset gdaldriver: the driver to use to write the output (defaults to geopackage, but could be anything the gdal library supports including POSTGIS) returns: nothing""" driver = ogr.GetDriverByName(gdaldriver) data_source = driver.CreateDataSource(outputname) # create the spatial reference, WGS84 srs = osr.SpatialReference() srs.ImportFromEPSG(4326) # create the layer containing the vertices vertlayer = data_source.CreateLayer("vert", srs, ogr.wkbPoint) field_onbound = ogr.FieldDefn("onboundary", ogr.OFTInteger) vertlayer.CreateField(field_onbound) field_topo = ogr.FieldDefn("topo", ogr.OFTReal) vertlayer.CreateField(field_topo) #also store the indices of the 3Delems for the corresponding z-levels (to look up 3d indices) # NOTE: ESRI SHapefiles do not support lists as attributes!! so this will not be registered when field_zindx=ogr.FieldDefn("nodeid",ogr.OFTIntegerList) vertlayer.CreateField(field_zindx) # add vertices for id,(lon,lat,onbnd) in enumerate(zip(mesh.x2,mesh.y2,mesh.ind2d)): feature = ogr.Feature(vertlayer.GetLayerDefn()) # Note: we need a conversion to int so the value get's accepted by the gdal library feature.SetField("onboundary", int(onbnd)) feature.SetField('topo',mesh.topo[id]) # note: we subtract 1 here to be consistent with the zero-indexing used in nodeid idxfield=feature.GetFieldIndex("nodeid") feature.SetFieldIntegerList(idxfield,[int(x-1) for x in mesh.n32[id,:] if x >=0]) #create a point geometry point = ogr.Geometry(ogr.wkbPoint) point.AddPoint(lon,lat) feature.SetGeometry(point) vertlayer.CreateFeature(feature) # Dereference the feature in order to appropriately call the destructor feature = None # create the layer containing the triangles # NOTE: the dedicated triangle type is not visible in Qgis # surftype=ogr.wkbTriangle surftype=ogr.wkbPolygon tinlayer = data_source.CreateLayer("tin", srs, ogr.wkbTriangle)
tinlayer.CreateField(field_nodeid) field_area = ogr.FieldDefn("area", ogr.OFTReal) tinlayer.CreateField(field_area) field_topo = ogr.FieldDefn("topo", ogr.OFTReal) tinlayer.CreateField(field_topo) # exclude cyclic elements elem2=mesh.elem[mesh.no_cyclic_elem,:] #loop over triangular elements for i1,i2,i3 in elem2: feature = ogr.Feature(tinlayer.GetLayerDefn()) ring=ogr.Geometry(ogr.wkbLinearRing) tri=ogr.Geometry(surftype) ring.AddPoint(mesh.x2[i1],mesh.y2[i1]) ring.AddPoint(mesh.x2[i2],mesh.y2[i2]) ring.AddPoint(mesh.x2[i3],mesh.y2[i3]) tri.AddGeometry(ring) idxfield=feature.GetFieldIndex("nodeid") feature.SetFieldIntegerList(idxfield,[int(i1),int(i2),int(i3)]) # TODO convert to squared km (which projection is used for FESOM??) feature.SetField("area", tri.Area()) #currently just set topo to the mean of the topo of the vertices feature.SetField("topo", (mesh.topo[i1]+mesh.topo[i2]+mesh.topo[i3])/3.0) feature.SetGeometry(tri) tinlayer.CreateFeature(feature) feature=None # Save and close the data source data_source = None
# Add the fields we're interested in (nodeid's of field_nodeid = ogr.FieldDefn("nodeid", ogr.OFTIntegerList)
cli.ts
#!/usr/bin/env node import * as args from "command-line-args"; import * as cmdusage from "command-line-usage"; import * as fs from "fs"; import * as path from "path"; import { Compiler } from "./components/Compiler/Compiler"; import { ConsoleHelper } from "./helpers/ConsoleHelper"; const cmdOptions = [ { name: "compile", alias: "c", type: String, typeLabel: "{underline schema-directory} {underline output-directory}", description: "Compile schema directory into output directory", multiple: true, }, { name: "help", alias: "h", description: "Print this usage guide.", }, { name: "logical-types", type: String, typeLabel: "{underline logical-type} {underline typescript-type}", description: "Use logical types", multiple: true, }, ]; const usageOptions = [ { header: "avro-to-typescript", content: "Compile avro schemas to typescript classes with ease. It will output to set directory " + "and append namespace to path.", }, { header: "Options", optionList: cmdOptions, }, { content: "Project home: {underline https://github.com/degordian/avro-to-typescript}", }, ]; let options; let usage; try { options = args(cmdOptions); console.log(options); usage = cmdusage(usageOptions); } catch (e) { ConsoleHelper.break("Invalid value or option used"); } if (options === undefined) {
let schemaDir = options.compile[0]; let classDir = options.compile[1]; if (schemaDir === undefined || classDir === undefined) { ConsoleHelper.break("Undefined"); } classDir = path.resolve(classDir); schemaDir = path.resolve(schemaDir); if (!fs.existsSync(schemaDir) || !fs.existsSync(classDir)) { ConsoleHelper.break("The directory does not exist or is invalid"); } const logicalTypes = {}; const logicalTypesMap = options["logical-types"]; if (logicalTypesMap && logicalTypesMap.length) { for (let index = 0; index < logicalTypesMap.length; index += 2) { if (!logicalTypesMap[index + 1]) { ConsoleHelper.break("Invalid logical-types, you must alternate logical type with typescript type"); } logicalTypes[logicalTypesMap[index]] = logicalTypesMap[index + 1]; } } const compiler: Compiler = new Compiler(classDir, logicalTypes); compiler.compileFolder(schemaDir); } if (options.help !== undefined) { console.log(usage); }
throw new Error(); } if (options.compile) {
index.js
'use strict'; var path = require('path'); var _ = require('lodash'); // if self signed CA //http://stackoverflow.com/questions/20433287/node-js-request-cert-has-expired process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; function requiredProcessEnv(name) { if(!process.env[name]) { throw new Error('You must set the ' + name + ' environment variable'); } return process.env[name]; } // All configurations will extend these options // ============================================ var all = { env: process.env.NODE_ENV || 'development', // Root path of server root: path.normalize(__dirname + '/../../..'), // Server port port: process.env.PORT || 9000, // Secret for session, you will want to change this and make it an environment variable secrets: { session: 'trunk-secret' }, // List of user roles userRoles: ['guest', 'user', 'admin'], // MongoDB connection options mongo: { options: { db: { safe: true } } }, }; /** * If env var CONFIG_PATH is set path is * CONFIG_PATH/$NODE_ENV.js * otherwise * ./$NODE_ENV.js */ function
() { var configPath = process.env.CONFIG_PATH; if(configPath) { //remove / at end if(configPath.substr(configPath.length - 1) === '/') { configPath = configPath.substr(0, configPath.length-1); } return process.env.CONFIG_PATH + '/' + all.env + '.js'; } else { return './' + all.env + '.js'; } } // Export the config object based on the NODE_ENV // ============================================== module.exports = _.merge( all, require(getEnvConfigPath()) || {} );
getEnvConfigPath
reset.js
/** * * Reset the device by clearing the device un- and reinstalling app package (if existing). * * <example> :resetApp.js browser.reset() * </example> * * @see https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/appium-bindings.md#reset * @type mobile * @for android * */ export default function
() { return this.requestHandler.create({ path: '/session/:sessionId/appium/app/reset', method: 'POST' }) }
reset
bdist_wininst.py
# Copyright (c) 2020 # Author: xiaoweixiang import distutils.command.bdist_wininst as orig class bdist_wininst(orig.bdist_wininst): def reinitialize_command(self, command, reinit_subcommands=0): """
http://bugs.python.org/issue20819 """ cmd = self.distribution.reinitialize_command( command, reinit_subcommands) if command in ('install', 'install_lib'): cmd.install_lib = None return cmd def run(self): self._is_running = True try: orig.bdist_wininst.run(self) finally: self._is_running = False
Supplement reinitialize_command to work around
AuthRoutes.ts
import express from "express"; import { Request, Response, NextFunction } from "express"; import config from "@config/auth"; import { CategoryController } from "@modules/Categories/infra/http/controllers/CategoryController"; import { UserController } from "@modules/Users/infra/http/controllers/UserController"; import { ProductController } from "@modules/Products/infra/http/controllers/ProductController"; import { CheckRoles } from "@modules/Users/infra/http/middlewares/CheckRoles"; import { verify } from "jsonwebtoken"; interface ITokenPayload { iat: number; exp: number; sub: string; info: any; } class
{ public authRoutes: express.Application; constructor() { this.authRoutes = express(); this.routes(); } private routes(): void { this.authRoutes.use(async function ( request: Request, response: Response, next: NextFunction ) { response.header( "Access-Control-Allow-Headers", "Origin, Content-Type, Accept" ); const authHeader = request.headers.authorization; if (!authHeader) { // throw new Error('JWT token is missing.'); return response.status(401).json("JWT token is missing."); } const [_, token] = authHeader.split(" "); try { const { info, sub } = verify(token, config.jwt.secret) as ITokenPayload; request.user = { id: sub, info: info, }; console.log( `Private Route accessed! Username: ${info.username}. JWT Token: ${token}` ); return next(); } catch (err) { // throw new Error('Invalid JWT token'); return response.status(401).json("Invalid JWT token"); } }); // Instânciando classe CheckRoles para verificar // se o usuário é administrador em determinada rota const checkRole = new CheckRoles().isAdmin; //Categories this.authRoutes.post( "/categories", /* #swagger.tags = ["Categories_auth"] */ new CategoryController().createCategory ); this.authRoutes.put( "/categories/:id", /* #swagger.tags = ["Categories_auth"] */ new CategoryController().updateCategory ); this.authRoutes.delete( "/categories/:id", /* #swagger.tags = ["Categories_auth"] */ new CategoryController().deleteCategory ); //Products this.authRoutes.post( "/products", /* #swagger.tags = ["Products_auth"] */ new ProductController().createProducts ); this.authRoutes.put( "/changeProduct/:id", /* #swagger.tags = ["Products_auth"] */ new ProductController().updateProduct ); //Users this.authRoutes.get( "/allUsers", /* #swagger.tags = ["Users_auth"] */ checkRole, new UserController().getAllUsers ); this.authRoutes.get( "/users/roles", /* #swagger.tags = ["Users_auth"] */ checkRole, new UserController().getAllRoles ); this.authRoutes.get( "/users/search/:username", /* #swagger.tags = ["Users_auth"] */ checkRole, new UserController().searchByUsername ); } } export default new AuthRoutes().authRoutes;
AuthRoutes
wallet_test.go
package wallet import ( "bytes" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "net/http/httptest" "sort" "testing" "time" "github.com/tarancss/adp/lib/block" "github.com/tarancss/adp/lib/block/types" "github.com/tarancss/adp/lib/config" "github.com/tarancss/adp/lib/msg/amqp" "github.com/tarancss/adp/lib/store" "github.com/tarancss/adp/lib/store/db" "github.com/tarancss/hd" ) //nolint:funlen,gocognit //test all methods func TestAPI(t *testing.T) { // start a mock blockchain server mock := httptest.NewServer(http.HandlerFunc(mockHandler)) defer mock.Close() t.Logf("Info: running tests against mock blockchain in %s", mock.URL) // connect to DB dbType := db.MONGODB dbURI := "mongodb://localhost:27017" s, _ := db.New(dbType, dbURI) defer db.Close(dbType, s) // connect to msg broker mb, err := amqp.New("amqp://guest:guest@localhost:5672") if err != nil { t.Errorf("Error creating broker:%e", err) return } defer mb.Close() // closing the message broker will stop the go routine launched by the function mb.Setup(nil) // setup the exchanges // load HD wallet seed, err := hex.DecodeString("642ce4e20f09c9f4d285c2b336063eaafbe4cb06dece8134f3a64bdd8f8c0c24df73e1a2e7056359b6db61e179ff45e5ada51d14f07b30becb6d92b961d35df4") //nolint:lll // seed is 64 bytes if err != nil { t.Errorf("Error decoding seed:%e", err) return } hdw, err := hd.Init(seed) if err != nil { t.Errorf("Error initializing HD wallet:%e", err) return } // define a chain at the mock server URL bc, err := block.Init([]config.BlockConfig{{Name: "ropsten", Node: mock.URL, Secret: "", MaxBlocks: 4}}) if err != nil
defer block.End(bc) // set up server for API w := New(db.MONGODB, s, mb, bc, hdw) go w.Init("", "3030", "", "", "") time.Sleep(200 * time.Millisecond) // let the server come up // define tests //nolint:lll // one test case per line cases := []struct { name, method, uri string // case name, http method to use and uri obj interface{} // object for POST, PUT, DELETE err error // error in the http request call status int // http status code errExp string // error expected resExp interface{} // body result expected }{ {"homePage_1", http.MethodGet, "http://localhost:3030", nil, nil, http.StatusOK, "", "Hello, this is your multi-blockchain adaptor!"}, {"homePage_2", http.MethodGet, "http://localhost:3030/", nil, nil, http.StatusOK, "", "Hello, this is your multi-blockchain adaptor!"}, {"homePage_3", http.MethodPost, "http://localhost:3030/", nil, nil, http.StatusOK, "", "Hello, this is your multi-blockchain adaptor!"}, {"networks_0", http.MethodPost, "http://localhost:3030/networks", nil, nil, 405, "", []string{}}, {"networks_1", http.MethodGet, "http://localhost:3030/networks", nil, nil, 200, "", []string{"ropsten"}}, {"addrbal_0", http.MethodPost, "http://localhost:3030/address/0x?tok=0x", nil, nil, 405, "", ""}, {"addrbal_1", http.MethodGet, "http://localhost:3030/address/0x", nil, nil, 200, "", []addrBalance{{Net: "ropsten", Bal: "0", Tok: "0"}}}, {"addrbal_2", http.MethodGet, "http://localhost:3030/address/0x?tok=0x", nil, nil, 200, "", []addrBalance{{Net: "ropsten", Bal: "0", Tok: "0"}}}, {"addrbal_3", http.MethodGet, "http://localhost:3030/address/0xcba75F167B03e34B8a572c50273C082401b073Ed", nil, nil, 200, "", []addrBalance{{Net: "ropsten", Bal: "1615796230433485760", Tok: "0"}}}, {"addrbal_4", http.MethodGet, "http://localhost:3030/address/0xcba75F167B03e34B8a572c50273C082401b073Ed?tok=0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f", nil, nil, 200, "", []addrBalance{{Net: "ropsten", Bal: "1615796230433485760", Tok: "751000000000000000"}}}, {"address_0", http.MethodGet, "http://localhost:3030/address?wallet=2&change=external&id=1", nil, nil, http.StatusOK, "", "0xf4cefc8d1afaa51d5a5e7f57d214b60429ca4378"}, {"address_1", http.MethodPost, "http://localhost:3030/address?wallet=2&change=external&id=1", nil, nil, http.StatusMethodNotAllowed, "", ""}, {"address_2", http.MethodGet, "http://localhost:3030/address?wallet=2&id=1", nil, nil, http.StatusBadRequest, ErrBadrequest.Error(), ""}, {"listen_0", http.MethodGet, "http://localhost:3030/listen/0xcba75F167B03e34B8a572c50273C082401b073Ed", nil, nil, http.StatusBadRequest, ErrMissingNet.Error(), ""}, {"listen_1", http.MethodGet, "http://localhost:3030/listen/0xcba75F167B03e34B8a572c50273C082401b073Ed?net=ropsten", nil, nil, http.StatusBadRequest, ErrBadMethod.Error(), ""}, {"listen_2", http.MethodPost, "http://localhost:3030/listen/0xcba75F167B03e34B8a572c50273C082401b073Ed?net=ropsten&net=rinkeby", nil, nil, http.StatusBadRequest, ErrMissingNet.Error(), ""}, {"listen_3", http.MethodPost, "http://localhost:3030/listen/0xcba75F167B03e34B8a572c50273C082401b073Ed?net=ropsten", nil, nil, http.StatusAccepted, "", ""}, {"listen_4", http.MethodDelete, "http://localhost:3030/listen/0xcba75F167B03e34B8a572c50273C082401b073Ed?net=ropsten", nil, nil, http.StatusAccepted, "", ""}, {"getAdr_0", http.MethodPost, "http://localhost:3030/listen", nil, nil, http.StatusMethodNotAllowed, "", ""}, {"getAdr_1", http.MethodGet, "http://localhost:3030/listen?net=mainNet", nil, nil, http.StatusAccepted, "", []store.ListenedAddresses{}}, {"getAdr_2", http.MethodGet, "http://localhost:3030/listen", nil, nil, http.StatusAccepted, "", []store.ListenedAddresses{{Net: "ropsten", Addr: []store.Address{}}}}, {"getAdr_3", http.MethodGet, "http://localhost:3030/listen?net=ropsten", nil, nil, http.StatusAccepted, "", []store.ListenedAddresses{{Net: "ropsten", Addr: []store.Address{}}}}, {"send_0", http.MethodPut, "http://localhost:3030/send", nil, nil, http.StatusMethodNotAllowed, "", ""}, {"send_1", http.MethodPost, "http://localhost:3030/send", TxReq{Net: "rinkeby"}, nil, http.StatusNotFound, "network not available", types.Trans{}}, {"send_2", http.MethodPost, "http://localhost:3030/send", TxReq{Net: "ropsten", Wallet: 2, Change: 0, ID: 1, Tx: types.Trans{To: "0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", Value: "0x565656"}}, nil, http.StatusAccepted, "", types.Trans{To: "0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", Value: "0x565656", Hash: "0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", Status: 0, From: "0xf4cefc8d1afaa51d5a5e7f57d214b60429ca4378"}}, {"tx_0", http.MethodPut, "http://localhost:3030/tx/0x123456", nil, nil, http.StatusMethodNotAllowed, "", types.Trans{}}, {"tx_1", http.MethodGet, "http://localhost:3030/tx/0x123456", nil, nil, http.StatusBadRequest, ErrNoHash.Error(), types.Trans{}}, {"tx_2", http.MethodGet, "http://localhost:3030/tx/0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", nil, nil, http.StatusBadRequest, ErrNoNet.Error(), types.Trans{}}, {"tx_3", http.MethodGet, "http://localhost:3030/tx/0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872?net=mainNet", nil, nil, http.StatusBadRequest, ErrNoNet.Error(), types.Trans{}}, {"tx_4", http.MethodGet, "http://localhost:3030/tx/0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872?net=ropsten", nil, nil, http.StatusBadRequest, "cannot get transaction for hash 0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872: hash of transaction does not match with requested hash", types.Trans{}}, {"tx_5", http.MethodGet, "http://localhost:3030/tx/0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872?net=ropsten", nil, nil, http.StatusOK, "", types.Trans{To: "0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", Value: "0x565656", Hash: "0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", Status: 0, From: "0xf4cefc8d1afaa51d5a5e7f57d214b60429ca4378"}}, } // run tests for _, c := range cases { // make http request to API s, b, e, err := makeRequest(c.method, c.uri, c.obj) // check error in call, StatusCode and error response if err != c.err { t.Errorf("[%s] Error in response:%e expected:%e", c.name, err, c.err) } else if s != c.status { t.Errorf("[%s] Error in StatusCode:%d expected:%d", c.name, s, c.status) } else if e != c.errExp { t.Errorf("[%s] Error in response:%s expected:%s", c.name, e, c.errExp) } else { // unmarshal and test body response if s < http.StatusBadRequest { switch c.name[:len(c.name)-2] { case "homepage", "address": if b != c.resExp { t.Errorf("[%s] Error in response:%s expected:%s", c.name, b, c.resExp) } case "network": var got []string if err = json.Unmarshal([]byte(b), &got); err != nil { t.Errorf("[%s] Error unmarshaling body:%s error:%s", c.name, b, err) } sort.Strings(got) exp := c.resExp.([]string) sort.Strings(exp) if len(got) != len(exp) { t.Errorf("[%s] Error in response:%v expected:%v", c.name, got, exp) } else { for i := 0; i < len(exp); i++ { if got[i] != exp[i] { t.Errorf("[%s] Error in response:%v expected:%v", c.name, got, exp) } } } case "addrbal": var sab []addrBalance = []addrBalance{} if err = json.Unmarshal([]byte(b), &sab); err != nil { t.Errorf("[%s] Error unmarshaling body:%s error:%s", c.name, b, err) } // check results if len(sab) != len(c.resExp.([]addrBalance)) || (len(sab) > 0 && len(c.resExp.([]addrBalance)) > 0 && (sab[0].Net != c.resExp.([]addrBalance)[0].Net || sab[0].Bal != c.resExp.([]addrBalance)[0].Bal || sab[0].Tok != c.resExp.([]addrBalance)[0].Tok)) { t.Errorf("[%s] Error in response:%v expected:%v", c.name, sab, c.resExp.([]addrBalance)) } case "listen": if b != "" && b != c.resExp.(string) { t.Errorf("[%s] Error in response:%s expected:%s", c.name, b, c.resExp.(string)) } case "getAdr": var sla []store.ListenedAddresses = []store.ListenedAddresses{} if b != "" { if err = json.Unmarshal([]byte(b), &sla); err != nil { t.Errorf("[%s] Error unmarshaling body:%s error:%s", c.name, b, err) } } // check results if len(sla) != len(c.resExp.([]store.ListenedAddresses)) || (len(sla) > 0 && len(c.resExp.([]store.ListenedAddresses)) > 0 && (sla[0].Net != c.resExp.([]store.ListenedAddresses)[0].Net)) { t.Errorf("[%s] Error in response:%v expected:%v", c.name, sla, c.resExp.([]store.ListenedAddresses)) } case "send", "tx": var tx types.Trans if b != "" { if err = json.Unmarshal([]byte(b), &tx); err != nil { t.Errorf("[%s] Error unmarshaling body:%s error:%s", c.name, b, err) } } // check result if tx.Hash != c.resExp.(types.Trans).Hash || tx.To != c.resExp.(types.Trans).To || tx.From != c.resExp.(types.Trans).From || tx.Value != c.resExp.(types.Trans).Value { t.Errorf("[%s] Error in response:%v expected:%v", c.name, tx, c.resExp.(types.Trans)) } } } } } w.Stop() } // makeRequest places a http request on uri. Depending on method it will include obj in the request (ie. for POST). // Returns the status code, the body and error fields of the received JSON response. //nolint:bodyclose,noctx // body is closed at the end, context not required for tests func makeRequest(method, uri string, obj interface{}) (s int, b, e string, err error) { var resp *http.Response switch method { case http.MethodGet: if resp, err = http.Get(uri); err != nil { return } case http.MethodPost: var pl []byte switch v := obj.(type) { case TxReq: if pl, err = json.Marshal(v); err != nil { return } default: if pl, err = json.Marshal(v); err != nil { return } } if resp, err = http.Post(uri, "application/json;charset=utf8", bytes.NewBuffer(pl)); err != nil { return } case http.MethodDelete, http.MethodPut: client := &http.Client{} var req *http.Request if req, err = http.NewRequest(method, uri, nil); err != nil { return } if resp, err = client.Do(req); err != nil { return } default: err = errors.New("method not found!!") //nolint:goerr113 // we are testing return } s = resp.StatusCode var v struct { B string `json:"body"` E string `json:"error"` } if resp.ContentLength > 0 { var p []byte = make([]byte, int(resp.ContentLength)) n, _ := resp.Body.Read(p) resp.Body.Close() err = json.Unmarshal(p[:n], &v) } return s, v.B, v.E, err //nolint:wrapcheck // we are testing } type mockRequest struct { Version string `json:"jsonrpc"` Method string `json:"method"` Params *json.RawMessage `json:"params"` ID *json.RawMessage `json:"id"` } type mockResponse struct { Version string `json:"jsonrpc"` ID *json.RawMessage `json:"id"` Result interface{} `json:"result,omitempty"` Error interface{} `json:"error,omitempty"` } // mockHandler defines the handler function for mock HTTP server. //nolint:gochecknoglobals // used by all tests var mockHandler = func(w http.ResponseWriter, r *http.Request) { var req mockRequest var res mockResponse var err error // make sure we reply to request either with error or the response defer func() { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) res.Version = "2.0" if err = json.NewEncoder(w).Encode(res); err != nil { fmt.Printf("[Mock server] Error encoding response:%e\n", err) } }() // read request body var body []byte = make([]byte, int(r.ContentLength)) var n int n, err = r.Body.Read(body) if err == nil || (errors.Is(err, io.EOF) && n == int(r.ContentLength)) { // fmt.Printf("[Mock server] Request Body:%s", body) // (un)comment this line for less/more verbosity } else { res.Error = fmt.Errorf("n:%d error:%w\n", n, err) return } // unmarshal JSON body if err = json.Unmarshal(body, &req); err != nil { res.Error = fmt.Errorf("error unmarshaling body: %w\n", err) return } res.ID = req.ID // reply with expected value var i int var buf []byte = []byte(*res.ID) for j := 0; j < len(buf); j++ { i = i*10 + int(buf[j]-0x30) } res.Result = mock[i] } // mock contains the data used by the mock server. //nolint:lll,gochecknoglobals // test data var mock []interface{} = []interface{}{ // addrBal_1 "0x00", // addrBal_2 "0x00", "0x0000000000000000000000000000000000000000000000000000000000000000", // addrBal_3 "0x166c761c586733c0", // addrBal_4 "0x166c761c586733c0", "0x0000000000000000000000000000000000000000000000000a6c168562518000", // send_2 "0x10", // getTransactionCount "0x100000", // getGasPrice "0x5208", // estimateGas "0x", // sendRawTransaction // tx_3 map[string]interface{}{"blockHash": "0xd44a255e40eee23bd90a54a792f7a35c175400958de22a9bbfe08a7b2c244ed6", "blockNumber": "0x29bf9b", "from": "0x1cd434711fbae1f2d9c70001409fd82d71fdccaa", "gas": "0xff59", "gasPrice": "0x98bca5a00", "hash": "0xdbd3184b2f947dab243071000df22cf5acc6efdce90a04aaf057521b1ee5bf60", "input": "0x", "nonce": "0x0", "r": "0xb506e6cf81364d01c126028ec0acb771ca372269c8b157e551238a1e2d1b7ecb", "s": "0x2d7ea699220630938f57fe05fa581abd5a21f3aa105668a7128fba49598bbd70", "to": "0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f", "transactionIndex": "0x1", "v": "0x29", "value": "0x16345785d8a0000"}, // tx_4 (3 calls to node) map[string]interface{}{"blockHash": "0xd44a255e40eee23bd90a54a792f7a35c175400958de22a9bbfe08a7b2c244ed6", "blockNumber": "0x29bf9b", "from": "0xf4cefc8d1afaa51d5a5e7f57d214b60429ca4378", "gas": "0xff59", "gasPrice": "0x98bca5a00", "hash": "0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", "input": "0x", "nonce": "0x0", "r": "0xb506e6cf81364d01c126028ec0acb771ca372269c8b157e551238a1e2d1b7ecb", "s": "0x2d7ea699220630938f57fe05fa581abd5a21f3aa105668a7128fba49598bbd70", "to": "0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", "transactionIndex": "0x1", "v": "0x29", "value": "0x565656"}, map[string]interface{}{"blockHash": "0xd44a255e40eee23bd90a54a792f7a35c175400958de22a9bbfe08a7b2c244ed6", "blockNumber": "0x29bf9b", "contractAddress": nil, "cumulativeGasUsed": "0x4fa3d", "from": "0xf4cefc8d1afaa51d5a5e7f57d214b60429ca4378", "gas": "0xff59", "gasPrice": "0x98bca5a00", "gasUsed": "0xf67f", "hash": "0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", "input": "0x", "logs": map[string]interface{}{"address": "0xa34de7bd2b4270c0b12d5fd7a0c219a4d68d732f", "blockHash": "0xd44a255e40eee23bd90a54a792f7a35c175400958de22a9bbfe08a7b2c244ed6", "blockNumber": "0x29bf9b", "data": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000", "logIndex": "0x2", "removed": false, "topics": []string{"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000008bac1770a2826111c0e773f39827c1cfa031a21e", "0x0000000000000000000000001cd434711fbae1f2d9c70001409fd82d71fdccaa"}, "transactionHash": "0xdbd3184b2f947dab243071000df22cf5acc6efdce90a04aaf057521b1ee5bf60", "transactionIndex": "0x1"}, "logsBloom": "0x00000000000000000000000000000000800000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000008000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000010000000020000000000000000000000000000000000000000000000002000000000000000000100000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000", "nonce": "0x0", "r": "0xb506e6cf81364d01c126028ec0acb771ca372269c8b157e551238a1e2d1b7ecb", "s": "0x2d7ea699220630938f57fe05fa581abd5a21f3aa105668a7128fba49598bbd70", "status": "0x1", "to": "0x357dd3856d856197c1a000bbAb4aBCB97Dfc92c4", "transactionHash": "0x2ba030485e79b5a98275b45d940e6fdd07b40dea593ef3b2a69b0a02a68a5872", "transactionIndex": "0x1", "v": "0x29", "value": "0x565656"}, map[string]interface{}{"difficulty": "0x73622046", "extraData": "0xde8302050c8f5061726974792d457468657265756d86312e33382e30826c69", "gasLimit": "0x7a121d", "gasUsed": "0x2120e6", "hash": "0xd44a255e40eee23bd90a54a792f7a35c175400958de22a9bbfe08a7b2c244ed6", "logsBloom": "0x00000008000000000000200000000000020000000040000000000000000000000000000020008000000000001000000000000200000000004000800080000000000000000000000000000008000000000000004000000000000000000000000000000400005000880000000000400020000004000000000008000010000000000000000000000000000000000800002000000000000000000000100000000000000000000000000020000000000000000000000000000000020000000000000000000002400000000402000000200000000000000000004000400000000401000000000000000040000000000000000001000108000000000000001000000000", "miner": "0x635b4764d1939dfacd3a8014726159abc277becc", "mixHash": "0x0d186ce62b77e466e4f66b30d1bbeff71b210f3bce72a6f7210a34edf84d9d98", "nonce": "0x87cce426abc7bcd5", "number": "0x29bf9b", "parentHash": "0x89cde9ba035de527c0fc03dd816e8205cb9c52bd9b7dc79567e72adce2460686", "receiptsRoot": "0x572216203b3b24631ea63c2f366f4d15612b6b120590350f3b8dffb69c6549bc", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": "0x1936", "stateRoot": "0xd6805cc98512c0f1f0086761f15a5bcbeb45db4c4b30997d08ca50511b127d72", "timestamp": "0x5dfeaab3", "totalDifficulty": "0x6912173ecef77f", "transactions": []string{"0x8f138401bff60dbd947ccdf9eceef46c8e0ccd97043027de566c42f022a8abcc", "0x8b2db064cdeacff34f18eb16c74298f6b5692b095c678759a39e16682c98ea7a", "0xe6ee32f5df6a617bb965df1356842cb9b34c3ccc11049cb9cf2f8a6a6afcc0f9", "0x795aad22918d79ccfe1ef7522b4c147a0fc650014e5f240ed04c16334ab7240c", "0xb8afe6057b31c7c63c5382175da72bd026e0f5b7e05800c5801cc41fb43db798", "0x4411c92db0d7b4b8d77fe53f4111712fc7cdecaa78725076544fbc6abdf2d019", "0xf536f7479394bd241be973677cbffe5fec6d28b536d5f30979281de5c34ceebf", "0x8bafdabef7b99aefeafbd8539e2b7072f4cf56a3c92e20dc2c201f5855ff39b3", "0x5c1e8a3b59838a2b961fcd548ab06fea00273f23e0174dbcf0196213f0da4265", "0x0ef5e2aec0545017fa27a65eeeb45f587098f38ede31a57589d3f5d6f3043bdf", "0x9bcfe01a8242a0d2b422527cd6abc704fab21424bf8c0e7d759b639eff1f8f69", "0xcdbb0dc7d6c661fddfd9c1a728fed43fe65c2eea3380f9688a6fc30e85e20d24", "0x48633a32b409defbd805b07418827c647a2eb29d3f53ccdd22a901a304f7c9c5", "0xb92ebb3c76e8e24950560d370b233d0ab14061be41f830392cf0ceee6f73cc2c", "0x7eef4a0785fe1bf02e8a8c727c4b956f1abf0096e2186b64e8be50f504ad1447", "0x366f653f97a3d2705ece8b76f6df9b0243afbacb838fb80c96e24957ab17b5bc", "0x36e20c01159d2aab0100b00ca2758a4b066c947b051cf71f29a9efea594e57a0", "0x194a774856c85facc98cea05681aea3078b0cbd9ff908b5a7cbe1d70b9d28751", "0xdab4600e32a7f839b47f8d9e6e081b22b4ab744c462f75414f4d43100203e01b", "0xfb2ffb9c643dca812999a3fa4d14c7f78e0b80333789a33bd7ed54521b82ecc5", "0xc4f0690dd1e1c0e3c99418529da10463c46942979d905abfaf2eb126aeeedc21", "0x85564c0b32204909c77f73c23df7e8484655dde3e62b06f887e6095c79f67f3e", "0xe309317b02143e481a98174c1cfe2a5cfac6b0662f5b1f370fc3f34ee9d8da91", "0x096760b5183b7e53d7e4e74f5e82d92616850eb307e81d9c94fdc5a18e93f670", "0x0bd588bd04af3acb6b5d4bfc699d715aadb3c7084da4ccb21dd1b830d214edd0", "0x0e3875750c6292529ce4e1a8d407f478fb78bdfc20ee328f5a88558e0ccc3de3", "0x2e476d344e24108e215f3f110b2315c53ef47552f434b3746e1df9ae42fc65be", "0xa26bf3698db9b0664fcd91296642e31918faafe94794bf59f3a251196d3d06a3", "0x8eabd6f7894194cc6e523a30ffd4ccb41b87219f52460a93aac31114dd54c1bc", "0xba414f298d033d570db3fa83611f3f9be4e91a01d4dfcdcb2fb06fee02332cfd", "0xeb2dee95e748feca129635bef1ab2b22ff6695306ddd653185382861db1c7f51", "0x2fb5cca0931f44bb5a1169f7b3aad7defbe1d78e4b24bdc4da19313193000c81", "0x38e67f95ef6b730bc04da132df3b2530118f9d2963cbd6bb4f750779aa3e5653", "0x33764f5c8e687b7841c50861fac9770f0f4f3fe09ef9f713137dbe806516449c", "0x83cf99e79755a0604bfee68daa7ab81b2f14e5ba1c8f320b13b24abe4a6517d1", "0x9bc276f828200578c9ee5fcc4ba7459bbf01cc5192ed6aa8aacc34b22a7fd896", "0x18385aea472253973fc2b1266a0b22ff53052107c6345681e74df48f05b2bf6a", "0xce978f61e64a174ee56d3414887270598f574eb5a2038f51685981bafc8c78d7", "0x3f3f895f532d7aab86a0a25f6df799f673d35e27dd48ecb73c76e824fb63d302"}, "transactionsRoot": "0x0ba49975aecff1120685561471fcc58c87d3c270361d56367fd5206cb8957687", "uncles": []string{}}, }
{ t.Errorf("error initializing blockchain client:%e", err) return }
health_test.go
package health import ( "bytes" "github.com/spf13/cobra" "github.com/stretchr/testify/suite" "testing" ) type HealthCmdTestSuite struct { suite.Suite } // TestNewHealthCheckCommand tests that the health check command has been initialised properly func (suite *HealthCmdTestSuite) TestNewHealthCheckCommand() { hc := NewHealthCheckCommand() suite.Equal("health", hc.Use) suite.Equal("Performs a health check call", hc.Short) suite.Equal("The health command is used to perform a health check to the grpc server", hc.Long) suite.True(hc.DisableFlagsInUseLine) } func (suite *HealthCmdTestSuite) TestHealthCheckCmdOutput() { hc := NewHealthCheckCommand() b := new(bytes.Buffer) // test the output of the help option hc.SetArgs([]string{"-h"}) hc.SetOutput(b) hc.Execute() expOut := "The health command is used to perform a health check to the grpc server\n\n" + "Usage:\n" + " health\n\n" + "Flags:\n" + " -h, --help help for health\n" suite.Equal(expOut, b.String()) // test the output of the health option(success) hc2 := NewHealthCheckCommand() b2 := new(bytes.Buffer) hc2.SetArgs([]string{"health"}) hc2.SetOutput(b2) // first override the run function in order to mock it hc2.Run = func(cmd *cobra.Command, args []string) { cmd.Println("Success: SERVING") } hc2.Execute() suite.Equal("Success: SERVING\n", b2.String()) // test the output of the health option(error) b2.Reset() hc2.Run = func(cmd *cobra.Command, args []string) { cmd.Println("Error: NOT_SERVING") } hc2.Execute() suite.Equal("Error: NOT_SERVING\n", b2.String()) } func
(t *testing.T) { suite.Run(t, new(HealthCmdTestSuite)) }
TestHealthCommandTestSuite
windows.rs
use std::mem; use api::win32; use api::wgl; use error::{TubResult, GlCreationResult}; use config::{WindowConfig, PixelFormat}; use {CursorType, WindowType}; pub struct Window<'p>( win32::Window<'p> ); impl<'p> Window<'p> { pub fn new<'a>(config: WindowConfig, pixel_format: PixelFormat) -> TubResult<Window<'p>> { // Because this struct is just a bitwise-equivalent wrapper around a win32 window, we can // just transmute the reference to the result. unsafe{ mem::transmute(win32::Window::new(config, pixel_format)) } } pub fn new_owned<'a>(&'p self, config: WindowConfig, pixel_format: PixelFormat) -> TubResult<Window<'p>> { unsafe{ mem::transmute(self.0.new_owned(config, pixel_format)) } } pub fn new_child<'a>(&'p self, config: WindowConfig, pixel_format: PixelFormat) -> TubResult<Window<'p>> { unsafe{ mem::transmute(self.0.new_child(config, pixel_format)) } } #[inline] pub fn set_title(&self, title: &str) { self.0.wrapper.set_title(title); } #[inline] pub fn show(&self) { self.0.wrapper.show(); } #[inline] pub fn hide(&self) { self.0.wrapper.hide(); } /// Allow the window to take user input. Any newly created window defaults to /// being enabled. #[inline] pub fn enable(&self) { self.0.wrapper.enable(); } /// Disallow the window from taking user input. #[inline] pub fn disable(&self) { self.0.wrapper.disable(); } /// Sets input focus to this window #[inline] pub fn focus(&self) { self.0.wrapper.focus(); } #[inline] pub fn get_inner_pos(&self) -> Option<(i32, i32)> { self.0.wrapper.get_inner_pos() } /// Gets the position of the upper-left corner of the window, including the title bar #[inline] pub fn get_outer_pos(&self) -> Option<(i32, i32)> { self.0.wrapper.get_outer_pos() } #[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { self.0.wrapper.get_inner_size() } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.0.wrapper.get_outer_size() } #[inline] pub fn set_pos(&self, x: i32, y: i32) -> Option<()> { self.0.wrapper.set_pos(x, y) } #[inline] pub fn set_inner_size(&self, x: u32, y: u32) -> Option<()> { self.0.wrapper.set_inner_size(x, y) } #[inline] pub fn is_active(&self) -> bool { self.0.wrapper.is_active() } #[inline] pub fn set_cursor(&self, cursor_type: CursorType) { self.0.wrapper.set_cursor(cursor_type); } #[inline] pub fn set_cursor_pos(&self, x: i32, y: i32) { self.0.set_cursor_pos(x, y); }
pub fn get_type(&self) -> WindowType { use api::win32::WindowType::*; unsafe { match self.0.get_type() { Owned(w) => WindowType::Owned(mem::transmute(w)), Child(w) => WindowType::Child(mem::transmute(w)), Top => WindowType::Top } } } #[inline] pub fn get_config(&self) -> &WindowConfig { self.0.get_config() } #[inline] pub fn get_pixel_format(&self) -> &PixelFormat { self.0.get_pixel_format() } #[inline] pub fn poll_events(&self) -> PollEventsIter { self.0.poll_events() } #[inline] pub fn wait_events(&self) -> WaitEventsIter { self.0.wait_events() } } pub struct GlContext<'w, 'c> ( wgl::GlContext<'w, 'c> ); impl<'w, 'c> GlContext<'w, 'c> { pub fn new(window: &'w Window, shared_context: Option<&'c GlContext>) -> GlCreationResult<GlContext<'w, 'c>> { unsafe{ mem::transmute(wgl::GlContext::new(&window.0, mem::transmute(shared_context))) } } pub unsafe fn make_current(&self) -> TubResult<()> { self.0.make_current() } pub fn get_proc_address(&self, proc_name: &str) -> *const () { self.0.get_proc_address(proc_name) } pub fn swap_buffers(&self) { self.0.swap_buffers() } } pub use api::win32::PollEventsIter; pub use api::win32::WaitEventsIter;
#[inline]
locustfile.py
from locust import HttpLocust, TaskSet, task import json, uuid, io, random, string class UserBehavior(TaskSet): def on_start(self): global token, headers, getId, userId,company #---------- Configurations #user token token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2JhY2suZGV2XC9iYWNrZW5kXC9hcGlcL2F1dGgiLCJpYXQiOjE0OTYxMzE2NDUsImV4cCI6MTQ5NjE1Njg0NSwibmJmIjoxNDk2MTMxNjQ1LCJqdGkiOiI4NmMxZGEzYTgzYThhMDVhYzUxMGYxN2FjMjg1MzU3NyJ9.KMPTAigJcICQeBjzxFCjTUVU2lOkzNwuH5qxKNd7E1M" # id for getId = 1 #user id userId = 9 #company company = 11 #------------------------------- headers = {'Authorization': 'Bearer '+token} #Add new @task(1) def addRoom(self): response = self.client.post("/leads/statuses",json={ "name":self.randomString() }, headers=headers) id = json.loads(response.content)["id"] if int(id) > 0: #update self.client.put("/leads/statuses/"+str(id),json={ "name":self.randomString() },headers=headers,name="/leads/statuses/:id") #delete self.client.delete("/leads/statuses/"+str(id),headers=headers,name="/lead/products/:id") @task(2) def getAll(self):
@task(3) def getById(self): response = self.client.get("/leads/statuses/"+str(getId),headers=headers) def randomString(self): return ''.join(random.choice(string.lowercase) for i in range(10)) def randomInt(self): return str(random.randrange(0, 101, 2)) class WebsiteUser(HttpLocust): task_set = UserBehavior min_wait = 5000 max_wait = 9000
response = self.client.get("/leads/statuses",headers=headers)
crnn_main.py
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import random import torch import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from torch.autograd import Variable import numpy as np from warpctc_pytorch import CTCLoss import os import utils import dataset from keys import alphabet #Alphabet = [e.encode('utf-8') for e in alphabet] import models.crnn as crnn #with open('../run/char.txt') as f: # newChars = f.read().strip().decode('utf-8') #alphabet += u''.join(list(set(newChars) - set(alphabet))) parser = argparse.ArgumentParser() parser.add_argument('--trainroot', help='path to dataset',default='../data/lmdb/train') parser.add_argument('--valroot', help='path to dataset',default='../data/lmdb/val') parser.add_argument('--workers', type=int, help='number of data loading workers', default=4) parser.add_argument('--batchSize', type=int, default=128, help='input batch size') parser.add_argument('--imgH', type=int, default=32, help='the height of the input image to network') parser.add_argument('--imgW', type=int, default=256, help='the width of the input image to network') parser.add_argument('--nh', type=int, default=256, help='size of the lstm hidden state') parser.add_argument('--niter', type=int, default=1000000, help='number of epochs to train for') parser.add_argument('--lr', type=float, default=0.005, help='learning rate for Critic, default=0.00005') parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5') parser.add_argument('--cuda', action='store_true', help='enables cuda') parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use') parser.add_argument('--crnn', help="path to crnn (to continue training)",default='../pretrain-models/netCRNN.pth') #parser.add_argument('--crnn', help="path to crnn (to continue training)",default='') parser.add_argument('--alphabet', default=alphabet) parser.add_argument('--experiment', help='Where to store samples and models',default='./save_model') parser.add_argument('--displayInterval', type=int, default=50, help='Interval to be displayed') parser.add_argument('--n_test_disp', type=int, default=1000, help='Number of samples to display when test') parser.add_argument('--valInterval', type=int, default=50, help='Interval to be displayed') parser.add_argument('--saveInterval', type=int, default=1000, help='Interval to be displayed') parser.add_argument('--adam', action='store_true', help='Whether to use adam (default is rmsprop)') parser.add_argument('--adadelta', action='store_true', help='Whether to use adadelta (default is rmsprop)') parser.add_argument('--keep_ratio', action='store_true', help='whether to keep ratio for image resize') parser.add_argument('--random_sample', action='store_true', help='whether to sample the dataset with random sampler') opt = parser.parse_args() print(opt) ifUnicode=True if opt.experiment is None: opt.experiment = 'expr' os.system('mkdir {0}'.format(opt.experiment)) opt.manualSeed = random.randint(1, 10000) # fix seed print("Random Seed: ", opt.manualSeed) random.seed(opt.manualSeed) np.random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) cudnn.benchmark = True if torch.cuda.is_available() and not opt.cuda: print("WARNING: You have a CUDA device, so you should probably run with --cuda") train_dataset = dataset.lmdbDataset(root=opt.trainroot) assert train_dataset if not opt.random_sample: sampler = dataset.randomSequentialSampler(train_dataset, opt.batchSize) else: sampler = None train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=opt.batchSize, shuffle=True, sampler=sampler, num_workers=int(opt.workers), collate_fn=dataset.alignCollate(imgH=opt.imgH, imgW=opt.imgW, keep_ratio=opt.keep_ratio)) test_dataset = dataset.lmdbDataset( root=opt.valroot, transform=dataset.resizeNormalize((256, 32))) ngpu = int(opt.ngpu) nh = int(opt.nh) alphabet = opt.alphabet nclass = len(alphabet) + 1 nc = 1 converter = utils.strLabelConverter(alphabet) criterion = CTCLoss() # custom weights initialization called on crnn def weights_init(m):
crnn = crnn.CRNN(opt.imgH, nc, nclass, nh, ngpu) crnn.apply(weights_init) if opt.crnn != '': print('loading pretrained model from %s' % opt.crnn) crnn.load_state_dict(torch.load(opt.crnn)) print(crnn) image = torch.FloatTensor(opt.batchSize, 3, opt.imgH, opt.imgH) text = torch.IntTensor(opt.batchSize * 5) length = torch.IntTensor(opt.batchSize) if opt.cuda: crnn.cuda() image = image.cuda() criterion = criterion.cuda() image = Variable(image) text = Variable(text) length = Variable(length) # loss averager loss_avg = utils.averager() # setup optimizer if opt.adam: optimizer = optim.Adam(crnn.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) elif opt.adadelta: optimizer = optim.Adadelta(crnn.parameters(), lr=opt.lr) else: optimizer = optim.RMSprop(crnn.parameters(), lr=opt.lr) def val(net, dataset, criterion, max_iter=2): print('Start val') for p in crnn.parameters(): p.requires_grad = False net.eval() data_loader = torch.utils.data.DataLoader( dataset, shuffle=True, batch_size=opt.batchSize, num_workers=int(opt.workers)) val_iter = iter(data_loader) i = 0 n_correct = 0 loss_avg = utils.averager() max_iter = min(max_iter, len(data_loader)) for i in range(max_iter): data = val_iter.next() i += 1 cpu_images, cpu_texts = data batch_size = cpu_images.size(0) utils.loadData(image, cpu_images) if ifUnicode: cpu_texts = [ clean_txt(tx.decode('utf-8')) for tx in cpu_texts] t, l = converter.encode(cpu_texts) utils.loadData(text, t) utils.loadData(length, l) preds = crnn(image) preds_size = Variable(torch.IntTensor([preds.size(0)] * batch_size)) cost = criterion(preds, text, preds_size, length) / batch_size loss_avg.add(cost) _, preds = preds.max(2) preds = preds.squeeze(2) preds = preds.transpose(1, 0).contiguous().view(-1) sim_preds = converter.decode(preds.data, preds_size.data, raw=False) for pred, target in zip(sim_preds, cpu_texts): if pred.strip() == target.strip(): n_correct += 1 raw_preds = converter.decode(preds.data, preds_size.data, raw=True)[:opt.n_test_disp] #for raw_pred, pred, gt in zip(raw_preds, sim_preds, cpu_texts): #print((pred, gt)) #print accuracy = n_correct / float(max_iter * opt.batchSize) testLoss = loss_avg.val() #print('Test loss: %f, accuray: %f' % (testLoss, accuracy)) return testLoss,accuracy def clean_txt(txt): """ filter char where not in alphabet with ' ' """ newTxt = u'' for t in txt: if t in alphabet: newTxt+=t else: newTxt+=u' ' return newTxt def trainBatch(net, criterion, optimizer,flage=False): data = train_iter.next() cpu_images, cpu_texts = data##decode utf-8 to unicode if ifUnicode: cpu_texts = [ clean_txt(tx.decode('utf-8')) for tx in cpu_texts] batch_size = cpu_images.size(0) utils.loadData(image, cpu_images) t, l = converter.encode(cpu_texts) utils.loadData(text, t) utils.loadData(length, l) preds = crnn(image) preds_size = Variable(torch.IntTensor([preds.size(0)] * batch_size)) cost = criterion(preds, text, preds_size, length) / batch_size crnn.zero_grad() cost.backward() if flage: lr = 0.0001 optimizer = optim.Adadelta(crnn.parameters(), lr=lr) optimizer.step() return cost num =0 lasttestLoss = 10000 testLoss = 10000 import os def delete(path): """ 删除文件 """ import os import glob paths = glob.glob(path+'/*.pth') for p in paths: os.remove(p) numLoss = 0##判断训练参数是否下降 for epoch in range(opt.niter): train_iter = iter(train_loader) i = 0 while i < len(train_loader): #print('The step{} ........\n'.format(i)) for p in crnn.parameters(): p.requires_grad = True crnn.train() #if numLoss>50: # cost = trainBatch(crnn, criterion, optimizer,True) # numLoss = 0 #else: cost = trainBatch(crnn, criterion, optimizer) loss_avg.add(cost) i += 1 #if i % opt.displayInterval == 0: # print('[%d/%d][%d/%d] Loss: %f' % # (epoch, opt.niter, i, len(train_loader), loss_avg.val())) # loss_avg.reset() if i % opt.valInterval == 0: testLoss,accuracy = val(crnn, test_dataset, criterion) #print('Test loss: %f, accuray: %f' % (testLoss, accuracy)) print("epoch:{},step:{},Test loss:{},accuracy:{},train loss:{}".format(epoch,num,testLoss,accuracy,loss_avg.val())) loss_avg.reset() # do checkpointing num +=1 #lasttestLoss = min(lasttestLoss,testLoss) if lasttestLoss >testLoss: print("The step {},last lost:{}, current: {},save model!".format(num,lasttestLoss,testLoss)) lasttestLoss = testLoss #delete(opt.experiment)##删除历史模型 torch.save(crnn.state_dict(), '{}/netCRNN.pth'.format(opt.experiment)) numLoss = 0 else: numLoss+=1
classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0)
configfile.py
# -*- coding: utf-8 -*- """ configfile.py - Human-readable text configuration file library Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more infomation. Used for reading and writing dictionary objects to a python-like configuration file format. Data structures may be nested and contain any data type as long as it can be converted to/from a string using repr and eval. """ import re, os, sys from .pgcollections import OrderedDict GLOBAL_PATH = None # so not thread safe. from . import units from .python2_3 import asUnicode class ParseError(Exception): def __init__(self, message, lineNum, line, fileName=None): self.lineNum = lineNum self.line = line #self.message = message self.fileName = fileName Exception.__init__(self, message) def __str__(self): if self.fileName is None: msg = "Error parsing string at line %d:\n" % self.lineNum else: msg = "Error parsing config file '%s' at line %d:\n" % (self.fileName, self.lineNum) msg += "%s\n%s" % (self.line, self.message) return msg #raise Exception() def writeConfigFile(data, fname): s = genString(data) fd = open(fname, 'w') fd.write(s) fd.close() def readConfigFile(fname): #cwd = os.getcwd() global GLOBAL_PATH if GLOBAL_PATH is not None: fname2 = os.path.join(GLOBAL_PATH, fname) if os.path.exists(fname2): fname = fname2 GLOBAL_PATH = os.path.dirname(os.path.abspath(fname)) try: #os.chdir(newDir) ## bad. fd = open(fname) s = asUnicode(fd.read()) fd.close() s = s.replace("\r\n", "\n") s = s.replace("\r", "\n")
except ParseError: sys.exc_info()[1].fileName = fname raise except: print("Error while reading config file %s:"% fname) raise #finally: #os.chdir(cwd) return data def appendConfigFile(data, fname): s = genString(data) fd = open(fname, 'a') fd.write(s) fd.close() def genString(data, indent=''): s = '' for k in data: sk = str(k) if len(sk) == 0: print(data) raise Exception('blank dict keys not allowed (see data above)') if sk[0] == ' ' or ':' in sk: print(data) raise Exception('dict keys must not contain ":" or start with spaces [offending key is "%s"]' % sk) if isinstance(data[k], dict): s += indent + sk + ':\n' s += genString(data[k], indent + ' ') else: s += indent + sk + ': ' + repr(data[k]) + '\n' return s def parseString(lines, start=0): data = OrderedDict() if isinstance(lines, basestring): lines = lines.split('\n') lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines indent = measureIndent(lines[start]) ln = start - 1 try: while True: ln += 1 #print ln if ln >= len(lines): break l = lines[ln] ## Skip blank lines or lines starting with # if re.match(r'\s*#', l) or not re.search(r'\S', l): continue ## Measure line indentation, make sure it is correct for this level lineInd = measureIndent(l) if lineInd < indent: ln -= 1 break if lineInd > indent: #print lineInd, indent raise ParseError('Indentation is incorrect. Expected %d, got %d' % (indent, lineInd), ln+1, l) if ':' not in l: raise ParseError('Missing colon', ln+1, l) (k, p, v) = l.partition(':') k = k.strip() v = v.strip() ## set up local variables to use for eval local = units.allUnits.copy() local['OrderedDict'] = OrderedDict local['readConfigFile'] = readConfigFile if len(k) < 1: raise ParseError('Missing name preceding colon', ln+1, l) if k[0] == '(' and k[-1] == ')': ## If the key looks like a tuple, try evaluating it. try: k1 = eval(k, local) if type(k1) is tuple: k = k1 except: pass if re.search(r'\S', v) and v[0] != '#': ## eval the value try: val = eval(v, local) except: ex = sys.exc_info()[1] raise ParseError("Error evaluating expression '%s': [%s: %s]" % (v, ex.__class__.__name__, str(ex)), (ln+1), l) else: if ln+1 >= len(lines) or measureIndent(lines[ln+1]) <= indent: #print "blank dict" val = {} else: #print "Going deeper..", ln+1 (ln, val) = parseString(lines, start=ln+1) data[k] = val #print k, repr(val) except ParseError: raise except: ex = sys.exc_info()[1] raise ParseError("%s: %s" % (ex.__class__.__name__, str(ex)), ln+1, l) #print "Returning shallower..", ln+1 return (ln, data) def measureIndent(s): n = 0 while n < len(s) and s[n] == ' ': n += 1 return n if __name__ == '__main__': import tempfile fn = tempfile.mktemp() tf = open(fn, 'w') cf = """ key: 'value' key2: ##comment ##comment key21: 'value' ## comment ##comment key22: [1,2,3] key23: 234 #comment """ tf.write(cf) tf.close() print("=== Test:===") num = 1 for line in cf.split('\n'): print("%02d %s" % (num, line)) num += 1 print(cf) print("============") data = readConfigFile(fn) print(data) os.remove(fn)
data = parseString(s)[1]
time_test.go
package demo_base import ( "fmt" "testing" "time" ) func
(t *testing.T) { // now time now := time.Now() fmt.Println(now) // unix timestamp fmt.Println(now.Unix()) // nano time fmt.Println(now.UnixNano()) // decimal part fmt.Println(now.Nanosecond()) } func TestGetTimeTypeCalendar(t *testing.T) { now := time.Now() year, month, day := now.Date() fmt.Printf("year:%d, month:%d, day:%d\n", year, month, day) fmt.Println(now.Year()) fmt.Println(now.Month()) fmt.Println(now.Day()) // clock hour, min, sec := now.Clock() fmt.Printf("hour:%d, min:%d, sec:%d\n", hour, min, sec) fmt.Println(now.Hour()) fmt.Println(now.Minute()) fmt.Println(now.Second()) // week fmt.Println(now.Weekday()) fmt.Println(now.YearDay()) // timezone fmt.Println(now.Location()) // day fmt.Println(now.YearDay()) }
TestGetTime
polar.js
import { __assign, __extends } from "tslib"; import { each, isArray } from '@antv/util'; import { getDistanceToCenter } from '../../util/coordinate'; import { getPointAngle } from '../../util/coordinate'; import GeometryLabel from './base'; var HALF_PI = Math.PI / 2; /** * 极坐标下的图形 label */ var PolarLabel = /** @class */ (function (_super) { __extends(PolarLabel, _super); function PolarLabel() {
eturn _super !== null && _super.apply(this, arguments) || this; } PolarLabel.prototype.getLabelAlign = function (point) { var coordinate = this.coordinate; var align; if (point.labelEmit) { if (point.angle <= Math.PI / 2 && point.angle > -Math.PI / 2) { align = 'left'; } else { align = 'right'; } } else if (!coordinate.isTransposed) { align = 'center'; } else { var center = coordinate.getCenter(); var offset = this.getDefaultOffset(point.offset); if (Math.abs(point.x - center.x) < 1) { align = 'center'; } else if (point.angle > Math.PI || point.angle <= 0) { if (offset > 0) { align = 'left'; } else { align = 'right'; } } else { if (offset > 0) { align = 'right'; } else { align = 'left'; } } } return align; }; PolarLabel.prototype.getLabelPoint = function (labelCfg, mappingData, index) { var factor = 1; var arcPoint; var content = labelCfg.content[index]; if (this.isToMiddle(mappingData)) { arcPoint = this.getMiddlePoint(mappingData.points); } else { if (labelCfg.content.length === 1 && index === 0) { index = 1; } else if (index === 0) { factor = -1; } arcPoint = this.getArcPoint(mappingData, index); } var offset = this.getDefaultOffset(labelCfg.offset) * factor; var middleAngle = this.getPointAngle(arcPoint); var isLabelEmit = labelCfg.labelEmit; var labelPositionCfg = this.getCirclePoint(middleAngle, offset, arcPoint, isLabelEmit); if (labelPositionCfg.r === 0) { // 如果文本位置位于圆心,则不展示 labelPositionCfg.content = ''; } else { labelPositionCfg.content = content; labelPositionCfg.angle = middleAngle; labelPositionCfg.color = mappingData.color; } labelPositionCfg.rotate = labelCfg.autoRotate ? this.getLabelRotate(middleAngle, offset, isLabelEmit) : labelCfg.rotate; labelPositionCfg.start = { x: arcPoint.x, y: arcPoint.y, }; return labelPositionCfg; }; PolarLabel.prototype.getArcPoint = function (mappingData, index) { if (index === void 0) { index = 0; } var arcPoint; if (!isArray(mappingData.x) && !isArray(mappingData.y)) { arcPoint = { x: mappingData.x, y: mappingData.y, }; } else { arcPoint = { x: isArray(mappingData.x) ? mappingData.x[index] : mappingData.x, y: isArray(mappingData.y) ? mappingData.y[index] : mappingData.y, }; } return arcPoint; }; // 获取点所在的角度 PolarLabel.prototype.getPointAngle = function (point) { return getPointAngle(this.coordinate, point); }; PolarLabel.prototype.getCirclePoint = function (angle, offset, point, isLabelEmit) { var coordinate = this.coordinate; var center = coordinate.getCenter(); var r = getDistanceToCenter(coordinate, point); if (r === 0) { return __assign(__assign({}, center), { r: r }); } var labelAngle = angle; if (coordinate.isTransposed && r > offset && !isLabelEmit) { var appendAngle = Math.asin(offset / (2 * r)); labelAngle = angle + appendAngle * 2; } else { r = r + offset; } return { x: center.x + r * Math.cos(labelAngle), y: center.y + r * Math.sin(labelAngle), r: r, }; }; // angle 为弧度 PolarLabel.prototype.getLabelRotate = function (angle, offset, isLabelEmit) { var rotate = angle + HALF_PI; if (isLabelEmit) { rotate -= HALF_PI; } if (rotate) { if (rotate > HALF_PI) { rotate = rotate - Math.PI; } else if (rotate < -HALF_PI) { rotate = rotate + Math.PI; } } return rotate; }; // 获取中心的位置 PolarLabel.prototype.getMiddlePoint = function (points) { var coordinate = this.coordinate; var count = points.length; var middlePoint = { x: 0, y: 0, }; each(points, function (point) { middlePoint.x += point.x; middlePoint.y += point.y; }); middlePoint.x /= count; middlePoint.y /= count; middlePoint = coordinate.convert(middlePoint); return middlePoint; }; // 是否居中 PolarLabel.prototype.isToMiddle = function (mappingData) { return mappingData.x.length > 2; }; return PolarLabel; }(GeometryLabel)); export default PolarLabel; //# sourceMappingURL=polar.js.map
r
test_tcp.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for implementations of L{IReactorTCP} and the TCP parts of L{IReactorSocket}. """ from __future__ import division, absolute_import __metaclass__ = type import socket, errno from zope.interface import implementer from twisted.python.compat import _PY3 from twisted.python.runtime import platform from twisted.python.failure import Failure from twisted.python import log from twisted.trial.unittest import SkipTest, TestCase from twisted.internet.test.reactormixins import ReactorBuilder from twisted.internet.error import ( ConnectionLost, UserError, ConnectionRefusedError, ConnectionDone, ConnectionAborted) from twisted.internet.interfaces import ( ILoggingContext, IConnector, IReactorFDSet, IReactorSocket, IReactorTCP) from twisted.internet.address import IPv4Address, IPv6Address from twisted.internet.defer import ( Deferred, DeferredList, maybeDeferred, gatherResults) from twisted.internet._endpointspy3 import ( TCP4ServerEndpoint, TCP4ClientEndpoint) from twisted.internet.protocol import ServerFactory, ClientFactory, Protocol from twisted.internet.interfaces import ( IPushProducer, IPullProducer, IHalfCloseableProtocol) from twisted.internet.tcp import Connection, Server, _resolveIPv6 from twisted.internet.test.connectionmixins import ( LogObserverMixin, ConnectionTestsMixin, TCPClientTestsMixin, findFreePort, ConnectableProtocol, EndpointCreator, runProtocolsWithReactor) from twisted.internet.test.test_core import ObjectModelIntegrationMixin from twisted.test.test_tcp import MyClientFactory, MyServerFactory from twisted.test.test_tcp import ClosingFactory, ClientStartStopFactory try: from OpenSSL import SSL except ImportError: useSSL = False else: from twisted.internet.ssl import ClientContextFactory useSSL = True try: socket.socket(socket.AF_INET6, socket.SOCK_STREAM).close() except socket.error as e: ipv6Skip = str(e) else: ipv6Skip = None if platform.isWindows(): from twisted.internet.test import _win32ifaces getLinkLocalIPv6Addresses = _win32ifaces.win32GetLinkLocalIPv6Addresses else: try: from twisted.internet.test import _posixifaces except ImportError: getLinkLocalIPv6Addresses = lambda: [] else: getLinkLocalIPv6Addresses = _posixifaces.posixGetLinkLocalIPv6Addresses def getLinkLocalIPv6Address(): """ Find and return a configured link local IPv6 address including a scope identifier using the % separation syntax. If the system has no link local IPv6 addresses, raise L{SkipTest} instead. @raise SkipTest: if no link local address can be found or if the C{netifaces} module is not available. @return: a C{str} giving the address """ addresses = getLinkLocalIPv6Addresses() if addresses: return addresses[0] raise SkipTest("Link local IPv6 address unavailable") def connect(client, destination): """ Connect a socket to the given destination. @param client: A C{socket.socket}. @param destination: A tuple of (host, port). The host is a C{str}, the port a C{int}. If the C{host} is an IPv6 IP, the address is resolved using C{getaddrinfo} and the first version found is used. """ (host, port) = destination if '%' in host or ':' in host: address = socket.getaddrinfo(host, port)[0][4] else: address = (host, port) client.connect(address) class FakeSocket(object): """ A fake for L{socket.socket} objects. @ivar data: A C{str} giving the data which will be returned from L{FakeSocket.recv}. @ivar sendBuffer: A C{list} of the objects passed to L{FakeSocket.send}. """ def __init__(self, data): self.data = data self.sendBuffer = [] def setblocking(self, blocking): self.blocking = blocking def recv(self, size): return self.data def send(self, bytes): """ I{Send} all of C{bytes} by accumulating it into C{self.sendBuffer}. @return: The length of C{bytes}, indicating all the data has been accepted. """ self.sendBuffer.append(bytes) return len(bytes) def shutdown(self, how): """ Shutdown is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. """ def close(self): """ Close is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. """ def setsockopt(self, *args): """ Setsockopt is not implemented. The method is provided since real sockets have it and some code expects it. No behavior of L{FakeSocket} is affected by a call to it. """ def fileno(self): """ Return a fake file descriptor. If actually used, this will have no connection to this L{FakeSocket} and will probably cause surprising results. """ return 1 class TestFakeSocket(TestCase): """ Test that the FakeSocket can be used by the doRead method of L{Connection} """ def test_blocking(self): skt = FakeSocket(b"someData") skt.setblocking(0) self.assertEqual(skt.blocking, 0) def test_recv(self): skt = FakeSocket(b"someData") self.assertEqual(skt.recv(10), b"someData") def test_send(self): """ L{FakeSocket.send} accepts the entire string passed to it, adds it to its send buffer, and returns its length. """ skt = FakeSocket(b"") count = skt.send(b"foo") self.assertEqual(count, 3) self.assertEqual(skt.sendBuffer, [b"foo"]) class FakeProtocol(Protocol): """ An L{IProtocol} that returns a value from its dataReceived method. """ def dataReceived(self, data): """ Return something other than C{None} to trigger a deprecation warning for that behavior. """ return () @implementer(IReactorFDSet) class _FakeFDSetReactor(object): """ A no-op implementation of L{IReactorFDSet}, which ignores all adds and removes. """ addReader = addWriter = removeReader = removeWriter = ( lambda self, desc: None) class TCPServerTests(TestCase): """ Whitebox tests for L{twisted.internet.tcp.Server}. """ def setUp(self): self.reactor = _FakeFDSetReactor() class FakePort(object): _realPortNumber = 3 self.skt = FakeSocket(b"") self.protocol = Protocol() self.server = Server( self.skt, self.protocol, ("", 0), FakePort(), None, self.reactor) def test_writeAfterDisconnect(self): """ L{Server.write} discards bytes passed to it if called after it has lost its connection. """ self.server.connectionLost( Failure(Exception("Simulated lost connection"))) self.server.write(b"hello world") self.assertEqual(self.skt.sendBuffer, []) def test_writeAfteDisconnectAfterTLS(self): """ L{Server.write} discards bytes passed to it if called after it has lost its connection when the connection had started TLS. """ self.server.TLS = True self.test_writeAfterDisconnect() def test_writeSequenceAfterDisconnect(self): """ L{Server.writeSequence} discards bytes passed to it if called after it has lost its connection. """ self.server.connectionLost( Failure(Exception("Simulated lost connection"))) self.server.writeSequence([b"hello world"]) self.assertEqual(self.skt.sendBuffer, []) def test_writeSequenceAfteDisconnectAfterTLS(self): """ L{Server.writeSequence} discards bytes passed to it if called after it has lost its connection when the connection had started TLS. """ self.server.TLS = True self.test_writeSequenceAfterDisconnect() class TCPConnectionTests(TestCase): """ Whitebox tests for L{twisted.internet.tcp.Connection}. """ def test_doReadWarningIsRaised(self): """ When an L{IProtocol} implementation that returns a value from its C{dataReceived} method, a deprecated warning is emitted. """ skt = FakeSocket(b"someData") protocol = FakeProtocol() conn = Connection(skt, protocol) conn.doRead() warnings = self.flushWarnings([FakeProtocol.dataReceived]) self.assertEqual(warnings[0]['category'], DeprecationWarning) self.assertEqual( warnings[0]["message"], "Returning a value other than None from " "twisted.internet.test.test_tcp.FakeProtocol.dataReceived " "is deprecated since Twisted 11.0.0.") self.assertEqual(len(warnings), 1) def test_noTLSBeforeStartTLS(self): """ The C{TLS} attribute of a L{Connection} instance is C{False} before L{Connection.startTLS} is called. """ skt = FakeSocket(b"") protocol = FakeProtocol() conn = Connection(skt, protocol) self.assertFalse(conn.TLS) def test_tlsAfterStartTLS(self): """ The C{TLS} attribute of a L{Connection} instance is C{True} after L{Connection.startTLS} is called. """ skt = FakeSocket(b"") protocol = FakeProtocol() conn = Connection(skt, protocol, reactor=_FakeFDSetReactor()) conn._tlsClientDefault = True conn.startTLS(ClientContextFactory(), True) self.assertTrue(conn.TLS) if not useSSL: test_tlsAfterStartTLS.skip = "No SSL support available" class TCPCreator(EndpointCreator): """ Create IPv4 TCP endpoints for L{runProtocolsWithReactor}-based tests. """ interface = "127.0.0.1" def server(self, reactor): """ Create a server-side TCP endpoint. """ return TCP4ServerEndpoint(reactor, 0, interface=self.interface) def client(self, reactor, serverAddress): """ Create a client end point that will connect to the given address. @type serverAddress: L{IPv4Address} """ return TCP4ClientEndpoint(reactor, self.interface, serverAddress.port) class TCP6Creator(TCPCreator): """ Create IPv6 TCP endpoints for C{ReactorBuilder.runProtocolsWithReactor}-based tests. The endpoint types in question here are still the TCP4 variety, since these simply pass through IPv6 address literals to the reactor, and we are only testing address literals, not name resolution (as name resolution has not yet been implemented). See http://twistedmatrix.com/trac/ticket/4470 for more specific information about new endpoint classes. The naming is slightly misleading, but presumably if you're passing an IPv6 literal, you know what you're asking for. """ def __init__(self): self.interface = getLinkLocalIPv6Address() class TCPClientTestsBase(ReactorBuilder, ConnectionTestsMixin, TCPClientTestsMixin): """ Base class for builders defining tests related to L{IReactorTCP.connectTCP}. """ requiredInterfaces = (IReactorTCP,) port = 1234 @property def interface(self): """ Return the interface attribute from the endpoints object. """ return self.endpoints.interface class TCP4ClientTestsBuilder(TCPClientTestsBase): """ Builder configured with IPv4 parameters for tests related to L{IReactorTCP.connectTCP}. """ fakeDomainName = 'some-fake.domain.example.com' family = socket.AF_INET addressClass = IPv4Address endpoints = TCPCreator() class TCP6ClientTestsBuilder(TCPClientTestsBase): """ Builder configured with IPv6 parameters for tests related to L{IReactorTCP.connectTCP}. """ if ipv6Skip: skip = ipv6Skip family = socket.AF_INET6 addressClass = IPv6Address def setUp(self): # Only create this object here, so that it won't be created if tests # are being skipped: self.endpoints = TCP6Creator() # This is used by test_addresses to test the distinction between the # resolved name and the name on the socket itself. All the same # invariants should hold, but giving back an IPv6 address from a # resolver is not something the reactor can handle, so instead, we make # it so that the connect call for the IPv6 address test simply uses an # address literal. self.fakeDomainName = self.endpoints.interface class TCPConnectorTestsBuilder(ReactorBuilder): """ Tests for the L{IConnector} provider returned by L{IReactorTCP.connectTCP}. """ requiredInterfaces = (IReactorTCP,) def test_connectorIdentity(self): """ L{IReactorTCP.connectTCP} returns an object which provides L{IConnector}. The destination of the connector is the address which was passed to C{connectTCP}. The same connector object is passed to the factory's C{startedConnecting} method as to the factory's C{clientConnectionLost} method. """ serverFactory = ClosingFactory() reactor = self.buildReactor() tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface) serverFactory.port = tcpPort portNumber = tcpPort.getHost().port seenConnectors = [] seenFailures = [] clientFactory = ClientStartStopFactory() clientFactory.clientConnectionLost = ( lambda connector, reason: (seenConnectors.append(connector), seenFailures.append(reason))) clientFactory.startedConnecting = seenConnectors.append connector = reactor.connectTCP(self.interface, portNumber, clientFactory) self.assertTrue(IConnector.providedBy(connector)) dest = connector.getDestination() self.assertEqual(dest.type, "TCP") self.assertEqual(dest.host, self.interface) self.assertEqual(dest.port, portNumber) clientFactory.whenStopped.addBoth(lambda _: reactor.stop()) self.runReactor(reactor) seenFailures[0].trap(ConnectionDone) self.assertEqual(seenConnectors, [connector, connector]) def test_userFail(self): """ Calling L{IConnector.stopConnecting} in C{Factory.startedConnecting} results in C{Factory.clientConnectionFailed} being called with L{error.UserError} as the reason. """ serverFactory = MyServerFactory() reactor = self.buildReactor() tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface) portNumber = tcpPort.getHost().port fatalErrors = [] def startedConnecting(connector): try: connector.stopConnecting() except Exception: fatalErrors.append(Failure()) reactor.stop() clientFactory = ClientStartStopFactory() clientFactory.startedConnecting = startedConnecting clientFactory.whenStopped.addBoth(lambda _: reactor.stop()) reactor.callWhenRunning(lambda: reactor.connectTCP(self.interface, portNumber, clientFactory)) self.runReactor(reactor) if fatalErrors: self.fail(fatalErrors[0].getTraceback()) clientFactory.reason.trap(UserError) self.assertEqual(clientFactory.failed, 1) def test_reconnect(self): """ Calling L{IConnector.connect} in C{Factory.clientConnectionLost} causes a new connection attempt to be made. """ serverFactory = ClosingFactory() reactor = self.buildReactor() tcpPort = reactor.listenTCP(0, serverFactory, interface=self.interface) serverFactory.port = tcpPort portNumber = tcpPort.getHost().port clientFactory = MyClientFactory() def clientConnectionLost(connector, reason): connector.connect() clientFactory.clientConnectionLost = clientConnectionLost reactor.connectTCP(self.interface, portNumber, clientFactory) protocolMadeAndClosed = [] def reconnectFailed(ignored): p = clientFactory.protocol protocolMadeAndClosed.append((p.made, p.closed)) reactor.stop() clientFactory.failDeferred.addCallback(reconnectFailed) self.runReactor(reactor) clientFactory.reason.trap(ConnectionRefusedError) self.assertEqual(protocolMadeAndClosed, [(1, 1)]) class TCP4ConnectorTestsBuilder(TCPConnectorTestsBuilder): interface = '127.0.0.1' family = socket.AF_INET addressClass = IPv4Address class TCP6ConnectorTestsBuilder(TCPConnectorTestsBuilder): family = socket.AF_INET6 addressClass = IPv6Address if ipv6Skip: skip = ipv6Skip def setUp(self): self.interface = getLinkLocalIPv6Address() def createTestSocket(test, addressFamily, socketType): """ Create a socket for the duration of the given test. @param test: the test to add cleanup to. @param addressFamily: an C{AF_*} constant @param socketType: a C{SOCK_*} constant. @return: a socket object. """ skt = socket.socket(addressFamily, socketType) test.addCleanup(skt.close) return skt class StreamTransportTestsMixin(LogObserverMixin): """ Mixin defining tests which apply to any port/connection based transport. """ def test_startedListeningLogMessage(self): """ When a port starts, a message including a description of the associated factory is logged. """ loggedMessages = self.observe() reactor = self.buildReactor() @implementer(ILoggingContext) class SomeFactory(ServerFactory): def logPrefix(self): return "Crazy Factory" factory = SomeFactory() p = self.getListeningPort(reactor, factory) expectedMessage = self.getExpectedStartListeningLogMessage( p, "Crazy Factory") self.assertEqual((expectedMessage,), loggedMessages[0]['message']) def test_connectionLostLogMsg(self): """ When a connection is lost, an informative message should be logged (see L{getExpectedConnectionLostLogMsg}): an address identifying the port and the fact that it was closed. """ loggedMessages = [] def logConnectionLostMsg(eventDict): loggedMessages.append(log.textFromEventDict(eventDict)) reactor = self.buildReactor() p = self.getListeningPort(reactor, ServerFactory()) expectedMessage = self.getExpectedConnectionLostLogMsg(p) log.addObserver(logConnectionLostMsg) def stopReactor(ignored): log.removeObserver(logConnectionLostMsg) reactor.stop() def doStopListening(): log.addObserver(logConnectionLostMsg) maybeDeferred(p.stopListening).addCallback(stopReactor) reactor.callWhenRunning(doStopListening) reactor.run() self.assertIn(expectedMessage, loggedMessages) def test_allNewStyle(self): """ The L{IListeningPort} object is an instance of a class with no classic classes in its hierarchy. """ reactor = self.buildReactor() port = self.getListeningPort(reactor, ServerFactory()) self.assertFullyNewStyle(port) class ListenTCPMixin(object): """ Mixin which uses L{IReactorTCP.listenTCP} to hand out listening TCP ports. """ def getListeningPort(self, reactor, factory, port=0, interface=''): """ Get a TCP port from a reactor. """ return reactor.listenTCP(port, factory, interface=interface) class SocketTCPMixin(object): """ Mixin which uses L{IReactorSocket.adoptStreamPort} to hand out listening TCP ports. """ def getListeningPort(self, reactor, factory, port=0, interface=''): """ Get a TCP port from a reactor, wrapping an already-initialized file descriptor. """ if IReactorSocket.providedBy(reactor): if ':' in interface: domain = socket.AF_INET6 address = socket.getaddrinfo(interface, port)[0][4] else: domain = socket.AF_INET address = (interface, port) portSock = socket.socket(domain) portSock.bind(address) portSock.listen(3) portSock.setblocking(False) try: return reactor.adoptStreamPort( portSock.fileno(), portSock.family, factory) finally: # The socket should still be open; fileno will raise if it is # not. portSock.fileno() # Now clean it up, because the rest of the test does not need # it. portSock.close() else: raise SkipTest("Reactor does not provide IReactorSocket") class TCPPortTestsMixin(object): """ Tests for L{IReactorTCP.listenTCP} """ requiredInterfaces = (IReactorTCP,) def getExpectedStartListeningLogMessage(self, port, factory): """ Get the message expected to be logged when a TCP port starts listening. """ return "%s starting on %d" % ( factory, port.getHost().port) def getExpectedConnectionLostLogMsg(self, port): """ Get the expected connection lost message for a TCP port. """ return "(TCP Port %s Closed)" % (port.getHost().port,) def test_portGetHostOnIPv4(self): """ When no interface is passed to L{IReactorTCP.listenTCP}, the returned listening port listens on an IPv4 address. """ reactor = self.buildReactor() port = self.getListeningPort(reactor, ServerFactory()) address = port.getHost() self.assertIsInstance(address, IPv4Address) def test_portGetHostOnIPv6(self): """ When listening on an IPv6 address, L{IListeningPort.getHost} returns an L{IPv6Address} with C{host} and C{port} attributes reflecting the address the port is bound to. """ reactor = self.buildReactor() host, portNumber = findFreePort( family=socket.AF_INET6, interface='::1')[:2] port = self.getListeningPort( reactor, ServerFactory(), portNumber, host) address = port.getHost() self.assertIsInstance(address, IPv6Address) self.assertEqual('::1', address.host) self.assertEqual(portNumber, address.port) if ipv6Skip: test_portGetHostOnIPv6.skip = ipv6Skip def test_portGetHostOnIPv6ScopeID(self): """ When a link-local IPv6 address including a scope identifier is passed as the C{interface} argument to L{IReactorTCP.listenTCP}, the resulting L{IListeningPort} reports its address as an L{IPv6Address} with a host value that includes the scope identifier. """ linkLocal = getLinkLocalIPv6Address() reactor = self.buildReactor() port = self.getListeningPort(reactor, ServerFactory(), 0, linkLocal) address = port.getHost() self.assertIsInstance(address, IPv6Address) self.assertEqual(linkLocal, address.host) if ipv6Skip: test_portGetHostOnIPv6ScopeID.skip = ipv6Skip def _buildProtocolAddressTest(self, client, interface): """ Connect C{client} to a server listening on C{interface} started with L{IReactorTCP.listenTCP} and return the address passed to the factory's C{buildProtocol} method. @param client: A C{SOCK_STREAM} L{socket.socket} created with an address family such that it will be able to connect to a server listening on C{interface}. @param interface: A C{str} giving an address for a server to listen on. This should almost certainly be the loopback address for some address family supported by L{IReactorTCP.listenTCP}. @return: Whatever object, probably an L{IAddress} provider, is passed to a server factory's C{buildProtocol} method when C{client} establishes a connection. """ class ObserveAddress(ServerFactory): def buildProtocol(self, address): reactor.stop() self.observedAddress = address return Protocol() factory = ObserveAddress() reactor = self.buildReactor() port = self.getListeningPort(reactor, factory, 0, interface) client.setblocking(False) try: connect(client, (port.getHost().host, port.getHost().port)) except socket.error as e: errnum, message = e.args self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK)) self.runReactor(reactor) return factory.observedAddress def test_buildProtocolIPv4Address(self): """ When a connection is accepted over IPv4, an L{IPv4Address} is passed to the factory's C{buildProtocol} method giving the peer's address. """ interface = '127.0.0.1' client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM) observedAddress = self._buildProtocolAddressTest(client, interface) self.assertEqual( IPv4Address('TCP', *client.getsockname()), observedAddress) def test_buildProtocolIPv6Address(self): """ When a connection is accepted to an IPv6 address, an L{IPv6Address} is passed to the factory's C{buildProtocol} method giving the peer's address. """ interface = '::1' client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) observedAddress = self._buildProtocolAddressTest(client, interface) self.assertEqual( IPv6Address('TCP', *client.getsockname()[:2]), observedAddress) if ipv6Skip: test_buildProtocolIPv6Address.skip = ipv6Skip def test_buildProtocolIPv6AddressScopeID(self): """ When a connection is accepted to a link-local IPv6 address, an L{IPv6Address} is passed to the factory's C{buildProtocol} method giving the peer's address, including a scope identifier. """ interface = getLinkLocalIPv6Address() client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) observedAddress = self._buildProtocolAddressTest(client, interface) self.assertEqual( IPv6Address('TCP', *client.getsockname()[:2]), observedAddress) if ipv6Skip: test_buildProtocolIPv6AddressScopeID.skip = ipv6Skip def _serverGetConnectionAddressTest(self, client, interface, which): """ Connect C{client} to a server listening on C{interface} started with L{IReactorTCP.listenTCP} and return the address returned by one of the server transport's address lookup methods, C{getHost} or C{getPeer}. @param client: A C{SOCK_STREAM} L{socket.socket} created with an address family such that it will be able to connect to a server listening on C{interface}. @param interface: A C{str} giving an address for a server to listen on. This should almost certainly be the loopback address for some address family supported by L{IReactorTCP.listenTCP}. @param which: A C{str} equal to either C{"getHost"} or C{"getPeer"} determining which address will be returned. @return: Whatever object, probably an L{IAddress} provider, is returned from the method indicated by C{which}. """ class ObserveAddress(Protocol): def makeConnection(self, transport): reactor.stop() self.factory.address = getattr(transport, which)() reactor = self.buildReactor() factory = ServerFactory() factory.protocol = ObserveAddress port = self.getListeningPort(reactor, factory, 0, interface) client.setblocking(False) try: connect(client, (port.getHost().host, port.getHost().port)) except socket.error as e: errnum, message = e.args self.assertIn(errnum, (errno.EINPROGRESS, errno.EWOULDBLOCK)) self.runReactor(reactor) return factory.address def test_serverGetHostOnIPv4(self): """ When a connection is accepted over IPv4, the server L{ITransport.getHost} method returns an L{IPv4Address} giving the address on which the server accepted the connection. """ interface = '127.0.0.1' client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM) hostAddress = self._serverGetConnectionAddressTest( client, interface, 'getHost') self.assertEqual( IPv4Address('TCP', *client.getpeername()), hostAddress) def test_serverGetHostOnIPv6(self): """ When a connection is accepted over IPv6, the server L{ITransport.getHost} method returns an L{IPv6Address} giving the address on which the server accepted the connection. """ interface = '::1' client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) hostAddress = self._serverGetConnectionAddressTest( client, interface, 'getHost') self.assertEqual( IPv6Address('TCP', *client.getpeername()[:2]), hostAddress) if ipv6Skip: test_serverGetHostOnIPv6.skip = ipv6Skip def test_serverGetHostOnIPv6ScopeID(self): """ When a connection is accepted over IPv6, the server L{ITransport.getHost} method returns an L{IPv6Address} giving the address on which the server accepted the connection, including the scope identifier. """ interface = getLinkLocalIPv6Address() client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) hostAddress = self._serverGetConnectionAddressTest( client, interface, 'getHost') self.assertEqual( IPv6Address('TCP', *client.getpeername()[:2]), hostAddress) if ipv6Skip: test_serverGetHostOnIPv6ScopeID.skip = ipv6Skip def test_serverGetPeerOnIPv4(self): """ When a connection is accepted over IPv4, the server L{ITransport.getPeer} method returns an L{IPv4Address} giving the address of the remote end of the connection. """ interface = '127.0.0.1' client = createTestSocket(self, socket.AF_INET, socket.SOCK_STREAM) peerAddress = self._serverGetConnectionAddressTest( client, interface, 'getPeer') self.assertEqual( IPv4Address('TCP', *client.getsockname()), peerAddress) def test_serverGetPeerOnIPv6(self): """ When a connection is accepted over IPv6, the server L{ITransport.getPeer} method returns an L{IPv6Address} giving the address on the remote end of the connection. """ interface = '::1' client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) peerAddress = self._serverGetConnectionAddressTest( client, interface, 'getPeer') self.assertEqual( IPv6Address('TCP', *client.getsockname()[:2]), peerAddress) if ipv6Skip: test_serverGetPeerOnIPv6.skip = ipv6Skip def test_serverGetPeerOnIPv6ScopeID(self): """ When a connection is accepted over IPv6, the server L{ITransport.getPeer} method returns an L{IPv6Address} giving the address on the remote end of the connection, including the scope identifier. """ interface = getLinkLocalIPv6Address() client = createTestSocket(self, socket.AF_INET6, socket.SOCK_STREAM) peerAddress = self._serverGetConnectionAddressTest( client, interface, 'getPeer') self.assertEqual( IPv6Address('TCP', *client.getsockname()[:2]), peerAddress) if ipv6Skip: test_serverGetPeerOnIPv6ScopeID.skip = ipv6Skip class TCPPortTestsBuilder(ReactorBuilder, ListenTCPMixin, TCPPortTestsMixin, ObjectModelIntegrationMixin, StreamTransportTestsMixin): pass class TCPFDPortTestsBuilder(ReactorBuilder, SocketTCPMixin, TCPPortTestsMixin, ObjectModelIntegrationMixin, StreamTransportTestsMixin): pass class StopStartReadingProtocol(Protocol): """ Protocol that pauses and resumes the transport a few times """ def connectionMade(self): self.data = b'' self.pauseResumeProducing(3) def pauseResumeProducing(self, counter): """ Toggle transport read state, then count down. """ self.transport.pauseProducing() self.transport.resumeProducing() if counter: self.factory.reactor.callLater(0, self.pauseResumeProducing, counter - 1) else: self.factory.reactor.callLater(0, self.factory.ready.callback, self) def dataReceived(self, data): log.msg('got data', len(data)) self.data += data if len(self.data) == 4*4096: self.factory.stop.callback(self.data) class TCPConnectionTestsBuilder(ReactorBuilder): """ Builder defining tests relating to L{twisted.internet.tcp.Connection}. """ requiredInterfaces = (IReactorTCP,) def test_stopStartReading(self): """ This test verifies transport socket read state after multiple pause/resumeProducing calls. """ sf = ServerFactory() reactor = sf.reactor = self.buildReactor() skippedReactors = ["Glib2Reactor", "Gtk2Reactor"] reactorClassName = reactor.__class__.__name__ if reactorClassName in skippedReactors and platform.isWindows(): raise SkipTest( "This test is broken on gtk/glib under Windows.") sf.protocol = StopStartReadingProtocol sf.ready = Deferred() sf.stop = Deferred() p = reactor.listenTCP(0, sf) port = p.getHost().port def proceed(protos, port): """ Send several IOCPReactor's buffers' worth of data. """ self.assertTrue(protos[0]) self.assertTrue(protos[1]) protos = protos[0][1], protos[1][1] protos[0].transport.write(b'x' * (2 * 4096) + b'y' * (2 * 4096)) return (sf.stop.addCallback(cleanup, protos, port) .addCallback(lambda ign: reactor.stop())) def cleanup(data, protos, port): """ Make sure IOCPReactor didn't start several WSARecv operations that clobbered each other's results. """ self.assertEqual(data, b'x'*(2*4096) + b'y'*(2*4096), 'did not get the right data') return DeferredList([ maybeDeferred(protos[0].transport.loseConnection), maybeDeferred(protos[1].transport.loseConnection), maybeDeferred(port.stopListening)]) cc = TCP4ClientEndpoint(reactor, '127.0.0.1', port) cf = ClientFactory() cf.protocol = Protocol d = DeferredList([cc.connect(cf), sf.ready]).addCallback(proceed, p) d.addErrback(log.err) self.runReactor(reactor) def test_connectionLostAfterPausedTransport(self): """ Alice connects to Bob. Alice writes some bytes and then shuts down the connection. Bob receives the bytes from the connection and then pauses the transport object. Shortly afterwards Bob resumes the transport object. At that point, Bob is notified that the connection has been closed. This is no problem for most reactors. The underlying event notification API will probably just remind them that the connection has been closed. It is a little tricky for win32eventreactor (MsgWaitForMultipleObjects). MsgWaitForMultipleObjects will only deliver the close notification once. The reactor needs to remember that notification until Bob resumes the transport. """ class Pauser(ConnectableProtocol): def __init__(self): self.events = [] def dataReceived(self, bytes): self.events.append("paused") self.transport.pauseProducing() self.reactor.callLater(0, self.resume) def resume(self): self.events.append("resumed") self.transport.resumeProducing() def connectionLost(self, reason): # This is the event you have been waiting for. self.events.append("lost") ConnectableProtocol.connectionLost(self, reason) class Client(ConnectableProtocol): def connectionMade(self): self.transport.write(b"some bytes for you") self.transport.loseConnection() pauser = Pauser() runProtocolsWithReactor(self, pauser, Client(), TCPCreator()) self.assertEqual(pauser.events, ["paused", "resumed", "lost"]) def test_doubleHalfClose(self): """ If one side half-closes its connection, and then the other side of the connection calls C{loseWriteConnection}, and then C{loseConnection} in {writeConnectionLost}, the connection is closed correctly. This rather obscure case used to fail (see ticket #3037). """ @implementer(IHalfCloseableProtocol) class ListenerProtocol(ConnectableProtocol): def readConnectionLost(self): self.transport.loseWriteConnection() def writeConnectionLost(self): self.transport.loseConnection() class Client(ConnectableProtocol): def connectionMade(self): self.transport.loseConnection() # If test fails, reactor won't stop and we'll hit timeout: runProtocolsWithReactor( self, ListenerProtocol(), Client(), TCPCreator()) class WriteSequenceTestsMixin(object): """ Test for L{twisted.internet.abstract.FileDescriptor.writeSequence}. """ requiredInterfaces = (IReactorTCP,) def setWriteBufferSize(self, transport, value): """ Set the write buffer size for the given transport, mananing possible differences (ie, IOCP). Bug #4322 should remove the need of that hack. """ if getattr(transport, "writeBufferSize", None) is not None: transport.writeBufferSize = value else: transport.bufferSize = value def test_writeSequeceWithoutWrite(self): """ C{writeSequence} sends the data even if C{write} hasn't been called. """ def connected(protocols): client, server, port = protocols def dataReceived(data): log.msg("data received: %r" % data) self.assertEqual(data, b"Some sequence splitted") client.transport.loseConnection() server.dataReceived = dataReceived client.transport.writeSequence([b"Some ", b"sequence ", b"splitted"]) reactor = self.buildReactor() d = self.getConnectedClientAndServer(reactor, "127.0.0.1", socket.AF_INET) d.addCallback(connected) d.addErrback(log.err) self.runReactor(reactor) def test_writeSequenceWithUnicodeRaisesException(self): """ C{writeSequence} with an element in the sequence of type unicode raises C{TypeError}. """ def connected(protocols): client, server, port = protocols exc = self.assertRaises( TypeError, server.transport.writeSequence, [u"Unicode is not kosher"]) self.assertEqual(str(exc), "Data must not be unicode") server.transport.loseConnection() reactor = self.buildReactor() d = self.getConnectedClientAndServer(reactor, "127.0.0.1", socket.AF_INET) d.addCallback(connected) d.addErrback(log.err) self.runReactor(reactor) def test_streamingProducer(self): """ C{writeSequence} pauses its streaming producer if too much data is buffered, and then resumes it. """ @implementer(IPushProducer) class SaveActionProducer(object): client = None server = None def __init__(self): self.actions = [] def pauseProducing(self): self.actions.append("pause") def resumeProducing(self): self.actions.append("resume") # Unregister the producer so the connection can close self.client.transport.unregisterProducer() # This is why the code below waits for the server connection # first - so we have it to close here. We close the server # side because win32evenreactor cannot reliably observe us # closing the client side (#5285). self.server.transport.loseConnection() def stopProducing(self): self.actions.append("stop") producer = SaveActionProducer() def connected(protocols): client, server = protocols[:2] producer.client = client producer.server = server # Register a streaming producer and verify that it gets paused # after it writes more than the local send buffer can hold. client.transport.registerProducer(producer, True) self.assertEqual(producer.actions, []) self.setWriteBufferSize(client.transport, 500) client.transport.writeSequence([b"x" * 50] * 20) self.assertEqual(producer.actions, ["pause"]) reactor = self.buildReactor() d = self.getConnectedClientAndServer(reactor, "127.0.0.1", socket.AF_INET) d.addCallback(connected) d.addErrback(log.err) self.runReactor(reactor) # After the send buffer gets a chance to empty out a bit, the producer # should be resumed. self.assertEqual(producer.actions, ["pause", "resume"]) def test_nonStreamingProducer(self): """ C{writeSequence} pauses its producer if too much data is buffered only if this is a streaming producer. """ test = self @implementer(IPullProducer) class SaveActionProducer(object): client = None def __init__(self): self.actions = [] def resumeProducing(self): self.actions.append("resume") if self.actions.count("resume") == 2: self.client.transport.stopConsuming() else: test.setWriteBufferSize(self.client.transport, 500) self.client.transport.writeSequence([b"x" * 50] * 20) def stopProducing(self): self.actions.append("stop") producer = SaveActionProducer() def connected(protocols): client = protocols[0] producer.client = client # Register a non-streaming producer and verify that it is resumed # immediately. client.transport.registerProducer(producer, False) self.assertEqual(producer.actions, ["resume"]) reactor = self.buildReactor() d = self.getConnectedClientAndServer(reactor, "127.0.0.1", socket.AF_INET) d.addCallback(connected) d.addErrback(log.err) self.runReactor(reactor) # After the local send buffer empties out, the producer should be # resumed again. self.assertEqual(producer.actions, ["resume", "resume"]) class TCPTransportServerAddressTestMixin(object): """ Test mixing for TCP server address building and log prefix. """ def getConnectedClientAndServer(self, reactor, interface, addressFamily): """ Helper method returnine a L{Deferred} firing with a tuple of a client protocol, a server protocol, and a running TCP port. """ raise NotImplementedError() def _testServerAddress(self, interface, addressFamily, adressClass): """ Helper method to test TCP server addresses on either IPv4 or IPv6. """ def connected(protocols): client, server, port = protocols try: self.assertEqual( "<AccumulatingProtocol #%s on %s>" % (server.transport.sessionno, port.getHost().port), str(server.transport)) self.assertEqual( "AccumulatingProtocol,%s,%s" % (server.transport.sessionno, interface), server.transport.logstr) [peerAddress] = server.factory.peerAddresses self.assertIsInstance(peerAddress, adressClass) self.assertEqual('TCP', peerAddress.type) self.assertEqual(interface, peerAddress.host) finally: # Be certain to drop the connection so the test completes. server.transport.loseConnection() reactor = self.buildReactor() d = self.getConnectedClientAndServer(reactor, interface, addressFamily) d.addCallback(connected) d.addErrback(log.err) self.runReactor(reactor) def test_serverAddressTCP4(self): """ L{Server} instances have a string representation indicating on which port they're running, and the connected address is stored on the C{peerAddresses} attribute of the factory. """ return self._testServerAddress("127.0.0.1", socket.AF_INET, IPv4Address) def test_serverAddressTCP6(self): """ IPv6 L{Server} instances have a string representation indicating on which port they're running, and the connected address is stored on the C{peerAddresses} attribute of the factory. """ return self._testServerAddress(getLinkLocalIPv6Address(), socket.AF_INET6, IPv6Address) if ipv6Skip: test_serverAddressTCP6.skip = ipv6Skip class TCPTransportTestsBuilder(TCPTransportServerAddressTestMixin, WriteSequenceTestsMixin, ReactorBuilder): """ Test standard L{ITCPTransport}s built with C{listenTCP} and C{connectTCP}. """ def getConnectedClientAndServer(self, reactor, interface, addressFamily): """ Return a L{Deferred} firing with a L{MyClientFactory} and L{MyServerFactory} connected pair, and the listening C{Port}. """ server = MyServerFactory() server.protocolConnectionMade = Deferred() server.protocolConnectionLost = Deferred() client = MyClientFactory() client.protocolConnectionMade = Deferred() client.protocolConnectionLost = Deferred() port = reactor.listenTCP(0, server, interface=interface) lostDeferred = gatherResults([client.protocolConnectionLost, server.protocolConnectionLost]) def stop(result): reactor.stop() return result lostDeferred.addBoth(stop) startDeferred = gatherResults([client.protocolConnectionMade, server.protocolConnectionMade]) deferred = Deferred() def start(protocols): client, server = protocols log.msg("client connected %s" % client) log.msg("server connected %s" % server) deferred.callback((client, server, port)) startDeferred.addCallback(start) reactor.connectTCP(interface, port.getHost().port, client) return deferred class AdoptStreamConnectionTestsBuilder(TCPTransportServerAddressTestMixin, WriteSequenceTestsMixin, ReactorBuilder): """ Test server transports built using C{adoptStreamConnection}. """ requiredInterfaces = (IReactorFDSet, IReactorSocket) def getConnectedClientAndServer(self, reactor, interface, addressFamily): """ Return a L{Deferred} firing with a L{MyClientFactory} and L{MyServerFactory} connected pair, and the listening C{Port}. The particularity is that the server protocol has been obtained after doing a C{adoptStreamConnection} against the original server connection. """ firstServer = MyServerFactory() firstServer.protocolConnectionMade = Deferred() server = MyServerFactory() server.protocolConnectionMade = Deferred() server.protocolConnectionLost = Deferred() client = MyClientFactory() client.protocolConnectionMade = Deferred() client.protocolConnectionLost = Deferred() port = reactor.listenTCP(0, firstServer, interface=interface) def firtServerConnected(proto): reactor.removeReader(proto.transport) reactor.removeWriter(proto.transport) reactor.adoptStreamConnection( proto.transport.fileno(), addressFamily, server) firstServer.protocolConnectionMade.addCallback(firtServerConnected) lostDeferred = gatherResults([client.protocolConnectionLost, server.protocolConnectionLost]) def stop(result): if reactor.running: reactor.stop() return result lostDeferred.addBoth(stop) deferred = Deferred() deferred.addErrback(stop) startDeferred = gatherResults([client.protocolConnectionMade, server.protocolConnectionMade]) def start(protocols): client, server = protocols log.msg("client connected %s" % client) log.msg("server connected %s" % server) deferred.callback((client, server, port)) startDeferred.addCallback(start) reactor.connectTCP(interface, port.getHost().port, client) return deferred globals().update(TCP4ClientTestsBuilder.makeTestCaseClasses()) globals().update(TCP6ClientTestsBuilder.makeTestCaseClasses()) globals().update(TCPPortTestsBuilder.makeTestCaseClasses()) globals().update(TCPFDPortTestsBuilder.makeTestCaseClasses()) globals().update(TCPConnectionTestsBuilder.makeTestCaseClasses()) globals().update(TCP4ConnectorTestsBuilder.makeTestCaseClasses()) globals().update(TCP6ConnectorTestsBuilder.makeTestCaseClasses()) globals().update(TCPTransportTestsBuilder.makeTestCaseClasses()) globals().update(AdoptStreamConnectionTestsBuilder.makeTestCaseClasses()) class ServerAbortsTwice(ConnectableProtocol): """ Call abortConnection() twice. """ def dataReceived(self, data): self.transport.abortConnection() self.transport.abortConnection() class ServerAbortsThenLoses(ConnectableProtocol): """ Call abortConnection() followed by loseConnection(). """ def dataReceived(self, data): self.transport.abortConnection() self.transport.loseConnection() class AbortServerWritingProtocol(ConnectableProtocol): """ Protocol that writes data upon connection. """ def
(self): """ Tell the client that the connection is set up and it's time to abort. """ self.transport.write(b"ready") class ReadAbortServerProtocol(AbortServerWritingProtocol): """ Server that should never receive any data, except 'X's which are written by the other side of the connection before abortConnection, and so might possibly arrive. """ def dataReceived(self, data): if data.replace(b'X', b''): raise Exception("Unexpectedly received data.") class NoReadServer(ConnectableProtocol): """ Stop reading immediately on connection. This simulates a lost connection that will cause the other side to time out, and therefore call abortConnection(). """ def connectionMade(self): self.transport.stopReading() class EventualNoReadServer(ConnectableProtocol): """ Like NoReadServer, except we Wait until some bytes have been delivered before stopping reading. This means TLS handshake has finished, where applicable. """ gotData = False stoppedReading = False def dataReceived(self, data): if not self.gotData: self.gotData = True self.transport.registerProducer(self, False) self.transport.write(b"hello") def resumeProducing(self): if self.stoppedReading: return self.stoppedReading = True # We've written out the data: self.transport.stopReading() def pauseProducing(self): pass def stopProducing(self): pass class BaseAbortingClient(ConnectableProtocol): """ Base class for abort-testing clients. """ inReactorMethod = False def connectionLost(self, reason): if self.inReactorMethod: raise RuntimeError("BUG: connectionLost was called re-entrantly!") ConnectableProtocol.connectionLost(self, reason) class WritingButNotAbortingClient(BaseAbortingClient): """ Write data, but don't abort. """ def connectionMade(self): self.transport.write(b"hello") class AbortingClient(BaseAbortingClient): """ Call abortConnection() after writing some data. """ def dataReceived(self, data): """ Some data was received, so the connection is set up. """ self.inReactorMethod = True self.writeAndAbort() self.inReactorMethod = False def writeAndAbort(self): # X is written before abortConnection, and so there is a chance it # might arrive. Y is written after, and so no Ys should ever be # delivered: self.transport.write(b"X" * 10000) self.transport.abortConnection() self.transport.write(b"Y" * 10000) class AbortingTwiceClient(AbortingClient): """ Call abortConnection() twice, after writing some data. """ def writeAndAbort(self): AbortingClient.writeAndAbort(self) self.transport.abortConnection() class AbortingThenLosingClient(AbortingClient): """ Call abortConnection() and then loseConnection(). """ def writeAndAbort(self): AbortingClient.writeAndAbort(self) self.transport.loseConnection() class ProducerAbortingClient(ConnectableProtocol): """ Call abortConnection from doWrite, via resumeProducing. """ inReactorMethod = True producerStopped = False def write(self): self.transport.write(b"lalala" * 127000) self.inRegisterProducer = True self.transport.registerProducer(self, False) self.inRegisterProducer = False def connectionMade(self): self.write() def resumeProducing(self): self.inReactorMethod = True if not self.inRegisterProducer: self.transport.abortConnection() self.inReactorMethod = False def stopProducing(self): self.producerStopped = True def connectionLost(self, reason): if not self.producerStopped: raise RuntimeError("BUG: stopProducing() was never called.") if self.inReactorMethod: raise RuntimeError("BUG: connectionLost called re-entrantly!") ConnectableProtocol.connectionLost(self, reason) class StreamingProducerClient(ConnectableProtocol): """ Call abortConnection() when the other side has stopped reading. In particular, we want to call abortConnection() only once our local socket hits a state where it is no longer writeable. This helps emulate the most common use case for abortConnection(), closing a connection after a timeout, with write buffers being full. Since it's very difficult to know when this actually happens, we just write a lot of data, and assume at that point no more writes will happen. """ paused = False extraWrites = 0 inReactorMethod = False def connectionMade(self): self.write() def write(self): """ Write large amount to transport, then wait for a while for buffers to fill up. """ self.transport.registerProducer(self, True) for i in range(100): self.transport.write(b"1234567890" * 32000) def resumeProducing(self): self.paused = False def stopProducing(self): pass def pauseProducing(self): """ Called when local buffer fills up. The goal is to hit the point where the local file descriptor is not writeable (or the moral equivalent). The fact that pauseProducing has been called is not sufficient, since that can happen when Twisted's buffers fill up but OS hasn't gotten any writes yet. We want to be as close as possible to every buffer (including OS buffers) being full. So, we wait a bit more after this for Twisted to write out a few chunks, then abortConnection. """ if self.paused: return self.paused = True # The amount we wait is arbitrary, we just want to make sure some # writes have happened and outgoing OS buffers filled up -- see # http://twistedmatrix.com/trac/ticket/5303 for details: self.reactor.callLater(0.01, self.doAbort) def doAbort(self): if not self.paused: log.err(RuntimeError("BUG: We should be paused a this point.")) self.inReactorMethod = True self.transport.abortConnection() self.inReactorMethod = False def connectionLost(self, reason): # Tell server to start reading again so it knows to go away: self.otherProtocol.transport.startReading() ConnectableProtocol.connectionLost(self, reason) class StreamingProducerClientLater(StreamingProducerClient): """ Call abortConnection() from dataReceived, after bytes have been exchanged. """ def connectionMade(self): self.transport.write(b"hello") self.gotData = False def dataReceived(self, data): if not self.gotData: self.gotData = True self.write() class ProducerAbortingClientLater(ProducerAbortingClient): """ Call abortConnection from doWrite, via resumeProducing. Try to do so after some bytes have already been exchanged, so we don't interrupt SSL handshake. """ def connectionMade(self): # Override base class connectionMade(). pass def dataReceived(self, data): self.write() class DataReceivedRaisingClient(AbortingClient): """ Call abortConnection(), and then throw exception, from dataReceived. """ def dataReceived(self, data): self.transport.abortConnection() raise ZeroDivisionError("ONO") class ResumeThrowsClient(ProducerAbortingClient): """ Call abortConnection() and throw exception from resumeProducing(). """ def resumeProducing(self): if not self.inRegisterProducer: self.transport.abortConnection() raise ZeroDivisionError("ono!") def connectionLost(self, reason): # Base class assertion about stopProducing being called isn't valid; # if the we blew up in resumeProducing, consumers are justified in # giving up on the producer and not calling stopProducing. ConnectableProtocol.connectionLost(self, reason) class AbortConnectionMixin(object): """ Unit tests for L{ITransport.abortConnection}. """ # Override in subclasses, should be a EndpointCreator instance: endpoints = None def runAbortTest(self, clientClass, serverClass, clientConnectionLostReason=None): """ A test runner utility function, which hooks up a matched pair of client and server protocols. We then run the reactor until both sides have disconnected, and then verify that the right exception resulted. """ clientExpectedExceptions = (ConnectionAborted, ConnectionLost) serverExpectedExceptions = (ConnectionLost, ConnectionDone) # In TLS tests we may get SSL.Error instead of ConnectionLost, # since we're trashing the TLS protocol layer. if useSSL: clientExpectedExceptions = clientExpectedExceptions + (SSL.Error,) serverExpectedExceptions = serverExpectedExceptions + (SSL.Error,) client = clientClass() server = serverClass() client.otherProtocol = server server.otherProtocol = client reactor = runProtocolsWithReactor(self, server, client, self.endpoints) # Make sure everything was shutdown correctly: self.assertEqual(reactor.removeAll(), []) # The reactor always has a timeout added in runReactor(): delayedCalls = reactor.getDelayedCalls() self.assertEqual(len(delayedCalls), 1, map(str, delayedCalls)) if clientConnectionLostReason is not None: self.assertIsInstance( client.disconnectReason.value, (clientConnectionLostReason,) + clientExpectedExceptions) else: self.assertIsInstance(client.disconnectReason.value, clientExpectedExceptions) self.assertIsInstance(server.disconnectReason.value, serverExpectedExceptions) def test_dataReceivedAbort(self): """ abortConnection() is called in dataReceived. The protocol should be disconnected, but connectionLost should not be called re-entrantly. """ return self.runAbortTest(AbortingClient, ReadAbortServerProtocol) def test_clientAbortsConnectionTwice(self): """ abortConnection() is called twice by client. No exception should be thrown, and the connection will be closed. """ return self.runAbortTest(AbortingTwiceClient, ReadAbortServerProtocol) def test_clientAbortsConnectionThenLosesConnection(self): """ Client calls abortConnection(), followed by loseConnection(). No exception should be thrown, and the connection will be closed. """ return self.runAbortTest(AbortingThenLosingClient, ReadAbortServerProtocol) def test_serverAbortsConnectionTwice(self): """ abortConnection() is called twice by server. No exception should be thrown, and the connection will be closed. """ return self.runAbortTest(WritingButNotAbortingClient, ServerAbortsTwice, clientConnectionLostReason=ConnectionLost) def test_serverAbortsConnectionThenLosesConnection(self): """ Server calls abortConnection(), followed by loseConnection(). No exception should be thrown, and the connection will be closed. """ return self.runAbortTest(WritingButNotAbortingClient, ServerAbortsThenLoses, clientConnectionLostReason=ConnectionLost) def test_resumeProducingAbort(self): """ abortConnection() is called in resumeProducing, before any bytes have been exchanged. The protocol should be disconnected, but connectionLost should not be called re-entrantly. """ self.runAbortTest(ProducerAbortingClient, ConnectableProtocol) def test_resumeProducingAbortLater(self): """ abortConnection() is called in resumeProducing, after some bytes have been exchanged. The protocol should be disconnected. """ return self.runAbortTest(ProducerAbortingClientLater, AbortServerWritingProtocol) def test_fullWriteBuffer(self): """ abortConnection() triggered by the write buffer being full. In particular, the server side stops reading. This is supposed to simulate a realistic timeout scenario where the client notices the server is no longer accepting data. The protocol should be disconnected, but connectionLost should not be called re-entrantly. """ self.runAbortTest(StreamingProducerClient, NoReadServer) def test_fullWriteBufferAfterByteExchange(self): """ abortConnection() is triggered by a write buffer being full. However, this buffer is filled after some bytes have been exchanged, allowing a TLS handshake if we're testing TLS. The connection will then be lost. """ return self.runAbortTest(StreamingProducerClientLater, EventualNoReadServer) def test_dataReceivedThrows(self): """ dataReceived calls abortConnection(), and then raises an exception. The connection will be lost, with the thrown exception (C{ZeroDivisionError}) as the reason on the client. The idea here is that bugs should not be masked by abortConnection, in particular unexpected exceptions. """ self.runAbortTest(DataReceivedRaisingClient, AbortServerWritingProtocol, clientConnectionLostReason=ZeroDivisionError) errors = self.flushLoggedErrors(ZeroDivisionError) self.assertEqual(len(errors), 1) def test_resumeProducingThrows(self): """ resumeProducing calls abortConnection(), and then raises an exception. The connection will be lost, with the thrown exception (C{ZeroDivisionError}) as the reason on the client. The idea here is that bugs should not be masked by abortConnection, in particular unexpected exceptions. """ self.runAbortTest(ResumeThrowsClient, ConnectableProtocol, clientConnectionLostReason=ZeroDivisionError) errors = self.flushLoggedErrors(ZeroDivisionError) self.assertEqual(len(errors), 1) class AbortConnectionTestCase(ReactorBuilder, AbortConnectionMixin): """ TCP-specific L{AbortConnectionMixin} tests. """ requiredInterfaces = (IReactorTCP,) endpoints = TCPCreator() globals().update(AbortConnectionTestCase.makeTestCaseClasses()) class SimpleUtilityTestCase(TestCase): """ Simple, direct tests for helpers within L{twisted.internet.tcp}. """ if ipv6Skip: skip = ipv6Skip def test_resolveNumericHost(self): """ L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when invoked with a non-numeric host. (In other words, it is passing L{socket.AI_NUMERICHOST} to L{socket.getaddrinfo} and will not accidentally block if it receives bad input.) """ err = self.assertRaises(socket.gaierror, _resolveIPv6, "localhost", 1) self.assertEqual(err.args[0], socket.EAI_NONAME) def test_resolveNumericService(self): """ L{_resolveIPv6} raises a L{socket.gaierror} (L{socket.EAI_NONAME}) when invoked with a non-numeric port. (In other words, it is passing L{socket.AI_NUMERICSERV} to L{socket.getaddrinfo} and will not accidentally block if it receives bad input.) """ err = self.assertRaises(socket.gaierror, _resolveIPv6, "::1", "http") self.assertEqual(err.args[0], socket.EAI_NONAME) if platform.isWindows(): test_resolveNumericService.skip = ("The AI_NUMERICSERV flag is not " "supported by Microsoft providers.") # http://msdn.microsoft.com/en-us/library/windows/desktop/ms738520.aspx def test_resolveIPv6(self): """ L{_resolveIPv6} discovers the flow info and scope ID of an IPv6 address. """ result = _resolveIPv6("::1", 2) self.assertEqual(len(result), 4) # We can't say anything more useful about these than that they're # integers, because the whole point of getaddrinfo is that you can never # know a-priori know _anything_ about the network interfaces of the # computer that you're on and you have to ask it. self.assertIsInstance(result[2], int) # flow info self.assertIsInstance(result[3], int) # scope id # but, luckily, IP presentation format and what it means to be a port # number are a little better specified. self.assertEqual(result[:2], ("::1", 2))
connectionMade
worker.go
// Copyright 2021 Northern.tech AS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package worker import ( "context" "os" "os/signal" "github.com/pkg/errors" "golang.org/x/sys/unix" "github.com/mendersoftware/go-lib-micro/config" "github.com/mendersoftware/go-lib-micro/log" dconfig "github.com/mendersoftware/workflows/config" "github.com/mendersoftware/workflows/model" "github.com/mendersoftware/workflows/store" ) // Workflows filters workflows executed by a worker type Workflows struct { Included []string Excluded []string } // InitAndRun initializes the worker and runs it func
(conf config.Reader, workflows Workflows, dataStore store.DataStore) error { ctx, cancel := context.WithCancel(context.Background()) // Calling cancel() before returning should shut down // all workers. However, the new driver is not // particularly good at listening to the context in the // current state, but it'll be forced to shut down // eventually. defer cancel() if conf.GetBool(dconfig.SettingDebugLog) { log.Setup(true) } l := log.FromContext(ctx) err := dataStore.LoadWorkflows(ctx, l) if err != nil { return errors.Wrap(err, "failed to load workflows") } channel, err := dataStore.GetJobs(ctx, workflows.Included, workflows.Excluded) if err != nil { return errors.Wrap(err, "Failed to start job scheduler") } var msg interface{} concurrency := conf.GetInt(dconfig.SettingConcurrency) sem := make(chan bool, concurrency) quit := make(chan os.Signal, 1) signal.Notify(quit, unix.SIGINT, unix.SIGTERM) for { select { case msg = <-channel: case <-quit: signal.Stop(quit) l.Info("Shutdown Worker ...") return err } if msg == nil { break } switch msg := msg.(type) { case *model.Job: job := msg sem <- true go func(ctx context.Context, job *model.Job, dataStore store.DataStore) { defer func() { <-sem }() l.Infof("Worker: processing job %s workflow %s", job.ID, job.WorkflowName) err := processJob(ctx, job, dataStore) if err != nil { l.Errorf("error: %v", err) } }(ctx, job, dataStore) case error: return msg } } return err }
InitAndRun
capture.py
# Copyright (c) 2021 Food-X Technologies # # This file is part of foodx_devops_tools. # # You should have received a copy of the MIT License along with # foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>. import contextlib import io import sys @contextlib.contextmanager def
(reset_seek: bool = True) -> None: new_stderr = io.StringIO() new_stdout = io.StringIO() with contextlib.redirect_stderr( new_stderr ) as err, contextlib.redirect_stdout(new_stdout) as out: yield out, err if reset_seek: # Reset the file pointer to the beginning of the stream. out.seek(0) err.seek(0)
capture_stdout_stderr
usbhs_hstpipifr.rs
#[doc = "Writer for register USBHS_HSTPIPIFR[%s]"] pub type W = crate::W<u32, super::USBHS_HSTPIPIFR>; #[doc = "Register USBHS_HSTPIPIFR[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::USBHS_HSTPIPIFR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `RXINIS`"] pub struct RXINIS_W<'a> { w: &'a mut W, } impl<'a> RXINIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Write proxy for field `TXOUTIS`"] pub struct TXOUTIS_W<'a> { w: &'a mut W, } impl<'a> TXOUTIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `TXSTPIS`"] pub struct TXSTPIS_W<'a> { w: &'a mut W, } impl<'a> TXSTPIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `PERRIS`"] pub struct PERRIS_W<'a> { w: &'a mut W, } impl<'a> PERRIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `NAKEDIS`"] pub struct NAKEDIS_W<'a> { w: &'a mut W, } impl<'a> NAKEDIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `OVERFIS`"] pub struct OVERFIS_W<'a> { w: &'a mut W, } impl<'a> OVERFIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `RXSTALLDIS`"] pub struct RXSTALLDIS_W<'a> { w: &'a mut W, } impl<'a> RXSTALLDIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `SHORTPACKETIS`"] pub struct SHORTPACKETIS_W<'a> { w: &'a mut W, } impl<'a> SHORTPACKETIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `NBUSYBKS`"] pub struct NBUSYBKS_W<'a> { w: &'a mut W, } impl<'a> NBUSYBKS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } impl W { #[doc = "Bit 0 - Received IN Data Interrupt Set"] #[inline(always)] pub fn rxinis(&mut self) -> RXINIS_W { RXINIS_W { w: self } } #[doc = "Bit 1 - Transmitted OUT Data Interrupt Set"] #[inline(always)] pub fn txoutis(&mut self) -> TXOUTIS_W { TXOUTIS_W { w: self } } #[doc = "Bit 2 - Transmitted SETUP Interrupt Set"] #[inline(always)] pub fn txstpis(&mut self) -> TXSTPIS_W { TXSTPIS_W { w: self } } #[doc = "Bit 3 - Pipe Error Interrupt Set"] #[inline(always)] pub fn perris(&mut self) -> PERRIS_W { PERRIS_W { w: self } } #[doc = "Bit 4 - NAKed Interrupt Set"] #[inline(always)] pub fn nakedis(&mut self) -> NAKEDIS_W { NAKEDIS_W { w: self } } #[doc = "Bit 5 - Overflow Interrupt Set"] #[inline(always)] pub fn overfis(&mut self) -> OVERFIS_W { OVERFIS_W { w: self } } #[doc = "Bit 6 - Received STALLed Interrupt Set"] #[inline(always)] pub fn rxstalldis(&mut self) -> RXSTALLDIS_W { RXSTALLDIS_W { w: self } } #[doc = "Bit 7 - Short Packet Interrupt Set"] #[inline(always)] pub fn shortpacketis(&mut self) -> SHORTPACKETIS_W { SHORTPACKETIS_W { w: self } } #[doc = "Bit 12 - Number of Busy Banks Set"] #[inline(always)] pub fn nbusybks(&mut self) -> NBUSYBKS_W { NBUSYBKS_W { w: self } } }
{ self.bit(false) }
mod.rs
use bracket_algorithm_traits::prelude::Algorithm2D; use bracket_geometry::prelude::Point; use std::collections::HashSet; mod recursive_shadowcasting; // Default algorithm / backwards compatibility pub use recursive_shadowcasting::{field_of_view, field_of_view_set}; mod symmetric_shadowcasting; /// Enumeration of available FOV algorithms #[derive(Clone, Copy)] #[non_exhaustive] // Other algorithms may be added in the future pub enum FieldOfViewAlg { RecursiveShadowcasting, SymmetricShadowcasting, } impl FieldOfViewAlg { pub fn field_of_view_set( self, center: Point, range: i32, fov_check: &dyn Algorithm2D, ) -> HashSet<Point> { match self { FieldOfViewAlg::RecursiveShadowcasting => { recursive_shadowcasting::field_of_view_set(center, range, fov_check) } FieldOfViewAlg::SymmetricShadowcasting => { symmetric_shadowcasting::field_of_view_set(center, range, fov_check) } } } pub fn field_of_view( self, start: Point, range: i32, fov_check: &dyn Algorithm2D, ) -> Vec<Point> { match self { FieldOfViewAlg::RecursiveShadowcasting => { recursive_shadowcasting::field_of_view(start, range, fov_check) } FieldOfViewAlg::SymmetricShadowcasting => { symmetric_shadowcasting::field_of_view(start, range, fov_check) } } } } #[cfg(test)] mod tests { use crate::prelude::FieldOfViewAlg; use bracket_algorithm_traits::prelude::{Algorithm2D, BaseMap}; use bracket_geometry::prelude::{BresenhamCircle, Point}; use std::cmp::max; use std::collections::HashSet; use std::hash::Hash; const TESTMAP_W: usize = 20; const TESTMAP_H: usize = 20; const TESTMAP_TILES: usize = (TESTMAP_W * TESTMAP_H) as usize; const ALGORITHS: [FieldOfViewAlg; 2] = [ FieldOfViewAlg::RecursiveShadowcasting, FieldOfViewAlg::SymmetricShadowcasting, ]; struct Map { pub tiles: Vec<bool>, } impl Map { fn new() -> Map { Map { tiles: vec![false; TESTMAP_TILES], } } } // The map needs to be see-through for the tests to check FOV impl BaseMap for Map { fn is_opaque(&self, idx: usize) -> bool { self.tiles[idx] } }
fn dimensions(&self) -> Point { Point::new(TESTMAP_W, TESTMAP_H) } } fn has_unique_elements<T>(iter: T) -> bool where T: IntoIterator, T::Item: Eq + Hash, { let mut uniq = HashSet::new(); iter.into_iter().all(move |x| uniq.insert(x)) } // Tests that we are correctly de-duplicating field of view #[test] fn fov_dupes() { let map = Map::new(); for alg in ALGORITHS { let visible = alg.field_of_view(Point::new(10, 10), 8, &map); assert!(has_unique_elements(&visible)); } } // Tests that the bounds-checking trait is applying properly to field-of-view checks #[test] fn fov_bounds_check() { let map = Map::new(); for alg in ALGORITHS { let visible = alg.field_of_view(Point::new(2, 2), 8, &map); for t in visible.iter() { assert!(t.x >= 0); assert!(t.x < TESTMAP_W as i32 - 1); assert!(t.y >= 0); assert!(t.y < TESTMAP_H as i32 - 1); } } } // Tests that the FOV scan does not miss any interior points #[test] fn fov_inclusive() { for radius in 4..=9 { let map = Map::new(); let dimensions = map.dimensions(); let c = Point::new(10, 10); for alg in ALGORITHS { let visible = alg.field_of_view(c, radius, &map); // let max_radius_sq: i32 = visible.iter().fold(0, |max_r2, p| { let max_radius_sq: i32 = BresenhamCircle::new(c, radius).fold(0, |max_r2, p| { let r2 = (p.x - c.x) * (p.x - c.x) + (p.y - c.y) * (p.y - c.y); max(r2, max_r2) }); /* for y in 0..dimensions.y { let mut s = "".to_string(); for x in 0..dimensions.x { let point = Point::new(x, y); let c = if visible.contains(&point) { '.' } else { '#' }; s.push(c); } println!("{}", s); } */ for x in 0..dimensions.x { for y in 0..dimensions.y { let r2 = (x - c.x) * (x - c.x) + (y - c.y) * (y - c.y); let point = Point::new(x, y); assert!( r2 >= max_radius_sq || visible.contains(&point), "Interior point ({:?}) not in FOV({})", point, radius ); } } } } } #[test] fn fov_corridor() { let mut map = Map::new(); let c = Point::new(10, 10); let radius: i32 = 5; for i in 0..20 { let idx = 9 * 20 + i; map.tiles[idx] = true; let idx = 11 * 20 + i; map.tiles[idx] = true; } for alg in ALGORITHS { let visible = alg.field_of_view(c, radius, &map); for i in 1..radius * 2 - 2 { let pos = Point::new(c.x - radius + i, c.y); assert!(visible.contains(&pos)); let pos = Point::new(c.x - radius + i, c.y - 1); assert!(visible.contains(&pos), "{:?} not in result", pos); let pos = Point::new(c.x - radius + i, c.y + 1); assert!(visible.contains(&pos)); } } } // NOTE: Symmetry applies to FieldOfViewAlg::SymmetricShadowcasting only #[test] fn fov_symmetric() { use bracket_random::prelude::RandomNumberGenerator; let mut rng = RandomNumberGenerator::seeded(0); let mut map = Map::new(); let c = Point::new(10, 10); let radius: i32 = 8; for _ in 0..TESTMAP_TILES / 5 { map.tiles[rng.range(0, TESTMAP_TILES)] = true; } map.tiles[c.to_index(TESTMAP_W)] = false; for point in FieldOfViewAlg::SymmetricShadowcasting.field_of_view_set(c, radius, &map) { // Symmetry only holds for transparent tiles if !map.tiles[point.to_index(TESTMAP_W)] { assert!(FieldOfViewAlg::SymmetricShadowcasting .field_of_view_set(point, radius, &map) .contains(&c)); } } } }
impl Algorithm2D for Map {
mpo_ops_test.py
# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for mpo_ops.py.""" import functools import math from absl.testing import absltest from absl.testing import parameterized import haiku as hk import jax import jax.numpy as jnp import numpy as np import optax from rlax._src import distributions from rlax._src import mpo_ops NUM_SAMPLES = 10 ACTION_DIM = 3 TIME_DIM = 8 BATCH_DIM = 100 # NOTE: These are not typical values used for MPO. In the test case, we know the # Q function perfectly so we loosen the bound on the mean to zone in to the # optimal policy very quickly. Similarly, we maintain a high variance to sample # distinct actions to explore and learn from. _INIT_TEMPERATURE = 0.2 _INIT_ALPHA_MEAN = 0.001 _INIT_ALPHA_COVARIANCE = float(1e6) _EPSILON_BOUND = 0.01 _EPSILON_MEAN_BOUND = 10.0 _EPSILON_COVARIANCE_BOUND = 1e-12 _NUM_ITERATIONS = 5000 _TARGET_UPDATE_PERIOD = 100 _RANDOM_SEED = 42 # The offset to ensure initially the policy is not close to 0 _MEAN_OFFSET = 2.0 # The final action should optimize down to be close to 0.0 _MAX_ACTION_ERROR = 0.2 _MAX_KL_ERROR = 1e-6 _DIAGONAL_GAUSSIAN_DIST = distributions.gaussian_diagonal() _PROJECTION_OPERATOR = functools.partial(jnp.clip, a_min=1e-10) def _hk_mock_policy_params(s_tm1): """Returns mock policy params.""" # Outputs of the network are mu and sigma. Both shaped [B, ACTION_DIM]. pi_out = hk.nets.MLP( output_sizes=[2 * ACTION_DIM], w_init=hk.initializers.VarianceScaling(1e-3), activation=jnp.tanh, activate_final=False, name='online_policy')(s_tm1) pi_mean, pi_cov = jnp.split(pi_out, 2, axis=-1) pi_cov = jax.nn.softplus(pi_cov) pi_mean = pi_mean + _MEAN_OFFSET return {'mean': pi_mean, 'stddev': pi_cov} def _init_params(key): init_fn, _ = hk.transform(_hk_mock_policy_params) key_seq = hk.PRNGSequence(key) s_tm1 = jax.random.normal( next(key_seq), (TIME_DIM, BATCH_DIM, ACTION_DIM), jnp.float32) online_params = init_fn(next(key_seq), s_tm1) return dict( online=online_params, target=online_params, mpo=dict( temperature=_INIT_TEMPERATURE, alpha_mean=_INIT_ALPHA_MEAN, alpha_covariance=_INIT_ALPHA_COVARIANCE), ) def _mock_outputs(online_params, target_params, key, target_name): """Returns mock network outputs.""" _, policy_params_fn = hk.transform(_hk_mock_policy_params) key_seq = hk.PRNGSequence(key) state_size = ACTION_DIM # Input state: [TIME_DIM, BATCH_DIM, DIM_STATE] s_tm1 = jax.random.normal( next(key_seq), (TIME_DIM, BATCH_DIM, state_size), jnp.float32) policy_params = policy_params_fn(online_params, None, s_tm1) target_policy_params = policy_params_fn(target_params, None, s_tm1) # Shape for actions: [NUM_SAMPLES, TIME_DIM, BATCH_DIM, ACTION_DIM] mean, stddev = target_policy_params['mean'], target_policy_params['stddev'] mean_repeated = jnp.repeat( mean.reshape((1,) + mean.shape), NUM_SAMPLES, axis=0) stddev_repeated = jnp.repeat( stddev.reshape((1,) + stddev.shape), NUM_SAMPLES, axis=0) target_actions = _DIAGONAL_GAUSSIAN_DIST.sample( next(key_seq), mean_repeated, stddev_repeated) # If the target is advantages then num samples is 1. if target_name == 'advantages': target_actions = target_actions[0, ...] # Shape for Q: [NUM_SAMPLES, TIME_DIM, BATCH_DIM] # Setting Q = -a_t * tf.transpose(a_t) where a_t = s_t + a. # The solution to optimizing this is basically for the policy to output # 0 actions thereby minimizing the cost. Since this is a convex # optimization problem, the algorithm should get to a good solution quickly. # First compute a_t = s_t + a with shape: [NUM_SAMPLES, TIME_DIM, BATCH_DIM, # ACTION_DIM] since action dim is the same as shape dim here and then compute # the quadratic form. a_t = target_actions + jnp.expand_dims(s_tm1, 0) sample_q_values = -jnp.sum(a_t ** 2, axis=-1) # Set the advantage to the same as the q value. # Shape for advantages: [TIME_DIM, BATCH_DIM] advantages = sample_q_values[0, :, :] return dict( pi_params=policy_params, target_pi_params=target_policy_params, sample_q_values=sample_q_values, advantages=advantages, target_actions=target_actions, ) def get_common_loss_fn_inputs(params, key, target_name): out = _mock_outputs(params['online'], params['target'], key, target_name) pi_sample_log_probs = _DIAGONAL_GAUSSIAN_DIST.logprob( out['target_actions'], out['pi_params']['mean'], out['pi_params']['stddev']) return out, { 'sample_log_probs': pi_sample_log_probs, target_name: out[target_name], 'temperature_constraint': mpo_ops.LagrangePenalty( params['mpo']['temperature'], _EPSILON_BOUND)} def get_decoupled_kl_constraints(out, params, per_dimension): """Factorises KL for Gaussian.""" kl_mean, kl_covariance = ( distributions.decoupled_multivariate_normal_kl_divergence( out['target_pi_params']['mean'], out['target_pi_params']['stddev'], out['pi_params']['mean'], out['pi_params']['stddev'], per_dimension=per_dimension)) alpha_mean = params['mpo']['alpha_mean'] * jnp.ones_like(kl_mean) alpha_covariance = params['mpo']['alpha_covariance'] * jnp.ones_like( kl_covariance) return [ (kl_mean, mpo_ops.LagrangePenalty( alpha=alpha_mean, epsilon=_EPSILON_MEAN_BOUND, per_dimension=per_dimension)), (kl_covariance, mpo_ops.LagrangePenalty( alpha=alpha_covariance, epsilon=_EPSILON_COVARIANCE_BOUND, per_dimension=per_dimension)), ] def get_coupled_kl_constraints(out, params, per_dimension): kl_mean, kl_covariance = ( distributions.decoupled_multivariate_normal_kl_divergence( out['target_pi_params']['mean'], out['target_pi_params']['stddev'], out['pi_params']['mean'], out['pi_params']['stddev'], per_dimension=per_dimension)) alpha_mean = params['mpo']['alpha_mean'] * jnp.ones_like(kl_mean) return [ (kl_mean + kl_covariance, mpo_ops.LagrangePenalty( alpha=alpha_mean, epsilon=_EPSILON_MEAN_BOUND + _EPSILON_COVARIANCE_BOUND, per_dimension=per_dimension)) ] def vmpo_e_step_without_restarting_or_importance_weights(advantages, **kwargs): restarting_weights = jnp.ones_like(advantages) importance_weights = jnp.ones_like(advantages) return mpo_ops.vmpo_compute_weights_and_temperature_loss( advantages=advantages, restarting_weights=restarting_weights, importance_weights=importance_weights, **kwargs) class MPOTest(parameterized.TestCase): """Tests for the MPO losses.""" @parameterized.parameters( {'target_name': 'sample_q_values', 'loss_fn': mpo_ops.mpo_loss, 'get_kl_constraints': get_decoupled_kl_constraints, 'per_dimension': False}, {'target_name': 'advantages', 'loss_fn': mpo_ops.vmpo_loss, 'get_kl_constraints': get_decoupled_kl_constraints, 'per_dimension': False}, {'target_name': 'sample_q_values', 'loss_fn': mpo_ops.mpo_loss, 'get_kl_constraints': get_coupled_kl_constraints, 'per_dimension': False}, {'target_name': 'advantages', 'loss_fn': mpo_ops.vmpo_loss, 'get_kl_constraints': get_coupled_kl_constraints, 'per_dimension': False}, {'target_name': 'sample_q_values', 'loss_fn': mpo_ops.mpo_loss, 'get_kl_constraints': get_decoupled_kl_constraints, 'per_dimension': True}, {'target_name': 'advantages', 'loss_fn': mpo_ops.vmpo_loss, 'get_kl_constraints': get_decoupled_kl_constraints, 'per_dimension': True}, {'target_name': 'sample_q_values', 'loss_fn': mpo_ops.mpo_loss, 'get_kl_constraints': get_coupled_kl_constraints, 'per_dimension': True}, {'target_name': 'advantages', 'loss_fn': mpo_ops.vmpo_loss, 'get_kl_constraints': get_coupled_kl_constraints, 'per_dimension': True}, ) def test_optimization( self, target_name, loss_fn, get_kl_constraints, per_dimension): """Tests that the policy optimization works correctly.""" def _loss(params, key): out, loss_fn_inputs = get_common_loss_fn_inputs(params, key, target_name) kl_constraints = get_kl_constraints(out, params, per_dimension) loss_fn_inputs.update({'kl_constraints': kl_constraints}) loss, mpo_stats = loss_fn(**loss_fn_inputs) loss = jnp.mean(loss) temperature_bound = jnp.mean(mpo_stats.normalized_weights * jnp.log( mpo_stats.num_samples * mpo_stats.normalized_weights + 1e-8)) return loss, {'outputs': out, 'temperature_bound': temperature_bound} key = jax.random.PRNGKey(_RANDOM_SEED) grad_fn = jax.jit(jax.grad(_loss, has_aux=True)) optimizer = optax.adam(1e-3) key, new_key = jax.random.split(key) params = _init_params(new_key) opt_state = optimizer.init((params['online'], params['mpo'])) @jax.jit def _update(params_, opt_state_, key_): next_key, key_ = jax.random.split(key_) grad, stats = grad_fn(params_, key_) updates, opt_state_ = optimizer.update( (grad['online'], grad['mpo']), opt_state_) online_params, mpo_params = optax.apply_updates( (params_['online'], params_['mpo']), updates) params_['online'] = online_params params_['mpo'] = mpo_params return params_, opt_state_, stats, next_key for iter_idx in range(_NUM_ITERATIONS): params, opt_state, extra, key = _update(params, opt_state, key) if iter_idx % _TARGET_UPDATE_PERIOD == 0: params['target'] = params['online'] # Test the bounds are within tolerance. key, new_key = jax.random.split(key) _, extra = _loss(params, new_key) action_mean = jnp.mean(extra['outputs']['pi_params']['mean']) # Check action mean is close to 0. self.assertBetween(action_mean, -_MAX_ACTION_ERROR, _MAX_ACTION_ERROR) # Check the temperature are within the bounds. self.assertLess(extra['temperature_bound'], _EPSILON_BOUND) @parameterized.parameters( {'e_step_fn': mpo_ops.mpo_compute_weights_and_temperature_loss, 'additional_inputs': {}, # dL/dq == 1 and dL/dt == epsilon (for one sample) 'expected_deriv_of_target': [[[1]]], 'sample_dimension': True}, {'e_step_fn': vmpo_e_step_without_restarting_or_importance_weights, 'additional_inputs': {'top_k_fraction': 1.0}, 'expected_deriv_of_target': [[1]], 'sample_dimension': False}, ) def test_e_step_gradient_computation( self, e_step_fn, additional_inputs, expected_deriv_of_target, sample_dimension): """Tests the gradients from the E-step against the analytic ones.""" # Target has shape [NUM_SAMPLES, T, B] => [1, 1, 1] target = jnp.array([[3]], jnp.float32) if sample_dimension: target = jnp.expand_dims(target, axis=0) temperature = jnp.array(0.1, jnp.float32) def fn(target_, temperature_): temperature_constraint = mpo_ops.LagrangePenalty( temperature_, _EPSILON_BOUND) temperature_loss, _, _ = e_step_fn( target_, temperature_constraint=temperature_constraint, projection_operator=_PROJECTION_OPERATOR, **additional_inputs) return jnp.mean(temperature_loss) grad = jax.grad(fn, argnums=(0, 1))(target, temperature) np.testing.assert_almost_equal(np.array(grad[0]), np.array( expected_deriv_of_target, np.float32), decimal=4) self.assertAlmostEqual(grad[1], _EPSILON_BOUND, places=4) @parameterized.parameters( {'e_step_fn': mpo_ops.mpo_compute_weights_and_temperature_loss, 'additional_inputs': {}, 'sample_dimension': True}, {'e_step_fn': vmpo_e_step_without_restarting_or_importance_weights, 'additional_inputs': {'top_k_fraction': 1.0}, 'sample_dimension': False}, ) def test_e_step_stop_gradient( self, e_step_fn, additional_inputs, sample_dimension): """Tests no gradients flow through `weights` in the E-Step.""" # Target has shape [NUM_SAMPLES, T, B] => [1, 1, 1] target = jnp.array([[3]], jnp.float32) if sample_dimension: target = jnp.expand_dims(target, axis=0) temperature = 0.1 # pylint: disable=g-long-lambda def mean_weights_fn(target_, temperature_): temperature_constraint = mpo_ops.LagrangePenalty( temperature_, _EPSILON_BOUND) _, weights, _ = e_step_fn( target_, temperature_constraint=temperature_constraint, projection_operator=_PROJECTION_OPERATOR, **additional_inputs) return jnp.mean(weights) grad = jax.grad(mean_weights_fn, argnums=(0, 1))(target, temperature) np.testing.assert_almost_equal( np.array(grad[0]), np.zeros_like(grad[0]), decimal=4) self.assertAlmostEqual(grad[1], 0., places=4) def test_kl_constraint_loss_gradients(self): """Tests the gradients in the `_kl_constraint_loss` method.""" kl = jnp.array(1., jnp.float32) alpha = jnp.array(1., jnp.float32) _, _, alpha = mpo_ops.kl_constraint_loss(kl, mpo_ops.LagrangePenalty( alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False), _PROJECTION_OPERATOR) def alpha_loss_fn(alpha_): penalty = mpo_ops.LagrangePenalty( alpha=alpha_, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False) _, alpha_loss, _ = mpo_ops.kl_constraint_loss( kl, penalty, _PROJECTION_OPERATOR) return alpha_loss alpha_gradients = jax.grad(alpha_loss_fn)(alpha) actual_alpha_gradients = _EPSILON_MEAN_BOUND - kl def kl_loss_fn(kl_): penalty = mpo_ops.LagrangePenalty( alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False) kl_loss, _, _ = mpo_ops.kl_constraint_loss( kl_, penalty, _PROJECTION_OPERATOR) return kl_loss kl_gradients = jax.grad(kl_loss_fn)(kl) actual_kl_gradients = alpha self.assertAlmostEqual(kl_gradients, actual_kl_gradients) self.assertAlmostEqual(alpha_gradients, actual_alpha_gradients) def test_kl_constraint_loss_stop_gradients(self): """Tests the stop gradients in the `kl_constraint_loss` function. The `alpha_loss` term should not affect the KL and the `kl` term should not affect `alpha`. """ kl = jnp.array(1., jnp.float32) alpha = jnp.array(1., jnp.float32) _, _, alpha = mpo_ops.kl_constraint_loss(kl, mpo_ops.LagrangePenalty( alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False), _PROJECTION_OPERATOR) def kl_loss_fn(alpha_): penalty = mpo_ops.LagrangePenalty( alpha=alpha_, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False) kl_loss, _, _ = mpo_ops.kl_constraint_loss( kl, penalty, _PROJECTION_OPERATOR) return kl_loss kl_gradients = jax.grad(kl_loss_fn)(alpha) def
(kl_): penalty = mpo_ops.LagrangePenalty( alpha=alpha, epsilon=_EPSILON_MEAN_BOUND, per_dimension=False) _, alpha_loss, _ = mpo_ops.kl_constraint_loss( kl_, penalty, _PROJECTION_OPERATOR) return alpha_loss alpha_gradients = jax.grad(alpha_loss_fn)(kl) # Test that there are no gradients of KL w.r.t alpha self.assertEqual(kl_gradients, 0.) # Test that there are no gradients of alpha w.r.t kl self.assertEqual(alpha_gradients, 0.) @parameterized.parameters( # With restarting weights of 1 (and temperature of 1) the weights should # be e^-1, 1, max advantage is 2 and num samples is 2 so temperature loss # is log(1 + e^-1) + 2 - log(2) + temperature epsilon {'advantages': np.array([[1.0, 2.0]]), 'restarting_weights': np.array([[1.0, 1.0]]), 'expected_temperature_loss': (math.log(1.0 + math.exp(-1.0)) + 2.0 - math.log(2.0) + _EPSILON_BOUND)}, # With the second restarting weight set to 0 the weights become 1, 0 # max advantage is 1 and num samples is 1 so temperature loss is # log(1) + 1 - log(1) + temperature epsilon {'advantages': np.array([[1.0, 2.0]]), 'restarting_weights': np.array([[1.0, 0.0]]), 'expected_temperature_loss': 1.0 + _EPSILON_BOUND}, ) def test_restarting_weights( self, advantages, restarting_weights, expected_temperature_loss): """Test that calculation is correct if restarting weight is set to 0.""" temperature_loss, _, _ = mpo_ops.vmpo_compute_weights_and_temperature_loss( advantages, restarting_weights, np.ones_like(restarting_weights), mpo_ops.LagrangePenalty(1.0, _EPSILON_BOUND), functools.partial(np.clip, a_min=1e-8, a_max=None), 1.0) self.assertAlmostEqual( temperature_loss, expected_temperature_loss, places=4) @parameterized.parameters( # When the top k fraction is 1.0 all of the weights should be 1 {'top_k_fraction': 1.0, 'scaled_advantages': np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), 'expected_top_k_weights': np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])}, # When the top k fraction is 0.5 it will take the bottom row as these are # the highest. {'top_k_fraction': 0.5, 'scaled_advantages': np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), 'expected_top_k_weights': np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])} ) def test_top_k_fraction( self, top_k_fraction, scaled_advantages, expected_top_k_weights): """Test that only the top k fraction are used.""" top_k_weights = mpo_ops.get_top_k_weights( top_k_fraction, jnp.ones_like(scaled_advantages), scaled_advantages) np.testing.assert_allclose(top_k_weights, expected_top_k_weights) def test_top_k_fraction_too_low(self): """Test if the top k fraction returns 0 advantages we raise an error.""" with self.assertRaises(ValueError): mpo_ops.get_top_k_weights(0.01, jnp.ones((3, 2)), jnp.ones((3, 2))) @parameterized.parameters( # With importance weights of 1 (and temperature of 1) the weights should # be e^-1, 1, max advantage is 2 and num samples is 2 so temperature loss # is log(1 + e^-1) + 2 - log(2) + temperature epsilon {'advantages': np.array([[1.0, 2.0]]), 'importance_weights': np.array([[1.0, 1.0]]), 'expected_temperature_loss': (math.log(1.0 + math.exp(-1.0)) + 2.0 - math.log(2.0) + _EPSILON_BOUND)}, # If the second importance weight is 0.5 temperature loss becomes # log(0.5 + e^-1) + 2 - log(2) + temperature epsilon {'advantages': np.array([[1.0, 2.0]]), 'importance_weights': np.array([[1.0, 0.5]]), 'expected_temperature_loss': (math.log(0.5 + math.exp(-1.0)) + 2.0 - math.log(2.0) + _EPSILON_BOUND)}, ) def test_importance_weights( self, advantages, importance_weights, expected_temperature_loss): """Test that importance weights have the correct effect.""" temperature_loss, _, _ = mpo_ops.vmpo_compute_weights_and_temperature_loss( advantages, np.ones_like(importance_weights), importance_weights, mpo_ops.LagrangePenalty(1.0, _EPSILON_BOUND), functools.partial(np.clip, a_min=1e-8, a_max=None), 1.0) self.assertAlmostEqual( temperature_loss, expected_temperature_loss, places=4) @parameterized.parameters({'per_dimension': True}, {'per_dimension': False}) def test_mpo_input_axis_order_equivalence(self, per_dimension): """Test loss functions are equivalent regardless of axis order.""" key = jax.random.PRNGKey(_RANDOM_SEED) key, new_key = jax.random.split(key) params = _init_params(new_key) out, mpo_inputs = get_common_loss_fn_inputs(params, key, 'sample_q_values') kl_constraints = get_coupled_kl_constraints(out, params, per_dimension=per_dimension) mpo_inputs.update({'kl_constraints': kl_constraints}) # Original loss fn inputs are [S T B], stb_loss, stb_outputs = mpo_ops.mpo_loss(**mpo_inputs) mean_stb_loss = jnp.mean(stb_loss) # Swap axes and try [S B T] mpo_inputs.update({ 'sample_log_probs': jnp.swapaxes(mpo_inputs['sample_log_probs'], 1, 2), 'sample_q_values': jnp.swapaxes(mpo_inputs['sample_q_values'], 1, 2), 'kl_constraints': [(jnp.swapaxes(kl, 0, 1), mpo_ops.LagrangePenalty( alpha=jnp.swapaxes(pen.alpha, 0, 1), epsilon=pen.epsilon, per_dimension=pen.per_dimension)) for (kl, pen) in kl_constraints], }) sbt_loss, sbt_outputs = mpo_ops.mpo_loss(**mpo_inputs) mean_sbt_loss = jnp.mean(sbt_loss) # Try [T B S] denoting sample_axis at 2 instead of 0. mpo_inputs.update({ 'sample_log_probs': jnp.swapaxes(mpo_inputs['sample_log_probs'], 0, 2), 'sample_q_values': jnp.swapaxes(mpo_inputs['sample_q_values'], 0, 2), 'kl_constraints': kl_constraints, # T B 'sample_axis': 2 }) tbs_loss, tbs_outputs = mpo_ops.mpo_loss(**mpo_inputs) mean_tbs_loss = jnp.mean(tbs_loss) self.assertAlmostEqual(mean_stb_loss, mean_sbt_loss, places=4) self.assertAlmostEqual(mean_tbs_loss, mean_sbt_loss, places=4) self.assertEqual(tbs_outputs.num_samples, sbt_outputs.num_samples) self.assertEqual(tbs_outputs.num_samples, stb_outputs.num_samples) @parameterized.parameters({'per_dimension': True}, {'per_dimension': False}) def test_vmpo_input_axis_order_equivalence(self, per_dimension): """Test loss functions are equivalent regardless of axis order.""" key = jax.random.PRNGKey(_RANDOM_SEED) key, new_key = jax.random.split(key) params = _init_params(new_key) out, vmpo_inputs = get_common_loss_fn_inputs(params, key, 'advantages') kl_constraints = get_coupled_kl_constraints(out, params, per_dimension=per_dimension) vmpo_inputs.update({'kl_constraints': kl_constraints}) # Original loss fn inputs are [T B], tb_loss, tb_outputs = mpo_ops.vmpo_loss(**vmpo_inputs) mean_tb_loss = jnp.mean(tb_loss) # Swap axes and try [B T] vmpo_inputs.update({ 'sample_log_probs': jnp.swapaxes(vmpo_inputs['sample_log_probs'], 0, 1), 'advantages': jnp.swapaxes(vmpo_inputs['advantages'], 0, 1), 'kl_constraints': [(jnp.swapaxes(kl, 0, 1), mpo_ops.LagrangePenalty( alpha=jnp.swapaxes(pen.alpha, 0, 1), epsilon=pen.epsilon, per_dimension=pen.per_dimension)) for (kl, pen) in kl_constraints], }) bt_loss, bt_outputs = mpo_ops.vmpo_loss(**vmpo_inputs) mean_bt_loss = jnp.mean(bt_loss) self.assertAlmostEqual(mean_tb_loss, mean_bt_loss, places=4) self.assertEqual(tb_outputs.num_samples, bt_outputs.num_samples) if __name__ == '__main__': absltest.main()
alpha_loss_fn
test_jwtutil.py
import jwt from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from authlib.jose import jwk from util.security.jwtutil import ( decode, exp_max_s_option, jwk_dict_to_public_key, InvalidTokenError, InvalidAlgorithmError, ) @pytest.fixture(scope="session") def private_key(): return rsa.generate_private_key( public_exponent=65537, key_size=2048, ) @pytest.fixture(scope="session") def private_key_pem(private_key): return private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) @pytest.fixture(scope="session") def public_key(private_key): return private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) def _token_data(audience, subject, iss, iat=None, exp=None, nbf=None): return { "iss": iss, "aud": audience, "nbf": nbf() if nbf is not None else int(time.time()), "iat": iat() if iat is not None else int(time.time()), "exp": exp() if exp is not None else int(time.time() + 3600), "sub": subject, } @pytest.mark.parametrize( "aud, iss, nbf, iat, exp, expected_exception", [ pytest.param( "invalidaudience", "someissuer", None, None, None, "Invalid audience", id="invalid audience", ), pytest.param( "someaudience", "invalidissuer", None, None, None, "Invalid issuer", id="invalid issuer" ), pytest.param( "someaudience", "someissuer", lambda: time.time() + 120, None, None, "The token is not yet valid", id="invalid not before", ), pytest.param( "someaudience", "someissuer", None, lambda: time.time() + 120, None, "Issued At claim", id="issued at in future", ), pytest.param( "someaudience", "someissuer", None, None, lambda: time.time() - 100, "Signature has expired", id="already expired", ), pytest.param( "someaudience", "someissuer", None, None, lambda: time.time() + 10000, "Token was signed for more than", id="expiration too far in future", ), pytest.param( "someaudience", "someissuer", lambda: time.time() + 10, None, None, None, id="not before in future by within leeway", ), pytest.param( "someaudience", "someissuer", None, lambda: time.time() + 10, None, None, id="issued at in future but within leeway", ), pytest.param( "someaudience", "someissuer", None, None, lambda: time.time() - 10, None, id="expiration in past but within leeway", ), ], ) def test_decode_jwt_validation( aud, iss, nbf, iat, exp, expected_exception, private_key_pem, public_key ): token = jwt.encode(_token_data(aud, "subject", iss, iat, exp, nbf), private_key_pem, "RS256") if expected_exception is not None: with pytest.raises(InvalidTokenError) as ite: max_exp = exp_max_s_option(3600) decode( token, public_key, algorithms=["RS256"], audience="someaudience", issuer="someissuer", options=max_exp, leeway=60, ) assert ite.match(expected_exception) else: max_exp = exp_max_s_option(3600) decode( token, public_key, algorithms=["RS256"], audience="someaudience", issuer="someissuer", options=max_exp, leeway=60, ) def test_decode_jwt_invalid_key(private_key_pem): # Encode with the test private key. token = jwt.encode(_token_data("aud", "subject", "someissuer"), private_key_pem, "RS256") # Try to decode with a different public key. another_public_key = ( rsa.generate_private_key( public_exponent=65537, key_size=2048, ) .public_key() .public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) ) with pytest.raises(InvalidTokenError) as ite: max_exp = exp_max_s_option(3600) decode( token, another_public_key, algorithms=["RS256"], audience="aud", issuer="someissuer", options=max_exp, leeway=60, ) assert ite.match("Signature verification failed") def test_decode_jwt_invalid_algorithm(private_key_pem, public_key): # Encode with the test private key. token = jwt.encode(_token_data("aud", "subject", "someissuer"), private_key_pem, "RS256") # Attempt to decode but only with a different algorithm than that used. with pytest.raises(InvalidAlgorithmError) as ite: max_exp = exp_max_s_option(3600) decode( token, public_key, algorithms=["ES256"], audience="aud", issuer="someissuer", options=max_exp, leeway=60, ) assert ite.match("are not whitelisted") def test_jwk_dict_to_public_key(private_key, private_key_pem): public_key = private_key.public_key() key_dict = jwk.dumps( public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ) ) converted = jwk_dict_to_public_key(key_dict) # Encode with the test private key. token = jwt.encode(_token_data("aud", "subject", "someissuer"), private_key_pem, "RS256") # Decode with the converted key. max_exp = exp_max_s_option(3600) decode( token, converted, algorithms=["RS256"], audience="aud", issuer="someissuer", options=max_exp, leeway=60, )
import time import pytest
config.go
package params import ( "fmt" "math/big" "github.com/ethereum/go-ethereum/common" ) // Well-known chain IDs. var ( MainnetChainID = big.NewInt(1) TestnetChainID = big.NewInt(2) PangaeaChainID = big.NewInt(3) PartnerChainID = big.NewInt(4) StressnetChainID = big.NewInt(5) TestChainID = big.NewInt(99) // not a real network AllProtocolChangesChainID = big.NewInt(100) // not a real network ) // EpochTBD is a large, “not anytime soon” epoch. It used as a placeholder // until the exact epoch is decided. var EpochTBD = big.NewInt(10000000) var ( // MainnetChainConfig is the chain parameters to run a node on the main network. MainnetChainConfig = &ChainConfig{ ChainID: MainnetChainID, CrossTxEpoch: big.NewInt(28), CrossLinkEpoch: EpochTBD, StakingEpoch: EpochTBD, PreStakingEpoch: EpochTBD, EIP155Epoch: big.NewInt(28), S3Epoch: big.NewInt(28), ReceiptLogEpoch: big.NewInt(101), } // TestnetChainConfig contains the chain parameters to run a node on the harmony test network. TestnetChainConfig = &ChainConfig{ ChainID: TestnetChainID, CrossTxEpoch: big.NewInt(0), CrossLinkEpoch: big.NewInt(4), StakingEpoch: big.NewInt(4), PreStakingEpoch: big.NewInt(2), EIP155Epoch: big.NewInt(0), S3Epoch: big.NewInt(0), ReceiptLogEpoch: big.NewInt(0), } // PangaeaChainConfig contains the chain parameters for the Pangaea network. // All features except for CrossLink are enabled at launch. PangaeaChainConfig = &ChainConfig{ ChainID: PangaeaChainID, CrossTxEpoch: big.NewInt(0), CrossLinkEpoch: big.NewInt(2), StakingEpoch: big.NewInt(2), PreStakingEpoch: big.NewInt(1), EIP155Epoch: big.NewInt(0), S3Epoch: big.NewInt(0), ReceiptLogEpoch: big.NewInt(0), } // PartnerChainConfig contains the chain parameters for the Partner network. // All features except for CrossLink are enabled at launch. PartnerChainConfig = &ChainConfig{ ChainID: PartnerChainID, CrossTxEpoch: big.NewInt(0), CrossLinkEpoch: big.NewInt(2), StakingEpoch: big.NewInt(2), PreStakingEpoch: big.NewInt(1), EIP155Epoch: big.NewInt(0), S3Epoch: big.NewInt(0), ReceiptLogEpoch: big.NewInt(0), } // StressnetChainConfig contains the chain parameters for the Stress test network. // All features except for CrossLink are enabled at launch. StressnetChainConfig = &ChainConfig{ ChainID: StressnetChainID, CrossTxEpoch: big.NewInt(0), CrossLinkEpoch: big.NewInt(2), StakingEpoch: big.NewInt(2), PreStakingEpoch: big.NewInt(1), EIP155Epoch: big.NewInt(0), S3Epoch: big.NewInt(0), ReceiptLogEpoch: big.NewInt(0), } // LocalnetChainConfig contains the chain parameters to run for local development. LocalnetChainConfig = &ChainConfig{ ChainID: TestnetChainID, CrossTxEpoch: big.NewInt(0), CrossLinkEpoch: big.NewInt(2), StakingEpoch: big.NewInt(2), PreStakingEpoch: big.NewInt(0), EIP155Epoch: big.NewInt(0), S3Epoch: big.NewInt(0), ReceiptLogEpoch: big.NewInt(0), } // AllProtocolChanges ... // This configuration is intentionally not using keyed fields to force anyone // adding flags to the config to also have to set these fields. AllProtocolChanges = &ChainConfig{ AllProtocolChangesChainID, // ChainID big.NewInt(0), // CrossTxEpoch big.NewInt(0), // CrossLinkEpoch big.NewInt(0), // StakingEpoch big.NewInt(0), // PreStakingEpoch big.NewInt(0), // EIP155Epoch big.NewInt(0), // S3Epoch big.NewInt(0), // ReceiptLogEpoch } // TestChainConfig ... // This configuration is intentionally not using keyed fields to force anyone // adding flags to the config to also have to set these fields. TestChainConfig = &ChainConfig{ TestChainID, // ChainID big.NewInt(0), // CrossTxEpoch big.NewInt(0), // CrossLinkEpoch big.NewInt(0), // StakingEpoch big.NewInt(0), // PreStakingEpoch big.NewInt(0), // EIP155Epoch big.NewInt(0), // S3Epoch big.NewInt(0), // ReceiptLogEpoch } // TestRules ... TestRules = TestChainConfig.Rules(new(big.Int)) ) // TrustedCheckpoint represents a set of post-processed trie roots (CHT and // BloomTrie) associated with the appropriate section index and head hash. It is // used to start light syncing from this checkpoint and avoid downloading the // entire header chain while still being able to securely access old headers/logs. type TrustedCheckpoint struct { Name string `json:"-"` SectionIndex uint64 `json:"sectionIndex"` SectionHead common.Hash `json:"sectionHead"` CHTRoot common.Hash `json:"chtRoot"` BloomRoot common.Hash `json:"bloomRoot"` } // ChainConfig is the core config which determines the blockchain settings. // // ChainConfig is stored in the database on a per block basis. This means // that any network, identified by its genesis block, can have its own // set of configuration options. type ChainConfig struct { // ChainId identifies the current chain and is used for replay protection ChainID *big.Int `json:"chain-id"` // CrossTxEpoch is the epoch where cross-shard transaction starts being // processed. CrossTxEpoch *big.Int `json:"cross-tx-epoch,omitempty"` // CrossLinkEpoch is the epoch where beaconchain starts containing // cross-shard links. CrossLinkEpoch *big.Int `json:"cross-link-epoch,omitempty"` // StakingEpoch is the epoch when shard assign takes staking into account StakingEpoch *big.Int `json:"staking-epoch,omitempty"` // PreStakingEpoch is the epoch we allow staking transactions PreStakingEpoch *big.Int `json:"prestaking-epoch,omitempty"` // EIP155 hard fork epoch (include EIP158 too) EIP155Epoch *big.Int `json:"eip155-epoch,omitempty"` // S3 epoch is the first epoch containing S3 mainnet and all ethereum update up to Constantinople S3Epoch *big.Int `json:"s3-epoch,omitempty"` // ReceiptLogEpoch is the first epoch support receiptlog ReceiptLogEpoch *big.Int `json:"receipt-log-epoch,omitempty"` } // String implements the fmt.Stringer interface. func (c *ChainConfig) String() string { return fmt.Sprintf("{ChainID: %v EIP155: %v CrossTx: %v Staking: %v CrossLink: %v ReceiptLog: %v}", c.ChainID, c.EIP155Epoch, c.CrossTxEpoch, c.StakingEpoch, c.CrossLinkEpoch, c.ReceiptLogEpoch, ) } // IsEIP155 returns whether epoch is either equal to the EIP155 fork epoch or greater. func (c *ChainConfig) IsEIP155(epoch *big.Int) bool { return isForked(c.EIP155Epoch, epoch) } // AcceptsCrossTx returns whether cross-shard transaction is accepted in the // given epoch. // // Note that this is different from comparing epoch against CrossTxEpoch. // Cross-shard transaction is accepted from CrossTxEpoch+1 and on, in order to // allow for all shards to roll into CrossTxEpoch and become able to handle // ingress receipts. In other words, cross-shard transaction fields are // introduced and ingress receipts are processed at CrossTxEpoch, but the shard // does not accept cross-shard transactions from clients until CrossTxEpoch+1. func (c *ChainConfig) AcceptsCrossTx(epoch *big.Int) bool { crossTxEpoch := new(big.Int).Add(c.CrossTxEpoch, common.Big1) return isForked(crossTxEpoch, epoch) } // HasCrossTxFields returns whether blocks in the given epoch includes // cross-shard transaction fields. func (c *ChainConfig) HasCrossTxFields(epoch *big.Int) bool { return isForked(c.CrossTxEpoch, epoch) } // IsStaking determines whether it is staking epoch func (c *ChainConfig) IsStaking(epoch *big.Int) bool { return isForked(c.StakingEpoch, epoch) } // IsPreStaking determines whether staking transactions are allowed func (c *ChainConfig) IsPreStaking(epoch *big.Int) bool { return isForked(c.PreStakingEpoch, epoch) } // IsCrossLink returns whether epoch is either equal to the CrossLink fork epoch or greater. func (c *ChainConfig) IsCrossLink(epoch *big.Int) bool { return isForked(c.CrossLinkEpoch, epoch) } // IsS3 returns whether epoch is either equal to the S3 fork epoch or greater. func (c *ChainConfig) IsS3(epoch *big.Int) bool { return isForked(c.S3Epoch, epoch) } // IsReceiptLog returns whether epoch is either equal to the ReceiptLog fork epoch or greater. func (c *ChainConfig) IsReceiptLog(epoch *big.Int) bool { return isForked(c.ReceiptLogEpoch, epoch) } // GasTable returns the gas table corresponding to the current phase (homestead or homestead reprice). // // The returned GasTable's fields shouldn't, under any circumstances, be changed. func (c *ChainConfig) GasTable(epoch *big.Int) GasTable { if epoch == nil { return GasTableR3 } switch { case c.IsS3(epoch): return GasTableS3 default: return GasTableR3 } } // CheckCompatible checks whether scheduled fork transitions have been imported // with a mismatching chain configuration. func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64) *ConfigCompatError { bhead := new(big.Int).SetUint64(height) // Iterate checkCompatible to find the lowest conflict. var lasterr *ConfigCompatError for { err := c.checkCompatible(newcfg, bhead) if err == nil || (lasterr != nil && err.RewindTo == lasterr.RewindTo) { break } lasterr = err bhead.SetUint64(err.RewindTo) } return lasterr } func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, head *big.Int) *ConfigCompatError { // TODO: check compatibility and reversion based on epochs. //if isForkIncompatible(c.EIP155Epoch, newcfg.EIP155Epoch, head) { // return newCompatError("EIP155 fork block", c.EIP155Epoch, newcfg.EIP155Epoch) //} //if isForkIncompatible(c.CrossLinkEpoch, newcfg.CrossLinkEpoch, head) { // return newCompatError("CrossLink fork block", c.CrossLinkEpoch, newcfg.CrossLinkEpoch) //} //if isForkIncompatible(c.S3Epoch, newcfg.S3Epoch, head) { // return newCompatError("S3 fork block", c.S3Epoch, newcfg.S3Epoch) //} return nil } // isForkIncompatible returns true if a fork scheduled at s1 cannot be rescheduled to // epoch s2 because head is already past the fork. func isForkIncompatible(s1, s2, epoch *big.Int) bool { return (isForked(s1, epoch) || isForked(s2, epoch)) && !configNumEqual(s1, s2) } // isForked returns whether a fork scheduled at epoch s is active at the given head epoch. func isForked(s, epoch *big.Int) bool { if s == nil || epoch == nil { return false } return s.Cmp(epoch) <= 0 } func conf
y *big.Int) bool { if x == nil { return y == nil } if y == nil { return x == nil } return x.Cmp(y) == 0 } // ConfigCompatError is raised if the locally-stored blockchain is initialised with a // ChainConfig that would alter the past. type ConfigCompatError struct { What string // block numbers of the stored and new configurations StoredConfig, NewConfig *big.Int // the block number to which the local chain must be rewound to correct the error RewindTo uint64 } func newCompatError(what string, storedblock, newblock *big.Int) *ConfigCompatError { var rew *big.Int switch { case storedblock == nil: rew = newblock case newblock == nil || storedblock.Cmp(newblock) < 0: rew = storedblock default: rew = newblock } err := &ConfigCompatError{what, storedblock, newblock, 0} if rew != nil && rew.Sign() > 0 { err.RewindTo = rew.Uint64() - 1 } return err } func (err *ConfigCompatError) Error() string { return fmt.Sprintf("mismatching %s in database (have %d, want %d, rewindto %d)", err.What, err.StoredConfig, err.NewConfig, err.RewindTo) } // Rules wraps ChainConfig and is merely syntactic sugar or can be used for functions // that do not have or require information about the block. // // Rules is a one time interface meaning that it shouldn't be used in between transition // phases. type Rules struct { ChainID *big.Int IsCrossLink, IsEIP155, IsS3, IsReceiptLog bool } // Rules ensures c's ChainID is not nil. func (c *ChainConfig) Rules(epoch *big.Int) Rules { chainID := c.ChainID if chainID == nil { chainID = new(big.Int) } return Rules{ ChainID: new(big.Int).Set(chainID), IsCrossLink: c.IsCrossLink(epoch), IsEIP155: c.IsEIP155(epoch), IsS3: c.IsS3(epoch), IsReceiptLog: c.IsReceiptLog(epoch), } }
igNumEqual(x,
backend-data.ts
export interface BackendData {
status: string, data: any }
snap.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const builder_util_1 = require("builder-util"); const builder_util_runtime_1 = require("builder-util-runtime"); const fs_extra_1 = require("fs-extra"); const js_yaml_1 = require("js-yaml"); const path = require("path"); const semver = require("semver"); const core_1 = require("../core"); const pathManager_1 = require("../util/pathManager"); const targetUtil_1 = require("./targetUtil"); const defaultPlugs = ["desktop", "desktop-legacy", "home", "x11", "wayland", "unity7", "browser-support", "network", "gsettings", "audio-playback", "pulseaudio", "opengl"]; class SnapTarget extends core_1.Target { constructor(name, packager, helper, outDir) { super(name); this.packager = packager; this.helper = helper; this.outDir = outDir; this.options = { ...this.packager.platformSpecificBuildOptions, ...this.packager.config[this.name] }; this.isUseTemplateApp = false; } replaceDefault(inList, defaultList) { const result = builder_util_1.replaceDefault(inList, defaultList); if (result !== defaultList) { this.isUseTemplateApp = false; } return result; } async createDescriptor(arch) { if (!this.isElectronVersionGreaterOrEqualThan("4.0.0")) { if (!this.isElectronVersionGreaterOrEqualThan("2.0.0-beta.1")) { throw new builder_util_1.InvalidConfigurationError("Electron 2 and higher is required to build Snap"); } builder_util_1.log.warn("Electron 4 and higher is highly recommended for Snap"); } const appInfo = this.packager.appInfo; const snapName = this.packager.executableName.toLowerCase(); const options = this.options; const plugs = normalizePlugConfiguration(this.options.plugs); const plugNames = this.replaceDefault(plugs == null ? null : Object.getOwnPropertyNames(plugs), defaultPlugs); const slots = normalizePlugConfiguration(this.options.slots); const buildPackages = builder_util_runtime_1.asArray(options.buildPackages); const defaultStagePackages = getDefaultStagePackages(); const stagePackages = this.replaceDefault(options.stagePackages, defaultStagePackages); this.isUseTemplateApp = this.options.useTemplateApp !== false && (arch === builder_util_1.Arch.x64 || arch === builder_util_1.Arch.armv7l) && buildPackages.length === 0 && isArrayEqualRegardlessOfSort(stagePackages, defaultStagePackages); const appDescriptor = { command: "command.sh", plugs: plugNames, adapter: "none", }; const snap = js_yaml_1.load(await fs_extra_1.readFile(path.join(pathManager_1.getTemplatePath("snap"), "snapcraft.yaml"), "utf-8")); if (this.isUseTemplateApp) { delete appDescriptor.adapter; } if (options.grade != null) { snap.grade = options.grade; } if (options.confinement != null) { snap.confinement = options.confinement; } if (options.appPartStage != null) { snap.parts.app.stage = options.appPartStage; } if (options.layout != null) { snap.layout = options.layout; } if (slots != null) { appDescriptor.slots = Object.getOwnPropertyNames(slots); for (const slotName of appDescriptor.slots) { const slotOptions = slots[slotName]; if (slotOptions == null) { continue; } if (!snap.slots) { snap.slots = {}; } snap.slots[slotName] = slotOptions; } } builder_util_1.deepAssign(snap, { name: snapName, version: appInfo.version, title: options.title || appInfo.productName, summary: options.summary || appInfo.productName, description: this.helper.getDescription(options), architectures: [builder_util_1.toLinuxArchString(arch, "snap")], apps: { [snapName]: appDescriptor, }, parts: { app: { "stage-packages": stagePackages, }, }, }); if (options.autoStart) { appDescriptor.autostart = `${snap.name}.desktop`; } if (options.confinement === "classic") { delete appDescriptor.plugs; delete snap.plugs; } else { const archTriplet = archNameToTriplet(arch); appDescriptor.environment = { // https://github.com/electron-userland/electron-builder/issues/4007 // https://github.com/electron/electron/issues/9056 DISABLE_WAYLAND: "1", TMPDIR: "$XDG_RUNTIME_DIR", PATH: "$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH", SNAP_DESKTOP_RUNTIME: "$SNAP/gnome-platform", LD_LIBRARY_PATH: [ "$SNAP_LIBRARY_PATH", "$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/" + archTriplet + ":$SNAP/usr/lib/" + archTriplet, "$LD_LIBRARY_PATH:$SNAP/lib:$SNAP/usr/lib", "$SNAP/lib/" + archTriplet + ":$SNAP/usr/lib/" + archTriplet, ].join(":"), ...options.environment, }; if (plugs != null) { for (const plugName of plugNames) {
} snap.plugs[plugName] = plugOptions; } } } if (buildPackages.length > 0) { snap.parts.app["build-packages"] = buildPackages; } if (options.after != null) { snap.parts.app.after = options.after; } if (options.assumes != null) { snap.assumes = builder_util_runtime_1.asArray(options.assumes); } return snap; } async build(appOutDir, arch) { const packager = this.packager; const options = this.options; // tslint:disable-next-line:no-invalid-template-strings const artifactName = packager.expandArtifactNamePattern(this.options, "snap", arch, "${name}_${version}_${arch}.${ext}", false); const artifactPath = path.join(this.outDir, artifactName); await packager.info.callArtifactBuildStarted({ targetPresentableName: "snap", file: artifactPath, arch, }); const snap = await this.createDescriptor(arch); if (this.isUseTemplateApp) { delete snap.parts; } const stageDir = await targetUtil_1.createStageDirPath(this, packager, arch); const snapArch = builder_util_1.toLinuxArchString(arch, "snap"); const args = ["snap", "--app", appOutDir, "--stage", stageDir, "--arch", snapArch, "--output", artifactPath, "--executable", this.packager.executableName]; await this.helper.icons; if (this.helper.maxIconPath != null) { if (!this.isUseTemplateApp) { snap.icon = "snap/gui/icon.png"; } args.push("--icon", this.helper.maxIconPath); } // snapcraft.yaml inside a snap directory const snapMetaDir = path.join(stageDir, this.isUseTemplateApp ? "meta" : "snap"); const desktopFile = path.join(snapMetaDir, "gui", `${snap.name}.desktop`); await this.helper.writeDesktopEntry(this.options, packager.executableName + " %U", desktopFile, { // tslint:disable:no-invalid-template-strings Icon: "${SNAP}/meta/gui/icon.png", }); if (this.isElectronVersionGreaterOrEqualThan("5.0.0") && !isBrowserSandboxAllowed(snap)) { args.push("--extraAppArgs=--no-sandbox"); if (this.isUseTemplateApp) { args.push("--exclude", "chrome-sandbox"); } } if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed({ snap, desktopFile, args }))) { return; } await fs_extra_1.outputFile(path.join(snapMetaDir, this.isUseTemplateApp ? "snap.yaml" : "snapcraft.yaml"), builder_util_1.serializeToYaml(snap)); const hooksDir = await packager.getResource(options.hooks, "snap-hooks"); if (hooksDir != null) { args.push("--hooks", hooksDir); } if (this.isUseTemplateApp) { args.push("--template-url", `electron4:${snapArch}`); } await builder_util_1.executeAppBuilder(args); await packager.info.callArtifactBuildCompleted({ file: artifactPath, safeArtifactName: packager.computeSafeArtifactName(artifactName, "snap", arch, false), target: this, arch, packager, publishConfig: options.publish == null ? { provider: "snapStore" } : null, }); } isElectronVersionGreaterOrEqualThan(version) { return semver.gte(this.packager.config.electronVersion || "7.0.0", version); } } exports.default = SnapTarget; function archNameToTriplet(arch) { switch (arch) { case builder_util_1.Arch.x64: return "x86_64-linux-gnu"; case builder_util_1.Arch.ia32: return "i386-linux-gnu"; case builder_util_1.Arch.armv7l: // noinspection SpellCheckingInspection return "arm-linux-gnueabihf"; case builder_util_1.Arch.arm64: return "aarch64-linux-gnu"; default: throw new Error(`Unsupported arch ${arch}`); } } function isArrayEqualRegardlessOfSort(a, b) { a = a.slice(); b = b.slice(); a.sort(); b.sort(); return a.length === b.length && a.every((value, index) => value === b[index]); } function normalizePlugConfiguration(raw) { if (raw == null) { return null; } const result = {}; for (const item of Array.isArray(raw) ? raw : [raw]) { if (typeof item === "string") { result[item] = null; } else { Object.assign(result, item); } } return result; } function isBrowserSandboxAllowed(snap) { if (snap.plugs != null) { for (const plugName of Object.keys(snap.plugs)) { const plug = snap.plugs[plugName]; if (plug.interface === "browser-support" && plug["allow-sandbox"] === true) { return true; } } } return false; } function getDefaultStagePackages() { // libxss1 - was "error while loading shared libraries: libXss.so.1" on Xubuntu 16.04 // noinspection SpellCheckingInspection return ["libnspr4", "libnss3", "libxss1", "libappindicator3-1", "libsecret-1-0"]; } //# sourceMappingURL=snap.js.map
const plugOptions = plugs[plugName]; if (plugOptions == null) { continue;
console.py
# ElectrumSV - lightweight BitcoinSV client # Copyright (C) 2012 thomasv@gitorious # Copyright (C) 2019-2020 The ElectrumSV Developers # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # source: http://stackoverflow.com/questions/2758159 import os import re import sys import traceback from PyQt5 import QtCore, QtWidgets from PyQt5.QtGui import QFont, QTextCursor, QTextOption from electrumsv import util from electrumsv.i18n import _ from electrumsv.logs import logs from electrumsv.platform import platform logger = logs.get_logger("console") class OverlayLabel(QtWidgets.QLabel): STYLESHEET = ''' QLabel, QLabel link { color: rgb(0, 0, 0); background-color: rgb(248, 240, 200); border: 1px solid; border-color: rgb(255, 114, 47); padding: 2px; } ''' def __init__(self, text, parent): super().__init__(text, parent) self.setMinimumHeight(150) self.setGeometry(0, 0, self.width(), self.height()) self.setStyleSheet(self.STYLESHEET) self.setMargin(0) parent.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.setWordWrap(True) def mousePressEvent(self, e): self.hide() def on_resize(self, w): padding = 2 # px, from the stylesheet above self.setFixedWidth(w - padding) class Console(QtWidgets.QPlainTextEdit): def __init__(self, prompt='>> ', startup_message='', parent=None): QtWidgets.QPlainTextEdit.__init__(self, parent) self.prompt = prompt self.history = [] self.namespace = {} self.construct = [] self.setGeometry(50, 75, 600, 400) self.setWordWrapMode(QTextOption.WrapAnywhere) self.setUndoRedoEnabled(False) self.document().setDefaultFont(QFont(platform.monospace_font, 10, QFont.Normal)) self.showMessage(startup_message) self.updateNamespace({'run': self.run_script}) self.set_json(False) warning_text = "<h1><center>{}</center></h1><br>{}<br><br>{}<br><br>{}".format( _("Warning!"), _("Do not run code here that you don't understand. Running bad or malicious code " "could lead to your coins being irreversibly lost."), _("Text shown here is sent by the server and may be malicious; ignore anything it " "might be asking you to do."), _("Click here to hide this message.") ) self.messageOverlay = OverlayLabel(warning_text, self) def resizeEvent(self, e): super().resizeEvent(e) scrollbar_width = self.verticalScrollBar().width() * self.verticalScrollBar().isVisible() self.messageOverlay.on_resize(self.width() - scrollbar_width) def set_json(self, b): self.is_json = b def run_script(self, filename): with open(filename) as f: script = f.read() # eval is generally considered bad practice. use it wisely! # pylint: disable=eval-used eval(script, self.namespace, self.namespace) def updateNamespace(self, namespace): self.namespace.update(namespace) def showMessage(self, message): self.appendPlainText(message) self.newPrompt() def clear(self): self.setPlainText('') self.newPrompt() def newPrompt(self): if self.construct: prompt = '.' * len(self.prompt) else: prompt = self.prompt self.completions_pos = self.textCursor().position() self.completions_visible = False self.appendPlainText(prompt) self.moveCursor(QTextCursor.End) def getCommand(self): doc = self.document() curr_line = doc.findBlockByLineNumber(doc.lineCount() - 1).text() curr_line = curr_line.rstrip() curr_line = curr_line[len(self.prompt):] return curr_line
def setCommand(self, command): if self.getCommand() == command: return doc = self.document() curr_line = doc.findBlockByLineNumber(doc.lineCount() - 1).text() self.moveCursor(QTextCursor.End) for i in range(len(curr_line) - len(self.prompt)): self.moveCursor(QTextCursor.Left, QTextCursor.KeepAnchor) self.textCursor().removeSelectedText() self.textCursor().insertText(command) self.moveCursor(QTextCursor.End) def show_completions(self, completions): if self.completions_visible: self.hide_completions() c = self.textCursor() c.setPosition(self.completions_pos) completions = [x.split('.')[-1] for x in completions] t = '\n' + ' '.join(completions) if len(t) > 500: t = t[:500] + '...' c.insertText(t) self.completions_end = c.position() self.moveCursor(QTextCursor.End) self.completions_visible = True def hide_completions(self): if not self.completions_visible: return c = self.textCursor() c.setPosition(self.completions_pos) for x in range(self.completions_end - self.completions_pos): c.deleteChar() self.moveCursor(QTextCursor.End) self.completions_visible = False def getConstruct(self, command): if self.construct: prev_command = self.construct[-1] self.construct.append(command) if not prev_command and not command: ret_val = '\n'.join(self.construct) self.construct = [] return ret_val else: return '' else: if command and command[-1] == (':'): self.construct.append(command) return '' else: return command def getHistory(self): return self.history def setHisory(self, history): self.history = history def addToHistory(self, command): if command[0:1] == ' ': return if command and (not self.history or self.history[-1] != command): self.history.append(command) self.history_index = len(self.history) def getPrevHistoryEntry(self): if self.history: self.history_index = max(0, self.history_index - 1) return self.history[self.history_index] return '' def getNextHistoryEntry(self): if self.history: hist_len = len(self.history) self.history_index = min(hist_len, self.history_index + 1) if self.history_index < hist_len: return self.history[self.history_index] return '' def getCursorPosition(self): c = self.textCursor() return c.position() - c.block().position() - len(self.prompt) def setCursorPosition(self, position): self.moveCursor(QTextCursor.StartOfLine) for i in range(len(self.prompt) + position): self.moveCursor(QTextCursor.Right) def register_command(self, c, func): methods = {c: func} self.updateNamespace(methods) def runCommand(self): command = self.getCommand() self.addToHistory(command) command = self.getConstruct(command) if command: tmp_stdout = sys.stdout class stdoutProxy(): def __init__(self, write_func): self.write_func = write_func self.skip = False def flush(self): pass def write(self, text): if not self.skip: stripped_text = text.rstrip('\n') self.write_func(stripped_text) QtCore.QCoreApplication.processEvents() self.skip = not self.skip sys.stdout = stdoutProxy(self.appendPlainText) try: try: # eval is generally considered bad practice. use it wisely! # pylint: disable=eval-used result = eval(command, self.namespace, self.namespace) if result is not None: if self.is_json: print(util.json_encode(result)) else: self.appendPlainText(repr(result)) except SyntaxError: # exec is generally considered bad practice. use it wisely! # pylint: disable=exec-used exec(command, self.namespace, self.namespace) except SystemExit: self.close() except Exception: # Catch errors in the network layer as well, as long as it uses Exception. traceback_lines = traceback.format_exc().split('\n') # Remove traceback mentioning this file, and a linebreak for i in (3, 2, 1, -1): traceback_lines.pop(i) self.appendPlainText('\n'.join(traceback_lines)) sys.stdout = tmp_stdout self.newPrompt() self.set_json(False) def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Tab: self.completions() return self.hide_completions() if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): self.runCommand() return if event.key() == QtCore.Qt.Key_Home: self.setCursorPosition(0) return if event.key() == QtCore.Qt.Key_PageUp: return elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace): if self.getCursorPosition() == 0: return elif event.key() == QtCore.Qt.Key_Up: self.setCommand(self.getPrevHistoryEntry()) return elif event.key() == QtCore.Qt.Key_Down: self.setCommand(self.getNextHistoryEntry()) return elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier: self.clear() super(Console, self).keyPressEvent(event) def completions(self): cmd = self.getCommand() lastword = re.split(r' |\(|\)', cmd)[-1] beginning = cmd[0: -len(lastword)] path = lastword.split('.') prefix = '.'.join(path[:-1]) prefix = (prefix + '.') if prefix else prefix ns = self.namespace.keys() if len(path) > 1: obj = self.namespace.get(path[0]) try: for attr in path[1:-1]: obj = getattr(obj, attr) except AttributeError: ns = [] else: ns = dir(obj) completions = [] for name in ns: if name[0] == '_': continue if name.startswith(path[-1]): completions.append(prefix + name) completions.sort() if not completions: self.hide_completions() elif len(completions) == 1: self.hide_completions() self.setCommand(beginning + completions[0]) else: # find common prefix p = os.path.commonprefix(completions) if len(p) > len(lastword): self.hide_completions() self.setCommand(beginning + p) else: self.show_completions(completions) welcome_message = ''' --------------------------------------------------------------- Welcome to a primitive Python interpreter. --------------------------------------------------------------- ''' if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) console = Console(startup_message=welcome_message) console.updateNamespace({'myVar1': app, 'myVar2': 1234}) console.show() sys.exit(app.exec_())
main.ts
import { Plugin, unified } from "unified"; import remarkParse from "remark-parse"; import rehypeParse from "rehype-parse"; import { selectAll } from "unist-util-select"; import { Node, visit } from "unist-util-visit"; import { HTML, Image } from "mdast"; import { Element } from "hast"; import rehypeStringify from "rehype-stringify"; import remarkStringify from "remark-stringify"; const markdown2Root = (markdown: string) => unified().use(remarkParse).parse(markdown); const html2Root = (html: string) => unified().use(rehypeParse, { emitParseErrors: true }).parse(html); const isRemarkImageNode = (node: Node): node is Image => node.type === "image"; const isRemarkHTMLNode = (node: Node): node is HTML => node.type === "html"; const isRehypeElementNode = (node: Node): node is Element => node.type === "element"; interface IRehypeMediaNode extends Element { properties: { src: string; }; } const isRehypeMediaTagName = (tagName: string) => ["video", "img"].includes(tagName); const isRehypeMediaNode = (node: Node): node is IRehypeMediaNode => !!( isRehypeElementNode(node) && isRehypeMediaTagName(node.tagName) && node.properties && node.properties.src ); interface IMediaUrlInfo { type: "video" | "image" | "unknown"; url: string; } const genGeneralMediaUrlInfo = ( type: IMediaUrlInfo["type"], url: IMediaUrlInfo["url"], ): IMediaUrlInfo => ({ type, url });
case "video": return "video"; case "img": return "image"; default: return "unknown"; } }; export const genAllMediaUrlInfosFromHTML = (html: string): IMediaUrlInfo[] => { const root = html2Root(html); const htmlNodes = selectAll( "element[tagName=video], element[tagName=img]", root, ) as Element[]; return ( htmlNodes.filter((element) => isRehypeMediaNode(element), ) as IRehypeMediaNode[] ).map((mediaElm) => genGeneralMediaUrlInfo( tagName2MediaType(mediaElm.tagName), mediaElm.properties.src, ), ); }; export const getAllImageUrls = (markdown: string) => { const root = markdown2Root(markdown); const imageNodes = selectAll("image[url]", root) as Image[]; return imageNodes.map((node) => node.url); }; export const getAllMediaUrlInfos = (markdown: string): IMediaUrlInfo[] => { const root = markdown2Root(markdown); const imgUrls = getAllImageUrls(markdown); const htmlNodes = selectAll("html", root) as HTML[]; const fromMarkdownNodes = imgUrls.map((url) => genGeneralMediaUrlInfo("image", url), ); const mediaInfosFromHtml = htmlNodes.flatMap(({ value }) => genAllMediaUrlInfosFromHTML(value), ); return [...fromMarkdownNodes, ...mediaInfosFromHtml]; }; export const getAllMediaUrls = (markdown: string) => getAllMediaUrlInfos(markdown).map(({ url }) => url); interface IURLMap { [key: string]: string; } export const remarkImageUrlReplacer = (urlMap: IURLMap): Plugin => () => { return (root) => { visit(root, (node) => { if (isRemarkImageNode(node) && urlMap[node.url]) { node.url = urlMap[node.url]; } }); }; }; export const rehypeMediaUrlReplacer = (urlMap: IURLMap): Plugin => () => { return (root) => { visit(root, (node) => { if (isRehypeMediaNode(node) && urlMap[node.properties.src]) { node.properties.src = urlMap[node.properties.src]; } }); }; }; export const replaceAllMediaUrlsInHTML = (urlMap: IURLMap, html: string) => { return unified() .use(rehypeParse, { fragment: true }) .use(rehypeMediaUrlReplacer(urlMap)) .use(rehypeStringify, { allowParseErrors: true }) .processSync(html) .toString(); }; export const remarkMediaUrlReplacer = (urlMap: IURLMap): Plugin => () => { return (root) => { visit(root, (node) => { if (isRemarkImageNode(node) && urlMap[node.url]) { node.url = urlMap[node.url]; return; } if (isRemarkHTMLNode(node)) { node.value = replaceAllMediaUrlsInHTML(urlMap, node.value); } }); }; }; export const replaceAllMediaUrlsInMarkdown = ( urlMap: IURLMap, markdown: string, ) => { return unified() .use(remarkParse) .use(remarkMediaUrlReplacer(urlMap)) .use(remarkStringify, { bullet: "-" }) .processSync(markdown) .toString(); };
const tagName2MediaType = (tagName: string): IMediaUrlInfo["type"] => { switch (tagName) {
csrapprove.go
package certificate import ( "context" "fmt" "strings" "github.com/openshift/library-go/pkg/controller/factory" "github.com/openshift/library-go/pkg/operator/events" certificatesv1 "k8s.io/api/certificates/v1beta1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" certificatesinformers "k8s.io/client-go/informers/certificates/v1beta1" "k8s.io/client-go/kubernetes" certificateslisters "k8s.io/client-go/listers/certificates/v1beta1" "k8s.io/klog/v2" "open-cluster-management.io/addon-framework/pkg/addonmanager/constants" "open-cluster-management.io/addon-framework/pkg/agent" addoninformerv1alpha1 "open-cluster-management.io/api/client/addon/informers/externalversions/addon/v1alpha1" addonlisterv1alpha1 "open-cluster-management.io/api/client/addon/listers/addon/v1alpha1" clusterinformers "open-cluster-management.io/api/client/cluster/informers/externalversions/cluster/v1" clusterlister "open-cluster-management.io/api/client/cluster/listers/cluster/v1" ) // csrApprovingController auto approve the renewal CertificateSigningRequests for an accepted spoke cluster on the hub. type csrApprovingController struct { kubeClient kubernetes.Interface agentAddons map[string]agent.AgentAddon eventRecorder events.Recorder managedClusterLister clusterlister.ManagedClusterLister managedClusterAddonLister addonlisterv1alpha1.ManagedClusterAddOnLister csrLister certificateslisters.CertificateSigningRequestLister } // NewCSRApprovingController creates a new csr approving controller func
( kubeClient kubernetes.Interface, clusterInformers clusterinformers.ManagedClusterInformer, csrInformer certificatesinformers.CertificateSigningRequestInformer, addonInformers addoninformerv1alpha1.ManagedClusterAddOnInformer, agentAddons map[string]agent.AgentAddon, recorder events.Recorder, ) factory.Controller { c := &csrApprovingController{ kubeClient: kubeClient, agentAddons: agentAddons, managedClusterLister: clusterInformers.Lister(), csrLister: csrInformer.Lister(), managedClusterAddonLister: addonInformers.Lister(), eventRecorder: recorder.WithComponentSuffix(fmt.Sprintf("csr-approving-controller")), } return factory.New(). WithFilteredEventsInformersQueueKeyFunc( func(obj runtime.Object) string { accessor, _ := meta.Accessor(obj) return accessor.GetName() }, func(obj interface{}) bool { accessor, _ := meta.Accessor(obj) if !strings.HasPrefix(accessor.GetName(), "addon") { return false } if len(accessor.GetLabels()) == 0 { return false } addonName := accessor.GetLabels()[constants.AddonLabel] if _, ok := agentAddons[addonName]; !ok { return false } return true }, csrInformer.Informer()). WithSync(c.sync). ToController("CSRApprovingController", recorder) } func (c *csrApprovingController) sync(ctx context.Context, syncCtx factory.SyncContext) error { csrName := syncCtx.QueueKey() klog.V(4).Infof("Reconciling CertificateSigningRequests %q", csrName) csr, err := c.csrLister.Get(csrName) if errors.IsNotFound(err) { return nil } if err != nil { return err } csr = csr.DeepCopy() if isCSRApproved(csr) || IsCSRInTerminalState(csr) { return nil } addonName := csr.Labels[constants.AddonLabel] agentAddon, ok := c.agentAddons[addonName] if !ok { return nil } registrationOption := agentAddon.GetAgentAddonOptions().Registration if registrationOption == nil { return nil } clusterName, ok := csr.Labels[constants.ClusterLabel] if !ok { return nil } // Get ManagedCluster managedCluster, err := c.managedClusterLister.Get(clusterName) if errors.IsNotFound(err) { return nil } if err != nil { return err } // Get Addon managedClusterAddon, err := c.managedClusterAddonLister.ManagedClusterAddOns(clusterName).Get(addonName) if errors.IsNotFound(err) { return nil } if err != nil { return err } if registrationOption.CSRApproveCheck == nil { klog.V(4).Infof("addon csr %q cannont be auto approved due to approve check not defined", csr.Name) return nil } approved := registrationOption.CSRApproveCheck(managedCluster, managedClusterAddon, csr) // Do not approve if csr check fails if !approved { klog.V(4).Infof("addon csr %q cannont be auto approved due to approve check fails", csr.Name) return nil } // Auto approve the spoke cluster csr csr.Status.Conditions = append(csr.Status.Conditions, certificatesv1.CertificateSigningRequestCondition{ Type: certificatesv1.CertificateApproved, Status: corev1.ConditionTrue, Reason: "AutoApprovedByHubCSRApprovingController", Message: "Auto approving addon agent certificate.", }) // _, err = c.kubeClient.CertificatesV1().CertificateSigningRequests().UpdateApproval(ctx, csr.Name, csr, metav1.UpdateOptions{}) _, err = c.kubeClient.CertificatesV1beta1().CertificateSigningRequests().UpdateApproval(ctx, csr, metav1.UpdateOptions{}) if err != nil { return err } c.eventRecorder.Eventf("AddonCSRAutoApproved", "addon csr %q is auto approved by addon csr controller", csr.Name) return nil } // Check whether a CSR is in terminal state func IsCSRInTerminalState(csr *certificatesv1.CertificateSigningRequest) bool { for _, c := range csr.Status.Conditions { if c.Type == certificatesv1.CertificateApproved { return true } if c.Type == certificatesv1.CertificateDenied { return true } } return false } func isCSRApproved(csr *certificatesv1.CertificateSigningRequest) bool { // TODO: need to make it work in csr v1 as well approved := false for _, condition := range csr.Status.Conditions { if condition.Type == certificatesv1.CertificateDenied { return false } else if condition.Type == certificatesv1.CertificateApproved { approved = true } } return approved }
NewCSRApprovingController
0003_profile_subscribers.py
# Generated by Django 3.2.5 on 2021-08-02 10:10 from django.conf import settings from django.db import migrations, models class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('profiles', '0002_alter_profile_profile_picture'), ] operations = [ migrations.AddField( model_name='profile', name='subscribers', field=models.ManyToManyField(related_name='subscribers', to=settings.AUTH_USER_MODEL), ), ]
Migration
lib.rs
#![feature(convert,custom_derive,plugin)] #![plugin(serde_macros)] extern crate hyper; extern crate serde; extern crate serde_json; use std::io::Read; use hyper::Client; use hyper::client::IntoUrl; use hyper::client::Response; use hyper::net::HttpsConnector; use hyper::net::Openssl; use hyper::status::StatusCode; use serde_json::Value; pub struct LxdServer { url: String, cert_location: String, key_location: String, } impl LxdServer { pub fn new(url: &str, cert_location: &str, key_location: &str) -> LxdServer { LxdServer { url: url.to_string(), cert_location: cert_location.to_string(), key_location: key_location.to_string() } } fn get_client(&self) -> Client { let connector = HttpsConnector::new( Openssl::with_cert_and_key(&self.cert_location, &self.key_location).unwrap()); Client::with_connector(connector) } fn get(&self, relative_url: &str) -> Response { let client = self.get_client(); let url = match (self.url.clone() + relative_url).into_url() { Err(why) => panic!("{:?}", why), Ok(url) => url, }; let unsent_response = client.get(url); let response = match unsent_response.send() { Err(why) => panic!("{:?}", why), Ok(response) => response, }; match response.status { StatusCode::Ok => response, _ => panic!("Response not OK: {}", response.status) } } pub fn list_containers(&self) -> Vec<Container> { let mut response = self.get("/1.0/containers?recursion=1"); let payload = response_to_value(&mut response); let container_values = payload.find("metadata").unwrap().as_array().unwrap(); container_values.iter().map(|v| { Container::from_json(v) }).collect() } } #[derive(Deserialize)] pub struct ContainerIP { pub address: String, pub host_veth: String, pub interface: String, pub protocol: String, } pub struct ContainerStatus { pub status: String, pub ips: Vec<ContainerIP>, } pub struct Container { pub name: String, pub status: ContainerStatus, pub ephemeral: bool, pub snapshot_urls: Vec<String>, } impl Container { pub fn from_json(json: &Value) -> Container { let value_for_path = |path: &[&str]| { match json.find_path(&path) { Some(value) => { value } None => panic!("Couldn't find {} in JSON", path.join(".")) } }; let get_array_from_json = |path: &[&str]| { match value_for_path(&path).as_array() { Some(array) => { array } None => panic!("Couldn't find array at {}", path.join(".")) } }; let get_boolean_from_json = |path: &[&str]| { match value_for_path(&path).as_boolean() { Some(boolean) => { boolean } None => panic!("Couldn't find boolean at {}", path.join(".")) } }; let get_string_from_json = |path: &[&str]| { match value_for_path(&path).as_string() { Some(string) => { string.to_string() } None => panic!("Couldn't find string at {}", path.join(".")) } }; Container { ephemeral: get_boolean_from_json(&["state", "ephemeral"]), name: get_string_from_json(&["state", "name"]), status: ContainerStatus { status: get_string_from_json(&["state", "status", "status"]), ips: get_array_from_json(&["state", "status", "ips"]).iter().map( |ip_value| -> ContainerIP { match serde_json::from_value(ip_value.clone()) { Ok(container_ip) => container_ip, Err(_) => panic!("Couldn't parse a ContainerIP for {:?}", ip_value) }}).collect(), }, snapshot_urls: match json.find_path(&["snaps"]).unwrap().as_array() { Some(array) => { array.iter().map(|x| {x.as_string().unwrap().to_string()}).collect() } None => { vec![] } } } } } fn response_to_value(response: &mut Response) -> Value { let mut body = String::new(); response.read_to_string(&mut body).unwrap(); serde_json::from_str(body.as_str()).unwrap()
}
user.py
# -*- coding: utf-8 -*- from wtforms import Form, StringField, PasswordField, validators class modificationForm(Form): username = StringField('User Name', [ validators.Optional(), validators.Length(min=2, max=20) ])
]) password = PasswordField('Password', [ validators.Optional(), validators.Length(min=5) ]) permission = StringField('Permission', [ validators.Optional(), validators.AnyOf(message='You can only choose from ADMIN, USER', values=['ADMIN', 'USER']) ])
email = StringField('Email', [ validators.Optional(), validators.Length(min=5), validators.Email()
ffmpeg.js
const formatOptionsMap = { startTime: '-ss', stopTime: '-to', }; const videoOptionsMap = { vcodec: '-c:v', preset: '-preset', bitrate: '-b:v', minrate: '-minrate', maxrate: '-maxrate', bufsize: '-bufsize', gopsize: '-g', pixelFormat: '-pix_fmt', frameRate: '-r', tune: '-tune', profile: '-profile:v', level: '-level', aspect: '-aspect', }; const audioOptionsMap = { acodec: '-c:a', sampleRate: '-ar', }; function setFlagsFromMap(map, options) { const flags = []; // Set flags by adding provided options from the map parameter and adding the // value to the flags array. Object.keys(map).forEach((o) => { if (options[o] && options[o] !== 'none' && options[o] !== 'auto') { const arg = [map[o], options[o]]; flags.push(...arg); } }); return flags; } // Builds an array of FFmpeg video filters (-vf). function setVideoFilters(options) { const vf = []; if (options.speed && options.speed !== 'auto') { const arg = [`setpts=${options.speed}`]; vf.push(...arg); } // Scale Filters. const scaleFilters = []; if (options.size && options.size !== 'source') { let arg; if (options.size === 'custom') { arg = [`scale=${options.width}:${options.height}`]; } else { arg = options.format === 'widescreen' ? [`scale=${options.size}:-1`] : [`scale=-1:${options.size}`]; } scaleFilters.push(...arg); } if (options.scaling && options.scaling !== 'auto') { const arg = [`flags=${options.scaling}`]; scaleFilters.push(...arg); } // Add Scale Filters to the vf flags if (scaleFilters.length > 0) { vf.push(scaleFilters.join(':')); } if (options.deband) { const arg = ['deband']; vf.push(...arg); } if (options.deshake) { const arg = ['deshake']; vf.push(...arg); } if (options.deflicker) { const arg = ['deflicker']; vf.push(...arg); } if (options.dejudder) { const arg = ['dejudder']; vf.push(...arg); } if (options.denoise !== 'none') { let arg; switch (options.denoise) { case 'light': arg = ['removegrain=22']; break; case 'medium': arg = ['vaguedenoiser=threshold=3:method=soft:nsteps=5']; break; case 'heavy': arg = ['vaguedenoiser=threshold=6:method=soft:nsteps=5']; break; default: arg = ['removegrain=0']; break; } vf.push(...arg); } if (options.deinterlace !== 'none') { let arg; switch (options.deinterlace) { case 'frame': arg = ['yadif=0:-1:0']; break; case 'field': arg = ['yadif=1:-1:0']; break; case 'frame_nospatial': arg = ['yadif=2:-1:0']; break; case 'field_nospatial': arg = ['yadif=3:-1:0']; break; default: break; } vf.push(...arg); } // EQ Filters. const eq = []; if (parseInt(options.contrast, 10) !== 0) { const arg = [`contrast=${(options.contrast / 100) + 1}`]; eq.push(...arg); } if (parseInt(options.brightness, 10) !== 0) { const arg = [`brightness=${options.brightness / 100}`]; eq.push(...arg); } if (parseInt(options.saturation, 10) !== 0) { const arg = [`saturation=${(options.saturation)}`]; eq.push(...arg); } if (parseInt(options.gamma, 10) !== 0) { const arg = [`gamma=${options.gamma / 10}`]; eq.push(...arg); } if (eq.length > 0) { const eqStr = eq.join(':'); vf.push(`eq=${eqStr}`); } return vf.join(','); } // Builds an array of FFmpeg audio filters (-af). function setAudioFilters(options) { const af = []; if (options.volume && parseInt(options.volume, 10) !== 100) { const arg = [`volume=${options.volume / 100}`]; af.push(...arg); } if (options.acontrast && parseInt(options.acontrast, 10) !== 33) { const arg = [`acontrast=${options.acontrast / 100}`]; af.push(...arg); } return af.join(','); } function
(flags, options) { const op = '/dev/null &&'; // For Windows use `NUL && \` const copy = flags.slice(); // Array clone for pass 2. // Rewrite command with 1 and 2 pass flags and append to flags array. if (options.vcodec === 'libx265' && options.codecOptions) { // Add pass param if the -x265-params flag is already present. const idx = flags.indexOf('-x265-params'); // eslint-disable-next-line no-param-reassign flags[idx + 1] += ':pass=1'; copy[idx + 1] += ':pass=2'; } else if (options.vcodec === 'libx265') { flags.push(...['-x265-params', 'pass=1', op]); copy.push(...['-x265-params', 'pass=2']); } else { flags.push(...['-pass', '1', op]); copy.push(...['-pass', '2']); } return copy; } function setFormatFlags(options) { return setFlagsFromMap(formatOptionsMap, options); } function setVideoFlags(options) { const flags = setFlagsFromMap(videoOptionsMap, options); // // Set more complex options that can't be set from the videoOptionsMap. // if (options.crf !== '0' && options.pass === 'crf') { const arg = ['-crf', options.crf]; flags.push(...arg); } if (options.faststart) { const arg = ['-movflags', 'faststart']; flags.push(...arg); } if (options.codecOptions && ['libx264', 'libx265'].includes(options.vcodec)) { const arg = [`-${options.vcodec.replace('lib', '')}-params`, options.codecOptions]; flags.push(...arg); } return flags; } function setAudioFlags(options) { const flags = setFlagsFromMap(audioOptionsMap, options); // // Set more complex options that can't be set from the audioOptionsMap. // if (options.channel && options.channel !== 'source') { const arg = ['-rematrix_maxval', '1.0', '-ac', options.channel]; flags.push(...arg); } if (options.quality && options.quality !== 'auto') { const arg = ['-b:a', options.quality === 'custom' ? options.audioBitrate : options.quality]; flags.push(...arg); } return flags; } // Build an array of FFmpeg from options parameter. function build(opt) { const options = opt || {}; const { input, output, container, } = options; const flags = [ 'ffmpeg', '-i', `${input}`, ]; // Set format flags if clip options are set. if (options.clip) { const formatFlags = setFormatFlags(options); flags.push(...formatFlags); } // Set video flags. const videoFlags = setVideoFlags(options); flags.push(...videoFlags); // Set video filters. const vf = setVideoFilters(options); if (vf) { flags.push(`-vf "${vf}"`); } // Set audio flags. const audioFlags = setAudioFlags(options); flags.push(...audioFlags); // Set audio filters. const af = setAudioFilters(options); if (af) { flags.push(`-af "${af}"`); } // Set 2 pass output if option is set. if (options.pass === '2') { const copy = set2Pass(flags, options); flags.push(...copy); } // Extra flags. const extra = []; if (options.extra.includes('f')) { const arg = ['-f', container]; extra.push(...arg); } if (options.extra.includes('y')) { const arg = ['-y']; extra.push(...arg); } if (options.extra.includes('n')) { const arg = ['-n']; extra.push(...arg); } if (options.extra.includes('progress')) { const arg = ['-progress pipe:1']; extra.push(...arg); } if (options.extra.includes('hide_banner')) { const arg = ['-hide_banner']; extra.push(...arg); } if (options.extra.includes('report')) { const arg = ['-report']; extra.push(...arg); } if (options.loglevel !== 'none') { const arg = ['-loglevel', options.loglevel]; extra.push(...arg); } // Set output. extra.push(output); // Push all flags and join them as a space separated string. flags.push(...extra); return flags.join(' '); } export default { build, };
set2Pass
linux_based_platform_backend.py
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. try: import resource # pylint: disable=import-error except ImportError: resource = None # Not available on all platforms import re from telemetry.core import exceptions from telemetry import decorators from telemetry.internal.platform import platform_backend class LinuxBasedPlatformBackend(platform_backend.PlatformBackend): """Abstract platform containing functionality domain.shared by all Linux based OSes. This includes Android and ChromeOS. Subclasses must implement RunCommand, GetFileContents, GetPsOutput, and ParseCStateSample.""" # Get the commit charge in kB. def GetSystemCommitCharge(self): meminfo_contents = self.GetFileContents('/proc/meminfo') meminfo = self._GetProcFileDict(meminfo_contents) if not meminfo: return None return (self._ConvertToKb(meminfo['MemTotal']) - self._ConvertToKb(meminfo['MemFree']) - self._ConvertToKb(meminfo['Buffers']) - self._ConvertToKb(meminfo['Cached'])) @decorators.Cache def GetSystemTotalPhysicalMemory(self): meminfo_contents = self.GetFileContents('/proc/meminfo') meminfo = self._GetProcFileDict(meminfo_contents) if not meminfo: return None return self._ConvertToBytes(meminfo['MemTotal']) def GetCpuStats(self, pid): results = {} stats = self._GetProcFileForPid(pid, 'stat') if not stats: return results stats = stats.split() utime = float(stats[13]) stime = float(stats[14]) cpu_process_jiffies = utime + stime clock_ticks = self.GetClockTicks() results.update({'CpuProcessTime': cpu_process_jiffies / clock_ticks}) return results def GetCpuTimestamp(self): total_jiffies = self._GetProcJiffies() clock_ticks = self.GetClockTicks() return {'TotalTime': total_jiffies / clock_ticks} @decorators.Deprecated( 2017, 11, 4, 'Clients should use tracing and memory-infra in new Telemetry ' 'benchmarks. See for context: https://crbug.com/632021') def GetMemoryStats(self, pid): status_contents = self._GetProcFileForPid(pid, 'status') stats = self._GetProcFileForPid(pid, 'stat').split() status = self._GetProcFileDict(status_contents) if not status or not stats or 'Z' in status['State']: return {} vm = int(stats[22]) vm_peak = (self._ConvertToBytes(status['VmPeak']) if 'VmPeak' in status else vm) wss = int(stats[23]) * resource.getpagesize() wss_peak = (self._ConvertToBytes(status['VmHWM']) if 'VmHWM' in status else wss) private_dirty_bytes = 0 for line in self._GetProcFileForPid(pid, 'smaps').splitlines(): if line.startswith('Private_Dirty:'): private_dirty_bytes += self._ConvertToBytes(line.split(':')[1].strip()) return {'VM': vm, 'VMPeak': vm_peak, 'PrivateDirty': private_dirty_bytes, 'WorkingSetSize': wss, 'WorkingSetSizePeak': wss_peak} @decorators.Cache def GetClockTicks(self): """Returns the number of clock ticks per second. The proper way is to call os.sysconf('SC_CLK_TCK') but that is not easy to do on Android/CrOS. In practice, nearly all Linux machines have a USER_HZ of 100, so just return that. """ return 100 def GetFileContents(self, filename): raise NotImplementedError() def GetPsOutput(self, columns, pid=None): raise NotImplementedError() def RunCommand(self, cmd): """Runs the specified command. Args: cmd: A list of program arguments or the path string of the program. Returns: A string whose content is the output of the command. """ raise NotImplementedError() @staticmethod def
(sample): """Parse a single c-state residency sample. Args: sample: A sample of c-state residency times to be parsed. Organized as a dictionary mapping CPU name to a string containing all c-state names, the times in each state, the latency of each state, and the time at which the sample was taken all separated by newlines. Ex: {'cpu0': 'C0\nC1\n5000\n2000\n20\n30\n1406673171'} Returns: Dictionary associating a c-state with a time. """ raise NotImplementedError() def _IsPidAlive(self, pid): assert pid, 'pid is required' return bool(self.GetPsOutput(['pid'], pid) == str(pid)) def _GetProcFileForPid(self, pid, filename): try: return self.GetFileContents('/proc/%s/%s' % (pid, filename)) except IOError: if not self._IsPidAlive(pid): raise exceptions.ProcessGoneException() raise def _ConvertToKb(self, value): return int(value.replace('kB', '')) def _ConvertToBytes(self, value): return self._ConvertToKb(value) * 1024 def _GetProcFileDict(self, contents): retval = {} for line in contents.splitlines(): key, value = line.split(':') retval[key.strip()] = value.strip() return retval def _GetProcJiffies(self): """Parse '/proc/timer_list' output and returns the first jiffies attribute. Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be essentially the same. Return the first one.""" jiffies_timer_lines = self.RunCommand( ['grep', 'jiffies', '/proc/timer_list']) if not jiffies_timer_lines: raise Exception('Unable to find jiffies from /proc/timer_list') jiffies_timer_list = jiffies_timer_lines.splitlines() # Each line should look something like 'jiffies: 4315883489'. for line in jiffies_timer_list: match = re.match(r'\s*jiffies\s*:\s*(\d+)', line) if match: value = match.group(1) return float(value) raise Exception('Unable to parse jiffies attribute: %s' % repr(jiffies_timer_lines))
ParseCStateSample
test_jac.py
# # Tests for the jacobian methods # import pybamm import numpy as np import unittest from scipy.sparse import eye from tests import get_mesh_for_testing def test_multi_var_function(arg1, arg2): return arg1 + arg2 class TestJacobian(unittest.TestCase): def test_variable_is_statevector(self): a = pybamm.Symbol("a") with self.assertRaisesRegex( TypeError, "Jacobian can only be taken with respect to a 'StateVector'" ): a.jac(a) def test_linear(self): y = pybamm.StateVector(slice(0, 4)) u = pybamm.StateVector(slice(0, 2)) v = pybamm.StateVector(slice(2, 4)) y0 = np.ones(4) func = u jacobian = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = -v jacobian = np.array([[0, 0, -1, 0], [0, 0, 0, -1]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = 3 * u + 4 * v jacobian = np.array([[3, 0, 4, 0], [0, 3, 0, 4]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = 7 * u - v * 9 jacobian = np.array([[7, 0, -9, 0], [0, 7, 0, -9]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) A = pybamm.Matrix(2 * eye(2)) func = A @ u jacobian = np.array([[2, 0, 0, 0], [0, 2, 0, 0]]) dfunc_dy = func.jac(y).simplify().evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = u @ pybamm.StateVector(slice(0, 1)) with self.assertRaises(NotImplementedError): func.jac(y) # when differentiating by independent part of the state vector jacobian = np.array([[0, 0], [0, 0]]) du_dv = u.jac(v).evaluate().toarray() np.testing.assert_array_equal(du_dv, jacobian) def test_nonlinear(self): y = pybamm.StateVector(slice(0, 4)) u = pybamm.StateVector(slice(0, 2)) v = pybamm.StateVector(slice(2, 4)) y0 = np.array([1, 2, 3, 4]) func = v ** 2 jacobian = np.array([[0, 0, 6, 0], [0, 0, 0, 8]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = 2 ** v jacobian = np.array( [[0, 0, 2 ** 3 * np.log(2), 0], [0, 0, 0, 2 ** 4 * np.log(2)]] ) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = v ** v jacobian = [[0, 0, 27 * (1 + np.log(3)), 0], [0, 0, 0, 256 * (1 + np.log(4))]] dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_almost_equal(jacobian, dfunc_dy.toarray()) func = u * v jacobian = np.array([[3, 0, 1, 0], [0, 4, 0, 2]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = u * (u + v) jacobian = np.array([[5, 0, 1, 0], [0, 8, 0, 2]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = 1 / u + v / 3 jacobian = np.array([[-1, 0, 1 / 3, 0], [0, -1 / 4, 0, 1 / 3]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = u / v jacobian = np.array([[1 / 3, 0, -1 / 9, 0], [0, 1 / 4, 0, -1 / 8]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = v / (1 + v) jacobian = np.array([[0, 0, 1 / 16, 0], [0, 0, 0, 1 / 25]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) def test_multislice_raises(self): y1 = pybamm.StateVector(slice(0, 4), slice(7, 8)) y_dot1 = pybamm.StateVectorDot(slice(0, 4), slice(7, 8)) y2 = pybamm.StateVector(slice(4, 7)) with self.assertRaises(NotImplementedError): y1.jac(y1) with self.assertRaises(NotImplementedError): y2.jac(y1) with self.assertRaises(NotImplementedError): y_dot1.jac(y1) def test_linear_ydot(self): y = pybamm.StateVector(slice(0, 4)) y_dot = pybamm.StateVectorDot(slice(0, 4)) u = pybamm.StateVector(slice(0, 2)) v = pybamm.StateVector(slice(2, 4)) u_dot = pybamm.StateVectorDot(slice(0, 2)) v_dot = pybamm.StateVectorDot(slice(2, 4)) y0 = np.ones(4) y_dot0 = np.ones(4) func = u_dot jacobian = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) dfunc_dy = func.jac(y_dot).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = -v_dot jacobian = np.array([[0, 0, -1, 0], [0, 0, 0, -1]]) dfunc_dy = func.jac(y_dot).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = u_dot jacobian = np.array([[0, 0, 0, 0], [0, 0, 0, 0]]) dfunc_dy = func.jac(y).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = -v_dot jacobian = np.array([[0, 0, 0, 0], [0, 0, 0, 0]]) dfunc_dy = func.jac(y).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = u jacobian = np.array([[0, 0, 0, 0], [0, 0, 0, 0]]) dfunc_dy = func.jac(y_dot).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = -v jacobian = np.array([[0, 0, 0, 0], [0, 0, 0, 0]]) dfunc_dy = func.jac(y_dot).evaluate(y=y0, y_dot=y_dot0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) def test_functions(self): y = pybamm.StateVector(slice(0, 4)) u = pybamm.StateVector(slice(0, 2)) v = pybamm.StateVector(slice(2, 4)) const = pybamm.Scalar(1) y0 = np.array([1.0, 2.0, 3.0, 4.0]) func = pybamm.sin(u) jacobian = np.array([[np.cos(1), 0, 0, 0], [0, np.cos(2), 0, 0]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = pybamm.cos(v) jacobian = np.array([[0, 0, -np.sin(3), 0], [0, 0, 0, -np.sin(4)]]) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = pybamm.sin(3 * u * v) jacobian = np.array( [ [9 * np.cos(9), 0, 3 * np.cos(9), 0], [0, 12 * np.cos(24), 0, 6 * np.cos(24)], ] ) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) func = pybamm.cos(5 * pybamm.exp(u + v)) jacobian = np.array( [ [ -5 * np.exp(4) * np.sin(5 * np.exp(4)), 0, -5 * np.exp(4) * np.sin(5 * np.exp(4)), 0, ], [ 0, -5 * np.exp(6) * np.sin(5 * np.exp(6)), 0, -5 * np.exp(6) * np.sin(5 * np.exp(6)), ], ] ) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) # when child evaluates to number func = pybamm.sin(const) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(0, dfunc_dy) # several children func = pybamm.Function(test_multi_var_function, 2 * y, 3 * y) jacobian = np.diag(5 * np.ones(4)) dfunc_dy = func.jac(y).evaluate(y=y0) np.testing.assert_array_equal(jacobian, dfunc_dy.toarray()) def test_index(self): vec = pybamm.StateVector(slice(0, 5)) ind = pybamm.Index(vec, 3) jac = ind.jac(vec).evaluate(y=np.linspace(0, 2, 5)).toarray() np.testing.assert_array_equal(jac, np.array([[0, 0, 0, 1, 0]])) # jac of ind of something that isn't a StateVector should return zeros const_vec = pybamm.Vector(np.ones(3)) ind = pybamm.Index(const_vec, 2) jac = ind.jac(vec).evaluate(y=np.linspace(0, 2, 5)).toarray() np.testing.assert_array_equal(jac, np.array([[0, 0, 0, 0, 0]])) def test_jac_of_number(self):
def test_jac_of_symbol(self): a = pybamm.Symbol("a") y = pybamm.StateVector(slice(0, 1)) with self.assertRaises(NotImplementedError): a.jac(y) def test_spatial_operator(self): a = pybamm.Variable("a") b = pybamm.SpatialOperator("Operator", a) y = pybamm.StateVector(slice(0, 1)) with self.assertRaises(NotImplementedError): b.jac(y) def test_jac_of_unary_operator(self): a = pybamm.Scalar(1) b = pybamm.UnaryOperator("Operator", a) y = pybamm.StateVector(slice(0, 1)) with self.assertRaises(NotImplementedError): b.jac(y) def test_jac_of_independent_variable(self): a = pybamm.IndependentVariable("Variable") y = pybamm.StateVector(slice(0, 1)) self.assertEqual(a.jac(y).evaluate(), 0) def test_jac_of_inner(self): a = pybamm.Scalar(1) b = pybamm.Scalar(2) y = pybamm.StateVector(slice(0, 1)) self.assertEqual(pybamm.inner(a, b).jac(y).evaluate(), 0) self.assertEqual(pybamm.inner(a, y).jac(y).evaluate(), 1) self.assertEqual(pybamm.inner(y, b).jac(y).evaluate(), 2) vec = pybamm.StateVector(slice(0, 2)) jac = pybamm.inner(a * vec, b * vec).jac(vec).evaluate(y=np.ones(2)).toarray() np.testing.assert_array_equal(jac, 4 * np.eye(2)) def test_jac_of_heaviside(self): a = pybamm.Scalar(1) y = pybamm.StateVector(slice(0, 5)) np.testing.assert_array_equal( ((a < y) * y ** 2).jac(y).evaluate(y=5 * np.ones(5)), 10 * np.eye(5) ) np.testing.assert_array_equal( ((a < y) * y ** 2).jac(y).evaluate(y=-5 * np.ones(5)), 0 ) def test_jac_of_minimum_maximum(self): y = pybamm.StateVector(slice(0, 10)) y_test = np.linspace(0, 2, 10) np.testing.assert_array_equal( np.diag(pybamm.minimum(1, y ** 2).jac(y).evaluate(y=y_test)), 2 * y_test * (y_test < 1), ) np.testing.assert_array_equal( np.diag(pybamm.maximum(1, y ** 2).jac(y).evaluate(y=y_test)), 2 * y_test * (y_test > 1), ) def test_jac_of_abs(self): y = pybamm.StateVector(slice(0, 10)) absy = abs(y) jac = absy.jac(y) y_test = np.linspace(-2, 2, 10) np.testing.assert_array_equal( np.diag(jac.evaluate(y=y_test).toarray()), np.sign(y_test) ) def test_jac_of_sign(self): y = pybamm.StateVector(slice(0, 10)) func = pybamm.sign(y) * y jac = func.jac(y) y_test = np.linspace(-2, 2, 10) np.testing.assert_array_equal(np.diag(jac.evaluate(y=y_test)), np.sign(y_test)) def test_jac_of_domain_concatenation(self): # create mesh mesh = get_mesh_for_testing() y = pybamm.StateVector(slice(0, 100)) # Jacobian of a DomainConcatenation of constants is a zero matrix of the # appropriate size a_dom = ["negative electrode"] b_dom = ["separator"] c_dom = ["positive electrode"] a_npts = mesh[a_dom[0]][0].npts b_npts = mesh[b_dom[0]][0].npts c_npts = mesh[c_dom[0]][0].npts a = 2 * pybamm.Vector(np.ones(a_npts), domain=a_dom) b = pybamm.Vector(np.ones(b_npts), domain=b_dom) c = 3 * pybamm.Vector(np.ones(c_npts), domain=c_dom) conc = pybamm.DomainConcatenation([a, b, c], mesh) jac = conc.jac(y).evaluate().toarray() np.testing.assert_array_equal(jac, np.zeros((100, 100))) # Jacobian of a DomainConcatenation of StateVectors a = 2 * pybamm.StateVector(slice(0, a_npts), domain=a_dom) b = pybamm.StateVector(slice(a_npts, a_npts + b_npts), domain=b_dom) c = 3 * pybamm.StateVector( slice(a_npts + b_npts, a_npts + b_npts + c_npts), domain=c_dom ) conc = pybamm.DomainConcatenation([a, b, c], mesh) y0 = np.ones(100) jac = conc.jac(y).evaluate(y=y0).toarray() np.testing.assert_array_equal( jac, np.diag( np.concatenate( [2 * np.ones(a_npts), np.ones(b_npts), 3 * np.ones(c_npts)] ) ), ) # multi=domain case not implemented a = 2 * pybamm.StateVector(slice(0, a_npts), domain=a_dom) b = pybamm.StateVector( slice(a_npts, a_npts + b_npts + c_npts), domain=b_dom + c_dom ) conc = pybamm.DomainConcatenation([a, b], mesh) with self.assertRaisesRegex( NotImplementedError, "jacobian only implemented for when each child has" ): conc.jac(y) if __name__ == "__main__": print("Add -v for more debug output") import sys if "-v" in sys.argv: debug = True pybamm.settings.debug_mode = True unittest.main()
"Jacobian of a number should be zero" a = pybamm.Scalar(1) b = pybamm.Scalar(2) y = pybamm.StateVector(slice(0, 1)) self.assertEqual(a.jac(y).evaluate(), 0) add = a + b self.assertEqual(add.jac(y).evaluate(), 0) subtract = a - b self.assertEqual(subtract.jac(y).evaluate(), 0) multiply = a * b self.assertEqual(multiply.jac(y).evaluate(), 0) divide = a / b self.assertEqual(divide.jac(y).evaluate(), 0) power = a ** b self.assertEqual(power.jac(y).evaluate(), 0)
qrangeslider.py
#!/usr/bin/env python # ------------------------------------------------------------------------------ # Copyright (c) 2011-2012, Ryan Galloway ([email protected]) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # - Neither the name of the software nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ------------------------------------------------------------------------------ # docs and latest version available for download at # http://rsgalloway.github.com/qrangeslider # ------------------------------------------------------------------------------ __author__ = "Ryan Galloway <[email protected]>" __version__ = "0.1" # ------------------------------------------------------------------------------ # SUMMARY # ------------------------------------------------------------------------------ """The QRangeSlider class implements a horizontal range slider widget. """ # ------------------------------------------------------------------------------ # TODO # ------------------------------------------------------------------------------ """ - smoother mouse move event handler - support splits and joins - verticle sliders - ticks """ # ------------------------------------------------------------------------------ # IMPORTS # ------------------------------------------------------------------------------ import os import sys from PyQt4 import QtCore from PyQt4 import QtGui from PyQt4 import uic try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s __all__ = ['QRangeSlider'] DEFAULT_CSS = """ QRangeSlider * { border: 0px; padding: 0px; } QRangeSlider #Head { background: #fff; } QRangeSlider #Span { background: #393; } QRangeSlider #Span:active { background: #282; } QRangeSlider #Tail { background: #fff; } QRangeSlider > QSplitter::handle { background: #393; } QRangeSlider > QSplitter::handle:vertical { height: 4px; } QRangeSlider > QSplitter::handle:pressed { background: #ca5; } """ class Ui_Form(object): """default range slider form""" def setupUi(self, Form): Form.setObjectName(_fromUtf8("QRangeSlider")) Form.resize(300, 30) Form.setStyleSheet(_fromUtf8(DEFAULT_CSS)) self.gridLayout = QtGui.QGridLayout(Form) self.gridLayout.setMargin(0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self._splitter = QtGui.QSplitter(Form) self._splitter.setMinimumSize(QtCore.QSize(0, 0)) self._splitter.setMaximumSize(QtCore.QSize(16777215, 16777215)) self._splitter.setOrientation(QtCore.Qt.Horizontal) self._splitter.setObjectName(_fromUtf8("splitter")) self._head = QtGui.QGroupBox(self._splitter) self._head.setTitle(_fromUtf8("")) self._head.setObjectName(_fromUtf8("Head")) self._handle = QtGui.QGroupBox(self._splitter) self._handle.setTitle(_fromUtf8("")) self._handle.setObjectName(_fromUtf8("Span")) self._tail = QtGui.QGroupBox(self._splitter) self._tail.setTitle(_fromUtf8("")) self._tail.setObjectName(_fromUtf8("Tail")) self.gridLayout.addWidget(self._splitter, 0, 0, 1, 1) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): encoding = QtGui.QApplication.UnicodeUTF8 Form.setWindowTitle(QtGui.QApplication.translate("QRangeSlider", "QRangeSlider", None, encoding)) class Element(QtGui.QGroupBox): def __init__(self, parent, main): super(Element, self).__init__(parent) self.main = main def setStyleSheet(self, style): """redirect style to parent groupbox""" self.parent().setStyleSheet(style) def textColor(self): """text paint color""" return getattr(self, '__textColor', QtGui.QColor(125, 125, 125)) def setTextColor(self, color): """set the text paint color""" if type(color) == tuple and len(color) == 3: color = QtGui.QColor(color[0], color[1], color[2]) elif type(color) == int: color = QtGui.QColor(color, color, color) setattr(self, '__textColor', color) def paintEvent(self, event): """overrides paint event to handle text""" qp = QtGui.QPainter() qp.begin(self) if self.main.drawValues(): self.drawText(event, qp) qp.end() class Head(Element): """area before the handle""" def __init__(self, parent, main): super(Head, self).__init__(parent, main) def drawText(self, event, qp): qp.setPen(self.textColor()) qp.setFont(QtGui.QFont('Arial', 10)) qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.min())) class Tail(Element): """area after the handle""" def __init__(self, parent, main): super(Tail, self).__init__(parent, main) def drawText(self, event, qp): qp.setPen(self.textColor()) qp.setFont(QtGui.QFont('Arial', 10)) qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.max())) class Handle(Element): """handle area""" def __init__(self, parent, main): super(Handle, self).__init__(parent, main) def drawText(self, event, qp): qp.setPen(self.textColor()) qp.setFont(QtGui.QFont('Arial', 10)) qp.drawText(event.rect(), QtCore.Qt.AlignLeft, str(self.main.start())) qp.drawText(event.rect(), QtCore.Qt.AlignRight, str(self.main.end())) def mouseMoveEvent(self, event): event.accept() mx = event.globalX() _mx = getattr(self, '__mx', None) if not _mx: setattr(self, '__mx', mx) dx = 0 else: dx = mx - _mx setattr(self, '__mx', mx) if dx == 0: event.ignore() return elif dx > 0: dx = 1 elif dx < 0: dx = -1 s = self.main.start() + dx e = self.main.end() + dx if s >= self.main.min() and e <= self.main.max(): self.main.setRange(s, e) class QRangeSlider(QtGui.QWidget, Ui_Form): """ The QRangeSlider class implements a horizontal range slider widget. Inherits QWidget. Methods * __init__ (self, QWidget parent = None) * bool drawValues (self) * int end (self) * (int, int) getRange (self) * int max (self) * int min (self) * int start (self) * setBackgroundStyle (self, QString styleSheet) * setDrawValues (self, bool draw) * setEnd (self, int end) * setStart (self, int start) * setRange (self, int start, int end) * setSpanStyle (self, QString styleSheet) Signals * endValueChanged (int) * maxValueChanged (int) * minValueChanged (int) * startValueChanged (int) Customizing QRangeSlider You can style the range slider as below: :: QRangeSlider * { border: 0px; padding: 0px; } QRangeSlider #Head { background: #222; } QRangeSlider #Span { background: #393; } QRangeSlider #Span:active { background: #282; } QRangeSlider #Tail { background: #222; } Styling the range slider handles follows QSplitter options: :: QRangeSlider > QSplitter::handle { background: #393; } QRangeSlider > QSplitter::handle:vertical { height: 4px; } QRangeSlider > QSplitter::handle:pressed { background: #ca5; } """ endValueChanged = QtCore.pyqtSignal(int) maxValueChanged = QtCore.pyqtSignal(int) minValueChanged = QtCore.pyqtSignal(int) startValueChanged = QtCore.pyqtSignal(int) # define splitter indices _SPLIT_START = 1 _SPLIT_END = 2 def __init__(self, parent=None): """Create a new QRangeSlider instance. :param parent: QWidget parent :return: New QRangeSlider instance. """ super(QRangeSlider, self).__init__(parent) self.setupUi(self) self.setMouseTracking(False) #self._splitter.setChildrenCollapsible(False) self._splitter.splitterMoved.connect(self._handleMoveSplitter) # head layout self._head_layout = QtGui.QHBoxLayout() self._head_layout.setSpacing(0) self._head_layout.setMargin(0) self._head.setLayout(self._head_layout) self.head = Head(self._head, main=self) self._head_layout.addWidget(self.head) # handle layout self._handle_layout = QtGui.QHBoxLayout() self._handle_layout.setSpacing(0) self._handle_layout.setMargin(0) self._handle.setLayout(self._handle_layout) self.handle = Handle(self._handle, main=self) self.handle.setTextColor((150, 255, 150)) self._handle_layout.addWidget(self.handle) # tail layout self._tail_layout = QtGui.QHBoxLayout() self._tail_layout.setSpacing(0) self._tail_layout.setMargin(0) self._tail.setLayout(self._tail_layout) self.tail = Tail(self._tail, main=self) self._tail_layout.addWidget(self.tail) # defaults self.setMin(0) self.setMax(99) self.setStart(0) self.setEnd(99) self.setDrawValues(True) def min(self): """:return: minimum value""" return getattr(self, '__min', None) def max(self): """:return: maximum value""" return getattr(self, '__max', None) def setMin(self, value): """sets minimum value""" assert type(value) is int setattr(self, '__min', value) self.minValueChanged.emit(value) def setMax(self, value): """sets maximum value""" assert type(value) is int setattr(self, '__max', value) self.maxValueChanged.emit(value) def start(self): """:return: range slider start value""" return getattr(self, '__start', None) def end(self): """:return: range slider end value""" return getattr(self, '__end', None) def _setStart(self, value): """stores the start value only""" setattr(self, '__start', value) self.startValueChanged.emit(value) def setStart(self, value):
def _setEnd(self, value): """stores the end value only""" setattr(self, '__end', value) self.endValueChanged.emit(value) def setEnd(self, value): """set the range slider end value""" assert type(value) is int v = self._valueToPos(value) self._splitter.moveSplitter(v, self._SPLIT_END) self._setEnd(value) def drawValues(self): """:return: True if slider values will be drawn""" return getattr(self, '__drawValues', None) def setDrawValues(self, draw): """sets draw values boolean to draw slider values""" assert type(draw) is bool setattr(self, '__drawValues', draw) def getRange(self): """:return: the start and end values as a tuple""" return (self.start(), self.end()) def setRange(self, start, end): """set the start and end values""" self.setStart(start) self.setEnd(end) def keyPressEvent(self, event): """overrides key press event to move range left and right""" key = event.key() if key == QtCore.Qt.Key_Left: s = self.start()-1 e = self.end()-1 elif key == QtCore.Qt.Key_Right: s = self.start()+1 e = self.end()+1 else: event.ignore() return event.accept() if s >= self.min() and e <= self.max(): self.setRange(s, e) def setBackgroundStyle(self, style): """sets background style""" self._tail.setStyleSheet(style) self._head.setStyleSheet(style) def setSpanStyle(self, style): """sets range span handle style""" self._handle.setStyleSheet(style) def _valueToPos(self, value): """converts slider value to local pixel x coord""" return int(self.width() * (float(value) / self.max())) def _posToValue(self, xpos): """converts local pixel x coord to slider value""" return int(((xpos + self._splitter.handleWidth()) / float(self.width())) * self.max()) def _handleMoveSplitter(self, xpos, index): """private method for handling moving splitter handles""" hw = self._splitter.handleWidth() def _lockWidth(widget): width = widget.size().width() widget.setMinimumWidth(width) widget.setMaximumWidth(width) def _unlockWidth(widget): widget.setMinimumWidth(0) widget.setMaximumWidth(16777215) v = self._posToValue(xpos) if index == self._SPLIT_START: _lockWidth(self._tail) if v >= self.end(): return offset = -20 w = xpos + offset self._setStart(v) elif index == self._SPLIT_END: _lockWidth(self._head) if v <= self.start(): return offset = -40 w = self.width() - xpos + offset self._setEnd(v) _unlockWidth(self._tail) _unlockWidth(self._head) _unlockWidth(self._handle) #------------------------------------------------------------------------------- # MAIN #------------------------------------------------------------------------------- if __name__ == '__main__': app = QtGui.QApplication(sys.argv) rs = QRangeSlider() rs.show() rs.setRange(15, 35) rs.setBackgroundStyle('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #222, stop:1 #333);') rs.handle.setStyleSheet('background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #282, stop:1 #393);') app.exec_()
"""sets the range slider start value""" assert type(value) is int v = self._valueToPos(value) self._splitter.moveSplitter(v, self._SPLIT_START) self._setStart(value)
server.go
//+build ignore package main import ( "flag" "log" "net" "golang.org/x/net/context" pb "google.golang.org/genproto/googleapis/pubsub/v1" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) func main()
type serv struct { pb.PublisherServer } func (*serv) GetTopic(_ context.Context, r *pb.GetTopicRequest) (*pb.Topic, error) { return &pb.Topic{Name: r.Topic}, nil }
{ addr := flag.String("a", "localhost:8080", "address") key := flag.String("key", "", "key file") cert := flag.String("cert", "", "cert file") flag.Parse() lis, err := net.Listen("tcp", *addr) if err != nil { log.Fatal(err) } if *cert == "" || *key == "" { log.Fatal("need TLS cert and key, for testing you can create your own: https://workaround.org/ispmail/jessie/create-certificate") } creds, err := credentials.NewServerTLSFromFile(*cert, *key) if err != nil { log.Fatal(err) } gs := grpc.NewServer(grpc.Creds(creds)) pb.RegisterPublisherServer(gs, &serv{}) log.Fatal(gs.Serve(lis)) }
dom_html_field_set_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMHTMLFormElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLFieldSetElement(Object<webkit2_webextension_sys::WebKitDOMHTMLFieldSetElement, webkit2_webextension_sys::WebKitDOMHTMLFieldSetElementClass, DOMHTMLFieldSetElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_field_set_element_get_type(), } } pub const NONE_DOMHTML_FIELD_SET_ELEMENT: Option<&DOMHTMLFieldSetElement> = None; pub trait DOMHTMLFieldSetElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_form(&self) -> Option<DOMHTMLFormElement>; fn connect_property_form_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLFieldSetElement>> DOMHTMLFieldSetElementExt for O { fn get_form(&self) -> Option<DOMHTMLFormElement> { unsafe { from_glib_none( webkit2_webextension_sys::webkit_dom_html_field_set_element_get_form( self.as_ref().to_glib_none().0, ), ) } } fn connect_property_form_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_form_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFieldSetElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFieldSetElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFieldSetElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::form\0".as_ptr() as *const _, Some(transmute(notify_form_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) }
} } impl fmt::Display for DOMHTMLFieldSetElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLFieldSetElement") } }
bit_uint8.go
package bitutil func
(b byte, startBit uint, bitLength uint) uint8 { if bitLength == 8 { return b } return b & uint8(1<<(8-startBit)-1) >> (8 - uint8(startBit+bitLength)) } func Uint8ToByteWithPos(v uint8, startBit uint, bitLength uint) byte { if bitLength == 8 { return v } return v << (8 - uint8(startBit+bitLength)) & uint8(1<<(8-startBit)-1) }
ByteToUint8WithPos
PopupDialogInput.js
import React, { Component } from 'react'; import { TouchableOpacity, KeyboardAvoidingView, Image, StyleSheet, Text, TextInput, View } from 'react-native'; import Utils from '../common/Utils'; import Line from './Line'; import PopupDialog, { DialogTitle, DialogButton, SlideAnimation, ScaleAnimation, FadeAnimation, } from 'react-native-popup-dialog'; const slideAnimation = new SlideAnimation({ slideFrom: 'bottom' }); import BorderButton from './BorderButton'; import * as CommonStyleSheet from '../common/StyleSheet'; import * as Constants from '../common/Constants'; import i18n from '../translations/i18n'; export default class PopupDialogInput extends Component { constructor(props) { super(props); this.title = props.title; this.style = props.style; this.labelStyle = props.labelStyle; this.onPress = props.onPress; this.label = props.label; this.placeholder = props.placeholder; this.onChangeText = props.onChangeText; this.placeholderTextColor = props.placeholderTextColor; this.secureTextEntry = props.secureTextEntry; this.editable = props.editable; this.key = props.key; this.state = { title: props.title, value: props.value, keyboardType: props.keyboardType }; } showSlideAnimationDialog = (id, text) => { this.setState({ value: text, key: id, }, () => { this.popupDialog.show(); this.textInput.focus(); }); } setKeyboardType = (keyboardType) => { this.setState({ keyboardType }); } componentWillReceiveProps(nextProps) { if (this.props !== nextProps) { this.setState({ title: nextProps.title, keyboardType: nextProps.keyboardType }); } } componentDidMount() { } dismissSlideAnimationDialog = () => { this.popupDialog.dismiss(); } render() { return ( <PopupDialog dialogStyle={styles.background_dialog} width={Utils.appSize().width - 50} // height={Utils.appSize().height} ref={(popupDialog) => { this.popupDialog = popupDialog; }} dialogAnimation={slideAnimation} onDismissed={() => Utils.dismissKeyboard()}> <View style={[styles.dialogContentView, { backgroundColor: CommonStyleSheet.THEME_DARCK ? '#1c1c1c' : 'white', }]}> <Text style={[styles.title, { color: CommonStyleSheet.THEME_DARCK ? '#949494' : 'black', }]}>{this.state.title}</Text> <View style={styles.content}> <TextInput ref={(textInput) => this.textInput = textInput} {...this.props} maxLength={this.maxLength} multiline={false} style={[styles.text_input, this.textInputStyle, { color: CommonStyleSheet.THEME_DARCK ? 'white' : 'black', }]} placeholder={this.placeholder} onChangeText={(text) => this._onChangeText(text)} underlineColorAndroid='transparent' placeholderTextColor={this.placeholderTextColor} value={this.state.value} secureTextEntry={this.secureTextEntry} editable={this.editable} numberOfLines={this.numberOfLines} keyboardType={this.state.keyboardType} returnKeyType='done' ellipsizeMode='tail' autoCapitalize='none'
</View> <View style={styles.view_content_button}> {/* cancel button */} <BorderButton title={i18n.t('CANCEL')} onPress={this._buttonCancel} titleStyle={{ color: CommonStyleSheet.THEME_DARCK ? 'white' : 'black' }} style={[styles.button_cancel]} imageStyle={[CommonStyleSheet.viewCommonStyles.common_button_dialog_1,]} background={CommonStyleSheet.THEME_DARCK ? require("../resource/buttonNew/icon_cancel_black.png") : require("../resource/buttonNew/icon_cancel_2_white.png")} /> {/* export button */} <BorderButton title={i18n.t('OK')} onPress={this._buttonOk} titleStyle={{ color: CommonStyleSheet.THEME_DARCK ? 'black' : 'white' }} style={[styles.button_ok]} imageStyle={[CommonStyleSheet.viewCommonStyles.common_button_dialog_1]} background={CommonStyleSheet.THEME_DARCK ? require("../resource/buttonNew/icon_ok_black.png") : require("../resource/buttonNew/icon_ok_1_white.png")} /> </View> </View> </PopupDialog> ); } _onChangeText(text) { if (this.state.keyboardType == 'phone-pad') { this.setState({ value: " " }) let valueText = Utils.removeEmojis(text); if (text.indexOf(',') > -1 || text.indexOf(';') > -1 || text.indexOf('N') > -1 || text.indexOf('n') > -1 || text.indexOf('/') > -1 || text.indexOf('*') > -1) { setTimeout(() => { this.setState({ value: valueText.replace(/[;,Nn/*]/g, '') }) }, 1); } else { setTimeout(() => { this.setState({ value: valueText }) }, 1); } } else { // alert(valueText) // this.setState({ value: " " }) // let valueText = Utils.removeEmojis(text); // setTimeout(() => { // this.setState({ value: valueText }) // }, 1); this.setState({ value: text }); } } _buttonCancel = () => { Utils.dismissKeyboard(); this.dismissSlideAnimationDialog(); } _buttonOk = () => { Utils.dismissKeyboard(); this.dismissSlideAnimationDialog(); if (this.onChangeText != null) { this.onChangeText(this.state.key, this.state.value); } } } let appSize = Utils.appSize(); const styles = StyleSheet.create({ content: { margin: 20, borderBottomColor: '#000000', borderBottomWidth: 1 }, title: { marginTop: 10, alignSelf: 'center', fontWeight: '400', fontSize: 16 }, text_input: { height: 35, fontSize: 14, padding: 0, margin: 0, marginTop: Utils.isAndroid() ? -10 : -15 }, background_dialog: { flex: 1, position: "absolute", backgroundColor: 'transparent', justifyContent: 'center', }, dialogContentView: { flexDirection: 'column', borderRadius: 20, }, view_content_button: { flexDirection: 'row', marginTop: 30 }, text: { width: appSize.width - 50, marginTop: 10, marginBottom: 10 }, button_cancel: { margin: 10, marginTop: 0, flex: 1 }, button_ok: { margin: 10, marginTop: 0, flex: 1 }, });
/>
ariesvcx-wallet.test.ts
import '../module-resolver-helper'; import { assert } from 'chai'; import { initVcxTestMode, shouldThrow } from 'helpers/utils'; import { shutdownVcx, VCXCode, Wallet } from 'src'; const WALLET_RECORD = { id: 'RecordId', tags_json: {}, type_: 'TestType', value: 'RecordValue', };
retrieveTags: false, retrieveType: true, retrieveValue: true, }; const QUERY_JSON = { tagName1: 'str1' }; const UPDATE_WALLET_RECORD = { id: 'RecordId', type_: 'TestType', value: 'RecordValueNew', }; const UPDATE_WALLET_TAGS = { id: 'RecordId', tags_json: {}, type_: 'TestType', value: '', }; describe('Wallet:', () => { before(() => initVcxTestMode()); describe('records:', () => { it('success', async () => { await Wallet.addRecord(WALLET_RECORD); await Wallet.getRecord({ type: WALLET_RECORD.type_, id: WALLET_RECORD.id, optionsJson: OPTIONS, }); await Wallet.updateRecordValue(UPDATE_WALLET_RECORD); await Wallet.updateRecordTags(UPDATE_WALLET_TAGS); await Wallet.addRecordTags(UPDATE_WALLET_TAGS); await Wallet.deleteRecordTags(WALLET_RECORD, { tagList: ['one', 'two'] }); await Wallet.deleteRecord({ type: WALLET_RECORD.type_, id: WALLET_RECORD.id }); const searchHandle = await Wallet.openSearch({ optionsJson: '{}', queryJson: JSON.stringify(QUERY_JSON), type: WALLET_RECORD.type_, }); assert(searchHandle === 1); JSON.parse(await Wallet.searchNextRecords(searchHandle, { count: 1 })); await Wallet.closeSearch(searchHandle); }); }); describe('import:', () => { it('throws: libindy error', async () => { let config = '{"wallet_name":"name","wallet_key":"","exported_wallet_path":"","backup_key":""}'; let error = await shouldThrow(async () => Wallet.import(config)); assert.equal(error.vcxCode, VCXCode.IO_ERROR); shutdownVcx(false); config = '{"wallet_key":"","exported_wallet_path":"","backup_key":""}'; error = await shouldThrow(async () => Wallet.import(config)); assert.equal(error.vcxCode, VCXCode.INVALID_CONFIGURATION); shutdownVcx(false); config = '{"wallet_name":"","exported_wallet_path":"","backup_key":""}'; error = await shouldThrow(async () => Wallet.import(config)); assert.equal(error.vcxCode, VCXCode.INVALID_CONFIGURATION); shutdownVcx(false); config = '{"wallet_name":"","wallet_key":"","backup_key":""}'; error = await shouldThrow(async () => Wallet.import(config)); assert.equal(error.vcxCode, VCXCode.INVALID_CONFIGURATION); shutdownVcx(false); config = '{"wallet_name":"","wallet_key":"","exported_wallet_path":""}'; error = await shouldThrow(async () => Wallet.import(config)); assert.equal(error.vcxCode, VCXCode.INVALID_CONFIGURATION); }); }); describe('export:', () => { it('throws: libindy error', async () => { const error = await shouldThrow(async () => Wallet.export('/tmp/foobar.wallet', 'key_for_wallet'), ); assert.equal(error.vcxCode, VCXCode.INVALID_WALLET_HANDLE); }); }); });
const OPTIONS = {
test_twofactor.py
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import unittest, frappe, pyotp from werkzeug.wrappers import Request from werkzeug.test import EnvironBuilder from frappe.auth import HTTPRequest from frappe.utils import cint from frappe.twofactor import (should_run_2fa, authenticate_for_2factor, get_cached_user_pass, two_factor_is_enabled_for_, confirm_otp_token, get_otpsecret_for_, get_verification_obj, render_string_template, two_factor_is_enabled) import time class TestTwoFactor(unittest.TestCase): def setUp(self):
self.http_requests = create_http_request() self.login_manager = frappe.local.login_manager self.user = self.login_manager.user def tearDown(self): frappe.local.response['verification'] = None frappe.local.response['tmp_id'] = None disable_2fa() frappe.clear_cache(user=self.user) def test_should_run_2fa(self): '''Should return true if enabled.''' toggle_2fa_all_role(state=True) self.assertTrue(should_run_2fa(self.user)) toggle_2fa_all_role(state=False) self.assertFalse(should_run_2fa(self.user)) def test_get_cached_user_pass(self): '''Cached data should not contain user and pass before 2fa.''' user,pwd = get_cached_user_pass() self.assertTrue(all([not user, not pwd])) def test_authenticate_for_2factor(self): '''Verification obj and tmp_id should be set in frappe.local.''' authenticate_for_2factor(self.user) verification_obj = frappe.local.response['verification'] tmp_id = frappe.local.response['tmp_id'] self.assertTrue(verification_obj) self.assertTrue(tmp_id) for k in ['_usr','_pwd','_otp_secret']: self.assertTrue(frappe.cache().get('{0}{1}'.format(tmp_id,k)), '{} not available'.format(k)) def test_two_factor_is_enabled(self): ''' 1. Should return true, if enabled and not bypass_2fa_for_retricted_ip_users 2. Should return false, if not enabled 3. Should return true, if enabled and bypass_2fa_for_retricted_ip_users and not user.restricted_ip 4. Should return false, if enabled and bypass_2fa_for_retricted_ip_users and user.restricted_ip ''' #Scenario 1 disable_2fa() self.assertFalse(two_factor_is_enabled(self.user)) #Scenario 2 enable_2fa() self.assertTrue(two_factor_is_enabled(self.user)) #Scenario 3 enable_2fa() user = frappe.get_doc('User', self.user) user.restrict_ip = frappe.local.request_ip user.save() self.assertTrue(two_factor_is_enabled(self.user)) #Scenario 4 user = frappe.get_doc('User', self.user) user.restrict_ip = "" user.save() enable_2fa(1) self.assertTrue(two_factor_is_enabled(self.user)) #Scenario 5 user = frappe.get_doc('User', self.user) user.restrict_ip = frappe.local.request_ip user.save() enable_2fa(1) self.assertFalse(two_factor_is_enabled(self.user)) def test_two_factor_is_enabled_for_user(self): '''Should return true if enabled for user.''' toggle_2fa_all_role(state=True) self.assertTrue(two_factor_is_enabled_for_(self.user)) self.assertFalse(two_factor_is_enabled_for_("Administrator")) toggle_2fa_all_role(state=False) self.assertFalse(two_factor_is_enabled_for_(self.user)) def test_get_otpsecret_for_user(self): '''OTP secret should be set for user.''' self.assertTrue(get_otpsecret_for_(self.user)) self.assertTrue(frappe.db.get_default(self.user + '_otpsecret')) def test_confirm_otp_token(self): '''Ensure otp is confirmed''' authenticate_for_2factor(self.user) tmp_id = frappe.local.response['tmp_id'] otp = 'wrongotp' with self.assertRaises(frappe.AuthenticationError): confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id) otp = get_otp(self.user) self.assertTrue(confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id)) if frappe.flags.tests_verbose: print('Sleeping for 30secs to confirm token expires..') time.sleep(30) with self.assertRaises(frappe.AuthenticationError): confirm_otp_token(self.login_manager,otp=otp,tmp_id=tmp_id) def test_get_verification_obj(self): '''Confirm verification object is returned.''' otp_secret = get_otpsecret_for_(self.user) token = int(pyotp.TOTP(otp_secret).now()) self.assertTrue(get_verification_obj(self.user,token,otp_secret)) def test_render_string_template(self): '''String template renders as expected with variables.''' args = {'issuer_name':'Frappe Technologies'} _str = 'Verification Code from {{issuer_name}}' _str = render_string_template(_str,args) self.assertEqual(_str,'Verification Code from Frappe Technologies') def set_request(**kwargs): builder = EnvironBuilder(**kwargs) frappe.local.request = Request(builder.get_environ()) def create_http_request(): '''Get http request object.''' set_request(method='POST', path='login') enable_2fa() frappe.form_dict['usr'] = '[email protected]' frappe.form_dict['pwd'] = 'test' frappe.local.form_dict['cmd'] = 'login' http_requests = HTTPRequest() return http_requests def enable_2fa(bypass_two_factor_auth=0): '''Enable Two factor in system settings.''' system_settings = frappe.get_doc('System Settings') system_settings.enable_two_factor_auth = 1 system_settings.bypass_2fa_for_retricted_ip_users = cint(bypass_two_factor_auth) system_settings.two_factor_method = 'OTP App' system_settings.save(ignore_permissions=True) frappe.db.commit() def disable_2fa(): system_settings = frappe.get_doc('System Settings') system_settings.enable_two_factor_auth = 0 system_settings.bypass_2fa_for_retricted_ip_users = 0 system_settings.save(ignore_permissions=True) frappe.db.commit() def toggle_2fa_all_role(state=None): '''Enable or disable 2fa for 'all' role on the system.''' all_role = frappe.get_doc('Role','All') if state == None: state = False if all_role.two_factor_auth == True else False if state not in [True,False]:return all_role.two_factor_auth = state all_role.save(ignore_permissions=True) frappe.db.commit() def get_otp(user): otp_secret = get_otpsecret_for_(user) otp = pyotp.TOTP(otp_secret) return otp.now()
build.go
// Copyright (c) 2018-2019, Sylabs Inc. All rights reserved. // This software is licensed under a 3-clause BSD license. Please consult the // LICENSE.md file distributed with the sources of this project regarding your // rights to use or distribute this software. package cli import ( "bufio" "fmt" "os" "strings" "github.com/sylabs/singularity/pkg/cmdline" ocitypes "github.com/containers/image/types" "github.com/spf13/cobra" "github.com/sylabs/singularity/docs" scs "github.com/sylabs/singularity/internal/pkg/remote" "github.com/sylabs/singularity/internal/pkg/sylog" "github.com/sylabs/singularity/internal/pkg/util/interactive" legacytypes "github.com/sylabs/singularity/pkg/build/legacy" legacyparser "github.com/sylabs/singularity/pkg/build/legacy/parser" ) var ( remote bool builderURL string detached bool libraryURL string isJSON bool sandbox bool force bool update bool noTest bool sections []string noHTTPS bool tmpDir string dockerUsername string dockerPassword string dockerLogin bool noCleanUp bool fakeroot bool ) // -s|--sandbox var buildSandboxFlag = cmdline.Flag{ ID: "buildSandboxFlag", Value: &sandbox, DefaultValue: false, Name: "sandbox", ShortHand: "s", Usage: "build image as sandbox format (chroot directory structure)", EnvKeys: []string{"SANDBOX"}, } // --section var buildSectionFlag = cmdline.Flag{ ID: "buildSectionFlag", Value: &sections, DefaultValue: []string{"all"}, Name: "section", Usage: "only run specific section(s) of deffile (setup, post, files, environment, test, labels, none)", EnvKeys: []string{"SECTION"}, } // --json var buildJSONFlag = cmdline.Flag{ ID: "buildJSONFlag", Value: &isJSON, DefaultValue: false, Name: "json", Usage: "interpret build definition as JSON", EnvKeys: []string{"JSON"}, } // -F|--force var buildForceFlag = cmdline.Flag{ ID: "buildForceFlag", Value: &force, DefaultValue: false, Name: "force", ShortHand: "F", Usage: "delete and overwrite an image if it currently exists", EnvKeys: []string{"FORCE"}, } // -u|--update var buildUpdateFlag = cmdline.Flag{ ID: "buildUpdateFlag", Value: &update, DefaultValue: false, Name: "update", ShortHand: "u", Usage: "run definition over existing container (skips header)", EnvKeys: []string{"UPDATE"}, } // -T|--notest var buildNoTestFlag = cmdline.Flag{ ID: "buildNoTestFlag", Value: &noTest, DefaultValue: false, Name: "notest", ShortHand: "T", Usage: "build without running tests in %test section", EnvKeys: []string{"NOTEST"}, } // -r|--remote var buildRemoteFlag = cmdline.Flag{ ID: "buildRemoteFlag", Value: &remote, DefaultValue: false, Name: "remote", ShortHand: "r", Usage: "build image remotely (does not require root)", EnvKeys: []string{"REMOTE"}, } // -d|--detached var buildDetachedFlag = cmdline.Flag{ ID: "buildDetachedFlag", Value: &detached, DefaultValue: false, Name: "detached", ShortHand: "d", Usage: "submit build job and print build ID (no real-time logs and requires --remote)", EnvKeys: []string{"DETACHED"}, } // --builder var buildBuilderFlag = cmdline.Flag{ ID: "buildBuilderFlag", Value: &builderURL, DefaultValue: "https://build.sylabs.io", Name: "builder", Usage: "remote Build Service URL, setting this implies --remote", EnvKeys: []string{"BUILDER"}, } // --library var buildLibraryFlag = cmdline.Flag{ ID: "buildLibraryFlag", Value: &libraryURL, DefaultValue: "https://library.sylabs.io", Name: "library", Usage: "container Library URL", EnvKeys: []string{"LIBRARY"}, } // --tmpdir var buildTmpdirFlag = cmdline.Flag{ ID: "buildTmpdirFlag", Value: &tmpDir, DefaultValue: "", Name: "tmpdir", Usage: "specify a temporary directory to use for build", EnvKeys: []string{"TMPDIR"}, } // --disable-cache var buildDisableCacheFlag = cmdline.Flag{ ID: "buildDisableCacheFlag", Value: &disableCache, DefaultValue: false, Name: "disable-cache", Usage: "do not use cache or create cache", EnvKeys: []string{"DISABLE_CACHE"}, } // --nohttps var buildNoHTTPSFlag = cmdline.Flag{ ID: "buildNoHTTPSFlag", Value: &noHTTPS, DefaultValue: false, Name: "nohttps", Usage: "do NOT use HTTPS, for communicating with local docker registry", EnvKeys: []string{"NOHTTPS"}, } // --no-cleanup var buildNoCleanupFlag = cmdline.Flag{ ID: "buildNoCleanupFlag", Value: &noCleanUp, DefaultValue: false, Name: "no-cleanup", Usage: "do NOT clean up bundle after failed build, can be helpul for debugging", EnvKeys: []string{"NO_CLEANUP"}, } // --fakeroot var buildFakerootFlag = cmdline.Flag{ ID: "buildFakerootFlag", Value: &fakeroot, DefaultValue: false, Name: "fakeroot", ShortHand: "f", Usage: "build using user namespace to fake root user (requires a privileged installation)", EnvKeys: []string{"FAKEROOT"}, } func init() { cmdManager.RegisterCmd(BuildCmd) cmdManager.RegisterFlagForCmd(&buildBuilderFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildDetachedFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildForceFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildJSONFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildLibraryFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildNoCleanupFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildNoHTTPSFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildNoTestFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildRemoteFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildSandboxFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildSectionFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildTmpdirFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildDisableCacheFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildUpdateFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&buildFakerootFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&actionDockerUsernameFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&actionDockerPasswordFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&actionDockerLoginFlag, BuildCmd) cmdManager.RegisterFlagForCmd(&commonEncryptFlag, BuildCmd) } // BuildCmd represents the build command var BuildCmd = &cobra.Command{ DisableFlagsInUseLine: true, Args: cobra.ExactArgs(2), Use: docs.BuildUse, Short: docs.BuildShort, Long: docs.BuildLong, Example: docs.BuildExample, PreRun: preRun, Run: run, TraverseChildren: true, } func preRun(cmd *cobra.Command, args []string) { if fakeroot && !remote { fakerootExec(args) } // Always perform remote build when builder flag is set if cmd.Flags().Lookup("builder").Changed { cmd.Flags().Lookup("remote").Value.Set("true") } sylabsToken(cmd, args) } // checkTargetCollision makes sure output target doesn't exist, or is ok to overwrite func checkBuildTarget(path string, update bool) bool { if f, err := os.Stat(path); err == nil { if update && !f.IsDir() { sylog.Fatalf("Only sandbox updating is supported.") } if !update && !force { reader := bufio.NewReader(os.Stdin) fmt.Print("Build target already exists. Do you want to overwrite? [N/y] ") input, err := reader.ReadString('\n') if err != nil { sylog.Fatalf("Error parsing input: %s", err) } if val := strings.Compare(strings.ToLower(input), "y\n"); val == 0 { force = true } else { sylog.Errorf("Stopping build.") return false } } } return true } // definitionFromSpec is specifically for parsing specs for the remote builder // it uses a different version the the definition struct and parser func definitionFromSpec(spec string) (legacytypes.Definition, error)
func makeDockerCredentials(cmd *cobra.Command) (authConf *ocitypes.DockerAuthConfig, err error) { usernameFlag := cmd.Flags().Lookup("docker-username") passwordFlag := cmd.Flags().Lookup("docker-password") if dockerLogin { if !usernameFlag.Changed { dockerUsername, err = interactive.AskQuestion("Enter Docker Username: ") if err != nil { return } usernameFlag.Value.Set(dockerUsername) usernameFlag.Changed = true } dockerPassword, err = interactive.AskQuestionNoEcho("Enter Docker Password: ") if err != nil { return } passwordFlag.Value.Set(dockerPassword) passwordFlag.Changed = true } if usernameFlag.Changed && passwordFlag.Changed { authConf = &ocitypes.DockerAuthConfig{ Username: dockerUsername, Password: dockerPassword, } } return } // remote builds need to fail if we cannot resolve remote URLS func handleRemoteBuildFlags(cmd *cobra.Command) { // if we can load config and if default endpoint is set, use that // otherwise fall back on regular authtoken and URI behavior endpoint, err := sylabsRemote(remoteConfig) if err == scs.ErrNoDefault { sylog.Warningf("No default remote in use, falling back to CLI defaults") return } else if err != nil { sylog.Fatalf("Unable to load remote configuration: %v", err) } authToken = endpoint.Token if !cmd.Flags().Lookup("builder").Changed { uri, err := endpoint.GetServiceURI("builder") if err != nil { sylog.Fatalf("Unable to get build service URI: %v", err) } builderURL = uri } if !cmd.Flags().Lookup("library").Changed { uri, err := endpoint.GetServiceURI("library") if err != nil { sylog.Fatalf("Unable to get library service URI: %v", err) } libraryURL = uri } }
{ // Try spec as URI first def, err := legacytypes.NewDefinitionFromURI(spec) if err == nil { return def, nil } // Try spec as local file var isValid bool isValid, err = legacyparser.IsValidDefinition(spec) if err != nil { return legacytypes.Definition{}, err } if isValid { sylog.Debugf("Found valid definition: %s\n", spec) // File exists and contains valid definition var defFile *os.File defFile, err = os.Open(spec) if err != nil { return legacytypes.Definition{}, err } defer defFile.Close() return legacyparser.ParseDefinitionFile(defFile) } // File exists and does NOT contain a valid definition // local image or sandbox def = legacytypes.Definition{ Header: map[string]string{ "bootstrap": "localimage", "from": spec, }, } return def, nil }
suggestMemory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { LRUCache, TernarySearchTree } from 'vs/base/common/map'; import { IStorageService, StorageScope, StorageTarget, WillSaveStateReason } from 'vs/platform/storage/common/storage'; import { ITextModel } from 'vs/editor/common/model'; import { IPosition } from 'vs/editor/common/core/position'; import { CompletionItemKind, completionKindFromString } from 'vs/editor/common/modes'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { RunOnceScheduler } from 'vs/base/common/async'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { CompletionItem } from 'vs/editor/contrib/suggest/suggest'; import { IModeService } from 'vs/editor/common/services/modeService'; export abstract class Memory { constructor(readonly name: MemMode) { } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { if (items.length === 0) { return 0; } let topScore = items[0].score[0]; for (let i = 0; i < items.length; i++) { const { score, completion: suggestion } = items[i]; if (score[0] !== topScore) { // stop when leaving the group of top matches break; } if (suggestion.preselect) { // stop when seeing an auto-select-item return i; } } return 0; } abstract memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void; abstract toJSON(): object | undefined; abstract fromJSON(data: object): void; } export class NoMemory extends Memory { constructor() { super('first'); } memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { // no-op } toJSON() { return undefined; } fromJSON() { // } } export interface MemItem { type: string | CompletionItemKind; insertText: string; touch: number; } export class LRUMemory extends Memory { constructor() { super('recentlyUsed'); } private _cache = new LRUCache<string, MemItem>(300, 0.66); private _seq = 0; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { const { label } = item.completion; const key = `${model.getLanguageIdentifier().language}/${label}`; this._cache.set(key, { touch: this._seq++, type: item.completion.kind, insertText: item.completion.insertText }); } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { if (items.length === 0) { return 0; } const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1); if (/\s$/.test(lineSuffix)) { return super.select(model, pos, items); } let topScore = items[0].score[0]; let indexPreselect = -1; let indexRecency = -1; let seq = -1; for (let i = 0; i < items.length; i++) { if (items[i].score[0] !== topScore) { // consider only top items break; } const key = `${model.getLanguageIdentifier().language}/${items[i].completion.label}`; const item = this._cache.peek(key); if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) { seq = item.touch; indexRecency = i; } if (items[i].completion.preselect && indexPreselect === -1) { // stop when seeing an auto-select-item return indexPreselect = i; } } if (indexRecency !== -1) { return indexRecency; } else if (indexPreselect !== -1) { return indexPreselect; } else { return 0; } } toJSON(): object { return this._cache.toJSON(); } fromJSON(data: [string, MemItem][]): void { this._cache.clear(); let seq = 0; for (const [key, value] of data) { value.touch = seq; value.type = typeof value.type === 'number' ? value.type : completionKindFromString(value.type); this._cache.set(key, value); } this._seq = this._cache.size; } } export class PrefixMemory extends Memory { constructor() { super('recentlyUsedByPrefix'); } private _trie = TernarySearchTree.forStrings<MemItem>(); private _seq = 0; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { const { word } = model.getWordUntilPosition(pos); const key = `${model.getLanguageIdentifier().language}/${word}`; this._trie.set(key, { type: item.completion.kind, insertText: item.completion.insertText, touch: this._seq++ }); } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { let { word } = model.getWordUntilPosition(pos); if (!word) { return super.select(model, pos, items); } let key = `${model.getLanguageIdentifier().language}/${word}`; let item = this._trie.get(key); if (!item) { item = this._trie.findSubstr(key); } if (item) { for (let i = 0; i < items.length; i++) { let { kind, insertText } = items[i].completion; if (kind === item.type && insertText === item.insertText) { return i; } } } return super.select(model, pos, items); } toJSON(): object { let entries: [string, MemItem][] = []; this._trie.forEach((value, key) => entries.push([key, value])); // sort by last recently used (touch), then // take the top 200 item and normalize their // touch entries .sort((a, b) => -(a[1].touch - b[1].touch)) .forEach((value, i) => value[1].touch = i); return entries.slice(0, 200); } fromJSON(data: [string, MemItem][]): void { this._trie.clear(); if (data.length > 0) { this._seq = data[0][1].touch + 1; for (const [key, value] of data) { value.type = typeof value.type === 'number' ? value.type : completionKindFromString(value.type); this._trie.set(key, value); } } } } export type MemMode = 'first' | 'recentlyUsed' | 'recentlyUsedByPrefix'; export class SuggestMemoryService implements ISuggestMemoryService { private static readonly _strategyCtors = new Map<MemMode, { new(): Memory }>([ ['recentlyUsedByPrefix', PrefixMemory], ['recentlyUsed', LRUMemory], ['first', NoMemory] ]); private static readonly _storagePrefix = 'suggest/memories'; readonly _serviceBrand: undefined; private readonly _persistSoon: RunOnceScheduler; private readonly _disposables = new DisposableStore(); private _strategy?: Memory; constructor( @IStorageService private readonly _storageService: IStorageService, @IModeService private readonly _modeService: IModeService, @IConfigurationService private readonly _configService: IConfigurationService, ) { this._persistSoon = new RunOnceScheduler(() => this._saveState(), 500); this._disposables.add(_storageService.onWillSaveState(e => { if (e.reason === WillSaveStateReason.SHUTDOWN) { this._saveState(); } })); } dispose(): void { this._disposables.dispose(); this._persistSoon.dispose(); } memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void { this._withStrategy(model, pos).memorize(model, pos, item); this._persistSoon.schedule(); } select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number { return this._withStrategy(model, pos).select(model, pos, items); } private _withStrategy(model: ITextModel, pos: IPosition): Memory { const mode = this._configService.getValue<MemMode>('editor.suggestSelection', { overrideIdentifier: this._modeService.getLanguageIdentifier(model.getLanguageIdAtPosition(pos.lineNumber, pos.column))?.language, resource: model.uri
this._saveState(); const ctor = SuggestMemoryService._strategyCtors.get(mode) || NoMemory; this._strategy = new ctor(); try { const share = this._configService.getValue<boolean>('editor.suggest.shareSuggestSelections'); const scope = share ? StorageScope.GLOBAL : StorageScope.WORKSPACE; const raw = this._storageService.get(`${SuggestMemoryService._storagePrefix}/${mode}`, scope); if (raw) { this._strategy.fromJSON(JSON.parse(raw)); } } catch (e) { // things can go wrong with JSON... } } return this._strategy; } private _saveState() { if (this._strategy) { const share = this._configService.getValue<boolean>('editor.suggest.shareSuggestSelections'); const scope = share ? StorageScope.GLOBAL : StorageScope.WORKSPACE; const raw = JSON.stringify(this._strategy); this._storageService.store2(`${SuggestMemoryService._storagePrefix}/${this._strategy.name}`, raw, scope, StorageTarget.MACHINE); } } } export const ISuggestMemoryService = createDecorator<ISuggestMemoryService>('ISuggestMemories'); export interface ISuggestMemoryService { readonly _serviceBrand: undefined; memorize(model: ITextModel, pos: IPosition, item: CompletionItem): void; select(model: ITextModel, pos: IPosition, items: CompletionItem[]): number; } registerSingleton(ISuggestMemoryService, SuggestMemoryService, true);
}); if (this._strategy?.name !== mode) {
tests2.rs
// tests2.rs // This test has a problem with it -- make the test compile! Make the test // pass! Make the test fail! Execute `rustlings hint tests2` for hints :) #[cfg(test)] mod tests { #[test] fn
() { assert_eq!(50, 50); } }
you_can_assert_eq
gpio.rs
use crate::traits::{ wg::{ digital::v2::{ InputPin, OutputPin, StatefulOutputPin, toggleable, }, } }; use crate::typestates::{ pin::{ state, gpio::{ direction, Level, }, PinId, }, reg_proxy::RegClusterProxy, }; use super::Pin; use crate::{ raw::gpio::{ // B, // W, CLR, DIRSET, DIRCLR, PIN, SET, }, reg_cluster, }; // reg_cluster!(B, B, raw::GPIO, b); // reg_cluster!(W, W, raw::GPIO, w); reg_cluster!(DIRSET, DIRSET, raw::GPIO, dirset); reg_cluster!(DIRCLR, DIRCLR, raw::GPIO, dirclr); reg_cluster!(PIN, PIN, raw::GPIO, pin); reg_cluster!(SET, SET, raw::GPIO, set); reg_cluster!(CLR, CLR, raw::GPIO, clr); impl<T> OutputPin for Pin<T, state::Gpio<direction::Output>> where T: PinId, { type Error = core::convert::Infallible; /// Set the pin output to HIGH fn set_high(&mut self) -> Result<(), Self::Error> { self.state.set[T::PORT].write(|w| unsafe { w.setp().bits(T::MASK) }); Ok(()) } /// Set the pin output to LOW fn set_low(&mut self) -> Result<(), Self::Error> { self.state.clr[T::PORT].write(|w| unsafe { w.clrp().bits(T::MASK) }); Ok(()) } } impl<T> StatefulOutputPin for Pin<T, state::Gpio<direction::Output>> where T: PinId, { fn is_set_high(&self) -> Result<bool, Self::Error> { Ok(self.state.pin[T::PORT].read().port().bits() & T::MASK == T::MASK) } fn is_set_low(&self) -> Result<bool, Self::Error> { Ok(!self.state.pin[T::PORT].read().port().bits() & T::MASK == T::MASK) } } impl<T: PinId> toggleable::Default for Pin<T, state::Gpio<direction::Output>> {} impl<T> InputPin for Pin<T, state::Gpio<direction::Input>> where T: PinId, { type Error = core::convert::Infallible; fn is_high(&self) -> Result<bool, Self::Error> { // Ok(self.state.b[T::OFFSET].b_.read().pbyte()) Ok(self.state.pin[T::PORT].read().port().bits() & T::MASK == T::MASK) } fn is_low(&self) -> Result<bool, Self::Error> { // Ok(!self.state.b.b_[T::OFFSET].read().pbyte()) Ok(!self.state.pin[T::PORT].read().port().bits() & T::MASK == T::MASK) } } impl<T, D> Pin<T, state::Gpio<D>> where T: PinId, D: direction::NotOutput, { pub fn into_output_high(self) -> Pin<T, state::Gpio<direction::Output>> { self.into_output(Level::High) } pub fn into_output_low(self) -> Pin<T, state::Gpio<direction::Output>>
pub fn into_output(self, initial: Level) -> Pin<T, state::Gpio<direction::Output>> { match initial { Level::High => self.state.set[T::PORT].write(|w| unsafe { w.setp().bits(T::MASK) }), Level::Low => self.state.clr[T::PORT].write(|w| unsafe { w.clrp().bits(T::MASK) }), } self.state.dirset[T::PORT].write(|w| unsafe { w.dirsetp().bits(T::MASK) }); Pin { id: self.id, state: state::Gpio { // b: RegClusterProxy::new(), // w: RegClusterProxy::new(), dirset: RegClusterProxy::new(), dirclr: RegClusterProxy::new(), pin: RegClusterProxy::new(), set: RegClusterProxy::new(), clr: RegClusterProxy::new(), _direction: direction::Output, }, } } } impl<T, D> Pin<T, state::Gpio<D>> where T: PinId, D: direction::NotInput, { pub fn into_input(self) -> Pin<T, state::Gpio<direction::Input>> { // currently, `into_gpio_pin()` sets `.digimode().digital()` in IOCON, // meaning input is enabled for all pins self.state.dirclr[T::PORT].write(|w| unsafe { w.dirclrp().bits(T::MASK) }); Pin { id: self.id, state: state::Gpio { // b: RegClusterProxy::new(), // w: RegClusterProxy::new(), dirset: RegClusterProxy::new(), dirclr: RegClusterProxy::new(), pin: RegClusterProxy::new(), set: RegClusterProxy::new(), clr: RegClusterProxy::new(), _direction: direction::Input, }, } } } impl<T, D> Pin<T, state::Analog<D>> where T: PinId, D: direction::NotInput, { pub fn into_input(self) -> Pin<T, state::Analog<direction::Input>> { // currently, `into_gpio_pin()` sets `.digimode().digital()` in IOCON, // meaning input is enabled for all pins self.state.dirclr[T::PORT].write(|w| unsafe { w.dirclrp().bits(T::MASK) }); Pin { id: self.id, state: state::Analog { channel: self.state.channel, dirclr: RegClusterProxy::new(), _direction: direction::Input, }, } } }
{ self.into_output(Level::Low) }
validator.js
/* ****************************************************************** * custom validators for express-validator. read more here: * https://github.com/ctavan/express-validator#middleware-options ****************************************************************** */ module.exports = { isString(value) { return typeof value === 'string' || value instanceof String }, isHash(value) { return /^[a-f0-9]{32}$/i.test(value) }, isPhone(value) {
}, isStamp(value) { return /^[0-9]{13}$/.test(value) }, isUnixStamp(value) { return /^[0-9]{10}$/.test(value) }, isStringArray(value) { if (!Array.isArray(value)) return false for (const item of value) { if (!this.isString(item)) return false } return true }, }
return /^1[3|4|5|8|7][0-9]\d{8}$/.test(value)
mutate_persistentvolumeclaim.go
package hook import ( "context" "encoding/json" "net/http" "github.com/kvaster/topols" corev1 "k8s.io/api/core/v1" storagev1 "k8s.io/api/storage/v1" apierrors "k8s.io/apimachinery/pkg/api/errors"
"sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) type persistentVolumeClaimMutator struct { client client.Client decoder *admission.Decoder } // PVCMutator creates a mutating webhook for PVCs. func PVCMutator(c client.Client, dec *admission.Decoder) http.Handler { return &webhook.Admission{Handler: persistentVolumeClaimMutator{c, dec}} } // +kubebuilder:webhook:failurePolicy=fail,matchPolicy=equivalent,groups="",resources=persistentvolumeclaims,verbs=create,versions=v1,name=pvc-hook.topols.kvaster.com,path=/pvc/mutate,mutating=true,sideEffects=none,admissionReviewVersions={v1,v1beta1} // +kubebuilder:rbac:groups=storage.k8s.io,resources=storageclasses,verbs=get;list;watch // Handle implements admission.Handler interface. func (m persistentVolumeClaimMutator) Handle(ctx context.Context, req admission.Request) admission.Response { pvc := &corev1.PersistentVolumeClaim{} err := m.decoder.Decode(req, pvc) if err != nil { return admission.Errored(http.StatusBadRequest, err) } // StorageClassName can be nil if pvc.Spec.StorageClassName == nil { return admission.Allowed("no request for TopoLS") } var sc storagev1.StorageClass err = m.client.Get(ctx, types.NamespacedName{Name: *pvc.Spec.StorageClassName}, &sc) switch { case err == nil: case apierrors.IsNotFound(err): // StorageClassName can be simple name linked PV return admission.Allowed("no request for TopoLS") default: return admission.Errored(http.StatusInternalServerError, err) } if sc.Provisioner != topols.PluginName { return admission.Allowed("no request for TopoLS") } pvcPatch := pvc.DeepCopy() pvcPatch.Finalizers = append(pvcPatch.Finalizers, topols.PVCFinalizer) marshaled, err := json.Marshal(pvcPatch) if err != nil { return admission.Errored(http.StatusInternalServerError, err) } return admission.PatchResponseFromRaw(req.Object.Raw, marshaled) }
"k8s.io/apimachinery/pkg/types"
secure_channel_worker.rs
use crate::{ IdentityChannelMessage, IdentityError, IdentityIdentifier, IdentitySecureChannelLocalInfo, IdentityTrait, SecureChannelTrustInfo, TrustPolicy, }; use core::future::Future; use core::pin::Pin; use core::time::Duration; use ockam_channel::{ CreateResponderChannelMessage, KeyExchangeCompleted, SecureChannel, SecureChannelInfo, }; use ockam_core::async_trait; use ockam_core::compat::rand::random; use ockam_core::compat::{boxed::Box, sync::Arc, vec::Vec}; use ockam_core::{ route, Address, Any, Decodable, Encodable, LocalMessage, Message, Result, Route, Routed, TransportMessage, Worker, }; use ockam_key_exchange_core::NewKeyExchanger; use ockam_key_exchange_xx::{XXNewKeyExchanger, XXVault}; use ockam_node::Context; use serde::{Deserialize, Serialize}; use tracing::{debug, info, warn}; #[derive(Serialize, Deserialize, Message)] pub(crate) struct AuthenticationConfirmation(pub Address); trait StartSecureChannelFuture: Future<Output = Result<SecureChannelInfo>> + Send + 'static {} impl<T> StartSecureChannelFuture for T where T: Future<Output = Result<SecureChannelInfo>> + Send + 'static { } struct InitiatorStartChannel<I: IdentityTrait> { channel_future: Pin<Box<dyn StartSecureChannelFuture>>, // TODO: Replace with generic callback_address: Address, identity: I, trust_policy: Arc<dyn TrustPolicy>, } struct ResponderWaitForKex<I: IdentityTrait> { first_responder_address: Address, identity: I, trust_policy: Arc<dyn TrustPolicy>, } struct InitiatorSendIdentity<I: IdentityTrait> { channel: SecureChannelInfo, callback_address: Address, identity: I, trust_policy: Arc<dyn TrustPolicy>, } struct ResponderWaitForIdentity<I: IdentityTrait> { auth_hash: [u8; 32], local_secure_channel_address: Address, identity: I, trust_policy: Arc<dyn TrustPolicy>, } #[derive(Clone)] struct Initialized { local_secure_channel_address: Address, remote_identity_secure_channel_address: Address, their_identity_id: IdentityIdentifier, } enum State<I: IdentityTrait> { InitiatorStartChannel(InitiatorStartChannel<I>), ResponderWaitForKex(ResponderWaitForKex<I>), InitiatorSendIdentity(InitiatorSendIdentity<I>), ResponderWaitForIdentity(ResponderWaitForIdentity<I>), Initialized(Initialized), } pub(crate) struct SecureChannelWorker<I: IdentityTrait> { is_initiator: bool, self_local_address: Address, self_remote_address: Address, state: Option<State<I>>, } impl<I: IdentityTrait> SecureChannelWorker<I> { pub async fn create_initiator( ctx: &Context, route: Route, identity: I, trust_policy: Arc<dyn TrustPolicy>, vault: impl XXVault, timeout: Duration, ) -> Result<Address> { let child_address = Address::random_local(); let mut child_ctx = ctx.new_context(child_address.clone()).await?; // Generate 2 random fresh address for newly created SecureChannel. // One for local workers to encrypt their messages // Second for remote workers to decrypt their messages let self_local_address: Address = random(); let self_remote_address: Address = random(); let initiator = XXNewKeyExchanger::new(vault.async_try_clone().await?) .initiator() .await?; // Create regular secure channel and set self address as first responder let temp_ctx = ctx.new_context(Address::random_local()).await?; let self_remote_address_clone = self_remote_address.clone(); let channel_future = Box::pin(async move { SecureChannel::create_extended( &temp_ctx, route, Some(self_remote_address_clone), initiator, vault, ) .await }); let state = State::InitiatorStartChannel(InitiatorStartChannel { channel_future, callback_address: child_address, identity, trust_policy, }); let worker = SecureChannelWorker { is_initiator: true, self_local_address: self_local_address.clone(), self_remote_address: self_remote_address.clone(), state: Some(state), }; ctx.start_worker( vec![self_local_address.clone(), self_remote_address.clone()], worker, ) .await?; debug!( "Starting IdentitySecureChannel Initiator at local: {}, remote: {}", &self_local_address, &self_remote_address ); let _ = child_ctx .receive_timeout::<AuthenticationConfirmation>(timeout.as_secs()) .await?; Ok(self_local_address) } pub(crate) async fn create_responder( ctx: &Context, identity: I, trust_policy: Arc<dyn TrustPolicy>, listener_address: Address, msg: Routed<CreateResponderChannelMessage>, ) -> Result<()> { let mut onward_route = msg.onward_route(); onward_route.step()?; onward_route.modify().prepend(listener_address); let return_route = msg.return_route(); let body = msg.body(); // This is the address of Worker on the other end, that Initiator gave us to perform further negotiations. let first_responder_address = body .completed_callback_address() .clone() .ok_or(IdentityError::SecureChannelCannotBeAuthenticated)?; // Generate 2 random fresh address for newly created SecureChannel. // One for local workers to encrypt their messages // Second for remote workers to decrypt their messages let self_local_address: Address = random(); let self_remote_address: Address = random(); // Change completed callback address and forward message for regular key exchange to happen let body = CreateResponderChannelMessage::new( body.payload().to_vec(), Some(self_local_address.clone()), ); let msg = TransportMessage::v1(onward_route, return_route, body.encode()?); let state = State::ResponderWaitForKex(ResponderWaitForKex { first_responder_address, identity, trust_policy, }); let worker = SecureChannelWorker { is_initiator: false, self_local_address: self_local_address.clone(), self_remote_address: self_remote_address.clone(), state: Some(state), }; ctx.start_worker( vec![self_local_address.clone(), self_remote_address.clone()], worker, ) .await?; debug!( "Starting IdentitySecureChannel Responder at local: {}, remote: {}", &self_local_address, &self_remote_address ); ctx.forward(LocalMessage::new(msg, Vec::new())).await?; Ok(()) } async fn
( &mut self, ctx: &mut <Self as Worker>::Context, msg: Routed<<Self as Worker>::Message>, state: ResponderWaitForKex<I>, ) -> Result<()> { let kex_msg = KeyExchangeCompleted::decode(msg.payload())?; // Prove we posses Identity key let proof = state .identity .create_auth_proof(&kex_msg.auth_hash()) .await?; let msg = IdentityChannelMessage::Request { contact: state.identity.as_contact().await?, proof, }; ctx.send_from_address( route![kex_msg.address().clone(), state.first_responder_address], msg, self.self_remote_address.clone(), ) .await?; debug!("Sent Authentication request"); self.state = Some(State::ResponderWaitForIdentity(ResponderWaitForIdentity { auth_hash: kex_msg.auth_hash(), local_secure_channel_address: kex_msg.address().clone(), identity: state.identity, trust_policy: Arc::clone(&state.trust_policy), })); Ok(()) } async fn handle_send_identity( &mut self, ctx: &mut <Self as Worker>::Context, msg: Routed<<Self as Worker>::Message>, state: InitiatorSendIdentity<I>, ) -> Result<()> { let return_route = msg.return_route(); // Ensure message came from dedicated SecureChannel if return_route.next()? != &state.channel.address() { return Err(IdentityError::UnknownChannelMsgDestination.into()); } let body = IdentityChannelMessage::decode(msg.payload())?; // Wait for responder to send us his Identity and Identity Proof. // In case of using Noise XX this is m4 message. if let IdentityChannelMessage::Request { contact, proof } = body { debug!("Received Authentication request"); let their_contact = contact; let their_identity_id = their_contact.identifier().clone(); let contact_result = state.identity.get_contact(&their_identity_id).await?; if contact_result.is_some() { // TODO: We're creating SecureChannel with known Identity. Need to update their Identity. } else { state.identity.verify_and_add_contact(their_contact).await?; } // Verify responder posses their Identity key let verified = state .identity .verify_auth_proof(&state.channel.auth_hash(), &their_identity_id, &proof) .await?; if !verified { return Err(IdentityError::SecureChannelVerificationFailed.into()); } info!( "Initiator verified SecureChannel from: {}", their_identity_id ); // Check our TrustPolicy let trust_info = SecureChannelTrustInfo::new(their_identity_id.clone()); let trusted = state.trust_policy.check(&trust_info).await?; if !trusted { return Err(IdentityError::SecureChannelTrustCheckFailed.into()); } info!( "Initiator checked trust policy for SecureChannel from: {}", &their_identity_id ); // Prove we posses our Identity key let contact = state.identity.as_contact().await?; let proof = state .identity .create_auth_proof(&state.channel.auth_hash()) .await?; let auth_msg = IdentityChannelMessage::Response { contact, proof }; let remote_identity_secure_channel_address = return_route.recipient(); ctx.send_from_address(return_route, auth_msg, self.self_remote_address.clone()) .await?; debug!("Sent Authentication response"); self.state = Some(State::Initialized(Initialized { local_secure_channel_address: state.channel.address(), remote_identity_secure_channel_address, their_identity_id, })); info!( "Initialized IdentitySecureChannel Initiator at local: {}, remote: {}", &self.self_local_address, &self.self_remote_address ); ctx.send( state.callback_address, AuthenticationConfirmation(self.self_local_address.clone()), ) .await?; Ok(()) } else { Err(IdentityError::InvalidSecureChannelInternalState.into()) } } async fn handle_receive_identity( &mut self, _ctx: &mut <Self as Worker>::Context, msg: Routed<<Self as Worker>::Message>, state: ResponderWaitForIdentity<I>, ) -> Result<()> { let return_route = msg.return_route(); // Ensure message came from dedicated SecureChannel if return_route.next()? != &state.local_secure_channel_address { return Err(IdentityError::UnknownChannelMsgDestination.into()); } let body = IdentityChannelMessage::decode(msg.payload())?; // Wait for responder to send us his Identity and Identity Proof. // In case of using Noise XX this is m4 message. if let IdentityChannelMessage::Response { contact, proof } = body { debug!("Received Authentication response"); let their_contact = contact; let their_identity_id = their_contact.identifier().clone(); let contact_result = state.identity.get_contact(&their_identity_id).await?; if contact_result.is_some() { // TODO: We're creating SecureChannel with known Identity. Need to update their Identity. } else { state .identity .verify_and_add_contact(their_contact.clone()) .await?; } // Verify initiator posses their Identity key let verified = state .identity .verify_auth_proof(&state.auth_hash, &their_identity_id, &proof) .await?; if !verified { return Err(IdentityError::SecureChannelVerificationFailed.into()); } info!( "Responder verified SecureChannel from: {}", &their_identity_id ); // Check our TrustPolicy let trust_info = SecureChannelTrustInfo::new(their_identity_id.clone()); let trusted = state.trust_policy.check(&trust_info).await?; if !trusted { return Err(IdentityError::SecureChannelTrustCheckFailed.into()); } info!( "Responder checked trust policy for SecureChannel from: {}", &their_identity_id ); let remote_identity_secure_channel_address = return_route.recipient(); self.state = Some(State::Initialized(Initialized { local_secure_channel_address: state.local_secure_channel_address, remote_identity_secure_channel_address, their_identity_id, })); info!( "Initialized IdentitySecureChannel Responder at local: {}, remote: {}", &self.self_local_address, &self.self_remote_address ); Ok(()) } else { Err(IdentityError::InvalidSecureChannelInternalState.into()) } } fn take_state(&mut self) -> Result<State<I>> { if let Some(s) = self.state.take() { Ok(s) } else { Err(IdentityError::InvalidSecureChannelInternalState.into()) } } async fn handle_encrypt( &mut self, ctx: &mut <Self as Worker>::Context, msg: Routed<<Self as Worker>::Message>, state: Initialized, ) -> Result<()> { debug!( "IdentitySecureChannel {} received Encrypt", if self.is_initiator { "Initiator" } else { "Responder" } ); self.state = Some(State::Initialized(state.clone())); let mut onward_route = msg.onward_route(); let mut return_route = msg.return_route(); let payload = msg.payload().to_vec(); // Send to the other party using local regular SecureChannel let _ = onward_route.step()?; let onward_route = onward_route .modify() .prepend(state.remote_identity_secure_channel_address) .prepend(state.local_secure_channel_address); let return_route = return_route .modify() .prepend(self.self_remote_address.clone()); let transport_msg = TransportMessage::v1(onward_route, return_route, payload); ctx.forward(LocalMessage::new(transport_msg, Vec::new())) .await?; Ok(()) } async fn handle_decrypt( &mut self, ctx: &mut <Self as Worker>::Context, msg: Routed<<Self as Worker>::Message>, state: Initialized, ) -> Result<()> { debug!( "IdentitySecureChannel {} received Decrypt", if self.is_initiator { "Initiator" } else { "Responder" } ); self.state = Some(State::Initialized(state.clone())); let mut onward_route = msg.onward_route(); let mut return_route = msg.return_route(); // Ensure message came from dedicated SecureChannel if return_route.next()? != &state.local_secure_channel_address { return Err(IdentityError::UnknownChannelMsgDestination.into()); } let local_msg = msg.into_local_message(); let mut local_info = local_msg.local_info().to_vec(); let payload = local_msg.into_transport_message().payload; // Forward to local workers let _ = onward_route.step()?; let return_route = return_route .modify() .pop_front() .pop_front() .prepend(self.self_local_address.clone()); let transport_msg = TransportMessage::v1(onward_route, return_route, payload); local_info.push( IdentitySecureChannelLocalInfo::new(state.their_identity_id.clone()).to_local_info()?, ); let msg = LocalMessage::new(transport_msg, local_info); match ctx.forward(msg).await { Ok(_) => Ok(()), Err(err) => { warn!( "{} forwarding decrypted message from {}", err, self.self_local_address ); Ok(()) } } } } #[async_trait] impl<I: IdentityTrait> Worker for SecureChannelWorker<I> { type Message = Any; type Context = Context; async fn initialize(&mut self, _ctx: &mut Self::Context) -> Result<()> { if self.is_initiator { match self.take_state()? { State::InitiatorStartChannel(s) => { let channel = s.channel_future.await?; self.state = Some(State::InitiatorSendIdentity(InitiatorSendIdentity { channel, callback_address: s.callback_address, identity: s.identity, trust_policy: s.trust_policy, })); } _ => return Err(IdentityError::InvalidSecureChannelInternalState.into()), } } Ok(()) } async fn handle_message( &mut self, ctx: &mut Self::Context, msg: Routed<Self::Message>, ) -> Result<()> { let msg_addr = msg.msg_addr(); match self.take_state()? { State::InitiatorStartChannel(_) => { return Err(IdentityError::InvalidSecureChannelInternalState.into()) } State::ResponderWaitForKex(s) => { if msg_addr == self.self_local_address { self.handle_kex_done(ctx, msg, s).await?; } else { return Err(IdentityError::UnknownChannelMsgDestination.into()); } } State::InitiatorSendIdentity(s) => { if msg_addr == self.self_remote_address { self.handle_send_identity(ctx, msg, s).await?; } else { return Err(IdentityError::UnknownChannelMsgDestination.into()); } } State::ResponderWaitForIdentity(s) => { if msg_addr == self.self_remote_address { self.handle_receive_identity(ctx, msg, s).await?; } else { return Err(IdentityError::UnknownChannelMsgDestination.into()); } } State::Initialized(s) => { if msg_addr == self.self_local_address { self.handle_encrypt(ctx, msg, s).await?; } else if msg_addr == self.self_remote_address { self.handle_decrypt(ctx, msg, s).await?; } else { return Err(IdentityError::UnknownChannelMsgDestination.into()); } } } Ok(()) } }
handle_kex_done
readwrite.go
package imagelib import ( "errors" "image" "image/gif" "image/jpeg" "image/png" "os" "path/filepath" "strings" ) func Read(filename string) (image.Image, error)
func Write(filename string, img image.Image) error { f, err := os.Create(filename) if err != nil { return err } defer f.Close() switch strings.ToLower(filepath.Ext(filename)) { case ".png": return png.Encode(f, img) case ".jpg", ".jpeg": return jpeg.Encode(f, img, nil) case ".gif": return gif.Encode(f, img, nil) } return errors.New("unrecognized file extension: " + filepath.Ext(filename)) }
{ f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() switch strings.ToLower(filepath.Ext(filename)) { case ".png": return png.Decode(f) case ".jpg", ".jpeg": return jpeg.Decode(f) case ".gif": return gif.Decode(f) } return nil, errors.New("unrecognized file extension: " + filepath.Ext(filename)) }
stt.py
from .base import ApiCaller from PyQt5.QtCore import pyqtSignal from surirobot.core.common import State, ehpyqtSlot import requests import logging import os class
(ApiCaller): """ API class for STT API https://github.com/suricats/surirobot-api-converse """ update_state = pyqtSignal(str, int, dict) def __init__(self, url): ApiCaller.__init__(self, url) self.logger = logging.getLogger(type(self).__name__) def __del__(self): self.stop() @ehpyqtSlot(str) def recognize(self, file_path): """ Recognize an audio file and give the corresponding text. Retrieve path of audio file and send a signal that includes state, intent("@STT") and reply Parameters ---------- file_path : str path of audio file Returns ------- None This function only send a signal """ with open(file_path, 'rb') as file: # Send request url = self.url+'/stt/recognize' data = {'language': self.DEFAULT_LANGUAGE_EXT} if id: data['id'] = id self.logger.info("Sent to STT API : File - {} : {}Ko".format(file_path, os.fstat(file.fileno()).st_size / 1000)) r = requests.post(url, files={'audio': file}, data=data) # Receive response if r.status_code == 200: json_object = r.json() self.update_state.emit("converse", State.CONVERSE_NEW, {"intent": "@STT", "reply": json_object["text"]}) elif r.status_code == 503: self.update_state.emit("converse", State.CONVERSE_NEW, {"intent": "no-understand", "reply": "J'ai n'ai pas entendu ce que vous avez dit."}) else: self.logger.error('HTTP {} error occurred while retrieving text.'.format(r.status_code)) self.logger.error(r.content) # self.signal_indicator.emit("converse", "orange") # self.update_state.emit("converse", State.CONVERSE_NEW, {"intent": "dont-understand", "reply": "Je n'ai pas compris."})
SttApiCaller
ex100.py
from random import randint from time import sleep def
(lista): print('=-=' * 15) for c in range(0, 5): lista.append(randint(1, 10)) print('Sorteando 5 valores da lista: ', end=' ') for c in lista: print(f'{c}', end=' ', flush=True) sleep(0.3) print() def somapar(lista): soma = 0 for c in n: if c % 2 == 0: soma += c print(f'Soma dos valores pares: {soma}') n = [] sorteia(n) somapar(n)
sorteia
fake_uaaclient.go
// Code generated by counterfeiter. DO NOT EDIT. package noaabridgefakes import ( "sync" "code.cloudfoundry.org/cli/api/uaa" "code.cloudfoundry.org/cli/api/uaa/noaabridge" ) type FakeUAAClient struct { RefreshAccessTokenStub func(refreshToken string) (uaa.RefreshToken, error) refreshAccessTokenMutex sync.RWMutex refreshAccessTokenArgsForCall []struct { refreshToken string } refreshAccessTokenReturns struct { result1 uaa.RefreshToken result2 error } refreshAccessTokenReturnsOnCall map[int]struct { result1 uaa.RefreshToken result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *FakeUAAClient) RefreshAccessToken(refreshToken string) (uaa.RefreshToken, error) { fake.refreshAccessTokenMutex.Lock() ret, specificReturn := fake.refreshAccessTokenReturnsOnCall[len(fake.refreshAccessTokenArgsForCall)] fake.refreshAccessTokenArgsForCall = append(fake.refreshAccessTokenArgsForCall, struct { refreshToken string }{refreshToken}) fake.recordInvocation("RefreshAccessToken", []interface{}{refreshToken}) fake.refreshAccessTokenMutex.Unlock() if fake.RefreshAccessTokenStub != nil { return fake.RefreshAccessTokenStub(refreshToken) } if specificReturn { return ret.result1, ret.result2 } return fake.refreshAccessTokenReturns.result1, fake.refreshAccessTokenReturns.result2 } func (fake *FakeUAAClient) RefreshAccessTokenCallCount() int { fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() return len(fake.refreshAccessTokenArgsForCall) } func (fake *FakeUAAClient) RefreshAccessTokenArgsForCall(i int) string { fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() return fake.refreshAccessTokenArgsForCall[i].refreshToken } func (fake *FakeUAAClient) RefreshAccessTokenReturns(result1 uaa.RefreshToken, result2 error) { fake.RefreshAccessTokenStub = nil fake.refreshAccessTokenReturns = struct { result1 uaa.RefreshToken result2 error }{result1, result2} } func (fake *FakeUAAClient) RefreshAccessTokenReturnsOnCall(i int, result1 uaa.RefreshToken, result2 error) { fake.RefreshAccessTokenStub = nil if fake.refreshAccessTokenReturnsOnCall == nil { fake.refreshAccessTokenReturnsOnCall = make(map[int]struct { result1 uaa.RefreshToken result2 error }) }
}{result1, result2} } func (fake *FakeUAAClient) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.refreshAccessTokenMutex.RLock() defer fake.refreshAccessTokenMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *FakeUAAClient) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) } var _ noaabridge.UAAClient = new(FakeUAAClient)
fake.refreshAccessTokenReturnsOnCall[i] = struct { result1 uaa.RefreshToken result2 error
output.rs
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateIdentityProviderConfigurationOutput {} impl std::fmt::Debug for UpdateIdentityProviderConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateIdentityProviderConfigurationOutput"); formatter.finish() } } /// See [`UpdateIdentityProviderConfigurationOutput`](crate::output::UpdateIdentityProviderConfigurationOutput) pub mod update_identity_provider_configuration_output { /// A builder for [`UpdateIdentityProviderConfigurationOutput`](crate::output::UpdateIdentityProviderConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateIdentityProviderConfigurationOutput`](crate::output::UpdateIdentityProviderConfigurationOutput) pub fn build(self) -> crate::output::UpdateIdentityProviderConfigurationOutput { crate::output::UpdateIdentityProviderConfigurationOutput {} } } } impl UpdateIdentityProviderConfigurationOutput { /// Creates a new builder-style object to manufacture [`UpdateIdentityProviderConfigurationOutput`](crate::output::UpdateIdentityProviderConfigurationOutput) pub fn builder() -> crate::output::update_identity_provider_configuration_output::Builder { crate::output::update_identity_provider_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateFleetMetadataOutput {} impl std::fmt::Debug for UpdateFleetMetadataOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateFleetMetadataOutput"); formatter.finish() } } /// See [`UpdateFleetMetadataOutput`](crate::output::UpdateFleetMetadataOutput) pub mod update_fleet_metadata_output { /// A builder for [`UpdateFleetMetadataOutput`](crate::output::UpdateFleetMetadataOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateFleetMetadataOutput`](crate::output::UpdateFleetMetadataOutput) pub fn build(self) -> crate::output::UpdateFleetMetadataOutput { crate::output::UpdateFleetMetadataOutput {} } } } impl UpdateFleetMetadataOutput { /// Creates a new builder-style object to manufacture [`UpdateFleetMetadataOutput`](crate::output::UpdateFleetMetadataOutput) pub fn builder() -> crate::output::update_fleet_metadata_output::Builder { crate::output::update_fleet_metadata_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateDomainMetadataOutput {} impl std::fmt::Debug for UpdateDomainMetadataOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateDomainMetadataOutput"); formatter.finish() } } /// See [`UpdateDomainMetadataOutput`](crate::output::UpdateDomainMetadataOutput) pub mod update_domain_metadata_output { /// A builder for [`UpdateDomainMetadataOutput`](crate::output::UpdateDomainMetadataOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateDomainMetadataOutput`](crate::output::UpdateDomainMetadataOutput) pub fn build(self) -> crate::output::UpdateDomainMetadataOutput { crate::output::UpdateDomainMetadataOutput {} } } } impl UpdateDomainMetadataOutput { /// Creates a new builder-style object to manufacture [`UpdateDomainMetadataOutput`](crate::output::UpdateDomainMetadataOutput) pub fn builder() -> crate::output::update_domain_metadata_output::Builder { crate::output::update_domain_metadata_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateDevicePolicyConfigurationOutput {} impl std::fmt::Debug for UpdateDevicePolicyConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateDevicePolicyConfigurationOutput"); formatter.finish() } } /// See [`UpdateDevicePolicyConfigurationOutput`](crate::output::UpdateDevicePolicyConfigurationOutput) pub mod update_device_policy_configuration_output { /// A builder for [`UpdateDevicePolicyConfigurationOutput`](crate::output::UpdateDevicePolicyConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateDevicePolicyConfigurationOutput`](crate::output::UpdateDevicePolicyConfigurationOutput) pub fn build(self) -> crate::output::UpdateDevicePolicyConfigurationOutput { crate::output::UpdateDevicePolicyConfigurationOutput {} } } } impl UpdateDevicePolicyConfigurationOutput { /// Creates a new builder-style object to manufacture [`UpdateDevicePolicyConfigurationOutput`](crate::output::UpdateDevicePolicyConfigurationOutput) pub fn builder() -> crate::output::update_device_policy_configuration_output::Builder { crate::output::update_device_policy_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateCompanyNetworkConfigurationOutput {} impl std::fmt::Debug for UpdateCompanyNetworkConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateCompanyNetworkConfigurationOutput"); formatter.finish() } } /// See [`UpdateCompanyNetworkConfigurationOutput`](crate::output::UpdateCompanyNetworkConfigurationOutput) pub mod update_company_network_configuration_output { /// A builder for [`UpdateCompanyNetworkConfigurationOutput`](crate::output::UpdateCompanyNetworkConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateCompanyNetworkConfigurationOutput`](crate::output::UpdateCompanyNetworkConfigurationOutput) pub fn build(self) -> crate::output::UpdateCompanyNetworkConfigurationOutput { crate::output::UpdateCompanyNetworkConfigurationOutput {} } } } impl UpdateCompanyNetworkConfigurationOutput { /// Creates a new builder-style object to manufacture [`UpdateCompanyNetworkConfigurationOutput`](crate::output::UpdateCompanyNetworkConfigurationOutput) pub fn builder() -> crate::output::update_company_network_configuration_output::Builder { crate::output::update_company_network_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UpdateAuditStreamConfigurationOutput {} impl std::fmt::Debug for UpdateAuditStreamConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UpdateAuditStreamConfigurationOutput"); formatter.finish() } } /// See [`UpdateAuditStreamConfigurationOutput`](crate::output::UpdateAuditStreamConfigurationOutput) pub mod update_audit_stream_configuration_output { /// A builder for [`UpdateAuditStreamConfigurationOutput`](crate::output::UpdateAuditStreamConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UpdateAuditStreamConfigurationOutput`](crate::output::UpdateAuditStreamConfigurationOutput) pub fn build(self) -> crate::output::UpdateAuditStreamConfigurationOutput { crate::output::UpdateAuditStreamConfigurationOutput {} } } } impl UpdateAuditStreamConfigurationOutput { /// Creates a new builder-style object to manufacture [`UpdateAuditStreamConfigurationOutput`](crate::output::UpdateAuditStreamConfigurationOutput) pub fn builder() -> crate::output::update_audit_stream_configuration_output::Builder { crate::output::update_audit_stream_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UntagResourceOutput {} impl std::fmt::Debug for UntagResourceOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UntagResourceOutput"); formatter.finish() } } /// See [`UntagResourceOutput`](crate::output::UntagResourceOutput) pub mod untag_resource_output { /// A builder for [`UntagResourceOutput`](crate::output::UntagResourceOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`UntagResourceOutput`](crate::output::UntagResourceOutput) pub fn build(self) -> crate::output::UntagResourceOutput { crate::output::UntagResourceOutput {} } } } impl UntagResourceOutput { /// Creates a new builder-style object to manufacture [`UntagResourceOutput`](crate::output::UntagResourceOutput) pub fn builder() -> crate::output::untag_resource_output::Builder { crate::output::untag_resource_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TagResourceOutput {} impl std::fmt::Debug for TagResourceOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TagResourceOutput"); formatter.finish() } } /// See [`TagResourceOutput`](crate::output::TagResourceOutput) pub mod tag_resource_output { /// A builder for [`TagResourceOutput`](crate::output::TagResourceOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`TagResourceOutput`](crate::output::TagResourceOutput) pub fn build(self) -> crate::output::TagResourceOutput { crate::output::TagResourceOutput {} } } } impl TagResourceOutput { /// Creates a new builder-style object to manufacture [`TagResourceOutput`](crate::output::TagResourceOutput) pub fn builder() -> crate::output::tag_resource_output::Builder { crate::output::tag_resource_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SignOutUserOutput {} impl std::fmt::Debug for SignOutUserOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SignOutUserOutput"); formatter.finish() } } /// See [`SignOutUserOutput`](crate::output::SignOutUserOutput) pub mod sign_out_user_output { /// A builder for [`SignOutUserOutput`](crate::output::SignOutUserOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`SignOutUserOutput`](crate::output::SignOutUserOutput) pub fn build(self) -> crate::output::SignOutUserOutput { crate::output::SignOutUserOutput {} } } } impl SignOutUserOutput { /// Creates a new builder-style object to manufacture [`SignOutUserOutput`](crate::output::SignOutUserOutput) pub fn builder() -> crate::output::sign_out_user_output::Builder { crate::output::sign_out_user_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RevokeDomainAccessOutput {} impl std::fmt::Debug for RevokeDomainAccessOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RevokeDomainAccessOutput"); formatter.finish() } } /// See [`RevokeDomainAccessOutput`](crate::output::RevokeDomainAccessOutput) pub mod revoke_domain_access_output { /// A builder for [`RevokeDomainAccessOutput`](crate::output::RevokeDomainAccessOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`RevokeDomainAccessOutput`](crate::output::RevokeDomainAccessOutput) pub fn build(self) -> crate::output::RevokeDomainAccessOutput { crate::output::RevokeDomainAccessOutput {} } } } impl RevokeDomainAccessOutput { /// Creates a new builder-style object to manufacture [`RevokeDomainAccessOutput`](crate::output::RevokeDomainAccessOutput) pub fn builder() -> crate::output::revoke_domain_access_output::Builder { crate::output::revoke_domain_access_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct RestoreDomainAccessOutput {} impl std::fmt::Debug for RestoreDomainAccessOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("RestoreDomainAccessOutput"); formatter.finish() } } /// See [`RestoreDomainAccessOutput`](crate::output::RestoreDomainAccessOutput) pub mod restore_domain_access_output { /// A builder for [`RestoreDomainAccessOutput`](crate::output::RestoreDomainAccessOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`RestoreDomainAccessOutput`](crate::output::RestoreDomainAccessOutput) pub fn build(self) -> crate::output::RestoreDomainAccessOutput { crate::output::RestoreDomainAccessOutput {} } } } impl RestoreDomainAccessOutput { /// Creates a new builder-style object to manufacture [`RestoreDomainAccessOutput`](crate::output::RestoreDomainAccessOutput) pub fn builder() -> crate::output::restore_domain_access_output::Builder { crate::output::restore_domain_access_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListWebsiteCertificateAuthoritiesOutput { /// <p>Information about the certificates.</p> pub website_certificate_authorities: std::option::Option<std::vec::Vec<crate::model::WebsiteCaSummary>>, /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub next_token: std::option::Option<std::string::String>, } impl ListWebsiteCertificateAuthoritiesOutput { /// <p>Information about the certificates.</p> pub fn website_certificate_authorities( &self, ) -> std::option::Option<&[crate::model::WebsiteCaSummary]> { self.website_certificate_authorities.as_deref() } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListWebsiteCertificateAuthoritiesOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListWebsiteCertificateAuthoritiesOutput"); formatter.field( "website_certificate_authorities", &self.website_certificate_authorities, ); formatter.field("next_token", &self.next_token); formatter.finish() } } /// See [`ListWebsiteCertificateAuthoritiesOutput`](crate::output::ListWebsiteCertificateAuthoritiesOutput) pub mod list_website_certificate_authorities_output { /// A builder for [`ListWebsiteCertificateAuthoritiesOutput`](crate::output::ListWebsiteCertificateAuthoritiesOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) website_certificate_authorities: std::option::Option<std::vec::Vec<crate::model::WebsiteCaSummary>>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `website_certificate_authorities`. /// /// To override the contents of this collection use [`set_website_certificate_authorities`](Self::set_website_certificate_authorities). /// /// <p>Information about the certificates.</p> pub fn website_certificate_authorities( mut self, input: impl Into<crate::model::WebsiteCaSummary>, ) -> Self { let mut v = self.website_certificate_authorities.unwrap_or_default(); v.push(input.into()); self.website_certificate_authorities = Some(v); self } /// <p>Information about the certificates.</p> pub fn set_website_certificate_authorities( mut self, input: std::option::Option<std::vec::Vec<crate::model::WebsiteCaSummary>>, ) -> Self { self.website_certificate_authorities = input; self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListWebsiteCertificateAuthoritiesOutput`](crate::output::ListWebsiteCertificateAuthoritiesOutput) pub fn build(self) -> crate::output::ListWebsiteCertificateAuthoritiesOutput { crate::output::ListWebsiteCertificateAuthoritiesOutput { website_certificate_authorities: self.website_certificate_authorities, next_token: self.next_token, } } } } impl ListWebsiteCertificateAuthoritiesOutput { /// Creates a new builder-style object to manufacture [`ListWebsiteCertificateAuthoritiesOutput`](crate::output::ListWebsiteCertificateAuthoritiesOutput) pub fn builder() -> crate::output::list_website_certificate_authorities_output::Builder { crate::output::list_website_certificate_authorities_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListWebsiteAuthorizationProvidersOutput { /// <p>The website authorization providers.</p> pub website_authorization_providers: std::option::Option<std::vec::Vec<crate::model::WebsiteAuthorizationProviderSummary>>, /// <p>The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.</p> pub next_token: std::option::Option<std::string::String>, } impl ListWebsiteAuthorizationProvidersOutput { /// <p>The website authorization providers.</p> pub fn website_authorization_providers( &self, ) -> std::option::Option<&[crate::model::WebsiteAuthorizationProviderSummary]> { self.website_authorization_providers.as_deref() } /// <p>The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListWebsiteAuthorizationProvidersOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListWebsiteAuthorizationProvidersOutput"); formatter.field( "website_authorization_providers", &self.website_authorization_providers, ); formatter.field("next_token", &self.next_token); formatter.finish() } } /// See [`ListWebsiteAuthorizationProvidersOutput`](crate::output::ListWebsiteAuthorizationProvidersOutput) pub mod list_website_authorization_providers_output { /// A builder for [`ListWebsiteAuthorizationProvidersOutput`](crate::output::ListWebsiteAuthorizationProvidersOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) website_authorization_providers: std::option::Option<std::vec::Vec<crate::model::WebsiteAuthorizationProviderSummary>>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `website_authorization_providers`. /// /// To override the contents of this collection use [`set_website_authorization_providers`](Self::set_website_authorization_providers). /// /// <p>The website authorization providers.</p> pub fn website_authorization_providers( mut self, input: impl Into<crate::model::WebsiteAuthorizationProviderSummary>, ) -> Self { let mut v = self.website_authorization_providers.unwrap_or_default(); v.push(input.into()); self.website_authorization_providers = Some(v); self } /// <p>The website authorization providers.</p> pub fn set_website_authorization_providers( mut self, input: std::option::Option< std::vec::Vec<crate::model::WebsiteAuthorizationProviderSummary>, >, ) -> Self { self.website_authorization_providers = input; self } /// <p>The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListWebsiteAuthorizationProvidersOutput`](crate::output::ListWebsiteAuthorizationProvidersOutput) pub fn build(self) -> crate::output::ListWebsiteAuthorizationProvidersOutput { crate::output::ListWebsiteAuthorizationProvidersOutput { website_authorization_providers: self.website_authorization_providers, next_token: self.next_token, } } } } impl ListWebsiteAuthorizationProvidersOutput { /// Creates a new builder-style object to manufacture [`ListWebsiteAuthorizationProvidersOutput`](crate::output::ListWebsiteAuthorizationProvidersOutput) pub fn builder() -> crate::output::list_website_authorization_providers_output::Builder { crate::output::list_website_authorization_providers_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForResourceOutput { /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl ListTagsForResourceOutput { /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn tags( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.tags.as_ref() } } impl std::fmt::Debug for ListTagsForResourceOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListTagsForResourceOutput"); formatter.field("tags", &self.tags); formatter.finish() } } /// See [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput) pub mod list_tags_for_resource_output { /// A builder for [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// Adds a key-value pair to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput) pub fn build(self) -> crate::output::ListTagsForResourceOutput { crate::output::ListTagsForResourceOutput { tags: self.tags } } } } impl ListTagsForResourceOutput { /// Creates a new builder-style object to manufacture [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput) pub fn builder() -> crate::output::list_tags_for_resource_output::Builder { crate::output::list_tags_for_resource_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListFleetsOutput { /// <p>The summary list of the fleets.</p> pub fleet_summary_list: std::option::Option<std::vec::Vec<crate::model::FleetSummary>>, /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub next_token: std::option::Option<std::string::String>, } impl ListFleetsOutput { /// <p>The summary list of the fleets.</p> pub fn fleet_summary_list(&self) -> std::option::Option<&[crate::model::FleetSummary]> { self.fleet_summary_list.as_deref() } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListFleetsOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListFleetsOutput"); formatter.field("fleet_summary_list", &self.fleet_summary_list); formatter.field("next_token", &self.next_token); formatter.finish() } } /// See [`ListFleetsOutput`](crate::output::ListFleetsOutput) pub mod list_fleets_output { /// A builder for [`ListFleetsOutput`](crate::output::ListFleetsOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) fleet_summary_list: std::option::Option<std::vec::Vec<crate::model::FleetSummary>>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `fleet_summary_list`. /// /// To override the contents of this collection use [`set_fleet_summary_list`](Self::set_fleet_summary_list). /// /// <p>The summary list of the fleets.</p> pub fn fleet_summary_list(mut self, input: impl Into<crate::model::FleetSummary>) -> Self { let mut v = self.fleet_summary_list.unwrap_or_default(); v.push(input.into()); self.fleet_summary_list = Some(v); self } /// <p>The summary list of the fleets.</p> pub fn set_fleet_summary_list( mut self, input: std::option::Option<std::vec::Vec<crate::model::FleetSummary>>, ) -> Self { self.fleet_summary_list = input; self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListFleetsOutput`](crate::output::ListFleetsOutput) pub fn build(self) -> crate::output::ListFleetsOutput { crate::output::ListFleetsOutput { fleet_summary_list: self.fleet_summary_list, next_token: self.next_token, } } } } impl ListFleetsOutput { /// Creates a new builder-style object to manufacture [`ListFleetsOutput`](crate::output::ListFleetsOutput) pub fn builder() -> crate::output::list_fleets_output::Builder { crate::output::list_fleets_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDomainsOutput { /// <p>Information about the domains.</p> pub domains: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub next_token: std::option::Option<std::string::String>, } impl ListDomainsOutput { /// <p>Information about the domains.</p> pub fn domains(&self) -> std::option::Option<&[crate::model::DomainSummary]> { self.domains.as_deref() } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListDomainsOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDomainsOutput"); formatter.field("domains", &self.domains); formatter.field("next_token", &self.next_token); formatter.finish() } } /// See [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub mod list_domains_output { /// A builder for [`ListDomainsOutput`](crate::output::ListDomainsOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domains: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `domains`. /// /// To override the contents of this collection use [`set_domains`](Self::set_domains). /// /// <p>Information about the domains.</p> pub fn domains(mut self, input: impl Into<crate::model::DomainSummary>) -> Self { let mut v = self.domains.unwrap_or_default(); v.push(input.into()); self.domains = Some(v); self } /// <p>Information about the domains.</p> pub fn set_domains( mut self, input: std::option::Option<std::vec::Vec<crate::model::DomainSummary>>, ) -> Self { self.domains = input; self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub fn build(self) -> crate::output::ListDomainsOutput { crate::output::ListDomainsOutput { domains: self.domains, next_token: self.next_token, } } } } impl ListDomainsOutput { /// Creates a new builder-style object to manufacture [`ListDomainsOutput`](crate::output::ListDomainsOutput) pub fn builder() -> crate::output::list_domains_output::Builder { crate::output::list_domains_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListDevicesOutput { /// <p>Information about the devices.</p> pub devices: std::option::Option<std::vec::Vec<crate::model::DeviceSummary>>, /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub next_token: std::option::Option<std::string::String>, } impl ListDevicesOutput { /// <p>Information about the devices.</p> pub fn devices(&self) -> std::option::Option<&[crate::model::DeviceSummary]> { self.devices.as_deref() } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(&self) -> std::option::Option<&str> { self.next_token.as_deref() } } impl std::fmt::Debug for ListDevicesOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListDevicesOutput"); formatter.field("devices", &self.devices); formatter.field("next_token", &self.next_token); formatter.finish() } } /// See [`ListDevicesOutput`](crate::output::ListDevicesOutput) pub mod list_devices_output { /// A builder for [`ListDevicesOutput`](crate::output::ListDevicesOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) devices: std::option::Option<std::vec::Vec<crate::model::DeviceSummary>>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// Appends an item to `devices`. /// /// To override the contents of this collection use [`set_devices`](Self::set_devices). /// /// <p>Information about the devices.</p> pub fn devices(mut self, input: impl Into<crate::model::DeviceSummary>) -> Self { let mut v = self.devices.unwrap_or_default(); v.push(input.into()); self.devices = Some(v); self } /// <p>Information about the devices.</p> pub fn set_devices( mut self, input: std::option::Option<std::vec::Vec<crate::model::DeviceSummary>>, ) -> Self { self.devices = input; self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } /// <p>The pagination token used to retrieve the next page of results for this operation. If /// there are no more pages, this value is null.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListDevicesOutput`](crate::output::ListDevicesOutput) pub fn build(self) -> crate::output::ListDevicesOutput { crate::output::ListDevicesOutput { devices: self.devices, next_token: self.next_token, } } } } impl ListDevicesOutput { /// Creates a new builder-style object to manufacture [`ListDevicesOutput`](crate::output::ListDevicesOutput) pub fn builder() -> crate::output::list_devices_output::Builder { crate::output::list_devices_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisassociateWebsiteCertificateAuthorityOutput {} impl std::fmt::Debug for DisassociateWebsiteCertificateAuthorityOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisassociateWebsiteCertificateAuthorityOutput"); formatter.finish() } } /// See [`DisassociateWebsiteCertificateAuthorityOutput`](crate::output::DisassociateWebsiteCertificateAuthorityOutput) pub mod disassociate_website_certificate_authority_output { /// A builder for [`DisassociateWebsiteCertificateAuthorityOutput`](crate::output::DisassociateWebsiteCertificateAuthorityOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DisassociateWebsiteCertificateAuthorityOutput`](crate::output::DisassociateWebsiteCertificateAuthorityOutput) pub fn build(self) -> crate::output::DisassociateWebsiteCertificateAuthorityOutput { crate::output::DisassociateWebsiteCertificateAuthorityOutput {} } } } impl DisassociateWebsiteCertificateAuthorityOutput { /// Creates a new builder-style object to manufacture [`DisassociateWebsiteCertificateAuthorityOutput`](crate::output::DisassociateWebsiteCertificateAuthorityOutput) pub fn builder() -> crate::output::disassociate_website_certificate_authority_output::Builder { crate::output::disassociate_website_certificate_authority_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisassociateWebsiteAuthorizationProviderOutput {} impl std::fmt::Debug for DisassociateWebsiteAuthorizationProviderOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisassociateWebsiteAuthorizationProviderOutput"); formatter.finish() } } /// See [`DisassociateWebsiteAuthorizationProviderOutput`](crate::output::DisassociateWebsiteAuthorizationProviderOutput) pub mod disassociate_website_authorization_provider_output { /// A builder for [`DisassociateWebsiteAuthorizationProviderOutput`](crate::output::DisassociateWebsiteAuthorizationProviderOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DisassociateWebsiteAuthorizationProviderOutput`](crate::output::DisassociateWebsiteAuthorizationProviderOutput) pub fn build(self) -> crate::output::DisassociateWebsiteAuthorizationProviderOutput { crate::output::DisassociateWebsiteAuthorizationProviderOutput {} } } } impl DisassociateWebsiteAuthorizationProviderOutput { /// Creates a new builder-style object to manufacture [`DisassociateWebsiteAuthorizationProviderOutput`](crate::output::DisassociateWebsiteAuthorizationProviderOutput) pub fn builder() -> crate::output::disassociate_website_authorization_provider_output::Builder { crate::output::disassociate_website_authorization_provider_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DisassociateDomainOutput {} impl std::fmt::Debug for DisassociateDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DisassociateDomainOutput"); formatter.finish() } } /// See [`DisassociateDomainOutput`](crate::output::DisassociateDomainOutput) pub mod disassociate_domain_output { /// A builder for [`DisassociateDomainOutput`](crate::output::DisassociateDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DisassociateDomainOutput`](crate::output::DisassociateDomainOutput) pub fn build(self) -> crate::output::DisassociateDomainOutput { crate::output::DisassociateDomainOutput {} } } } impl DisassociateDomainOutput { /// Creates a new builder-style object to manufacture [`DisassociateDomainOutput`](crate::output::DisassociateDomainOutput) pub fn builder() -> crate::output::disassociate_domain_output::Builder { crate::output::disassociate_domain_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeWebsiteCertificateAuthorityOutput { /// <p>The root certificate of the certificate authority.</p> pub certificate: std::option::Option<std::string::String>, /// <p>The time that the certificate authority was added.</p> pub created_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The certificate name to display.</p> pub display_name: std::option::Option<std::string::String>, } impl DescribeWebsiteCertificateAuthorityOutput { /// <p>The root certificate of the certificate authority.</p> pub fn certificate(&self) -> std::option::Option<&str> { self.certificate.as_deref() } /// <p>The time that the certificate authority was added.</p> pub fn created_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.created_time.as_ref() } /// <p>The certificate name to display.</p> pub fn display_name(&self) -> std::option::Option<&str> { self.display_name.as_deref() } } impl std::fmt::Debug for DescribeWebsiteCertificateAuthorityOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeWebsiteCertificateAuthorityOutput"); formatter.field("certificate", &self.certificate); formatter.field("created_time", &self.created_time); formatter.field("display_name", &self.display_name); formatter.finish() } } /// See [`DescribeWebsiteCertificateAuthorityOutput`](crate::output::DescribeWebsiteCertificateAuthorityOutput) pub mod describe_website_certificate_authority_output { /// A builder for [`DescribeWebsiteCertificateAuthorityOutput`](crate::output::DescribeWebsiteCertificateAuthorityOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) certificate: std::option::Option<std::string::String>, pub(crate) created_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) display_name: std::option::Option<std::string::String>, } impl Builder { /// <p>The root certificate of the certificate authority.</p> pub fn certificate(mut self, input: impl Into<std::string::String>) -> Self { self.certificate = Some(input.into()); self } /// <p>The root certificate of the certificate authority.</p> pub fn set_certificate(mut self, input: std::option::Option<std::string::String>) -> Self { self.certificate = input; self } /// <p>The time that the certificate authority was added.</p> pub fn created_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.created_time = Some(input); self } /// <p>The time that the certificate authority was added.</p> pub fn set_created_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.created_time = input; self } /// <p>The certificate name to display.</p> pub fn display_name(mut self, input: impl Into<std::string::String>) -> Self { self.display_name = Some(input.into()); self } /// <p>The certificate name to display.</p> pub fn set_display_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.display_name = input; self } /// Consumes the builder and constructs a [`DescribeWebsiteCertificateAuthorityOutput`](crate::output::DescribeWebsiteCertificateAuthorityOutput) pub fn build(self) -> crate::output::DescribeWebsiteCertificateAuthorityOutput { crate::output::DescribeWebsiteCertificateAuthorityOutput { certificate: self.certificate, created_time: self.created_time, display_name: self.display_name, } } } } impl DescribeWebsiteCertificateAuthorityOutput { /// Creates a new builder-style object to manufacture [`DescribeWebsiteCertificateAuthorityOutput`](crate::output::DescribeWebsiteCertificateAuthorityOutput) pub fn builder() -> crate::output::describe_website_certificate_authority_output::Builder { crate::output::describe_website_certificate_authority_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeIdentityProviderConfigurationOutput { /// <p>The type of identity provider.</p> pub identity_provider_type: std::option::Option<crate::model::IdentityProviderType>, /// <p>The SAML metadata document uploaded to the user’s identity provider.</p> pub service_provider_saml_metadata: std::option::Option<std::string::String>, /// <p>The SAML metadata document provided by the user’s identity provider.</p> pub identity_provider_saml_metadata: std::option::Option<std::string::String>, } impl DescribeIdentityProviderConfigurationOutput { /// <p>The type of identity provider.</p> pub fn identity_provider_type( &self, ) -> std::option::Option<&crate::model::IdentityProviderType> { self.identity_provider_type.as_ref() } /// <p>The SAML metadata document uploaded to the user’s identity provider.</p> pub fn service_provider_saml_metadata(&self) -> std::option::Option<&str> { self.service_provider_saml_metadata.as_deref() } /// <p>The SAML metadata document provided by the user’s identity provider.</p> pub fn identity_provider_saml_metadata(&self) -> std::option::Option<&str> { self.identity_provider_saml_metadata.as_deref() } } impl std::fmt::Debug for DescribeIdentityProviderConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeIdentityProviderConfigurationOutput"); formatter.field("identity_provider_type", &self.identity_provider_type); formatter.field( "service_provider_saml_metadata", &self.service_provider_saml_metadata, ); formatter.field( "identity_provider_saml_metadata", &self.identity_provider_saml_metadata, ); formatter.finish() } } /// See [`DescribeIdentityProviderConfigurationOutput`](crate::output::DescribeIdentityProviderConfigurationOutput) pub mod describe_identity_provider_configuration_output { /// A builder for [`DescribeIdentityProviderConfigurationOutput`](crate::output::DescribeIdentityProviderConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) identity_provider_type: std::option::Option<crate::model::IdentityProviderType>, pub(crate) service_provider_saml_metadata: std::option::Option<std::string::String>, pub(crate) identity_provider_saml_metadata: std::option::Option<std::string::String>, } impl Builder { /// <p>The type of identity provider.</p> pub fn identity_provider_type(mut self, input: crate::model::IdentityProviderType) -> Self { self.identity_provider_type = Some(input); self } /// <p>The type of identity provider.</p> pub fn set_identity_provider_type( mut self, input: std::option::Option<crate::model::IdentityProviderType>, ) -> Self { self.identity_provider_type = input; self } /// <p>The SAML metadata document uploaded to the user’s identity provider.</p> pub fn service_provider_saml_metadata( mut self, input: impl Into<std::string::String>, ) -> Self { self.service_provider_saml_metadata = Some(input.into()); self } /// <p>The SAML metadata document uploaded to the user’s identity provider.</p> pub fn set_service_provider_saml_metadata( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.service_provider_saml_metadata = input; self } /// <p>The SAML metadata document provided by the user’s identity provider.</p> pub fn identity_provider_saml_metadata( mut self, input: impl Into<std::string::String>, ) -> Self { self.identity_provider_saml_metadata = Some(input.into()); self } /// <p>The SAML metadata document provided by the user’s identity provider.</p> pub fn set_identity_provider_saml_metadata( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.identity_provider_saml_metadata = input; self } /// Consumes the builder and constructs a [`DescribeIdentityProviderConfigurationOutput`](crate::output::DescribeIdentityProviderConfigurationOutput) pub fn build(self) -> crate::output::DescribeIdentityProviderConfigurationOutput { crate::output::DescribeIdentityProviderConfigurationOutput { identity_provider_type: self.identity_provider_type, service_provider_saml_metadata: self.service_provider_saml_metadata, identity_provider_saml_metadata: self.identity_provider_saml_metadata, } } } } impl DescribeIdentityProviderConfigurationOutput { /// Creates a new builder-style object to manufacture [`DescribeIdentityProviderConfigurationOutput`](crate::output::DescribeIdentityProviderConfigurationOutput) pub fn builder() -> crate::output::describe_identity_provider_configuration_output::Builder { crate::output::describe_identity_provider_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeFleetMetadataOutput { /// <p>The time that the fleet was created.</p> pub created_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The time that the fleet was last updated.</p> pub last_updated_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The name of the fleet.</p> pub fleet_name: std::option::Option<std::string::String>, /// <p>The name to display.</p> pub display_name: std::option::Option<std::string::String>, /// <p>The option to optimize for better performance by routing traffic through the closest /// AWS Region to users, which may be outside of your home Region.</p> pub optimize_for_end_user_location: std::option::Option<bool>, /// <p>The identifier used by users to sign in to the Amazon WorkLink app.</p> pub company_code: std::option::Option<std::string::String>, /// <p>The current state of the fleet.</p> pub fleet_status: std::option::Option<crate::model::FleetStatus>, /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl DescribeFleetMetadataOutput { /// <p>The time that the fleet was created.</p> pub fn created_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.created_time.as_ref() } /// <p>The time that the fleet was last updated.</p> pub fn last_updated_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.last_updated_time.as_ref() } /// <p>The name of the fleet.</p> pub fn fleet_name(&self) -> std::option::Option<&str> { self.fleet_name.as_deref() } /// <p>The name to display.</p> pub fn display_name(&self) -> std::option::Option<&str> { self.display_name.as_deref() } /// <p>The option to optimize for better performance by routing traffic through the closest /// AWS Region to users, which may be outside of your home Region.</p> pub fn optimize_for_end_user_location(&self) -> std::option::Option<bool> { self.optimize_for_end_user_location } /// <p>The identifier used by users to sign in to the Amazon WorkLink app.</p> pub fn company_code(&self) -> std::option::Option<&str> { self.company_code.as_deref() } /// <p>The current state of the fleet.</p> pub fn fleet_status(&self) -> std::option::Option<&crate::model::FleetStatus> { self.fleet_status.as_ref() } /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn tags( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.tags.as_ref() } } impl std::fmt::Debug for DescribeFleetMetadataOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeFleetMetadataOutput"); formatter.field("created_time", &self.created_time); formatter.field("last_updated_time", &self.last_updated_time); formatter.field("fleet_name", &self.fleet_name); formatter.field("display_name", &self.display_name); formatter.field( "optimize_for_end_user_location", &self.optimize_for_end_user_location, ); formatter.field("company_code", &self.company_code); formatter.field("fleet_status", &self.fleet_status); formatter.field("tags", &self.tags); formatter.finish() } } /// See [`DescribeFleetMetadataOutput`](crate::output::DescribeFleetMetadataOutput) pub mod describe_fleet_metadata_output { /// A builder for [`DescribeFleetMetadataOutput`](crate::output::DescribeFleetMetadataOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) created_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) last_updated_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) fleet_name: std::option::Option<std::string::String>, pub(crate) display_name: std::option::Option<std::string::String>, pub(crate) optimize_for_end_user_location: std::option::Option<bool>, pub(crate) company_code: std::option::Option<std::string::String>, pub(crate) fleet_status: std::option::Option<crate::model::FleetStatus>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The time that the fleet was created.</p> pub fn created_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.created_time = Some(input); self } /// <p>The time that the fleet was created.</p> pub fn set_created_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.created_time = input; self } /// <p>The time that the fleet was last updated.</p> pub fn last_updated_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.last_updated_time = Some(input); self } /// <p>The time that the fleet was last updated.</p> pub fn set_last_updated_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.last_updated_time = input; self } /// <p>The name of the fleet.</p> pub fn fleet_name(mut self, input: impl Into<std::string::String>) -> Self { self.fleet_name = Some(input.into()); self } /// <p>The name of the fleet.</p> pub fn set_fleet_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.fleet_name = input; self } /// <p>The name to display.</p> pub fn display_name(mut self, input: impl Into<std::string::String>) -> Self { self.display_name = Some(input.into()); self } /// <p>The name to display.</p> pub fn set_display_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.display_name = input; self } /// <p>The option to optimize for better performance by routing traffic through the closest /// AWS Region to users, which may be outside of your home Region.</p> pub fn optimize_for_end_user_location(mut self, input: bool) -> Self { self.optimize_for_end_user_location = Some(input); self } /// <p>The option to optimize for better performance by routing traffic through the closest /// AWS Region to users, which may be outside of your home Region.</p> pub fn set_optimize_for_end_user_location( mut self, input: std::option::Option<bool>, ) -> Self { self.optimize_for_end_user_location = input; self } /// <p>The identifier used by users to sign in to the Amazon WorkLink app.</p> pub fn company_code(mut self, input: impl Into<std::string::String>) -> Self { self.company_code = Some(input.into()); self } /// <p>The identifier used by users to sign in to the Amazon WorkLink app.</p> pub fn set_company_code(mut self, input: std::option::Option<std::string::String>) -> Self { self.company_code = input; self } /// <p>The current state of the fleet.</p> pub fn fleet_status(mut self, input: crate::model::FleetStatus) -> Self { self.fleet_status = Some(input); self } /// <p>The current state of the fleet.</p> pub fn set_fleet_status( mut self, input: std::option::Option<crate::model::FleetStatus>, ) -> Self { self.fleet_status = input; self } /// Adds a key-value pair to `tags`. /// /// To override the contents of this collection use [`set_tags`](Self::set_tags). /// /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } /// <p>The tags attached to the resource. A tag is a key-value pair.</p> pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`DescribeFleetMetadataOutput`](crate::output::DescribeFleetMetadataOutput) pub fn build(self) -> crate::output::DescribeFleetMetadataOutput { crate::output::DescribeFleetMetadataOutput { created_time: self.created_time, last_updated_time: self.last_updated_time, fleet_name: self.fleet_name, display_name: self.display_name, optimize_for_end_user_location: self.optimize_for_end_user_location, company_code: self.company_code, fleet_status: self.fleet_status, tags: self.tags, } } } } impl DescribeFleetMetadataOutput { /// Creates a new builder-style object to manufacture [`DescribeFleetMetadataOutput`](crate::output::DescribeFleetMetadataOutput) pub fn builder() -> crate::output::describe_fleet_metadata_output::Builder { crate::output::describe_fleet_metadata_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeDomainOutput { /// <p>The name of the domain.</p> pub domain_name: std::option::Option<std::string::String>, /// <p>The name to display.</p> pub display_name: std::option::Option<std::string::String>, /// <p>The time that the domain was added.</p> pub created_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The current state for the domain.</p> pub domain_status: std::option::Option<crate::model::DomainStatus>, /// <p>The ARN of an issued ACM certificate that is valid for the domain being associated.</p> pub acm_certificate_arn: std::option::Option<std::string::String>, } impl DescribeDomainOutput { /// <p>The name of the domain.</p> pub fn domain_name(&self) -> std::option::Option<&str> { self.domain_name.as_deref() } /// <p>The name to display.</p> pub fn display_name(&self) -> std::option::Option<&str> { self.display_name.as_deref() } /// <p>The time that the domain was added.</p> pub fn created_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.created_time.as_ref() } /// <p>The current state for the domain.</p> pub fn domain_status(&self) -> std::option::Option<&crate::model::DomainStatus> { self.domain_status.as_ref() } /// <p>The ARN of an issued ACM certificate that is valid for the domain being associated.</p> pub fn acm_certificate_arn(&self) -> std::option::Option<&str> { self.acm_certificate_arn.as_deref() } } impl std::fmt::Debug for DescribeDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeDomainOutput"); formatter.field("domain_name", &self.domain_name); formatter.field("display_name", &self.display_name); formatter.field("created_time", &self.created_time); formatter.field("domain_status", &self.domain_status); formatter.field("acm_certificate_arn", &self.acm_certificate_arn); formatter.finish() } } /// See [`DescribeDomainOutput`](crate::output::DescribeDomainOutput) pub mod describe_domain_output { /// A builder for [`DescribeDomainOutput`](crate::output::DescribeDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) domain_name: std::option::Option<std::string::String>, pub(crate) display_name: std::option::Option<std::string::String>, pub(crate) created_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) domain_status: std::option::Option<crate::model::DomainStatus>, pub(crate) acm_certificate_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The name of the domain.</p> pub fn domain_name(mut self, input: impl Into<std::string::String>) -> Self { self.domain_name = Some(input.into()); self } /// <p>The name of the domain.</p> pub fn set_domain_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.domain_name = input; self } /// <p>The name to display.</p> pub fn display_name(mut self, input: impl Into<std::string::String>) -> Self { self.display_name = Some(input.into()); self } /// <p>The name to display.</p> pub fn set_display_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.display_name = input; self } /// <p>The time that the domain was added.</p> pub fn created_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.created_time = Some(input); self } /// <p>The time that the domain was added.</p> pub fn set_created_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.created_time = input; self } /// <p>The current state for the domain.</p> pub fn domain_status(mut self, input: crate::model::DomainStatus) -> Self { self.domain_status = Some(input); self } /// <p>The current state for the domain.</p> pub fn set_domain_status( mut self, input: std::option::Option<crate::model::DomainStatus>, ) -> Self { self.domain_status = input; self } /// <p>The ARN of an issued ACM certificate that is valid for the domain being associated.</p> pub fn acm_certificate_arn(mut self, input: impl Into<std::string::String>) -> Self { self.acm_certificate_arn = Some(input.into()); self } /// <p>The ARN of an issued ACM certificate that is valid for the domain being associated.</p> pub fn set_acm_certificate_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.acm_certificate_arn = input; self } /// Consumes the builder and constructs a [`DescribeDomainOutput`](crate::output::DescribeDomainOutput) pub fn build(self) -> crate::output::DescribeDomainOutput { crate::output::DescribeDomainOutput { domain_name: self.domain_name, display_name: self.display_name, created_time: self.created_time, domain_status: self.domain_status, acm_certificate_arn: self.acm_certificate_arn, } } } } impl DescribeDomainOutput { /// Creates a new builder-style object to manufacture [`DescribeDomainOutput`](crate::output::DescribeDomainOutput) pub fn builder() -> crate::output::describe_domain_output::Builder { crate::output::describe_domain_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeDevicePolicyConfigurationOutput { /// <p>The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates.</p> pub device_ca_certificate: std::option::Option<std::string::String>, } impl DescribeDevicePolicyConfigurationOutput { /// <p>The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates.</p> pub fn device_ca_certificate(&self) -> std::option::Option<&str> { self.device_ca_certificate.as_deref() } } impl std::fmt::Debug for DescribeDevicePolicyConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeDevicePolicyConfigurationOutput"); formatter.field("device_ca_certificate", &self.device_ca_certificate); formatter.finish() } } /// See [`DescribeDevicePolicyConfigurationOutput`](crate::output::DescribeDevicePolicyConfigurationOutput) pub mod describe_device_policy_configuration_output { /// A builder for [`DescribeDevicePolicyConfigurationOutput`](crate::output::DescribeDevicePolicyConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) device_ca_certificate: std::option::Option<std::string::String>, } impl Builder { /// <p>The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates.</p> pub fn device_ca_certificate(mut self, input: impl Into<std::string::String>) -> Self { self.device_ca_certificate = Some(input.into()); self } /// <p>The certificate chain, including intermediate certificates and the root certificate authority certificate used to issue device certificates.</p> pub fn set_device_ca_certificate( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.device_ca_certificate = input; self } /// Consumes the builder and constructs a [`DescribeDevicePolicyConfigurationOutput`](crate::output::DescribeDevicePolicyConfigurationOutput) pub fn build(self) -> crate::output::DescribeDevicePolicyConfigurationOutput { crate::output::DescribeDevicePolicyConfigurationOutput { device_ca_certificate: self.device_ca_certificate, } } } } impl DescribeDevicePolicyConfigurationOutput { /// Creates a new builder-style object to manufacture [`DescribeDevicePolicyConfigurationOutput`](crate::output::DescribeDevicePolicyConfigurationOutput) pub fn builder() -> crate::output::describe_device_policy_configuration_output::Builder { crate::output::describe_device_policy_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeDeviceOutput { /// <p>The current state of the device.</p> pub status: std::option::Option<crate::model::DeviceStatus>, /// <p>The model of the device.</p> pub model: std::option::Option<std::string::String>, /// <p>The manufacturer of the device.</p> pub manufacturer: std::option::Option<std::string::String>, /// <p>The operating system of the device.</p> pub operating_system: std::option::Option<std::string::String>, /// <p>The operating system version of the device.</p> pub operating_system_version: std::option::Option<std::string::String>, /// <p>The operating system patch level of the device.</p> pub patch_level: std::option::Option<std::string::String>, /// <p>The date that the device first signed in to Amazon WorkLink.</p> pub first_accessed_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The date that the device last accessed Amazon WorkLink.</p> pub last_accessed_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>The user name associated with the device.</p> pub username: std::option::Option<std::string::String>, } impl DescribeDeviceOutput { /// <p>The current state of the device.</p> pub fn status(&self) -> std::option::Option<&crate::model::DeviceStatus> { self.status.as_ref() } /// <p>The model of the device.</p> pub fn model(&self) -> std::option::Option<&str> { self.model.as_deref() } /// <p>The manufacturer of the device.</p> pub fn manufacturer(&self) -> std::option::Option<&str> { self.manufacturer.as_deref() } /// <p>The operating system of the device.</p> pub fn operating_system(&self) -> std::option::Option<&str> { self.operating_system.as_deref() } /// <p>The operating system version of the device.</p> pub fn operating_system_version(&self) -> std::option::Option<&str> { self.operating_system_version.as_deref() } /// <p>The operating system patch level of the device.</p> pub fn patch_level(&self) -> std::option::Option<&str> { self.patch_level.as_deref() } /// <p>The date that the device first signed in to Amazon WorkLink.</p> pub fn first_accessed_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.first_accessed_time.as_ref() } /// <p>The date that the device last accessed Amazon WorkLink.</p> pub fn last_accessed_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.last_accessed_time.as_ref() } /// <p>The user name associated with the device.</p> pub fn username(&self) -> std::option::Option<&str> { self.username.as_deref() } } impl std::fmt::Debug for DescribeDeviceOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeDeviceOutput"); formatter.field("status", &self.status); formatter.field("model", &self.model); formatter.field("manufacturer", &self.manufacturer); formatter.field("operating_system", &self.operating_system); formatter.field("operating_system_version", &self.operating_system_version); formatter.field("patch_level", &self.patch_level); formatter.field("first_accessed_time", &self.first_accessed_time); formatter.field("last_accessed_time", &self.last_accessed_time); formatter.field("username", &self.username); formatter.finish() } } /// See [`DescribeDeviceOutput`](crate::output::DescribeDeviceOutput) pub mod describe_device_output { /// A builder for [`DescribeDeviceOutput`](crate::output::DescribeDeviceOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) status: std::option::Option<crate::model::DeviceStatus>, pub(crate) model: std::option::Option<std::string::String>, pub(crate) manufacturer: std::option::Option<std::string::String>, pub(crate) operating_system: std::option::Option<std::string::String>, pub(crate) operating_system_version: std::option::Option<std::string::String>, pub(crate) patch_level: std::option::Option<std::string::String>, pub(crate) first_accessed_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) last_accessed_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) username: std::option::Option<std::string::String>, } impl Builder { /// <p>The current state of the device.</p> pub fn status(mut self, input: crate::model::DeviceStatus) -> Self { self.status = Some(input); self } /// <p>The current state of the device.</p> pub fn set_status( mut self, input: std::option::Option<crate::model::DeviceStatus>, ) -> Self { self.status = input; self } /// <p>The model of the device.</p> pub fn model(mut self, input: impl Into<std::string::String>) -> Self { self.model = Some(input.into()); self } /// <p>The model of the device.</p> pub fn set_model(mut self, input: std::option::Option<std::string::String>) -> Self { self.model = input; self } /// <p>The manufacturer of the device.</p> pub fn manufacturer(mut self, input: impl Into<std::string::String>) -> Self { self.manufacturer = Some(input.into()); self } /// <p>The manufacturer of the device.</p> pub fn set_manufacturer(mut self, input: std::option::Option<std::string::String>) -> Self { self.manufacturer = input; self } /// <p>The operating system of the device.</p> pub fn operating_system(mut self, input: impl Into<std::string::String>) -> Self { self.operating_system = Some(input.into()); self } /// <p>The operating system of the device.</p> pub fn set_operating_system( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.operating_system = input; self } /// <p>The operating system version of the device.</p> pub fn operating_system_version(mut self, input: impl Into<std::string::String>) -> Self { self.operating_system_version = Some(input.into()); self } /// <p>The operating system version of the device.</p> pub fn set_operating_system_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.operating_system_version = input; self } /// <p>The operating system patch level of the device.</p> pub fn patch_level(mut self, input: impl Into<std::string::String>) -> Self { self.patch_level = Some(input.into()); self } /// <p>The operating system patch level of the device.</p> pub fn set_patch_level(mut self, input: std::option::Option<std::string::String>) -> Self { self.patch_level = input; self } /// <p>The date that the device first signed in to Amazon WorkLink.</p> pub fn first_accessed_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.first_accessed_time = Some(input); self } /// <p>The date that the device first signed in to Amazon WorkLink.</p> pub fn set_first_accessed_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.first_accessed_time = input; self } /// <p>The date that the device last accessed Amazon WorkLink.</p> pub fn last_accessed_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.last_accessed_time = Some(input); self } /// <p>The date that the device last accessed Amazon WorkLink.</p> pub fn set_last_accessed_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.last_accessed_time = input; self } /// <p>The user name associated with the device.</p> pub fn username(mut self, input: impl Into<std::string::String>) -> Self { self.username = Some(input.into()); self } /// <p>The user name associated with the device.</p> pub fn set_username(mut self, input: std::option::Option<std::string::String>) -> Self { self.username = input; self } /// Consumes the builder and constructs a [`DescribeDeviceOutput`](crate::output::DescribeDeviceOutput) pub fn build(self) -> crate::output::DescribeDeviceOutput { crate::output::DescribeDeviceOutput { status: self.status, model: self.model, manufacturer: self.manufacturer, operating_system: self.operating_system, operating_system_version: self.operating_system_version, patch_level: self.patch_level, first_accessed_time: self.first_accessed_time, last_accessed_time: self.last_accessed_time, username: self.username, } } } } impl DescribeDeviceOutput { /// Creates a new builder-style object to manufacture [`DescribeDeviceOutput`](crate::output::DescribeDeviceOutput) pub fn builder() -> crate::output::describe_device_output::Builder { crate::output::describe_device_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeCompanyNetworkConfigurationOutput { /// <p>The VPC with connectivity to associated websites.</p> pub vpc_id: std::option::Option<std::string::String>, /// <p>The subnets used for X-ENI connections from Amazon WorkLink rendering containers.</p> pub subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The security groups associated with access to the provided subnets.</p> pub security_group_ids: std::option::Option<std::vec::Vec<std::string::String>>, } impl DescribeCompanyNetworkConfigurationOutput { /// <p>The VPC with connectivity to associated websites.</p> pub fn vpc_id(&self) -> std::option::Option<&str> { self.vpc_id.as_deref() } /// <p>The subnets used for X-ENI connections from Amazon WorkLink rendering containers.</p> pub fn subnet_ids(&self) -> std::option::Option<&[std::string::String]> { self.subnet_ids.as_deref() } /// <p>The security groups associated with access to the provided subnets.</p> pub fn security_group_ids(&self) -> std::option::Option<&[std::string::String]> { self.security_group_ids.as_deref() } } impl std::fmt::Debug for DescribeCompanyNetworkConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeCompanyNetworkConfigurationOutput"); formatter.field("vpc_id", &self.vpc_id); formatter.field("subnet_ids", &self.subnet_ids); formatter.field("security_group_ids", &self.security_group_ids); formatter.finish() } } /// See [`DescribeCompanyNetworkConfigurationOutput`](crate::output::DescribeCompanyNetworkConfigurationOutput) pub mod describe_company_network_configuration_output { /// A builder for [`DescribeCompanyNetworkConfigurationOutput`](crate::output::DescribeCompanyNetworkConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) vpc_id: std::option::Option<std::string::String>, pub(crate) subnet_ids: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) security_group_ids: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The VPC with connectivity to associated websites.</p> pub fn vpc_id(mut self, input: impl Into<std::string::String>) -> Self { self.vpc_id = Some(input.into()); self } /// <p>The VPC with connectivity to associated websites.</p> pub fn set_vpc_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.vpc_id = input; self } /// Appends an item to `subnet_ids`. /// /// To override the contents of this collection use [`set_subnet_ids`](Self::set_subnet_ids). /// /// <p>The subnets used for X-ENI connections from Amazon WorkLink rendering containers.</p> pub fn subnet_ids(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.subnet_ids.unwrap_or_default(); v.push(input.into()); self.subnet_ids = Some(v); self } /// <p>The subnets used for X-ENI connections from Amazon WorkLink rendering containers.</p> pub fn set_subnet_ids( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.subnet_ids = input; self } /// Appends an item to `security_group_ids`. /// /// To override the contents of this collection use [`set_security_group_ids`](Self::set_security_group_ids). /// /// <p>The security groups associated with access to the provided subnets.</p> pub fn security_group_ids(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.security_group_ids.unwrap_or_default(); v.push(input.into()); self.security_group_ids = Some(v); self } /// <p>The security groups associated with access to the provided subnets.</p> pub fn set_security_group_ids( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.security_group_ids = input; self } /// Consumes the builder and constructs a [`DescribeCompanyNetworkConfigurationOutput`](crate::output::DescribeCompanyNetworkConfigurationOutput) pub fn build(self) -> crate::output::DescribeCompanyNetworkConfigurationOutput { crate::output::DescribeCompanyNetworkConfigurationOutput { vpc_id: self.vpc_id, subnet_ids: self.subnet_ids, security_group_ids: self.security_group_ids, } } } } impl DescribeCompanyNetworkConfigurationOutput { /// Creates a new builder-style object to manufacture [`DescribeCompanyNetworkConfigurationOutput`](crate::output::DescribeCompanyNetworkConfigurationOutput) pub fn builder() -> crate::output::describe_company_network_configuration_output::Builder { crate::output::describe_company_network_configuration_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeAuditStreamConfigurationOutput { /// <p>The ARN of the Amazon Kinesis data stream that will receive the audit events.</p> pub audit_stream_arn: std::option::Option<std::string::String>, } impl DescribeAuditStreamConfigurationOutput { /// <p>The ARN of the Amazon Kinesis data stream that will receive the audit events.</p> pub fn audit_stream_arn(&self) -> std::option::Option<&str> { self.audit_stream_arn.as_deref() } } impl std::fmt::Debug for DescribeAuditStreamConfigurationOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeAuditStreamConfigurationOutput"); formatter.field("audit_stream_arn", &self.audit_stream_arn); formatter.finish() } } /// See [`DescribeAuditStreamConfigurationOutput`](crate::output::DescribeAuditStreamConfigurationOutput) pub mod describe_audit_stream_configuration_output { /// A builder for [`DescribeAuditStreamConfigurationOutput`](crate::output::DescribeAuditStreamConfigurationOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) audit_stream_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The ARN of the Amazon Kinesis data stream that will receive the audit events.</p> pub fn audit_stream_arn(mut self, input: impl Into<std::string::String>) -> Self { self.audit_stream_arn = Some(input.into()); self } /// <p>The ARN of the Amazon Kinesis data stream that will receive the audit events.</p> pub fn set_audit_stream_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.audit_stream_arn = input; self } /// Consumes the builder and constructs a [`DescribeAuditStreamConfigurationOutput`](crate::output::DescribeAuditStreamConfigurationOutput) pub fn build(self) -> crate::output::DescribeAuditStreamConfigurationOutput { crate::output::DescribeAuditStreamConfigurationOutput { audit_stream_arn: self.audit_stream_arn, } } } } impl DescribeAuditStreamConfigurationOutput { /// Creates a new builder-style object to manufacture [`DescribeAuditStreamConfigurationOutput`](crate::output::DescribeAuditStreamConfigurationOutput) pub fn builder() -> crate::output::describe_audit_stream_configuration_output::Builder { crate::output::describe_audit_stream_configuration_output::Builder::default()
#[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteFleetOutput {} impl std::fmt::Debug for DeleteFleetOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteFleetOutput"); formatter.finish() } } /// See [`DeleteFleetOutput`](crate::output::DeleteFleetOutput) pub mod delete_fleet_output { /// A builder for [`DeleteFleetOutput`](crate::output::DeleteFleetOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`DeleteFleetOutput`](crate::output::DeleteFleetOutput) pub fn build(self) -> crate::output::DeleteFleetOutput { crate::output::DeleteFleetOutput {} } } } impl DeleteFleetOutput { /// Creates a new builder-style object to manufacture [`DeleteFleetOutput`](crate::output::DeleteFleetOutput) pub fn builder() -> crate::output::delete_fleet_output::Builder { crate::output::delete_fleet_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateFleetOutput { /// <p>The Amazon Resource Name (ARN) of the fleet.</p> pub fleet_arn: std::option::Option<std::string::String>, } impl CreateFleetOutput { /// <p>The Amazon Resource Name (ARN) of the fleet.</p> pub fn fleet_arn(&self) -> std::option::Option<&str> { self.fleet_arn.as_deref() } } impl std::fmt::Debug for CreateFleetOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateFleetOutput"); formatter.field("fleet_arn", &self.fleet_arn); formatter.finish() } } /// See [`CreateFleetOutput`](crate::output::CreateFleetOutput) pub mod create_fleet_output { /// A builder for [`CreateFleetOutput`](crate::output::CreateFleetOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) fleet_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The Amazon Resource Name (ARN) of the fleet.</p> pub fn fleet_arn(mut self, input: impl Into<std::string::String>) -> Self { self.fleet_arn = Some(input.into()); self } /// <p>The Amazon Resource Name (ARN) of the fleet.</p> pub fn set_fleet_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.fleet_arn = input; self } /// Consumes the builder and constructs a [`CreateFleetOutput`](crate::output::CreateFleetOutput) pub fn build(self) -> crate::output::CreateFleetOutput { crate::output::CreateFleetOutput { fleet_arn: self.fleet_arn, } } } } impl CreateFleetOutput { /// Creates a new builder-style object to manufacture [`CreateFleetOutput`](crate::output::CreateFleetOutput) pub fn builder() -> crate::output::create_fleet_output::Builder { crate::output::create_fleet_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AssociateWebsiteCertificateAuthorityOutput { /// <p>A unique identifier for the CA.</p> pub website_ca_id: std::option::Option<std::string::String>, } impl AssociateWebsiteCertificateAuthorityOutput { /// <p>A unique identifier for the CA.</p> pub fn website_ca_id(&self) -> std::option::Option<&str> { self.website_ca_id.as_deref() } } impl std::fmt::Debug for AssociateWebsiteCertificateAuthorityOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AssociateWebsiteCertificateAuthorityOutput"); formatter.field("website_ca_id", &self.website_ca_id); formatter.finish() } } /// See [`AssociateWebsiteCertificateAuthorityOutput`](crate::output::AssociateWebsiteCertificateAuthorityOutput) pub mod associate_website_certificate_authority_output { /// A builder for [`AssociateWebsiteCertificateAuthorityOutput`](crate::output::AssociateWebsiteCertificateAuthorityOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) website_ca_id: std::option::Option<std::string::String>, } impl Builder { /// <p>A unique identifier for the CA.</p> pub fn website_ca_id(mut self, input: impl Into<std::string::String>) -> Self { self.website_ca_id = Some(input.into()); self } /// <p>A unique identifier for the CA.</p> pub fn set_website_ca_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.website_ca_id = input; self } /// Consumes the builder and constructs a [`AssociateWebsiteCertificateAuthorityOutput`](crate::output::AssociateWebsiteCertificateAuthorityOutput) pub fn build(self) -> crate::output::AssociateWebsiteCertificateAuthorityOutput { crate::output::AssociateWebsiteCertificateAuthorityOutput { website_ca_id: self.website_ca_id, } } } } impl AssociateWebsiteCertificateAuthorityOutput { /// Creates a new builder-style object to manufacture [`AssociateWebsiteCertificateAuthorityOutput`](crate::output::AssociateWebsiteCertificateAuthorityOutput) pub fn builder() -> crate::output::associate_website_certificate_authority_output::Builder { crate::output::associate_website_certificate_authority_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AssociateWebsiteAuthorizationProviderOutput { /// <p>A unique identifier for the authorization provider.</p> pub authorization_provider_id: std::option::Option<std::string::String>, } impl AssociateWebsiteAuthorizationProviderOutput { /// <p>A unique identifier for the authorization provider.</p> pub fn authorization_provider_id(&self) -> std::option::Option<&str> { self.authorization_provider_id.as_deref() } } impl std::fmt::Debug for AssociateWebsiteAuthorizationProviderOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AssociateWebsiteAuthorizationProviderOutput"); formatter.field("authorization_provider_id", &self.authorization_provider_id); formatter.finish() } } /// See [`AssociateWebsiteAuthorizationProviderOutput`](crate::output::AssociateWebsiteAuthorizationProviderOutput) pub mod associate_website_authorization_provider_output { /// A builder for [`AssociateWebsiteAuthorizationProviderOutput`](crate::output::AssociateWebsiteAuthorizationProviderOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) authorization_provider_id: std::option::Option<std::string::String>, } impl Builder { /// <p>A unique identifier for the authorization provider.</p> pub fn authorization_provider_id(mut self, input: impl Into<std::string::String>) -> Self { self.authorization_provider_id = Some(input.into()); self } /// <p>A unique identifier for the authorization provider.</p> pub fn set_authorization_provider_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.authorization_provider_id = input; self } /// Consumes the builder and constructs a [`AssociateWebsiteAuthorizationProviderOutput`](crate::output::AssociateWebsiteAuthorizationProviderOutput) pub fn build(self) -> crate::output::AssociateWebsiteAuthorizationProviderOutput { crate::output::AssociateWebsiteAuthorizationProviderOutput { authorization_provider_id: self.authorization_provider_id, } } } } impl AssociateWebsiteAuthorizationProviderOutput { /// Creates a new builder-style object to manufacture [`AssociateWebsiteAuthorizationProviderOutput`](crate::output::AssociateWebsiteAuthorizationProviderOutput) pub fn builder() -> crate::output::associate_website_authorization_provider_output::Builder { crate::output::associate_website_authorization_provider_output::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AssociateDomainOutput {} impl std::fmt::Debug for AssociateDomainOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("AssociateDomainOutput"); formatter.finish() } } /// See [`AssociateDomainOutput`](crate::output::AssociateDomainOutput) pub mod associate_domain_output { /// A builder for [`AssociateDomainOutput`](crate::output::AssociateDomainOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder {} impl Builder { /// Consumes the builder and constructs a [`AssociateDomainOutput`](crate::output::AssociateDomainOutput) pub fn build(self) -> crate::output::AssociateDomainOutput { crate::output::AssociateDomainOutput {} } } } impl AssociateDomainOutput { /// Creates a new builder-style object to manufacture [`AssociateDomainOutput`](crate::output::AssociateDomainOutput) pub fn builder() -> crate::output::associate_domain_output::Builder { crate::output::associate_domain_output::Builder::default() } }
} }
test_compose.py
# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np import pytest import mindspore.common.dtype as mstype import mindspore.dataset as ds import mindspore.dataset.transforms.c_transforms as c_transforms import mindspore.dataset.transforms.py_transforms as py_transforms import mindspore.dataset.vision.c_transforms as c_vision import mindspore.dataset.vision.py_transforms as py_vision from util import visualize_list, save_and_check_md5, config_get_set_seed, config_get_set_num_parallel_workers GENERATE_GOLDEN = False def test_compose(): """ Test C++ and Python Compose Op """ ds.config.set_seed(0) def test_config(arr, op_list):
try: data = ds.NumpySlicesDataset(arr, column_names="col", shuffle=False) data = data.map(input_columns=["col"], operations=op_list) res = [] for i in data.create_dict_iterator(output_numpy=True): res.append(i["col"].tolist()) return res except (TypeError, ValueError) as e: return str(e) # Test simple compose with only 1 op, this would generate a warning assert test_config([[1, 0], [3, 4]], c_transforms.Compose([c_transforms.Fill(2)])) == [[2, 2], [2, 2]] # Test 1 column -> 2 columns -> 1 -> 2 -> 1 assert test_config([[1, 0]], c_transforms.Compose( [c_transforms.Duplicate(), c_transforms.Concatenate(), c_transforms.Duplicate(), c_transforms.Concatenate()])) \ == [[1, 0] * 4] # Test one Python transform followed by a C++ transform. Type after OneHot is a float (mixed use-case) assert test_config([1, 0], c_transforms.Compose([py_transforms.OneHotOp(2), c_transforms.TypeCast(mstype.int32)])) \ == [[[0, 1]], [[1, 0]]] # Test exceptions. with pytest.raises(TypeError) as error_info: c_transforms.Compose([1, c_transforms.TypeCast(mstype.int32)]) assert "op_list[0] is neither a c_transform op (TensorOperation) nor a callable pyfunc." in str(error_info.value) # Test empty op list with pytest.raises(ValueError) as error_info: test_config([1, 0], c_transforms.Compose([])) assert "op_list can not be empty." in str(error_info.value) # Test Python compose op assert test_config([1, 0], py_transforms.Compose([py_transforms.OneHotOp(2)])) == [[[0, 1]], [[1, 0]]] assert test_config([1, 0], py_transforms.Compose([py_transforms.OneHotOp(2), (lambda x: x + x)])) == [[[0, 2]], [[2, 0]]] # Test nested Python compose op assert test_config([1, 0], py_transforms.Compose([py_transforms.Compose([py_transforms.OneHotOp(2)]), (lambda x: x + x)])) \ == [[[0, 2]], [[2, 0]]] # Test passing a list of Python ops without Compose wrapper assert test_config([1, 0], [py_transforms.Compose([py_transforms.OneHotOp(2)]), (lambda x: x + x)]) \ == [[[0, 2]], [[2, 0]]] assert test_config([1, 0], [py_transforms.OneHotOp(2), (lambda x: x + x)]) == [[[0, 2]], [[2, 0]]] # Test a non callable function with pytest.raises(ValueError) as error_info: py_transforms.Compose([1]) assert "transforms[0] is not callable." in str(error_info.value) # Test empty Python op list with pytest.raises(ValueError) as error_info: test_config([1, 0], py_transforms.Compose([])) assert "transforms list is empty." in str(error_info.value) # Pass in extra brackets with pytest.raises(TypeError) as error_info: py_transforms.Compose([(lambda x: x + x)])() assert "Compose was called without an image. Fix invocation (avoid it being invoked as Compose([...])())." in str( error_info.value) def test_lambdas(): """ Test Multi Column Python Compose Op """ ds.config.set_seed(0) def test_config(arr, input_columns, output_cols, op_list): data = ds.NumpySlicesDataset(arr, column_names=input_columns, shuffle=False) data = data.map(operations=op_list, input_columns=input_columns, output_columns=output_cols, column_order=output_cols) res = [] for i in data.create_dict_iterator(output_numpy=True): for col_name in output_cols: res.append(i[col_name].tolist()) return res arr = ([[1]], [[3]]) assert test_config(arr, ["col0", "col1"], ["a"], py_transforms.Compose([(lambda x, y: x)])) == [[1]] assert test_config(arr, ["col0", "col1"], ["a"], py_transforms.Compose([lambda x, y: x, lambda x: x])) == [[1]] assert test_config(arr, ["col0", "col1"], ["a", "b"], py_transforms.Compose([lambda x, y: x, lambda x: (x, x * 2)])) == \ [[1], [2]] assert test_config(arr, ["col0", "col1"], ["a", "b"], [lambda x, y: (x, x + y), lambda x, y: (x, y * 2)]) == [[1], [8]] def test_c_py_compose_transforms_module(): """ Test combining Python and C++ transforms """ ds.config.set_seed(0) def test_config(arr, input_columns, output_cols, op_list): data = ds.NumpySlicesDataset(arr, column_names=input_columns, shuffle=False) data = data.map(operations=op_list, input_columns=input_columns, output_columns=output_cols, column_order=output_cols) res = [] for i in data.create_dict_iterator(output_numpy=True): for col_name in output_cols: res.append(i[col_name].tolist()) return res arr = [1, 0] assert test_config(arr, ["cols"], ["cols"], [py_transforms.OneHotOp(2), c_transforms.Mask(c_transforms.Relational.EQ, 1)]) == \ [[[False, True]], [[True, False]]] assert test_config(arr, ["cols"], ["cols"], [py_transforms.OneHotOp(2), (lambda x: x + x), c_transforms.Fill(1)]) \ == [[[1, 1]], [[1, 1]]] assert test_config(arr, ["cols"], ["cols"], [py_transforms.OneHotOp(2), (lambda x: x + x), c_transforms.Fill(1), (lambda x: x + x)]) \ == [[[2, 2]], [[2, 2]]] assert test_config([[1, 3]], ["cols"], ["cols"], [c_transforms.PadEnd([3], -1), (lambda x: x + x)]) \ == [[2, 6, -2]] arr = ([[1]], [[3]]) assert test_config(arr, ["col0", "col1"], ["a"], [(lambda x, y: x + y), c_transforms.PadEnd([2], -1)]) == [[4, -1]] def test_c_py_compose_vision_module(plot=False, run_golden=True): """ Test combining Python and C++ vision transforms """ original_seed = config_get_set_seed(10) original_num_parallel_workers = config_get_set_num_parallel_workers(1) def test_config(plot, file_name, op_list): data_dir = "../data/dataset/testImageNetData/train/" data1 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False) data1 = data1.map(operations=op_list, input_columns=["image"]) data2 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False) data2 = data2.map(operations=c_vision.Decode(), input_columns=["image"]) original_images = [] transformed_images = [] for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True): transformed_images.append(item["image"]) for item in data2.create_dict_iterator(num_epochs=1, output_numpy=True): original_images.append(item["image"]) if run_golden: # Compare with expected md5 from images save_and_check_md5(data1, file_name, generate_golden=GENERATE_GOLDEN) if plot: visualize_list(original_images, transformed_images) test_config(op_list=[c_vision.Decode(), py_vision.ToPIL(), py_vision.Resize((224, 224)), np.array], plot=plot, file_name="compose_c_py_1.npz") test_config(op_list=[c_vision.Decode(), c_vision.Resize((224, 244)), py_vision.ToPIL(), np.array, c_vision.Resize((24, 24))], plot=plot, file_name="compose_c_py_2.npz") test_config(op_list=[py_vision.Decode(), py_vision.Resize((224, 224)), np.array, c_vision.RandomColor()], plot=plot, file_name="compose_c_py_3.npz") # Restore configuration ds.config.set_seed(original_seed) ds.config.set_num_parallel_workers((original_num_parallel_workers)) def test_py_transforms_with_c_vision(): """ These examples will fail, as py_transforms.Random(Apply/Choice/Order) expect callable functions """ ds.config.set_seed(0) def test_config(op_list): data_dir = "../data/dataset/testImageNetData/train/" data = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False) data = data.map(operations=op_list) res = [] for i in data.create_dict_iterator(output_numpy=True): for col_name in output_cols: res.append(i[col_name].tolist()) return res with pytest.raises(ValueError) as error_info: test_config(py_transforms.RandomApply([c_vision.RandomResizedCrop(200)])) assert "transforms[0] is not callable." in str(error_info.value) with pytest.raises(ValueError) as error_info: test_config(py_transforms.RandomChoice([c_vision.RandomResizedCrop(200)])) assert "transforms[0] is not callable." in str(error_info.value) with pytest.raises(ValueError) as error_info: test_config(py_transforms.RandomOrder([np.array, c_vision.RandomResizedCrop(200)])) assert "transforms[1] is not callable." in str(error_info.value) with pytest.raises(RuntimeError) as error_info: test_config([py_transforms.OneHotOp(20, 0.1)]) assert "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()" in str( error_info.value) def test_py_vision_with_c_transforms(): """ Test combining Python vision operations with C++ transforms operations """ ds.config.set_seed(0) def test_config(op_list): data_dir = "../data/dataset/testImageNetData/train/" data1 = ds.ImageFolderDataset(dataset_dir=data_dir, shuffle=False) data1 = data1.map(operations=op_list, input_columns=["image"]) transformed_images = [] for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True): transformed_images.append(item["image"]) return transformed_images # Test with Mask Op output_arr = test_config([py_vision.Decode(), py_vision.CenterCrop((2)), np.array, c_transforms.Mask(c_transforms.Relational.GE, 100)]) exp_arr = [np.array([[[True, False, False], [True, False, False]], [[True, False, False], [True, False, False]]]), np.array([[[True, False, False], [True, False, False]], [[True, False, False], [True, False, False]]])] for exp_a, output in zip(exp_arr, output_arr): np.testing.assert_array_equal(exp_a, output) # Test with Fill Op output_arr = test_config([py_vision.Decode(), py_vision.CenterCrop((4)), np.array, c_transforms.Fill(10)]) exp_arr = [np.ones((4, 4, 3)) * 10] * 2 for exp_a, output in zip(exp_arr, output_arr): np.testing.assert_array_equal(exp_a, output) # Test with Concatenate Op, which will raise an error since ConcatenateOp only supports rank 1 tensors. with pytest.raises(RuntimeError) as error_info: test_config([py_vision.Decode(), py_vision.CenterCrop((2)), np.array, c_transforms.Concatenate(0)]) assert "Only 1D tensors supported" in str(error_info.value) def test_compose_with_custom_function(): """ Test Python Compose with custom function """ def custom_function(x): return (x, x * x) # First dataset op_list = [ lambda x: x * 3, custom_function, # convert two column output to one lambda *images: np.stack(images) ] data = ds.NumpySlicesDataset([[1, 2]], column_names=["col0"], shuffle=False) data = data.map(input_columns=["col0"], operations=op_list) # res = [] for i in data.create_dict_iterator(output_numpy=True): res.append(i["col0"].tolist()) assert res == [[[3, 6], [9, 36]]] if __name__ == "__main__": test_compose() test_lambdas() test_c_py_compose_transforms_module() test_c_py_compose_vision_module(plot=True) test_py_transforms_with_c_vision() test_py_vision_with_c_transforms() test_compose_with_custom_function()
p2p_segwit.py
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Copyright (c) 2017-2018 The AmlBitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test segwit transactions and blocks on P2P network.""" from test_framework.mininode import * from test_framework.test_framework import AmlBitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment, get_witness_script, WITNESS_COMMITMENT_HEADER from test_framework.key import CECKey, CPubKey import time import random from binascii import hexlify # The versionbit bit used to signal activation of SegWit VB_WITNESS_BIT = 1 VB_PERIOD = 144 VB_TOP_BITS = 0x20000000 MAX_SIGOP_COST = 80000 # Calculate the virtual size of a witness block: # (base + witness/4) def get_virtual_size(witness_block): base_size = len(witness_block.serialize()) total_size = len(witness_block.serialize(with_witness=True)) # the "+3" is so we round up vsize = int((3*base_size + total_size + 3)/4) return vsize class TestNode(NodeConnCB): def __init__(self): super().__init__() self.getdataset = set() def on_getdata(self, conn, message): for inv in message.inv: self.getdataset.add(inv.hash) def announce_tx_and_wait_for_getdata(self, tx, timeout=60): with mininode_lock: self.last_message.pop("getdata", None) self.send_message(msg_inv(inv=[CInv(1, tx.sha256)])) self.wait_for_getdata(timeout) def announce_block_and_wait_for_getdata(self, block, use_header, timeout=60): with mininode_lock: self.last_message.pop("getdata", None) self.last_message.pop("getheaders", None) msg = msg_headers() msg.headers = [ CBlockHeader(block) ] if use_header: self.send_message(msg) else: self.send_message(msg_inv(inv=[CInv(2, block.sha256)])) self.wait_for_getheaders() self.send_message(msg) self.wait_for_getdata() def request_block(self, blockhash, inv_type, timeout=60): with mininode_lock: self.last_message.pop("block", None) self.send_message(msg_getdata(inv=[CInv(inv_type, blockhash)])) self.wait_for_block(blockhash, timeout) return self.last_message["block"].block def test_transaction_acceptance(self, tx, with_witness, accepted, reason=None): tx_message = msg_tx(tx) if with_witness: tx_message = msg_witness_tx(tx) self.send_message(tx_message) self.sync_with_ping() assert_equal(tx.hash in self.connection.rpc.getrawmempool(), accepted) if (reason != None and not accepted): # Check the rejection reason as well. with mininode_lock: assert_equal(self.last_message["reject"].reason, reason) # Test whether a witness block had the correct effect on the tip def test_witness_block(self, block, accepted, with_witness=True): if with_witness: self.send_message(msg_witness_block(block)) else: self.send_message(msg_block(block)) self.sync_with_ping() assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted) # Used to keep track of anyone-can-spend outputs that we can use in the tests class UTXO(): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue # Helper for getting the script associated with a P2PKH def GetP2PKHScript(pubkeyhash): return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)]) # Add signature for a P2PK witness program. def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key): tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value) signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1') txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script] txTo.rehash() class SegWitTest(AmlBitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [["-whitelist=127.0.0.1"], ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0"], ["-whitelist=127.0.0.1"]] def setup_network(self): self.setup_nodes() connect_nodes(self.nodes[0], 1) connect_nodes(self.nodes[0], 2) self.sync_all() ''' Helpers ''' # Build a block on top of node0's tip. def build_next_block(self, nVersion=4): tip = self.nodes[0].getbestblockhash() height = self.nodes[0].getblockcount() + 1 block_time = self.nodes[0].getblockheader(tip)["mediantime"] + 1 block = create_block(int(tip, 16), create_coinbase(height), block_time) block.nVersion = nVersion block.rehash() return block # Adds list of transactions to block, adds witness commitment, then solves. def update_witness_block_with_transactions(self, block, tx_list, nonce=0): block.vtx.extend(tx_list) add_witness_commitment(block, nonce) block.solve() return ''' Individual tests ''' def test_witness_services(self): self.log.info("Verifying NODE_WITNESS service bit") assert((self.test_node.connection.nServices & NODE_WITNESS) != 0) # See if sending a regular transaction works, and create a utxo # to use in later tests. def test_non_witness_transaction(self): # Mine a block with an anyone-can-spend coinbase, # let it mature, then try to spend it. self.log.info("Testing non-witness transaction") block = self.build_next_block(nVersion=1) block.solve() self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() # make sure the block was processed txid = block.vtx[0].sha256 self.nodes[0].generate(99) # let the block mature # Create a transaction that spends the coinbase tx = CTransaction() tx.vin.append(CTxIn(COutPoint(txid, 0), b"")) tx.vout.append(CTxOut(49*100000000, CScript([OP_TRUE]))) tx.calc_sha256() # Check that serializing it with or without witness is the same # This is a sanity check of our testing framework. assert_equal(msg_tx(tx).serialize(), msg_witness_tx(tx).serialize()) self.test_node.send_message(msg_witness_tx(tx)) self.test_node.sync_with_ping() # make sure the tx was processed assert(tx.hash in self.nodes[0].getrawmempool()) # Save this transaction for later self.utxo.append(UTXO(tx.sha256, 0, 49*100000000)) self.nodes[0].generate(1) # Verify that blocks with witnesses are rejected before activation. def test_unnecessary_witness_before_segwit_activation(self): self.log.info("Testing behavior of unnecessary witnesses") # For now, rely on earlier tests to have created at least one utxo for # us to use assert(len(self.utxo) > 0) assert(get_bip9_status(self.nodes[0], 'segwit')['status'] != 'active') tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)])] # Verify the hash with witness differs from the txid # (otherwise our testing framework must be broken!) tx.rehash() assert(tx.sha256 != tx.calc_sha256(with_witness=True)) # Construct a segwit-signaling block that includes the transaction. block = self.build_next_block(nVersion=(VB_TOP_BITS|(1 << VB_WITNESS_BIT))) self.update_witness_block_with_transactions(block, [tx]) # Sending witness data before activation is not allowed (anti-spam # rule). self.test_node.test_witness_block(block, accepted=False) # TODO: fix synchronization so we can test reject reason # Right now, AmlBitcoind delays sending reject messages for blocks # until the future, making synchronization here difficult. #assert_equal(self.test_node.last_message["reject"].reason, "unexpected-witness") # But it should not be permanently marked bad... # Resend without witness information. self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() assert_equal(self.nodes[0].getbestblockhash(), block.hash) sync_blocks(self.nodes) # Create a p2sh output -- this is so we can pass the standardness # rules (an anyone-can-spend OP_TRUE would be rejected, if not wrapped # in P2SH). p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # Now check that unnecessary witnesses can't be used to blind a node # to a transaction, eg by violating standardness checks. tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey)) tx2.rehash() self.test_node.test_transaction_acceptance(tx2, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # We'll add an unnecessary witness to this transaction that would cause # it to be non-standard, to test that violating policy with a witness before # segwit activation doesn't blind a node to a transaction. Transactions # rejected for having a witness before segwit activation shouldn't be added # to the rejection cache. tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program]))) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptPubKey)) tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000] tx3.rehash() # Note that this should be rejected for the premature witness reason, # rather than a policy check, since segwit hasn't activated yet. self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet') # If we send without witness, it should be accepted. self.std_node.test_transaction_acceptance(tx3, False, True) # Now create a new anyone-can-spend utxo for the next test. tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), CScript([p2sh_program]))) tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, CScript([OP_TRUE]))) tx4.rehash() self.test_node.test_transaction_acceptance(tx3, False, True) self.test_node.test_transaction_acceptance(tx4, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Update our utxo list; we spent the first entry. self.utxo.pop(0) self.utxo.append(UTXO(tx4.sha256, 0, tx4.vout[0].nValue)) # Mine enough blocks for segwit's vb state to be 'started'. def advance_to_segwit_started(self): height = self.nodes[0].getblockcount() # Will need to rewrite the tests here if we are past the first period assert(height < VB_PERIOD - 1) # Genesis block is 'defined'. assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'defined') # Advance to end of period, status should now be 'started' self.nodes[0].generate(VB_PERIOD-height-1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Mine enough blocks to lock in segwit, but don't activate. # TODO: we could verify that lockin only happens at the right threshold of # signalling blocks, rather than just at the right period boundary. def advance_to_segwit_lockin(self): height = self.nodes[0].getblockcount() assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Advance to end of period, and verify lock-in happens at the end self.nodes[0].generate(VB_PERIOD-1) height = self.nodes[0].getblockcount() assert((height % VB_PERIOD) == VB_PERIOD - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') # Mine enough blocks to activate segwit. # TODO: we could verify that activation only happens at the right threshold # of signalling blocks, rather than just at the right period boundary. def advance_to_segwit_active(self): assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') height = self.nodes[0].getblockcount() self.nodes[0].generate(VB_PERIOD - (height%VB_PERIOD) - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'active') # This test can only be run after segwit has activated def test_witness_commitments(self): self.log.info("Testing witness commitments") # First try a correct witness commitment. block = self.build_next_block() add_witness_commitment(block) block.solve() # Test the test -- witness serialization should be different assert(msg_witness_block(block).serialize() != msg_block(block).serialize()) # This empty block should be valid. self.test_node.test_witness_block(block, accepted=True) # Try to tweak the nonce block_2 = self.build_next_block() add_witness_commitment(block_2, nonce=28) block_2.solve() # The commitment should have changed! assert(block_2.vtx[0].vout[-1] != block.vtx[0].vout[-1]) # This should also be valid. self.test_node.test_witness_block(block_2, accepted=True) # Now test commitments with actual transactions assert (len(self.utxo) > 0) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # Let's construct a witness program witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() # tx2 will spend tx1, and send back to a regular anyone-can-spend address tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx, tx2], nonce=1) # Add an extra OP_RETURN output that matches the witness commitment template, # even though it has extra data after the incorrect commitment. # This block should fail. block_3.vtx[0].vout.append(CTxOut(0, CScript([OP_RETURN, WITNESS_COMMITMENT_HEADER + ser_uint256(2), 10]))) block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() block_3.solve() self.test_node.test_witness_block(block_3, accepted=False) # Add a different commitment with different nonce, but in the # right location, and with some funds burned(!). # This should succeed (nValue shouldn't affect finding the # witness commitment). add_witness_commitment(block_3, nonce=0) block_3.vtx[0].vout[0].nValue -= 1 block_3.vtx[0].vout[-1].nValue += 1 block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() assert(len(block_3.vtx[0].vout) == 4) # 3 OP_returns block_3.solve() self.test_node.test_witness_block(block_3, accepted=True) # Finally test that a block with no witness transactions can # omit the commitment. block_4 = self.build_next_block() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx3.rehash() block_4.vtx.append(tx3) block_4.hashMerkleRoot = block_4.calc_merkle_root() block_4.solve() self.test_node.test_witness_block(block_4, with_witness=False, accepted=True) # Update available utxo's for use in later test. self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_block_malleability(self): self.log.info("Testing witness block malleability") # Make sure that a block that has too big a virtual size # because of a too-large coinbase witness is not permanently # marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.append(b'a'*5000000) assert(get_virtual_size(block) > MAX_BLOCK_BASE_SIZE) # We can't send over the p2p network, because this is too big to relay # TODO: repeat this test with a block that can be relayed self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.pop() assert(get_virtual_size(block) < MAX_BLOCK_BASE_SIZE) self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() == block.hash) # Now make sure that malleating the witness nonce doesn't # result in a block permanently marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() # Change the nonce -- should not cause the block to be permanently # failed block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(1) ] self.test_node.test_witness_block(block, accepted=False) # Changing the witness nonce doesn't change the block hash block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(0) ] self.test_node.test_witness_block(block, accepted=True) def test_witness_block_size(self): self.log.info("Testing witness block size limit") # TODO: Test that non-witness carrying blocks can't exceed 1MB # Skipping this test for now; this is covered in p2p_fullblock.py # Test that witness-bearing blocks are limited at ceil(base + wit/4) <= 1MB. block = self.build_next_block() assert(len(self.utxo) > 0) # Create a P2WSH transaction. # The witness program will be a bunch of OP_2DROP's, followed by OP_TRUE. # This should give us plenty of room to tweak the spending tx's # virtual size. NUM_DROPS = 200 # 201 max ops per script! NUM_OUTPUTS = 50 witness_program = CScript([OP_2DROP]*NUM_DROPS + [OP_TRUE]) witness_hash = uint256_from_str(sha256(witness_program)) scriptPubKey = CScript([OP_0, ser_uint256(witness_hash)]) prevout = COutPoint(self.utxo[0].sha256, self.utxo[0].n) value = self.utxo[0].nValue parent_tx = CTransaction() parent_tx.vin.append(CTxIn(prevout, b"")) child_value = int(value/NUM_OUTPUTS) for i in range(NUM_OUTPUTS): parent_tx.vout.append(CTxOut(child_value, scriptPubKey)) parent_tx.vout[0].nValue -= 50000 assert(parent_tx.vout[0].nValue > 0) parent_tx.rehash() child_tx = CTransaction() for i in range(NUM_OUTPUTS): child_tx.vin.append(CTxIn(COutPoint(parent_tx.sha256, i), b"")) child_tx.vout = [CTxOut(value - 100000, CScript([OP_TRUE]))] for i in range(NUM_OUTPUTS): child_tx.wit.vtxinwit.append(CTxInWitness()) child_tx.wit.vtxinwit[-1].scriptWitness.stack = [b'a'*195]*(2*NUM_DROPS) + [witness_program] child_tx.rehash() self.update_witness_block_with_transactions(block, [parent_tx, child_tx]) vsize = get_virtual_size(block) additional_bytes = (MAX_BLOCK_BASE_SIZE - vsize)*4 i = 0 while additional_bytes > 0: # Add some more bytes to each input until we hit MAX_BLOCK_BASE_SIZE+1 extra_bytes = min(additional_bytes+1, 55) block.vtx[-1].wit.vtxinwit[int(i/(2*NUM_DROPS))].scriptWitness.stack[i%(2*NUM_DROPS)] = b'a'*(195+extra_bytes) additional_bytes -= extra_bytes i += 1 block.vtx[0].vout.pop() # Remove old commitment add_witness_commitment(block) block.solve() vsize = get_virtual_size(block) assert_equal(vsize, MAX_BLOCK_BASE_SIZE + 1) # Make sure that our test case would exceed the old max-network-message # limit assert(len(block.serialize(True)) > 2*1024*1024) self.test_node.test_witness_block(block, accepted=False) # Now resize the second transaction to make the block fit. cur_length = len(block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0]) block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(cur_length-1) block.vtx[0].vout.pop() add_witness_commitment(block) block.solve() assert(get_virtual_size(block) == MAX_BLOCK_BASE_SIZE) self.test_node.test_witness_block(block, accepted=True) # Update available utxo's self.utxo.pop(0) self.utxo.append(UTXO(block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue)) # submitblock will try to add the nonce automatically, so that mining # software doesn't need to worry about doing so itself. def test_submit_block(self): block = self.build_next_block() # Try using a custom nonce and then don't supply it. # This shouldn't possibly work. add_witness_commitment(block, nonce=1) block.vtx[0].wit = CTxWitness() # drop the nonce block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) # Now redo commitment with the standard nonce, but let AmlBitcoind fill it in. add_witness_commitment(block, nonce=0) block.vtx[0].wit = CTxWitness() block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert_equal(self.nodes[0].getbestblockhash(), block.hash) # This time, add a tx with non-empty witness, but don't supply # the commitment. block_2 = self.build_next_block() add_witness_commitment(block_2) block_2.solve() # Drop commitment and nonce -- submitblock should not fill in. block_2.vtx[0].vout.pop() block_2.vtx[0].wit = CTxWitness() self.nodes[0].submitblock(bytes_to_hex_str(block_2.serialize(True))) # Tip should not advance! assert(self.nodes[0].getbestblockhash() != block_2.hash) # Consensus tests of extra witness data in a transaction. def test_extra_witness_data(self): self.log.info("Testing extra witness data in tx") assert(len(self.utxo) > 0) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First try extra witness data on a tx that doesn't require a witness tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-2000, scriptPubKey)) tx.vout.append(CTxOut(1000, CScript([OP_TRUE]))) # non-witness output tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([])] tx.rehash() self.update_witness_block_with_transactions(block, [tx]) # Extra witness data should not be allowed. self.test_node.test_witness_block(block, accepted=False) # Try extra signature data. Ok if we're not spending a witness output. block.vtx[1].wit.vtxinwit = [] block.vtx[1].vin[0].scriptSig = CScript([OP_0]) block.vtx[1].rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Now try extra witness/signature data on an input that DOES require a # witness tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) # witness output tx2.vin.append(CTxIn(COutPoint(tx.sha256, 1), b"")) # non-witness tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) tx2.wit.vtxinwit.extend([CTxInWitness(), CTxInWitness()]) tx2.wit.vtxinwit[0].scriptWitness.stack = [ CScript([CScriptNum(1)]), CScript([CScriptNum(1)]), witness_program ] tx2.wit.vtxinwit[1].scriptWitness.stack = [ CScript([OP_TRUE]) ] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) # This has extra witness data, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra witness, but add extra scriptSig data tx2.vin[0].scriptSig = CScript([OP_TRUE]) tx2.vin[1].scriptSig = CScript([OP_TRUE]) tx2.wit.vtxinwit[0].scriptWitness.stack.pop(0) tx2.wit.vtxinwit[1].scriptWitness.stack = [] tx2.rehash() add_witness_commitment(block) block.solve() # This has extra signature data for a witness input, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra scriptsig on the witness input, and verify # success (even with extra scriptsig data in the non-witness input) tx2.vin[0].scriptSig = b"" tx2.rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update utxo for later tests self.utxo.pop(0) self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_push_length(self): ''' Should only allow up to 520 byte pushes in witness stack ''' self.log.info("Testing maximum witness push size") MAX_SCRIPT_ELEMENT_SIZE = 520 assert(len(self.utxo)) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) # First try a 521-byte stack element tx2.wit.vtxinwit[0].scriptWitness.stack = [ b'a'*(MAX_SCRIPT_ELEMENT_SIZE+1), witness_program ] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Now reduce the length of the stack element tx2.wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(MAX_SCRIPT_ELEMENT_SIZE) add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update the utxo for later tests self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_program_length(self): # Can create witness outputs that are long, but can't be greater than # 10k bytes to successfully spend self.log.info("Testing maximum witness program length") assert(len(self.utxo)) MAX_PROGRAM_LENGTH = 10000 # This program is 19 max pushes (9937 bytes), then 64 more opcode-bytes. long_witness_program = CScript([b'a'*520]*19 + [OP_DROP]*63 + [OP_TRUE]) assert(len(long_witness_program) == MAX_PROGRAM_LENGTH+1) long_witness_hash = sha256(long_witness_program) long_scriptPubKey = CScript([OP_0, long_witness_hash]) block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, long_scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*44 + [long_witness_program] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Try again with one less byte in the witness program witness_program = CScript([b'a'*520]*19 + [OP_DROP]*62 + [OP_TRUE]) assert(len(witness_program) == MAX_PROGRAM_LENGTH) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout[0] = CTxOut(tx.vout[0].nValue, scriptPubKey) tx.rehash() tx2.vin[0].prevout.hash = tx.sha256 tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*43 + [witness_program] tx2.rehash() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_input_length(self): ''' Ensure that vin length must match vtxinwit length ''' self.log.info("Testing witness input length") assert(len(self.utxo)) witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # Create a transaction that splits our utxo into many outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) nValue = self.utxo[0].nValue for i in range(10): tx.vout.append(CTxOut(int(nValue/10), scriptPubKey)) tx.vout[0].nValue -= 1000 assert(tx.vout[0].nValue >= 0) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Try various ways to spend tx that should all break. # This "broken" transaction serializer will not normalize # the length of vtxinwit. class BrokenCTransaction(CTransaction): def serialize_with_witness(self): flags = 0 if not self.wit.is_null(): flags |= 1 r = b"" r += struct.pack("<i", self.nVersion) if flags: dummy = [] r += ser_vector(dummy) r += struct.pack("<B", flags) r += ser_vector(self.vin) r += ser_vector(self.vout) if flags & 1: r += self.wit.serialize() r += struct.pack("<I", self.nLockTime) return r tx2 = BrokenCTransaction() for i in range(10): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.vout.append(CTxOut(nValue-3000, CScript([OP_TRUE]))) # First try using a too long vtxinwit for i in range(11): tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[i].scriptWitness.stack = [b'a', witness_program] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now try using a too short vtxinwit tx2.wit.vtxinwit.pop() tx2.wit.vtxinwit.pop() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now make one of the intermediate witnesses be incorrect tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [b'a', witness_program] tx2.wit.vtxinwit[5].scriptWitness.stack = [ witness_program ] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Fix the broken witness and the block should be accepted. tx2.wit.vtxinwit[5].scriptWitness.stack = [b'a', witness_program] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_tx_relay_before_segwit_activation(self): self.log.info("Testing relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected for premature-witness, but should # not be added to recently rejected list. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 tx_value = tx.vout[0].nValue # Verify that if a peer doesn't set nServices to include NODE_WITNESS, # the getdata is just for the non-witness portion. self.old_node.announce_tx_and_wait_for_getdata(tx) assert(self.old_node.last_message["getdata"].inv[0].type == 1) # Since we haven't delivered the tx yet, inv'ing the same tx from # a witness transaction ought not result in a getdata. try: self.test_node.announce_tx_and_wait_for_getdata(tx, timeout=2) self.log.error("Error: duplicate tx getdata!") assert(False) except AssertionError as e: pass # Delivering this transaction with witness should fail (no matter who # its from) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.old_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # But eliminating the witness should fix it self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Cleanup: mine the first transaction and update utxo self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx_hash, 0, tx_value)) # After segwit activates, verify that mempool: # - rejects transactions with unnecessary/extra witnesses # - accepts transactions with valid witnesses # and that witness transactions are relayed to non-upgraded peers. def test_tx_relay_after_segwit_activation(self): self.log.info("Testing relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected because we can't use a witness # when spending a non-witness output. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 # Verify that unnecessary witnesses are rejected. self.test_node.announce_tx_and_wait_for_getdata(tx) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # Verify that removing the witness succeeds. self.test_node.announce_tx_and_wait_for_getdata(tx) self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Now try to add extra witness data to a valid witness tx. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx_hash, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey)) tx2.rehash() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) # Add too-large for IsStandard witness and check that it does not enter reject filter p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) witness_program2 = CScript([b'a'*400000]) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]))) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program2] tx3.rehash() # Node will not be blinded to the transaction self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') # Remove witness stuffing, instead add extra witness push on stack tx3.vout[0] = CTxOut(tx2.vout[0].nValue-1000, CScript([OP_TRUE])) tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), witness_program ] tx3.rehash() self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) # Get rid of the extra witness, and verify acceptance. tx3.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] # Also check that old_node gets a tx announcement, even though this is # a witness transaction. self.old_node.wait_for_inv([CInv(1, tx2.sha256)]) # wait until tx2 was inv'ed self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.old_node.wait_for_inv([CInv(1, tx3.sha256)]) # Test that getrawtransaction returns correct witness information # hash, size, vsize raw_tx = self.nodes[0].getrawtransaction(tx3.hash, 1) assert_equal(int(raw_tx["hash"], 16), tx3.calc_sha256(True)) assert_equal(raw_tx["size"], len(tx3.serialize_with_witness())) vsize = (len(tx3.serialize_with_witness()) + 3*len(tx3.serialize_without_witness()) + 3) / 4 assert_equal(raw_tx["vsize"], vsize) assert_equal(len(raw_tx["vin"][0]["txinwitness"]), 1) assert_equal(raw_tx["vin"][0]["txinwitness"][0], hexlify(witness_program).decode('ascii')) assert(vsize != raw_tx["size"]) # Cleanup: mine the transactions and update utxo for next test self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) # Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG # This is true regardless of segwit activation. # Also test that we don't ask for blocks from unupgraded peers def test_block_relay(self, segwit_activated): self.log.info("Testing block relay") blocktype = 2|MSG_WITNESS_FLAG # test_node has set NODE_WITNESS, so all getdata requests should be for # witness blocks. # Test announcing a block via inv results in a getdata, and that # announcing a version 4 or random VB block with a header results in a getdata block1 = self.build_next_block() block1.solve() self.test_node.announce_block_and_wait_for_getdata(block1, use_header=False) assert(self.test_node.last_message["getdata"].inv[0].type == blocktype) self.test_node.test_witness_block(block1, True) block2 = self.build_next_block(nVersion=4) block2.solve() self.test_node.announce_block_and_wait_for_getdata(block2, use_header=True) assert(self.test_node.last_message["getdata"].inv[0].type == blocktype) self.test_node.test_witness_block(block2, True) block3 = self.build_next_block(nVersion=(VB_TOP_BITS | (1<<15))) block3.solve() self.test_node.announce_block_and_wait_for_getdata(block3, use_header=True) assert(self.test_node.last_message["getdata"].inv[0].type == blocktype) self.test_node.test_witness_block(block3, True) # Check that we can getdata for witness blocks or regular blocks, # and the right thing happens. if segwit_activated == False: # Before activation, we should be able to request old blocks with # or without witness, and they should be the same. chain_height = self.nodes[0].getblockcount() # Pick 10 random blocks on main chain, and verify that getdata's # for MSG_BLOCK, MSG_WITNESS_BLOCK, and rpc getblock() are equal. all_heights = list(range(chain_height+1)) random.shuffle(all_heights) all_heights = all_heights[0:10] for height in all_heights: block_hash = self.nodes[0].getblockhash(height) rpc_block = self.nodes[0].getblock(block_hash, False) block_hash = int(block_hash, 16) block = self.test_node.request_block(block_hash, 2) wit_block = self.test_node.request_block(block_hash, 2|MSG_WITNESS_FLAG) assert_equal(block.serialize(True), wit_block.serialize(True)) assert_equal(block.serialize(), hex_str_to_bytes(rpc_block)) else: # After activation, witness blocks and non-witness blocks should # be different. Verify rpc getblock() returns witness blocks, while # getdata respects the requested type. block = self.build_next_block() self.update_witness_block_with_transactions(block, []) # This gives us a witness commitment. assert(len(block.vtx[0].wit.vtxinwit) == 1) assert(len(block.vtx[0].wit.vtxinwit[0].scriptWitness.stack) == 1) self.test_node.test_witness_block(block, accepted=True) # Now try to retrieve it... rpc_block = self.nodes[0].getblock(block.hash, False) non_wit_block = self.test_node.request_block(block.sha256, 2) wit_block = self.test_node.request_block(block.sha256, 2|MSG_WITNESS_FLAG) assert_equal(wit_block.serialize(True), hex_str_to_bytes(rpc_block)) assert_equal(wit_block.serialize(False), non_wit_block.serialize()) assert_equal(wit_block.serialize(True), block.serialize(True)) # Test size, vsize, weight rpc_details = self.nodes[0].getblock(block.hash, True) assert_equal(rpc_details["size"], len(block.serialize(True))) assert_equal(rpc_details["strippedsize"], len(block.serialize(False))) weight = 3*len(block.serialize(False)) + len(block.serialize(True)) assert_equal(rpc_details["weight"], weight) # Upgraded node should not ask for blocks from unupgraded block4 = self.build_next_block(nVersion=4) block4.solve() self.old_node.getdataset = set() # Blocks can be requested via direct-fetch (immediately upon processing the announcement) # or via parallel download (with an indeterminate delay from processing the announcement) # so to test that a block is NOT requested, we could guess a time period to sleep for, # and then check. We can avoid the sleep() by taking advantage of transaction getdata's # being processed after block getdata's, and announce a transaction as well, # and then check to see if that particular getdata has been received. # Since 0.14, inv's will only be responded to with a getheaders, so send a header # to announce this block. msg = msg_headers() msg.headers = [ CBlockHeader(block4) ] self.old_node.send_message(msg) self.old_node.announce_tx_and_wait_for_getdata(block4.vtx[0]) assert(block4.sha256 not in self.old_node.getdataset) # V0 segwit outputs should be standard after activation, but not before. def test_standardness_v0(self, segwit_activated): self.log.info("Testing standardness of v0 outputs (%s activation)" % ("after" if segwit_activated else "before")) assert(len(self.utxo)) witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) p2sh_pubkey = hash160(witness_program) p2sh_scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # First prepare a p2sh output (so that spending it will pass standardness) p2sh_tx = CTransaction() p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] p2sh_tx.vout = [CTxOut(self.utxo[0].nValue-1000, p2sh_scriptPubKey)] p2sh_tx.rehash() # Mine it on test_node to create the confirmed output. self.test_node.test_transaction_acceptance(p2sh_tx, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Now test standardness of v0 P2WSH outputs. # Start by creating a transaction with two outputs. tx = CTransaction() tx.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx.vout = [CTxOut(p2sh_tx.vout[0].nValue-10000, scriptPubKey)] tx.vout.append(CTxOut(8000, scriptPubKey)) # Might burn this later tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=segwit_activated) # Now create something that looks like a P2PKH output. This won't be spendable. scriptPubKey = CScript([OP_0, hash160(witness_hash)]) tx2 = CTransaction() if segwit_activated: # if tx was accepted, then we spend the second output. tx2.vin = [CTxIn(COutPoint(tx.sha256, 1), b"")] tx2.vout = [CTxOut(7000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] else: # if tx wasn't accepted, we just re-spend the p2sh output we started with. tx2.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx2.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, scriptPubKey)] tx2.rehash() self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=segwit_activated) # Now update self.utxo for later tests. tx3 = CTransaction() if segwit_activated: # tx and tx2 were both accepted. Don't bother trying to reclaim the # P2PKH output; just send tx's first output back to an anyone-can-spend. sync_mempools([self.nodes[0], self.nodes[1]]) tx3.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx3.vout = [CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))] tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) else: # tx and tx2 didn't go anywhere; just clean up the p2sh_tx output. tx3.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx3.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, witness_program)] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) assert_equal(len(self.nodes[1].getrawmempool()), 0) # Verify that future segwit upgraded transactions are non-standard, # but valid in blocks. Can run this before and after segwit activation. def test_segwit_versions(self): self.log.info("Testing standardness/consensus for segwit versions (0-16)") assert(len(self.utxo)) NUM_TESTS = 17 # will test OP_0, OP1, ..., OP_16 if (len(self.utxo) < NUM_TESTS): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) split_value = (self.utxo[0].nValue - 4000) // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, CScript([OP_TRUE]))) tx.rehash() block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop(0) for i in range(NUM_TESTS): self.utxo.append(UTXO(tx.sha256, i, split_value)) sync_blocks(self.nodes) temp_utxo = [] tx = CTransaction() count = 0 witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) assert_equal(len(self.nodes[1].getrawmempool()), 0) for version in list(range(OP_1, OP_16+1)) + [OP_0]: count += 1 # First try to spend to a future version segwit scriptPubKey. scriptPubKey = CScript([CScriptOp(version), witness_hash]) tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] tx.vout = [CTxOut(self.utxo[0].nValue-1000, scriptPubKey)] tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) self.utxo.pop(0) temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue)) self.nodes[0].generate(1) # Mine all the transactions sync_blocks(self.nodes) assert(len(self.nodes[0].getrawmempool()) == 0) # Finally, verify that version 0 -> version 1 transactions # are non-standard scriptPubKey = CScript([CScriptOp(OP_1), witness_hash]) tx2 = CTransaction() tx2.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx2.vout = [CTxOut(tx.vout[0].nValue-1000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] tx2.rehash() # Gets accepted to test_node, because standardness of outputs isn't # checked with fRequireStandard self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=False) temp_utxo.pop() # last entry in temp_utxo was the output we just spent temp_utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) # Spend everything in temp_utxo back to an OP_TRUE output. tx3 = CTransaction() total_value = 0 for i in temp_utxo: tx3.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) total_value += i.nValue tx3.wit.vtxinwit[-1].scriptWitness.stack = [witness_program] tx3.vout.append(CTxOut(total_value - 1000, CScript([OP_TRUE]))) tx3.rehash() # Spending a higher version witness output is not allowed by policy, # even with fRequireStandard=false. self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) self.test_node.sync_with_ping() with mininode_lock: assert(b"reserved for soft-fork upgrades" in self.test_node.last_message["reject"].reason) # Building a block with the transaction must be valid, however. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2, tx3]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) # Add utxo to our list self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_premature_coinbase_witness_spend(self): self.log.info("Testing premature coinbase witness spend") block = self.build_next_block() # Change the output of the block to be a witness output. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) block.vtx[0].vout[0].scriptPubKey = scriptPubKey # This next line will rehash the coinbase and update the merkle # root, and solve. self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) spend_tx = CTransaction() spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].sha256, 0), b"")] spend_tx.vout = [CTxOut(block.vtx[0].vout[0].nValue, witness_program)] spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] spend_tx.rehash() # Now test a premature spend. self.nodes[0].generate(98) sync_blocks(self.nodes) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=False) # Advancing one more block should allow the spend. self.nodes[0].generate(1) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=True) sync_blocks(self.nodes) def test_signature_version_1(self): self.log.info("Testing segwit signature hash version 1") key = CECKey() key.set_secretbytes(b"9") pubkey = CPubKey(key.get_pubkey()) witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First create a witness output for use in the tests. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) # Mine this transaction in preparation for following tests. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) self.utxo.pop(0) # Test each hashtype prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) for sigflag in [ 0, SIGHASH_ANYONECANPAY ]: for hashtype in [SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE]: hashtype |= sigflag block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) tx.vout.append(CTxOut(prev_utxo.nValue - 1000, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) # Too-large input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue+1, key) self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Too-small input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue-1, key) block.vtx.pop() # remove last tx self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Now try correct value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue, key) block.vtx.pop() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) # Test combinations of signature hashes. # Split the utxo into a lot of outputs. # Randomly choose up to 10 to spend, sign with different hashtypes, and # output to a random number of outputs. Repeat NUM_TESTS times. # Ensure that we've tested a situation where we use SIGHASH_SINGLE with # an input index > number of outputs. NUM_TESTS = 500 temp_utxos = [] tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) split_value = prev_utxo.nValue // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, prev_utxo.nValue, key) for i in range(NUM_TESTS): temp_utxos.append(UTXO(tx.sha256, i, split_value)) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() used_sighash_single_out_of_bounds = False for i in range(NUM_TESTS): # Ping regularly to keep the connection alive if (not i % 100): self.test_node.sync_with_ping() # Choose random number of inputs to use. num_inputs = random.randint(1, 10) # Create a slight bias for producing more utxos num_outputs = random.randint(1, 11) random.shuffle(temp_utxos) assert(len(temp_utxos) > num_inputs) tx = CTransaction() total_value = 0 for i in range(num_inputs): tx.vin.append(CTxIn(COutPoint(temp_utxos[i].sha256, temp_utxos[i].n), b"")) tx.wit.vtxinwit.append(CTxInWitness()) total_value += temp_utxos[i].nValue split_value = total_value // num_outputs for i in range(num_outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) for i in range(num_inputs): # Now try to sign each input, using a random hashtype. anyonecanpay = 0 if random.randint(0, 1): anyonecanpay = SIGHASH_ANYONECANPAY hashtype = random.randint(1, 3) | anyonecanpay sign_P2PK_witness_input(witness_program, tx, i, hashtype, temp_utxos[i].nValue, key) if (hashtype == SIGHASH_SINGLE and i >= num_outputs): used_sighash_single_out_of_bounds = True tx.rehash() for i in range(num_outputs): temp_utxos.append(UTXO(tx.sha256, i, split_value)) temp_utxos = temp_utxos[num_inputs:] block.vtx.append(tx) # Test the block periodically, if we're close to maxblocksize if (get_virtual_size(block) > MAX_BLOCK_BASE_SIZE - 1000): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() if (not used_sighash_single_out_of_bounds): self.log.info("WARNING: this test run didn't attempt SIGHASH_SINGLE with out-of-bounds index value") # Test the transactions we've added to the block if (len(block.vtx) > 1): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) # Now test witness version 0 P2PKH transactions pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(temp_utxos[0].sha256, temp_utxos[0].n), b"")) tx.vout.append(CTxOut(temp_utxos[0].nValue, scriptPKH)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, temp_utxos[0].nValue, key) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL # Check that we can't have a scriptSig tx2.vin[0].scriptSig = CScript([signature, pubkey]) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Move the signature to the witness. block.vtx.pop() tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [signature, pubkey] tx2.vin[0].scriptSig = b"" tx2.rehash() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) temp_utxos.pop(0) # Update self.utxos for later tests. Just spend everything in # temp_utxos to a corresponding entry in self.utxos tx = CTransaction() index = 0 for i in temp_utxos: # Just spend to our usual anyone-can-spend output # Use SIGHASH_SINGLE|SIGHASH_ANYONECANPAY so we can build up # the signatures as we go. tx.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx.vout.append(CTxOut(i.nValue, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, index, SIGHASH_SINGLE|SIGHASH_ANYONECANPAY, i.nValue, key) index += 1 block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) for i in range(len(tx.vout)): self.utxo.append(UTXO(tx.sha256, i, tx.vout[i].nValue)) # Test P2SH wrapped witness programs. def test_p2sh_witness(self, segwit_activated): self.log.info("Testing P2SH witness transactions") assert(len(self.utxo)) # Prepare the p2sh-wrapped witness output witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) p2wsh_pubkey = CScript([OP_0, witness_hash]) p2sh_witness_hash = hash160(p2wsh_pubkey) scriptPubKey = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([p2wsh_pubkey]) # a push of the redeem script # Fund the P2SH output tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() # Verify mempool acceptance and block validity self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True, with_witness=segwit_activated) sync_blocks(self.nodes) # Now test attempts to spend the output. spend_tx = CTransaction() spend_tx.vin.append(CTxIn(COutPoint(tx.sha256, 0), scriptSig)) spend_tx.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) spend_tx.rehash() # This transaction should not be accepted into the mempool pre- or # post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which # will require a witness to spend a witness program regardless of # segwit activation. Note that older AmlBitcoind's that are not # segwit-aware would also reject this for failing CLEANSTACK. self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Try to put the witness script in the scriptSig, should also fail. spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a']) spend_tx.rehash() self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Now put the witness script in the witness, should succeed after # segwit activates. spend_tx.vin[0].scriptSig = scriptSig spend_tx.rehash() spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a', witness_program ] # Verify mempool acceptance self.test_node.test_transaction_acceptance(spend_tx, with_witness=True, accepted=segwit_activated) block = self.build_next_block() self.update_witness_block_with_transactions(block, [spend_tx]) # If we're before activation, then sending this without witnesses # should be valid. If we're after activation, then sending this with # witnesses should be valid. if segwit_activated: self.test_node.test_witness_block(block, accepted=True) else: self.test_node.test_witness_block(block, accepted=True, with_witness=False) # Update self.utxo self.utxo.pop(0) self.utxo.append(UTXO(spend_tx.sha256, 0, spend_tx.vout[0].nValue)) # Test the behavior of starting up a segwit-aware node after the softfork # has activated. As segwit requires different block data than pre-segwit # nodes would have stored, this requires special handling. # To enable this test, pass --oldbinary=<path-to-pre-segwit-AmlBitcoind> to # the test. def test_upgrade_after_activation(self, node_id): self.log.info("Testing software upgrade after softfork activation") assert(node_id != 0) # node0 is assumed to be a segwit-active AmlBitcoind # Make sure the nodes are all up sync_blocks(self.nodes) # Restart with the new binary self.stop_node(node_id) self.start_node(node_id, extra_args=[]) connect_nodes(self.nodes[0], node_id) sync_blocks(self.nodes) # Make sure that this peer thinks segwit has activated. assert(get_bip9_status(self.nodes[node_id], 'segwit')['status'] == "active") # Make sure this peers blocks match those of node0. height = self.nodes[node_id].getblockcount() while height >= 0: block_hash = self.nodes[node_id].getblockhash(height) assert_equal(block_hash, self.nodes[0].getblockhash(height)) assert_equal(self.nodes[0].getblock(block_hash), self.nodes[node_id].getblock(block_hash)) height -= 1 def test_witness_sigops(self): '''Ensure sigop counting is correct inside witnesses.''' self.log.info("Testing sigops limit") assert(len(self.utxo)) # Keep this under MAX_OPS_PER_SCRIPT (201) witness_program = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKMULTISIG]*5 + [OP_CHECKSIG]*193 + [OP_ENDIF]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) sigops_per_script = 20*5 + 193*1 # We'll produce 2 extra outputs, one with a program that would take us # over max sig ops, and one with a program that would exactly reach max # sig ops outputs = (MAX_SIGOP_COST // sigops_per_script) + 2 extra_sigops_available = MAX_SIGOP_COST % sigops_per_script # We chose the number of checkmultisigs/checksigs to make this work: assert(extra_sigops_available < 100) # steer clear of MAX_OPS_PER_SCRIPT # This script, when spent with the first # N(=MAX_SIGOP_COST//sigops_per_script) outputs of our transaction, # would push us just over the block sigop limit. witness_program_toomany = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available + 1) + [OP_ENDIF]) witness_hash_toomany = sha256(witness_program_toomany) scriptPubKey_toomany = CScript([OP_0, witness_hash_toomany]) # If we spend this script instead, we would exactly reach our sigop # limit (for witness sigops). witness_program_justright = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available) + [OP_ENDIF]) witness_hash_justright = sha256(witness_program_justright) scriptPubKey_justright = CScript([OP_0, witness_hash_justright]) # First split our available utxo into a bunch of outputs split_value = self.utxo[0].nValue // outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) for i in range(outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.vout[-2].scriptPubKey = scriptPubKey_toomany tx.vout[-1].scriptPubKey = scriptPubKey_justright tx.rehash() block_1 = self.build_next_block() self.update_witness_block_with_transactions(block_1, [tx]) self.test_node.test_witness_block(block_1, accepted=True) tx2 = CTransaction() # If we try to spend the first n-1 outputs from tx, that should be # too many sigops. total_value = 0 for i in range(outputs-1): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program ] total_value += tx.vout[i].nValue tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_toomany ] tx2.vout.append(CTxOut(total_value, CScript([OP_TRUE]))) tx2.rehash() block_2 = self.build_next_block() self.update_witness_block_with_transactions(block_2, [tx2]) self.test_node.test_witness_block(block_2, accepted=False) # Try dropping the last input in tx2, and add an output that has # too many sigops (contributing to legacy sigop count). checksig_count = (extra_sigops_available // 4) + 1 scriptPubKey_checksigs = CScript([OP_CHECKSIG]*checksig_count) tx2.vout.append(CTxOut(0, scriptPubKey_checksigs)) tx2.vin.pop() tx2.wit.vtxinwit.pop() tx2.vout[0].nValue -= tx.vout[-2].nValue tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx2]) self.test_node.test_witness_block(block_3, accepted=False) # If we drop the last checksig in this output, the tx should succeed. block_4 = self.build_next_block() tx2.vout[-1].scriptPubKey = CScript([OP_CHECKSIG]*(checksig_count-1)) tx2.rehash() self.update_witness_block_with_transactions(block_4, [tx2]) self.test_node.test_witness_block(block_4, accepted=True) # Reset the tip back down for the next test sync_blocks(self.nodes) for x in self.nodes: x.invalidateblock(block_4.hash) # Try replacing the last input of tx2 to be spending the last # output of tx block_5 = self.build_next_block() tx2.vout.pop() tx2.vin.append(CTxIn(COutPoint(tx.sha256, outputs-1), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_justright ] tx2.rehash() self.update_witness_block_with_transactions(block_5, [tx2]) self.test_node.test_witness_block(block_5, accepted=True) # TODO: test p2sh sigop counting def test_getblocktemplate_before_lockin(self): self.log.info("Testing getblocktemplate setting of segwit versionbit (before lockin)") # Node0 is segwit aware, node2 is not. for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate() block_version = gbt_results['version'] # If we're not indicating segwit support, we will still be # signalling for segwit activation. assert_equal((block_version & (1 << VB_WITNESS_BIT) != 0), node == self.nodes[0]) # If we don't specify the segwit rule, then we won't get a default # commitment. assert('default_witness_commitment' not in gbt_results) # Workaround: # Can either change the tip, or change the mempool and wait 5 seconds # to trigger a recomputation of getblocktemplate. txid = int(self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1), 16) # Using mocktime lets us avoid sleep() sync_mempools(self.nodes) self.nodes[0].setmocktime(int(time.time())+10) self.nodes[2].setmocktime(int(time.time())+10) for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate({"rules" : ["segwit"]}) block_version = gbt_results['version'] if node == self.nodes[2]: # If this is a non-segwit node, we should still not get a witness # commitment, nor a version bit signalling segwit. assert_equal(block_version & (1 << VB_WITNESS_BIT), 0) assert('default_witness_commitment' not in gbt_results) else: # For segwit-aware nodes, check the version bit and the witness # commitment are correct. assert(block_version & (1 << VB_WITNESS_BIT) != 0) assert('default_witness_commitment' in gbt_results) witness_commitment = gbt_results['default_witness_commitment'] # Check that default_witness_commitment is present. witness_root = CBlock.get_merkle_root([ser_uint256(0), ser_uint256(txid)]) script = get_witness_script(witness_root, 0) assert_equal(witness_commitment, bytes_to_hex_str(script)) # undo mocktime self.nodes[0].setmocktime(0) self.nodes[2].setmocktime(0) # Uncompressed pubkeys are no longer supported in default relay policy, # but (for now) are still valid in blocks. def test_uncompressed_pubkey(self): self.log.info("Testing uncompressed pubkeys") # Segwit transactions using uncompressed pubkeys are not accepted # under default policy, but should still pass consensus. key = CECKey() key.set_secretbytes(b"9") key.set_compressed(False) pubkey = CPubKey(key.get_pubkey()) assert_equal(len(pubkey), 65) # This should be an uncompressed pubkey assert(len(self.utxo) > 0) utxo = self.utxo.pop(0) # Test 1: P2WPKH # First create a P2WPKH output that uses an uncompressed pubkey pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(utxo.sha256, utxo.n), b"")) tx.vout.append(CTxOut(utxo.nValue-1000, scriptPKH)) tx.rehash() # Confirm it in a block. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Now try to spend it. Send it to a P2WSH output, which we'll # use in the next test. witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptWSH = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptWSH)) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ signature, pubkey ] tx2.rehash() # Should fail policy test. self.test_node.test_transaction_acceptance(tx2, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) # Test 2: P2WSH # Try to spend the P2WSH output created in last test. # Send it to a P2SH(P2WSH) output, which we'll use in the next test. p2sh_witness_hash = hash160(scriptWSH) scriptP2SH = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([scriptWSH]) tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptP2SH)) tx3.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx3, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx3]) self.test_node.test_witness_block(block, accepted=True) # Test 3: P2SH(P2WSH) # Try to spend the P2SH output created in the last test. # Send it to a P2PKH output, which we'll use in the next test. scriptPubKey = GetP2PKHScript(pubkeyhash) tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), scriptSig)) tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, scriptPubKey)) tx4.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx4, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx4]) self.test_node.test_witness_block(block, accepted=True) # Test 4: Uncompressed pubkeys should still be valid in non-segwit # transactions. tx5 = CTransaction() tx5.vin.append(CTxIn(COutPoint(tx4.sha256, 0), b"")) tx5.vout.append(CTxOut(tx4.vout[0].nValue-1000, CScript([OP_TRUE]))) (sig_hash, err) = SignatureHash(scriptPubKey, tx5, 0, SIGHASH_ALL) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx5.vin[0].scriptSig = CScript([signature, pubkey]) tx5.rehash() # Should pass policy and consensus. self.test_node.test_transaction_acceptance(tx5, True, True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx5]) self.test_node.test_witness_block(block, accepted=True) self.utxo.append(UTXO(tx5.sha256, 0, tx5.vout[0].nValue)) def test_non_standard_witness(self):
def run_test(self): # Setup the p2p connections and start up the network thread. self.test_node = TestNode() # sets NODE_WITNESS|NODE_NETWORK self.old_node = TestNode() # only NODE_NETWORK self.std_node = TestNode() # for testing node1 (fRequireStandard=true) self.p2p_connections = [self.test_node, self.old_node] self.connections = [] self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node, services=NODE_NETWORK|NODE_WITNESS)) self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.old_node, services=NODE_NETWORK)) self.connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], self.std_node, services=NODE_NETWORK|NODE_WITNESS)) self.test_node.add_connection(self.connections[0]) self.old_node.add_connection(self.connections[1]) self.std_node.add_connection(self.connections[2]) NetworkThread().start() # Start up network handling in another thread # Keep a place to store utxo's that can be used in later tests self.utxo = [] # Test logic begins here self.test_node.wait_for_verack() self.log.info("Starting tests before segwit lock in:") self.test_witness_services() # Verifies NODE_WITNESS self.test_non_witness_transaction() # non-witness tx's are accepted self.test_unnecessary_witness_before_segwit_activation() self.test_block_relay(segwit_activated=False) # Advance to segwit being 'started' self.advance_to_segwit_started() sync_blocks(self.nodes) self.test_getblocktemplate_before_lockin() sync_blocks(self.nodes) # At lockin, nothing should change. self.log.info("Testing behavior post lockin, pre-activation") self.advance_to_segwit_lockin() # Retest unnecessary witnesses self.test_unnecessary_witness_before_segwit_activation() self.test_witness_tx_relay_before_segwit_activation() self.test_block_relay(segwit_activated=False) self.test_p2sh_witness(segwit_activated=False) self.test_standardness_v0(segwit_activated=False) sync_blocks(self.nodes) # Now activate segwit self.log.info("Testing behavior after segwit activation") self.advance_to_segwit_active() sync_blocks(self.nodes) # Test P2SH witness handling again self.test_p2sh_witness(segwit_activated=True) self.test_witness_commitments() self.test_block_malleability() self.test_witness_block_size() self.test_submit_block() self.test_extra_witness_data() self.test_max_witness_push_length() self.test_max_witness_program_length() self.test_witness_input_length() self.test_block_relay(segwit_activated=True) self.test_tx_relay_after_segwit_activation() self.test_standardness_v0(segwit_activated=True) self.test_segwit_versions() self.test_premature_coinbase_witness_spend() self.test_uncompressed_pubkey() self.test_signature_version_1() self.test_non_standard_witness() sync_blocks(self.nodes) self.test_upgrade_after_activation(node_id=2) self.test_witness_sigops() if __name__ == '__main__': SegWitTest().main()
self.log.info("Testing detection of non-standard P2WSH witness") pad = chr(1).encode('latin-1') # Create scripts for tests scripts = [] scripts.append(CScript([OP_DROP] * 100)) scripts.append(CScript([OP_DROP] * 99)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 60)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 61)) p2wsh_scripts = [] assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # For each script, generate a pair of P2WSH and P2SH-P2WSH output. outputvalue = (self.utxo[0].nValue - 1000) // (len(scripts) * 2) for i in scripts: p2wsh = CScript([OP_0, sha256(i)]) p2sh = hash160(p2wsh) p2wsh_scripts.append(p2wsh) tx.vout.append(CTxOut(outputvalue, p2wsh)) tx.vout.append(CTxOut(outputvalue, CScript([OP_HASH160, p2sh, OP_EQUAL]))) tx.rehash() txid = tx.sha256 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Creating transactions for tests p2wsh_txs = [] p2sh_txs = [] for i in range(len(scripts)): p2wsh_tx = CTransaction() p2wsh_tx.vin.append(CTxIn(COutPoint(txid,i*2))) p2wsh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) p2wsh_tx.rehash() p2wsh_txs.append(p2wsh_tx) p2sh_tx = CTransaction() p2sh_tx.vin.append(CTxIn(COutPoint(txid,i*2+1), CScript([p2wsh_scripts[i]]))) p2sh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2sh_tx.wit.vtxinwit.append(CTxInWitness()) p2sh_tx.rehash() p2sh_txs.append(p2sh_tx) # Testing native P2WSH # Witness stack size, excluding witnessScript, over 100 is non-standard p2wsh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2wsh_txs[0], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[0], True, True) # Stack element size over 80 bytes is non-standard p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # Standard nodes should accept if element size is not over 80 bytes p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # witnessScript size at 3600 bytes is standard p2wsh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2wsh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2wsh_txs[2], True, True) # witnessScript size at 3601 bytes is non-standard p2wsh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2wsh_txs[3], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[3], True, True) # Repeating the same tests with P2SH-P2WSH p2sh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2sh_txs[0], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[0], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2sh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2sh_txs[2], True, True) p2sh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2sh_txs[3], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[3], True, True) self.nodes[0].generate(1) # Mine and clean up the mempool of non-standard node # Valid but non-standard transactions in a block should be accepted by standard node sync_blocks(self.nodes) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.utxo.pop(0)
auth.umd.min.js
/* @preserve * @esri/arcgis-rest-auth - v2.14.1 - Apache-2.0 * Copyright (c) 2017-2020 Esri, Inc. * Thu Jul 23 2020 13:27:15 GMT-0600 (Mountain Daylight Time) */ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@esri/arcgis-rest-request")):"function"==typeof define&&define.amd?define(["exports","@esri/arcgis-rest-request"],r):r((e=e||self).arcgisRest=e.arcgisRest||{},e.arcgisRest)}(this,function(e,d){"use strict";var k=function(){return(k=Object.assign||function(e){for(var r,t=1,n=arguments.length;t<n;t++)for(var s in r=arguments[t])Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s]);return e}).apply(this,arguments)};function a(e,r){var t=r;return t.rawResponse=!1,d.request(e,t).then(function(e){var r={token:e.access_token,username:e.username,expires:new Date(Date.now()+(1e3*e.expires_in-1e3)),ssl:!0===e.ssl};return e.refresh_token&&(r.refreshToken=e.refresh_token),r})}var r=(t.prototype.getToken=function(e,r){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(r)),this._pendingTokenRequest)},t.prototype.refreshToken=function(e){var r=this,t=k({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return a(this.portal+"/oauth2/token/",t).then(function(e){return r._pendingTokenRequest=null,r.token=e.token,r.expires=e.expires,e.token})},t.prototype.refreshSession=function(){var e=this;return this.refreshToken().then(function(){return e})},t);function t(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}function o(e,r){var t=r;return"undefined"!=typeof window&&window.location&&window.location.host?t.params.referer=window.location.host:t.params.referer=d.NODEJS_DEFAULT_REFERER_HEADER,d.request(e,t)}var s=/^https?:\/\/(\S+)\.arcgis\.com.+/;function i(e){return s.test(e)}function
(e){if(!s.test(e))return null;var r=e.match(s)[1].split(".").pop();return r.includes("dev")?"dev":r.includes("qa")?"qa":"production"}function p(e,r){var t=d.cleanUrl(function(e){if(!s.test(e))return e;switch(h(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}(r)).replace(/https?:\/\//,""),n=d.cleanUrl(e).replace(/https?:\/\//,"");return new RegExp(n,"i").test(t)}var n=(T.beginOAuth2=function(e,r){void 0===r&&(r=window);var t,n=k({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",duration:20160,popup:!0,state:e.clientId,locale:""},e),s=n.portal,o=n.provider,i=n.clientId,a=n.duration,h=n.redirectUri,p=n.popup,u=n.state,c=n.locale,l=n.params;if(t="arcgis"===o?s+"/oauth2/authorize?client_id="+i+"&response_type=token&expiration="+a+"&redirect_uri="+encodeURIComponent(h)+"&state="+u+"&locale="+c:s+"/oauth2/social/authorize?client_id="+i+"&socialLoginProviderName="+o+"&autoAccountCreateForSocial=true&response_type=token&expiration="+a+"&redirect_uri="+encodeURIComponent(h)+"&state="+u+"&locale="+c,l&&(t=t+"&"+d.encodeQueryString(l)),p){var f=function(){var t={promise:null,resolve:null,reject:null};return t.promise=new Promise(function(e,r){t.resolve=e,t.reject=r}),t}();return r["__ESRI_REST_AUTH_HANDLER_"+i]=function(e,r){if(e){var t=JSON.parse(e);f.reject(new d.ArcGISAuthError(t.errorMessage,t.error))}else if(r){var n=JSON.parse(r);f.resolve(new T({clientId:i,portal:s,ssl:n.ssl,token:n.token,tokenExpires:new Date(n.expires),username:n.username}))}},r.open(t,"oauth-window","height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes"),f.promise}r.location.href=t},T.completeOAuth2=function(e,s){void 0===s&&(s=window);var r=k({portal:"https://www.arcgis.com/sharing/rest",popup:!0},e),o=r.portal,i=r.clientId,a=r.popup;function t(e,r){try{var t=void 0,n="__ESRI_REST_AUTH_HANDLER_"+i;if(a&&(s.opener?s.opener.parent&&s.opener.parent[n]?t=s.opener.parent[n]:s.opener&&s.opener[n]&&(t=s.opener[n]):s!==s.parent&&s.parent&&s.parent[n]&&(t=s.parent[n]),t))return t(e?JSON.stringify(e):void 0,JSON.stringify(r)),void s.close()}catch(e){throw new d.ArcGISAuthError('Unable to complete authentication. It\'s possible you specified popup based oAuth2 but no handler from "beginOAuth2()" present. This generally happens because the "popup" option differs between "beginOAuth2()" and "completeOAuth2()".')}if(e)throw new d.ArcGISAuthError(e.errorMessage,e.error);return new T({clientId:i,portal:o,ssl:r.ssl,token:r.token,tokenExpires:r.expires,username:r.username})}var n=s.location.href.match(/access_token=(.+)&expires_in=(.+)&username=([^&]+)/);if(!n){var h=s.location.href.match(/error=(.+)&error_description=(.+)/);return t({error:h[1],errorMessage:decodeURIComponent(h[2])})}var p=n[1],u=new Date(Date.now()+1e3*parseInt(n[2],10)-6e4),c=decodeURIComponent(n[3]);return t(void 0,{token:p,expires:u,ssl:-1<s.location.href.indexOf("&ssl=true")||-1<s.location.href.indexOf("#ssl=true"),username:c})},T.authorize=function(e,r){var t=k({portal:"https://arcgis.com/sharing/rest",duration:20160},e),n=t.portal,s=t.clientId,o=t.duration,i=t.redirectUri;r.writeHead(301,{Location:n+"/oauth2/authorize?client_id="+s+"&duration="+o+"&response_type=code&redirect_uri="+encodeURIComponent(i)}),r.end()},T.exchangeAuthorizationCode=function(e,r){var t=k({portal:"https://www.arcgis.com/sharing/rest",refreshTokenTTL:1440},e),n=t.portal,s=t.clientId,o=t.redirectUri,i=t.refreshTokenTTL;return a(n+"/oauth2/token",{params:{grant_type:"authorization_code",client_id:s,redirect_uri:o,code:r}}).then(function(e){return new T({clientId:s,portal:n,ssl:e.ssl,redirectUri:o,refreshToken:e.refreshToken,refreshTokenTTL:i,refreshTokenExpires:new Date(Date.now()+1e3*(i-1)),token:e.token,tokenExpires:e.expires,username:e.username})})},T.deserialize=function(e){var r=JSON.parse(e);return new T({clientId:r.clientId,refreshToken:r.refreshToken,refreshTokenExpires:new Date(r.refreshTokenExpires),username:r.username,password:r.password,token:r.token,tokenExpires:new Date(r.tokenExpires),portal:r.portal,ssl:r.ssl,tokenDuration:r.tokenDuration,redirectUri:r.redirectUri,refreshTokenTTL:r.refreshTokenTTL})},T.fromCredential=function(e){return new T({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:e.ssl,token:e.token,username:e.userId,tokenExpires:new Date(e.expires)})},Object.defineProperty(T.prototype,"token",{get:function(){return this._token},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"tokenExpires",{get:function(){return this._tokenExpires},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"refreshToken",{get:function(){return this._refreshToken},enumerable:!0,configurable:!0}),Object.defineProperty(T.prototype,"refreshTokenExpires",{get:function(){return this._refreshTokenExpires},enumerable:!0,configurable:!0}),T.prototype.toCredential=function(){return{expires:this.tokenExpires.getTime(),server:this.portal,ssl:this.ssl,token:this.token,userId:this.username}},T.prototype.getUser=function(e){var r=this;if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);var t=this.portal+"/community/self",n=k({httpMethod:"GET",authentication:this},e,{rawResponse:!1});return this._pendingUserRequest=d.request(t,n).then(function(e){return r._user=e,r._pendingUserRequest=null,e}),this._pendingUserRequest},T.prototype.getUsername=function(){return this.username?Promise.resolve(this.username):this._user?Promise.resolve(this._user.username):this.getUser().then(function(e){return e.username})},T.prototype.getToken=function(e,r){return function(e,r){var t=i(e),n=i(r),s=h(e),o=h(r);return!(!t||!n||s!==o)}(this.portal,e)?this.getFreshToken(r):new RegExp(this.portal,"i").test(e)?this.getFreshToken(r):this.getTokenForServer(e,r)},T.prototype.toJSON=function(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,refreshTokenTTL:this.refreshTokenTTL}},T.prototype.serialize=function(){return JSON.stringify(this)},T.prototype.refreshSession=function(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new d.ArcGISAuthError("Unable to refresh token."))},T.prototype.getServerRootUrl=function(e){var r=d.cleanUrl(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/)[0].match(/(https?:\/\/)(.+)/),t=(r[0],r[1]),n=r[2].split("/"),s=n[0],o=n.slice(1);return""+t+s.toLowerCase()+"/"+o.join("/")},T.prototype.getTokenForServer=function(r,t){var n=this,s=this.getServerRootUrl(r),e=this.trustedServers[s];return e&&e.expires&&e.expires.getTime()>Date.now()?Promise.resolve(e.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=d.request(s+"/rest/info").then(function(e){if(e.owningSystemUrl){if(p(e.owningSystemUrl,n.portal))return d.request(e.owningSystemUrl+"/sharing/rest/info",t);throw new d.ArcGISAuthError(r+" is not federated with "+n.portal+".","NOT_FEDERATED")}if(e.authInfo&&void 0!==n.trustedServers[s])return Promise.resolve({authInfo:e.authInfo});throw new d.ArcGISAuthError(r+" is not federated with any portal and is not explicitly trusted.","NOT_FEDERATED")}).then(function(e){return e.authInfo.tokenServicesUrl}).then(function(e){return n.token&&n.tokenExpires.getTime()>Date.now()?o(e,{params:{token:n.token,serverUrl:r,expiration:n.tokenDuration,client:"referer"}}):o(e,{params:{username:n.username,password:n.password,expiration:n.tokenDuration,client:"referer"}}).then(function(e){return n._token=e.token,n._tokenExpires=new Date(e.expires),e})}).then(function(e){return n.trustedServers[s]={expires:new Date(e.expires),token:e.token},delete n._pendingTokenRequests[s],e.token})),this._pendingTokenRequests[s])},T.prototype.getFreshToken=function(e){var r=this;return this.token&&!this.tokenExpires?Promise.resolve(this.token):this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshSession(e).then(function(e){return r._pendingTokenRequests[r.portal]=null,e.token})),this._pendingTokenRequests[this.portal])},T.prototype.refreshWithUsernameAndPassword=function(e){var r=this,t=k({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return o(this.portal+"/generateToken",t).then(function(e){return r._token=e.token,r._tokenExpires=new Date(e.expires),r})},T.prototype.refreshWithRefreshToken=function(e){var r=this;if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<Date.now())return this.refreshRefreshToken(e);var t=k({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return a(this.portal+"/oauth2/token",t).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r})},T.prototype.refreshRefreshToken=function(e){var r=this,t=k({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return a(this.portal+"/oauth2/token",t).then(function(e){return r._token=e.token,r._tokenExpires=e.expires,r._refreshToken=e.refreshToken,r._refreshTokenExpires=new Date(Date.now()+60*(r.refreshTokenTTL-1)*1e3),r})},T);function T(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this.username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?d.cleanUrl(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.refreshTokenTTL=e.refreshTokenTTL||1440,this.trustedServers={},e.server){var r=this.getServerRootUrl(e.server);this.trustedServers[r]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}e.ApplicationSession=r,e.UserSession=n,e.fetchToken=a,e.generateToken=o,Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=auth.umd.min.js.map
h
AlipayEcoMycarViolationCityPushModel.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayEcoMycarViolationCityPushModel(object): def __init__(self): self._city_code = None self._push_type = None self._service_status = None @property def city_code(self): return self._city_code @city_code.setter def city_code(self, value): self._city_code = value @property def push_type(self): return self._push_type @push_type.setter def push_type(self, value): self._push_type = value @property def service_status(self): return self._service_status @service_status.setter def service_status(self, value): self._service_status = value def to_alipay_dict(self): params = dict() if self.city_code: if hasattr(self.city_code, 'to_alipay_dict'): params['city_code'] = self.city_code.to_alipay_dict() else: params['city_code'] = self.city_code if self.push_type: if hasattr(self.push_type, 'to_alipay_dict'): params['push_type'] = self.push_type.to_alipay_dict() else: params['push_type'] = self.push_type if self.service_status:
return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayEcoMycarViolationCityPushModel() if 'city_code' in d: o.city_code = d['city_code'] if 'push_type' in d: o.push_type = d['push_type'] if 'service_status' in d: o.service_status = d['service_status'] return o
if hasattr(self.service_status, 'to_alipay_dict'): params['service_status'] = self.service_status.to_alipay_dict() else: params['service_status'] = self.service_status
swap_chain.rs
/*! Swap chain management. ## Lifecycle At the low level, the swap chain is using the new simplified model of gfx-rs. A swap chain is a separate object that is backend-dependent but shares the index with the parent surface, which is backend-independent. This ensures a 1:1 correspondence between them. `get_next_image()` requests a new image from the surface. It becomes a part of `TextureViewInner::SwapChain` of the resulted view. The view is registered in the HUB but not in the device tracker. The only operation allowed on the view is to be either a color or a resolve attachment. It can only be used in one command buffer, which needs to be submitted before presenting. Command buffer tracker knows about the view, but only for the duration of recording. The view ID is erased from it at the end, so that it's not merged into the device tracker. When a swapchain view is used in `begin_render_pass()`, we assume the start and end image layouts purely based on whether or not this view was used in this command buffer before. It always starts with `Uninitialized` and ends with `Present`, so that no barriers are needed when we need to actually present it. In `queue_submit()` we make sure to signal the semaphore whenever we render to a swap chain view. In `present()` we return the swap chain image back and wait on the semaphore. !*/ #[cfg(feature = "trace")] use crate::device::trace::Action; use crate::{ device::DeviceError, hub::{Global, GlobalIdentityHandlerFactory, HalApi, Input, Token}, id::{DeviceId, SwapChainId, TextureViewId, Valid}, resource, track::TextureSelector, LifeGuard, Stored, SubmissionIndex, }; use hal::{Device as _, Queue as _, Surface as _}; use std::{borrow::Borrow, marker::PhantomData}; use thiserror::Error; use wgt::SwapChainStatus as Status; const FRAME_TIMEOUT_MS: u32 = 1000; pub const DESIRED_NUM_FRAMES: u32 = 3; #[derive(Debug)] pub struct SwapChain<A: hal::Api> { pub(crate) life_guard: LifeGuard, pub(crate) device_id: Stored<DeviceId>, pub(crate) desc: wgt::SwapChainDescriptor, pub(crate) num_frames: u32, pub(crate) acquired_texture: Option<(Stored<TextureViewId>, A::SurfaceTexture)>, pub(crate) active_submission_index: SubmissionIndex, pub(crate) marker: PhantomData<A>, } impl<A: hal::Api> crate::hub::Resource for SwapChain<A> { const TYPE: &'static str = "SwapChain"; fn life_guard(&self) -> &LifeGuard { &self.life_guard } } #[derive(Clone, Debug, Error)] pub enum SwapChainError { #[error("swap chain is invalid")] Invalid, #[error("parent surface is invalid")] InvalidSurface, #[error(transparent)] Device(#[from] DeviceError), #[error("swap chain image is already acquired")] AlreadyAcquired, #[error("acquired frame is still referenced")] StillReferenced, } #[derive(Clone, Debug, Error)] pub enum CreateSwapChainError { #[error(transparent)] Device(#[from] DeviceError), #[error("invalid surface")] InvalidSurface, #[error("`SwapChainOutput` must be dropped before a new `SwapChain` is made")] SwapChainOutputExists, #[error("Both `SwapChain` width and height must be non-zero. Wait to recreate the `SwapChain` until the window has non-zero area.")] ZeroArea, #[error("surface does not support the adapter's queue family")] UnsupportedQueueFamily, #[error("requested format {requested:?} is not in list of supported formats: {available:?}")] UnsupportedFormat { requested: wgt::TextureFormat, available: Vec<wgt::TextureFormat>, }, #[error("requested usage is not supported")] UnsupportedUsage, } #[repr(C)] #[derive(Debug)] pub struct SwapChainOutput { pub status: Status, pub view_id: Option<TextureViewId>, } impl<G: GlobalIdentityHandlerFactory> Global<G> { pub fn swap_chain_get_current_texture_view<A: HalApi>( &self, swap_chain_id: SwapChainId, view_id_in: Input<G, TextureViewId>, ) -> Result<SwapChainOutput, SwapChainError> { profiling::scope!("get_next_texture", "SwapChain"); let hub = A::hub(self); let mut token = Token::root(); let fid = hub.texture_views.prepare(view_id_in); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); let surface = surface_guard .get_mut(swap_chain_id.to_surface_id()) .map_err(|_| SwapChainError::InvalidSurface)?; let (device_guard, mut token) = hub.devices.read(&mut token); let (mut swap_chain_guard, mut token) = hub.swap_chains.write(&mut token); let sc = swap_chain_guard .get_mut(swap_chain_id) .map_err(|_| SwapChainError::Invalid)?; let device = &device_guard[sc.device_id.value]; #[cfg(feature = "trace")] if let Some(ref trace) = device.trace { trace.lock().add(Action::GetSwapChainTexture { id: fid.id(), parent_id: swap_chain_id, }); } let suf = A::get_surface_mut(surface); let (texture, status) = match unsafe { suf.acquire_texture(FRAME_TIMEOUT_MS) } { Ok(Some(ast)) => { let status = if ast.suboptimal { Status::Suboptimal } else { Status::Good }; (Some(ast.texture), status) } Ok(None) => (None, Status::Timeout), Err(err) => ( None, match err { hal::SurfaceError::Lost => Status::Lost, hal::SurfaceError::Device(err) => { return Err(DeviceError::from(err).into()); } hal::SurfaceError::Outdated => Status::Outdated, hal::SurfaceError::Other(msg) => { log::error!("acquire error: {}", msg); Status::Lost } }, ), }; let hal_desc = hal::TextureViewDescriptor { label: Some("_Frame"), format: sc.desc.format, dimension: wgt::TextureViewDimension::D2, usage: hal::TextureUses::COLOR_TARGET, range: wgt::ImageSubresourceRange::default(), }; let view_id = match texture { Some(suf_texture) => { let raw = unsafe { device .raw .create_texture_view(suf_texture.borrow(), &hal_desc) .map_err(DeviceError::from)? }; let view = resource::TextureView { raw, source: resource::TextureViewSource::SwapChain(Stored { value: Valid(swap_chain_id), ref_count: sc.life_guard.add_ref(), }), desc: resource::HalTextureViewDescriptor { format: sc.desc.format, dimension: wgt::TextureViewDimension::D2, range: wgt::ImageSubresourceRange::default(), }, format_features: wgt::TextureFormatFeatures { allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT, flags: wgt::TextureFormatFeatureFlags::empty(), filterable: false, }, extent: wgt::Extent3d { width: sc.desc.width, height: sc.desc.height, depth_or_array_layers: 1, }, samples: 1, sampled_internal_use: hal::TextureUses::empty(), selector: TextureSelector { layers: 0..1, levels: 0..1, }, life_guard: LifeGuard::new("<SwapChain View>"), }; let ref_count = view.life_guard.add_ref(); let id = fid.assign(view, &mut token); if sc.acquired_texture.is_some() { return Err(SwapChainError::AlreadyAcquired); } sc.acquired_texture = Some(( Stored { value: id, ref_count, }, suf_texture, )); Some(id.0) } None => None, }; Ok(SwapChainOutput { status, view_id }) } pub fn swap_chain_present<A: HalApi>( &self, swap_chain_id: SwapChainId, ) -> Result<Status, SwapChainError> { profiling::scope!("present", "SwapChain"); let hub = A::hub(self); let mut token = Token::root(); let (mut surface_guard, mut token) = self.surfaces.write(&mut token); let surface = surface_guard .get_mut(swap_chain_id.to_surface_id()) .map_err(|_| SwapChainError::InvalidSurface)?; let (mut device_guard, mut token) = hub.devices.write(&mut token); let (mut swap_chain_guard, _) = hub.swap_chains.write(&mut token); let sc = swap_chain_guard .get_mut(swap_chain_id) .map_err(|_| SwapChainError::Invalid)?; let device = &mut device_guard[sc.device_id.value];
} let suf_texture = { let (view_id, suf_texture) = sc .acquired_texture .take() .ok_or(SwapChainError::AlreadyAcquired)?; drop(swap_chain_guard); let (view, _) = hub.texture_views.unregister(view_id.value.0, &mut token); if let Some(view) = view { device.schedule_rogue_texture_view_for_destruction(view_id.value, view, &mut token); } suf_texture }; let result = unsafe { device .queue .present(A::get_surface_mut(surface), suf_texture) }; log::debug!("Presented. End of Frame"); match result { Ok(()) => Ok(Status::Good), Err(err) => match err { hal::SurfaceError::Lost => Ok(Status::Lost), hal::SurfaceError::Device(err) => Err(SwapChainError::from(DeviceError::from(err))), hal::SurfaceError::Outdated => Ok(Status::Outdated), hal::SurfaceError::Other(msg) => { log::error!("acquire error: {}", msg); Err(SwapChainError::InvalidSurface) } }, } } }
#[cfg(feature = "trace")] if let Some(ref trace) = device.trace { trace.lock().add(Action::PresentSwapChain(swap_chain_id));
test_info_panel_model.py
from cms import models def test_create_no_media(db): """ Test creating an info panel. """ models.InfoPanel.objects.create( text="The quick brown fox jumped over the lazy dog.", title="No Media" ) def test_ordering(info_panel_factory): """ Panels should be ordered by their ``order`` attribute. """ p1 = info_panel_factory(order=2) p2 = info_panel_factory(order=3) p3 = info_panel_factory(order=1) assert list(models.InfoPanel.objects.all()) == [p3, p1, p2] def test_repr(): """ The representation of the panel should contain the information necessary to reconstruct it. """ panel = models.InfoPanel(title="Test Panel") expected = f"InfoPanel(id={repr(panel.id)}, title={repr(panel.title)})" assert repr(panel) == expected
""" Converting an info panel to a string should return the panel's title. """ panel = models.InfoPanel(title="Test Panel") assert str(panel) == panel.title
def test_str():
mover.ts
import { renameSync, existsSync } from "fs"; import { dirname, basename, join } from "path"; const postfix = ".lock"; const moveAsync = (sourcePath: string, destinationPath: string): Promise<string> => { if (!existsSync(sourcePath)) { return Promise.reject(`Can't find file '${sourcePath}'`); } const promise = new Promise<string>((resolve, reject) => {
renameSync(sourcePath, destinationPath); resolve(`Success '${sourcePath}' moved to '${destinationPath}'`); } catch (err) { reject(`Unable to move '${sourcePath}' to '${destinationPath}'. Error: '${err.message}'`) } }); return promise; } export const lock = (filePath: string): Promise<string> => { return moveAsync(filePath, `${filePath}${postfix}`); }; export const unlock = (filePath: string): Promise<string> => { const dir = dirname(filePath); const name = basename(filePath, postfix) const targetPath = join(dir, name); return moveAsync(filePath, targetPath); }; export const move = (filePath: string, targetDir: string): Promise<string> => { const name = basename(filePath); const targetPath = join(targetDir, name); return moveAsync(filePath, targetPath); };
try {
echarts.d.ts
import * as zrender from 'zrender/esm/zrender'; import Eventful from 'zrender/esm/core/Eventful'; import { GlobalModelSetOptionOpts } from './model/Global'; import ComponentModel from './model/Component'; import SeriesModel from './model/Series'; import ChartView from './view/Chart'; import * as modelUtil from './util/model'; import './component/dataset'; import mapDataStorage from './coord/geo/mapDataStorage'; import { CoordinateSystemCreator } from './coord/CoordinateSystem'; import { Payload, RendererType, ECEvent, ActionHandler, ActionInfo, OptionPreprocessor, PostUpdater, LoadingEffectCreator, StageHandlerOverallReset, StageHandler, DimensionDefinitionLoose, ThemeOption, ZRColor, ComponentMainType, DimensionLoose, ScaleDataValue } from './util/types'; import 'zrender/esm/canvas/canvas'; import { registerExternalTransform } from './data/helper/transform'; import { LocaleOption } from './locale'; import type { EChartsFullOption } from './option'; import { MorphDividingMethod } from 'zrender/esm/tool/morphPath'; declare type ModelFinder = modelUtil.ModelFinder; export declare const version = "5.0.0"; export declare const dependencies: { zrender: string; }; export declare const PRIORITY: { PROCESSOR: { FILTER: number; SERIES_FILTER: number; STATISTIC: number; }; VISUAL: { LAYOUT: number; PROGRESSIVE_LAYOUT: number; GLOBAL: number; CHART: number; POST_CHART_LAYOUT: number; COMPONENT: number; BRUSH: number; CHART_ITEM: number; ARIA: number; DECAL: number; }; }; declare const IN_MAIN_PROCESS_KEY: "__flagInMainProcess"; declare const OPTION_UPDATED_KEY: "__optionUpdated"; declare const STATUS_NEEDS_UPDATE_KEY: "__needsUpdateStatus"; declare const CONNECT_STATUS_KEY: "__connectUpdateStatus"; interface SetOptionOpts { notMerge?: boolean; lazyUpdate?: boolean; silent?: boolean; replaceMerge?: GlobalModelSetOptionOpts['replaceMerge']; transition?: SetOptionTransitionOpt; } export interface SetOptionTransitionOptItem { from?: SetOptionTransitionOptFinder; to: SetOptionTransitionOptFinder; dividingMethod: MorphDividingMethod; } interface SetOptionTransitionOptFinder extends modelUtil.ModelFinderObject { dimension: DimensionLoose; } declare type SetOptionTransitionOpt = SetOptionTransitionOptItem | SetOptionTransitionOptItem[]; interface PostIniter { (chart: EChartsType): void; } declare class ECharts extends Eventful { id: string; group: string; private _zr; private _dom; private _model; private _throttledZrFlush; private _theme; private _locale; private _chartsViews; private _chartsMap;
private _scheduler; private _messageCenter; private _pendingActions; protected _$eventProcessor: never; private _disposed; private _loadingFX; private _labelManager; private [OPTION_UPDATED_KEY]; private [IN_MAIN_PROCESS_KEY]; private [CONNECT_STATUS_KEY]; private [STATUS_NEEDS_UPDATE_KEY]; constructor(dom: HTMLElement, theme?: string | ThemeOption, opts?: { locale?: string | LocaleOption; renderer?: RendererType; devicePixelRatio?: number; useDirtyRect?: boolean; width?: number; height?: number; }); private _onframe; getDom(): HTMLElement; getId(): string; getZr(): zrender.ZRenderType; setOption(option: EChartsFullOption, notMerge?: boolean, lazyUpdate?: boolean): void; setOption(option: EChartsFullOption, opts?: SetOptionOpts): void; private setTheme; private getModel; getOption(): EChartsFullOption; getWidth(): number; getHeight(): number; getDevicePixelRatio(): number; getRenderedCanvas(opts?: { backgroundColor?: ZRColor; pixelRatio?: number; }): HTMLCanvasElement; getSvgDataURL(): string; getDataURL(opts?: { type?: 'png' | 'jpg' | 'svg'; pixelRatio?: number; backgroundColor?: ZRColor; excludeComponents?: ComponentMainType[]; }): string; getConnectedDataURL(opts?: { type?: 'png' | 'jpg' | 'svg'; pixelRatio?: number; backgroundColor?: ZRColor; connectedBackgroundColor?: ZRColor; excludeComponents?: string[]; }): string; convertToPixel(finder: ModelFinder, value: ScaleDataValue): number; convertToPixel(finder: ModelFinder, value: ScaleDataValue[]): number[]; convertFromPixel(finder: ModelFinder, value: number): number; convertFromPixel(finder: ModelFinder, value: number[]): number[]; containPixel(finder: ModelFinder, value: number[]): boolean; getVisual(finder: ModelFinder, visualType: string): string | number | number[] | import("zrender/esm/graphic/Pattern").PatternObject | import("zrender/esm/graphic/LinearGradient").LinearGradientObject | import("zrender/esm/graphic/RadialGradient").RadialGradientObject; private getViewOfComponentModel; private getViewOfSeriesModel; private _initEvents; isDisposed(): boolean; clear(): void; dispose(): void; resize(opts?: { width?: number | 'auto'; height?: number | 'auto'; silent?: boolean; }): void; showLoading(cfg?: object): void; showLoading(name?: string, cfg?: object): void; hideLoading(): void; makeActionFromEvent(eventObj: ECEvent): Payload; dispatchAction(payload: Payload, opt?: boolean | { silent?: boolean; flush?: boolean | undefined; }): void; updateLabelLayout(): void; appendData(params: { seriesIndex: number; data: any; }): void; private static internalField; } export declare function init(dom: HTMLElement, theme?: string | object, opts?: { renderer?: RendererType; devicePixelRatio?: number; width?: number; height?: number; locale?: string | LocaleOption; }): ECharts; export declare function connect(groupId: string | ECharts[]): string; export declare function disConnect(groupId: string): void; export declare const disconnect: typeof disConnect; export declare function dispose(chart: ECharts | HTMLElement | string): void; export declare function getInstanceByDom(dom: HTMLElement): ECharts; export declare function getInstanceById(key: string): ECharts; export declare function registerTheme(name: string, theme: ThemeOption): void; export declare function registerPreprocessor(preprocessorFunc: OptionPreprocessor): void; export declare function registerProcessor(priority: number | StageHandler | StageHandlerOverallReset, processor?: StageHandler | StageHandlerOverallReset): void; export declare function registerPostInit(postInitFunc: PostIniter): void; export declare function registerPostUpdate(postUpdateFunc: PostUpdater): void; export declare function registerAction(type: string, eventName: string, action: ActionHandler): void; export declare function registerAction(type: string, action: ActionHandler): void; export declare function registerAction(actionInfo: ActionInfo, action: ActionHandler): void; export declare function registerCoordinateSystem(type: string, coordSysCreator: CoordinateSystemCreator): void; export declare function getCoordinateSystemDimensions(type: string): DimensionDefinitionLoose[]; export { registerLocale } from './locale'; declare function registerLayout(priority: number, layoutTask: StageHandler | StageHandlerOverallReset): void; declare function registerLayout(layoutTask: StageHandler | StageHandlerOverallReset): void; declare function registerVisual(priority: number, layoutTask: StageHandler | StageHandlerOverallReset): void; declare function registerVisual(layoutTask: StageHandler | StageHandlerOverallReset): void; export { registerLayout, registerVisual }; export declare function registerLoading(name: string, loadingFx: LoadingEffectCreator): void; export declare function extendComponentModel(proto: object): ComponentModel; export declare function extendComponentView(proto: object): ChartView; export declare function extendSeriesModel(proto: object): SeriesModel; export declare function extendChartView(proto: object): ChartView; export declare function setCanvasCreator(creator: () => HTMLCanvasElement): void; export declare function registerMap(mapName: Parameters<typeof mapDataStorage.registerMap>[0], geoJson: Parameters<typeof mapDataStorage.registerMap>[1], specialAreas?: Parameters<typeof mapDataStorage.registerMap>[2]): void; export declare function getMap(mapName: string): { geoJson: any; specialAreas: import("./coord/geo/geoTypes").GeoSpecialAreas; }; export declare const registerTransform: typeof registerExternalTransform; export declare const dataTool: {}; export interface EChartsType extends ECharts { }
private _componentsViews; private _componentsMap; private _coordSysMgr; private _api;
mod.rs
//! //! https://tools.ietf.org/html/rfc3501 //! //! INTERNET MESSAGE ACCESS PROTOCOL //! // rustfmt doesn't do a very good job on nom parser invocations. #![cfg_attr(rustfmt, rustfmt_skip)] use std::str; use crate::{ parser::{ core::*, rfc3501::body::*, rfc3501::body_structure::*, rfc4551, rfc5464::resp_metadata, ParseResult, }, types::*, }; pub mod body; pub mod body_structure; fn is_tag_char(c: u8) -> bool { c != b'+' && is_astring_char(c) } named!(status_ok<Status>, map!(tag_no_case!("OK"), |_s| Status::Ok )); named!(status_no<Status>, map!(tag_no_case!("NO"), |_s| Status::No )); named!(status_bad<Status>, map!(tag_no_case!("BAD"), |_s| Status::Bad )); named!(status_preauth<Status>, map!(tag_no_case!("PREAUTH"), |_s| Status::PreAuth )); named!(status_bye<Status>, map!(tag_no_case!("BYE"), |_s| Status::Bye )); named!(status<Status>, alt!( status_ok | status_no | status_bad | status_preauth | status_bye )); named!(mailbox<&str>, map!( astring_utf8, |s| { if s.eq_ignore_ascii_case("INBOX") { "INBOX" } else { s } } )); named!(flag_extension<&str>, map_res!( recognize!(pair!(tag!("\\"), take_while!(is_atom_char))), str::from_utf8 )); named!(flag<&str>, alt!(flag_extension | atom)); named!(flag_list<Vec<&str>>, parenthesized_list!(flag)); named!(flag_perm<&str>, alt!( map_res!(tag!("\\*"), str::from_utf8) | flag )); named!(resp_text_code_alert<ResponseCode>, do_parse!( tag_no_case!("ALERT") >> (ResponseCode::Alert) )); named!(resp_text_code_badcharset<ResponseCode>, do_parse!( tag_no_case!("BADCHARSET") >> ch: opt!(do_parse!( tag!(" ") >> charsets: parenthesized_nonempty_list!(astring_utf8) >> (charsets) )) >> (ResponseCode::BadCharset(ch)) )); named!(resp_text_code_capability<ResponseCode>, map!( capability_data, |c| ResponseCode::Capabilities(c) )); named!(resp_text_code_parse<ResponseCode>, do_parse!( tag_no_case!("PARSE") >> (ResponseCode::Parse) )); named!(resp_text_code_permanent_flags<ResponseCode>, do_parse!( tag_no_case!("PERMANENTFLAGS ") >> flags: parenthesized_list!(flag_perm) >> (ResponseCode::PermanentFlags(flags)) )); named!(resp_text_code_read_only<ResponseCode>, do_parse!( tag_no_case!("READ-ONLY") >> (ResponseCode::ReadOnly) )); named!(resp_text_code_read_write<ResponseCode>, do_parse!( tag_no_case!("READ-WRITE") >> (ResponseCode::ReadWrite) )); named!(resp_text_code_try_create<ResponseCode>, do_parse!( tag_no_case!("TRYCREATE") >> (ResponseCode::TryCreate) )); named!(resp_text_code_uid_validity<ResponseCode>, do_parse!( tag_no_case!("UIDVALIDITY ") >> num: number >> (ResponseCode::UidValidity(num)) )); named!(resp_text_code_uid_next<ResponseCode>, do_parse!( tag_no_case!("UIDNEXT ") >> num: number >> (ResponseCode::UidNext(num)) )); named!(resp_text_code_unseen<ResponseCode>, do_parse!( tag_no_case!("UNSEEN ") >> num: number >> (ResponseCode::Unseen(num)) )); named!(resp_text_code<ResponseCode>, do_parse!( tag!("[") >> coded: alt!( resp_text_code_alert | resp_text_code_badcharset | resp_text_code_capability | resp_text_code_parse | resp_text_code_permanent_flags | resp_text_code_uid_validity | resp_text_code_uid_next | resp_text_code_unseen | resp_text_code_read_only | resp_text_code_read_write | resp_text_code_try_create | rfc4551::resp_text_code_highest_mod_seq ) >> // Per the spec, the closing tag should be "] ". // See `resp_text` for more on why this is done differently. tag!("]") >> (coded) )); named!(capability<Capability>, alt!( map!(tag_no_case!("IMAP4rev1"), |_| Capability::Imap4rev1) | map!(preceded!(tag_no_case!("AUTH="), atom), |a| Capability::Auth(a)) | map!(atom, |a| Capability::Atom(a)) )); fn ensure_capabilities_contains_imap4rev<'a>( capabilities: Vec<Capability<'a>>, ) -> Result<Vec<Capability<'a>>, ()> { if capabilities.contains(&Capability::Imap4rev1) { Ok(capabilities) } else { Err(()) } } named!(capability_data<Vec<Capability>>, map_res!( do_parse!( tag_no_case!("CAPABILITY") >> capabilities: many0!(preceded!(char!(' '), capability)) >> (capabilities) ), ensure_capabilities_contains_imap4rev )); named!(resp_capability<Response>, map!( capability_data, |c| Response::Capabilities(c) )); named!(mailbox_data_search<Response>, do_parse!( tag_no_case!("SEARCH") >> ids: many0!(do_parse!( tag!(" ") >> id: number >> (id) )) >> (Response::IDs(ids)) )); named!(mailbox_data_flags<Response>, do_parse!( tag_no_case!("FLAGS ") >> flags: flag_list >> (Response::MailboxData(MailboxDatum::Flags(flags))) )); named!(mailbox_data_exists<Response>, do_parse!( num: number >> tag_no_case!(" EXISTS") >> (Response::MailboxData(MailboxDatum::Exists(num))) )); named!(mailbox_list<(Vec<&str>, Option<&str>, &str)>, do_parse!( flags: flag_list >> tag!(" ") >> delimiter: alt!( map!(quoted_utf8, |v| Some(v)) | map!(nil, |_| None) ) >> tag!(" ") >> name: mailbox >> ((flags, delimiter, name)) )); named!(mailbox_data_list<Response>, do_parse!( tag_no_case!("LIST ") >> data: mailbox_list >> (Response::MailboxData(MailboxDatum::List { flags: data.0, delimiter: data.1, name: data.2, })) )); named!(mailbox_data_lsub<Response>, do_parse!( tag_no_case!("LSUB ") >> data: mailbox_list >> (Response::MailboxData(MailboxDatum::List { flags: data.0, delimiter: data.1, name: data.2, })) )); // Unlike `status_att` in the RFC syntax, this includes the value, // so that it can return a valid enum object instead of just a key. named!(status_att<StatusAttribute>, alt!( rfc4551::status_att_val_highest_mod_seq | do_parse!( tag_no_case!("MESSAGES ") >> val: number >> (StatusAttribute::Messages(val)) ) | do_parse!( tag_no_case!("RECENT ") >> val: number >> (StatusAttribute::Recent(val)) ) | do_parse!( tag_no_case!("UIDNEXT ") >> val: number >> (StatusAttribute::UidNext(val)) ) | do_parse!( tag_no_case!("UIDVALIDITY ") >> val: number >> (StatusAttribute::UidValidity(val)) ) | do_parse!( tag_no_case!("UNSEEN ") >> val: number >> (StatusAttribute::Unseen(val)) ) )); named!(status_att_list<Vec<StatusAttribute>>, parenthesized_nonempty_list!(status_att)); named!(mailbox_data_status<Response>, do_parse!( tag_no_case!("STATUS ") >> mailbox: mailbox >> tag!(" ") >> status: status_att_list >> (Response::MailboxData(MailboxDatum::Status { mailbox, status, })) )); named!(mailbox_data_recent<Response>, do_parse!( num: number >> tag_no_case!(" RECENT") >> (Response::MailboxData(MailboxDatum::Recent(num))) )); named!(mailbox_data<Response>, alt!( mailbox_data_flags | mailbox_data_exists | mailbox_data_list | mailbox_data_lsub | mailbox_data_status | mailbox_data_recent | mailbox_data_search )); // An address structure is a parenthesized list that describes an // electronic mail address. named!(address<Address>, paren_delimited!( do_parse!( name: nstring >> tag!(" ") >> adl: nstring >> tag!(" ") >> mailbox: nstring >> tag!(" ") >> host: nstring >> (Address { name, adl, mailbox, host, }) ) )); named!(opt_addresses<Option<Vec<Address>>>, alt!( map!(nil, |_s| None) | map!(paren_delimited!( many1!(do_parse!( addr: address >> opt!(char!(' ')) >> (addr) )) ), |v| Some(v)) )); named!(pub(crate) envelope<Envelope>, paren_delimited!( do_parse!( date: nstring >> tag!(" ") >> subject: nstring >> tag!(" ") >> from: opt_addresses >> tag!(" ") >> sender: opt_addresses >> tag!(" ") >> reply_to: opt_addresses >> tag!(" ") >> to: opt_addresses >> tag!(" ") >> cc: opt_addresses >> tag!(" ") >> bcc: opt_addresses >> tag!(" ") >> in_reply_to: nstring >> tag!(" ") >> message_id: nstring >> (Envelope { date, subject, from, sender, reply_to, to, cc, bcc, in_reply_to, message_id, }) ) )); named!(msg_att_envelope<AttributeValue>, do_parse!( tag_no_case!("ENVELOPE ") >> envelope: envelope >> (AttributeValue::Envelope(Box::new(envelope))) )); named!(msg_att_internal_date<AttributeValue>, do_parse!( tag_no_case!("INTERNALDATE ") >> date: nstring_utf8 >> (AttributeValue::InternalDate(date.unwrap())) )); named!(msg_att_flags<AttributeValue>, do_parse!( tag_no_case!("FLAGS ") >> flags: flag_list >> (AttributeValue::Flags(flags)) )); named!(msg_att_rfc822<AttributeValue>, do_parse!( tag_no_case!("RFC822 ") >> raw: nstring >> (AttributeValue::Rfc822(raw)) )); named!(msg_att_rfc822_header<AttributeValue>, do_parse!( tag_no_case!("RFC822.HEADER ") >> opt!(tag!(" ")) >> // extra space workaround for DavMail raw: nstring >> (AttributeValue::Rfc822Header(raw)) )); named!(msg_att_rfc822_size<AttributeValue>, do_parse!( tag_no_case!("RFC822.SIZE ") >> num: number >> (AttributeValue::Rfc822Size(num)) )); named!(msg_att_rfc822_text<AttributeValue>, do_parse!( tag_no_case!("RFC822.TEXT ") >> raw: nstring >> (AttributeValue::Rfc822Text(raw)) )); named!(msg_att_uid<AttributeValue>, do_parse!( tag_no_case!("UID ") >> num: number >> (AttributeValue::Uid(num)) )); named!(msg_att<AttributeValue>, alt!( msg_att_body_section | msg_att_body_structure | msg_att_envelope | msg_att_internal_date | msg_att_flags | rfc4551::msg_att_mod_seq | msg_att_rfc822 | msg_att_rfc822_header | msg_att_rfc822_size | msg_att_rfc822_text | msg_att_uid )); named!(msg_att_list<Vec<AttributeValue>>, parenthesized_nonempty_list!(msg_att)); named!(message_data_fetch<Response>, do_parse!( num: number >> tag_no_case!(" FETCH ") >> attrs: msg_att_list >> (Response::Fetch(num, attrs)) )); named!(message_data_expunge<Response>, do_parse!( num: number >> tag_no_case!(" EXPUNGE") >> (Response::Expunge(num)) )); named!(tag<RequestId>, map!( map_res!(take_while1!(is_tag_char), str::from_utf8), |s| RequestId(s.to_string()) )); // This is not quite according to spec, which mandates the following: // ["[" resp-text-code "]" SP] text // However, examples in RFC 4551 (Conditional STORE) counteract this by giving // examples of `resp-text` that do not include the trailing space and text. named!(resp_text<(Option<ResponseCode>, Option<&str>)>, do_parse!( code: opt!(resp_text_code) >> text: text >> ({ let res = if text.is_empty() { None } else if code.is_some() { Some(&text[1..]) } else { Some(text) }; (code, res) }) )); named!(continue_req<Response>, do_parse!( tag!("+") >> opt!(tag!(" ")) >> // Some servers do not send the space :/ text: resp_text >> // TODO: base64 tag!("\r\n") >> (Response::Continue { code: text.0, information: text.1, }) )); named!(response_tagged<Response>, do_parse!( tag: tag >> tag!(" ") >> status: status >> tag!(" ") >> text: resp_text >> tag!("\r\n") >> (Response::Done { tag, status, code: text.0, information: text.1, }) )); named!(resp_cond<Response>, do_parse!( status: status >> tag!(" ") >> text: resp_text >> (Response::Data { status, code: text.0, information: text.1, }) )); named!(response_data<Response>, do_parse!( tag!("* ") >> contents: alt!( resp_cond | mailbox_data | message_data_expunge | message_data_fetch | resp_capability | resp_metadata ) >> tag!("\r\n") >> (contents) )); named!(response<Response>, alt!( continue_req | response_data | response_tagged )); pub fn parse_response(msg: &[u8]) -> ParseResult { response(msg) } #[cfg(test)] mod tests { use super::parse_response; use crate::types::*; use nom; #[test] fn test_number_overflow() { match parse_response(b"* 2222222222222222222222222222222222222222222C\r\n") { Err(_) => {} _ => panic!("error required for integer overflow"), } } #[test] fn test_unseen() { match parse_response(b"* OK [UNSEEN 3] Message 3 is first unseen\r\n").unwrap() { ( _, Response::Data { status: Status::Ok, code: Some(ResponseCode::Unseen(3)), information: Some("Message 3 is first unseen"), }, ) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_body_text() { match parse_response(b"* 2 FETCH (BODY[TEXT] {3}\r\nfoo)\r\n") { Ok((_, Response::Fetch(_, attrs))) => { let body = &attrs[0]; assert_eq!( body, &AttributeValue::BodySection { section: Some(SectionPath::Full(MessageSection::Text)), index: None, data: Some(b"foo"), }, "body = {:?}", body ); } rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_body_structure() { const RESPONSE: &[u8] = b"* 15 FETCH (BODYSTRUCTURE (\"TEXT\" \"PLAIN\" (\"CHARSET\" \"iso-8859-1\") NIL NIL \"QUOTED-PRINTABLE\" 1315 42 NIL NIL NIL NIL))\r\n"; match parse_response(RESPONSE) { Ok((_, Response::Fetch(_, attrs))) => { let body = &attrs[0]; assert!( if let AttributeValue::BodyStructure(_) = *body { true } else { false }, "body = {:?}", body ); } rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_status() { match parse_response(b"* STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)\r\n") { Ok((_, Response::MailboxData(MailboxDatum::Status { mailbox, status }))) => { assert_eq!(mailbox, "blurdybloop"); assert_eq!( status, [ StatusAttribute::Messages(231), StatusAttribute::UidNext(44292), ] ); } rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_notify() { match parse_response(b"* 3501 EXPUNGE\r\n") { Ok((_, Response::Expunge(3501))) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* 3501 EXISTS\r\n") { Ok((_, Response::MailboxData(MailboxDatum::Exists(3501)))) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"+ idling\r\n") { Ok(( _, Response::Continue { code: None, information: Some("idling"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_search() { match parse_response(b"* SEARCH\r\n") { Ok((_, Response::IDs(ids))) => { assert!(ids.is_empty()); } rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* SEARCH 12345 67890\r\n") { Ok((_, Response::IDs(ids))) => { assert_eq!(ids[0], 12345); assert_eq!(ids[1], 67890); } rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_uid_fetch() { match parse_response(b"* 4 FETCH (UID 71372 RFC822.HEADER {10275}\r\n") { Err(nom::Err::Incomplete(nom::Needed::Size(10275))) => {} rsp => panic!("unexpected response {:?}", rsp), } }
fn test_list() { match crate::parser::rfc3501::mailbox(b"iNboX ") { Ok((_, mb)) => { assert_eq!(mb, "INBOX"); } rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* LIST (\\HasNoChildren) \".\" INBOX.Tests\r\n") { Ok((_, Response::MailboxData(_))) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_uid_fetch_extra_space() { // DavMail inserts an extra space after RFC822.HEADER match parse_response(b"* 4 FETCH (UID 71372 RFC822.HEADER {10275}\r\n") { Err(nom::Err::Incomplete(nom::Needed::Size(10275))) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_envelope() { let env = br#"ENVELOPE ("Wed, 17 Jul 1996 02:23:25 -0700 (PDT)" "IMAP4rev1 WG mtg summary and minutes" (("Terry Gray" NIL "gray" "cac.washington.edu")) (("Terry Gray" NIL "gray" "cac.washington.edu")) (("Terry Gray" NIL "gray" "cac.washington.edu")) ((NIL NIL "imap" "cac.washington.edu")) ((NIL NIL "minutes" "CNRI.Reston.VA.US") ("John Klensin" NIL "KLENSIN" "MIT.EDU")) NIL NIL "<[email protected]>") "#; match crate::parser::rfc3501::msg_att_envelope(env) { Ok((_, AttributeValue::Envelope(_))) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_header_fields() { const RESPONSE: &[u8] = b"* 1 FETCH (UID 1 BODY[HEADER.FIELDS (CHAT-VERSION)] {21}\r\nChat-Version: 1.0\r\n\r\n)\r\n"; match parse_response(RESPONSE) { Ok((_, Response::Fetch(_, _))) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_opt_addresses() { let addr = b"((NIL NIL \"minutes\" \"CNRI.Reston.VA.US\") (\"John Klensin\" NIL \"KLENSIN\" \"MIT.EDU\")) "; match crate::parser::rfc3501::opt_addresses(addr) { Ok((_, _addresses)) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_opt_addresses_no_space() { let addr = br#"((NIL NIL "test" "[email protected]")(NIL NIL "test" "[email protected]"))"#; match super::opt_addresses(addr) { Ok((_, _addresses)) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_addresses() { match crate::parser::rfc3501::address(b"(\"John Klensin\" NIL \"KLENSIN\" \"MIT.EDU\") ") { Ok((_, _address)) => {} rsp => panic!("unexpected response {:?}", rsp), } // Literal non-UTF8 address match crate::parser::rfc3501::address( b"({12}\r\nJoh\xff Klensin NIL \"KLENSIN\" \"MIT.EDU\") ", ) { Ok((_, _address)) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_response_codes() { match parse_response(b"* OK [ALERT] Alert!\r\n") { Ok(( _, Response::Data { status: Status::Ok, code: Some(ResponseCode::Alert), information: Some("Alert!"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* NO [PARSE] Something\r\n") { Ok(( _, Response::Data { status: Status::No, code: Some(ResponseCode::Parse), information: Some("Something"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* OK [CAPABILITY IMAP4rev1 IDLE] Logged in\r\n") { Ok(( _, Response::Data { status: Status::Ok, code: Some(ResponseCode::Capabilities(c)), information: Some("Logged in"), }, )) => { assert_eq!(c.len(), 2); assert_eq!(c[0], Capability::Imap4rev1); assert_eq!(c[1], Capability::Atom("IDLE")); } rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* OK [CAPABILITY UIDPLUS IMAP4rev1 IDLE] Logged in\r\n") { Ok(( _, Response::Data { status: Status::Ok, code: Some(ResponseCode::Capabilities(c)), information: Some("Logged in"), }, )) => { assert_eq!(c.len(), 3); assert_eq!(c[0], Capability::Atom("UIDPLUS")); assert_eq!(c[1], Capability::Imap4rev1); assert_eq!(c[2], Capability::Atom("IDLE")); } rsp => panic!("unexpected response {:?}", rsp), } // Missing IMAP4rev1 match parse_response(b"* OK [CAPABILITY UIDPLUS IDLE] Logged in\r\n") { Ok(( _, Response::Data { status: Status::Ok, code: None, information: Some("[CAPABILITY UIDPLUS IDLE] Logged in"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* NO [BADCHARSET] error\r\n") { Ok(( _, Response::Data { status: Status::No, code: Some(ResponseCode::BadCharset(None)), information: Some("error"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* NO [BADCHARSET (utf-8 latin1)] error\r\n") { Ok(( _, Response::Data { status: Status::No, code: Some(ResponseCode::BadCharset(Some(v))), information: Some("error"), }, )) => { assert_eq!(v.len(), 2); assert_eq!(v[0], "utf-8"); assert_eq!(v[1], "latin1"); } rsp => panic!("unexpected response {:?}", rsp), } match parse_response(b"* NO [BADCHARSET ()] error\r\n") { Ok(( _, Response::Data { status: Status::No, code: None, information: Some("[BADCHARSET ()] error"), }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } } #[test] fn test_capability_data() { // Minimal capabilities assert_matches!( super::capability_data(b"CAPABILITY IMAP4rev1\r\n"), Ok((_, capabilities)) => { assert_eq!(capabilities, vec![Capability::Imap4rev1]) } ); assert_matches!( super::capability_data(b"CAPABILITY IMAP4REV1\r\n"), Ok((_, capabilities)) => { assert_eq!(capabilities, vec![Capability::Imap4rev1]) } ); assert_matches!( super::capability_data(b"CAPABILITY XPIG-LATIN IMAP4rev1 STARTTLS AUTH=GSSAPI\r\n"), Ok((_, capabilities)) => { assert_eq!(capabilities, vec![ Capability::Atom("XPIG-LATIN"), Capability::Imap4rev1, Capability::Atom("STARTTLS"), Capability::Auth("GSSAPI") ]) } ); assert_matches!( super::capability_data(b"CAPABILITY IMAP4rev1 AUTH=GSSAPI AUTH=PLAIN\r\n"), Ok((_, capabilities)) => { assert_eq!(capabilities, vec![ Capability::Imap4rev1, Capability::Auth("GSSAPI"), Capability::Auth("PLAIN") ]) } ); // Capability command must contain IMAP4rev1 assert_matches!( super::capability_data(b"CAPABILITY AUTH=GSSAPI AUTH=PLAIN\r\n"), Err(_) ); } #[test] fn test_incomplete_fetch() { match parse_response(b"* 4644 FETCH (UID ") { Err(nom::Err::Incomplete(_)) => {} rsp => panic!("should be incomplete: {:?}", rsp), } } #[test] fn test_continuation() { // regular RFC compliant match parse_response(b"+ \r\n") { Ok(( _, Response::Continue { code: None, information: None, }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } // short version, sent by yandex match parse_response(b"+\r\n") { Ok(( _, Response::Continue { code: None, information: None, }, )) => {} rsp => panic!("unexpected response {:?}", rsp), } } }
#[test]
commands.py
""" MIT License Copyright (c) 2020-2021 phenom4n4n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import asyncio import logging import re import time import types from typing import Dict, List, Optional, Set, Union from urllib.parse import quote_plus import bs4 import discord import TagScriptEngine as tse from redbot.core import commands from redbot.core.config import Config from redbot.core.utils import AsyncIter from redbot.core.utils.chat_formatting import humanize_list, inline, pagify from redbot.core.utils.menus import DEFAULT_CONTROLS, menu, start_adding_reactions from redbot.core.utils.predicates import MessagePredicate, ReactionPredicate from .abc import MixinMeta from .blocks import ContextVariableBlock, ConverterBlock from .converters import ( GlobalTagConverter, GuildTagConverter, TagConverter, TagName, TagScriptConverter, ) from .errors import TagFeedbackError from .objects import Tag TAG_GUILD_LIMIT = 250 TAG_GLOBAL_LIMIT = 250 TAG_RE = re.compile(r"(?i)(\[p\])?\btag'?s?\b") DOCS_URL = "https://phen-cogs.readthedocs.io/en/latest/" log = logging.getLogger("red.phenom4n4n.tags.commands") def _sub(match: re.Match) -> str: if match.group(1): return "[p]tag global" repl = "global " name = match.group(0) repl += name if name.istitle(): repl = repl.title() return repl def copy_doc(original: Union[commands.Command, types.FunctionType]): def decorator(overriden: Union[commands.Command, types.FunctionType]): doc = original.help if isinstance(original, commands.Command) else original.__doc__ doc = TAG_RE.sub(_sub, doc) if isinstance(overriden, commands.Command): overriden._help_override = doc else: overriden.__doc__ = doc return overriden return decorator class Commands(MixinMeta): def __init__(self): self.custom_command_engine = tse.Interpreter([ContextVariableBlock(), ConverterBlock()]) super().__init__() @staticmethod def generate_tag_list(tags: Set[Tag]) -> Dict[str, List[str]]: aliases = [] description = [] for tag in tags: aliases.extend(tag.aliases) tagscript = tag.tagscript.replace("\n", " ") if len(tagscript) > 23: tagscript = tagscript[:20] + "..." tagscript = discord.utils.escape_markdown(tagscript) description.append(f"`{tag}` - {tagscript}") return {"aliases": aliases, "description": description} @commands.command(usage="<tag_name> [args]") async def invoketag( self, ctx: commands.Context, response: Optional[bool], tag_name: str, *, args: Optional[str] = "", ): """ Manually invoke a tag with its name and arguments. Restricting this command with permissions in servers will restrict all members from invoking tags. **Examples:** `[p]invoketag searchitem trophy` `[p]invoketag donate` """ response = response or True try: _tag = await TagConverter(check_global=True).convert(ctx, tag_name) except commands.BadArgument as e: if response is True: await ctx.send(e) else: seed = {"args": tse.StringAdapter(args)} await self.process_tag(ctx, _tag, seed_variables=seed) @commands.bot_has_permissions(embed_links=True) @commands.command() async def tags(self, ctx: commands.Context): """ View all tags and aliases. This command will show global tags if run in DMs. **Example:** `[p]tags` """ guild = ctx.guild path = self.guild_tag_cache[guild.id] if guild else self.global_tag_cache if not path: return await ctx.send( "This server has no tags." if guild else "No global tags have been added." ) tags = path.keys() title = f"Tags in {guild}" if guild else "Global Tags" embed = discord.Embed(color=await ctx.embed_color(), title=title) footer = f"{len(tags)} tags" embeds = [] description = humanize_list([inline(tag) for tag in tags]) pages = list(pagify(description)) for index, page in enumerate(pages, 1): e = embed.copy() e.description = page e.set_footer(text=f"{index}/{len(pages)} | {footer}") embeds.append(e) await menu(ctx, embeds, DEFAULT_CONTROLS) @commands.guild_only() @commands.group(aliases=["customcom", "cc", "alias"]) async def tag(self, ctx: commands.Context): """ Tag management with TagScript. These commands use TagScriptEngine. Read the [TagScript documentation](https://phen-cogs.readthedocs.io/en/latest/) to learn how to use TagScript blocks. """ @commands.mod_or_permissions(manage_guild=True) @tag.command(name="add", aliases=["create", "+"]) async def tag_add( self, ctx: commands.Context, tag_name: TagName(allow_named_tags=True), *, tagscript: TagScriptConverter, ): """ Add a tag with TagScript. [Tag usage guide](https://phen-cogs.readthedocs.io/en/latest/blocks.html#usage) **Example:** `[p]tag add lawsofmotion {embed(title):Newton's Laws of motion} {embed(description): According to all known laws of aviation, there is no way a bee should be able to fly.` """ await self.create_tag(ctx, tag_name, tagscript) def validate_tag_count(self, guild: discord.Guild): tag_count = len(self.get_unique_tags(guild)) if guild: if tag_count >= TAG_GUILD_LIMIT: raise TagFeedbackError( f"This server has reached the limit of **{TAG_GUILD_LIMIT}** tags." ) else: if tag_count >= TAG_GLOBAL_LIMIT: raise TagFeedbackError( f"You have reached the limit of **{TAG_GLOBAL_LIMIT}** global tags." ) async def create_tag( self, ctx: commands.Context, tag_name: str, tagscript: str, *, global_tag: bool = False ): kwargs = {"author_id": ctx.author.id} if global_tag: guild = None tag = self.get_tag(None, tag_name, global_priority=True) else: guild = ctx.guild tag = self.get_tag(guild, tag_name, check_global=False) kwargs["guild_id"] = guild.id self.validate_tag_count(guild) if tag: tag_prefix = tag.name_prefix msg = await ctx.send( f"`{tag_name}` is already a registered {tag_prefix.lower()}. Would you like to overwrite it?" ) start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS) pred = ReactionPredicate.yes_or_no(msg, ctx.author) try: await ctx.bot.wait_for("reaction_add", check=pred, timeout=30) except asyncio.TimeoutError: return await ctx.send(f"{tag_prefix} edit cancelled.") if pred.result is False: return await ctx.send(f"{tag_prefix} edit cancelled.") await ctx.send(await tag.edit_tagscript(tagscript)) return tag = Tag(self, tag_name, tagscript, **kwargs) await ctx.send(await tag.initialize()) @commands.mod_or_permissions(manage_guild=True) @tag.command(name="alias") async def tag_alias(self, ctx: commands.Context, tag: GuildTagConverter, alias: TagName): """ Add an alias for a tag. Adding an alias to the tag will make the tag invokable using the alias or the tag name. In the example below, running `[p]donation` will invoke the `donate` tag. ​ **Example:** `[p]tag alias donate donation` """ await ctx.send(await tag.add_alias(alias)) @commands.mod_or_permissions(manage_guild=True) @tag.command(name="unalias") async def tag_unalias( self, ctx: commands.Context, tag: GuildTagConverter, alias: TagName(allow_named_tags=True) ): """ Remove an alias for a tag. ​The tag will still be able to be used under its original name. You can delete the original tag with the `[p]tag remove` command. **Example:** `tag unalias donate donation` """ await ctx.send(await tag.remove_alias(alias)) @commands.mod_or_permissions(manage_guild=True) @tag.command(name="edit", aliases=["e"]) async def tag_edit( self, ctx: commands.Context, tag: GuildTagConverter, *, tagscript: TagScriptConverter ): """ Edit a tag's TagScript. The passed tagscript will replace the tag's current tagscript. View the [TagScript docs](https://phen-cogs.readthedocs.io/en/latest/blocks.html) to find information on how to write valid tagscript. **Example:** `[p]tag edit rickroll Never gonna give you up!` """ await ctx.send(await tag.edit_tagscript(tagscript)) @commands.mod_or_permissions(manage_guild=True) @tag.command(name="remove", aliases=["delete", "-"]) async def tag_remove(self, ctx: commands.Context, tag: GuildTagConverter): """ Permanently delete a tag. If you want to remove a tag's alias, use `[p]tag unalias`. **Example:** `[p]tag remove RickRoll` """ await ctx.send(await tag.delete()) @tag.command(name="info") async def tag_info(self, ctx: commands.Context, tag: TagConverter): """ Show information about a tag. You can view meta information for a tag on this server or a global tag. If a tag on this server has the same name as a global tag, it will show the server tag. **Example:** `[p]tag info notsupport` """ await tag.send_info(ctx) @tag.command(name="raw") async def tag_raw(self, ctx: commands.Context, tag: GuildTagConverter): """ Get a tag's raw content. The sent TagScript will be escaped from Discord style formatting characters. **Example:** `[p]tag raw noping` """ await tag.send_raw_tagscript(ctx) @tag.command(name="list") async def tag_list(self, ctx: commands.Context): """ View all stored tags on this server. To view info on a specific tag, use `[p]tag info`. **Example:** `[p]tag list` """ tags = self.get_unique_tags(ctx.guild) if not tags: return await ctx.send("There are no stored tags on this server.") data = self.generate_tag_list(tags) aliases = data["aliases"] description = data["description"] e = discord.Embed(color=await ctx.embed_color()) e.set_author(name="Stored Tags", icon_url=ctx.guild.icon_url) embeds = [] pages = list(pagify("\n".join(description))) footer = f"{len(tags)} tags | {len(aliases)} aliases" for index, page in enumerate(pages, 1): embed = e.copy() embed.description = page embed.set_footer(text=f"{index}/{len(pages)} | {footer}") embeds.append(embed) await menu(ctx, embeds, DEFAULT_CONTROLS) async def doc_fetch(self): # from https://github.com/eunwoo1104/slash-bot/blob/8162fd5a0b6ac6c372486438e498a3140b5970bb/modules/sphinx_parser.py#L5 async with self.session.get(f"{DOCS_URL}genindex.html") as response: text = await response.read() soup = bs4.BeautifulSoup(text, "html.parser") self.docs = soup.findAll("a") async def doc_search(self, keyword: str) -> List[bs4.Tag]: keyword = keyword.lower() if not self.docs: await self.doc_fetch() return [x for x in self.docs if keyword in str(x).lower()] @tag.command(name="docs") async def tag_docs(self, ctx: commands.Context, keyword: str = None): """ Search the TagScript documentation for a block. https://phen-cogs.readthedocs.io/en/latest/ **Example:** `[p]tag docs embed` """ await ctx.trigger_typing() e = discord.Embed(color=await ctx.embed_color(), title="Tags Documentation") if keyword: doc_tags = await self.doc_search(keyword) description = [f"Search for: `{keyword}`"] for doc_tag in doc_tags: href = doc_tag.get("href") description.append(f"[`{doc_tag.text}`]({DOCS_URL}{href})") url = f"{DOCS_URL}search.html?q={quote_plus(keyword)}&check_keywords=yes&area=default" e.url = url embeds = [] description = "\n".join(description) for page in pagify(description): embed = e.copy() embed.description = page embeds.append(embed) await menu(ctx, embeds, DEFAULT_CONTROLS) else: e.url = DOCS_URL await ctx.send(embed=e) @commands.is_owner() @tag.command(name="run", aliases=["execute"]) async def tag_run(self, ctx: commands.Context, *, tagscript: str): """ Execute TagScript without storing. The variables and actions fields display debugging information. **Example:** `[p]tag run {#:yes,no}` """ start = time.monotonic() seed = self.get_seed_from_context(ctx) output = self.engine.process(tagscript, seed_variables=seed) end = time.monotonic() actions = output.actions content = output.body[:2000] if output.body else None await self.send_tag_response(ctx, actions, content) e = discord.Embed( color=await ctx.embed_color(), title="TagScriptEngine", description=f"Executed in **{round((end - start) * 1000, 3)}** ms", ) for page in pagify(tagscript, page_length=1024): e.add_field(name="Input", value=page, inline=False) if actions: e.add_field(name="Actions", value=actions, inline=False) if output.variables: variables = "\n".join( f"`{name}`: {type(adapter).__name__}" for name, adapter in output.variables.items() ) for page in pagify(variables, page_length=1024): e.add_field(name="Variables", value=page, inline=False) await ctx.send(embed=e) @commands.is_owner() @tag.command(name="process") async def tag_process(self, ctx: commands.Context, *, tagscript: str): """ Process a temporary Tag without storing. This differs from `[p]tag run` as it creates a fake tag and properly handles actions for all blocks. The `{args}` block is not supported. **Example:** `[p]tag run {require(Admin):You must be admin to use this tag.} Congrats on being an admin!` """ tag = Tag( self, "processed_tag", tagscript, author_id=ctx.author.id, real=False, ) await self.process_tag(ctx, tag) await ctx.tick() @commands.is_owner() @tag.group(name="global") @copy_doc(tag) async def tag_global(self, ctx: commands.Context): pass @tag_global.command(name="add", aliases=["create", "+"]) @copy_doc(tag_add) async def tag_global_add( self, ctx: commands.Context, tag_name: TagName(global_priority=True), *, tagscript: TagScriptConverter, ): await self.create_tag(ctx, tag_name, tagscript, global_tag=True) @tag_global.command(name="alias") @copy_doc(tag_alias) async def tag_global_alias( self, ctx: commands.Context, tag: GlobalTagConverter, alias: TagName ): await ctx.send(await tag.add_alias(alias)) @tag_global.command(name="unalias") @copy_doc(tag_unalias) async def tag_global_unalias( self, ctx: commands.Context, tag: GlobalTagConverter, alias: TagName(allow_named_tags=True) ): await ctx.send(await tag.remove_alias(alias)) @tag_global.command(name="edit", aliases=["e"]) @copy_doc(tag_edit) async def tag_global_edit( self, ctx: commands.Context, tag: GlobalTagConverter, *, tagscript: TagScriptConverter, ): await ctx.send(await tag.edit_tagscript(tagscript)) @tag_global.command(name="remove", aliases=["delete", "-"]) @copy_doc(tag_remove) async def tag_global_remove(self, ctx: commands.Context, tag: GlobalTagConverter): await ctx.send(await tag.delete()) @tag_global.command(name="raw") @copy_doc(tag_raw) async def tag_global_raw(self, ctx: commands.Context, tag: GlobalTagConverter): await tag.send_raw_tagscript(ctx) @tag_global.command(name="list") @copy_doc(tag_list) async def tag_global_list(self, ctx: commands.Context): tags = self.get_unique_tags() if not tags: return await ctx.send("There are no global tags.") data = self.generate_tag_list(tags) aliases = data["aliases"] description = data["description"] e = discord.Embed(color=await ctx.embed_color()) e.set_author(name="Global Tags", icon_url=ctx.me.avatar_url) embeds = [] pages = list(pagify("\n".join(description))) footer = f"{len(tags)} tags | {len(aliases)} aliases" for index, page in enumerate(pages, 1): embed = e.copy() embed.description = page embed.set_footer(text=f"{index}/{len(pages)} | {footer}") embeds.append(embed) await menu(ctx, embeds, DEFAULT_CONTROLS) @commands.is_owner() @commands.command() async def migratealias(self, ctx: commands.Context): """ Migrate the Alias cog's global and server aliases into tags. This converts all aliases created with the Alias cog into tags with command blocks. This action cannot be undone. **Example:** `[p]migratealias` """ await ctx.send(f"Are you sure you want to migrate Alias data to tags? (Y/n)") pred = MessagePredicate.yes_or_no(ctx) try: await self.bot.wait_for("message", check=pred, timeout=30) except asyncio.TimeoutError: return await ctx.send("Query timed out, not migrating alias to tags.") if pred.result is False: return await ctx.send("Migration cancelled.") migrated_guilds = 0 migrated_guild_alias = 0 alias_config = Config.get_conf( None, 8927348724, cog_name="Alias" # core cog doesn't use force_registration=True smh ) # Red can't change these values without breaking data # so while this is sus it is technically safe to use alias_config.register_global(entries=[]) all_guild_data: dict = await alias_config.all_guilds() async for guild_data in AsyncIter(all_guild_data.values(), steps=100): if not guild_data["entries"]: continue migrated_guilds += 1 for alias in guild_data["entries"]: tagscript = "{c:%s {args}}" % alias["command"] tag = Tag( self, alias["name"], tagscript, author_id=alias["creator"], guild_id=alias["guild"], uses=alias["uses"], ) await tag.initialize() migrated_guild_alias += 1 await ctx.send( f"Migrated {migrated_guild_alias} aliases from {migrated_guilds} " "servers to tags. Moving on to global aliases.." ) migrated_global_alias = 0 async for entry in AsyncIter(await alias_config.entries(), steps=50): tagscript = "{c:%s {args}}" % entry["command"] global_tag = Tag( self, entry["name"], tagscript, author_id=entry["creator"], uses=entry["uses"], ) await global_tag.initialize() migrated_global_alias += 1 await ctx.send(f"Migrated {migrated_global_alias} global aliases to tags.") def parse_cc_text(self, content: str) -> str: output = self.custom_command_engine.process(content) return output.body def convert_customcommand(self, guild_id: int, name: str, custom_command: dict) -> Tag: auth
@commands.is_owner() @commands.command(aliases=["migratecustomcommands"]) async def migratecustomcom(self, ctx: commands.Context): """ Migrate the CustomCommand cog's server commands into tags. This converts all custom commands created into tags with the command text as TagScript. Randomized commands are converted into random blocks. Commands with converters are converted into indexed args blocks. This action cannot be undone. **Example:** `[p]migratecustomcom` """ await ctx.send(f"Are you sure you want to migrate CustomCommands data to tags? (Y/n)") pred = MessagePredicate.yes_or_no(ctx) try: await self.bot.wait_for("message", check=pred, timeout=30) except asyncio.TimeoutError: return await ctx.send("Query timed out, not migrating CustomCommands to tags.") if pred.result is False: return await ctx.send("Migration cancelled.") cc_config = Config.get_conf(None, 414589031223512, cog_name="CustomCommands") migrated_guilds = 0 migrated_ccs = 0 all_guild_data: dict = await cc_config.all_guilds() async for guild_id, guild_data in AsyncIter(all_guild_data.items(), steps=100): if not guild_data["commands"]: continue migrated_guilds += 1 for name, command in guild_data["commands"].items(): if not command: continue # some keys in custom commands config are None instead of being deleted try: tag = self.convert_customcommand(guild_id, name, command) except Exception as exc: log.exception( "An exception occured while converting custom command %s (%r) from guild %s" % (name, command, guild_id), exc_info=exc, ) return await ctx.send( f"An exception occured while converting custom command `{name}` from " f"server {guild_id}. Check your logs for more details and report this to the cog author." ) await tag.initialize() migrated_ccs += 1 await ctx.send( f"Migrated {migrated_ccs} custom commands from {migrated_guilds} servers to tags." )
or_id = custom_command.get("author", {"id": None})["id"] response = custom_command["response"] if isinstance(response, str): tagscript = self.parse_cc_text(response) else: tag_lines = [] indices = [] for index, response_text in enumerate(response, 1): script = self.parse_cc_text(response_text) tag_lines.append("{=(choice.%s):%s}" % (index, script)) indices.append(index) random_block = "{#:%s}" % ",".join(str(i) for i in indices) tag_lines.append("{=(chosen):%s}" % random_block) tag_lines.append("{choice.{chosen}}") tagscript = "\n".join(tag_lines) return Tag(self, name, tagscript, guild_id=guild_id, author_id=author_id)
stock_notation_screener_search_data_simple_moving_average_trading_days_since_crossover_sma50vs200_number_days_maximum.py
""" Prime Developer Trial No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from fds.sdk.StocksAPIforDigitalPortals.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from fds.sdk.StocksAPIforDigitalPortals.exceptions import ApiAttributeError class StockNotationScreenerSearchDataSimpleMovingAverageTradingDaysSinceCrossoverSma50vs200NumberDaysMaximum(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { ('value',): { 'inclusive_maximum': 3E+2, 'inclusive_minimum': 0, }, } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'value': (float,), # noqa: E501 'inclusive': (bool,), # noqa: E501 } @cached_property def
(): return None attribute_map = { 'value': 'value', # noqa: E501 'inclusive': 'inclusive', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """StockNotationScreenerSearchDataSimpleMovingAverageTradingDaysSinceCrossoverSma50vs200NumberDaysMaximum - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) value (float): The maximum value.. [optional] # noqa: E501 inclusive (bool): Indicates whether the maximum value is included in the range or not.. [optional] if omitted the server will use the default value of True # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """StockNotationScreenerSearchDataSimpleMovingAverageTradingDaysSinceCrossoverSma50vs200NumberDaysMaximum - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) value (float): The maximum value.. [optional] # noqa: E501 inclusive (bool): Indicates whether the maximum value is included in the range or not.. [optional] if omitted the server will use the default value of True # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
discriminator
webpack.base.conf.js
/* * @Author: Kadia * @Date: 2021-08-29 22:39:25 * @LastEditors: Kadia * @LastEditTime: 2021-08-30 14:57:36 * @Connect: [email protected] */ 'use strict' const path = require('path') const utils = require('./utils') const config = require('../config') const vueLoaderConfig = require('./vue-loader.conf') function
(dir) { return path.join(__dirname, '..', dir) } module.exports = { context: path.resolve(__dirname, '../'), entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src'), } }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.sass$/, loaders: ['style', 'css', 'sass'] }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }, node: { // prevent webpack from injecting useless setImmediate polyfill because Vue // source contains it (although only uses it if it's native). setImmediate: false, // prevent webpack from injecting mocks to Node native modules // that does not make sense for the client dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty' } }
resolve
small_integer.rs
use std::backtrace::Backtrace; use anyhow::*;
use liblumen_alloc::erts::exception::InternalResult; use liblumen_alloc::erts::term::prelude::*; use liblumen_alloc::erts::Process; use super::{u8, DecodeError, Tag}; pub fn decode<'a>(process: &Process, bytes: &'a [u8]) -> InternalResult<(Term, &'a [u8])> { let (small_integer_u8, after_small_integer_bytes) = u8::decode(bytes)?; let integer = process.integer(small_integer_u8); Ok((integer, after_small_integer_bytes)) } pub fn decode_tagged_u8<'a>(bytes: &'a [u8]) -> InternalResult<(u8, &'a [u8])> { let (tag, after_tag_bytes) = Tag::decode(bytes)?; match tag { Tag::SmallInteger => u8::decode(after_tag_bytes), _ => Err(DecodeError::UnexpectedTag { tag, backtrace: Backtrace::capture(), }) .with_context(|| format!("Only {:?} tag expected", Tag::SmallInteger)) .map_err(|error| error.into()), } }
freebsdkmod.py
''' Module to manage FreeBSD kernel modules ''' import os def __virtual__(): ''' Only runs on FreeBSD systems ''' return 'kmod' if __grains__['kernel'] == 'FreeBSD' else False def _new_mods(pre_mods, post_mods): ''' Return a list of the new modules, pass an kldstat dict before running modprobe and one after modprobe has run ''' pre = set() post = set() for mod in pre_mods: pre.add(mod['module']) for mod in post_mods: post.add(mod['module']) return list(post - pre) def _rm_mods(pre_mods, post_mods): ''' Return a list of the new modules, pass an kldstat dict before running modprobe and one after modprobe has run ''' pre = set() post = set() for mod in pre_mods: pre.add(mod['module']) for mod in post_mods: post.add(mod['module']) return list(pre - post) def available(): ''' Return a list of all available kernel modules CLI Example:: salt '*' kmod.available ''' ret = [] for path in __salt__['cmd.run']('ls /boot/kernel | grep .ko$').split('\n'): bpath = os.path.basename(path) comps = bpath.split('.') if 'ko' in comps: # This is a kernel module, return it without the .ko extension ret.append('.'.join(comps[:comps.index('ko')])) return ret def check_available(mod): ''' Check to see if the specified kernel module is available CLI Example:: salt '*' kmod.check_available kvm ''' return mod in available() def
(): ''' Return a dict containing information about currently loaded modules CLI Example:: salt '*' kmod.lsmod ''' ret = [] for line in __salt__['cmd.run']('kldstat').split('\n'): comps = line.split() if not len(comps) > 2: continue if comps[0] == 'Module': continue mdat = {} mdat['module'] = comps[0] mdat['size'] = comps[1] mdat['depcount'] = comps[2] if len(comps) > 3: mdat['deps'] = comps[3].split(',') else: mdat['deps'] = [] ret.append(mdat) return ret def load(mod): ''' Load the specified kernel module CLI Example:: salt '*' kmod.load kvm ''' pre_mods = lsmod() __salt__['cmd.run_all']('kldload {0}'.format(mod)) post_mods = lsmod() return _new_mods(pre_mods, post_mods) def remove(mod): ''' Remove the specified kernel module CLI Example:: salt '*' kmod.remove kvm ''' pre_mods = lsmod() __salt__['cmd.run_all']('kldunload {0}'.format(mod)) post_mods = lsmod() return _rm_mods(pre_mods, post_mods)
lsmod
mod.rs
// ignore-tidy-filelength /*! # typeck: check phase Within the check phase of type check, we check each item one at a time (bodies of function expressions are checked as part of the containing function). Inference is used to supply types wherever they are unknown. By far the most complex case is checking the body of a function. This can be broken down into several distinct phases: - gather: creates type variables to represent the type of each local variable and pattern binding. - main: the main pass does the lion's share of the work: it determines the types of all expressions, resolves methods, checks for most invalid conditions, and so forth. In some cases, where a type is unknown, it may create a type or region variable and use that as the type of an expression. In the process of checking, various constraints will be placed on these type variables through the subtyping relationships requested through the `demand` module. The `infer` module is in charge of resolving those constraints. - regionck: after main is complete, the regionck pass goes over all types looking for regions and making sure that they did not escape into places they are not in scope. This may also influence the final assignments of the various region variables if there is some flexibility. - vtable: find and records the impls to use for each trait bound that appears on a type parameter. - writeback: writes the final types within a function body, replacing type variables with their final inferred types. These final types are written into the `tcx.node_types` table, which should *never* contain any reference to a type variable. ## Intermediate types While type checking a function, the intermediate types for the expressions, blocks, and so forth contained within the function are stored in `fcx.node_types` and `fcx.node_substs`. These types may contain unresolved type variables. After type checking is complete, the functions in the writeback module are used to take the types from this table, resolve them, and then write them into their permanent home in the type context `tcx`. This means that during inferencing you should use `fcx.write_ty()` and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of nodes within the function. The types of top-level items, which never contain unbound type variables, are stored directly into the `tcx` tables. N.B., a type variable is not the same thing as a type parameter. A type variable is rather an "instance" of a type parameter: that is, given a generic function `fn foo<T>(t: T)`: while checking the function `foo`, the type `ty_param(0)` refers to the type `T`, which is treated in abstract. When `foo()` is called, however, `T` will be substituted for a fresh type variable `N`. This variable will eventually be resolved to some concrete type (which might itself be type parameter). */ pub mod _match; mod autoderef; mod callee; mod cast; mod closure; pub mod coercion; mod compare_method; pub mod demand; pub mod dropck; mod expr; mod generator_interior; pub mod intrinsic; pub mod method; mod op; mod pat; mod regionck; mod upvar; mod wfcheck; pub mod writeback; use crate::astconv::{AstConv, PathSeg}; use crate::middle::lang_items; use crate::namespace::Namespace; use rustc::hir::map::Map; use rustc::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; use rustc::infer::error_reporting::TypeAnnotationNeeded::E0282; use rustc::infer::opaque_types::OpaqueTypeDecl; use rustc::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKind}; use rustc::infer::{self, InferCtxt, InferOk, InferResult}; use rustc::middle::region; use rustc::mir::interpret::ConstValue; use rustc::session::parse::feature_err; use rustc::traits::error_reporting::recursive_type_with_infinite_size_error; use rustc::traits::{self, ObligationCause, ObligationCauseCode, TraitEngine}; use rustc::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCast, }; use rustc::ty::fold::{TypeFoldable, TypeFolder}; use rustc::ty::layout::VariantIdx; use rustc::ty::query::Providers; use rustc::ty::subst::{GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSelfTy, UserSubsts}; use rustc::ty::util::{Discr, IntTypeExt, Representability}; use rustc::ty::{ self, AdtKind, CanonicalUserType, Const, GenericParamDefKind, RegionKind, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, UserType, }; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, DiagnosticId}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LOCAL_CRATE}; use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::itemlikevisit::ItemLikeVisitor; use rustc_hir::{ExprKind, GenericArg, HirIdMap, Item, ItemKind, Node, PatKind, QPath}; use rustc_index::vec::Idx; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::{original_sp, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{self, BytePos, MultiSpan, Span}; use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr; use syntax::util::parser::ExprPrecedence; use std::cell::{Cell, Ref, RefCell, RefMut}; use std::cmp; use std::collections::hash_map::Entry; use std::iter; use std::mem::replace; use std::ops::{self, Deref}; use std::slice; use crate::lint; use crate::require_c_abi_if_c_variadic; use crate::session::config::EntryFnType; use crate::session::Session; use crate::util::common::{indenter, ErrorReported}; use crate::TypeAndSubsts; use self::autoderef::Autoderef; use self::callee::DeferredCallResolution; use self::coercion::{CoerceMany, DynamicCoerceMany}; use self::compare_method::{compare_const_impl, compare_impl_method, compare_ty_impl}; use self::method::{MethodCallee, SelfSource}; pub use self::Expectation::*; use self::TupleArgumentsFlag::*; #[macro_export] macro_rules! type_error_struct { ($session:expr, $span:expr, $typ:expr, $code:ident, $($message:tt)*) => ({ if $typ.references_error() { $session.diagnostic().struct_dummy() } else { rustc_errors::struct_span_err!($session, $span, $code, $($message)*) } }) } /// The type of a local binding, including the revealed type for anon types. #[derive(Copy, Clone, Debug)] pub struct LocalTy<'tcx> { decl_ty: Ty<'tcx>, revealed_ty: Ty<'tcx>, } /// A wrapper for `InferCtxt`'s `in_progress_tables` field. #[derive(Copy, Clone)] struct MaybeInProgressTables<'a, 'tcx> { maybe_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>, } impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> { fn borrow(self) -> Ref<'a, ty::TypeckTables<'tcx>> { match self.maybe_tables { Some(tables) => tables.borrow(), None => bug!("MaybeInProgressTables: inh/fcx.tables.borrow() with no tables"), } } fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> { match self.maybe_tables { Some(tables) => tables.borrow_mut(), None => bug!("MaybeInProgressTables: inh/fcx.tables.borrow_mut() with no tables"), } } } /// Closures defined within the function. For example: /// /// fn foo() { /// bar(move|| { ... }) /// } /// /// Here, the function `foo()` and the closure passed to /// `bar()` will each have their own `FnCtxt`, but they will /// share the inherited fields. pub struct Inherited<'a, 'tcx> { infcx: InferCtxt<'a, 'tcx>, tables: MaybeInProgressTables<'a, 'tcx>, locals: RefCell<HirIdMap<LocalTy<'tcx>>>, fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>, // Some additional `Sized` obligations badly affect type inference. // These obligations are added in a later stage of typeck. deferred_sized_obligations: RefCell<Vec<(Ty<'tcx>, Span, traits::ObligationCauseCode<'tcx>)>>, // When we process a call like `c()` where `c` is a closure type, // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or // `FnOnce` closure. In that case, we defer full resolution of the // call until upvar inference can kick in and make the // decision. We keep these deferred resolutions grouped by the // def-id of the closure, so that once we decide, we can easily go // back and process them. deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'tcx>>>>, deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>, deferred_generator_interiors: RefCell<Vec<(hir::BodyId, Ty<'tcx>, hir::GeneratorKind)>>, // Opaque types found in explicit return types and their // associated fresh inference variable. Writeback resolves these // variables to get the concrete type, which can be used to // 'de-opaque' OpaqueTypeDecl, after typeck is done with all functions. opaque_types: RefCell<DefIdMap<OpaqueTypeDecl<'tcx>>>, /// A map from inference variables created from opaque /// type instantiations (`ty::Infer`) to the actual opaque /// type (`ty::Opaque`). Used during fallback to map unconstrained /// opaque type inference variables to their corresponding /// opaque type. opaque_types_vars: RefCell<FxHashMap<Ty<'tcx>, Ty<'tcx>>>, /// Each type parameter has an implicit region bound that /// indicates it must outlive at least the function body (the user /// may specify stronger requirements). This field indicates the /// region of the callee. If it is `None`, then the parameter /// environment is for an item or something where the "callee" is /// not clear. implicit_region_bound: Option<ty::Region<'tcx>>, body_id: Option<hir::BodyId>, } impl<'a, 'tcx> Deref for Inherited<'a, 'tcx> { type Target = InferCtxt<'a, 'tcx>; fn deref(&self) -> &Self::Target { &self.infcx } } /// When type-checking an expression, we propagate downward /// whatever type hint we are able in the form of an `Expectation`. #[derive(Copy, Clone, Debug)] pub enum Expectation<'tcx> { /// We know nothing about what type this expression should have. NoExpectation, /// This expression should have the type given (or some subtype). ExpectHasType(Ty<'tcx>), /// This expression will be cast to the `Ty`. ExpectCastableToType(Ty<'tcx>), /// This rvalue expression will be wrapped in `&` or `Box` and coerced /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`. ExpectRvalueLikeUnsized(Ty<'tcx>), } impl<'a, 'tcx> Expectation<'tcx> { // Disregard "castable to" expectations because they // can lead us astray. Consider for example `if cond // {22} else {c} as u8` -- if we propagate the // "castable to u8" constraint to 22, it will pick the // type 22u8, which is overly constrained (c might not // be a u8). In effect, the problem is that the // "castable to" expectation is not the tightest thing // we can say, so we want to drop it in this case. // The tightest thing we can say is "must unify with // else branch". Note that in the case of a "has type" // constraint, this limitation does not hold. // If the expected type is just a type variable, then don't use // an expected type. Otherwise, we might write parts of the type // when checking the 'then' block which are incompatible with the // 'else' branch. fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'tcx>) -> Expectation<'tcx> { match *self { ExpectHasType(ety) => { let ety = fcx.shallow_resolve(ety); if !ety.is_ty_var() { ExpectHasType(ety) } else { NoExpectation } } ExpectRvalueLikeUnsized(ety) => ExpectRvalueLikeUnsized(ety), _ => NoExpectation, } } /// Provides an expectation for an rvalue expression given an *optional* /// hint, which is not required for type safety (the resulting type might /// be checked higher up, as is the case with `&expr` and `box expr`), but /// is useful in determining the concrete type. /// /// The primary use case is where the expected type is a fat pointer, /// like `&[isize]`. For example, consider the following statement: /// /// let x: &[isize] = &[1, 2, 3]; /// /// In this case, the expected type for the `&[1, 2, 3]` expression is /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the /// expectation `ExpectHasType([isize])`, that would be too strong -- /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`. /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced /// to the type `&[isize]`. Therefore, we propagate this more limited hint, /// which still is useful, because it informs integer literals and the like. /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169 /// for examples of where this comes up,. fn rvalue_hint(fcx: &FnCtxt<'a, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> { match fcx.tcx.struct_tail_without_normalization(ty).kind { ty::Slice(_) | ty::Str | ty::Dynamic(..) => ExpectRvalueLikeUnsized(ty), _ => ExpectHasType(ty), } } // Resolves `expected` by a single level if it is a variable. If // there is no expected type or resolution is not possible (e.g., // no constraints yet present), just returns `None`. fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) -> Expectation<'tcx> { match self { NoExpectation => NoExpectation, ExpectCastableToType(t) => ExpectCastableToType(fcx.resolve_vars_if_possible(&t)), ExpectHasType(t) => ExpectHasType(fcx.resolve_vars_if_possible(&t)), ExpectRvalueLikeUnsized(t) => ExpectRvalueLikeUnsized(fcx.resolve_vars_if_possible(&t)), } } fn to_option(self, fcx: &FnCtxt<'a, 'tcx>) -> Option<Ty<'tcx>> { match self.resolve(fcx) { NoExpectation => None, ExpectCastableToType(ty) | ExpectHasType(ty) | ExpectRvalueLikeUnsized(ty) => Some(ty), } } /// It sometimes happens that we want to turn an expectation into /// a **hard constraint** (i.e., something that must be satisfied /// for the program to type-check). `only_has_type` will return /// such a constraint, if it exists. fn only_has_type(self, fcx: &FnCtxt<'a, 'tcx>) -> Option<Ty<'tcx>> { match self.resolve(fcx) { ExpectHasType(ty) => Some(ty), NoExpectation | ExpectCastableToType(_) | ExpectRvalueLikeUnsized(_) => None, } } /// Like `only_has_type`, but instead of returning `None` if no /// hard constraint exists, creates a fresh type variable. fn coercion_target_type(self, fcx: &FnCtxt<'a, 'tcx>, span: Span) -> Ty<'tcx> { self.only_has_type(fcx).unwrap_or_else(|| { fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span }) }) } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Needs { MutPlace, None, } impl Needs { fn maybe_mut_place(m: hir::Mutability) -> Self { match m { hir::Mutability::Mut => Needs::MutPlace, hir::Mutability::Not => Needs::None, } } } #[derive(Copy, Clone)] pub struct UnsafetyState { pub def: hir::HirId, pub unsafety: hir::Unsafety, pub unsafe_push_count: u32, from_fn: bool, } impl UnsafetyState { pub fn function(unsafety: hir::Unsafety, def: hir::HirId) -> UnsafetyState { UnsafetyState { def, unsafety, unsafe_push_count: 0, from_fn: true } } pub fn recurse(&mut self, blk: &hir::Block<'_>) -> UnsafetyState { use hir::BlockCheckMode; match self.unsafety { // If this unsafe, then if the outer function was already marked as // unsafe we shouldn't attribute the unsafe'ness to the block. This // way the block can be warned about instead of ignoring this // extraneous block (functions are never warned about). hir::Unsafety::Unsafe if self.from_fn => *self, unsafety => { let (unsafety, def, count) = match blk.rules { BlockCheckMode::PushUnsafeBlock(..) => { (unsafety, blk.hir_id, self.unsafe_push_count.checked_add(1).unwrap()) } BlockCheckMode::PopUnsafeBlock(..) => { (unsafety, blk.hir_id, self.unsafe_push_count.checked_sub(1).unwrap()) } BlockCheckMode::UnsafeBlock(..) => { (hir::Unsafety::Unsafe, blk.hir_id, self.unsafe_push_count) } BlockCheckMode::DefaultBlock => (unsafety, self.def, self.unsafe_push_count), }; UnsafetyState { def, unsafety, unsafe_push_count: count, from_fn: false } } } } } #[derive(Debug, Copy, Clone)] pub enum PlaceOp { Deref, Index, } /// Tracks whether executing a node may exit normally (versus /// return/break/panic, which "diverge", leaving dead code in their /// wake). Tracked semi-automatically (through type variables marked /// as diverging), with some manual adjustments for control-flow /// primitives (approximating a CFG). #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Diverges { /// Potentially unknown, some cases converge, /// others require a CFG to determine them. Maybe, /// Definitely known to diverge and therefore /// not reach the next sibling or its parent. Always { /// The `Span` points to the expression /// that caused us to diverge /// (e.g. `return`, `break`, etc). span: Span, /// In some cases (e.g. a `match` expression /// where all arms diverge), we may be /// able to provide a more informative /// message to the user. /// If this is `None`, a default messsage /// will be generated, which is suitable /// for most cases. custom_note: Option<&'static str>, }, /// Same as `Always` but with a reachability /// warning already emitted. WarnedAlways, } // Convenience impls for combining `Diverges`. impl ops::BitAnd for Diverges { type Output = Self; fn bitand(self, other: Self) -> Self { cmp::min(self, other) } } impl ops::BitOr for Diverges { type Output = Self; fn bitor(self, other: Self) -> Self { cmp::max(self, other) } } impl ops::BitAndAssign for Diverges { fn bitand_assign(&mut self, other: Self) { *self = *self & other; } } impl ops::BitOrAssign for Diverges { fn bitor_assign(&mut self, other: Self) { *self = *self | other; } } impl Diverges { /// Creates a `Diverges::Always` with the provided `span` and the default note message. fn always(span: Span) -> Diverges { Diverges::Always { span, custom_note: None } } fn is_always(self) -> bool { // Enum comparison ignores the // contents of fields, so we just // fill them in with garbage here. self >= Diverges::Always { span: DUMMY_SP, custom_note: None } } } pub struct BreakableCtxt<'tcx> { may_break: bool, // this is `null` for loops where break with a value is illegal, // such as `while`, `for`, and `while let` coerce: Option<DynamicCoerceMany<'tcx>>, } pub struct EnclosingBreakables<'tcx> { stack: Vec<BreakableCtxt<'tcx>>, by_id: HirIdMap<usize>, } impl<'tcx> EnclosingBreakables<'tcx> { fn find_breakable(&mut self, target_id: hir::HirId) -> &mut BreakableCtxt<'tcx> { self.opt_find_breakable(target_id).unwrap_or_else(|| { bug!("could not find enclosing breakable with id {}", target_id); }) } fn opt_find_breakable(&mut self, target_id: hir::HirId) -> Option<&mut BreakableCtxt<'tcx>> { match self.by_id.get(&target_id) { Some(ix) => Some(&mut self.stack[*ix]), None => None, } } } pub struct FnCtxt<'a, 'tcx> { body_id: hir::HirId, /// The parameter environment used for proving trait obligations /// in this function. This can change when we descend into /// closures (as they bring new things into scope), hence it is /// not part of `Inherited` (as of the time of this writing, /// closures do not yet change the environment, but they will /// eventually). param_env: ty::ParamEnv<'tcx>, /// Number of errors that had been reported when we started /// checking this function. On exit, if we find that *more* errors /// have been reported, we will skip regionck and other work that /// expects the types within the function to be consistent. // FIXME(matthewjasper) This should not exist, and it's not correct // if type checking is run in parallel. err_count_on_creation: usize, /// If `Some`, this stores coercion information for returned /// expressions. If `None`, this is in a context where return is /// inappropriate, such as a const expression. /// /// This is a `RefCell<DynamicCoerceMany>`, which means that we /// can track all the return expressions and then use them to /// compute a useful coercion from the set, similar to a match /// expression or other branching context. You can use methods /// like `expected_ty` to access the declared return type (if /// any). ret_coercion: Option<RefCell<DynamicCoerceMany<'tcx>>>, /// First span of a return site that we find. Used in error messages. ret_coercion_span: RefCell<Option<Span>>, yield_ty: Option<Ty<'tcx>>, ps: RefCell<UnsafetyState>, /// Whether the last checked node generates a divergence (e.g., /// `return` will set this to `Always`). In general, when entering /// an expression or other node in the tree, the initial value /// indicates whether prior parts of the containing expression may /// have diverged. It is then typically set to `Maybe` (and the /// old value remembered) for processing the subparts of the /// current expression. As each subpart is processed, they may set /// the flag to `Always`, etc. Finally, at the end, we take the /// result and "union" it with the original value, so that when we /// return the flag indicates if any subpart of the parent /// expression (up to and including this part) has diverged. So, /// if you read it after evaluating a subexpression `X`, the value /// you get indicates whether any subexpression that was /// evaluating up to and including `X` diverged. /// /// We currently use this flag only for diagnostic purposes: /// /// - To warn about unreachable code: if, after processing a /// sub-expression but before we have applied the effects of the /// current node, we see that the flag is set to `Always`, we /// can issue a warning. This corresponds to something like /// `foo(return)`; we warn on the `foo()` expression. (We then /// update the flag to `WarnedAlways` to suppress duplicate /// reports.) Similarly, if we traverse to a fresh statement (or /// tail expression) from a `Always` setting, we will issue a /// warning. This corresponds to something like `{return; /// foo();}` or `{return; 22}`, where we would warn on the /// `foo()` or `22`. /// /// An expression represents dead code if, after checking it, /// the diverges flag is set to something other than `Maybe`. diverges: Cell<Diverges>, /// Whether any child nodes have any type errors. has_errors: Cell<bool>, enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>, inh: &'a Inherited<'a, 'tcx>, } impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> { type Target = Inherited<'a, 'tcx>; fn deref(&self) -> &Self::Target { &self.inh } } /// Helper type of a temporary returned by `Inherited::build(...)`. /// Necessary because we can't write the following bound: /// `F: for<'b, 'tcx> where 'tcx FnOnce(Inherited<'b, 'tcx>)`. pub struct InheritedBuilder<'tcx> { infcx: infer::InferCtxtBuilder<'tcx>, def_id: DefId, } impl Inherited<'_, 'tcx> { pub fn build(tcx: TyCtxt<'tcx>, def_id: DefId) -> InheritedBuilder<'tcx> { let hir_id_root = if def_id.is_local() { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); DefId::local(hir_id.owner) } else { def_id }; InheritedBuilder { infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(hir_id_root), def_id, } } } impl<'tcx> InheritedBuilder<'tcx> { fn enter<F, R>(&mut self, f: F) -> R where F: for<'a> FnOnce(Inherited<'a, 'tcx>) -> R, { let def_id = self.def_id; self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id))) } } impl Inherited<'a, 'tcx> { fn new(infcx: InferCtxt<'a, 'tcx>, def_id: DefId) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir().as_local_hir_id(def_id); let body_id = item_id.and_then(|id| tcx.hir().maybe_body_owned_by(id)); let implicit_region_bound = body_id.map(|body_id| { let body = tcx.hir().body(body_id); tcx.mk_region(ty::ReScope(region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite, })) }); Inherited { tables: MaybeInProgressTables { maybe_tables: infcx.in_progress_tables }, infcx, fulfillment_cx: RefCell::new(TraitEngine::new(tcx)), locals: RefCell::new(Default::default()), deferred_sized_obligations: RefCell::new(Vec::new()), deferred_call_resolutions: RefCell::new(Default::default()), deferred_cast_checks: RefCell::new(Vec::new()), deferred_generator_interiors: RefCell::new(Vec::new()), opaque_types: RefCell::new(Default::default()), opaque_types_vars: RefCell::new(Default::default()), implicit_region_bound, body_id, } } fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) { debug!("register_predicate({:?})", obligation); if obligation.has_escaping_bound_vars() { span_bug!(obligation.cause.span, "escaping bound vars in predicate {:?}", obligation); } self.fulfillment_cx.borrow_mut().register_predicate_obligation(self, obligation); } fn register_predicates<I>(&self, obligations: I) where I: IntoIterator<Item = traits::PredicateObligation<'tcx>>, { for obligation in obligations { self.register_predicate(obligation); } } fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T { self.register_predicates(infer_ok.obligations); infer_ok.value } fn normalize_associated_types_in<T>( &self, span: Span, body_id: hir::HirId, param_env: ty::ParamEnv<'tcx>, value: &T, ) -> T where T: TypeFoldable<'tcx>, { let ok = self.partially_normalize_associated_types_in(span, body_id, param_env, value); self.register_infer_ok_obligations(ok) } } struct CheckItemTypesVisitor<'tcx> { tcx: TyCtxt<'tcx>, } impl ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'tcx> { fn visit_item(&mut self, i: &'tcx hir::Item<'tcx>) { check_item_type(self.tcx, i); } fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem<'tcx>) {} fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem<'tcx>) {} } pub fn check_wf_new(tcx: TyCtxt<'_>) { let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); tcx.hir().krate().par_visit_all_item_likes(&mut visit); } fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) { tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckItemTypesVisitor { tcx }); } fn typeck_item_bodies(tcx: TyCtxt<'_>, crate_num: CrateNum) { debug_assert!(crate_num == LOCAL_CRATE); tcx.par_body_owners(|body_owner_def_id| { tcx.ensure().typeck_tables_of(body_owner_def_id); }); } fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_item_well_formed(tcx, def_id); } fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_trait_item(tcx, def_id); } fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) { wfcheck::check_impl_item(tcx, def_id); } pub fn provide(providers: &mut Providers<'_>) { method::provide(providers); *providers = Providers { typeck_item_bodies, typeck_tables_of, diagnostic_only_typeck_tables_of, has_typeck_tables, adt_destructor, used_trait_imports, check_item_well_formed, check_trait_item_well_formed, check_impl_item_well_formed, check_mod_item_types, ..*providers }; } fn adt_destructor(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::Destructor> { tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl) } /// If this `DefId` is a "primary tables entry", returns /// `Some((body_id, header, decl))` with information about /// it's body-id, fn-header and fn-decl (if any). Otherwise, /// returns `None`. /// /// If this function returns `Some`, then `typeck_tables(def_id)` will /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or /// may not succeed. In some cases where this function returns `None` /// (notably closures), `typeck_tables(def_id)` would wind up /// redirecting to the owning function. fn primary_body_of( tcx: TyCtxt<'_>, id: hir::HirId, ) -> Option<(hir::BodyId, Option<&hir::Ty<'_>>, Option<&hir::FnHeader>, Option<&hir::FnDecl<'_>>)> { match tcx.hir().get(id) { Node::Item(item) => match item.kind { hir::ItemKind::Const(ref ty, body) | hir::ItemKind::Static(ref ty, _, body) => { Some((body, Some(ty), None, None)) } hir::ItemKind::Fn(ref sig, .., body) => { Some((body, None, Some(&sig.header), Some(&sig.decl))) } _ => None, }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Const(ref ty, Some(body)) => Some((body, Some(ty), None, None)), hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => { Some((body, None, Some(&sig.header), Some(&sig.decl))) } _ => None, }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Const(ref ty, body) => Some((body, Some(ty), None, None)), hir::ImplItemKind::Method(ref sig, body) => { Some((body, None, Some(&sig.header), Some(&sig.decl))) } _ => None, }, Node::AnonConst(constant) => Some((constant.body, None, None, None)), _ => None, } } fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { return tcx.has_typeck_tables(outer_def_id); } let id = tcx.hir().as_local_hir_id(def_id).unwrap(); primary_body_of(tcx, id).is_some() } fn used_trait_imports(tcx: TyCtxt<'_>, def_id: DefId) -> &DefIdSet { &*tcx.typeck_tables_of(def_id).used_trait_imports } /// Inspects the substs of opaque types, replacing any inference variables /// with proper generic parameter from the identity substs. /// /// This is run after we normalize the function signature, to fix any inference /// variables introduced by the projection of associated types. This ensures that /// any opaque types used in the signature continue to refer to generic parameters, /// allowing them to be considered for defining uses in the function body /// /// For example, consider this code. /// /// ```rust /// trait MyTrait { /// type MyItem; /// fn use_it(self) -> Self::MyItem /// } /// impl<T, I> MyTrait for T where T: Iterator<Item = I> { /// type MyItem = impl Iterator<Item = I>; /// fn use_it(self) -> Self::MyItem { /// self /// } /// } /// ``` /// /// When we normalize the signature of `use_it` from the impl block, /// we will normalize `Self::MyItem` to the opaque type `impl Iterator<Item = I>` /// However, this projection result may contain inference variables, due /// to the way that projection works. We didn't have any inference variables /// in the signature to begin with - leaving them in will cause us to incorrectly /// conclude that we don't have a defining use of `MyItem`. By mapping inference /// variables back to the actual generic parameters, we will correctly see that /// we have a defining use of `MyItem` fn fixup_opaque_types<'tcx, T>(tcx: TyCtxt<'tcx>, val: &T) -> T where T: TypeFoldable<'tcx>, { struct FixupFolder<'tcx> { tcx: TyCtxt<'tcx>, } impl<'tcx> TypeFolder<'tcx> for FixupFolder<'tcx> { fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { self.tcx } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { match ty.kind { ty::Opaque(def_id, substs) => { debug!("fixup_opaque_types: found type {:?}", ty); // Here, we replace any inference variables that occur within // the substs of an opaque type. By definition, any type occuring // in the substs has a corresponding generic parameter, which is what // we replace it with. // This replacement is only run on the function signature, so any // inference variables that we come across must be the rust of projection // (there's no other way for a user to get inference variables into // a function signature). if ty.needs_infer() { let new_substs = InternalSubsts::for_item(self.tcx, def_id, |param, _| { let old_param = substs[param.index as usize]; match old_param.unpack() { GenericArgKind::Type(old_ty) => { if let ty::Infer(_) = old_ty.kind { // Replace inference type with a generic parameter self.tcx.mk_param_from_def(param) } else { old_param.fold_with(self) } } GenericArgKind::Const(old_const) => { if let ty::ConstKind::Infer(_) = old_const.val { // This should never happen - we currently do not support // 'const projections', e.g.: // `impl<T: SomeTrait> MyTrait for T where <T as SomeTrait>::MyConst == 25` // which should be the only way for us to end up with a const inference // variable after projection. If Rust ever gains support for this kind // of projection, this should *probably* be changed to // `self.tcx.mk_param_from_def(param)` bug!( "Found infer const: `{:?}` in opaque type: {:?}", old_const, ty ); } else { old_param.fold_with(self) } } GenericArgKind::Lifetime(old_region) => { if let RegionKind::ReVar(_) = old_region { self.tcx.mk_param_from_def(param) } else { old_param.fold_with(self) } } } }); let new_ty = self.tcx.mk_opaque(def_id, new_substs); debug!("fixup_opaque_types: new type: {:?}", new_ty); new_ty } else { ty } } _ => ty.super_fold_with(self), } } } debug!("fixup_opaque_types({:?})", val); val.fold_with(&mut FixupFolder { tcx }) } fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &ty::TypeckTables<'tcx> { let fallback = move || tcx.type_of(def_id); typeck_tables_of_with_fallback(tcx, def_id, fallback) } /// Used only to get `TypeckTables` for type inference during error recovery. /// Currently only used for type inference of `static`s and `const`s to avoid type cycle errors. fn diagnostic_only_typeck_tables_of<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, ) -> &ty::TypeckTables<'tcx> { assert!(def_id.is_local()); let fallback = move || { let span = tcx.hir().span(tcx.hir().as_local_hir_id(def_id).unwrap()); tcx.sess.delay_span_bug(span, "diagnostic only typeck table used"); tcx.types.err }; typeck_tables_of_with_fallback(tcx, def_id, fallback) } fn typeck_tables_of_with_fallback<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, fallback: impl Fn() -> Ty<'tcx> + 'tcx, ) -> &'tcx ty::TypeckTables<'tcx> { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { return tcx.typeck_tables_of(outer_def_id); } let id = tcx.hir().as_local_hir_id(def_id).unwrap(); let span = tcx.hir().span(id); // Figure out what primary body this item has. let (body_id, body_ty, fn_header, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| { span_bug!(span, "can't type-check body of {:?}", def_id); }); let body = tcx.hir().body(body_id); let tables = Inherited::build(tcx, def_id).enter(|inh| { let param_env = tcx.param_env(def_id); let fcx = if let (Some(header), Some(decl)) = (fn_header, fn_decl) { let fn_sig = if crate::collect::get_infer_ret_ty(&decl.output).is_some() { let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id); AstConv::ty_of_fn(&fcx, header.unsafety, header.abi, decl, &[], None) } else { tcx.fn_sig(def_id) }; check_abi(tcx, span, fn_sig.abi()); // Compute the fty from point of view of inside the fn. let fn_sig = tcx.liberate_late_bound_regions(def_id, &fn_sig); let fn_sig = inh.normalize_associated_types_in( body.value.span, body_id.hir_id, param_env, &fn_sig, ); let fn_sig = fixup_opaque_types(tcx, &fn_sig); let fcx = check_fn(&inh, param_env, fn_sig, decl, id, body, None).0; fcx } else { let fcx = FnCtxt::new(&inh, param_env, body.value.hir_id); let expected_type = body_ty .and_then(|ty| match ty.kind { hir::TyKind::Infer => Some(AstConv::ast_ty_to_ty(&fcx, ty)), _ => None, }) .unwrap_or_else(fallback); let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type); fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized); let revealed_ty = if tcx.features().impl_trait_in_bindings { fcx.instantiate_opaque_types_from_value(id, &expected_type, body.value.span) } else { expected_type }; // Gather locals in statics (because of block expressions). GatherLocalsVisitor { fcx: &fcx, parent_id: id }.visit_body(body); fcx.check_expr_coercable_to_type(&body.value, revealed_ty); fcx.write_ty(id, revealed_ty); fcx }; // All type checking constraints were added, try to fallback unsolved variables. fcx.select_obligations_where_possible(false, |_| {}); let mut fallback_has_occurred = false; // We do fallback in two passes, to try to generate // better error messages. // The first time, we do *not* replace opaque types. for ty in &fcx.unsolved_variables() { fallback_has_occurred |= fcx.fallback_if_possible(ty, FallbackMode::NoOpaque); } // We now see if we can make progress. This might // cause us to unify inference variables for opaque types, // since we may have unified some other type variables // during the first phase of fallback. // This means that we only replace inference variables with their underlying // opaque types as a last resort. // // In code like this: // // ```rust // type MyType = impl Copy; // fn produce() -> MyType { true } // fn bad_produce() -> MyType { panic!() } // ``` // // we want to unify the opaque inference variable in `bad_produce` // with the diverging fallback for `panic!` (e.g. `()` or `!`). // This will produce a nice error message about conflicting concrete // types for `MyType`. // // If we had tried to fallback the opaque inference variable to `MyType`, // we will generate a confusing type-check error that does not explicitly // refer to opaque types. fcx.select_obligations_where_possible(fallback_has_occurred, |_| {}); // We now run fallback again, but this time we allow it to replace // unconstrained opaque type variables, in addition to performing // other kinds of fallback. for ty in &fcx.unsolved_variables() { fallback_has_occurred |= fcx.fallback_if_possible(ty, FallbackMode::All); } // See if we can make any more progress. fcx.select_obligations_where_possible(fallback_has_occurred, |_| {}); // Even though coercion casts provide type hints, we check casts after fallback for // backwards compatibility. This makes fallback a stronger type hint than a cast coercion. fcx.check_casts(); // Closure and generator analysis may run after fallback // because they don't constrain other type variables. fcx.closure_analyze(body); assert!(fcx.deferred_call_resolutions.borrow().is_empty()); fcx.resolve_generator_interiors(def_id); for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) { let ty = fcx.normalize_ty(span, ty); fcx.require_type_is_sized(ty, span, code); } fcx.select_all_obligations_or_error(); if fn_decl.is_some() { fcx.regionck_fn(id, body); } else { fcx.regionck_expr(body); } fcx.resolve_type_vars_in_body(body) }); // Consistency check our TypeckTables instance can hold all ItemLocalIds // it will need to hold. assert_eq!(tables.local_id_root, Some(DefId::local(id.owner))); tables } fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { if !tcx.sess.target.target.is_abi_supported(abi) { struct_span_err!( tcx.sess, span, E0570, "The ABI `{}` is not supported for the current target", abi ) .emit() } } struct GatherLocalsVisitor<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, parent_id: hir::HirId, } impl<'a, 'tcx> GatherLocalsVisitor<'a, 'tcx> { fn assign(&mut self, span: Span, nid: hir::HirId, ty_opt: Option<LocalTy<'tcx>>) -> Ty<'tcx> { match ty_opt { None => { // infer the variable's type let var_ty = self.fcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span, }); self.fcx .locals .borrow_mut() .insert(nid, LocalTy { decl_ty: var_ty, revealed_ty: var_ty }); var_ty } Some(typ) => { // take type that the user specified self.fcx.locals.borrow_mut().insert(nid, typ); typ.revealed_ty } } } } impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { type Map = Map<'tcx>; fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> { NestedVisitorMap::None } // Add explicitly-declared locals. fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { let local_ty = match local.ty { Some(ref ty) => { let o_ty = self.fcx.to_ty(&ty); let revealed_ty = if self.fcx.tcx.features().impl_trait_in_bindings { self.fcx.instantiate_opaque_types_from_value(self.parent_id, &o_ty, ty.span) } else { o_ty }; let c_ty = self .fcx .inh .infcx .canonicalize_user_type_annotation(&UserType::Ty(revealed_ty)); debug!( "visit_local: ty.hir_id={:?} o_ty={:?} revealed_ty={:?} c_ty={:?}", ty.hir_id, o_ty, revealed_ty, c_ty ); self.fcx.tables.borrow_mut().user_provided_types_mut().insert(ty.hir_id, c_ty); Some(LocalTy { decl_ty: o_ty, revealed_ty }) } None => None, }; self.assign(local.span, local.hir_id, local_ty); debug!( "local variable {:?} is assigned type {}", local.pat, self.fcx .ty_to_string(self.fcx.locals.borrow().get(&local.hir_id).unwrap().clone().decl_ty) ); intravisit::walk_local(self, local); } // Add pattern bindings. fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { if let PatKind::Binding(_, _, ident, _) = p.kind { let var_ty = self.assign(p.span, p.hir_id, None); if !self.fcx.tcx.features().unsized_locals { self.fcx.require_type_is_sized(var_ty, p.span, traits::VariableType(p.hir_id)); } debug!( "pattern binding {} is assigned to {} with type {:?}", ident, self.fcx .ty_to_string(self.fcx.locals.borrow().get(&p.hir_id).unwrap().clone().decl_ty), var_ty ); } intravisit::walk_pat(self, p); } // Don't descend into the bodies of nested closures fn visit_fn( &mut self, _: intravisit::FnKind<'tcx>, _: &'tcx hir::FnDecl<'tcx>, _: hir::BodyId, _: Span, _: hir::HirId, ) { } } /// When `check_fn` is invoked on a generator (i.e., a body that /// includes yield), it returns back some information about the yield /// points. struct GeneratorTypes<'tcx> { /// Type of value that is yielded. yield_ty: Ty<'tcx>, /// Types that are captured (see `GeneratorInterior` for more). interior: Ty<'tcx>, /// Indicates if the generator is movable or static (immovable). movability: hir::Movability, } /// Helper used for fns and closures. Does the grungy work of checking a function /// body and returns the function context used for that purpose, since in the case of a fn item /// there is still a bit more to do. /// /// * ... /// * inherited: other fields inherited from the enclosing fn (if any) fn check_fn<'a, 'tcx>( inherited: &'a Inherited<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, fn_sig: ty::FnSig<'tcx>, decl: &'tcx hir::FnDecl<'tcx>, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>, can_be_generator: Option<hir::Movability>, ) -> (FnCtxt<'a, 'tcx>, Option<GeneratorTypes<'tcx>>) { let mut fn_sig = fn_sig.clone(); debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env); // Create the function context. This is either derived from scratch or, // in the case of closures, based on the outer context. let mut fcx = FnCtxt::new(inherited, param_env, body.value.hir_id); *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id); let tcx = fcx.tcx; let sess = tcx.sess; let hir = tcx.hir(); let declared_ret_ty = fn_sig.output(); fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); let revealed_ret_ty = fcx.instantiate_opaque_types_from_value(fn_id, &declared_ret_ty, decl.output.span()); debug!("check_fn: declared_ret_ty: {}, revealed_ret_ty: {}", declared_ret_ty, revealed_ret_ty); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); fn_sig = tcx.mk_fn_sig( fn_sig.inputs().iter().cloned(), revealed_ret_ty, fn_sig.c_variadic, fn_sig.unsafety, fn_sig.abi, ); let span = body.value.span; fn_maybe_err(tcx, span, fn_sig.abi); if body.generator_kind.is_some() && can_be_generator.is_some() { let yield_ty = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }); fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType); fcx.yield_ty = Some(yield_ty); } let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id)); let outer_hir_id = hir.as_local_hir_id(outer_def_id).unwrap(); GatherLocalsVisitor { fcx: &fcx, parent_id: outer_hir_id }.visit_body(body); // C-variadic fns also have a `VaList` input that's not listed in `fn_sig` // (as it's created inside the body itself, not passed in from outside). let maybe_va_list = if fn_sig.c_variadic { let va_list_did = tcx.require_lang_item( lang_items::VaListTypeLangItem, Some(body.params.last().unwrap().span), ); let region = tcx.mk_region(ty::ReScope(region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite, })); Some(tcx.type_of(va_list_did).subst(tcx, &[region.into()])) } else { None }; // Add formal parameters. let inputs_hir = hir.fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs); let inputs_fn = fn_sig.inputs().iter().copied(); for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() { // Check the pattern. fcx.check_pat_top(&param.pat, param_ty, try { inputs_hir?.get(idx)?.span }, false); // Check that argument is Sized. // The check for a non-trivial pattern is a hack to avoid duplicate warnings // for simple cases like `fn foo(x: Trait)`, // where we would error once on the parameter as a whole, and once on the binding `x`. if param.pat.simple_ident().is_none() && !tcx.features().unsized_locals { fcx.require_type_is_sized(param_ty, decl.output.span(), traits::SizedArgumentType); } fcx.write_ty(param.hir_id, param_ty); } inherited.tables.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); fcx.check_return_expr(&body.value); // We insert the deferred_generator_interiors entry after visiting the body. // This ensures that all nested generators appear before the entry of this generator. // resolve_generator_interiors relies on this property. let gen_ty = if let (Some(_), Some(gen_kind)) = (can_be_generator, body.generator_kind) { let interior = fcx .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::MiscVariable, span }); fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior, gen_kind)); Some(GeneratorTypes { yield_ty: fcx.yield_ty.unwrap(), interior, movability: can_be_generator.unwrap(), }) } else { None }; // Finalize the return check by taking the LUB of the return types // we saw and assigning it to the expected return type. This isn't // really expected to fail, since the coercions would have failed // earlier when trying to find a LUB. // // However, the behavior around `!` is sort of complex. In the // event that the `actual_return_ty` comes back as `!`, that // indicates that the fn either does not return or "returns" only // values of type `!`. In this case, if there is an expected // return type that is *not* `!`, that should be ok. But if the // return type is being inferred, we want to "fallback" to `!`: // // let x = move || panic!(); // // To allow for that, I am creating a type variable with diverging // fallback. This was deemed ever so slightly better than unifying // the return value with `!` because it allows for the caller to // make more assumptions about the return type (e.g., they could do // // let y: Option<u32> = Some(x()); // // which would then cause this return type to become `u32`, not // `!`). let coercion = fcx.ret_coercion.take().unwrap().into_inner(); let mut actual_return_ty = coercion.complete(&fcx); if actual_return_ty.is_never() { actual_return_ty = fcx.next_diverging_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::DivergingFn, span, }); } fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty); // Check that the main return type implements the termination trait. if let Some(term_id) = tcx.lang_items().termination() { if let Some((def_id, EntryFnType::Main)) = tcx.entry_fn(LOCAL_CRATE) { let main_id = hir.as_local_hir_id(def_id).unwrap(); if main_id == fn_id { let substs = tcx.mk_substs_trait(declared_ret_ty, &[]); let trait_ref = ty::TraitRef::new(term_id, substs); let return_ty_span = decl.output.span(); let cause = traits::ObligationCause::new( return_ty_span, fn_id, ObligationCauseCode::MainFunctionType, ); inherited.register_predicate(traits::Obligation::new( cause, param_env, trait_ref.to_predicate(), )); } } } // Check that a function marked as `#[panic_handler]` has signature `fn(&PanicInfo) -> !` if let Some(panic_impl_did) = tcx.lang_items().panic_impl() { if panic_impl_did == hir.local_def_id(fn_id) { if let Some(panic_info_did) = tcx.lang_items().panic_info() { if declared_ret_ty.kind != ty::Never { sess.span_err(decl.output.span(), "return type should be `!`"); } let inputs = fn_sig.inputs(); let span = hir.span(fn_id); if inputs.len() == 1 { let arg_is_panic_info = match inputs[0].kind { ty::Ref(region, ty, mutbl) => match ty.kind { ty::Adt(ref adt, _) => { adt.did == panic_info_did && mutbl == hir::Mutability::Not && *region != RegionKind::ReStatic } _ => false, }, _ => false, }; if !arg_is_panic_info { sess.span_err(decl.inputs[0].span, "argument should be `&PanicInfo`"); } if let Node::Item(item) = hir.get(fn_id) { if let ItemKind::Fn(_, ref generics, _) = item.kind { if !generics.params.is_empty() { sess.span_err(span, "should have no type parameters"); } } } } else { let span = sess.source_map().def_span(span); sess.span_err(span, "function should have one argument"); } } else { sess.err("language item required, but not found: `panic_info`"); } } } // Check that a function marked as `#[alloc_error_handler]` has signature `fn(Layout) -> !` if let Some(alloc_error_handler_did) = tcx.lang_items().oom() { if alloc_error_handler_did == hir.local_def_id(fn_id) { if let Some(alloc_layout_did) = tcx.lang_items().alloc_layout() { if declared_ret_ty.kind != ty::Never { sess.span_err(decl.output.span(), "return type should be `!`"); } let inputs = fn_sig.inputs(); let span = hir.span(fn_id); if inputs.len() == 1 { let arg_is_alloc_layout = match inputs[0].kind { ty::Adt(ref adt, _) => adt.did == alloc_layout_did, _ => false, }; if !arg_is_alloc_layout { sess.span_err(decl.inputs[0].span, "argument should be `Layout`"); } if let Node::Item(item) = hir.get(fn_id) { if let ItemKind::Fn(_, ref generics, _) = item.kind { if !generics.params.is_empty() { sess.span_err( span, "`#[alloc_error_handler]` function should have no type \ parameters", ); } } } } else { let span = sess.source_map().def_span(span); sess.span_err(span, "function should have one argument"); } } else { sess.err("language item required, but not found: `alloc_layout`"); } } } (fcx, gen_ty) } fn check_struct(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { let def_id = tcx.hir().local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated check_representable(tcx, span, def_id); if def.repr.simd() { check_simd(tcx, span, def_id); } check_transparent(tcx, span, def_id); check_packed(tcx, span, def_id); } fn check_union(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) { let def_id = tcx.hir().local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated check_representable(tcx, span, def_id); check_transparent(tcx, span, def_id); check_union_fields(tcx, span, def_id); check_packed(tcx, span, def_id); } /// When the `#![feature(untagged_unions)]` gate is active, /// check that the fields of the `union` does not contain fields that need dropping. fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: DefId) -> bool { let item_type = tcx.type_of(item_def_id); if let ty::Adt(def, substs) = item_type.kind { assert!(def.is_union()); let fields = &def.non_enum_variant().fields; for field in fields { let field_ty = field.ty(tcx, substs); // We are currently checking the type this field came from, so it must be local. let field_span = tcx.hir().span_if_local(field.did).unwrap(); let param_env = tcx.param_env(field.did); if field_ty.needs_drop(tcx, param_env) { struct_span_err!( tcx.sess, field_span, E0740, "unions may not contain fields that need dropping" ) .span_note(field_span, "`std::mem::ManuallyDrop` can be used to wrap the type") .emit(); return false; } } } else { span_bug!(span, "unions must be ty::Adt, but got {:?}", item_type.kind); } return true; } /// Checks that an opaque type does not contain cycles and does not use `Self` or `T::Foo` /// projections that would result in "inheriting lifetimes". fn check_opaque<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) { check_opaque_for_inheriting_lifetimes(tcx, def_id, span); check_opaque_for_cycles(tcx, def_id, substs, span, origin); } /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result /// in "inheriting lifetimes". fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, def_id: DefId, span: Span) { let item = tcx.hir().expect_item(tcx.hir().as_local_hir_id(def_id).expect("opaque type is not local")); debug!( "check_opaque_for_inheriting_lifetimes: def_id={:?} span={:?} item={:?}", def_id, span, item ); #[derive(Debug)] struct ProhibitOpaqueVisitor<'tcx> { opaque_identity_ty: Ty<'tcx>, generics: &'tcx ty::Generics, }; impl<'tcx> ty::fold::TypeVisitor<'tcx> for ProhibitOpaqueVisitor<'tcx> { fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { debug!("check_opaque_for_inheriting_lifetimes: (visit_ty) t={:?}", t); if t == self.opaque_identity_ty { false } else { t.super_visit_with(self) } } fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool { debug!("check_opaque_for_inheriting_lifetimes: (visit_region) r={:?}", r); if let RegionKind::ReEarlyBound(ty::EarlyBoundRegion { index, .. }) = r { return *index < self.generics.parent_count as u32; } r.super_visit_with(self) } } let prohibit_opaque = match item.kind { ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::AsyncFn, .. }) | ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn, .. }) => { let mut visitor = ProhibitOpaqueVisitor { opaque_identity_ty: tcx .mk_opaque(def_id, InternalSubsts::identity_for_item(tcx, def_id)), generics: tcx.generics_of(def_id), }; debug!("check_opaque_for_inheriting_lifetimes: visitor={:?}", visitor); tcx.predicates_of(def_id) .predicates .iter() .any(|(predicate, _)| predicate.visit_with(&mut visitor)) } _ => false, }; debug!("check_opaque_for_inheriting_lifetimes: prohibit_opaque={:?}", prohibit_opaque); if prohibit_opaque { let is_async = match item.kind { ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => match origin { hir::OpaqueTyOrigin::AsyncFn => true, _ => false, }, _ => unreachable!(), }; tcx.sess.span_err(span, &format!( "`{}` return type cannot contain a projection or `Self` that references lifetimes from \ a parent scope", if is_async { "async fn" } else { "impl Trait" }, )); } } /// Checks that an opaque type does not contain cycles. fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) { if let Err(partially_expanded_type) = tcx.try_expand_impl_trait_type(def_id, substs) { if let hir::OpaqueTyOrigin::AsyncFn = origin { struct_span_err!(tcx.sess, span, E0733, "recursion in an `async fn` requires boxing",) .span_label(span, "recursive `async fn`") .note("a recursive `async fn` must be rewritten to return a boxed `dyn Future`") .emit(); } else { let mut err = struct_span_err!(tcx.sess, span, E0720, "opaque type expands to a recursive type",); err.span_label(span, "expands to a recursive type"); if let ty::Opaque(..) = partially_expanded_type.kind { err.note("type resolves to itself"); } else { err.note(&format!("expanded type is `{}`", partially_expanded_type)); } err.emit(); } } } // Forbid defining intrinsics in Rust code, // as they must always be defined by the compiler. fn fn_maybe_err(tcx: TyCtxt<'_>, sp: Span, abi: Abi) { if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = abi { tcx.sess.span_err(sp, "intrinsic must be in `extern \"rust-intrinsic\" { ... }` block"); } } pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { debug!( "check_item_type(it.hir_id={}, it.name={})", it.hir_id, tcx.def_path_str(tcx.hir().local_def_id(it.hir_id)) ); let _indenter = indenter(); match it.kind { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { let def_id = tcx.hir().local_def_id(it.hir_id); tcx.typeck_tables_of(def_id); maybe_check_static_with_link_section(tcx, def_id, it.span); } hir::ItemKind::Const(..) => { tcx.typeck_tables_of(tcx.hir().local_def_id(it.hir_id)); } hir::ItemKind::Enum(ref enum_definition, _) => { check_enum(tcx, it.span, &enum_definition.variants, it.hir_id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl { ref items, .. } => { debug!("ItemKind::Impl {} with id {}", it.ident, it.hir_id); let impl_def_id = tcx.hir().local_def_id(it.hir_id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) { check_impl_items_against_trait(tcx, it.span, impl_def_id, impl_trait_ref, items); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } } hir::ItemKind::Trait(_, _, _, _, ref items) => { let def_id = tcx.hir().local_def_id(it.hir_id); check_on_unimplemented(tcx, def_id, it); for item in items.iter() { let item = tcx.hir().trait_item(item.id); if let hir::TraitItemKind::Method(sig, _) = &item.kind { let abi = sig.header.abi; fn_maybe_err(tcx, item.ident.span, abi); } } } hir::ItemKind::Struct(..) => { check_struct(tcx, it.hir_id, it.span); } hir::ItemKind::Union(..) => { check_union(tcx, it.hir_id, it.span); } hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => { let def_id = tcx.hir().local_def_id(it.hir_id); let substs = InternalSubsts::identity_for_item(tcx, def_id); check_opaque(tcx, def_id, substs, it.span, &origin); } hir::ItemKind::TyAlias(..) => { let def_id = tcx.hir().local_def_id(it.hir_id); let pty_ty = tcx.type_of(def_id); let generics = tcx.generics_of(def_id); check_bounds_are_used(tcx, &generics, pty_ty); } hir::ItemKind::ForeignMod(ref m) => { check_abi(tcx, it.span, m.abi); if m.abi == Abi::RustIntrinsic { for item in m.items { intrinsic::check_intrinsic_type(tcx, item); } } else if m.abi == Abi::PlatformIntrinsic { for item in m.items { intrinsic::check_platform_intrinsic_type(tcx, item); } } else { for item in m.items { let generics = tcx.generics_of(tcx.hir().local_def_id(item.hir_id)); let own_counts = generics.own_counts(); if generics.params.len() - own_counts.lifetimes != 0 { let (kinds, kinds_pl, egs) = match (own_counts.types, own_counts.consts) { (_, 0) => ("type", "types", Some("u32")), // We don't specify an example value, because we can't generate // a valid value for any type. (0, _) => ("const", "consts", None), _ => ("type or const", "types or consts", None), }; struct_span_err!( tcx.sess, item.span, E0044, "foreign items may not have {} parameters", kinds, ) .span_label(item.span, &format!("can't have {} parameters", kinds)) .help( // FIXME: once we start storing spans for type arguments, turn this // into a suggestion. &format!( "replace the {} parameters with concrete {}{}", kinds, kinds_pl, egs.map(|egs| format!(" like `{}`", egs)).unwrap_or_default(), ), ) .emit(); } if let hir::ForeignItemKind::Fn(ref fn_decl, _, _) = item.kind { require_c_abi_if_c_variadic(tcx, fn_decl, m.abi, item.span); } } } } _ => { /* nothing to do */ } } } fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: DefId, span: Span) { // Only restricted on wasm32 target for now if !tcx.sess.opts.target_triple.triple().starts_with("wasm32") { return; } // If `#[link_section]` is missing, then nothing to verify let attrs = tcx.codegen_fn_attrs(id); if attrs.link_section.is_none() { return; } // For the wasm32 target statics with `#[link_section]` are placed into custom // sections of the final output file, but this isn't link custom sections of // other executable formats. Namely we can only embed a list of bytes, // nothing with pointers to anything else or relocations. If any relocation // show up, reject them here. // `#[link_section]` may contain arbitrary, or even undefined bytes, but it is // the consumer's responsibility to ensure all bytes that have been read // have defined values. if let Ok(static_) = tcx.const_eval_poly(id) { let alloc = if let ty::ConstKind::Value(ConstValue::ByRef { alloc, .. }) = static_.val { alloc } else { bug!("Matching on non-ByRef static") }; if alloc.relocations().len() != 0 { let msg = "statics with a custom `#[link_section]` must be a \ simple list of bytes on the wasm target with no \ extra levels of indirection such as references"; tcx.sess.span_err(span, msg); } } } fn check_on_unimplemented(tcx: TyCtxt<'_>, trait_def_id: DefId, item: &hir::Item<'_>) { let item_def_id = tcx.hir().local_def_id(item.hir_id); // an error would be reported if this fails. let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id); } fn report_forbidden_specialization( tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>, parent_impl: DefId, ) { let mut err = struct_span_err!( tcx.sess, impl_item.span, E0520, "`{}` specializes an item from a parent `impl`, but \ that item is not marked `default`", impl_item.ident ); err.span_label(impl_item.span, format!("cannot specialize default item `{}`", impl_item.ident)); match tcx.span_of_impl(parent_impl) { Ok(span) => { err.span_label(span, "parent `impl` is here"); err.note(&format!( "to specialize, `{}` in the parent `impl` must be marked `default`", impl_item.ident )); } Err(cname) => { err.note(&format!("parent implementation is in crate `{}`", cname)); } } err.emit(); } fn check_specialization_validity<'tcx>( tcx: TyCtxt<'tcx>, trait_def: &ty::TraitDef, trait_item: &ty::AssocItem, impl_id: DefId, impl_item: &hir::ImplItem<'_>, ) { let kind = match impl_item.kind { hir::ImplItemKind::Const(..) => ty::AssocKind::Const, hir::ImplItemKind::Method(..) => ty::AssocKind::Method, hir::ImplItemKind::OpaqueTy(..) => ty::AssocKind::OpaqueTy, hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type, }; let mut ancestor_impls = trait_def .ancestors(tcx, impl_id) .skip(1) .filter_map(|parent| { if parent.is_from_trait() { None } else { Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id))) } }) .peekable(); if ancestor_impls.peek().is_none() { // No parent, nothing to specialize. return; } let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| { match parent_item { // Parent impl exists, and contains the parent item we're trying to specialize, but // doesn't mark it `default`. Some(parent_item) if traits::impl_item_is_final(tcx, &parent_item) => { Some(Err(parent_impl.def_id())) } // Parent impl contains item and makes it specializable. Some(_) => Some(Ok(())), // Parent impl doesn't mention the item. This means it's inherited from the // grandparent. In that case, if parent is a `default impl`, inherited items use the // "defaultness" from the grandparent, else they are final. None => { if traits::impl_is_default(tcx, parent_impl.def_id()) { None } else { Some(Err(parent_impl.def_id())) } } } }); // If `opt_result` is `None`, we have only encoutered `default impl`s that don't contain the // item. This is allowed, the item isn't actually getting specialized here. let result = opt_result.unwrap_or(Ok(())); if let Err(parent_impl) = result { report_forbidden_specialization(tcx, impl_item, parent_impl); } } fn check_impl_items_against_trait<'tcx>( tcx: TyCtxt<'tcx>, full_impl_span: Span, impl_id: DefId, impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef<'_>], ) { let impl_span = tcx.sess.source_map().def_span(full_impl_span); // If the trait reference itself is erroneous (so the compilation is going // to fail), skip checking the items here -- the `impl_item` table in `tcx` // isn't populated for such impls. if impl_trait_ref.references_error() { return; } // Locate trait definition and items let trait_def = tcx.trait_def(impl_trait_ref.def_id); let mut overridden_associated_type = None; let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir().impl_item(iiref.id)); // Check existing impl methods to see if they are both present in trait // and compatible with trait signature for impl_item in impl_items() { let ty_impl_item = tcx.associated_item(tcx.hir().local_def_id(impl_item.hir_id)); let ty_trait_item = tcx .associated_items(impl_trait_ref.def_id) .find(|ac| { Namespace::from(&impl_item.kind) == Namespace::from(ac.kind) && tcx.hygienic_eq(ty_impl_item.ident, ac.ident, impl_trait_ref.def_id) }) .or_else(|| { // Not compatible, but needed for the error message tcx.associated_items(impl_trait_ref.def_id) .find(|ac| tcx.hygienic_eq(ty_impl_item.ident, ac.ident, impl_trait_ref.def_id)) }); // Check that impl definition matches trait definition if let Some(ty_trait_item) = ty_trait_item { match impl_item.kind { hir::ImplItemKind::Const(..) => { // Find associated const definition. if ty_trait_item.kind == ty::AssocKind::Const { compare_const_impl( tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, ); } else { let mut err = struct_span_err!( tcx.sess, impl_item.span, E0323, "item `{}` is an associated const, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref.print_only_trait_path() ); err.span_label(impl_item.span, "does not match trait"); // We can only get the spans from local trait definition // Same for E0324 and E0325 if let Some(trait_span) = tcx.hir().span_if_local(ty_trait_item.def_id) { err.span_label(trait_span, "item in trait"); } err.emit() } } hir::ImplItemKind::Method(..) => { let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); if ty_trait_item.kind == ty::AssocKind::Method { compare_impl_method( tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, opt_trait_span, ); } else { let mut err = struct_span_err!( tcx.sess, impl_item.span, E0324, "item `{}` is an associated method, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref.print_only_trait_path() ); err.span_label(impl_item.span, "does not match trait"); if let Some(trait_span) = opt_trait_span { err.span_label(trait_span, "item in trait"); } err.emit() } } hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => { let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); if ty_trait_item.kind == ty::AssocKind::Type { if ty_trait_item.defaultness.has_value() { overridden_associated_type = Some(impl_item); } compare_ty_impl( tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, opt_trait_span, ) } else { let mut err = struct_span_err!( tcx.sess, impl_item.span, E0325, "item `{}` is an associated type, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref.print_only_trait_path() ); err.span_label(impl_item.span, "does not match trait"); if let Some(trait_span) = opt_trait_span { err.span_label(trait_span, "item in trait"); } err.emit() } } } check_specialization_validity(tcx, trait_def, &ty_trait_item, impl_id, impl_item); } } // Check for missing items from trait let mut missing_items = Vec::new(); let mut invalidated_items = Vec::new(); let associated_type_overridden = overridden_associated_type.is_some(); for trait_item in tcx.associated_items(impl_trait_ref.def_id) { let is_implemented = trait_def .ancestors(tcx, impl_id) .leaf_def(tcx, trait_item.ident, trait_item.kind) .map(|node_item| !node_item.node.is_from_trait()) .unwrap_or(false); if !is_implemented && !traits::impl_is_default(tcx, impl_id) { if !trait_item.defaultness.has_value() { missing_items.push(trait_item); } else if associated_type_overridden { invalidated_items.push(trait_item.ident); } } } if !missing_items.is_empty() { missing_items_err(tcx, impl_span, &missing_items, full_impl_span); } if !invalidated_items.is_empty() { let invalidator = overridden_associated_type.unwrap(); struct_span_err!( tcx.sess, invalidator.span, E0399, "the following trait items need to be reimplemented as `{}` was overridden: `{}`", invalidator.ident, invalidated_items.iter().map(|name| name.to_string()).collect::<Vec<_>>().join("`, `") ) .emit(); } } fn missing_items_err( tcx: TyCtxt<'_>, impl_span: Span, missing_items: &[ty::AssocItem], full_impl_span: Span, ) { let missing_items_msg = missing_items .iter() .map(|trait_item| trait_item.ident.to_string()) .collect::<Vec<_>>() .join("`, `"); let mut err = struct_span_err!( tcx.sess, impl_span, E0046, "not all trait items implemented, missing: `{}`", missing_items_msg ); err.span_label(impl_span, format!("missing `{}` in implementation", missing_items_msg)); // `Span` before impl block closing brace. let hi = full_impl_span.hi() - BytePos(1); // Point at the place right before the closing brace of the relevant `impl` to suggest // adding the associated item at the end of its body. let sugg_sp = full_impl_span.with_lo(hi).with_hi(hi); // Obtain the level of indentation ending in `sugg_sp`. let indentation = tcx.sess.source_map().span_to_margin(sugg_sp).unwrap_or(0); // Make the whitespace that will make the suggestion have the right indentation. let padding: String = (0..indentation).map(|_| " ").collect(); for trait_item in missing_items { let snippet = suggestion_signature(&trait_item, tcx); let code = format!("{}{}\n{}", padding, snippet, padding); let msg = format!("implement the missing item: `{}`", snippet); let appl = Applicability::HasPlaceholders; if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) { err.span_label(span, format!("`{}` from trait", trait_item.ident)); err.tool_only_span_suggestion(sugg_sp, &msg, code, appl); } else { err.span_suggestion_hidden(sugg_sp, &msg, code, appl); } } err.emit(); } /// Return placeholder code for the given function. fn fn_sig_suggestion(sig: &ty::FnSig<'_>, ident: Ident) -> String { let args = sig .inputs() .iter() .map(|ty| { Some(match ty.kind { ty::Param(param) if param.name == kw::SelfUpper => "self".to_string(), ty::Ref(reg, ref_ty, mutability) => { let reg = match &format!("{}", reg)[..] { "'_" | "" => String::new(), reg => format!("{} ", reg), }; match ref_ty.kind { ty::Param(param) if param.name == kw::SelfUpper => { format!("&{}{}self", reg, mutability.prefix_str()) } _ => format!("_: {:?}", ty), } } _ => format!("_: {:?}", ty), }) }) .chain(std::iter::once(if sig.c_variadic { Some("...".to_string()) } else { None })) .filter_map(|arg| arg) .collect::<Vec<String>>() .join(", "); let output = sig.output(); let output = if !output.is_unit() { format!(" -> {:?}", output) } else { String::new() }; let unsafety = sig.unsafety.prefix_str(); // FIXME: this is not entirely correct, as the lifetimes from borrowed params will // not be present in the `fn` definition, not will we account for renamed // lifetimes between the `impl` and the `trait`, but this should be good enough to // fill in a significant portion of the missing code, and other subsequent // suggestions can help the user fix the code. format!("{}fn {}({}){} {{ unimplemented!() }}", unsafety, ident, args, output) } /// Return placeholder code for the given associated item. /// Similar to `ty::AssocItem::suggestion`, but appropriate for use as the code snippet of a /// structured suggestion. fn suggestion_signature(assoc: &ty::AssocItem, tcx: TyCtxt<'_>) -> String { match assoc.kind { ty::AssocKind::Method => { // We skip the binder here because the binder would deanonymize all // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. fn_sig_suggestion(tcx.fn_sig(assoc.def_id).skip_binder(), assoc.ident) } ty::AssocKind::Type => format!("type {} = Type;", assoc.ident), // FIXME(type_alias_impl_trait): we should print bounds here too. ty::AssocKind::OpaqueTy => format!("type {} = Type;", assoc.ident), ty::AssocKind::Const => { let ty = tcx.type_of(assoc.def_id); let val = expr::ty_kind_suggestion(ty).unwrap_or("value"); format!("const {}: {:?} = {};", assoc.ident, ty, val) } } } /// Checks whether a type can be represented in memory. In particular, it /// identifies types that contain themselves without indirection through a /// pointer, which would mean their size is unbounded. fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: DefId) -> bool { let rty = tcx.type_of(item_def_id); // Check that it is possible to represent this type. This call identifies // (1) types that contain themselves and (2) types that contain a different // recursive type. It is only necessary to throw an error on those that // contain themselves. For case 2, there must be an inner type that will be // caught by case 1. match rty.is_representable(tcx, sp) { Representability::SelfRecursive(spans) => { let mut err = recursive_type_with_infinite_size_error(tcx, item_def_id); for span in spans { err.span_label(span, "recursive without indirection"); } err.emit(); return false; } Representability::Representable | Representability::ContainsRecursive => (), } return true; } pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let t = tcx.type_of(def_id); if let ty::Adt(def, substs) = t.kind { if def.is_struct() { let fields = &def.non_enum_variant().fields; if fields.is_empty() { struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; } let e = fields[0].ty(tcx, substs); if !fields.iter().all(|f| f.ty(tcx, substs) == e) { struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous") .span_label(sp, "SIMD elements must have the same type") .emit(); return; } match e.kind { ty::Param(_) => { /* struct<T>(T, T, T, T) is ok */ } _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ } _ => { struct_span_err!( tcx.sess, sp, E0077, "SIMD vector element type should be machine type" ) .emit(); return; } } } } } fn check_packed(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let repr = tcx.adt_def(def_id).repr; if repr.packed() { for attr in tcx.get_attrs(def_id).iter() { for r in attr::find_repr_attrs(&tcx.sess.parse_sess, attr) { if let attr::ReprPacked(pack) = r { if let Some(repr_pack) = repr.pack { if pack as u64 != repr_pack.bytes() { struct_span_err!( tcx.sess, sp, E0634, "type has conflicting packed representation hints" ) .emit(); } } } } } if repr.align.is_some() { struct_span_err!( tcx.sess, sp, E0587, "type has conflicting packed and align representation hints" ) .emit(); } else { if let Some(def_spans) = check_packed_inner(tcx, def_id, &mut vec![]) { let mut err = struct_span_err!( tcx.sess, sp, E0588, "packed type cannot transitively contain a `#[repr(align)]` type" ); let hir = tcx.hir(); if let Some(hir_id) = hir.as_local_hir_id(def_spans[0].0) { if let Node::Item(Item { ident, .. }) = hir.get(hir_id) { err.span_note( tcx.def_span(def_spans[0].0), &format!("`{}` has a `#[repr(align)]` attribute", ident), ); } } if def_spans.len() > 2 { let mut first = true; for (adt_def, span) in def_spans.iter().skip(1).rev() { if let Some(hir_id) = hir.as_local_hir_id(*adt_def) { if let Node::Item(Item { ident, .. }) = hir.get(hir_id) { err.span_note( *span, &if first { format!( "`{}` contains a field of type `{}`", tcx.type_of(def_id), ident ) } else { format!("...which contains a field of type `{}`", ident) }, ); first = false; } } } } err.emit(); } } } } fn check_packed_inner( tcx: TyCtxt<'_>, def_id: DefId, stack: &mut Vec<DefId>, ) -> Option<Vec<(DefId, Span)>> { if let ty::Adt(def, substs) = tcx.type_of(def_id).kind { if def.is_struct() || def.is_union() { if def.repr.align.is_some() { return Some(vec![(def.did, DUMMY_SP)]); } stack.push(def_id); for field in &def.non_enum_variant().fields { if let ty::Adt(def, _) = field.ty(tcx, substs).kind { if !stack.contains(&def.did) { if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) { defs.push((def.did, field.ident.span)); return Some(defs); } } } } stack.pop(); } } None } /// Emit an error when encountering more or less than one variant in a transparent enum. fn bad_variant_count<'tcx>(tcx: TyCtxt<'tcx>, adt: &'tcx ty::AdtDef, sp: Span, did: DefId) { let variant_spans: Vec<_> = adt .variants .iter() .map(|variant| tcx.hir().span_if_local(variant.def_id).unwrap()) .collect(); let msg = format!("needs exactly one variant, but has {}", adt.variants.len(),); let mut err = struct_span_err!(tcx.sess, sp, E0731, "transparent enum {}", msg); err.span_label(sp, &msg); if let [start @ .., end] = &*variant_spans { for variant_span in start { err.span_label(*variant_span, ""); } err.span_label(*end, &format!("too many variants in `{}`", tcx.def_path_str(did))); } err.emit(); } /// Emit an error when encountering more or less than one non-zero-sized field in a transparent /// enum. fn bad_non_zero_sized_fields<'tcx>( tcx: TyCtxt<'tcx>, adt: &'tcx ty::AdtDef, field_count: usize, field_spans: impl Iterator<Item = Span>, sp: Span, ) { let msg = format!("needs exactly one non-zero-sized field, but has {}", field_count); let mut err = struct_span_err!( tcx.sess, sp, E0690, "{}transparent {} {}", if adt.is_enum() { "the variant of a " } else { "" }, adt.descr(), msg, ); err.span_label(sp, &msg); for sp in field_spans { err.span_label(sp, "this field is non-zero-sized"); } err.emit(); } fn check_transparent(tcx: TyCtxt<'_>, sp: Span, def_id: DefId) { let adt = tcx.adt_def(def_id); if !adt.repr.transparent() { return; } let sp = tcx.sess.source_map().def_span(sp); if adt.is_enum() && !tcx.features().transparent_enums { feature_err( &tcx.sess.parse_sess, sym::transparent_enums, sp, "transparent enums are unstable", ) .emit(); } if adt.is_union() && !tcx.features().transparent_unions { feature_err( &tcx.sess.parse_sess, sym::transparent_unions, sp, "transparent unions are unstable", ) .emit(); } if adt.variants.len() != 1 { bad_variant_count(tcx, adt, sp, def_id); if adt.variants.is_empty() { // Don't bother checking the fields. No variants (and thus no fields) exist. return; } } // For each field, figure out if it's known to be a ZST and align(1) let field_infos = adt.all_fields().map(|field| { let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did)); let param_env = tcx.param_env(field.did); let layout = tcx.layout_of(param_env.and(ty)); // We are currently checking the type this field came from, so it must be local let span = tcx.hir().span_if_local(field.did).unwrap(); let zst = layout.map(|layout| layout.is_zst()).unwrap_or(false); let align1 = layout.map(|layout| layout.align.abi.bytes() == 1).unwrap_or(false); (span, zst, align1) }); let non_zst_fields = field_infos.clone().filter_map(|(span, zst, _align1)| if !zst { Some(span) } else { None }); let non_zst_count = non_zst_fields.clone().count(); if non_zst_count != 1 { bad_non_zero_sized_fields(tcx, adt, non_zst_count, non_zst_fields, sp); } for (span, zst, align1) in field_infos { if zst && !align1 { struct_span_err!( tcx.sess, span, E0691, "zero-sized field in transparent {} has alignment larger than 1", adt.descr(), ) .span_label(span, "has alignment larger than 1") .emit(); } } } #[allow(trivial_numeric_casts)] pub fn check_enum<'tcx>( tcx: TyCtxt<'tcx>, sp: Span, vs: &'tcx [hir::Variant<'tcx>], id: hir::HirId, ) { let def_id = tcx.hir().local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated if vs.is_empty() { let attributes = tcx.get_attrs(def_id); if let Some(attr) = attr::find_by_name(&attributes, sym::repr) { struct_span_err!( tcx.sess, attr.span, E0084, "unsupported representation for zero-variant enum" ) .span_label(sp, "zero-variant enum") .emit(); } } let repr_type_ty = def.repr.discr_type().to_ty(tcx); if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 { if !tcx.features().repr128 { feature_err( &tcx.sess.parse_sess, sym::repr128, sp, "repr with 128-bit type is unstable", ) .emit(); } } for v in vs { if let Some(ref e) = v.disr_expr { tcx.typeck_tables_of(tcx.hir().local_def_id(e.hir_id)); } } if tcx.adt_def(def_id).repr.int.is_none() && tcx.features().arbitrary_enum_discriminant { let is_unit = |var: &hir::Variant<'_>| match var.data { hir::VariantData::Unit(..) => true, _ => false, }; let has_disr = |var: &hir::Variant<'_>| var.disr_expr.is_some(); let has_non_units = vs.iter().any(|var| !is_unit(var)); let disr_units = vs.iter().any(|var| is_unit(&var) && has_disr(&var)); let disr_non_unit = vs.iter().any(|var| !is_unit(&var) && has_disr(&var)); if disr_non_unit || (disr_units && has_non_units) { let mut err = struct_span_err!(tcx.sess, sp, E0732, "`#[repr(inttype)]` must be specified"); err.emit(); } } let mut disr_vals: Vec<Discr<'tcx>> = Vec::with_capacity(vs.len()); for ((_, discr), v) in def.discriminants(tcx).zip(vs) { // Check for duplicate discriminant values if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) { let variant_did = def.variants[VariantIdx::new(i)].def_id; let variant_i_hir_id = tcx.hir().as_local_hir_id(variant_did).unwrap(); let variant_i = tcx.hir().expect_variant(variant_i_hir_id); let i_span = match variant_i.disr_expr { Some(ref expr) => tcx.hir().span(expr.hir_id), None => tcx.hir().span(variant_i_hir_id), }; let span = match v.disr_expr { Some(ref expr) => tcx.hir().span(expr.hir_id), None => v.span, }; struct_span_err!( tcx.sess, span, E0081, "discriminant value `{}` already exists", disr_vals[i] ) .span_label(i_span, format!("first use of `{}`", disr_vals[i])) .span_label(span, format!("enum already has `{}`", disr_vals[i])) .emit(); } disr_vals.push(discr); } check_representable(tcx, sp, def_id); check_transparent(tcx, sp, def_id); } fn report_unexpected_variant_res(tcx: TyCtxt<'_>, res: Res, span: Span, qpath: &QPath<'_>) { struct_span_err!( tcx.sess, span, E0533, "expected unit struct, unit variant or constant, found {} `{}`", res.descr(), hir::print::to_string(tcx.hir(), |s| s.print_qpath(qpath, false)) ) .emit(); } impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.tcx } fn item_def_id(&self) -> Option<DefId> { None } fn get_type_parameter_bounds(&self, _: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> { let tcx = self.tcx; let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); let item_id = tcx.hir().ty_param_owner(hir_id); let item_def_id = tcx.hir().local_def_id(item_id); let generics = tcx.generics_of(item_def_id); let index = generics.param_def_id_to_index[&def_id]; ty::GenericPredicates { parent: None, predicates: tcx.arena.alloc_from_iter(self.param_env.caller_bounds.iter().filter_map( |&predicate| match predicate { ty::Predicate::Trait(ref data) if data.skip_binder().self_ty().is_param(index) => { // HACK(eddyb) should get the original `Span`. let span = tcx.def_span(def_id); Some((predicate, span)) } _ => None, }, )), } } fn re_infer(&self, def: Option<&ty::GenericParamDef>, span: Span) -> Option<ty::Region<'tcx>> { let v = match def { Some(def) => infer::EarlyBoundRegion(span, def.name), None => infer::MiscVariable(span), }; Some(self.next_region_var(v)) } fn allow_ty_infer(&self) -> bool { true } fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> { if let Some(param) = param { if let GenericArgKind::Type(ty) = self.var_for_def(span, param).unpack() { return ty; } unreachable!() } else { self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span, }) } } fn ct_infer( &self, ty: Ty<'tcx>, param: Option<&ty::GenericParamDef>, span: Span, ) -> &'tcx Const<'tcx> { if let Some(param) = param { if let GenericArgKind::Const(ct) = self.var_for_def(span, param).unpack() { return ct; } unreachable!() } else { self.next_const_var( ty, ConstVariableOrigin { kind: ConstVariableOriginKind::ConstInference, span }, ) } } fn projected_ty_from_poly_trait_ref( &self, span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'_>, poly_trait_ref: ty::PolyTraitRef<'tcx>, ) -> Ty<'tcx> { let (trait_ref, _) = self.replace_bound_vars_with_fresh_vars( span, infer::LateBoundRegionConversionTime::AssocTypeProjection(item_def_id), &poly_trait_ref, ); let item_substs = <dyn AstConv<'tcx>>::create_substs_for_associated_item( self, self.tcx, span, item_def_id, item_segment, trait_ref.substs, ); self.tcx().mk_projection(item_def_id, item_substs) } fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> { if ty.has_escaping_bound_vars() { ty // FIXME: normalization and escaping regions } else { self.normalize_associated_types_in(span, &ty) } } fn set_tainted_by_errors(&self) { self.infcx.set_tainted_by_errors() } fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, _span: Span) { self.write_ty(hir_id, ty) } } /// Controls whether the arguments are tupled. This is used for the call /// operator. /// /// Tupling means that all call-side arguments are packed into a tuple and /// passed as a single parameter. For example, if tupling is enabled, this /// function: /// /// fn f(x: (isize, isize)) /// /// Can be called as: /// /// f(1, 2); /// /// Instead of: /// /// f((1, 2)); #[derive(Clone, Eq, PartialEq)] enum TupleArgumentsFlag { DontTupleArguments, TupleArguments, } /// Controls how we perform fallback for unconstrained /// type variables. enum FallbackMode { /// Do not fallback type variables to opaque types. NoOpaque, /// Perform all possible kinds of fallback, including /// turning type variables to opaque types. All, } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn new( inh: &'a Inherited<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, body_id: hir::HirId, ) -> FnCtxt<'a, 'tcx> { FnCtxt { body_id, param_env, err_count_on_creation: inh.tcx.sess.err_count(), ret_coercion: None, ret_coercion_span: RefCell::new(None), yield_ty: None, ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal, hir::CRATE_HIR_ID)), diverges: Cell::new(Diverges::Maybe), has_errors: Cell::new(false), enclosing_breakables: RefCell::new(EnclosingBreakables { stack: Vec::new(), by_id: Default::default(), }), inh, } } pub fn sess(&self) -> &Session { &self.tcx.sess } pub fn errors_reported_since_creation(&self) -> bool { self.tcx.sess.err_count() > self.err_count_on_creation } /// Produces warning on the given node, if the current point in the /// function is unreachable, and there hasn't been another warning. fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) { // FIXME: Combine these two 'if' expressions into one once // let chains are implemented if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() { // If span arose from a desugaring of `if` or `while`, then it is the condition itself, // which diverges, that we are about to lint on. This gives suboptimal diagnostics. // Instead, stop here so that the `if`- or `while`-expression's block is linted instead. if !span.is_desugaring(DesugaringKind::CondTemporary) && !span.is_desugaring(DesugaringKind::Async) && !orig_span.is_desugaring(DesugaringKind::Await) { self.diverges.set(Diverges::WarnedAlways); debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); let msg = format!("unreachable {}", kind); self.tcx() .struct_span_lint_hir(lint::builtin::UNREACHABLE_CODE, id, span, &msg) .span_label(span, &msg) .span_label( orig_span, custom_note.unwrap_or("any code following this expression is unreachable"), ) .emit(); } } } pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { ObligationCause::new(span, self.body_id, code) } pub fn misc(&self, span: Span) -> ObligationCause<'tcx> { self.cause(span, ObligationCauseCode::MiscObligation) } /// Resolves type and const variables in `ty` if possible. Unlike the infcx /// version (resolve_vars_if_possible), this version will /// also select obligations if it seems useful, in an effort /// to get more type information. fn resolve_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> { debug!("resolve_vars_with_obligations(ty={:?})", ty); // No Infer()? Nothing needs doing. if !ty.has_infer_types() && !ty.has_infer_consts() { debug!("resolve_vars_with_obligations: ty={:?}", ty); return ty; } // If `ty` is a type variable, see whether we already know what it is. ty = self.resolve_vars_if_possible(&ty); if !ty.has_infer_types() && !ty.has_infer_consts() { debug!("resolve_vars_with_obligations: ty={:?}", ty); return ty; } // If not, try resolving pending obligations as much as // possible. This can help substantially when there are // indirect dependencies that don't seem worth tracking // precisely. self.select_obligations_where_possible(false, |_| {}); ty = self.resolve_vars_if_possible(&ty); debug!("resolve_vars_with_obligations: ty={:?}", ty); ty } fn record_deferred_call_resolution( &self, closure_def_id: DefId, r: DeferredCallResolution<'tcx>, ) { let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); deferred_call_resolutions.entry(closure_def_id).or_default().push(r); } fn remove_deferred_call_resolutions( &self, closure_def_id: DefId, ) -> Vec<DeferredCallResolution<'tcx>> { let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![]) } pub fn tag(&self) -> String { format!("{:p}", self) } pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> { self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| { span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid)) }) } #[inline] pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) { debug!( "write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(&ty), self.tag() ); self.tables.borrow_mut().node_types_mut().insert(id, ty); if ty.references_error() { self.has_errors.set(true); self.set_tainted_by_errors(); } } pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) { self.tables.borrow_mut().field_indices_mut().insert(hir_id, index); } fn write_resolution(&self, hir_id: hir::HirId, r: Result<(DefKind, DefId), ErrorReported>) { self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, r); } pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { debug!("write_method_call(hir_id={:?}, method={:?})", hir_id, method); self.write_resolution(hir_id, Ok((DefKind::Method, method.def_id))); self.write_substs(hir_id, method.substs); // When the method is confirmed, the `method.substs` includes // parameters from not just the method, but also the impl of // the method -- in particular, the `Self` type will be fully // resolved. However, those are not something that the "user // specified" -- i.e., those types come from the inferred type // of the receiver, not something the user wrote. So when we // create the user-substs, we want to replace those earlier // types with just the types that the user actually wrote -- // that is, those that appear on the *method itself*. // // As an example, if the user wrote something like // `foo.bar::<u32>(...)` -- the `Self` type here will be the // type of `foo` (possibly adjusted), but we don't want to // include that. We want just the `[_, u32]` part. if !method.substs.is_noop() { let method_generics = self.tcx.generics_of(method.def_id); if !method_generics.params.is_empty() { let user_type_annotation = self.infcx.probe(|_| { let user_substs = UserSubsts { substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| { let i = param.index as usize; if i < method_generics.parent_count { self.infcx.var_for_def(DUMMY_SP, param) } else { method.substs[i] } }), user_self_ty: None, // not relevant here }; self.infcx.canonicalize_user_type_annotation(&UserType::TypeOf( method.def_id, user_substs, )) }); debug!("write_method_call: user_type_annotation={:?}", user_type_annotation); self.write_user_type_annotation(hir_id, user_type_annotation); } } } pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) { if !substs.is_noop() { debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); self.tables.borrow_mut().node_substs_mut().insert(node_id, substs); } } /// Given the substs that we just converted from the HIR, try to /// canonicalize them and store them as user-given substitutions /// (i.e., substitutions that must be respected by the NLL check). /// /// This should be invoked **before any unifications have /// occurred**, so that annotations like `Vec<_>` are preserved /// properly. pub fn write_user_type_annotation_from_substs( &self, hir_id: hir::HirId, def_id: DefId, substs: SubstsRef<'tcx>, user_self_ty: Option<UserSelfTy<'tcx>>, ) { debug!( "write_user_type_annotation_from_substs: hir_id={:?} def_id={:?} substs={:?} \ user_self_ty={:?} in fcx {}", hir_id, def_id, substs, user_self_ty, self.tag(), ); if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) { let canonicalized = self.infcx.canonicalize_user_type_annotation(&UserType::TypeOf( def_id, UserSubsts { substs, user_self_ty }, )); debug!("write_user_type_annotation_from_substs: canonicalized={:?}", canonicalized); self.write_user_type_annotation(hir_id, canonicalized); } } pub fn write_user_type_annotation( &self, hir_id: hir::HirId, canonical_user_type_annotation: CanonicalUserType<'tcx>, ) { debug!( "write_user_type_annotation: hir_id={:?} canonical_user_type_annotation={:?} tag={}", hir_id, canonical_user_type_annotation, self.tag(), ); if !canonical_user_type_annotation.is_identity() { self.tables .borrow_mut() .user_provided_types_mut() .insert(hir_id, canonical_user_type_annotation); } else { debug!("write_user_type_annotation: skipping identity substs"); } } pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec<Adjustment<'tcx>>) { debug!("apply_adjustments(expr={:?}, adj={:?})", expr, adj); if adj.is_empty() { return; } match self.tables.borrow_mut().adjustments_mut().entry(expr.hir_id) { Entry::Vacant(entry) => { entry.insert(adj); } Entry::Occupied(mut entry) => { debug!(" - composing on top of {:?}", entry.get()); match (&entry.get()[..], &adj[..]) { // Applying any adjustment on top of a NeverToAny // is a valid NeverToAny adjustment, because it can't // be reached. (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return, (&[ Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. }, ], &[ Adjustment { kind: Adjust::Deref(_), .. }, .. // Any following adjustments are allowed. ]) => { // A reborrow has no effect before a dereference. } // FIXME: currently we never try to compose autoderefs // and ReifyFnPointer/UnsafeFnPointer, but we could. _ => bug!("while adjusting {:?}, can't compose {:?} and {:?}", expr, entry.get(), adj) }; *entry.get_mut() = adj; } } } /// Basically whenever we are converting from a type scheme into /// the fn body space, we always want to normalize associated /// types as well. This function combines the two. fn instantiate_type_scheme<T>(&self, span: Span, substs: SubstsRef<'tcx>, value: &T) -> T where T: TypeFoldable<'tcx>, { let value = value.subst(self.tcx, substs); let result = self.normalize_associated_types_in(span, &value); debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}", value, substs, result); result } /// As `instantiate_type_scheme`, but for the bounds found in a /// generic type scheme. fn instantiate_bounds( &self, span: Span, def_id: DefId, substs: SubstsRef<'tcx>, ) -> (ty::InstantiatedPredicates<'tcx>, Vec<Span>) { let bounds = self.tcx.predicates_of(def_id); let spans: Vec<Span> = bounds.predicates.iter().map(|(_, span)| *span).collect(); let result = bounds.instantiate(self.tcx, substs); let result = self.normalize_associated_types_in(span, &result); debug!( "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}", bounds, substs, result, spans, ); (result, spans) } /// Replaces the opaque types from the given value with type variables, /// and records the `OpaqueTypeMap` for later use during writeback. See /// `InferCtxt::instantiate_opaque_types` for more details. fn instantiate_opaque_types_from_value<T: TypeFoldable<'tcx>>( &self, parent_id: hir::HirId, value: &T, value_span: Span, ) -> T { let parent_def_id = self.tcx.hir().local_def_id(parent_id); debug!( "instantiate_opaque_types_from_value(parent_def_id={:?}, value={:?})", parent_def_id, value ); let (value, opaque_type_map) = self.register_infer_ok_obligations(self.instantiate_opaque_types( parent_def_id, self.body_id, self.param_env, value, value_span, )); let mut opaque_types = self.opaque_types.borrow_mut(); let mut opaque_types_vars = self.opaque_types_vars.borrow_mut(); for (ty, decl) in opaque_type_map { let _ = opaque_types.insert(ty, decl); let _ = opaque_types_vars.insert(decl.concrete_ty, decl.opaque_type); } value } fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T where T: TypeFoldable<'tcx>, { self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value) } fn normalize_associated_types_in_as_infer_ok<T>( &self, span: Span, value: &T, ) -> InferOk<'tcx, T> where T: TypeFoldable<'tcx>, { self.inh.partially_normalize_associated_types_in(span, self.body_id, self.param_env, value) } pub fn require_type_meets( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, def_id: DefId, ) { self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code)); } pub fn require_type_is_sized( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, ) { if !ty.references_error() { let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem, None); self.require_type_meets(ty, span, code, lang_item); } } pub fn require_type_is_sized_deferred( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, ) { if !ty.references_error() { self.deferred_sized_obligations.borrow_mut().push((ty, span, code)); } } pub fn register_bound( &self, ty: Ty<'tcx>, def_id: DefId, cause: traits::ObligationCause<'tcx>, ) { if !ty.references_error() { self.fulfillment_cx.borrow_mut().register_bound( self, self.param_env, ty, def_id, cause, ); } } pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> { let t = AstConv::ast_ty_to_ty(self, ast_t); self.register_wf_obligation(t, ast_t.span, traits::MiscObligation); t } pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> { let ty = self.to_ty(ast_ty); debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); if Self::can_contain_user_lifetime_bounds(ty) { let c_ty = self.infcx.canonicalize_response(&UserType::Ty(ty)); debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); self.tables.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); } ty } /// Returns the `DefId` of the constant parameter that the provided expression is a path to. pub fn const_param_def_id(&self, hir_c: &hir::AnonConst) -> Option<DefId> { AstConv::const_param_def_id(self, &self.tcx.hir().body(hir_c.body).value) } pub fn to_const(&self, ast_c: &hir::AnonConst, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> { AstConv::ast_const_to_const(self, ast_c, ty) } // If the type given by the user has free regions, save it for later, since // NLL would like to enforce those. Also pass in types that involve // projections, since those can resolve to `'static` bounds (modulo #54940, // which hopefully will be fixed by the time you see this comment, dear // reader, although I have my doubts). Also pass in types with inference // types, because they may be repeated. Other sorts of things are already // sufficiently enforced with erased regions. =) fn can_contain_user_lifetime_bounds<T>(t: T) -> bool where T: TypeFoldable<'tcx>, { t.has_free_regions() || t.has_projections() || t.has_infer_types() } pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { match self.tables.borrow().node_types().get(id) { Some(&t) => t, None if self.is_tainted_by_errors() => self.tcx.types.err, None => { bug!( "no type for node {}: {} in fcx {}", id, self.tcx.hir().node_to_string(id), self.tag() ); } } } /// Registers an obligation for checking later, during regionck, that the type `ty` must /// outlive the region `r`. pub fn register_wf_obligation( &self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, ) { // WF obligations never themselves fail, so no real need to give a detailed cause: let cause = traits::ObligationCause::new(span, self.body_id, code); self.register_predicate(traits::Obligation::new( cause, self.param_env, ty::Predicate::WellFormed(ty), )); } /// Registers obligations that all types appearing in `substs` are well-formed. pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) { for ty in substs.types() { if !ty.references_error() { self.register_wf_obligation(ty, expr.span, traits::MiscObligation); } } } /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each /// type/region parameter was instantiated (`substs`), creates and registers suitable /// trait/region obligations. /// /// For example, if there is a function: /// /// ``` /// fn foo<'a,T:'a>(...) /// ``` /// /// and a reference: /// /// ``` /// let f = foo; /// ``` /// /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a` /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally. pub fn add_obligations_for_parameters( &self, cause: traits::ObligationCause<'tcx>, predicates: &ty::InstantiatedPredicates<'tcx>, ) { assert!(!predicates.has_escaping_bound_vars()); debug!("add_obligations_for_parameters(predicates={:?})", predicates); for obligation in traits::predicates_for_generics(cause, self.param_env, predicates) { self.register_predicate(obligation); } } // FIXME(arielb1): use this instead of field.ty everywhere // Only for fields! Returns <none> for methods> // Indifferent to privacy flags pub fn field_ty( &self, span: Span, field: &'tcx ty::FieldDef, substs: SubstsRef<'tcx>, ) -> Ty<'tcx> { self.normalize_associated_types_in(span, &field.ty(self.tcx, substs)) } fn check_casts(&self) { let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); for cast in deferred_cast_checks.drain(..) { cast.check(self); } } fn resolve_generator_interiors(&self, def_id: DefId) { let mut generators = self.deferred_generator_interiors.borrow_mut(); for (body_id, interior, kind) in generators.drain(..) { self.select_obligations_where_possible(false, |_| {}); generator_interior::resolve_interior(self, def_id, body_id, interior, kind); } } // Tries to apply a fallback to `ty` if it is an unsolved variable. // // - Unconstrained ints are replaced with `i32`. // // - Unconstrained floats are replaced with with `f64`. // // - Non-numerics get replaced with `!` when `#![feature(never_type_fallback)]` // is enabled. Otherwise, they are replaced with `()`. // // Fallback becomes very dubious if we have encountered type-checking errors. // In that case, fallback to Error. // The return value indicates whether fallback has occurred. fn fallback_if_possible(&self, ty: Ty<'tcx>, mode: FallbackMode) -> bool { use rustc::ty::error::UnconstrainedNumeric::Neither; use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedFloat, UnconstrainedInt}; assert!(ty.is_ty_infer()); let fallback = match self.type_is_unconstrained_numeric(ty) { _ if self.is_tainted_by_errors() => self.tcx().types.err, UnconstrainedInt => self.tcx.types.i32, UnconstrainedFloat => self.tcx.types.f64, Neither if self.type_var_diverges(ty) => self.tcx.mk_diverging_default(), Neither => { // This type variable was created from the instantiation of an opaque // type. The fact that we're attempting to perform fallback for it // means that the function neither constrained it to a concrete // type, nor to the opaque type itself. // // For example, in this code: // //``` // type MyType = impl Copy; // fn defining_use() -> MyType { true } // fn other_use() -> MyType { defining_use() } // ``` // // `defining_use` will constrain the instantiated inference // variable to `bool`, while `other_use` will constrain // the instantiated inference variable to `MyType`. // // When we process opaque types during writeback, we // will handle cases like `other_use`, and not count // them as defining usages // // However, we also need to handle cases like this: // // ```rust // pub type Foo = impl Copy; // fn produce() -> Option<Foo> { // None // } // ``` // // In the above snippet, the inference varaible created by // instantiating `Option<Foo>` will be completely unconstrained. // We treat this as a non-defining use by making the inference // variable fall back to the opaque type itself. if let FallbackMode::All = mode { if let Some(opaque_ty) = self.opaque_types_vars.borrow().get(ty) { debug!( "fallback_if_possible: falling back opaque type var {:?} to {:?}", ty, opaque_ty ); *opaque_ty } else { return false; } } else { return false; } } }; debug!("fallback_if_possible: defaulting `{:?}` to `{:?}`", ty, fallback); self.demand_eqtype(rustc_span::DUMMY_SP, ty, fallback); true } fn select_all_obligations_or_error(&self) { debug!("select_all_obligations_or_error"); if let Err(errors) = self.fulfillment_cx.borrow_mut().select_all_or_error(&self) { self.report_fulfillment_errors(&errors, self.inh.body_id, false); } } /// Select as many obligations as we can at present. fn select_obligations_where_possible( &self, fallback_has_occurred: bool, mutate_fullfillment_errors: impl Fn(&mut Vec<traits::FulfillmentError<'tcx>>), ) { let result = self.fulfillment_cx.borrow_mut().select_where_possible(self); if let Err(mut errors) = result { mutate_fullfillment_errors(&mut errors); self.report_fulfillment_errors(&errors, self.inh.body_id, fallback_has_occurred); } } /// For the overloaded place expressions (`*x`, `x[3]`), the trait /// returns a type of `&T`, but the actual type we assign to the /// *expression* is `T`. So this function just peels off the return /// type by one layer to yield `T`. fn make_overloaded_place_return_type( &self, method: MethodCallee<'tcx>, ) -> ty::TypeAndMut<'tcx> { // extract method return type, which will be &T; let ret_ty = method.sig.output(); // method returns &T, but the type as visible to user is T, so deref ret_ty.builtin_deref(true).unwrap() } fn lookup_indexing( &self, expr: &hir::Expr<'_>, base_expr: &'tcx hir::Expr<'tcx>, base_ty: Ty<'tcx>, idx_ty: Ty<'tcx>, needs: Needs, ) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { // FIXME(#18741) -- this is almost but not quite the same as the // autoderef that normal method probing does. They could likely be // consolidated. let mut autoderef = self.autoderef(base_expr.span, base_ty); let mut result = None; while result.is_none() && autoderef.next().is_some() { result = self.try_index_step(expr, base_expr, &autoderef, needs, idx_ty); } autoderef.finalize(self); result } /// To type-check `base_expr[index_expr]`, we progressively autoderef /// (and otherwise adjust) `base_expr`, looking for a type which either /// supports builtin indexing or overloaded indexing. /// This loop implements one step in that search; the autoderef loop /// is implemented by `lookup_indexing`. fn try_index_step( &self, expr: &hir::Expr<'_>, base_expr: &hir::Expr<'_>, autoderef: &Autoderef<'a, 'tcx>, needs: Needs, index_ty: Ty<'tcx>, ) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { let adjusted_ty = autoderef.unambiguous_final_ty(self); debug!( "try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \ index_ty={:?})", expr, base_expr, adjusted_ty, index_ty ); for &unsize in &[false, true] { let mut self_ty = adjusted_ty; if unsize { // We only unsize arrays here. if let ty::Array(element_ty, _) = adjusted_ty.kind { self_ty = self.tcx.mk_slice(element_ty); } else { continue; } } // If some lookup succeeds, write callee into table and extract index/element // type from the method signature. // If some lookup succeeded, install method in table let input_ty = self.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::AutoDeref, span: base_expr.span, }); let method = self.try_overloaded_place_op( expr.span, self_ty, &[input_ty], needs, PlaceOp::Index, ); let result = method.map(|ok| { debug!("try_index_step: success, using overloaded indexing"); let method = self.register_infer_ok_obligations(ok); let mut adjustments = autoderef.adjust_steps(self, needs); if let ty::Ref(region, _, r_mutbl) = method.sig.inputs()[0].kind { let mutbl = match r_mutbl { hir::Mutability::Not => AutoBorrowMutability::Not, hir::Mutability::Mut => AutoBorrowMutability::Mut { // Indexing can be desugared to a method call, // so maybe we could use two-phase here. // See the documentation of AllowTwoPhase for why that's // not the case today. allow_two_phase_borrow: AllowTwoPhase::No, }, }; adjustments.push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)), target: self .tcx .mk_ref(region, ty::TypeAndMut { mutbl: r_mutbl, ty: adjusted_ty }), }); } if unsize { adjustments.push(Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target: method.sig.inputs()[0], }); } self.apply_adjustments(base_expr, adjustments); self.write_method_call(expr.hir_id, method); (input_ty, self.make_overloaded_place_return_type(method).ty) }); if result.is_some() { return result; } } None } fn resolve_place_op(&self, op: PlaceOp, is_mut: bool) -> (Option<DefId>, ast::Ident) { let (tr, name) = match (op, is_mut) { (PlaceOp::Deref, false) => (self.tcx.lang_items().deref_trait(), sym::deref), (PlaceOp::Deref, true) => (self.tcx.lang_items().deref_mut_trait(), sym::deref_mut), (PlaceOp::Index, false) => (self.tcx.lang_items().index_trait(), sym::index), (PlaceOp::Index, true) => (self.tcx.lang_items().index_mut_trait(), sym::index_mut), }; (tr, ast::Ident::with_dummy_span(name)) } fn try_overloaded_place_op( &self, span: Span, base_ty: Ty<'tcx>, arg_tys: &[Ty<'tcx>], needs: Needs, op: PlaceOp, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> { debug!("try_overloaded_place_op({:?},{:?},{:?},{:?})", span, base_ty, needs, op); // Try Mut first, if needed. let (mut_tr, mut_op) = self.resolve_place_op(op, true); let method = match (needs, mut_tr) { (Needs::MutPlace, Some(trait_did)) => { self.lookup_method_in_trait(span, mut_op, trait_did, base_ty, Some(arg_tys)) } _ => None, }; // Otherwise, fall back to the immutable version. let (imm_tr, imm_op) = self.resolve_place_op(op, false); let method = match (method, imm_tr) { (None, Some(trait_did)) => { self.lookup_method_in_trait(span, imm_op, trait_did, base_ty, Some(arg_tys)) } (method, _) => method, }; method } fn check_method_argument_types( &self, sp: Span, expr: &'tcx hir::Expr<'tcx>, method: Result<MethodCallee<'tcx>, ()>, args_no_rcvr: &'tcx [hir::Expr<'tcx>], tuple_arguments: TupleArgumentsFlag, expected: Expectation<'tcx>, ) -> Ty<'tcx> { let has_error = match method { Ok(method) => method.substs.references_error() || method.sig.references_error(), Err(_) => true, }; if has_error { let err_inputs = self.err_args(args_no_rcvr.len()); let err_inputs = match tuple_arguments { DontTupleArguments => err_inputs, TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..])], }; self.check_argument_types( sp, expr, &err_inputs[..], &[], args_no_rcvr, false, tuple_arguments, None, ); return self.tcx.types.err; } let method = method.unwrap(); // HACK(eddyb) ignore self in the definition (see above). let expected_arg_tys = self.expected_inputs_for_expected_output( sp, expected, method.sig.output(), &method.sig.inputs()[1..], ); self.check_argument_types( sp, expr, &method.sig.inputs()[1..], &expected_arg_tys[..], args_no_rcvr, method.sig.c_variadic, tuple_arguments, self.tcx.hir().span_if_local(method.def_id), ); method.sig.output() } fn self_type_matches_expected_vid( &self, trait_ref: ty::PolyTraitRef<'tcx>, expected_vid: ty::TyVid, ) -> bool { let self_ty = self.shallow_resolve(trait_ref.self_ty()); debug!( "self_type_matches_expected_vid(trait_ref={:?}, self_ty={:?}, expected_vid={:?})", trait_ref, self_ty, expected_vid ); match self_ty.kind { ty::Infer(ty::TyVar(found_vid)) => { // FIXME: consider using `sub_root_var` here so we // can see through subtyping. let found_vid = self.root_var(found_vid); debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid); expected_vid == found_vid } _ => false, } } fn obligations_for_self_ty<'b>( &'b self, self_ty: ty::TyVid, ) -> impl Iterator<Item = (ty::PolyTraitRef<'tcx>, traits::PredicateObligation<'tcx>)> + Captures<'tcx> + 'b { // FIXME: consider using `sub_root_var` here so we // can see through subtyping. let ty_var_root = self.root_var(self_ty); debug!( "obligations_for_self_ty: self_ty={:?} ty_var_root={:?} pending_obligations={:?}", self_ty, ty_var_root, self.fulfillment_cx.borrow().pending_obligations() ); self.fulfillment_cx .borrow() .pending_obligations() .into_iter() .filter_map(move |obligation| match obligation.predicate { ty::Predicate::Projection(ref data) => { Some((data.to_poly_trait_ref(self.tcx), obligation)) } ty::Predicate::Trait(ref data) => Some((data.to_poly_trait_ref(), obligation)), ty::Predicate::Subtype(..) => None, ty::Predicate::RegionOutlives(..) => None, ty::Predicate::TypeOutlives(..) => None, ty::Predicate::WellFormed(..) => None, ty::Predicate::ObjectSafe(..) => None, ty::Predicate::ConstEvaluatable(..) => None, // N.B., this predicate is created by breaking down a // `ClosureType: FnFoo()` predicate, where // `ClosureType` represents some `Closure`. It can't // possibly be referring to the current closure, // because we haven't produced the `Closure` for // this closure yet; this is exactly why the other // code is looking for a self type of a unresolved // inference variable. ty::Predicate::ClosureKind(..) => None, }) .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root)) } fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool { self.obligations_for_self_ty(self_ty) .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait()) } /// Generic function that factors out common logic from function calls, /// method calls and overloaded operators. fn check_argument_types( &self, sp: Span, expr: &'tcx hir::Expr<'tcx>, fn_inputs: &[Ty<'tcx>], expected_arg_tys: &[Ty<'tcx>], args: &'tcx [hir::Expr<'tcx>], c_variadic: bool, tuple_arguments: TupleArgumentsFlag, def_span: Option<Span>, ) { let tcx = self.tcx; // Grab the argument types, supplying fresh type variables // if the wrong number of arguments were supplied let supplied_arg_count = if tuple_arguments == DontTupleArguments { args.len() } else { 1 }; // All the input types from the fn signature must outlive the call // so as to validate implied bounds. for (fn_input_ty, arg_expr) in fn_inputs.iter().zip(args.iter()) { self.register_wf_obligation(fn_input_ty, arg_expr.span, traits::MiscObligation); } let expected_arg_count = fn_inputs.len(); let param_count_error = |expected_count: usize, arg_count: usize, error_code: &str, c_variadic: bool, sugg_unit: bool| { let mut err = tcx.sess.struct_span_err_with_code( sp, &format!( "this function takes {}{} but {} {} supplied", if c_variadic { "at least " } else { "" }, potentially_plural_count(expected_count, "parameter"), potentially_plural_count(arg_count, "parameter"), if arg_count == 1 { "was" } else { "were" } ), DiagnosticId::Error(error_code.to_owned()), ); if let Some(def_s) = def_span.map(|sp| tcx.sess.source_map().def_span(sp)) { err.span_label(def_s, "defined here"); } if sugg_unit { let sugg_span = tcx.sess.source_map().end_point(expr.span); // remove closing `)` from the span let sugg_span = sugg_span.shrink_to_lo(); err.span_suggestion( sugg_span, "expected the unit value `()`; create it with empty parentheses", String::from("()"), Applicability::MachineApplicable, ); } else { err.span_label( sp, format!( "expected {}{}", if c_variadic { "at least " } else { "" }, potentially_plural_count(expected_count, "parameter") ), ); } err.emit(); }; let mut expected_arg_tys = expected_arg_tys.to_vec(); let formal_tys = if tuple_arguments == TupleArguments { let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]); match tuple_type.kind { ty::Tuple(arg_types) if arg_types.len() != args.len() => { param_count_error(arg_types.len(), args.len(), "E0057", false, false); expected_arg_tys = vec![]; self.err_args(args.len()) } ty::Tuple(arg_types) => { expected_arg_tys = match expected_arg_tys.get(0) { Some(&ty) => match ty.kind { ty::Tuple(ref tys) => tys.iter().map(|k| k.expect_ty()).collect(), _ => vec![], }, None => vec![], }; arg_types.iter().map(|k| k.expect_ty()).collect() } _ => { struct_span_err!( tcx.sess, sp, E0059, "cannot use call notation; the first type parameter \ for the function trait is neither a tuple nor unit" ) .emit(); expected_arg_tys = vec![]; self.err_args(args.len()) } } } else if expected_arg_count == supplied_arg_count { fn_inputs.to_vec() } else if c_variadic { if supplied_arg_count >= expected_arg_count { fn_inputs.to_vec() } else { param_count_error(expected_arg_count, supplied_arg_count, "E0060", true, false); expected_arg_tys = vec![]; self.err_args(supplied_arg_count) } } else { // is the missing argument of type `()`? let sugg_unit = if expected_arg_tys.len() == 1 && supplied_arg_count == 0 { self.resolve_vars_if_possible(&expected_arg_tys[0]).is_unit() } else if fn_inputs.len() == 1 && supplied_arg_count == 0 { self.resolve_vars_if_possible(&fn_inputs[0]).is_unit() } else { false }; param_count_error(expected_arg_count, supplied_arg_count, "E0061", false, sugg_unit); expected_arg_tys = vec![]; self.err_args(supplied_arg_count) }; debug!( "check_argument_types: formal_tys={:?}", formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>() ); // If there is no expectation, expect formal_tys. let expected_arg_tys = if !expected_arg_tys.is_empty() { expected_arg_tys } else { formal_tys.clone() }; let mut final_arg_types: Vec<(usize, Ty<'_>, Ty<'_>)> = vec![]; // Check the arguments. // We do this in a pretty awful way: first we type-check any arguments // that are not closures, then we type-check the closures. This is so // that we have more information about the types of arguments when we // type-check the functions. This isn't really the right way to do this. for &check_closures in &[false, true] { debug!("check_closures={}", check_closures); // More awful hacks: before we check argument types, try to do // an "opportunistic" vtable resolution of any trait bounds on // the call. This helps coercions. if check_closures { self.select_obligations_where_possible(false, |errors| { self.point_at_type_arg_instead_of_call_if_possible(errors, expr); self.point_at_arg_instead_of_call_if_possible( errors, &final_arg_types[..], sp, &args, ); }) } // For C-variadic functions, we don't have a declared type for all of // the arguments hence we only do our usual type checking with // the arguments who's types we do know. let t = if c_variadic { expected_arg_count } else if tuple_arguments == TupleArguments { args.len() } else { supplied_arg_count }; for (i, arg) in args.iter().take(t).enumerate() { // Warn only for the first loop (the "no closures" one). // Closure arguments themselves can't be diverging, but // a previous argument can, e.g., `foo(panic!(), || {})`. if !check_closures { self.warn_if_unreachable(arg.hir_id, arg.span, "expression"); } let is_closure = match arg.kind { ExprKind::Closure(..) => true, _ => false, }; if is_closure != check_closures { continue; } debug!("checking the argument"); let formal_ty = formal_tys[i]; // The special-cased logic below has three functions: // 1. Provide as good of an expected type as possible. let expected = Expectation::rvalue_hint(self, expected_arg_tys[i]); let checked_ty = self.check_expr_with_expectation(&arg, expected); // 2. Coerce to the most detailed type that could be coerced // to, which is `expected_ty` if `rvalue_hint` returns an // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise. let coerce_ty = expected.only_has_type(self).unwrap_or(formal_ty); // We're processing function arguments so we definitely want to use // two-phase borrows. self.demand_coerce(&arg, checked_ty, coerce_ty, AllowTwoPhase::Yes); final_arg_types.push((i, checked_ty, coerce_ty)); // 3. Relate the expected type and the formal one, // if the expected type was used for the coercion. self.demand_suptype(arg.span, formal_ty, coerce_ty); } } // We also need to make sure we at least write the ty of the other // arguments which we skipped above. if c_variadic { fn variadic_error<'tcx>(s: &Session, span: Span, t: Ty<'tcx>, cast_ty: &str) { use crate::structured_errors::{StructuredDiagnostic, VariadicError}; VariadicError::new(s, span, t, cast_ty).diagnostic().emit(); } for arg in args.iter().skip(expected_arg_count) { let arg_ty = self.check_expr(&arg); // There are a few types which get autopromoted when passed via varargs // in C but we just error out instead and require explicit casts. let arg_ty = self.structurally_resolved_type(arg.span, arg_ty); match arg_ty.kind { ty::Float(ast::FloatTy::F32) => { variadic_error(tcx.sess, arg.span, arg_ty, "c_double"); } ty::Int(ast::IntTy::I8) | ty::Int(ast::IntTy::I16) | ty::Bool => { variadic_error(tcx.sess, arg.span, arg_ty, "c_int"); } ty::Uint(ast::UintTy::U8) | ty::Uint(ast::UintTy::U16) => { variadic_error(tcx.sess, arg.span, arg_ty, "c_uint"); } ty::FnDef(..) => { let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx)); let ptr_ty = self.resolve_vars_if_possible(&ptr_ty); variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string()); } _ => {} } } } } fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> { vec![self.tcx.types.err; len] } /// Given a vec of evaluated `FulfillmentError`s and an `fn` call argument expressions, we walk /// the checked and coerced types for each argument to see if any of the `FulfillmentError`s /// reference a type argument. The reason to walk also the checked type is that the coerced type /// can be not easily comparable with predicate type (because of coercion). If the types match /// for either checked or coerced type, and there's only *one* argument that does, we point at /// the corresponding argument's expression span instead of the `fn` call path span. fn point_at_arg_instead_of_call_if_possible( &self, errors: &mut Vec<traits::FulfillmentError<'_>>, final_arg_types: &[(usize, Ty<'tcx>, Ty<'tcx>)], call_sp: Span, args: &'tcx [hir::Expr<'tcx>], ) { // We *do not* do this for desugared call spans to keep good diagnostics when involving // the `?` operator. if call_sp.desugaring_kind().is_some() { return; } for error in errors { // Only if the cause is somewhere inside the expression we want try to point at arg. // Otherwise, it means that the cause is somewhere else and we should not change // anything because we can break the correct span. if !call_sp.contains(error.obligation.cause.span) { continue; } if let ty::Predicate::Trait(predicate) = error.obligation.predicate { // Collect the argument position for all arguments that could have caused this // `FulfillmentError`. let mut referenced_in = final_arg_types .iter() .map(|(i, checked_ty, _)| (i, checked_ty)) .chain(final_arg_types.iter().map(|(i, _, coerced_ty)| (i, coerced_ty))) .flat_map(|(i, ty)| { let ty = self.resolve_vars_if_possible(ty); // We walk the argument type because the argument's type could have // been `Option<T>`, but the `FulfillmentError` references `T`. ty.walk() .filter(|&ty| ty == predicate.skip_binder().self_ty()) .map(move |_| *i) }) .collect::<Vec<_>>(); // Both checked and coerced types could have matched, thus we need to remove // duplicates. referenced_in.dedup(); if let (Some(ref_in), None) = (referenced_in.pop(), referenced_in.pop()) { // We make sure that only *one* argument matches the obligation failure // and we assign the obligation's span to its expression's. error.obligation.cause.span = args[ref_in].span; error.points_at_arg_span = true; } } } } /// Given a vec of evaluated `FulfillmentError`s and an `fn` call expression, we walk the /// `PathSegment`s and resolve their type parameters to see if any of the `FulfillmentError`s /// were caused by them. If they were, we point at the corresponding type argument's span /// instead of the `fn` call path span. fn point_at_type_arg_instead_of_call_if_possible( &self, errors: &mut Vec<traits::FulfillmentError<'_>>, call_expr: &'tcx hir::Expr<'tcx>, ) { if let hir::ExprKind::Call(path, _) = &call_expr.kind { if let hir::ExprKind::Path(qpath) = &path.kind { if let hir::QPath::Resolved(_, path) = &qpath { for error in errors { if let ty::Predicate::Trait(predicate) = error.obligation.predicate { // If any of the type arguments in this path segment caused the // `FullfillmentError`, point at its span (#61860). for arg in path .segments .iter() .filter_map(|seg| seg.args.as_ref()) .flat_map(|a| a.args.iter()) { if let hir::GenericArg::Type(hir_ty) = &arg { if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) = &hir_ty.kind { // Avoid ICE with associated types. As this is best // effort only, it's ok to ignore the case. It // would trigger in `is_send::<T::AssocType>();` // from `typeck-default-trait-impl-assoc-type.rs`. } else { let ty = AstConv::ast_ty_to_ty(self, hir_ty); let ty = self.resolve_vars_if_possible(&ty); if ty == predicate.skip_binder().self_ty() { error.obligation.cause.span = hir_ty.span; } } } } } } } } } } // AST fragment checking fn check_lit(&self, lit: &hir::Lit, expected: Expectation<'tcx>) -> Ty<'tcx> { let tcx = self.tcx; match lit.node { ast::LitKind::Str(..) => tcx.mk_static_str(), ast::LitKind::ByteStr(ref v) => { tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.u8, v.len() as u64)) } ast::LitKind::Byte(_) => tcx.types.u8, ast::LitKind::Char(_) => tcx.types.char, ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t), ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t), ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => { let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind { ty::Int(_) | ty::Uint(_) => Some(ty), ty::Char => Some(tcx.types.u8), ty::RawPtr(..) => Some(tcx.types.usize), ty::FnDef(..) | ty::FnPtr(_) => Some(tcx.types.usize), _ => None, }); opt_ty.unwrap_or_else(|| self.next_int_var()) } ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => tcx.mk_mach_float(t), ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => { let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind { ty::Float(_) => Some(ty), _ => None, }); opt_ty.unwrap_or_else(|| self.next_float_var()) } ast::LitKind::Bool(_) => tcx.types.bool, ast::LitKind::Err(_) => tcx.types.err, } } // Determine the `Self` type, using fresh variables for all variables // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>` // would return `($0, $1)` where `$0` and `$1` are freshly instantiated type // variables. pub fn impl_self_ty( &self, span: Span, // (potential) receiver for this impl did: DefId, ) -> TypeAndSubsts<'tcx> { let ity = self.tcx.type_of(did); debug!("impl_self_ty: ity={:?}", ity); let substs = self.fresh_substs_for_item(span, did); let substd_ty = self.instantiate_type_scheme(span, &substs, &ity); TypeAndSubsts { substs: substs, ty: substd_ty } } /// Unifies the output type with the expected type early, for more coercions /// and forward type information on the input expressions. fn expected_inputs_for_expected_output( &self, call_span: Span, expected_ret: Expectation<'tcx>, formal_ret: Ty<'tcx>, formal_args: &[Ty<'tcx>], ) -> Vec<Ty<'tcx>> { let formal_ret = self.resolve_vars_with_obligations(formal_ret); let ret_ty = match expected_ret.only_has_type(self) { Some(ret) => ret, None => return Vec::new(), }; let expect_args = self .fudge_inference_if_ok(|| { // Attempt to apply a subtyping relationship between the formal // return type (likely containing type variables if the function // is polymorphic) and the expected return type. // No argument expectations are produced if unification fails. let origin = self.misc(call_span); let ures = self.at(&origin, self.param_env).sup(ret_ty, &formal_ret); // FIXME(#27336) can't use ? here, Try::from_error doesn't default // to identity so the resulting type is not constrained. match ures { Ok(ok) => { // Process any obligations locally as much as // we can. We don't care if some things turn // out unconstrained or ambiguous, as we're // just trying to get hints here. self.save_and_restore_in_snapshot_flag(|_| { let mut fulfill = TraitEngine::new(self.tcx); for obligation in ok.obligations { fulfill.register_predicate_obligation(self, obligation); } fulfill.select_where_possible(self) }) .map_err(|_| ())?; } Err(_) => return Err(()), } // Record all the argument types, with the substitutions // produced from the above subtyping unification. Ok(formal_args.iter().map(|ty| self.resolve_vars_if_possible(ty)).collect()) }) .unwrap_or_default(); debug!( "expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})", formal_args, formal_ret, expect_args, expected_ret ); expect_args } pub fn check_struct_path( &self, qpath: &QPath<'_>, hir_id: hir::HirId, ) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { let path_span = match *qpath { QPath::Resolved(_, ref path) => path.span, QPath::TypeRelative(ref qself, _) => qself.span, }; let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id); let variant = match def { Res::Err => { self.set_tainted_by_errors(); return None; } Res::Def(DefKind::Variant, _) => match ty.kind { ty::Adt(adt, substs) => Some((adt.variant_of_res(def), adt.did, substs)), _ => bug!("unexpected type: {:?}", ty), }, Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) | Res::Def(DefKind::TyAlias, _) | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) => match ty.kind { ty::Adt(adt, substs) if !adt.is_enum() => { Some((adt.non_enum_variant(), adt.did, substs)) } _ => None, }, _ => bug!("unexpected definition: {:?}", def), }; if let Some((variant, did, substs)) = variant { debug!("check_struct_path: did={:?} substs={:?}", did, substs); self.write_user_type_annotation_from_substs(hir_id, did, substs, None); // Check bounds on type arguments used in the path. let (bounds, _) = self.instantiate_bounds(path_span, did, substs); let cause = traits::ObligationCause::new(path_span, self.body_id, traits::ItemObligation(did)); self.add_obligations_for_parameters(cause, &bounds); Some((variant, ty)) } else { struct_span_err!( self.tcx.sess, path_span, E0071, "expected struct, variant or union type, found {}", ty.sort_string(self.tcx) ) .span_label(path_span, "not a struct") .emit(); None } } // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary. // The newly resolved definition is written into `type_dependent_defs`. fn finish_resolving_struct_path( &self, qpath: &QPath<'_>, path_span: Span, hir_id: hir::HirId, ) -> (Res, Ty<'tcx>) { match *qpath { QPath::Resolved(ref maybe_qself, ref path) => { let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself)); let ty = AstConv::res_to_ty(self, self_ty, path, true); (path.res, ty) } QPath::TypeRelative(ref qself, ref segment) => { let ty = self.to_ty(qself); let res = if let hir::TyKind::Path(QPath::Resolved(_, ref path)) = qself.kind { path.res } else { Res::Err }; let result = AstConv::associated_path_to_ty(self, hir_id, path_span, ty, res, segment, true); let ty = result.map(|(ty, _, _)| ty).unwrap_or(self.tcx().types.err); let result = result.map(|(_, kind, def_id)| (kind, def_id)); // Write back the new resolution. self.write_resolution(hir_id, result); (result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err), ty) } } } /// Resolves an associated value path into a base type and associated constant, or method /// resolution. The newly resolved definition is written into `type_dependent_defs`. pub fn resolve_ty_and_res_ufcs<'b>( &self, qpath: &'b QPath<'b>, hir_id: hir::HirId, span: Span, ) -> (Res, Option<Ty<'tcx>>, &'b [hir::PathSegment<'b>]) { debug!("resolve_ty_and_res_ufcs: qpath={:?} hir_id={:?} span={:?}", qpath, hir_id, span); let (ty, qself, item_segment) = match *qpath { QPath::Resolved(ref opt_qself, ref path) => { return ( path.res, opt_qself.as_ref().map(|qself| self.to_ty(qself)), &path.segments[..], ); } QPath::TypeRelative(ref qself, ref segment) => (self.to_ty(qself), qself, segment), }; if let Some(&cached_result) = self.tables.borrow().type_dependent_defs().get(hir_id) { // Return directly on cache hit. This is useful to avoid doubly reporting // errors with default match binding modes. See #44614. let def = cached_result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err); return (def, Some(ty), slice::from_ref(&**item_segment)); } let item_name = item_segment.ident; let result = self.resolve_ufcs(span, item_name, ty, hir_id).or_else(|error| { let result = match error { method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)), _ => Err(ErrorReported), }; if item_name.name != kw::Invalid { self.report_method_error( span, ty, item_name, SelfSource::QPath(qself), error, None, ) .map(|mut e| e.emit()); } result }); // Write back the new resolution. self.write_resolution(hir_id, result); ( result.map(|(kind, def_id)| Res::Def(kind, def_id)).unwrap_or(Res::Err), Some(ty), slice::from_ref(&**item_segment), ) } pub fn check_decl_initializer( &self, local: &'tcx hir::Local<'tcx>, init: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { // FIXME(tschottdorf): `contains_explicit_ref_binding()` must be removed // for #42640 (default match binding modes). // // See #44848. let ref_bindings = local.pat.contains_explicit_ref_binding(); let local_ty = self.local_ty(init.span, local.hir_id).revealed_ty; if let Some(m) = ref_bindings { // Somewhat subtle: if we have a `ref` binding in the pattern, // we want to avoid introducing coercions for the RHS. This is // both because it helps preserve sanity and, in the case of // ref mut, for soundness (issue #23116). In particular, in // the latter case, we need to be clear that the type of the // referent for the reference that results is *equal to* the // type of the place it is referencing, and not some // supertype thereof. let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m)); self.demand_eqtype(init.span, local_ty, init_ty); init_ty } else { self.check_expr_coercable_to_type(init, local_ty) } } /// Type check a `let` statement. pub fn check_decl_local(&self, local: &'tcx hir::Local<'tcx>) { // Determine and write the type which we'll check the pattern against. let ty = self.local_ty(local.span, local.hir_id).decl_ty; self.write_ty(local.hir_id, ty); // Type check the initializer. if let Some(ref init) = local.init { let init_ty = self.check_decl_initializer(local, &init); self.overwrite_local_ty_if_err(local, ty, init_ty); } // Does the expected pattern type originate from an expression and what is the span? let (origin_expr, ty_span) = match (local.ty, local.init) { (Some(ty), _) => (false, Some(ty.span)), // Bias towards the explicit user type. (_, Some(init)) => (true, Some(init.span)), // No explicit type; so use the scrutinee. _ => (false, None), // We have `let $pat;`, so the expected type is unconstrained. }; // Type check the pattern. Override if necessary to avoid knock-on errors. self.check_pat_top(&local.pat, ty, ty_span, origin_expr); let pat_ty = self.node_ty(local.pat.hir_id); self.overwrite_local_ty_if_err(local, ty, pat_ty); } fn overwrite_local_ty_if_err( &self, local: &'tcx hir::Local<'tcx>, decl_ty: Ty<'tcx>, ty: Ty<'tcx>, ) { if ty.references_error() { // Override the types everywhere with `types.err` to avoid knock on errors. self.write_ty(local.hir_id, ty); self.write_ty(local.pat.hir_id, ty); let local_ty = LocalTy { decl_ty, revealed_ty: ty }; self.locals.borrow_mut().insert(local.hir_id, local_ty); self.locals.borrow_mut().insert(local.pat.hir_id, local_ty); } } fn suggest_semicolon_at_end(&self, span: Span, err: &mut DiagnosticBuilder<'_>) { err.span_suggestion_short( span.shrink_to_hi(), "consider using a semicolon here", ";".to_string(), Applicability::MachineApplicable, ); } pub fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>) { // Don't do all the complex logic below for `DeclItem`. match stmt.kind { hir::StmtKind::Item(..) => return, hir::StmtKind::Local(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} } self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement"); // Hide the outer diverging and `has_errors` flags. let old_diverges = self.diverges.get(); let old_has_errors = self.has_errors.get(); self.diverges.set(Diverges::Maybe); self.has_errors.set(false); match stmt.kind { hir::StmtKind::Local(ref l) => { self.check_decl_local(&l); } // Ignore for now. hir::StmtKind::Item(_) => {} hir::StmtKind::Expr(ref expr) => { // Check with expected type of `()`. self.check_expr_has_type_or_error(&expr, self.tcx.mk_unit(), |err| { self.suggest_semicolon_at_end(expr.span, err); }); } hir::StmtKind::Semi(ref expr) => { self.check_expr(&expr); } } // Combine the diverging and `has_error` flags. self.diverges.set(self.diverges.get() | old_diverges); self.has_errors.set(self.has_errors.get() | old_has_errors); } pub fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) { let unit = self.tcx.mk_unit(); let ty = self.check_block_with_expected(blk, ExpectHasType(unit)); // if the block produces a `!` value, that can always be // (effectively) coerced to unit. if !ty.is_never() { self.demand_suptype(blk.span, unit, ty); } } /// If `expr` is a `match` expression that has only one non-`!` arm, use that arm's tail /// expression's `Span`, otherwise return `expr.span`. This is done to give better errors /// when given code like the following: /// ```text /// if false { return 0i32; } else { 1u32 } /// // ^^^^ point at this instead of the whole `if` expression /// ``` fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span { if let hir::ExprKind::Match(_, arms, _) = &expr.kind { let arm_spans: Vec<Span> = arms .iter() .filter_map(|arm| { self.in_progress_tables .and_then(|tables| tables.borrow().node_type_opt(arm.body.hir_id)) .and_then(|arm_ty| { if arm_ty.is_never() { None } else { Some(match &arm.body.kind { // Point at the tail expression when possible. hir::ExprKind::Block(block, _) => { block.expr.as_ref().map(|e| e.span).unwrap_or(block.span) } _ => arm.body.span, }) } }) }) .collect(); if arm_spans.len() == 1 { return arm_spans[0]; } } expr.span } fn check_block_with_expected( &self, blk: &'tcx hir::Block<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx> { let prev = { let mut fcx_ps = self.ps.borrow_mut(); let unsafety_state = fcx_ps.recurse(blk); replace(&mut *fcx_ps, unsafety_state) }; // In some cases, blocks have just one exit, but other blocks // can be targeted by multiple breaks. This can happen both // with labeled blocks as well as when we desugar // a `try { ... }` expression. // // Example 1: // // 'a: { if true { break 'a Err(()); } Ok(()) } // // Here we would wind up with two coercions, one from // `Err(())` and the other from the tail expression // `Ok(())`. If the tail expression is omitted, that's a // "forced unit" -- unless the block diverges, in which // case we can ignore the tail expression (e.g., `'a: { // break 'a 22; }` would not force the type of the block // to be `()`). let tail_expr = blk.expr.as_ref(); let coerce_to_ty = expected.coercion_target_type(self, blk.span); let coerce = if blk.targeted_by_break { CoerceMany::new(coerce_to_ty) } else { let tail_expr: &[&hir::Expr<'_>] = match tail_expr { Some(e) => slice::from_ref(e), None => &[], }; CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr) }; let prev_diverges = self.diverges.get(); let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false }; let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || { for s in blk.stmts { self.check_stmt(s); } // check the tail expression **without** holding the // `enclosing_breakables` lock below. let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected)); let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let ctxt = enclosing_breakables.find_breakable(blk.hir_id); let coerce = ctxt.coerce.as_mut().unwrap(); if let Some(tail_expr_ty) = tail_expr_ty { let tail_expr = tail_expr.unwrap(); let span = self.get_expr_coercion_span(tail_expr); let cause = self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id)); coerce.coerce(self, &cause, tail_expr, tail_expr_ty); } else { // Subtle: if there is no explicit tail expression, // that is typically equivalent to a tail expression // of `()` -- except if the block diverges. In that // case, there is no value supplied from the tail // expression (assuming there are no other breaks, // this implies that the type of the block will be // `!`). // // #41425 -- label the implicit `()` as being the // "found type" here, rather than the "expected type". if !self.diverges.get().is_always() { // #50009 -- Do not point at the entire fn block span, point at the return type // span, as it is the cause of the requirement, and // `consider_hint_about_removing_semicolon` will point at the last expression // if it were a relevant part of the error. This improves usability in editors // that highlight errors inline. let mut sp = blk.span; let mut fn_span = None; if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) { let ret_sp = decl.output.span(); if let Some(block_sp) = self.parent_item_span(blk.hir_id) { // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the // output would otherwise be incorrect and even misleading. Make sure // the span we're aiming at correspond to a `fn` body. if block_sp == blk.span { sp = ret_sp; fn_span = Some(ident.span); } } } coerce.coerce_forced_unit( self, &self.misc(sp), &mut |err| { if let Some(expected_ty) = expected.only_has_type(self) { self.consider_hint_about_removing_semicolon(blk, expected_ty, err); } if let Some(fn_span) = fn_span { err.span_label( fn_span, "implicitly returns `()` as its body has no tail or `return` \ expression", ); } }, false, ); } } }); if ctxt.may_break { // If we can break from the block, then the block's exit is always reachable // (... as long as the entry is reachable) - regardless of the tail of the block. self.diverges.set(prev_diverges); } let mut ty = ctxt.coerce.unwrap().complete(self); if self.has_errors.get() || ty.references_error() { ty = self.tcx.types.err } self.write_ty(blk.hir_id, ty); *self.ps.borrow_mut() = prev; ty } fn parent_item_span(&self, id: hir::HirId) -> Option<Span> { let node = self.tcx.hir().get(self.tcx.hir().get_parent_item(id)); match node { Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(_, body_id), .. }) => { let body = self.tcx.hir().body(body_id); if let ExprKind::Block(block, _) = &body.value.kind { return Some(block.span); } } _ => {} } None } /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise. fn get_parent_fn_decl( &self, blk_id: hir::HirId, ) -> Option<(&'tcx hir::FnDecl<'tcx>, ast::Ident)> { let parent = self.tcx.hir().get(self.tcx.hir().get_parent_item(blk_id)); self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident)) } /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise. fn get_node_fn_decl( &self, node: Node<'tcx>, ) -> Option<(&'tcx hir::FnDecl<'tcx>, ast::Ident, bool)> { match node { Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => { // This is less than ideal, it will not suggest a return type span on any // method called `main`, regardless of whether it is actually the entry point, // but it will still present it as the reason for the expected type. Some((&sig.decl, ident, ident.name != sym::main)) } Node::TraitItem(&hir::TraitItem { ident, kind: hir::TraitItemKind::Method(ref sig, ..), .. }) => Some((&sig.decl, ident, true)), Node::ImplItem(&hir::ImplItem { ident, kind: hir::ImplItemKind::Method(ref sig, ..), .. }) => Some((&sig.decl, ident, false)), _ => None, } } /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a /// suggestion can be made, `None` otherwise. pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { let parent = self.tcx.hir().get(blk_id); self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main)) }) } /// On implicit return expressions with mismatched types, provides the following suggestions: /// /// - Points out the method's return type as the reason for the expected type. /// - Possible missing semicolon. /// - Possible missing return type if the return type is the default, and not `fn main()`. pub fn suggest_mismatched_types_on_tail( &self, err: &mut DiagnosticBuilder<'_>, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, cause_span: Span, blk_id: hir::HirId, ) -> bool { let expr = expr.peel_drop_temps(); self.suggest_missing_semicolon(err, expr, expected, cause_span); let mut pointing_at_return_type = false; if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) { pointing_at_return_type = self.suggest_missing_return_type(err, &fn_decl, expected, found, can_suggest); } pointing_at_return_type } /// When encountering an fn-like ctor that needs to unify with a value, check whether calling /// the ctor would successfully solve the type mismatch and if so, suggest it: /// ``` /// fn foo(x: usize) -> usize { x } /// let x: usize = foo; // suggest calling the `foo` function: `foo(42)` /// ``` fn suggest_fn_call( &self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { let hir = self.tcx.hir(); let (def_id, sig) = match found.kind { ty::FnDef(def_id, _) => (def_id, found.fn_sig(self.tcx)), ty::Closure(def_id, substs) => { // We don't use `closure_sig` to account for malformed closures like // `|_: [_; continue]| {}` and instead we don't suggest anything. let closure_sig_ty = substs.as_closure().sig_ty(def_id, self.tcx); ( def_id, match closure_sig_ty.kind { ty::FnPtr(sig) => sig, _ => return false, }, ) } _ => return false, }; let sig = self.replace_bound_vars_with_fresh_vars(expr.span, infer::FnCall, &sig).0; let sig = self.normalize_associated_types_in(expr.span, &sig); if self.can_coerce(sig.output(), expected) { let (mut sugg_call, applicability) = if sig.inputs().is_empty() { (String::new(), Applicability::MachineApplicable) } else { ("...".to_string(), Applicability::HasPlaceholders) }; let mut msg = "call this function"; match hir.get_if_local(def_id) { Some(Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })) | Some(Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Method(_, body_id), .. })) | Some(Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Method(.., hir::TraitMethod::Provided(body_id)), .. })) => { let body = hir.body(*body_id); sugg_call = body .params .iter() .map(|param| match &param.pat.kind { hir::PatKind::Binding(_, _, ident, None) if ident.name != kw::SelfLower => { ident.to_string() } _ => "_".to_string(), }) .collect::<Vec<_>>() .join(", "); } Some(Node::Expr(hir::Expr { kind: ExprKind::Closure(_, _, body_id, _, _), span: full_closure_span, .. })) => { if *full_closure_span == expr.span { return false; } msg = "call this closure"; let body = hir.body(*body_id); sugg_call = body .params .iter() .map(|param| match &param.pat.kind { hir::PatKind::Binding(_, _, ident, None) if ident.name != kw::SelfLower => { ident.to_string() } _ => "_".to_string(), }) .collect::<Vec<_>>() .join(", "); } Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => { sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", "); match hir.as_local_hir_id(def_id).and_then(|hir_id| hir.def_kind(hir_id)) { Some(hir::def::DefKind::Ctor(hir::def::CtorOf::Variant, _)) => { msg = "instantiate this tuple variant"; } Some(hir::def::DefKind::Ctor(hir::def::CtorOf::Struct, _)) => { msg = "instantiate this tuple struct"; } _ => {} } } Some(Node::ForeignItem(hir::ForeignItem { kind: hir::ForeignItemKind::Fn(_, idents, _), .. })) => { sugg_call = idents .iter() .map(|ident| { if ident.name != kw::SelfLower { ident.to_string() } else { "_".to_string() } }) .collect::<Vec<_>>() .join(", ") } Some(Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Method(.., hir::TraitMethod::Required(idents)), .. })) => { sugg_call = idents .iter() .map(|ident| { if ident.name != kw::SelfLower { ident.to_string() } else { "_".to_string() } }) .collect::<Vec<_>>() .join(", ") } _ => {} } if let Ok(code) = self.sess().source_map().span_to_snippet(expr.span) { err.span_suggestion( expr.span, &format!("use parentheses to {}", msg), format!("{}({})", code, sugg_call), applicability, ); return true; } } false } pub fn suggest_ref_or_into( &self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, ) { if let Some((sp, msg, suggestion)) = self.check_ref(expr, found, expected) { err.span_suggestion(sp, msg, suggestion, Applicability::MachineApplicable); } else if let (ty::FnDef(def_id, ..), true) = (&found.kind, self.suggest_fn_call(err, expr, expected, found)) { if let Some(sp) = self.tcx.hir().span_if_local(*def_id) { let sp = self.sess().source_map().def_span(sp); err.span_label(sp, &format!("{} defined here", found)); } } else if !self.check_for_cast(err, expr, found, expected) { let is_struct_pat_shorthand_field = self.is_hir_id_from_struct_pattern_shorthand_field(expr.hir_id, expr.span); let methods = self.get_conversion_methods(expr.span, expected, found); if let Ok(expr_text) = self.sess().source_map().span_to_snippet(expr.span) { let mut suggestions = iter::repeat(&expr_text) .zip(methods.iter()) .filter_map(|(receiver, method)| { let method_call = format!(".{}()", method.ident); if receiver.ends_with(&method_call) { None // do not suggest code that is already there (#53348) } else { let method_call_list = [".to_vec()", ".to_string()"]; let sugg = if receiver.ends_with(".clone()") && method_call_list.contains(&method_call.as_str()) { let max_len = receiver.rfind(".").unwrap(); format!("{}{}", &receiver[..max_len], method_call) } else { if expr.precedence().order() < ExprPrecedence::MethodCall.order() { format!("({}){}", receiver, method_call) } else { format!("{}{}", receiver, method_call) } }; Some(if is_struct_pat_shorthand_field { format!("{}: {}", receiver, sugg) } else { sugg }) } }) .peekable(); if suggestions.peek().is_some() { err.span_suggestions( expr.span, "try using a conversion method", suggestions, Applicability::MaybeIncorrect, ); } } } } /// When encountering the expected boxed value allocated in the stack, suggest allocating it /// in the heap by calling `Box::new()`. fn suggest_boxing_when_appropriate( &self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, ) { if self.tcx.hir().is_const_context(expr.hir_id) { // Do not suggest `Box::new` in const context. return; } if !expected.is_box() || found.is_box() { return; } let boxed_found = self.tcx.mk_box(found); if let (true, Ok(snippet)) = ( self.can_coerce(boxed_found, expected), self.sess().source_map().span_to_snippet(expr.span), ) { err.span_suggestion( expr.span, "store this in the heap by calling `Box::new`", format!("Box::new({})", snippet), Applicability::MachineApplicable, ); err.note( "for more on the distinction between the stack and the \ heap, read https://doc.rust-lang.org/book/ch15-01-box.html, \ https://doc.rust-lang.org/rust-by-example/std/box.html, and \ https://doc.rust-lang.org/std/boxed/index.html", ); } } /// A common error is to forget to add a semicolon at the end of a block, e.g., /// /// ``` /// fn foo() { /// bar_that_returns_u32() /// } /// ``` /// /// This routine checks if the return expression in a block would make sense on its own as a /// statement and the return type has been left as default or has been specified as `()`. If so, /// it suggests adding a semicolon. fn suggest_missing_semicolon( &self, err: &mut DiagnosticBuilder<'_>, expression: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>, cause_span: Span, ) { if expected.is_unit() { // `BlockTailExpression` only relevant if the tail expr would be // useful on its own. match expression.kind { ExprKind::Call(..) | ExprKind::MethodCall(..) | ExprKind::Loop(..) | ExprKind::Match(..) | ExprKind::Block(..) => { err.span_suggestion( cause_span.shrink_to_hi(), "try adding a semicolon", ";".to_string(), Applicability::MachineApplicable, ); } _ => (), } } } /// A possible error is to forget to add a return type that is needed: /// /// ``` /// fn foo() { /// bar_that_returns_u32() /// } /// ``` /// /// This routine checks if the return type is left as default, the method is not part of an /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return /// type. fn suggest_missing_return_type( &self, err: &mut DiagnosticBuilder<'_>, fn_decl: &hir::FnDecl<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, can_suggest: bool, ) -> bool { // Only suggest changing the return type for methods that // haven't set a return type at all (and aren't `fn main()` or an impl). match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_unit()) { (&hir::FunctionRetTy::DefaultReturn(span), true, true, true) => { err.span_suggestion( span, "try adding a return type", format!("-> {} ", self.resolve_vars_with_obligations(found)), Applicability::MachineApplicable, ); true } (&hir::FunctionRetTy::DefaultReturn(span), false, true, true) => { err.span_label(span, "possibly return type missing here?"); true } (&hir::FunctionRetTy::DefaultReturn(span), _, false, true) => { // `fn main()` must return `()`, do not suggest changing return type err.span_label(span, "expected `()` because of default return type"); true } // expectation was caused by something else, not the default return (&hir::FunctionRetTy::DefaultReturn(_), _, _, false) => false, (&hir::FunctionRetTy::Return(ref ty), _, _, _) => { // Only point to return type if the expected type is the return type, as if they // are not, the expectation must have been caused by something else. debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.kind); let sp = ty.span; let ty = AstConv::ast_ty_to_ty(self, ty); debug!("suggest_missing_return_type: return type {:?}", ty); debug!("suggest_missing_return_type: expected type {:?}", ty); if ty.kind == expected.kind { err.span_label(sp, format!("expected `{}` because of return type", expected)); return true; } false } } } /// A possible error is to forget to add `.await` when using futures: /// /// ``` /// async fn make_u32() -> u32 { /// 22 /// } /// /// fn take_u32(x: u32) {} /// /// async fn foo() { /// let x = make_u32(); /// take_u32(x); /// } /// ``` /// /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the /// expected type. If this is the case, and we are inside of an async body, it suggests adding /// `.await` to the tail of the expression. fn suggest_missing_await( &self, err: &mut DiagnosticBuilder<'_>, expr: &hir::Expr<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, )
/// A common error is to add an extra semicolon: /// /// ``` /// fn foo() -> usize { /// 22; /// } /// ``` /// /// This routine checks if the final statement in a block is an /// expression with an explicit semicolon whose type is compatible /// with `expected_ty`. If so, it suggests removing the semicolon. fn consider_hint_about_removing_semicolon( &self, blk: &'tcx hir::Block<'tcx>, expected_ty: Ty<'tcx>, err: &mut DiagnosticBuilder<'_>, ) { if let Some(span_semi) = self.could_remove_semicolon(blk, expected_ty) { err.span_suggestion( span_semi, "consider removing this semicolon", String::new(), Applicability::MachineApplicable, ); } } fn could_remove_semicolon( &self, blk: &'tcx hir::Block<'tcx>, expected_ty: Ty<'tcx>, ) -> Option<Span> { // Be helpful when the user wrote `{... expr;}` and // taking the `;` off is enough to fix the error. let last_stmt = blk.stmts.last()?; let last_expr = match last_stmt.kind { hir::StmtKind::Semi(ref e) => e, _ => return None, }; let last_expr_ty = self.node_ty(last_expr.hir_id); if self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err() { return None; } let original_span = original_sp(last_stmt.span, blk.span); Some(original_span.with_lo(original_span.hi() - BytePos(1))) } // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. pub fn instantiate_value_path( &self, segments: &[hir::PathSegment<'_>], self_ty: Option<Ty<'tcx>>, res: Res, span: Span, hir_id: hir::HirId, ) -> (Ty<'tcx>, Res) { debug!( "instantiate_value_path(segments={:?}, self_ty={:?}, res={:?}, hir_id={})", segments, self_ty, res, hir_id, ); let tcx = self.tcx; let path_segs = match res { Res::Local(_) | Res::SelfCtor(_) => vec![], Res::Def(kind, def_id) => { AstConv::def_ids_for_value_path_segments(self, segments, self_ty, kind, def_id) } _ => bug!("instantiate_value_path on {:?}", res), }; let mut user_self_ty = None; let mut is_alias_variant_ctor = false; match res { Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) => { if let Some(self_ty) = self_ty { let adt_def = self_ty.ty_adt_def().unwrap(); user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did, self_ty }); is_alias_variant_ctor = true; } } Res::Def(DefKind::Method, def_id) | Res::Def(DefKind::AssocConst, def_id) => { let container = tcx.associated_item(def_id).container; debug!("instantiate_value_path: def_id={:?} container={:?}", def_id, container); match container { ty::TraitContainer(trait_did) => { callee::check_legal_trait_for_method_call(tcx, span, trait_did) } ty::ImplContainer(impl_def_id) => { if segments.len() == 1 { // `<T>::assoc` will end up here, and so // can `T::assoc`. It this came from an // inherent impl, we need to record the // `T` for posterity (see `UserSelfTy` for // details). let self_ty = self_ty.expect("UFCS sugared assoc missing Self"); user_self_ty = Some(UserSelfTy { impl_def_id, self_ty }); } } } } _ => {} } // Now that we have categorized what space the parameters for each // segment belong to, let's sort out the parameters that the user // provided (if any) into their appropriate spaces. We'll also report // errors if type parameters are provided in an inappropriate place. let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect(); let generics_has_err = AstConv::prohibit_generics( self, segments.iter().enumerate().filter_map(|(index, seg)| { if !generic_segs.contains(&index) || is_alias_variant_ctor { Some(seg) } else { None } }), ); if let Res::Local(hid) = res { let ty = self.local_ty(span, hid).decl_ty; let ty = self.normalize_associated_types_in(span, &ty); self.write_ty(hir_id, ty); return (ty, res); } if generics_has_err { // Don't try to infer type parameters when prohibited generic arguments were given. user_self_ty = None; } // Now we have to compare the types that the user *actually* // provided against the types that were *expected*. If the user // did not provide any types, then we want to substitute inference // variables. If the user provided some types, we may still need // to add defaults. If the user provided *too many* types, that's // a problem. let mut infer_args_for_err = FxHashSet::default(); for &PathSeg(def_id, index) in &path_segs { let seg = &segments[index]; let generics = tcx.generics_of(def_id); // Argument-position `impl Trait` is treated as a normal generic // parameter internally, but we don't allow users to specify the // parameter's value explicitly, so we have to do some error- // checking here. let suppress_errors = AstConv::check_generic_arg_count_for_call( tcx, span, &generics, &seg, false, // `is_method_call` ); if suppress_errors { infer_args_for_err.insert(index); self.set_tainted_by_errors(); // See issue #53251. } } let has_self = path_segs .last() .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self) .unwrap_or(false); let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { let ty = self.impl_self_ty(span, impl_def_id).ty; let adt_def = ty.ty_adt_def(); match ty.kind { ty::Adt(adt_def, substs) if adt_def.has_ctor() => { let variant = adt_def.non_enum_variant(); let ctor_def_id = variant.ctor_def_id.unwrap(); ( Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id), Some(substs), ) } _ => { let mut err = tcx.sess.struct_span_err( span, "the `Self` constructor can only be used with tuple or unit structs", ); if let Some(adt_def) = adt_def { match adt_def.adt_kind() { AdtKind::Enum => { err.help("did you mean to use one of the enum's variants?"); } AdtKind::Struct | AdtKind::Union => { err.span_suggestion( span, "use curly brackets", String::from("Self { /* fields */ }"), Applicability::HasPlaceholders, ); } } } err.emit(); return (tcx.types.err, res); } } } else { (res, None) }; let def_id = res.def_id(); // The things we are substituting into the type should not contain // escaping late-bound regions, and nor should the base type scheme. let ty = tcx.type_of(def_id); let substs = self_ctor_substs.unwrap_or_else(|| { AstConv::create_substs_for_generic_args( tcx, def_id, &[][..], has_self, self_ty, // Provide the generic args, and whether types should be inferred. |def_id| { if let Some(&PathSeg(_, index)) = path_segs.iter().find(|&PathSeg(did, _)| *did == def_id) { // If we've encountered an `impl Trait`-related error, we're just // going to infer the arguments for better error messages. if !infer_args_for_err.contains(&index) { // Check whether the user has provided generic arguments. if let Some(ref data) = segments[index].args { return (Some(data), segments[index].infer_args); } } return (None, segments[index].infer_args); } (None, true) }, // Provide substitutions for parameters for which (valid) arguments have been provided. |param, arg| match (&param.kind, arg) { (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { AstConv::ast_region_to_region(self, lt, Some(param)).into() } (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { self.to_ty(ty).into() } (GenericParamDefKind::Const, GenericArg::Const(ct)) => { self.to_const(&ct.value, self.tcx.type_of(param.def_id)).into() } _ => unreachable!(), }, // Provide substitutions for parameters for which arguments are inferred. |substs, param, infer_args| { match param.kind { GenericParamDefKind::Lifetime => { self.re_infer(Some(param), span).unwrap().into() } GenericParamDefKind::Type { has_default, .. } => { if !infer_args && has_default { // If we have a default, then we it doesn't matter that we're not // inferring the type arguments: we provide the default where any // is missing. let default = tcx.type_of(param.def_id); self.normalize_ty( span, default.subst_spanned(tcx, substs.unwrap(), Some(span)), ) .into() } else { // If no type arguments were provided, we have to infer them. // This case also occurs as a result of some malformed input, e.g. // a lifetime argument being given instead of a type parameter. // Using inference instead of `Error` gives better error messages. self.var_for_def(span, param) } } GenericParamDefKind::Const => { // FIXME(const_generics:defaults) // No const parameters were provided, we have to infer them. self.var_for_def(span, param) } } }, ) }); assert!(!substs.has_escaping_bound_vars()); assert!(!ty.has_escaping_bound_vars()); // First, store the "user substs" for later. self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty); self.add_required_obligations(span, def_id, &substs); // Substitute the values for the type parameters into the type of // the referenced item. let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty); if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method` // is inherent, there is no `Self` parameter; instead, the impl needs // type parameters, which we can infer by unifying the provided `Self` // with the substituted impl type. // This also occurs for an enum variant on a type alias. let ty = tcx.type_of(impl_def_id); let impl_ty = self.instantiate_type_scheme(span, &substs, &ty); match self.at(&self.misc(span), self.param_env).sup(impl_ty, self_ty) { Ok(ok) => self.register_infer_ok_obligations(ok), Err(_) => { self.tcx.sess.delay_span_bug(span, &format!( "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", self_ty, impl_ty, )); } } } self.check_rustc_args_require_const(def_id, hir_id, span); debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted); self.write_substs(hir_id, substs); (ty_substituted, res) } /// Add all the obligations that are required, substituting and normalized appropriately. fn add_required_obligations(&self, span: Span, def_id: DefId, substs: &SubstsRef<'tcx>) { let (bounds, spans) = self.instantiate_bounds(span, def_id, &substs); for (i, mut obligation) in traits::predicates_for_generics( traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def_id)), self.param_env, &bounds, ) .into_iter() .enumerate() { // This makes the error point at the bound, but we want to point at the argument if let Some(span) = spans.get(i) { obligation.cause.code = traits::BindingObligation(def_id, *span); } self.register_predicate(obligation); } } fn check_rustc_args_require_const(&self, def_id: DefId, hir_id: hir::HirId, span: Span) { // We're only interested in functions tagged with // #[rustc_args_required_const], so ignore anything that's not. if !self.tcx.has_attr(def_id, sym::rustc_args_required_const) { return; } // If our calling expression is indeed the function itself, we're good! // If not, generate an error that this can only be called directly. if let Node::Expr(expr) = self.tcx.hir().get(self.tcx.hir().get_parent_node(hir_id)) { if let ExprKind::Call(ref callee, ..) = expr.kind { if callee.hir_id == hir_id { return; } } } self.tcx.sess.span_err( span, "this function can only be invoked \ directly, not through a function pointer", ); } /// Resolves `typ` by a single level if `typ` is a type variable. /// If no resolution is possible, then an error is reported. /// Numeric inference variables may be left unresolved. pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { let ty = self.resolve_vars_with_obligations(ty); if !ty.is_ty_var() { ty } else { if !self.is_tainted_by_errors() { self.need_type_info_err((**self).body_id, sp, ty, E0282) .note("type must be known at this point") .emit(); } self.demand_suptype(sp, self.tcx.types.err, ty); self.tcx.types.err } } fn with_breakable_ctxt<F: FnOnce() -> R, R>( &self, id: hir::HirId, ctxt: BreakableCtxt<'tcx>, f: F, ) -> (BreakableCtxt<'tcx>, R) { let index; { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); index = enclosing_breakables.stack.len(); enclosing_breakables.by_id.insert(id, index); enclosing_breakables.stack.push(ctxt); } let result = f(); let ctxt = { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); debug_assert!(enclosing_breakables.stack.len() == index + 1); enclosing_breakables.by_id.remove(&id).expect("missing breakable context"); enclosing_breakables.stack.pop().expect("missing breakable context") }; (ctxt, result) } /// Instantiate a QueryResponse in a probe context, without a /// good ObligationCause. fn probe_instantiate_query_response( &self, span: Span, original_values: &OriginalQueryValues<'tcx>, query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, ) -> InferResult<'tcx, Ty<'tcx>> { self.instantiate_query_response_and_region_obligations( &traits::ObligationCause::misc(span, self.body_id), self.param_env, original_values, query_result, ) } /// Returns `true` if an expression is contained inside the LHS of an assignment expression. fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool { let mut contained_in_place = false; while let hir::Node::Expr(parent_expr) = self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id)) { match &parent_expr.kind { hir::ExprKind::Assign(lhs, ..) | hir::ExprKind::AssignOp(_, lhs, ..) => { if lhs.hir_id == expr_id { contained_in_place = true; break; } } _ => (), } expr_id = parent_expr.hir_id; } contained_in_place } } pub fn check_bounds_are_used<'tcx>(tcx: TyCtxt<'tcx>, generics: &ty::Generics, ty: Ty<'tcx>) { let own_counts = generics.own_counts(); debug!( "check_bounds_are_used(n_tys={}, n_cts={}, ty={:?})", own_counts.types, own_counts.consts, ty ); if own_counts.types == 0 { return; } // Make a vector of booleans initially `false`; set to `true` when used. let mut types_used = vec![false; own_counts.types]; for leaf_ty in ty.walk() { if let ty::Param(ty::ParamTy { index, .. }) = leaf_ty.kind { debug!("found use of ty param num {}", index); types_used[index as usize - own_counts.lifetimes] = true; } else if let ty::Error = leaf_ty.kind { // If there is already another error, do not emit // an error for not using a type parameter. assert!(tcx.sess.has_errors()); return; } } let types = generics.params.iter().filter(|param| match param.kind { ty::GenericParamDefKind::Type { .. } => true, _ => false, }); for (&used, param) in types_used.iter().zip(types) { if !used { let id = tcx.hir().as_local_hir_id(param.def_id).unwrap(); let span = tcx.hir().span(id); struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name) .span_label(span, "unused type parameter") .emit(); } } } fn fatally_break_rust(sess: &Session) { let handler = sess.diagnostic(); handler.span_bug_no_panic( MultiSpan::new(), "It looks like you're trying to break rust; would you like some ICE?", ); handler.note_without_error("the compiler expectedly panicked. this is a feature."); handler.note_without_error( "we would appreciate a joke overview: \ https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675", ); handler.note_without_error(&format!( "rustc {} running on {}", option_env!("CFG_VERSION").unwrap_or("unknown_version"), crate::session::config::host_triple(), )); } fn potentially_plural_count(count: usize, word: &str) -> String { format!("{} {}{}", count, word, pluralize!(count)) }
{ // `.await` is not permitted outside of `async` bodies, so don't bother to suggest if the // body isn't `async`. let item_id = self.tcx().hir().get_parent_node(self.body_id); if let Some(body_id) = self.tcx().hir().maybe_body_owned_by(item_id) { let body = self.tcx().hir().body(body_id); if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind { let sp = expr.span; // Check for `Future` implementations by constructing a predicate to // prove: `<T as Future>::Output == U` let future_trait = self.tcx.lang_items().future_trait().unwrap(); let item_def_id = self.tcx.associated_items(future_trait).next().unwrap().def_id; let predicate = ty::Predicate::Projection(ty::Binder::bind(ty::ProjectionPredicate { // `<T as Future>::Output` projection_ty: ty::ProjectionTy { // `T` substs: self.tcx.mk_substs_trait( found, self.fresh_substs_for_item(sp, item_def_id), ), // `Future::Output` item_def_id, }, ty: expected, })); let obligation = traits::Obligation::new(self.misc(sp), self.param_env, predicate); debug!("suggest_missing_await: trying obligation {:?}", obligation); if self.infcx.predicate_may_hold(&obligation) { debug!("suggest_missing_await: obligation held: {:?}", obligation); if let Ok(code) = self.sess().source_map().span_to_snippet(sp) { err.span_suggestion( sp, "consider using `.await` here", format!("{}.await", code), Applicability::MaybeIncorrect, ); } else { debug!("suggest_missing_await: no snippet for {:?}", sp); } } else { debug!("suggest_missing_await: obligation did not hold: {:?}", obligation) } } } }
vk.go
package vk import ( "encoding/json" "errors" "fmt" "log" "os" "github.com/go-resty/resty" ) // VK struct type VK struct { url string lang string version string token string logFile *os.File longPoll *longPoll Messages *Messages Proxy string } // RequestParams struct type RequestParams map[string]string // CallMethod calls VK API method func (client *VK) CallMethod(method string, params RequestParams) ([]byte, error) { params["access_token"] = client.token params["lang"] = client.lang params["v"] = client.version if client.Proxy != "" { resty.SetProxy(fmt.Sprint("http://", client.Proxy)) } resp, err := resty.R(). SetQueryParams(params). Get(client.url + method) if err != nil { client.Log("[Error] VK::CallMethod:", err.Error(), "WebResponse:", string(resp.Body())) return nil, err } type JSONBody struct { Error map[string]interface{} `json:"error"` } var body JSONBody if err := json.Unmarshal(resp.Body(), &body); err != nil { client.Log("[Error] VK::CallMethod:", err.Error(), "WebResponse:", string(resp.Body())) return nil, err } if body.Error != nil { if errorMsg, exists := body.Error["error_msg"].(string); exists { client.Log("[Error] VK::CallMethod:", errorMsg, "WebResponse:", string(resp.Body())) return nil, errors.New(errorMsg) } client.Log("[Error] VK::CallMethod:", "Unknown error", "WebResponse:", string(resp.Body())) return nil, errors.New("Unknown error") } return resp.Body(), nil } // Init sets the token func (client *VK) Init(token string) error { client.token = token return nil } // RunLongPoll starts longpoll process func (client *VK) RunLongPoll() { if err := client.longPoll.update(); err != nil { client.Log("[Error] VK::RunLongPoll:", err.Error()) return } client.longPoll.chanNewMessage = make(chan *LPMessage) go client.longPoll.processEvents() client.longPoll.process() } // OnNewMessage sets event func (client *VK) OnNewMessage(event EventNewMessage) { client.longPoll.eventNewMessage = event } // SetLogFile sets pointer to logfile func (client *VK) SetLogFile(logFile *os.File) { client.logFile = logFile } // Log writes data in stdout and logfile func (client *VK) Log(a ...interface{}) { log.SetFlags(log.LstdFlags) log.SetOutput(os.Stdout) log.Println(a...) if client.logFile != nil { log.SetOutput(client.logFile) log.Println(a...) } } // New returns a new VK instance func New(lang string) *VK
{ vk := new(VK) vk.url = "https://api.vk.com/method/" vk.lang = lang vk.version = "5.52" vk.longPoll = &longPoll{client: vk} vk.Messages = &Messages{client: vk} return vk }
cell_renderer_spinner.rs
use glib::subclass::prelude::*; use super::cell_renderer::CellRendererImpl; use CellRenderer; use CellRendererSpinner; pub trait CellRendererSpinnerImpl: CellRendererImpl {} unsafe impl<T: CellRendererSpinnerImpl> IsSubclassable<T> for CellRendererSpinner { fn override_vfuncs(class: &mut ::glib::Class<Self>) { <CellRenderer as IsSubclassable<T>>::override_vfuncs(class);
}
}
oidc-client.min.js
var Oidc=function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){n(1),t.exports=n(327)},function(t,e,n){(function(t){"use strict";function e(t,e,n){t[e]||Object[r](t,e,{writable:!0,configurable:!0,value:n})}if(n(2),n(323),n(324),t._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");t._babelPolyfill=!0;var r="defineProperty";e(String.prototype,"padLeft","".padStart),e(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(t){[][t]&&e(Array,t,Function.call.bind([][t]))})}).call(e,function(){return this}())},function(t,e,n){n(3),n(51),n(52),n(53),n(54),n(56),n(59),n(60),n(61),n(62),n(63),n(64),n(65),n(66),n(67),n(69),n(71),n(73),n(75),n(78),n(79),n(80),n(84),n(86),n(88),n(91),n(92),n(93),n(94),n(96),n(97),n(98),n(99),n(100),n(101),n(102),n(104),n(105),n(106),n(108),n(109),n(110),n(112),n(114),n(115),n(116),n(117),n(118),n(119),n(120),n(121),n(122),n(123),n(124),n(125),n(126),n(131),n(132),n(136),n(137),n(138),n(139),n(141),n(142),n(143),n(144),n(145),n(146),n(147),n(148),n(149),n(150),n(151),n(152),n(153),n(154),n(155),n(157),n(158),n(160),n(161),n(167),n(168),n(170),n(171),n(172),n(176),n(177),n(178),n(179),n(180),n(182),n(183),n(184),n(185),n(188),n(190),n(191),n(192),n(194),n(196),n(198),n(199),n(200),n(202),n(203),n(204),n(205),n(215),n(219),n(220),n(222),n(223),n(227),n(228),n(230),n(231),n(232),n(233),n(234),n(235),n(236),n(237),n(238),n(239),n(240),n(241),n(242),n(243),n(244),n(245),n(246),n(247),n(248),n(250),n(251),n(252),n(253),n(254),n(256),n(257),n(258),n(261),n(262),n(263),n(264),n(265),n(266),n(267),n(268),n(270),n(271),n(273),n(274),n(275),n(276),n(279),n(280),n(282),n(283),n(284),n(285),n(287),n(288),n(289),n(290),n(291),n(292),n(293),n(294),n(295),n(296),n(298),n(299),n(300),n(301),n(302),n(303),n(304),n(305),n(306),n(307),n(308),n(310),n(311),n(312),n(313),n(314),n(315),n(316),n(317),n(318),n(319),n(320),n(321),n(322),t.exports=n(9)},function(t,e,n){"use strict";var r=n(4),i=n(5),o=n(6),s=n(8),a=n(18),u=n(22).KEY,c=n(7),f=n(23),h=n(24),l=n(19),p=n(25),d=n(26),g=n(27),v=n(29),y=n(44),m=n(12),S=n(13),b=n(32),F=n(16),w=n(17),_=n(45),x=n(48),E=n(50),A=n(11),P=n(30),C=E.f,k=A.f,T=x.f,R=r.Symbol,I=r.JSON,D=I&&I.stringify,N="prototype",O=p("_hidden"),j=p("toPrimitive"),L={}.propertyIsEnumerable,M=f("symbol-registry"),B=f("symbols"),H=f("op-symbols"),U=Object[N],V="function"==typeof R,K=r.QObject,q=!K||!K[N]||!K[N].findChild,W=o&&c(function(){return 7!=_(k({},"a",{get:function(){return k(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=C(U,e);r&&delete U[e],k(t,e,n),r&&t!==U&&k(U,e,r)}:k,J=function(t){var e=B[t]=_(R[N]);return e._k=t,e},G=V&&"symbol"==typeof R.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof R},z=function(t,e,n){return t===U&&z(H,e,n),m(t),e=F(e,!0),m(n),i(B,e)?(n.enumerable?(i(t,O)&&t[O][e]&&(t[O][e]=!1),n=_(n,{enumerable:w(0,!1)})):(i(t,O)||k(t,O,w(1,{})),t[O][e]=!0),W(t,e,n)):k(t,e,n)},Y=function(t,e){m(t);for(var n,r=v(e=b(e)),i=0,o=r.length;o>i;)z(t,n=r[i++],e[n]);return t},$=function(t,e){return void 0===e?_(t):Y(_(t),e)},X=function(t){var e=L.call(this,t=F(t,!0));return!(this===U&&i(B,t)&&!i(H,t))&&(!(e||!i(this,t)||!i(B,t)||i(this,O)&&this[O][t])||e)},Z=function(t,e){if(t=b(t),e=F(e,!0),t!==U||!i(B,e)||i(H,e)){var n=C(t,e);return!n||!i(B,e)||i(t,O)&&t[O][e]||(n.enumerable=!0),n}},Q=function(t){for(var e,n=T(b(t)),r=[],o=0;n.length>o;)i(B,e=n[o++])||e==O||e==u||r.push(e);return r},tt=function(t){for(var e,n=t===U,r=T(n?H:b(t)),o=[],s=0;r.length>s;)!i(B,e=r[s++])||n&&!i(U,e)||o.push(B[e]);return o};V||(R=function(){if(this instanceof R)throw TypeError("Symbol is not a constructor!");var t=l(arguments.length>0?arguments[0]:void 0),e=function(n){this===U&&e.call(H,n),i(this,O)&&i(this[O],t)&&(this[O][t]=!1),W(this,t,w(1,n))};return o&&q&&W(U,t,{configurable:!0,set:e}),J(t)},a(R[N],"toString",function(){return this._k}),E.f=Z,A.f=z,n(49).f=x.f=Q,n(43).f=X,n(42).f=tt,o&&!n(28)&&a(U,"propertyIsEnumerable",X,!0),d.f=function(t){return J(p(t))}),s(s.G+s.W+s.F*!V,{Symbol:R});for(var et="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),nt=0;et.length>nt;)p(et[nt++]);for(var rt=P(p.store),it=0;rt.length>it;)g(rt[it++]);s(s.S+s.F*!V,"Symbol",{for:function(t){return i(M,t+="")?M[t]:M[t]=R(t)},keyFor:function(t){if(!G(t))throw TypeError(t+" is not a symbol!");for(var e in M)if(M[e]===t)return e},useSetter:function(){q=!0},useSimple:function(){q=!1}}),s(s.S+s.F*!V,"Object",{create:$,defineProperty:z,defineProperties:Y,getOwnPropertyDescriptor:Z,getOwnPropertyNames:Q,getOwnPropertySymbols:tt}),I&&s(s.S+s.F*(!V||c(function(){var t=R();return"[null]"!=D([t])||"{}"!=D({a:t})||"{}"!=D(Object(t))})),"JSON",{stringify:function(t){for(var e,n,r=[t],i=1;arguments.length>i;)r.push(arguments[i++]);if(n=e=r[1],(S(e)||void 0!==t)&&!G(t))return y(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!G(e))return e}),r[1]=e,D.apply(I,r)}}),R[N][j]||n(10)(R[N],j,R[N].valueOf),h(R,"Symbol"),h(Math,"Math",!0),h(r.JSON,"JSON",!0)},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){t.exports=!n(7)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,n){var r=n(4),i=n(9),o=n(10),s=n(18),a=n(20),u="prototype",c=function(t,e,n){var f,h,l,p,d=t&c.F,g=t&c.G,v=t&c.S,y=t&c.P,m=t&c.B,S=g?r:v?r[e]||(r[e]={}):(r[e]||{})[u],b=g?i:i[e]||(i[e]={}),F=b[u]||(b[u]={});g&&(n=e);for(f in n)h=!d&&S&&void 0!==S[f],l=(h?S:n)[f],p=m&&h?a(l,r):y&&"function"==typeof l?a(Function.call,l):l,S&&s(S,f,l,t&c.U),b[f]!=l&&o(b,f,p),y&&F[f]!=l&&(F[f]=l)};r.core=i,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,t.exports=c},function(t,e){var n=t.exports={version:"2.5.5"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(11),i=n(17);t.exports=n(6)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var r=n(12),i=n(14),o=n(16),s=Object.defineProperty;e.f=n(6)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return s(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(13);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){t.exports=!n(6)&&!n(7)(function(){return 7!=Object.defineProperty(n(15)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(13),i=n(4).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e,n){var r=n(13);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(4),i=n(10),o=n(5),s=n(19)("src"),a="toString",u=Function[a],c=(""+u).split(a);n(9).inspectSource=function(t){return u.call(t)},(t.exports=function(t,e,n,a){var u="function"==typeof n;u&&(o(n,"name")||i(n,"name",e)),t[e]!==n&&(u&&(o(n,s)||i(n,s,t[e]?""+t[e]:c.join(String(e)))),t===r?t[e]=n:a?t[e]?t[e]=n:i(t,e,n):(delete t[e],i(t,e,n)))})(Function.prototype,a,function(){return"function"==typeof this&&this[s]||u.call(this)})},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){var r=n(21);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var r=n(19)("meta"),i=n(13),o=n(5),s=n(11).f,a=0,u=Object.isExtensible||function(){return!0},c=!n(7)(function(){return u(Object.preventExtensions({}))}),f=function(t){s(t,r,{value:{i:"O"+ ++a,w:{}}})},h=function(t,e){if(!i(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,r)){if(!u(t))return"F";if(!e)return"E";f(t)}return t[r].i},l=function(t,e){if(!o(t,r)){if(!u(t))return!0;if(!e)return!1;f(t)}return t[r].w},p=function(t){return c&&d.NEED&&u(t)&&!o(t,r)&&f(t),t},d=t.exports={KEY:r,NEED:!1,fastKey:h,getWeak:l,onFreeze:p}},function(t,e,n){var r=n(4),i="__core-js_shared__",o=r[i]||(r[i]={});t.exports=function(t){return o[t]||(o[t]={})}},function(t,e,n){var r=n(11).f,i=n(5),o=n(25)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(23)("wks"),i=n(19),o=n(4).Symbol,s="function"==typeof o,a=t.exports=function(t){return r[t]||(r[t]=s&&o[t]||(s?o:i)("Symbol."+t))};a.store=r},function(t,e,n){e.f=n(25)},function(t,e,n){var r=n(4),i=n(9),o=n(28),s=n(26),a=n(11).f;t.exports=function(t){var e=i.Symbol||(i.Symbol=o?{}:r.Symbol||{});"_"==t.charAt(0)||t in e||a(e,t,{value:s.f(t)})}},function(t,e){t.exports=!1},function(t,e,n){var r=n(30),i=n(42),o=n(43);t.exports=function(t){var e=r(t),n=i.f;if(n)for(var s,a=n(t),u=o.f,c=0;a.length>c;)u.call(t,s=a[c++])&&e.push(s);return e}},function(t,e,n){var r=n(31),i=n(41);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e,n){var r=n(5),i=n(32),o=n(36)(!1),s=n(40)("IE_PROTO");t.exports=function(t,e){var n,a=i(t),u=0,c=[];for(n in a)n!=s&&r(a,n)&&c.push(n);for(;e.length>u;)r(a,n=e[u++])&&(~o(c,n)||c.push(n));return c}},function(t,e,n){var r=n(33),i=n(35);t.exports=function(t){return r(i(t))}},function(t,e,n){var r=n(34);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(32),i=n(37),o=n(39);t.exports=function(t){return function(e,n,s){var a,u=r(e),c=i(u.length),f=o(s,c);if(t&&n!=n){for(;c>f;)if(a=u[f++],a!=a)return!0}else for(;c>f;f++)if((t||f in u)&&u[f]===n)return t||f||0;return!t&&-1}}},function(t,e,n){var r=n(38),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(38),i=Math.max,o=Math.min;t.exports=function(t,e){return t=r(t),t<0?i(t+e,0):o(t,e)}},function(t,e,n){var r=n(23)("keys"),i=n(19);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var r=n(34);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,e,n){var r=n(12),i=n(46),o=n(41),s=n(40)("IE_PROTO"),a=function(){},u="prototype",c=function(){var t,e=n(15)("iframe"),r=o.length,i="<",s=">";for(e.style.display="none",n(47).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(i+"script"+s+"document.F=Object"+i+"/script"+s),t.close(),c=t.F;r--;)delete c[u][o[r]];return c()};t.exports=Object.create||function(t,e){var n;return null!==t?(a[u]=r(t),n=new a,a[u]=null,n[s]=t):n=c(),void 0===e?n:i(n,e)}},function(t,e,n){var r=n(11),i=n(12),o=n(30);t.exports=n(6)?Object.defineProperties:function(t,e){i(t);for(var n,s=o(e),a=s.length,u=0;a>u;)r.f(t,n=s[u++],e[n]);return t}},function(t,e,n){var r=n(4).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(32),i=n(49).f,o={}.toString,s="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],a=function(t){try{return i(t)}catch(t){return s.slice()}};t.exports.f=function(t){return s&&"[object Window]"==o.call(t)?a(t):i(r(t))}},function(t,e,n){var r=n(31),i=n(41).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},function(t,e,n){var r=n(43),i=n(17),o=n(32),s=n(16),a=n(5),u=n(14),c=Object.getOwnPropertyDescriptor;e.f=n(6)?c:function(t,e){if(t=o(t),e=s(e,!0),u)try{return c(t,e)}catch(t){}if(a(t,e))return i(!r.f.call(t,e),t[e])}},function(t,e,n){var r=n(8);r(r.S,"Object",{create:n(45)})},function(t,e,n){var r=n(8);r(r.S+r.F*!n(6),"Object",{defineProperty:n(11).f})},function(t,e,n){var r=n(8);r(r.S+r.F*!n(6),"Object",{defineProperties:n(46)})},function(t,e,n){var r=n(32),i=n(50).f;n(55)("getOwnPropertyDescriptor",function(){return function(t,e){return i(r(t),e)}})},function(t,e,n){var r=n(8),i=n(9),o=n(7);t.exports=function(t,e){var n=(i.Object||{})[t]||Object[t],s={};s[t]=e(n),r(r.S+r.F*o(function(){n(1)}),"Object",s)}},function(t,e,n){var r=n(57),i=n(58);n(55)("getPrototypeOf",function(){return function(t){return i(r(t))}})},function(t,e,n){var r=n(35);t.exports=function(t){return Object(r(t))}},function(t,e,n){var r=n(5),i=n(57),o=n(40)("IE_PROTO"),s=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?s:null}},function(t,e,n){var r=n(57),i=n(30);n(55)("keys",function(){return function(t){return i(r(t))}})},function(t,e,n){n(55)("getOwnPropertyNames",function(){return n(48).f})},function(t,e,n){var r=n(13),i=n(22).onFreeze;n(55)("freeze",function(t){return function(e){return t&&r(e)?t(i(e)):e}})},function(t,e,n){var r=n(13),i=n(22).onFreeze;n(55)("seal",function(t){return function(e){return t&&r(e)?t(i(e)):e}})},function(t,e,n){var r=n(13),i=n(22).onFreeze;n(55)("preventExtensions",function(t){return function(e){return t&&r(e)?t(i(e)):e}})},function(t,e,n){var r=n(13);n(55)("isFrozen",function(t){return function(e){return!r(e)||!!t&&t(e)}})},function(t,e,n){var r=n(13);n(55)("isSealed",function(t){return function(e){return!r(e)||!!t&&t(e)}})},function(t,e,n){var r=n(13);n(55)("isExtensible",function(t){return function(e){return!!r(e)&&(!t||t(e))}})},function(t,e,n){var r=n(8);r(r.S+r.F,"Object",{assign:n(68)})},function(t,e,n){"use strict";var r=n(30),i=n(42),o=n(43),s=n(57),a=n(33),u=Object.assign;t.exports=!u||n(7)(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=u({},t)[n]||Object.keys(u({},e)).join("")!=r})?function(t,e){for(var n=s(t),u=arguments.length,c=1,f=i.f,h=o.f;u>c;)for(var l,p=a(arguments[c++]),d=f?r(p).concat(f(p)):r(p),g=d.length,v=0;g>v;)h.call(p,l=d[v++])&&(n[l]=p[l]);return n}:u},function(t,e,n){var r=n(8);r(r.S,"Object",{is:n(70)})},function(t,e){t.exports=Object.is||function(t,e){return t===e?0!==t||1/t===1/e:t!=t&&e!=e}},function(t,e,n){var r=n(8);r(r.S,"Object",{setPrototypeOf:n(72).set})},function(t,e,n){var r=n(13),i=n(12),o=function(t,e){if(i(t),!r(e)&&null!==e)throw TypeError(e+": can't set as prototype!")};t.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(t,e,r){try{r=n(20)(Function.call,n(50).f(Object.prototype,"__proto__").set,2),r(t,[]),e=!(t instanceof Array)}catch(t){e=!0}return function(t,n){return o(t,n),e?t.__proto__=n:r(t,n),t}}({},!1):void 0),check:o}},function(t,e,n){"use strict";var r=n(74),i={};i[n(25)("toStringTag")]="z",i+""!="[object z]"&&n(18)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(t,e,n){var r=n(34),i=n(25)("toStringTag"),o="Arguments"==r(function(){return arguments}()),s=function(t,e){try{return t[e]}catch(t){}};t.exports=function(t){var e,n,a;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=s(e=Object(t),i))?n:o?r(e):"Object"==(a=r(e))&&"function"==typeof e.callee?"Arguments":a}},function(t,e,n){var r=n(8);r(r.P,"Function",{bind:n(76)})},function(t,e,n){"use strict";var r=n(21),i=n(13),o=n(77),s=[].slice,a={},u=function(t,e,n){if(!(e in a)){for(var r=[],i=0;i<e;i++)r[i]="a["+i+"]";a[e]=Function("F,a","return new F("+r.join(",")+")")}return a[e](t,n)};t.exports=Function.bind||function(t){var e=r(this),n=s.call(arguments,1),a=function(){var r=n.concat(s.call(arguments));return this instanceof a?u(e,r.length,r):o(e,r,t)};return i(e.prototype)&&(a.prototype=e.prototype),a}},function(t,e){t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){var r=n(11).f,i=Function.prototype,o=/^\s*function ([^ (]*)/,s="name";s in i||n(6)&&r(i,s,{configurable:!0,get:function(){try{return(""+this).match(o)[1]}catch(t){return""}}})},function(t,e,n){"use strict";var r=n(13),i=n(58),o=n(25)("hasInstance"),s=Function.prototype;o in s||n(11).f(s,o,{value:function(t){if("function"!=typeof this||!r(t))return!1;if(!r(this.prototype))return t instanceof this;for(;t=i(t);)if(this.prototype===t)return!0;return!1}})},function(t,e,n){var r=n(8),i=n(81);r(r.G+r.F*(parseInt!=i),{parseInt:i})},function(t,e,n){var r=n(4).parseInt,i=n(82).trim,o=n(83),s=/^[-+]?0[xX]/;t.exports=8!==r(o+"08")||22!==r(o+"0x16")?function(t,e){var n=i(String(t),3);return r(n,e>>>0||(s.test(n)?16:10))}:r},function(t,e,n){var r=n(8),i=n(35),o=n(7),s=n(83),a="["+s+"]",u="​…",c=RegExp("^"+a+a+"*"),f=RegExp(a+a+"*$"),h=function(t,e,n){var i={},a=o(function(){return!!s[t]()||u[t]()!=u}),c=i[t]=a?e(l):s[t];n&&(i[n]=c),r(r.P+r.F*a,"String",i)},l=h.trim=function(t,e){return t=String(i(t)),1&e&&(t=t.replace(c,"")),2&e&&(t=t.replace(f,"")),t};t.exports=h},function(t,e){t.exports="\t\n\v\f\r   ᠎              \u2028\u2029\ufeff"},function(t,e,n){var r=n(8),i=n(85);r(r.G+r.F*(parseFloat!=i),{parseFloat:i})},function(t,e,n){var r=n(4).parseFloat,i=n(82).trim;t.exports=1/r(n(83)+"-0")!==-(1/0)?function(t){var e=i(String(t),3),n=r(e);return 0===n&&"-"==e.charAt(0)?-0:n}:r},function(t,e,n){"use strict";var r=n(4),i=n(5),o=n(34),s=n(87),a=n(16),u=n(7),c=n(49).f,f=n(50).f,h=n(11).f,l=n(82).trim,p="Number",d=r[p],g=d,v=d.prototype,y=o(n(45)(v))==p,m="trim"in String.prototype,S=function(t){var e=a(t,!1);if("string"==typeof e&&e.length>2){e=m?e.trim():l(e,3);var n,r,i,o=e.charCodeAt(0);if(43===o||45===o){if(n=e.charCodeAt(2),88===n||120===n)return NaN}else if(48===o){switch(e.charCodeAt(1)){case 66:case 98:r=2,i=49;break;case 79:case 111:r=8,i=55;break;default:return+e}for(var s,u=e.slice(2),c=0,f=u.length;c<f;c++)if(s=u.charCodeAt(c),s<48||s>i)return NaN;return parseInt(u,r)}}return+e};if(!d(" 0o1")||!d("0b1")||d("+0x1")){d=function(t){var e=arguments.length<1?0:t,n=this;return n instanceof d&&(y?u(function(){v.valueOf.call(n)}):o(n)!=p)?s(new g(S(e)),n,d):S(e)};for(var b,F=n(6)?c(g):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),w=0;F.length>w;w++)i(g,b=F[w])&&!i(d,b)&&h(d,b,f(g,b));d.prototype=v,v.constructor=d,n(18)(r,p,d)}},function(t,e,n){var r=n(13),i=n(72).set;t.exports=function(t,e,n){var o,s=e.constructor;return s!==n&&"function"==typeof s&&(o=s.prototype)!==n.prototype&&r(o)&&i&&i(t,o),t}},function(t,e,n){"use strict";var r=n(8),i=n(38),o=n(89),s=n(90),a=1..toFixed,u=Math.floor,c=[0,0,0,0,0,0],f="Number.toFixed: incorrect invocation!",h="0",l=function(t,e){for(var n=-1,r=e;++n<6;)r+=t*c[n],c[n]=r%1e7,r=u(r/1e7)},p=function(t){for(var e=6,n=0;--e>=0;)n+=c[e],c[e]=u(n/t),n=n%t*1e7},d=function(){for(var t=6,e="";--t>=0;)if(""!==e||0===t||0!==c[t]){var n=String(c[t]);e=""===e?n:e+s.call(h,7-n.length)+n}return e},g=function(t,e,n){return 0===e?n:e%2===1?g(t,e-1,n*t):g(t*t,e/2,n)},v=function(t){for(var e=0,n=t;n>=4096;)e+=12,n/=4096;for(;n>=2;)e+=1,n/=2;return e};r(r.P+r.F*(!!a&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!n(7)(function(){a.call({})})),"Number",{toFixed:function(t){var e,n,r,a,u=o(this,f),c=i(t),y="",m=h;if(c<0||c>20)throw RangeError(f);if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return String(u);if(u<0&&(y="-",u=-u),u>1e-21)if(e=v(u*g(2,69,1))-69,n=e<0?u*g(2,-e,1):u/g(2,e,1),n*=4503599627370496,e=52-e,e>0){for(l(0,n),r=c;r>=7;)l(1e7,0),r-=7;for(l(g(10,r,1),0),r=e-1;r>=23;)p(1<<23),r-=23;p(1<<r),l(1,1),p(2),m=d()}else l(0,n),l(1<<-e,0),m=d()+s.call(h,c);return c>0?(a=m.length,m=y+(a<=c?"0."+s.call(h,c-a)+m:m.slice(0,a-c)+"."+m.slice(a-c))):m=y+m,m}})},function(t,e,n){var r=n(34);t.exports=function(t,e){if("number"!=typeof t&&"Number"!=r(t))throw TypeError(e);return+t}},function(t,e,n){"use strict";var r=n(38),i=n(35);t.exports=function(t){var e=String(i(this)),n="",o=r(t);if(o<0||o==1/0)throw RangeError("Count can't be negative");for(;o>0;(o>>>=1)&&(e+=e))1&o&&(n+=e);return n}},function(t,e,n){"use strict";var r=n(8),i=n(7),o=n(89),s=1..toPrecision;r(r.P+r.F*(i(function(){return"1"!==s.call(1,void 0)})||!i(function(){s.call({})})),"Number",{toPrecision:function(t){var e=o(this,"Number#toPrecision: incorrect invocation!");return void 0===t?s.call(e):s.call(e,t)}})},function(t,e,n){var r=n(8);r(r.S,"Number",{EPSILON:Math.pow(2,-52)})},function(t,e,n){var r=n(8),i=n(4).isFinite;r(r.S,"Number",{isFinite:function(t){return"number"==typeof t&&i(t)}})},function(t,e,n){var r=n(8);r(r.S,"Number",{isInteger:n(95)})},function(t,e,n){var r=n(13),i=Math.floor;t.exports=function(t){return!r(t)&&isFinite(t)&&i(t)===t}},function(t,e,n){var r=n(8);r(r.S,"Number",{isNaN:function(t){return t!=t}})},function(t,e,n){var r=n(8),i=n(95),o=Math.abs;r(r.S,"Number",{isSafeInteger:function(t){return i(t)&&o(t)<=9007199254740991}})},function(t,e,n){var r=n(8);r(r.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(t,e,n){var r=n(8);r(r.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991})},function(t,e,n){var r=n(8),i=n(85);r(r.S+r.F*(Number.parseFloat!=i),"Number",{parseFloat:i})},function(t,e,n){var r=n(8),i=n(81);r(r.S+r.F*(Number.parseInt!=i),"Number",{parseInt:i})},function(t,e,n){var r=n(8),i=n(103),o=Math.sqrt,s=Math.acosh;r(r.S+r.F*!(s&&710==Math.floor(s(Number.MAX_VALUE))&&s(1/0)==1/0),"Math",{acosh:function(t){return(t=+t)<1?NaN:t>94906265.62425156?Math.log(t)+Math.LN2:i(t-1+o(t-1)*o(t+1))}})},function(t,e){t.exports=Math.log1p||function(t){return(t=+t)>-1e-8&&t<1e-8?t-t*t/2:Math.log(1+t)}},function(t,e,n){function r(t){return isFinite(t=+t)&&0!=t?t<0?-r(-t):Math.log(t+Math.sqrt(t*t+1)):t}var i=n(8),o=Math.asinh;i(i.S+i.F*!(o&&1/o(0)>0),"Math",{asinh:r})},function(t,e,n){var r=n(8),i=Math.atanh;r(r.S+r.F*!(i&&1/i(-0)<0),"Math",{atanh:function(t){return 0==(t=+t)?t:Math.log((1+t)/(1-t))/2}})},function(t,e,n){var r=n(8),i=n(107);r(r.S,"Math",{cbrt:function(t){return i(t=+t)*Math.pow(Math.abs(t),1/3)}})},function(t,e){t.exports=Math.sign||function(t){return 0==(t=+t)||t!=t?t:t<0?-1:1}},function(t,e,n){var r=n(8);r(r.S,"Math",{clz32:function(t){return(t>>>=0)?31-Math.floor(Math.log(t+.5)*Math.LOG2E):32}})},function(t,e,n){var r=n(8),i=Math.exp;r(r.S,"Math",{cosh:function(t){return(i(t=+t)+i(-t))/2}})},function(t,e,n){var r=n(8),i=n(111);r(r.S+r.F*(i!=Math.expm1),"Math",{expm1:i})},function(t,e){var n=Math.expm1;t.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||n(-2e-17)!=-2e-17?function(t){return 0==(t=+t)?t:t>-1e-6&&t<1e-6?t+t*t/2:Math.exp(t)-1}:n},function(t,e,n){var r=n(8);r(r.S,"Math",{fround:n(113)})},function(t,e,n){var r=n(107),i=Math.pow,o=i(2,-52),s=i(2,-23),a=i(2,127)*(2-s),u=i(2,-126),c=function(t){return t+1/o-1/o};t.exports=Math.fround||function(t){var e,n,i=Math.abs(t),f=r(t);return i<u?f*c(i/u/s)*u*s:(e=(1+s/o)*i,n=e-(e-i),n>a||n!=n?f*(1/0):f*n)}},function(t,e,n){var r=n(8),i=Math.abs;r(r.S,"Math",{hypot:function(t,e){for(var n,r,o=0,s=0,a=arguments.length,u=0;s<a;)n=i(arguments[s++]),u<n?(r=u/n,o=o*r*r+1,u=n):n>0?(r=n/u,o+=r*r):o+=n;return u===1/0?1/0:u*Math.sqrt(o)}})},function(t,e,n){var r=n(8),i=Math.imul;r(r.S+r.F*n(7)(function(){return i(4294967295,5)!=-5||2!=i.length}),"Math",{imul:function(t,e){var n=65535,r=+t,i=+e,o=n&r,s=n&i;return 0|o*s+((n&r>>>16)*s+o*(n&i>>>16)<<16>>>0)}})},function(t,e,n){var r=n(8);r(r.S,"Math",{log10:function(t){return Math.log(t)*Math.LOG10E}})},function(t,e,n){var r=n(8);r(r.S,"Math",{log1p:n(103)})},function(t,e,n){var r=n(8);r(r.S,"Math",{log2:function(t){return Math.log(t)/Math.LN2}})},function(t,e,n){var r=n(8);r(r.S,"Math",{sign:n(107)})},function(t,e,n){var r=n(8),i=n(111),o=Math.exp;r(r.S+r.F*n(7)(function(){return!Math.sinh(-2e-17)!=-2e-17}),"Math",{sinh:function(t){return Math.abs(t=+t)<1?(i(t)-i(-t))/2:(o(t-1)-o(-t-1))*(Math.E/2)}})},function(t,e,n){var r=n(8),i=n(111),o=Math.exp;r(r.S,"Math",{tanh:function(t){var e=i(t=+t),n=i(-t);return e==1/0?1:n==1/0?-1:(e-n)/(o(t)+o(-t))}})},function(t,e,n){var r=n(8);r(r.S,"Math",{trunc:function(t){return(t>0?Math.floor:Math.ceil)(t)}})},function(t,e,n){var r=n(8),i=n(39),o=String.fromCharCode,s=String.fromCodePoint;r(r.S+r.F*(!!s&&1!=s.length),"String",{fromCodePoint:function(t){for(var e,n=[],r=arguments.length,s=0;r>s;){if(e=+arguments[s++],i(e,1114111)!==e)throw RangeError(e+" is not a valid code point");n.push(e<65536?o(e):o(((e-=65536)>>10)+55296,e%1024+56320))}return n.join("")}})},function(t,e,n){var r=n(8),i=n(32),o=n(37);r(r.S,"String",{raw:function(t){for(var e=i(t.raw),n=o(e.length),r=arguments.length,s=[],a=0;n>a;)s.push(String(e[a++])),a<r&&s.push(String(arguments[a]));return s.join("")}})},function(t,e,n){"use strict";n(82)("trim",function(t){return function(){return t(this,3)}})},function(t,e,n){"use strict";var r=n(127)(!0);n(128)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){var r=n(38),i=n(35);t.exports=function(t){return function(e,n){var o,s,a=String(i(e)),u=r(n),c=a.length;return u<0||u>=c?t?"":void 0:(o=a.charCodeAt(u),o<55296||o>56319||u+1===c||(s=a.charCodeAt(u+1))<56320||s>57343?t?a.charAt(u):o:t?a.slice(u,u+2):(o-55296<<10)+(s-56320)+65536)}}},function(t,e,n){"use strict";var r=n(28),i=n(8),o=n(18),s=n(10),a=n(129),u=n(130),c=n(24),f=n(58),h=n(25)("iterator"),l=!([].keys&&"next"in[].keys()),p="@@iterator",d="keys",g="values",v=function(){return this};t.exports=function(t,e,n,y,m,S,b){u(n,e,y);var F,w,_,x=function(t){if(!l&&t in C)return C[t];switch(t){case d:return function(){return new n(this,t)};case g:return function(){return new n(this,t)}}return function(){return new n(this,t)}},E=e+" Iterator",A=m==g,P=!1,C=t.prototype,k=C[h]||C[p]||m&&C[m],T=k||x(m),R=m?A?x("entries"):T:void 0,I="Array"==e?C.entries||k:k;if(I&&(_=f(I.call(new t)),_!==Object.prototype&&_.next&&(c(_,E,!0),r||"function"==typeof _[h]||s(_,h,v))),A&&k&&k.name!==g&&(P=!0,T=function(){return k.call(this)}),r&&!b||!l&&!P&&C[h]||s(C,h,T),a[e]=T,a[E]=v,m)if(F={values:A?T:x(g),keys:S?T:x(d),entries:R},b)for(w in F)w in C||o(C,w,F[w]);else i(i.P+i.F*(l||P),e,F);return F}},function(t,e){t.exports={}},function(t,e,n){"use strict";var r=n(45),i=n(17),o=n(24),s={};n(10)(s,n(25)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(s,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e,n){"use strict";var r=n(8),i=n(127)(!1);r(r.P,"String",{codePointAt:function(t){return i(this,t)}})},function(t,e,n){"use strict";var r=n(8),i=n(37),o=n(133),s="endsWith",a=""[s];r(r.P+r.F*n(135)(s),"String",{endsWith:function(t){var e=o(this,t,s),n=arguments.length>1?arguments[1]:void 0,r=i(e.length),u=void 0===n?r:Math.min(i(n),r),c=String(t);return a?a.call(e,c,u):e.slice(u-c.length,u)===c}})},function(t,e,n){var r=n(134),i=n(35);t.exports=function(t,e,n){if(r(e))throw TypeError("String#"+n+" doesn't accept regex!");return String(i(t))}},function(t,e,n){var r=n(13),i=n(34),o=n(25)("match");t.exports=function(t){var e;return r(t)&&(void 0!==(e=t[o])?!!e:"RegExp"==i(t))}},function(t,e,n){var r=n(25)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[r]=!1,!"/./"[t](e)}catch(t){}}return!0}},function(t,e,n){"use strict";var r=n(8),i=n(133),o="includes";r(r.P+r.F*n(135)(o),"String",{includes:function(t){return!!~i(this,t,o).indexOf(t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,n){var r=n(8);r(r.P,"String",{repeat:n(90)})},function(t,e,n){"use strict";var r=n(8),i=n(37),o=n(133),s="startsWith",a=""[s];r(r.P+r.F*n(135)(s),"String",{startsWith:function(t){var e=o(this,t,s),n=i(Math.min(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return a?a.call(e,r,n):e.slice(n,n+r.length)===r}})},function(t,e,n){"use strict";n(140)("anchor",function(t){return function(e){return t(this,"a","name",e)}})},function(t,e,n){var r=n(8),i=n(7),o=n(35),s=/"/g,a=function(t,e,n,r){var i=String(o(t)),a="<"+e;return""!==n&&(a+=" "+n+'="'+String(r).replace(s,"&quot;")+'"'),a+">"+i+"</"+e+">"};t.exports=function(t,e){var n={};n[t]=e(a),r(r.P+r.F*i(function(){var e=""[t]('"');return e!==e.toLowerCase()||e.split('"').length>3}),"String",n)}},function(t,e,n){"use strict";n(140)("big",function(t){return function(){return t(this,"big","","")}})},function(t,e,n){"use strict";n(140)("blink",function(t){return function(){return t(this,"blink","","")}})},function(t,e,n){"use strict";n(140)("bold",function(t){return function(){return t(this,"b","","")}})},function(t,e,n){"use strict";n(140)("fixed",function(t){return function(){return t(this,"tt","","")}})},function(t,e,n){"use strict";n(140)("fontcolor",function(t){return function(e){return t(this,"font","color",e)}})},function(t,e,n){"use strict";n(140)("fontsize",function(t){return function(e){return t(this,"font","size",e)}})},function(t,e,n){"use strict";n(140)("italics",function(t){return function(){return t(this,"i","","")}})},function(t,e,n){"use strict";n(140)("link",function(t){return function(e){return t(this,"a","href",e)}})},function(t,e,n){"use strict";n(140)("small",function(t){return function(){return t(this,"small","","")}})},function(t,e,n){"use strict";n(140)("strike",function(t){return function(){return t(this,"strike","","")}})},function(t,e,n){"use strict";n(140)("sub",function(t){return function(){return t(this,"sub","","")}})},function(t,e,n){"use strict";n(140)("sup",function(t){return function(){return t(this,"sup","","")}})},function(t,e,n){var r=n(8);r(r.S,"Date",{now:function(){return(new Date).getTime()}})},function(t,e,n){"use strict";var r=n(8),i=n(57),o=n(16);r(r.P+r.F*n(7)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}),"Date",{toJSON:function(t){var e=i(this),n=o(e);return"number"!=typeof n||isFinite(n)?e.toISOString():null}})},function(t,e,n){var r=n(8),i=n(156);r(r.P+r.F*(Date.prototype.toISOString!==i),"Date",{toISOString:i})},function(t,e,n){"use strict";var r=n(7),i=Date.prototype.getTime,o=Date.prototype.toISOString,s=function(t){return t>9?t:"0"+t};t.exports=r(function(){return"0385-07-25T07:06:39.999Z"!=o.call(new Date(-5e13-1))})||!r(function(){o.call(new Date(NaN))})?function(){if(!isFinite(i.call(this)))throw RangeError("Invalid time value");var t=this,e=t.getUTCFullYear(),n=t.getUTCMilliseconds(),r=e<0?"-":e>9999?"+":""; return r+("00000"+Math.abs(e)).slice(r?-6:-4)+"-"+s(t.getUTCMonth()+1)+"-"+s(t.getUTCDate())+"T"+s(t.getUTCHours())+":"+s(t.getUTCMinutes())+":"+s(t.getUTCSeconds())+"."+(n>99?n:"0"+s(n))+"Z"}:o},function(t,e,n){var r=Date.prototype,i="Invalid Date",o="toString",s=r[o],a=r.getTime;new Date(NaN)+""!=i&&n(18)(r,o,function(){var t=a.call(this);return t===t?s.call(this):i})},function(t,e,n){var r=n(25)("toPrimitive"),i=Date.prototype;r in i||n(10)(i,r,n(159))},function(t,e,n){"use strict";var r=n(12),i=n(16),o="number";t.exports=function(t){if("string"!==t&&t!==o&&"default"!==t)throw TypeError("Incorrect hint");return i(r(this),t!=o)}},function(t,e,n){var r=n(8);r(r.S,"Array",{isArray:n(44)})},function(t,e,n){"use strict";var r=n(20),i=n(8),o=n(57),s=n(162),a=n(163),u=n(37),c=n(164),f=n(165);i(i.S+i.F*!n(166)(function(t){Array.from(t)}),"Array",{from:function(t){var e,n,i,h,l=o(t),p="function"==typeof this?this:Array,d=arguments.length,g=d>1?arguments[1]:void 0,v=void 0!==g,y=0,m=f(l);if(v&&(g=r(g,d>2?arguments[2]:void 0,2)),void 0==m||p==Array&&a(m))for(e=u(l.length),n=new p(e);e>y;y++)c(n,y,v?g(l[y],y):l[y]);else for(h=m.call(l),n=new p;!(i=h.next()).done;y++)c(n,y,v?s(h,g,[i.value,y],!0):i.value);return n.length=y,n}})},function(t,e,n){var r=n(12);t.exports=function(t,e,n,i){try{return i?e(r(n)[0],n[1]):e(n)}catch(e){var o=t.return;throw void 0!==o&&r(o.call(t)),e}}},function(t,e,n){var r=n(129),i=n(25)("iterator"),o=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||o[i]===t)}},function(t,e,n){"use strict";var r=n(11),i=n(17);t.exports=function(t,e,n){e in t?r.f(t,e,i(0,n)):t[e]=n}},function(t,e,n){var r=n(74),i=n(25)("iterator"),o=n(129);t.exports=n(9).getIteratorMethod=function(t){if(void 0!=t)return t[i]||t["@@iterator"]||o[r(t)]}},function(t,e,n){var r=n(25)("iterator"),i=!1;try{var o=[7][r]();o.return=function(){i=!0},Array.from(o,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!i)return!1;var n=!1;try{var o=[7],s=o[r]();s.next=function(){return{done:n=!0}},o[r]=function(){return s},t(o)}catch(t){}return n}},function(t,e,n){"use strict";var r=n(8),i=n(164);r(r.S+r.F*n(7)(function(){function t(){}return!(Array.of.call(t)instanceof t)}),"Array",{of:function(){for(var t=0,e=arguments.length,n=new("function"==typeof this?this:Array)(e);e>t;)i(n,t,arguments[t++]);return n.length=e,n}})},function(t,e,n){"use strict";var r=n(8),i=n(32),o=[].join;r(r.P+r.F*(n(33)!=Object||!n(169)(o)),"Array",{join:function(t){return o.call(i(this),void 0===t?",":t)}})},function(t,e,n){"use strict";var r=n(7);t.exports=function(t,e){return!!t&&r(function(){e?t.call(null,function(){},1):t.call(null)})}},function(t,e,n){"use strict";var r=n(8),i=n(47),o=n(34),s=n(39),a=n(37),u=[].slice;r(r.P+r.F*n(7)(function(){i&&u.call(i)}),"Array",{slice:function(t,e){var n=a(this.length),r=o(this);if(e=void 0===e?n:e,"Array"==r)return u.call(this,t,e);for(var i=s(t,n),c=s(e,n),f=a(c-i),h=new Array(f),l=0;l<f;l++)h[l]="String"==r?this.charAt(i+l):this[i+l];return h}})},function(t,e,n){"use strict";var r=n(8),i=n(21),o=n(57),s=n(7),a=[].sort,u=[1,2,3];r(r.P+r.F*(s(function(){u.sort(void 0)})||!s(function(){u.sort(null)})||!n(169)(a)),"Array",{sort:function(t){return void 0===t?a.call(o(this)):a.call(o(this),i(t))}})},function(t,e,n){"use strict";var r=n(8),i=n(173)(0),o=n(169)([].forEach,!0);r(r.P+r.F*!o,"Array",{forEach:function(t){return i(this,t,arguments[1])}})},function(t,e,n){var r=n(20),i=n(33),o=n(57),s=n(37),a=n(174);t.exports=function(t,e){var n=1==t,u=2==t,c=3==t,f=4==t,h=6==t,l=5==t||h,p=e||a;return function(e,a,d){for(var g,v,y=o(e),m=i(y),S=r(a,d,3),b=s(m.length),F=0,w=n?p(e,b):u?p(e,0):void 0;b>F;F++)if((l||F in m)&&(g=m[F],v=S(g,F,y),t))if(n)w[F]=v;else if(v)switch(t){case 3:return!0;case 5:return g;case 6:return F;case 2:w.push(g)}else if(f)return!1;return h?-1:c||f?f:w}}},function(t,e,n){var r=n(175);t.exports=function(t,e){return new(r(t))(e)}},function(t,e,n){var r=n(13),i=n(44),o=n(25)("species");t.exports=function(t){var e;return i(t)&&(e=t.constructor,"function"!=typeof e||e!==Array&&!i(e.prototype)||(e=void 0),r(e)&&(e=e[o],null===e&&(e=void 0))),void 0===e?Array:e}},function(t,e,n){"use strict";var r=n(8),i=n(173)(1);r(r.P+r.F*!n(169)([].map,!0),"Array",{map:function(t){return i(this,t,arguments[1])}})},function(t,e,n){"use strict";var r=n(8),i=n(173)(2);r(r.P+r.F*!n(169)([].filter,!0),"Array",{filter:function(t){return i(this,t,arguments[1])}})},function(t,e,n){"use strict";var r=n(8),i=n(173)(3);r(r.P+r.F*!n(169)([].some,!0),"Array",{some:function(t){return i(this,t,arguments[1])}})},function(t,e,n){"use strict";var r=n(8),i=n(173)(4);r(r.P+r.F*!n(169)([].every,!0),"Array",{every:function(t){return i(this,t,arguments[1])}})},function(t,e,n){"use strict";var r=n(8),i=n(181);r(r.P+r.F*!n(169)([].reduce,!0),"Array",{reduce:function(t){return i(this,t,arguments.length,arguments[1],!1)}})},function(t,e,n){var r=n(21),i=n(57),o=n(33),s=n(37);t.exports=function(t,e,n,a,u){r(e);var c=i(t),f=o(c),h=s(c.length),l=u?h-1:0,p=u?-1:1;if(n<2)for(;;){if(l in f){a=f[l],l+=p;break}if(l+=p,u?l<0:h<=l)throw TypeError("Reduce of empty array with no initial value")}for(;u?l>=0:h>l;l+=p)l in f&&(a=e(a,f[l],l,c));return a}},function(t,e,n){"use strict";var r=n(8),i=n(181);r(r.P+r.F*!n(169)([].reduceRight,!0),"Array",{reduceRight:function(t){return i(this,t,arguments.length,arguments[1],!0)}})},function(t,e,n){"use strict";var r=n(8),i=n(36)(!1),o=[].indexOf,s=!!o&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(s||!n(169)(o)),"Array",{indexOf:function(t){return s?o.apply(this,arguments)||0:i(this,t,arguments[1])}})},function(t,e,n){"use strict";var r=n(8),i=n(32),o=n(38),s=n(37),a=[].lastIndexOf,u=!!a&&1/[1].lastIndexOf(1,-0)<0;r(r.P+r.F*(u||!n(169)(a)),"Array",{lastIndexOf:function(t){if(u)return a.apply(this,arguments)||0;var e=i(this),n=s(e.length),r=n-1;for(arguments.length>1&&(r=Math.min(r,o(arguments[1]))),r<0&&(r=n+r);r>=0;r--)if(r in e&&e[r]===t)return r||0;return-1}})},function(t,e,n){var r=n(8);r(r.P,"Array",{copyWithin:n(186)}),n(187)("copyWithin")},function(t,e,n){"use strict";var r=n(57),i=n(39),o=n(37);t.exports=[].copyWithin||function(t,e){var n=r(this),s=o(n.length),a=i(t,s),u=i(e,s),c=arguments.length>2?arguments[2]:void 0,f=Math.min((void 0===c?s:i(c,s))-u,s-a),h=1;for(u<a&&a<u+f&&(h=-1,u+=f-1,a+=f-1);f-- >0;)u in n?n[a]=n[u]:delete n[a],a+=h,u+=h;return n}},function(t,e,n){var r=n(25)("unscopables"),i=Array.prototype;void 0==i[r]&&n(10)(i,r,{}),t.exports=function(t){i[r][t]=!0}},function(t,e,n){var r=n(8);r(r.P,"Array",{fill:n(189)}),n(187)("fill")},function(t,e,n){"use strict";var r=n(57),i=n(39),o=n(37);t.exports=function(t){for(var e=r(this),n=o(e.length),s=arguments.length,a=i(s>1?arguments[1]:void 0,n),u=s>2?arguments[2]:void 0,c=void 0===u?n:i(u,n);c>a;)e[a++]=t;return e}},function(t,e,n){"use strict";var r=n(8),i=n(173)(5),o="find",s=!0;o in[]&&Array(1)[o](function(){s=!1}),r(r.P+r.F*s,"Array",{find:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),n(187)(o)},function(t,e,n){"use strict";var r=n(8),i=n(173)(6),o="findIndex",s=!0;o in[]&&Array(1)[o](function(){s=!1}),r(r.P+r.F*s,"Array",{findIndex:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),n(187)(o)},function(t,e,n){n(193)("Array")},function(t,e,n){"use strict";var r=n(4),i=n(11),o=n(6),s=n(25)("species");t.exports=function(t){var e=r[t];o&&e&&!e[s]&&i.f(e,s,{configurable:!0,get:function(){return this}})}},function(t,e,n){"use strict";var r=n(187),i=n(195),o=n(129),s=n(32);t.exports=n(128)(Array,"Array",function(t,e){this._t=s(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,i(1)):"keys"==e?i(0,n):"values"==e?i(0,t[n]):i(0,[n,t[n]])},"values"),o.Arguments=o.Array,r("keys"),r("values"),r("entries")},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(4),i=n(87),o=n(11).f,s=n(49).f,a=n(134),u=n(197),c=r.RegExp,f=c,h=c.prototype,l=/a/g,p=/a/g,d=new c(l)!==l;if(n(6)&&(!d||n(7)(function(){return p[n(25)("match")]=!1,c(l)!=l||c(p)==p||"/a/i"!=c(l,"i")}))){c=function(t,e){var n=this instanceof c,r=a(t),o=void 0===e;return!n&&r&&t.constructor===c&&o?t:i(d?new f(r&&!o?t.source:t,e):f((r=t instanceof c)?t.source:t,r&&o?u.call(t):e),n?this:h,c)};for(var g=(function(t){t in c||o(c,t,{configurable:!0,get:function(){return f[t]},set:function(e){f[t]=e}})}),v=s(f),y=0;v.length>y;)g(v[y++]);h.constructor=c,c.prototype=h,n(18)(r,"RegExp",c)}n(193)("RegExp")},function(t,e,n){"use strict";var r=n(12);t.exports=function(){var t=r(this),e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.unicode&&(e+="u"),t.sticky&&(e+="y"),e}},function(t,e,n){"use strict";n(199);var r=n(12),i=n(197),o=n(6),s="toString",a=/./[s],u=function(t){n(18)(RegExp.prototype,s,t,!0)};n(7)(function(){return"/a/b"!=a.call({source:"a",flags:"b"})})?u(function(){var t=r(this);return"/".concat(t.source,"/","flags"in t?t.flags:!o&&t instanceof RegExp?i.call(t):void 0)}):a.name!=s&&u(function(){return a.call(this)})},function(t,e,n){n(6)&&"g"!=/./g.flags&&n(11).f(RegExp.prototype,"flags",{configurable:!0,get:n(197)})},function(t,e,n){n(201)("match",1,function(t,e,n){return[function(n){"use strict";var r=t(this),i=void 0==n?void 0:n[e];return void 0!==i?i.call(n,r):new RegExp(n)[e](String(r))},n]})},function(t,e,n){"use strict";var r=n(10),i=n(18),o=n(7),s=n(35),a=n(25);t.exports=function(t,e,n){var u=a(t),c=n(s,u,""[t]),f=c[0],h=c[1];o(function(){var e={};return e[u]=function(){return 7},7!=""[t](e)})&&(i(String.prototype,t,f),r(RegExp.prototype,u,2==e?function(t,e){return h.call(t,this,e)}:function(t){return h.call(t,this)}))}},function(t,e,n){n(201)("replace",2,function(t,e,n){return[function(r,i){"use strict";var o=t(this),s=void 0==r?void 0:r[e];return void 0!==s?s.call(r,o,i):n.call(String(o),r,i)},n]})},function(t,e,n){n(201)("search",1,function(t,e,n){return[function(n){"use strict";var r=t(this),i=void 0==n?void 0:n[e];return void 0!==i?i.call(n,r):new RegExp(n)[e](String(r))},n]})},function(t,e,n){n(201)("split",2,function(t,e,r){"use strict";var i=n(134),o=r,s=[].push,a="split",u="length",c="lastIndex";if("c"=="abbc"[a](/(b)*/)[1]||4!="test"[a](/(?:)/,-1)[u]||2!="ab"[a](/(?:ab)*/)[u]||4!="."[a](/(.?)(.?)/)[u]||"."[a](/()()/)[u]>1||""[a](/.?/)[u]){var f=void 0===/()??/.exec("")[1];r=function(t,e){var n=String(this);if(void 0===t&&0===e)return[];if(!i(t))return o.call(n,t,e);var r,a,h,l,p,d=[],g=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),v=0,y=void 0===e?4294967295:e>>>0,m=new RegExp(t.source,g+"g");for(f||(r=new RegExp("^"+m.source+"$(?!\\s)",g));(a=m.exec(n))&&(h=a.index+a[0][u],!(h>v&&(d.push(n.slice(v,a.index)),!f&&a[u]>1&&a[0].replace(r,function(){for(p=1;p<arguments[u]-2;p++)void 0===arguments[p]&&(a[p]=void 0)}),a[u]>1&&a.index<n[u]&&s.apply(d,a.slice(1)),l=a[0][u],v=h,d[u]>=y)));)m[c]===a.index&&m[c]++;return v===n[u]?!l&&m.test("")||d.push(""):d.push(n.slice(v)),d[u]>y?d.slice(0,y):d}}else"0"[a](void 0,0)[u]&&(r=function(t,e){return void 0===t&&0===e?[]:o.call(this,t,e)});return[function(n,i){var o=t(this),s=void 0==n?void 0:n[e];return void 0!==s?s.call(n,o,i):r.call(String(o),n,i)},r]})},function(t,e,n){"use strict";var r,i,o,s,a=n(28),u=n(4),c=n(20),f=n(74),h=n(8),l=n(13),p=n(21),d=n(206),g=n(207),v=n(208),y=n(209).set,m=n(210)(),S=n(211),b=n(212),F=n(213),w="Promise",_=u.TypeError,x=u.process,E=u[w],A="process"==f(x),P=function(){},C=i=S.f,k=!!function(){try{var t=E.resolve(1),e=(t.constructor={})[n(25)("species")]=function(t){t(P,P)};return(A||"function"==typeof PromiseRejectionEvent)&&t.then(P)instanceof e}catch(t){}}(),T=function(t){var e;return!(!l(t)||"function"!=typeof(e=t.then))&&e},R=function(t,e){if(!t._n){t._n=!0;var n=t._c;m(function(){for(var r=t._v,i=1==t._s,o=0,s=function(e){var n,o,s,a=i?e.ok:e.fail,u=e.resolve,c=e.reject,f=e.domain;try{a?(i||(2==t._h&&N(t),t._h=1),a===!0?n=r:(f&&f.enter(),n=a(r),f&&(f.exit(),s=!0)),n===e.promise?c(_("Promise-chain cycle")):(o=T(n))?o.call(n,u,c):u(n)):c(r)}catch(t){f&&!s&&f.exit(),c(t)}};n.length>o;)s(n[o++]);t._c=[],t._n=!1,e&&!t._h&&I(t)})}},I=function(t){y.call(u,function(){var e,n,r,i=t._v,o=D(t);if(o&&(e=b(function(){A?x.emit("unhandledRejection",i,t):(n=u.onunhandledrejection)?n({promise:t,reason:i}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",i)}),t._h=A||D(t)?2:1),t._a=void 0,o&&e.e)throw e.v})},D=function(t){return 1!==t._h&&0===(t._a||t._c).length},N=function(t){y.call(u,function(){var e;A?x.emit("rejectionHandled",t):(e=u.onrejectionhandled)&&e({promise:t,reason:t._v})})},O=function(t){var e=this;e._d||(e._d=!0,e=e._w||e,e._v=t,e._s=2,e._a||(e._a=e._c.slice()),R(e,!0))},j=function(t){var e,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===t)throw _("Promise can't be resolved itself");(e=T(t))?m(function(){var r={_w:n,_d:!1};try{e.call(t,c(j,r,1),c(O,r,1))}catch(t){O.call(r,t)}}):(n._v=t,n._s=1,R(n,!1))}catch(t){O.call({_w:n,_d:!1},t)}}};k||(E=function(t){d(this,E,w,"_h"),p(t),r.call(this);try{t(c(j,this,1),c(O,this,1))}catch(t){O.call(this,t)}},r=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(214)(E.prototype,{then:function(t,e){var n=C(v(this,E));return n.ok="function"!=typeof t||t,n.fail="function"==typeof e&&e,n.domain=A?x.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&R(this,!1),n.promise},catch:function(t){return this.then(void 0,t)}}),o=function(){var t=new r;this.promise=t,this.resolve=c(j,t,1),this.reject=c(O,t,1)},S.f=C=function(t){return t===E||t===s?new o(t):i(t)}),h(h.G+h.W+h.F*!k,{Promise:E}),n(24)(E,w),n(193)(w),s=n(9)[w],h(h.S+h.F*!k,w,{reject:function(t){var e=C(this),n=e.reject;return n(t),e.promise}}),h(h.S+h.F*(a||!k),w,{resolve:function(t){return F(a&&this===s?E:this,t)}}),h(h.S+h.F*!(k&&n(166)(function(t){E.all(t).catch(P)})),w,{all:function(t){var e=this,n=C(e),r=n.resolve,i=n.reject,o=b(function(){var n=[],o=0,s=1;g(t,!1,function(t){var a=o++,u=!1;n.push(void 0),s++,e.resolve(t).then(function(t){u||(u=!0,n[a]=t,--s||r(n))},i)}),--s||r(n)});return o.e&&i(o.v),n.promise},race:function(t){var e=this,n=C(e),r=n.reject,i=b(function(){g(t,!1,function(t){e.resolve(t).then(n.resolve,r)})});return i.e&&r(i.v),n.promise}})},function(t,e){t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){var r=n(20),i=n(162),o=n(163),s=n(12),a=n(37),u=n(165),c={},f={},e=t.exports=function(t,e,n,h,l){var p,d,g,v,y=l?function(){return t}:u(t),m=r(n,h,e?2:1),S=0;if("function"!=typeof y)throw TypeError(t+" is not iterable!");if(o(y)){for(p=a(t.length);p>S;S++)if(v=e?m(s(d=t[S])[0],d[1]):m(t[S]),v===c||v===f)return v}else for(g=y.call(t);!(d=g.next()).done;)if(v=i(g,m,d.value,e),v===c||v===f)return v};e.BREAK=c,e.RETURN=f},function(t,e,n){var r=n(12),i=n(21),o=n(25)("species");t.exports=function(t,e){var n,s=r(t).constructor;return void 0===s||void 0==(n=r(s)[o])?e:i(n)}},function(t,e,n){var r,i,o,s=n(20),a=n(77),u=n(47),c=n(15),f=n(4),h=f.process,l=f.setImmediate,p=f.clearImmediate,d=f.MessageChannel,g=f.Dispatch,v=0,y={},m="onreadystatechange",S=function(){var t=+this;if(y.hasOwnProperty(t)){var e=y[t];delete y[t],e()}},b=function(t){S.call(t.data)};l&&p||(l=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return y[++v]=function(){a("function"==typeof t?t:Function(t),e)},r(v),v},p=function(t){delete y[t]},"process"==n(34)(h)?r=function(t){h.nextTick(s(S,t,1))}:g&&g.now?r=function(t){g.now(s(S,t,1))}:d?(i=new d,o=i.port2,i.port1.onmessage=b,r=s(o.postMessage,o,1)):f.addEventListener&&"function"==typeof postMessage&&!f.importScripts?(r=function(t){f.postMessage(t+"","*")},f.addEventListener("message",b,!1)):r=m in c("script")?function(t){u.appendChild(c("script"))[m]=function(){u.removeChild(this),S.call(t)}}:function(t){setTimeout(s(S,t,1),0)}),t.exports={set:l,clear:p}},function(t,e,n){var r=n(4),i=n(209).set,o=r.MutationObserver||r.WebKitMutationObserver,s=r.process,a=r.Promise,u="process"==n(34)(s);t.exports=function(){var t,e,n,c=function(){var r,i;for(u&&(r=s.domain)&&r.exit();t;){i=t.fn,t=t.next;try{i()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(u)n=function(){s.nextTick(c)};else if(!o||r.navigator&&r.navigator.standalone)if(a&&a.resolve){var f=a.resolve();n=function(){f.then(c)}}else n=function(){i.call(r,c)};else{var h=!0,l=document.createTextNode("");new o(c).observe(l,{characterData:!0}),n=function(){l.data=h=!h}}return function(r){var i={fn:r,next:void 0};e&&(e.next=i),t||(t=i,n()),e=i}}},function(t,e,n){"use strict";function r(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=i(e),this.reject=i(n)}var i=n(21);t.exports.f=function(t){return new r(t)}},function(t,e){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,e,n){var r=n(12),i=n(13),o=n(211);t.exports=function(t,e){if(r(t),i(e)&&e.constructor===t)return e;var n=o.f(t),s=n.resolve;return s(e),n.promise}},function(t,e,n){var r=n(18);t.exports=function(t,e,n){for(var i in e)r(t,i,e[i],n);return t}},function(t,e,n){"use strict";var r=n(216),i=n(217),o="Map";t.exports=n(218)(o,function(t){return function(){return t(this,arguments.length>0?arguments[0]:void 0)}},{get:function(t){var e=r.getEntry(i(this,o),t);return e&&e.v},set:function(t,e){return r.def(i(this,o),0===t?0:t,e)}},r,!0)},function(t,e,n){"use strict";var r=n(11).f,i=n(45),o=n(214),s=n(20),a=n(206),u=n(207),c=n(128),f=n(195),h=n(193),l=n(6),p=n(22).fastKey,d=n(217),g=l?"_s":"size",v=function(t,e){var n,r=p(e);if("F"!==r)return t._i[r];for(n=t._f;n;n=n.n)if(n.k==e)return n};t.exports={getConstructor:function(t,e,n,c){var f=t(function(t,r){a(t,f,e,"_i"),t._t=e,t._i=i(null),t._f=void 0,t._l=void 0,t[g]=0,void 0!=r&&u(r,n,t[c],t)});return o(f.prototype,{clear:function(){for(var t=d(this,e),n=t._i,r=t._f;r;r=r.n)r.r=!0,r.p&&(r.p=r.p.n=void 0),delete n[r.i];t._f=t._l=void 0,t[g]=0},delete:function(t){var n=d(this,e),r=v(n,t);if(r){var i=r.n,o=r.p;delete n._i[r.i],r.r=!0,o&&(o.n=i),i&&(i.p=o),n._f==r&&(n._f=i),n._l==r&&(n._l=o),n[g]--}return!!r},forEach:function(t){d(this,e);for(var n,r=s(t,arguments.length>1?arguments[1]:void 0,3);n=n?n.n:this._f;)for(r(n.v,n.k,this);n&&n.r;)n=n.p},has:function(t){return!!v(d(this,e),t)}}),l&&r(f.prototype,"size",{get:function(){return d(this,e)[g]}}),f},def:function(t,e,n){var r,i,o=v(t,e);return o?o.v=n:(t._l=o={i:i=p(e,!0),k:e,v:n,p:r=t._l,n:void 0,r:!1},t._f||(t._f=o),r&&(r.n=o),t[g]++,"F"!==i&&(t._i[i]=o)),t},getEntry:v,setStrong:function(t,e,n){c(t,e,function(t,n){this._t=d(t,e),this._k=n,this._l=void 0},function(){for(var t=this,e=t._k,n=t._l;n&&n.r;)n=n.p;return t._t&&(t._l=n=n?n.n:t._t._f)?"keys"==e?f(0,n.k):"values"==e?f(0,n.v):f(0,[n.k,n.v]):(t._t=void 0,f(1))},n?"entries":"values",!n,!0),h(e)}}},function(t,e,n){var r=n(13);t.exports=function(t,e){if(!r(t)||t._t!==e)throw TypeError("Incompatible receiver, "+e+" required!");return t}},function(t,e,n){"use strict";var r=n(4),i=n(8),o=n(18),s=n(214),a=n(22),u=n(207),c=n(206),f=n(13),h=n(7),l=n(166),p=n(24),d=n(87);t.exports=function(t,e,n,g,v,y){var m=r[t],S=m,b=v?"set":"add",F=S&&S.prototype,w={},_=function(t){var e=F[t];o(F,t,"delete"==t?function(t){return!(y&&!f(t))&&e.call(this,0===t?0:t)}:"has"==t?function(t){return!(y&&!f(t))&&e.call(this,0===t?0:t)}:"get"==t?function(t){return y&&!f(t)?void 0:e.call(this,0===t?0:t)}:"add"==t?function(t){return e.call(this,0===t?0:t),this}:function(t,n){return e.call(this,0===t?0:t,n),this})};if("function"==typeof S&&(y||F.forEach&&!h(function(){(new S).entries().next()}))){var x=new S,E=x[b](y?{}:-0,1)!=x,A=h(function(){x.has(1)}),P=l(function(t){new S(t)}),C=!y&&h(function(){for(var t=new S,e=5;e--;)t[b](e,e);return!t.has(-0)});P||(S=e(function(e,n){c(e,S,t);var r=d(new m,e,S);return void 0!=n&&u(n,v,r[b],r),r}),S.prototype=F,F.constructor=S),(A||C)&&(_("delete"),_("has"),v&&_("get")),(C||E)&&_(b),y&&F.clear&&delete F.clear}else S=g.getConstructor(e,t,v,b),s(S.prototype,n),a.NEED=!0;return p(S,t),w[t]=S,i(i.G+i.W+i.F*(S!=m),w),y||g.setStrong(S,t,v),S}},function(t,e,n){"use strict";var r=n(216),i=n(217),o="Set";t.exports=n(218)(o,function(t){return function(){return t(this,arguments.length>0?arguments[0]:void 0)}},{add:function(t){return r.def(i(this,o),t=0===t?0:t,t)}},r)},function(t,e,n){"use strict";var r,i=n(173)(0),o=n(18),s=n(22),a=n(68),u=n(221),c=n(13),f=n(7),h=n(217),l="WeakMap",p=s.getWeak,d=Object.isExtensible,g=u.ufstore,v={},y=function(t){return function(){return t(this,arguments.length>0?arguments[0]:void 0)}},m={get:function(t){if(c(t)){var e=p(t);return e===!0?g(h(this,l)).get(t):e?e[this._i]:void 0}},set:function(t,e){return u.def(h(this,l),t,e)}},S=t.exports=n(218)(l,y,m,u,!0,!0);f(function(){return 7!=(new S).set((Object.freeze||Object)(v),7).get(v)})&&(r=u.getConstructor(y,l),a(r.prototype,m),s.NEED=!0,i(["delete","has","get","set"],function(t){var e=S.prototype,n=e[t];o(e,t,function(e,i){if(c(e)&&!d(e)){this._f||(this._f=new r);var o=this._f[t](e,i);return"set"==t?this:o}return n.call(this,e,i)})}))},function(t,e,n){"use strict";var r=n(214),i=n(22).getWeak,o=n(12),s=n(13),a=n(206),u=n(207),c=n(173),f=n(5),h=n(217),l=c(5),p=c(6),d=0,g=function(t){return t._l||(t._l=new v)},v=function(){this.a=[]},y=function(t,e){return l(t.a,function(t){return t[0]===e})};v.prototype={get:function(t){var e=y(this,t);if(e)return e[1]},has:function(t){return!!y(this,t)},set:function(t,e){var n=y(this,t);n?n[1]=e:this.a.push([t,e])},delete:function(t){var e=p(this.a,function(e){return e[0]===t});return~e&&this.a.splice(e,1),!!~e}},t.exports={getConstructor:function(t,e,n,o){var c=t(function(t,r){a(t,c,e,"_i"),t._t=e,t._i=d++,t._l=void 0,void 0!=r&&u(r,n,t[o],t)});return r(c.prototype,{delete:function(t){if(!s(t))return!1;var n=i(t);return n===!0?g(h(this,e)).delete(t):n&&f(n,this._i)&&delete n[this._i]},has:function(t){if(!s(t))return!1;var n=i(t);return n===!0?g(h(this,e)).has(t):n&&f(n,this._i)}}),c},def:function(t,e,n){var r=i(o(e),!0);return r===!0?g(t).set(e,n):r[t._i]=n,t},ufstore:g}},function(t,e,n){"use strict";var r=n(221),i=n(217),o="WeakSet";n(218)(o,function(t){return function(){return t(this,arguments.length>0?arguments[0]:void 0)}},{add:function(t){return r.def(i(this,o),t,!0)}},r,!1,!0)},function(t,e,n){"use strict";var r=n(8),i=n(224),o=n(225),s=n(12),a=n(39),u=n(37),c=n(13),f=n(4).ArrayBuffer,h=n(208),l=o.ArrayBuffer,p=o.DataView,d=i.ABV&&f.isView,g=l.prototype.slice,v=i.VIEW,y="ArrayBuffer";r(r.G+r.W+r.F*(f!==l),{ArrayBuffer:l}),r(r.S+r.F*!i.CONSTR,y,{isView:function(t){return d&&d(t)||c(t)&&v in t}}),r(r.P+r.U+r.F*n(7)(function(){return!new l(2).slice(1,void 0).byteLength}),y,{slice:function(t,e){if(void 0!==g&&void 0===e)return g.call(s(this),t);for(var n=s(this).byteLength,r=a(t,n),i=a(void 0===e?n:e,n),o=new(h(this,l))(u(i-r)),c=new p(this),f=new p(o),d=0;r<i;)f.setUint8(d++,c.getUint8(r++));return o}}),n(193)(y)},function(t,e,n){for(var r,i=n(4),o=n(10),s=n(19),a=s("typed_array"),u=s("view"),c=!(!i.ArrayBuffer||!i.DataView),f=c,h=0,l=9,p="Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array".split(",");h<l;)(r=i[p[h++]])?(o(r.prototype,a,!0),o(r.prototype,u,!0)):f=!1;t.exports={ABV:c,CONSTR:f,TYPED:a,VIEW:u}},function(t,e,n){"use strict";function r(t,e,n){var r,i,o,s=new Array(n),a=8*n-e-1,u=(1<<a)-1,c=u>>1,f=23===e?U(2,-24)-U(2,-77):0,h=0,l=t<0||0===t&&1/t<0?1:0;for(t=H(t),t!=t||t===M?(i=t!=t?1:0,r=u):(r=V(K(t)/q),t*(o=U(2,-r))<1&&(r--,o*=2),t+=r+c>=1?f/o:f*U(2,1-c),t*o>=2&&(r++,o/=2),r+c>=u?(i=0,r=u):r+c>=1?(i=(t*o-1)*U(2,e),r+=c):(i=t*U(2,c-1)*U(2,e),r=0));e>=8;s[h++]=255&i,i/=256,e-=8);for(r=r<<e|i,a+=e;a>0;s[h++]=255&r,r/=256,a-=8);return s[--h]|=128*l,s}function i(t,e,n){var r,i=8*n-e-1,o=(1<<i)-1,s=o>>1,a=i-7,u=n-1,c=t[u--],f=127&c;for(c>>=7;a>0;f=256*f+t[u],u--,a-=8);for(r=f&(1<<-a)-1,f>>=-a,a+=e;a>0;r=256*r+t[u],u--,a-=8);if(0===f)f=1-s;else{if(f===o)return r?NaN:c?-M:M;r+=U(2,e),f-=s}return(c?-1:1)*r*U(2,f-e)}function o(t){return t[3]<<24|t[2]<<16|t[1]<<8|t[0]}function s(t){return[255&t]}function a(t){return[255&t,t>>8&255]}function u(t){return[255&t,t>>8&255,t>>16&255,t>>24&255]}function c(t){return r(t,52,8)}function f(t){return r(t,23,4)}function h(t,e,n){A(t[R],e,{get:function(){return this[n]}})}function l(t,e,n,r){var i=+n,o=x(i);if(o+e>t[Y])throw L(D);var s=t[z]._b,a=o+t[$],u=s.slice(a,a+e);return r?u:u.reverse()}function p(t,e,n,r,i,o){var s=+n,a=x(s);if(a+e>t[Y])throw L(D);for(var u=t[z]._b,c=a+t[$],f=r(+i),h=0;h<e;h++)u[c+h]=f[o?h:e-h-1]}var d=n(4),g=n(6),v=n(28),y=n(224),m=n(10),S=n(214),b=n(7),F=n(206),w=n(38),_=n(37),x=n(226),E=n(49).f,A=n(11).f,P=n(189),C=n(24),k="ArrayBuffer",T="DataView",R="prototype",I="Wrong length!",D="Wrong index!",N=d[k],O=d[T],j=d.Math,L=d.RangeError,M=d.Infinity,B=N,H=j.abs,U=j.pow,V=j.floor,K=j.log,q=j.LN2,W="buffer",J="byteLength",G="byteOffset",z=g?"_b":W,Y=g?"_l":J,$=g?"_o":G;if(y.ABV){if(!b(function(){N(1)})||!b(function(){new N(-1)})||b(function(){return new N,new N(1.5),new N(NaN),N.name!=k})){N=function(t){return F(this,N),new B(x(t))};for(var X,Z=N[R]=B[R],Q=E(B),tt=0;Q.length>tt;)(X=Q[tt++])in N||m(N,X,B[X]);v||(Z.constructor=N)}var et=new O(new N(2)),nt=O[R].setInt8;et.setInt8(0,2147483648),et.setInt8(1,2147483649),!et.getInt8(0)&&et.getInt8(1)||S(O[R],{setInt8:function(t,e){nt.call(this,t,e<<24>>24)},setUint8:function(t,e){nt.call(this,t,e<<24>>24)}},!0)}else N=function(t){F(this,N,k);var e=x(t);this._b=P.call(new Array(e),0),this[Y]=e},O=function(t,e,n){F(this,O,T),F(t,N,T);var r=t[Y],i=w(e);if(i<0||i>r)throw L("Wrong offset!");if(n=void 0===n?r-i:_(n),i+n>r)throw L(I);this[z]=t,this[$]=i,this[Y]=n},g&&(h(N,J,"_l"),h(O,W,"_b"),h(O,J,"_l"),h(O,G,"_o")),S(O[R],{getInt8:function(t){return l(this,1,t)[0]<<24>>24},getUint8:function(t){return l(this,1,t)[0]},getInt16:function(t){var e=l(this,2,t,arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(t){var e=l(this,2,t,arguments[1]);return e[1]<<8|e[0]},getInt32:function(t){return o(l(this,4,t,arguments[1]))},getUint32:function(t){return o(l(this,4,t,arguments[1]))>>>0},getFloat32:function(t){return i(l(this,4,t,arguments[1]),23,4)},getFloat64:function(t){return i(l(this,8,t,arguments[1]),52,8)},setInt8:function(t,e){p(this,1,t,s,e)},setUint8:function(t,e){p(this,1,t,s,e)},setInt16:function(t,e){p(this,2,t,a,e,arguments[2])},setUint16:function(t,e){p(this,2,t,a,e,arguments[2])},setInt32:function(t,e){p(this,4,t,u,e,arguments[2])},setUint32:function(t,e){p(this,4,t,u,e,arguments[2])},setFloat32:function(t,e){p(this,4,t,f,e,arguments[2])},setFloat64:function(t,e){p(this,8,t,c,e,arguments[2])}});C(N,k),C(O,T),m(O[R],y.VIEW,!0),e[k]=N,e[T]=O},function(t,e,n){var r=n(38),i=n(37);t.exports=function(t){if(void 0===t)return 0;var e=r(t),n=i(e);if(e!==n)throw RangeError("Wrong length!");return n}},function(t,e,n){var r=n(8);r(r.G+r.W+r.F*!n(224).ABV,{DataView:n(225).DataView})},function(t,e,n){n(229)("Int8",1,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){"use strict";if(n(6)){var r=n(28),i=n(4),o=n(7),s=n(8),a=n(224),u=n(225),c=n(20),f=n(206),h=n(17),l=n(10),p=n(214),d=n(38),g=n(37),v=n(226),y=n(39),m=n(16),S=n(5),b=n(74),F=n(13),w=n(57),_=n(163),x=n(45),E=n(58),A=n(49).f,P=n(165),C=n(19),k=n(25),T=n(173),R=n(36),I=n(208),D=n(194),N=n(129),O=n(166),j=n(193),L=n(189),M=n(186),B=n(11),H=n(50),U=B.f,V=H.f,K=i.RangeError,q=i.TypeError,W=i.Uint8Array,J="ArrayBuffer",G="Shared"+J,z="BYTES_PER_ELEMENT",Y="prototype",$=Array[Y],X=u.ArrayBuffer,Z=u.DataView,Q=T(0),tt=T(2),et=T(3),nt=T(4),rt=T(5),it=T(6),ot=R(!0),st=R(!1),at=D.values,ut=D.keys,ct=D.entries,ft=$.lastIndexOf,ht=$.reduce,lt=$.reduceRight,pt=$.join,dt=$.sort,gt=$.slice,vt=$.toString,yt=$.toLocaleString,mt=k("iterator"),St=k("toStringTag"),bt=C("typed_constructor"),Ft=C("def_constructor"),wt=a.CONSTR,_t=a.TYPED,xt=a.VIEW,Et="Wrong length!",At=T(1,function(t,e){return Rt(I(t,t[Ft]),e)}),Pt=o(function(){return 1===new W(new Uint16Array([1]).buffer)[0]}),Ct=!!W&&!!W[Y].set&&o(function(){new W(1).set({})}),kt=function(t,e){var n=d(t);if(n<0||n%e)throw K("Wrong offset!");return n},Tt=function(t){if(F(t)&&_t in t)return t;throw q(t+" is not a typed array!")},Rt=function(t,e){if(!(F(t)&&bt in t))throw q("It is not a typed array constructor!");return new t(e)},It=function(t,e){return Dt(I(t,t[Ft]),e)},Dt=function(t,e){for(var n=0,r=e.length,i=Rt(t,r);r>n;)i[n]=e[n++];return i},Nt=function(t,e,n){U(t,e,{get:function(){return this._d[n]}})},Ot=function(t){var e,n,r,i,o,s,a=w(t),u=arguments.length,f=u>1?arguments[1]:void 0,h=void 0!==f,l=P(a);if(void 0!=l&&!_(l)){for(s=l.call(a),r=[],e=0;!(o=s.next()).done;e++)r.push(o.value);a=r}for(h&&u>2&&(f=c(f,arguments[2],2)),e=0,n=g(a.length),i=Rt(this,n);n>e;e++)i[e]=h?f(a[e],e):a[e];return i},jt=function(){for(var t=0,e=arguments.length,n=Rt(this,e);e>t;)n[t]=arguments[t++];return n},Lt=!!W&&o(function(){yt.call(new W(1))}),Mt=function(){return yt.apply(Lt?gt.call(Tt(this)):Tt(this),arguments)},Bt={copyWithin:function(t,e){return M.call(Tt(this),t,e,arguments.length>2?arguments[2]:void 0)},every:function(t){return nt(Tt(this),t,arguments.length>1?arguments[1]:void 0)},fill:function(t){return L.apply(Tt(this),arguments)},filter:function(t){return It(this,tt(Tt(this),t,arguments.length>1?arguments[1]:void 0))},find:function(t){return rt(Tt(this),t,arguments.length>1?arguments[1]:void 0)},findIndex:function(t){return it(Tt(this),t,arguments.length>1?arguments[1]:void 0)},forEach:function(t){Q(Tt(this),t,arguments.length>1?arguments[1]:void 0)},indexOf:function(t){return st(Tt(this),t,arguments.length>1?arguments[1]:void 0)},includes:function(t){return ot(Tt(this),t,arguments.length>1?arguments[1]:void 0)},join:function(t){return pt.apply(Tt(this),arguments)},lastIndexOf:function(t){return ft.apply(Tt(this),arguments)},map:function(t){return At(Tt(this),t,arguments.length>1?arguments[1]:void 0)},reduce:function(t){return ht.apply(Tt(this),arguments)},reduceRight:function(t){return lt.apply(Tt(this),arguments)},reverse:function(){for(var t,e=this,n=Tt(e).length,r=Math.floor(n/2),i=0;i<r;)t=e[i],e[i++]=e[--n],e[n]=t;return e},some:function(t){return et(Tt(this),t,arguments.length>1?arguments[1]:void 0)},sort:function(t){return dt.call(Tt(this),t)},subarray:function(t,e){var n=Tt(this),r=n.length,i=y(t,r);return new(I(n,n[Ft]))(n.buffer,n.byteOffset+i*n.BYTES_PER_ELEMENT,g((void 0===e?r:y(e,r))-i))}},Ht=function(t,e){return It(this,gt.call(Tt(this),t,e))},Ut=function(t){Tt(this);var e=kt(arguments[1],1),n=this.length,r=w(t),i=g(r.length),o=0;if(i+e>n)throw K(Et);for(;o<i;)this[e+o]=r[o++]},Vt={entries:function(){return ct.call(Tt(this))},keys:function(){return ut.call(Tt(this))},values:function(){return at.call(Tt(this))}},Kt=function(t,e){return F(t)&&t[_t]&&"symbol"!=typeof e&&e in t&&String(+e)==String(e)},qt=function(t,e){return Kt(t,e=m(e,!0))?h(2,t[e]):V(t,e)},Wt=function(t,e,n){return!(Kt(t,e=m(e,!0))&&F(n)&&S(n,"value"))||S(n,"get")||S(n,"set")||n.configurable||S(n,"writable")&&!n.writable||S(n,"enumerable")&&!n.enumerable?U(t,e,n):(t[e]=n.value,t)};wt||(H.f=qt,B.f=Wt),s(s.S+s.F*!wt,"Object",{getOwnPropertyDescriptor:qt,defineProperty:Wt}),o(function(){vt.call({})})&&(vt=yt=function(){return pt.call(this)});var Jt=p({},Bt);p(Jt,Vt),l(Jt,mt,Vt.values),p(Jt,{slice:Ht,set:Ut,constructor:function(){},toString:vt,toLocaleString:Mt}),Nt(Jt,"buffer","b"),Nt(Jt,"byteOffset","o"),Nt(Jt,"byteLength","l"),Nt(Jt,"length","e"),U(Jt,St,{get:function(){return this[_t]}}),t.exports=function(t,e,n,u){u=!!u;var c=t+(u?"Clamped":"")+"Array",h="get"+t,p="set"+t,d=i[c],y=d||{},m=d&&E(d),S=!d||!a.ABV,w={},_=d&&d[Y],P=function(t,n){var r=t._d;return r.v[h](n*e+r.o,Pt)},C=function(t,n,r){var i=t._d;u&&(r=(r=Math.round(r))<0?0:r>255?255:255&r),i.v[p](n*e+i.o,r,Pt)},k=function(t,e){U(t,e,{get:function(){return P(this,e)},set:function(t){ return C(this,e,t)},enumerable:!0})};S?(d=n(function(t,n,r,i){f(t,d,c,"_d");var o,s,a,u,h=0,p=0;if(F(n)){if(!(n instanceof X||(u=b(n))==J||u==G))return _t in n?Dt(d,n):Ot.call(d,n);o=n,p=kt(r,e);var y=n.byteLength;if(void 0===i){if(y%e)throw K(Et);if(s=y-p,s<0)throw K(Et)}else if(s=g(i)*e,s+p>y)throw K(Et);a=s/e}else a=v(n),s=a*e,o=new X(s);for(l(t,"_d",{b:o,o:p,l:s,e:a,v:new Z(o)});h<a;)k(t,h++)}),_=d[Y]=x(Jt),l(_,"constructor",d)):o(function(){d(1)})&&o(function(){new d(-1)})&&O(function(t){new d,new d(null),new d(1.5),new d(t)},!0)||(d=n(function(t,n,r,i){f(t,d,c);var o;return F(n)?n instanceof X||(o=b(n))==J||o==G?void 0!==i?new y(n,kt(r,e),i):void 0!==r?new y(n,kt(r,e)):new y(n):_t in n?Dt(d,n):Ot.call(d,n):new y(v(n))}),Q(m!==Function.prototype?A(y).concat(A(m)):A(y),function(t){t in d||l(d,t,y[t])}),d[Y]=_,r||(_.constructor=d));var T=_[mt],R=!!T&&("values"==T.name||void 0==T.name),I=Vt.values;l(d,bt,!0),l(_,_t,c),l(_,xt,!0),l(_,Ft,d),(u?new d(1)[St]==c:St in _)||U(_,St,{get:function(){return c}}),w[c]=d,s(s.G+s.W+s.F*(d!=y),w),s(s.S,c,{BYTES_PER_ELEMENT:e}),s(s.S+s.F*o(function(){y.of.call(d,1)}),c,{from:Ot,of:jt}),z in _||l(_,z,e),s(s.P,c,Bt),j(c),s(s.P+s.F*Ct,c,{set:Ut}),s(s.P+s.F*!R,c,Vt),r||_.toString==vt||(_.toString=vt),s(s.P+s.F*o(function(){new d(1).slice()}),c,{slice:Ht}),s(s.P+s.F*(o(function(){return[1,2].toLocaleString()!=new d([1,2]).toLocaleString()})||!o(function(){_.toLocaleString.call([1,2])})),c,{toLocaleString:Mt}),N[c]=R?T:I,r||R||l(_,mt,I)}}else t.exports=function(){}},function(t,e,n){n(229)("Uint8",1,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Uint8",1,function(t){return function(e,n,r){return t(this,e,n,r)}},!0)},function(t,e,n){n(229)("Int16",2,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Uint16",2,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Int32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Uint32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Float32",4,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){n(229)("Float64",8,function(t){return function(e,n,r){return t(this,e,n,r)}})},function(t,e,n){var r=n(8),i=n(21),o=n(12),s=(n(4).Reflect||{}).apply,a=Function.apply;r(r.S+r.F*!n(7)(function(){s(function(){})}),"Reflect",{apply:function(t,e,n){var r=i(t),u=o(n);return s?s(r,e,u):a.call(r,e,u)}})},function(t,e,n){var r=n(8),i=n(45),o=n(21),s=n(12),a=n(13),u=n(7),c=n(76),f=(n(4).Reflect||{}).construct,h=u(function(){function t(){}return!(f(function(){},[],t)instanceof t)}),l=!u(function(){f(function(){})});r(r.S+r.F*(h||l),"Reflect",{construct:function(t,e){o(t),s(e);var n=arguments.length<3?t:o(arguments[2]);if(l&&!h)return f(t,e,n);if(t==n){switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3])}var r=[null];return r.push.apply(r,e),new(c.apply(t,r))}var u=n.prototype,p=i(a(u)?u:Object.prototype),d=Function.apply.call(t,p,e);return a(d)?d:p}})},function(t,e,n){var r=n(11),i=n(8),o=n(12),s=n(16);i(i.S+i.F*n(7)(function(){Reflect.defineProperty(r.f({},1,{value:1}),1,{value:2})}),"Reflect",{defineProperty:function(t,e,n){o(t),e=s(e,!0),o(n);try{return r.f(t,e,n),!0}catch(t){return!1}}})},function(t,e,n){var r=n(8),i=n(50).f,o=n(12);r(r.S,"Reflect",{deleteProperty:function(t,e){var n=i(o(t),e);return!(n&&!n.configurable)&&delete t[e]}})},function(t,e,n){"use strict";var r=n(8),i=n(12),o=function(t){this._t=i(t),this._i=0;var e,n=this._k=[];for(e in t)n.push(e)};n(130)(o,"Object",function(){var t,e=this,n=e._k;do if(e._i>=n.length)return{value:void 0,done:!0};while(!((t=n[e._i++])in e._t));return{value:t,done:!1}}),r(r.S,"Reflect",{enumerate:function(t){return new o(t)}})},function(t,e,n){function r(t,e){var n,a,f=arguments.length<3?t:arguments[2];return c(t)===f?t[e]:(n=i.f(t,e))?s(n,"value")?n.value:void 0!==n.get?n.get.call(f):void 0:u(a=o(t))?r(a,e,f):void 0}var i=n(50),o=n(58),s=n(5),a=n(8),u=n(13),c=n(12);a(a.S,"Reflect",{get:r})},function(t,e,n){var r=n(50),i=n(8),o=n(12);i(i.S,"Reflect",{getOwnPropertyDescriptor:function(t,e){return r.f(o(t),e)}})},function(t,e,n){var r=n(8),i=n(58),o=n(12);r(r.S,"Reflect",{getPrototypeOf:function(t){return i(o(t))}})},function(t,e,n){var r=n(8);r(r.S,"Reflect",{has:function(t,e){return e in t}})},function(t,e,n){var r=n(8),i=n(12),o=Object.isExtensible;r(r.S,"Reflect",{isExtensible:function(t){return i(t),!o||o(t)}})},function(t,e,n){var r=n(8);r(r.S,"Reflect",{ownKeys:n(249)})},function(t,e,n){var r=n(49),i=n(42),o=n(12),s=n(4).Reflect;t.exports=s&&s.ownKeys||function(t){var e=r.f(o(t)),n=i.f;return n?e.concat(n(t)):e}},function(t,e,n){var r=n(8),i=n(12),o=Object.preventExtensions;r(r.S,"Reflect",{preventExtensions:function(t){i(t);try{return o&&o(t),!0}catch(t){return!1}}})},function(t,e,n){function r(t,e,n){var u,l,p=arguments.length<4?t:arguments[3],d=o.f(f(t),e);if(!d){if(h(l=s(t)))return r(l,e,n,p);d=c(0)}if(a(d,"value")){if(d.writable===!1||!h(p))return!1;if(u=o.f(p,e)){if(u.get||u.set||u.writable===!1)return!1;u.value=n,i.f(p,e,u)}else i.f(p,e,c(0,n));return!0}return void 0!==d.set&&(d.set.call(p,n),!0)}var i=n(11),o=n(50),s=n(58),a=n(5),u=n(8),c=n(17),f=n(12),h=n(13);u(u.S,"Reflect",{set:r})},function(t,e,n){var r=n(8),i=n(72);i&&r(r.S,"Reflect",{setPrototypeOf:function(t,e){i.check(t,e);try{return i.set(t,e),!0}catch(t){return!1}}})},function(t,e,n){"use strict";var r=n(8),i=n(36)(!0);r(r.P,"Array",{includes:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0)}}),n(187)("includes")},function(t,e,n){"use strict";var r=n(8),i=n(255),o=n(57),s=n(37),a=n(21),u=n(174);r(r.P,"Array",{flatMap:function(t){var e,n,r=o(this);return a(t),e=s(r.length),n=u(r,0),i(n,r,r,e,0,1,t,arguments[1]),n}}),n(187)("flatMap")},function(t,e,n){"use strict";function r(t,e,n,c,f,h,l,p){for(var d,g,v=f,y=0,m=!!l&&a(l,p,3);y<c;){if(y in n){if(d=m?m(n[y],y,e):n[y],g=!1,o(d)&&(g=d[u],g=void 0!==g?!!g:i(d)),g&&h>0)v=r(t,e,d,s(d.length),v,h-1)-1;else{if(v>=9007199254740991)throw TypeError();t[v]=d}v++}y++}return v}var i=n(44),o=n(13),s=n(37),a=n(20),u=n(25)("isConcatSpreadable");t.exports=r},function(t,e,n){"use strict";var r=n(8),i=n(255),o=n(57),s=n(37),a=n(38),u=n(174);r(r.P,"Array",{flatten:function(){var t=arguments[0],e=o(this),n=s(e.length),r=u(e,0);return i(r,e,e,n,0,void 0===t?1:a(t)),r}}),n(187)("flatten")},function(t,e,n){"use strict";var r=n(8),i=n(127)(!0);r(r.P,"String",{at:function(t){return i(this,t)}})},function(t,e,n){"use strict";var r=n(8),i=n(259),o=n(260);r(r.P+r.F*/Version\/10\.\d+(\.\d+)? Safari\//.test(o),"String",{padStart:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0,!0)}})},function(t,e,n){var r=n(37),i=n(90),o=n(35);t.exports=function(t,e,n,s){var a=String(o(t)),u=a.length,c=void 0===n?" ":String(n),f=r(e);if(f<=u||""==c)return a;var h=f-u,l=i.call(c,Math.ceil(h/c.length));return l.length>h&&(l=l.slice(0,h)),s?l+a:a+l}},function(t,e,n){var r=n(4),i=r.navigator;t.exports=i&&i.userAgent||""},function(t,e,n){"use strict";var r=n(8),i=n(259),o=n(260);r(r.P+r.F*/Version\/10\.\d+(\.\d+)? Safari\//.test(o),"String",{padEnd:function(t){return i(this,t,arguments.length>1?arguments[1]:void 0,!1)}})},function(t,e,n){"use strict";n(82)("trimLeft",function(t){return function(){return t(this,1)}},"trimStart")},function(t,e,n){"use strict";n(82)("trimRight",function(t){return function(){return t(this,2)}},"trimEnd")},function(t,e,n){"use strict";var r=n(8),i=n(35),o=n(37),s=n(134),a=n(197),u=RegExp.prototype,c=function(t,e){this._r=t,this._s=e};n(130)(c,"RegExp String",function(){var t=this._r.exec(this._s);return{value:t,done:null===t}}),r(r.P,"String",{matchAll:function(t){if(i(this),!s(t))throw TypeError(t+" is not a regexp!");var e=String(this),n="flags"in u?String(t.flags):a.call(t),r=new RegExp(t.source,~n.indexOf("g")?n:"g"+n);return r.lastIndex=o(t.lastIndex),new c(r,e)}})},function(t,e,n){n(27)("asyncIterator")},function(t,e,n){n(27)("observable")},function(t,e,n){var r=n(8),i=n(249),o=n(32),s=n(50),a=n(164);r(r.S,"Object",{getOwnPropertyDescriptors:function(t){for(var e,n,r=o(t),u=s.f,c=i(r),f={},h=0;c.length>h;)n=u(r,e=c[h++]),void 0!==n&&a(f,e,n);return f}})},function(t,e,n){var r=n(8),i=n(269)(!1);r(r.S,"Object",{values:function(t){return i(t)}})},function(t,e,n){var r=n(30),i=n(32),o=n(43).f;t.exports=function(t){return function(e){for(var n,s=i(e),a=r(s),u=a.length,c=0,f=[];u>c;)o.call(s,n=a[c++])&&f.push(t?[n,s[n]]:s[n]);return f}}},function(t,e,n){var r=n(8),i=n(269)(!0);r(r.S,"Object",{entries:function(t){return i(t)}})},function(t,e,n){"use strict";var r=n(8),i=n(57),o=n(21),s=n(11);n(6)&&r(r.P+n(272),"Object",{__defineGetter__:function(t,e){s.f(i(this),t,{get:o(e),enumerable:!0,configurable:!0})}})},function(t,e,n){"use strict";t.exports=n(28)||!n(7)(function(){var t=Math.random();__defineSetter__.call(null,t,function(){}),delete n(4)[t]})},function(t,e,n){"use strict";var r=n(8),i=n(57),o=n(21),s=n(11);n(6)&&r(r.P+n(272),"Object",{__defineSetter__:function(t,e){s.f(i(this),t,{set:o(e),enumerable:!0,configurable:!0})}})},function(t,e,n){"use strict";var r=n(8),i=n(57),o=n(16),s=n(58),a=n(50).f;n(6)&&r(r.P+n(272),"Object",{__lookupGetter__:function(t){var e,n=i(this),r=o(t,!0);do if(e=a(n,r))return e.get;while(n=s(n))}})},function(t,e,n){"use strict";var r=n(8),i=n(57),o=n(16),s=n(58),a=n(50).f;n(6)&&r(r.P+n(272),"Object",{__lookupSetter__:function(t){var e,n=i(this),r=o(t,!0);do if(e=a(n,r))return e.set;while(n=s(n))}})},function(t,e,n){var r=n(8);r(r.P+r.R,"Map",{toJSON:n(277)("Map")})},function(t,e,n){var r=n(74),i=n(278);t.exports=function(t){return function(){if(r(this)!=t)throw TypeError(t+"#toJSON isn't generic");return i(this)}}},function(t,e,n){var r=n(207);t.exports=function(t,e){var n=[];return r(t,!1,n.push,n,e),n}},function(t,e,n){var r=n(8);r(r.P+r.R,"Set",{toJSON:n(277)("Set")})},function(t,e,n){n(281)("Map")},function(t,e,n){"use strict";var r=n(8);t.exports=function(t){r(r.S,t,{of:function(){for(var t=arguments.length,e=new Array(t);t--;)e[t]=arguments[t];return new this(e)}})}},function(t,e,n){n(281)("Set")},function(t,e,n){n(281)("WeakMap")},function(t,e,n){n(281)("WeakSet")},function(t,e,n){n(286)("Map")},function(t,e,n){"use strict";var r=n(8),i=n(21),o=n(20),s=n(207);t.exports=function(t){r(r.S,t,{from:function(t){var e,n,r,a,u=arguments[1];return i(this),e=void 0!==u,e&&i(u),void 0==t?new this:(n=[],e?(r=0,a=o(u,arguments[2],2),s(t,!1,function(t){n.push(a(t,r++))})):s(t,!1,n.push,n),new this(n))}})}},function(t,e,n){n(286)("Set")},function(t,e,n){n(286)("WeakMap")},function(t,e,n){n(286)("WeakSet")},function(t,e,n){var r=n(8);r(r.G,{global:n(4)})},function(t,e,n){var r=n(8);r(r.S,"System",{global:n(4)})},function(t,e,n){var r=n(8),i=n(34);r(r.S,"Error",{isError:function(t){return"Error"===i(t)}})},function(t,e,n){var r=n(8);r(r.S,"Math",{clamp:function(t,e,n){return Math.min(n,Math.max(e,t))}})},function(t,e,n){var r=n(8);r(r.S,"Math",{DEG_PER_RAD:Math.PI/180})},function(t,e,n){var r=n(8),i=180/Math.PI;r(r.S,"Math",{degrees:function(t){return t*i}})},function(t,e,n){var r=n(8),i=n(297),o=n(113);r(r.S,"Math",{fscale:function(t,e,n,r,s){return o(i(t,e,n,r,s))}})},function(t,e){t.exports=Math.scale||function(t,e,n,r,i){return 0===arguments.length||t!=t||e!=e||n!=n||r!=r||i!=i?NaN:t===1/0||t===-(1/0)?t:(t-e)*(i-r)/(n-e)+r}},function(t,e,n){var r=n(8);r(r.S,"Math",{iaddh:function(t,e,n,r){var i=t>>>0,o=e>>>0,s=n>>>0;return o+(r>>>0)+((i&s|(i|s)&~(i+s>>>0))>>>31)|0}})},function(t,e,n){var r=n(8);r(r.S,"Math",{isubh:function(t,e,n,r){var i=t>>>0,o=e>>>0,s=n>>>0;return o-(r>>>0)-((~i&s|~(i^s)&i-s>>>0)>>>31)|0}})},function(t,e,n){var r=n(8);r(r.S,"Math",{imulh:function(t,e){var n=65535,r=+t,i=+e,o=r&n,s=i&n,a=r>>16,u=i>>16,c=(a*s>>>0)+(o*s>>>16);return a*u+(c>>16)+((o*u>>>0)+(c&n)>>16)}})},function(t,e,n){var r=n(8);r(r.S,"Math",{RAD_PER_DEG:180/Math.PI})},function(t,e,n){var r=n(8),i=Math.PI/180;r(r.S,"Math",{radians:function(t){return t*i}})},function(t,e,n){var r=n(8);r(r.S,"Math",{scale:n(297)})},function(t,e,n){var r=n(8);r(r.S,"Math",{umulh:function(t,e){var n=65535,r=+t,i=+e,o=r&n,s=i&n,a=r>>>16,u=i>>>16,c=(a*s>>>0)+(o*s>>>16);return a*u+(c>>>16)+((o*u>>>0)+(c&n)>>>16)}})},function(t,e,n){var r=n(8);r(r.S,"Math",{signbit:function(t){return(t=+t)!=t?t:0==t?1/t==1/0:t>0}})},function(t,e,n){"use strict";var r=n(8),i=n(9),o=n(4),s=n(208),a=n(213);r(r.P+r.R,"Promise",{finally:function(t){var e=s(this,i.Promise||o.Promise),n="function"==typeof t;return this.then(n?function(n){return a(e,t()).then(function(){return n})}:t,n?function(n){return a(e,t()).then(function(){throw n})}:t)}})},function(t,e,n){"use strict";var r=n(8),i=n(211),o=n(212);r(r.S,"Promise",{try:function(t){var e=i.f(this),n=o(t);return(n.e?e.reject:e.resolve)(n.v),e.promise}})},function(t,e,n){var r=n(309),i=n(12),o=r.key,s=r.set;r.exp({defineMetadata:function(t,e,n,r){s(t,e,i(n),o(r))}})},function(t,e,n){var r=n(215),i=n(8),o=n(23)("metadata"),s=o.store||(o.store=new(n(220))),a=function(t,e,n){var i=s.get(t);if(!i){if(!n)return;s.set(t,i=new r)}var o=i.get(e);if(!o){if(!n)return;i.set(e,o=new r)}return o},u=function(t,e,n){var r=a(e,n,!1);return void 0!==r&&r.has(t)},c=function(t,e,n){var r=a(e,n,!1);return void 0===r?void 0:r.get(t)},f=function(t,e,n,r){a(n,r,!0).set(t,e)},h=function(t,e){var n=a(t,e,!1),r=[];return n&&n.forEach(function(t,e){r.push(e)}),r},l=function(t){return void 0===t||"symbol"==typeof t?t:String(t)},p=function(t){i(i.S,"Reflect",t)};t.exports={store:s,map:a,has:u,get:c,set:f,keys:h,key:l,exp:p}},function(t,e,n){var r=n(309),i=n(12),o=r.key,s=r.map,a=r.store;r.exp({deleteMetadata:function(t,e){var n=arguments.length<3?void 0:o(arguments[2]),r=s(i(e),n,!1);if(void 0===r||!r.delete(t))return!1;if(r.size)return!0;var u=a.get(e);return u.delete(n),!!u.size||a.delete(e)}})},function(t,e,n){var r=n(309),i=n(12),o=n(58),s=r.has,a=r.get,u=r.key,c=function(t,e,n){var r=s(t,e,n);if(r)return a(t,e,n);var i=o(e);return null!==i?c(t,i,n):void 0};r.exp({getMetadata:function(t,e){return c(t,i(e),arguments.length<3?void 0:u(arguments[2]))}})},function(t,e,n){var r=n(219),i=n(278),o=n(309),s=n(12),a=n(58),u=o.keys,c=o.key,f=function(t,e){var n=u(t,e),o=a(t);if(null===o)return n;var s=f(o,e);return s.length?n.length?i(new r(n.concat(s))):s:n};o.exp({getMetadataKeys:function(t){return f(s(t),arguments.length<2?void 0:c(arguments[1]))}})},function(t,e,n){var r=n(309),i=n(12),o=r.get,s=r.key;r.exp({getOwnMetadata:function(t,e){return o(t,i(e),arguments.length<3?void 0:s(arguments[2]))}})},function(t,e,n){var r=n(309),i=n(12),o=r.keys,s=r.key;r.exp({getOwnMetadataKeys:function(t){return o(i(t),arguments.length<2?void 0:s(arguments[1]))}})},function(t,e,n){var r=n(309),i=n(12),o=n(58),s=r.has,a=r.key,u=function(t,e,n){var r=s(t,e,n);if(r)return!0;var i=o(e);return null!==i&&u(t,i,n)};r.exp({hasMetadata:function(t,e){return u(t,i(e),arguments.length<3?void 0:a(arguments[2]))}})},function(t,e,n){var r=n(309),i=n(12),o=r.has,s=r.key;r.exp({hasOwnMetadata:function(t,e){return o(t,i(e),arguments.length<3?void 0:s(arguments[2]))}})},function(t,e,n){var r=n(309),i=n(12),o=n(21),s=r.key,a=r.set;r.exp({metadata:function(t,e){return function(n,r){a(t,e,(void 0!==r?i:o)(n),s(r))}}})},function(t,e,n){var r=n(8),i=n(210)(),o=n(4).process,s="process"==n(34)(o);r(r.G,{asap:function(t){var e=s&&o.domain;i(e?e.bind(t):t)}})},function(t,e,n){"use strict";var r=n(8),i=n(4),o=n(9),s=n(210)(),a=n(25)("observable"),u=n(21),c=n(12),f=n(206),h=n(214),l=n(10),p=n(207),d=p.RETURN,g=function(t){return null==t?void 0:u(t)},v=function(t){var e=t._c;e&&(t._c=void 0,e())},y=function(t){return void 0===t._o},m=function(t){y(t)||(t._o=void 0,v(t))},S=function(t,e){c(t),this._c=void 0,this._o=t,t=new b(this);try{var n=e(t),r=n;null!=n&&("function"==typeof n.unsubscribe?n=function(){r.unsubscribe()}:u(n),this._c=n)}catch(e){return void t.error(e)}y(this)&&v(this)};S.prototype=h({},{unsubscribe:function(){m(this)}});var b=function(t){this._s=t};b.prototype=h({},{next:function(t){var e=this._s;if(!y(e)){var n=e._o;try{var r=g(n.next);if(r)return r.call(n,t)}catch(t){try{m(e)}finally{throw t}}}},error:function(t){var e=this._s;if(y(e))throw t;var n=e._o;e._o=void 0;try{var r=g(n.error);if(!r)throw t;t=r.call(n,t)}catch(t){try{v(e)}finally{throw t}}return v(e),t},complete:function(t){var e=this._s;if(!y(e)){var n=e._o;e._o=void 0;try{var r=g(n.complete);t=r?r.call(n,t):void 0}catch(t){try{v(e)}finally{throw t}}return v(e),t}}});var F=function(t){f(this,F,"Observable","_f")._f=u(t)};h(F.prototype,{subscribe:function(t){return new S(t,this._f)},forEach:function(t){var e=this;return new(o.Promise||i.Promise)(function(n,r){u(t);var i=e.subscribe({next:function(e){try{return t(e)}catch(t){r(t),i.unsubscribe()}},error:r,complete:n})})}}),h(F,{from:function(t){var e="function"==typeof this?this:F,n=g(c(t)[a]);if(n){var r=c(n.call(t));return r.constructor===e?r:new e(function(t){return r.subscribe(t)})}return new e(function(e){var n=!1;return s(function(){if(!n){try{if(p(t,!1,function(t){if(e.next(t),n)return d})===d)return}catch(t){if(n)throw t;return void e.error(t)}e.complete()}}),function(){n=!0}})},of:function(){for(var t=0,e=arguments.length,n=new Array(e);t<e;)n[t]=arguments[t++];return new("function"==typeof this?this:F)(function(t){var e=!1;return s(function(){if(!e){for(var r=0;r<n.length;++r)if(t.next(n[r]),e)return;t.complete()}}),function(){e=!0}})}}),l(F.prototype,a,function(){return this}),r(r.G,{Observable:F}),n(193)("Observable")},function(t,e,n){var r=n(4),i=n(8),o=n(260),s=[].slice,a=/MSIE .\./.test(o),u=function(t){return function(e,n){var r=arguments.length>2,i=!!r&&s.call(arguments,2);return t(r?function(){("function"==typeof e?e:Function(e)).apply(this,i)}:e,n)}};i(i.G+i.B+i.F*a,{setTimeout:u(r.setTimeout),setInterval:u(r.setInterval)})},function(t,e,n){var r=n(8),i=n(209);r(r.G+r.B,{setImmediate:i.set,clearImmediate:i.clear})},function(t,e,n){for(var r=n(194),i=n(30),o=n(18),s=n(4),a=n(10),u=n(129),c=n(25),f=c("iterator"),h=c("toStringTag"),l=u.Array,p={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},d=i(p),g=0;g<d.length;g++){var v,y=d[g],m=p[y],S=s[y],b=S&&S.prototype;if(b&&(b[f]||a(b,f,l),b[h]||a(b,h,y),u[y]=l,m))for(v in r)b[v]||o(b,v,r[v],!0)}},function(t,e){(function(e){!function(e){"use strict";function n(t,e,n,r){var o=e&&e.prototype instanceof i?e:i,s=Object.create(o.prototype),a=new p(r||[]);return s._invoke=c(t,n,a),s}function r(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function i(){}function o(){}function s(){}function a(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function u(t){function n(e,i,o,s){var a=r(t[e],t,i);if("throw"!==a.type){var u=a.arg,c=u.value;return c&&"object"==typeof c&&m.call(c,"__await")?Promise.resolve(c.__await).then(function(t){n("next",t,o,s)},function(t){n("throw",t,o,s)}):Promise.resolve(c).then(function(t){u.value=t,o(u)},s)}s(a.arg)}function i(t,e){function r(){return new Promise(function(r,i){n(t,e,r,i)})}return o=o?o.then(r,r):r()}"object"==typeof e.process&&e.process.domain&&(n=e.process.domain.bind(n));var o;this._invoke=i}function c(t,e,n){var i=E;return function(o,s){if(i===P)throw new Error("Generator is already running");if(i===C){if("throw"===o)throw s;return g()}for(n.method=o,n.arg=s;;){var a=n.delegate;if(a){var u=f(a,n);if(u){if(u===k)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===E)throw i=C,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=P;var c=r(t,e,n);if("normal"===c.type){if(i=n.done?C:A,c.arg===k)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(i=C,n.method="throw",n.arg=c.arg)}}}function f(t,e){var n=t.iterator[e.method];if(n===v){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=v,f(t,e),"throw"===e.method))return k;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return k}var i=r(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,k;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=v),e.delegate=null,k):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,k)}function h(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function l(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function p(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(h,this),this.reset(!0)}function d(t){if(t){var e=t[b];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n<t.length;)if(m.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=v,e.done=!0,e};return r.next=r}}return{next:g}}function g(){return{value:v,done:!0}}var v,y=Object.prototype,m=y.hasOwnProperty,S="function"==typeof Symbol?Symbol:{},b=S.iterator||"@@iterator",F=S.asyncIterator||"@@asyncIterator",w=S.toStringTag||"@@toStringTag",_="object"==typeof t,x=e.regeneratorRuntime;if(x)return void(_&&(t.exports=x));x=e.regeneratorRuntime=_?t.exports:{},x.wrap=n;var E="suspendedStart",A="suspendedYield",P="executing",C="completed",k={},T={};T[b]=function(){return this};var R=Object.getPrototypeOf,I=R&&R(R(d([])));I&&I!==y&&m.call(I,b)&&(T=I);var D=s.prototype=i.prototype=Object.create(T);o.prototype=D.constructor=s,s.constructor=o,s[w]=o.displayName="GeneratorFunction",x.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===o||"GeneratorFunction"===(e.displayName||e.name))},x.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,s):(t.__proto__=s,w in t||(t[w]="GeneratorFunction")),t.prototype=Object.create(D),t},x.awrap=function(t){return{__await:t}},a(u.prototype),u.prototype[F]=function(){return this},x.AsyncIterator=u,x.async=function(t,e,r,i){var o=new u(n(t,e,r,i));return x.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},a(D),D[w]="Generator",D[b]=function(){return this},D.toString=function(){return"[object Generator]"},x.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},x.values=d,p.prototype={constructor:p,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=v,this.done=!1,this.delegate=null,this.method="next",this.arg=v,this.tryEntries.forEach(l),!t)for(var e in this)"t"===e.charAt(0)&&m.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=v)},stop:function(){this.done=!0;var t=this.tryEntries[0],e=t.completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(t){function e(e,r){return o.type="throw",o.arg=t,n.next=e,r&&(n.method="next",n.arg=v),!!r}if(this.done)throw t;for(var n=this,r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return e("end");if(i.tryLoc<=this.prev){var s=m.call(i,"catchLoc"),a=m.call(i,"finallyLoc");if(s&&a){if(this.prev<i.catchLoc)return e(i.catchLoc,!0);if(this.prev<i.finallyLoc)return e(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return e(i.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return e(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&m.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=t,o.arg=e,i?(this.method="next",this.next=i.finallyLoc,k):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),k},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),l(n),k}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;l(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:d(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=v),k}}}("object"==typeof e?e:"object"==typeof window?window:"object"==typeof self?self:this)}).call(e,function(){return this}())},function(t,e,n){n(325),t.exports=n(9).RegExp.escape},function(t,e,n){var r=n(8),i=n(326)(/[\\^$*+?.()|[\]{}]/g,"\\$&");r(r.S,"RegExp",{escape:function(t){return i(t)}})},function(t,e){t.exports=function(t,e){var n=e===Object(e)?function(t){return e[t]}:e;return function(e){return String(e).replace(t,n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(328);Object.defineProperty(e,"Log",{enumerable:!0,get:function(){return r.Log}});var i=n(329);Object.defineProperty(e,"OidcClient",{enumerable:!0,get:function(){return i.OidcClient}});var o=n(330);Object.defineProperty(e,"OidcClientSettings",{enumerable:!0,get:function(){return o.OidcClientSettings}});var s=n(331);Object.defineProperty(e,"WebStorageStateStore",{enumerable:!0,get:function(){return s.WebStorageStateStore}});var a=n(349);Object.defineProperty(e,"InMemoryWebStorage",{enumerable:!0,get:function(){return a.InMemoryWebStorage}});var u=n(350);Object.defineProperty(e,"UserManager",{enumerable:!0,get:function(){return u.UserManager}});var c=n(359);Object.defineProperty(e,"AccessTokenEvents",{enumerable:!0,get:function(){return c.AccessTokenEvents}});var f=n(334);Object.defineProperty(e,"MetadataService",{enumerable:!0,get:function(){return f.MetadataService}});var h=n(366);Object.defineProperty(e,"CordovaPopupNavigator",{enumerable:!0,get:function(){return h.CordovaPopupNavigator}});var l=n(368);Object.defineProperty(e,"CordovaIFrameNavigator",{enumerable:!0,get:function(){return l.CordovaIFrameNavigator}});var p=n(364);Object.defineProperty(e,"CheckSessionIFrame",{enumerable:!0,get:function(){return p.CheckSessionIFrame}});var d=n(365);Object.defineProperty(e,"TokenRevocationClient",{enumerable:!0,get:function(){return d.TokenRevocationClient}});var g=n(363);Object.defineProperty(e,"SessionMonitor",{enumerable:!0,get:function(){return g.SessionMonitor}});var v=n(332);Object.defineProperty(e,"Global",{enumerable:!0,get:function(){return v.Global}});var y=n(357);Object.defineProperty(e,"User",{enumerable:!0,get:function(){return y.User}})},function(t,e){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i={debug:function(){},info:function(){},warn:function(){},error:function(){}},o=0,s=1,a=2,u=3,c=4,f=void 0,h=void 0,l=e.Log=function(){function t(){n(this,t)}return t.reset=function(){h=u,f=i},t.debug=function(){if(h>=c){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];f.debug.apply(f,Array.from(e))}},t.info=function(){if(h>=u){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];f.info.apply(f,Array.from(e))}},t.warn=function(){if(h>=a){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];f.warn.apply(f,Array.from(e))}},t.error=function(){if(h>=s){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];f.error.apply(f,Array.from(e))}},r(t,null,[{key:"NONE",get:function(){return o}},{key:"ERROR",get:function(){return s}},{key:"WARN",get:function(){return a}},{key:"INFO",get:function(){return u}},{key:"DEBUG",get:function(){return c}},{key:"level",get:function(){return h},set:function(t){if(!(o<=t&&t<=c))throw new Error("Invalid log level");h=t}},{key:"logger",get:function(){return f},set:function(t){if(!t.debug&&t.info&&(t.debug=t.info),!(t.debug&&t.info&&t.warn&&t.error))throw new Error("Invalid logger");f=t}}]),t}();l.reset()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.OidcClient=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s=n(330),a=n(337),u=n(341),c=n(346),f=n(347),h=n(348),l=n(343),p=n(344);e.OidcClient=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};r(this,t),e instanceof s.OidcClientSettings?this._settings=e:this._settings=new s.OidcClientSettings(e)}return t.prototype.createSigninRequest=function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.response_type,r=e.scope,i=e.redirect_uri,s=e.data,a=e.state,c=e.prompt,f=e.display,h=e.max_age,l=e.ui_locales,p=e.id_token_hint,d=e.login_hint,g=e.acr_values,v=e.resource,y=e.request,m=e.request_uri,S=e.extraQueryParams,b=arguments[1];o.Log.debug("OidcClient.createSigninRequest");var F=this._settings.client_id;n=n||this._settings.response_type,r=r||this._settings.scope,i=i||this._settings.redirect_uri,c=c||this._settings.prompt,f=f||this._settings.display,h=h||this._settings.max_age,l=l||this._settings.ui_locales,g=g||this._settings.acr_values,v=v||this._settings.resource,S=S||this._settings.extraQueryParams;var w=this._settings.authority;return this._metadataService.getAuthorizationEndpoint().then(function(e){o.Log.debug("OidcClient.createSigninRequest: Received authorization endpoint",e);var _=new u.SigninRequest({url:e,client_id:F,redirect_uri:i,response_type:n,scope:r,data:s||a,authority:w,prompt:c,display:f,max_age:h,ui_locales:l,id_token_hint:p,login_hint:d,acr_values:g,resource:v,request:y,request_uri:m,extraQueryParams:S}),x=_.state;return b=b||t._stateStore,b.set(x.id,x.toStorageString()).then(function(){return _})})},t.prototype.processSigninResponse=function(t,e){var n=this;o.Log.debug("OidcClient.processSigninResponse");var r=new c.SigninResponse(t);return r.state?(e=e||this._stateStore,e.remove(r.state).then(function(t){if(!t)throw o.Log.error("OidcClient.processSigninResponse: No matching state found in storage"),new Error("No matching state found in storage");var e=l.SigninState.fromStorageString(t);return o.Log.debug("OidcClient.processSigninResponse: Received state from storage; validating response"),n._validator.validateSigninResponse(e,r)})):(o.Log.error("OidcClient.processSigninResponse: No state in response"),Promise.reject(new Error("No state in response")))},t.prototype.createSignoutRequest=function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.id_token_hint,r=e.data,i=e.state,s=e.post_logout_redirect_uri,a=arguments[1];return o.Log.debug("OidcClient.createSignoutRequest"),s=s||this._settings.post_logout_redirect_uri,this._metadataService.getEndSessionEndpoint().then(function(e){ if(!e)throw o.Log.error("OidcClient.createSignoutRequest: No end session endpoint url returned"),new Error("no end session endpoint");o.Log.debug("OidcClient.createSignoutRequest: Received end session endpoint",e);var u=new f.SignoutRequest({url:e,id_token_hint:n,post_logout_redirect_uri:s,data:r||i}),c=u.state;return c&&(o.Log.debug("OidcClient.createSignoutRequest: Signout request has state to persist"),a=a||t._stateStore,a.set(c.id,c.toStorageString())),u})},t.prototype.processSignoutResponse=function(t,e){var n=this;o.Log.debug("OidcClient.processSignoutResponse");var r=new h.SignoutResponse(t);if(!r.state)return o.Log.debug("OidcClient.processSignoutResponse: No state in response"),r.error?(o.Log.warn("OidcClient.processSignoutResponse: Response was error: ",r.error),Promise.reject(new a.ErrorResponse(r))):Promise.resolve(r);var i=r.state;return e=e||this._stateStore,e.remove(i).then(function(t){if(!t)throw o.Log.error("OidcClient.processSignoutResponse: No matching state found in storage"),new Error("No matching state found in storage");var e=p.State.fromStorageString(t);return o.Log.debug("OidcClient.processSignoutResponse: Received state from storage; validating response"),n._validator.validateSignoutResponse(e,r)})},t.prototype.clearStaleState=function(t){return o.Log.debug("OidcClient.clearStaleState"),t=t||this._stateStore,p.State.clearStaleState(t,this.settings.staleStateAge)},i(t,[{key:"_stateStore",get:function(){return this.settings.stateStore}},{key:"_validator",get:function(){return this.settings.validator}},{key:"_metadataService",get:function(){return this.settings.metadataService}},{key:"settings",get:function(){return this._settings}},{key:"metadataService",get:function(){return this._metadataService}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.OidcClientSettings=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=n(328),a=n(331),u=n(333),c=n(334),f=".well-known/openid-configuration",h="id_token",l="openid",p=300,d=300;e.OidcClientSettings=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.authority,o=e.metadataUrl,s=e.metadata,f=e.signingKeys,g=e.client_id,v=e.client_secret,y=e.response_type,m=void 0===y?h:y,S=e.scope,b=void 0===S?l:S,F=e.redirect_uri,w=e.post_logout_redirect_uri,_=e.prompt,x=e.display,E=e.max_age,A=e.ui_locales,P=e.acr_values,C=e.resource,k=e.filterProtocolClaims,T=void 0===k||k,R=e.loadUserInfo,I=void 0===R||R,D=e.staleStateAge,N=void 0===D?p:D,O=e.clockSkew,j=void 0===O?d:O,L=e.stateStore,M=void 0===L?new a.WebStorageStateStore:L,B=e.ResponseValidatorCtor,H=void 0===B?u.ResponseValidator:B,U=e.MetadataServiceCtor,V=void 0===U?c.MetadataService:U,K=e.extraQueryParams,q=void 0===K?{}:K;r(this,t),this._authority=n,this._metadataUrl=o,this._metadata=s,this._signingKeys=f,this._client_id=g,this._client_secret=v,this._response_type=m,this._scope=b,this._redirect_uri=F,this._post_logout_redirect_uri=w,this._prompt=_,this._display=x,this._max_age=E,this._ui_locales=A,this._acr_values=P,this._resource=C,this._filterProtocolClaims=!!T,this._loadUserInfo=!!I,this._staleStateAge=N,this._clockSkew=j,this._stateStore=M,this._validator=new H(this),this._metadataService=new V(this),this._extraQueryParams="object"===("undefined"==typeof q?"undefined":i(q))?q:{}}return o(t,[{key:"client_id",get:function(){return this._client_id},set:function(t){if(this._client_id)throw s.Log.error("OidcClientSettings.set_client_id: client_id has already been assigned."),new Error("client_id has already been assigned.");this._client_id=t}},{key:"client_secret",get:function(){return this._client_secret}},{key:"response_type",get:function(){return this._response_type}},{key:"scope",get:function(){return this._scope}},{key:"redirect_uri",get:function(){return this._redirect_uri}},{key:"post_logout_redirect_uri",get:function(){return this._post_logout_redirect_uri}},{key:"prompt",get:function(){return this._prompt}},{key:"display",get:function(){return this._display}},{key:"max_age",get:function(){return this._max_age}},{key:"ui_locales",get:function(){return this._ui_locales}},{key:"acr_values",get:function(){return this._acr_values}},{key:"resource",get:function(){return this._resource}},{key:"authority",get:function(){return this._authority},set:function(t){if(this._authority)throw s.Log.error("OidcClientSettings.set_authority: authority has already been assigned."),new Error("authority has already been assigned.");this._authority=t}},{key:"metadataUrl",get:function(){return this._metadataUrl||(this._metadataUrl=this.authority,this._metadataUrl&&this._metadataUrl.indexOf(f)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=f)),this._metadataUrl}},{key:"metadata",get:function(){return this._metadata},set:function(t){this._metadata=t}},{key:"signingKeys",get:function(){return this._signingKeys},set:function(t){this._signingKeys=t}},{key:"filterProtocolClaims",get:function(){return this._filterProtocolClaims}},{key:"loadUserInfo",get:function(){return this._loadUserInfo}},{key:"staleStateAge",get:function(){return this._staleStateAge}},{key:"clockSkew",get:function(){return this._clockSkew}},{key:"stateStore",get:function(){return this._stateStore}},{key:"validator",get:function(){return this._validator}},{key:"metadataService",get:function(){return this._metadataService}},{key:"extraQueryParams",get:function(){return this._extraQueryParams},set:function(t){"object"===("undefined"==typeof t?"undefined":i(t))?this._extraQueryParams=t:this._extraQueryParams={}}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.WebStorageStateStore=void 0;var i=n(328),o=n(332);e.WebStorageStateStore=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.prefix,i=void 0===n?"oidc.":n,s=e.store,a=void 0===s?o.Global.localStorage:s;r(this,t),this._store=a,this._prefix=i}return t.prototype.set=function(t,e){return i.Log.debug("WebStorageStateStore.set",t),t=this._prefix+t,this._store.setItem(t,e),Promise.resolve()},t.prototype.get=function(t){i.Log.debug("WebStorageStateStore.get",t),t=this._prefix+t;var e=this._store.getItem(t);return Promise.resolve(e)},t.prototype.remove=function(t){i.Log.debug("WebStorageStateStore.remove",t),t=this._prefix+t;var e=this._store.getItem(t);return this._store.removeItem(t),Promise.resolve(e)},t.prototype.getAllKeys=function(){i.Log.debug("WebStorageStateStore.getAllKeys");for(var t=[],e=0;e<this._store.length;e++){var n=this._store.key(e);0===n.indexOf(this._prefix)&&t.push(n.substr(this._prefix.length))}return Promise.resolve(t)},t}()},function(t,e){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i={setInterval:function(t){function e(e,n){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t,e){return setInterval(t,e)}),clearInterval:function(t){function e(e){return t.apply(this,arguments)}return e.toString=function(){return t.toString()},e}(function(t){return clearInterval(t)})},o=!1,s=null;e.Global=function(){function t(){n(this,t)}return t._testing=function(){o=!0},t.setXMLHttpRequest=function(t){s=t},r(t,null,[{key:"location",get:function(){if(!o)return location}},{key:"localStorage",get:function(){if(!o&&"undefined"!=typeof window)return localStorage}},{key:"sessionStorage",get:function(){if(!o&&"undefined"!=typeof window)return sessionStorage}},{key:"XMLHttpRequest",get:function(){if(!o&&"undefined"!=typeof window)return s||XMLHttpRequest}},{key:"timer",get:function(){if(!o)return i}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.ResponseValidator=void 0;var i=n(328),o=n(334),s=n(336),a=n(337),u=n(338),c=["nonce","at_hash","iat","nbf","exp","aud","iss","c_hash"];e.ResponseValidator=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o.MetadataService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:s.UserInfoService,c=arguments.length>3&&void 0!==arguments[3]?arguments[3]:u.JoseUtil;if(r(this,t),!e)throw i.Log.error("ResponseValidator.ctor: No settings passed to ResponseValidator"),new Error("settings");this._settings=e,this._metadataService=new n(this._settings),this._userInfoService=new a(this._settings),this._joseUtil=c}return t.prototype.validateSigninResponse=function(t,e){var n=this;return i.Log.debug("ResponseValidator.validateSigninResponse"),this._processSigninParams(t,e).then(function(e){return i.Log.debug("ResponseValidator.validateSigninResponse: state processed"),n._validateTokens(t,e).then(function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: tokens validated"),n._processClaims(t).then(function(t){return i.Log.debug("ResponseValidator.validateSigninResponse: claims processed"),t})})})},t.prototype.validateSignoutResponse=function(t,e){return t.id!==e.state?(i.Log.error("ResponseValidator.validateSignoutResponse: State does not match"),Promise.reject(new Error("State does not match"))):(i.Log.debug("ResponseValidator.validateSignoutResponse: state validated"),e.state=t.data,e.error?(i.Log.warn("ResponseValidator.validateSignoutResponse: Response was error",e.error),Promise.reject(new a.ErrorResponse(e))):Promise.resolve(e))},t.prototype._processSigninParams=function(t,e){if(t.id!==e.state)return i.Log.error("ResponseValidator._processSigninParams: State does not match"),Promise.reject(new Error("State does not match"));if(!t.client_id)return i.Log.error("ResponseValidator._processSigninParams: No client_id on state"),Promise.reject(new Error("No client_id on state"));if(!t.authority)return i.Log.error("ResponseValidator._processSigninParams: No authority on state"),Promise.reject(new Error("No authority on state"));if(this._settings.authority){if(this._settings.authority&&this._settings.authority!==t.authority)return i.Log.error("ResponseValidator._processSigninParams: authority mismatch on settings vs. signin state"),Promise.reject(new Error("authority mismatch on settings vs. signin state"))}else this._settings.authority=t.authority;if(this._settings.client_id){if(this._settings.client_id&&this._settings.client_id!==t.client_id)return i.Log.error("ResponseValidator._processSigninParams: client_id mismatch on settings vs. signin state"),Promise.reject(new Error("client_id mismatch on settings vs. signin state"))}else this._settings.client_id=t.client_id;return i.Log.debug("ResponseValidator._processSigninParams: state validated"),e.state=t.data,e.error?(i.Log.warn("ResponseValidator._processSigninParams: Response was error",e.error),Promise.reject(new a.ErrorResponse(e))):t.nonce&&!e.id_token?(i.Log.error("ResponseValidator._processSigninParams: Expecting id_token in response"),Promise.reject(new Error("No id_token in response"))):!t.nonce&&e.id_token?(i.Log.error("ResponseValidator._processSigninParams: Not expecting id_token in response"),Promise.reject(new Error("Unexpected id_token in response"))):Promise.resolve(e)},t.prototype._processClaims=function(t){var e=this;if(t.isOpenIdConnect){if(i.Log.debug("ResponseValidator._processClaims: response is OIDC, processing claims"),t.profile=this._filterProtocolClaims(t.profile),this._settings.loadUserInfo&&t.access_token)return i.Log.debug("ResponseValidator._processClaims: loading user info"),this._userInfoService.getClaims(t.access_token).then(function(n){return i.Log.debug("ResponseValidator._processClaims: user info claims received from user info endpoint"),n.sub!==t.profile.sub?(i.Log.error("ResponseValidator._processClaims: sub from user info endpoint does not match sub in access_token"),Promise.reject(new Error("sub from user info endpoint does not match sub in access_token"))):(t.profile=e._mergeClaims(t.profile,n),i.Log.debug("ResponseValidator._processClaims: user info claims received, updated profile:",t.profile),t)});i.Log.debug("ResponseValidator._processClaims: not loading user info")}else i.Log.debug("ResponseValidator._processClaims: response is not OIDC, not processing claims");return Promise.resolve(t)},t.prototype._mergeClaims=function(t,e){var n=Object.assign({},t);for(var r in e){var i=e[r];Array.isArray(i)||(i=[i]);for(var o=0;o<i.length;o++){var s=i[o];n[r]?Array.isArray(n[r])?n[r].indexOf(s)<0&&n[r].push(s):n[r]!==s&&(n[r]=[n[r],s]):n[r]=s}}return n},t.prototype._filterProtocolClaims=function(t){i.Log.debug("ResponseValidator._filterProtocolClaims, incoming claims:",t);var e=Object.assign({},t);return this._settings._filterProtocolClaims?(c.forEach(function(t){delete e[t]}),i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims filtered",e)):i.Log.debug("ResponseValidator._filterProtocolClaims: protocol claims not filtered"),e},t.prototype._validateTokens=function(t,e){return e.id_token?e.access_token?(i.Log.debug("ResponseValidator._validateTokens: Validating id_token and access_token"),this._validateIdTokenAndAccessToken(t,e)):(i.Log.debug("ResponseValidator._validateTokens: Validating id_token"),this._validateIdToken(t,e)):(i.Log.debug("ResponseValidator._validateTokens: No id_token to validate"),Promise.resolve(e))},t.prototype._validateIdTokenAndAccessToken=function(t,e){var n=this;return this._validateIdToken(t,e).then(function(t){return n._validateAccessToken(t)})},t.prototype._validateIdToken=function(t,e){var n=this;if(!t.nonce)return i.Log.error("ResponseValidator._validateIdToken: No nonce on state"),Promise.reject(new Error("No nonce on state"));var r=this._joseUtil.parseJwt(e.id_token);if(!r||!r.header||!r.payload)return i.Log.error("ResponseValidator._validateIdToken: Failed to parse id_token",r),Promise.reject(new Error("Failed to parse id_token"));if(t.nonce!==r.payload.nonce)return i.Log.error("ResponseValidator._validateIdToken: Invalid nonce in id_token"),Promise.reject(new Error("Invalid nonce in id_token"));var o=r.header.kid;return this._metadataService.getIssuer().then(function(s){return i.Log.debug("ResponseValidator._validateIdToken: Received issuer"),n._metadataService.getSigningKeys().then(function(a){if(!a)return i.Log.error("ResponseValidator._validateIdToken: No signing keys from metadata"),Promise.reject(new Error("No signing keys from metadata"));i.Log.debug("ResponseValidator._validateIdToken: Received signing keys");var u=void 0;if(o)u=a.filter(function(t){return t.kid===o})[0];else{if(a=n._filterByAlg(a,r.header.alg),a.length>1)return i.Log.error("ResponseValidator._validateIdToken: No kid found in id_token and more than one key found in metadata"),Promise.reject(new Error("No kid found in id_token and more than one key found in metadata"));u=a[0]}if(!u)return i.Log.error("ResponseValidator._validateIdToken: No key matching kid or alg found in signing keys"),Promise.reject(new Error("No key matching kid or alg found in signing keys"));var c=t.client_id,f=n._settings.clockSkew;return i.Log.debug("ResponseValidator._validateIdToken: Validaing JWT; using clock skew (in seconds) of: ",f),n._joseUtil.validateJwt(e.id_token,u,s,c,f).then(function(){return i.Log.debug("ResponseValidator._validateIdToken: JWT validation successful"),r.payload.sub?(e.profile=r.payload,e):(i.Log.error("ResponseValidator._validateIdToken: No sub present in id_token"),Promise.reject(new Error("No sub present in id_token")))})})})},t.prototype._filterByAlg=function(t,e){var n=null;if(e.startsWith("RS"))n="RSA";else if(e.startsWith("PS"))n="PS";else{if(!e.startsWith("ES"))return i.Log.debug("ResponseValidator._filterByAlg: alg not supported: ",e),[];n="EC"}return i.Log.debug("ResponseValidator._filterByAlg: Looking for keys that match kty: ",n),t=t.filter(function(t){return t.kty===n}),i.Log.debug("ResponseValidator._filterByAlg: Number of keys that match kty: ",n,t.length),t},t.prototype._validateAccessToken=function(t){if(!t.profile)return i.Log.error("ResponseValidator._validateAccessToken: No profile loaded from id_token"),Promise.reject(new Error("No profile loaded from id_token"));if(!t.profile.at_hash)return i.Log.error("ResponseValidator._validateAccessToken: No at_hash in id_token"),Promise.reject(new Error("No at_hash in id_token"));if(!t.id_token)return i.Log.error("ResponseValidator._validateAccessToken: No id_token"),Promise.reject(new Error("No id_token"));var e=this._joseUtil.parseJwt(t.id_token);if(!e||!e.header)return i.Log.error("ResponseValidator._validateAccessToken: Failed to parse id_token",e),Promise.reject(new Error("Failed to parse id_token"));var n=e.header.alg;if(!n||5!==n.length)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",n),Promise.reject(new Error("Unsupported alg: "+n));var r=n.substr(2,3);if(!r)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",n,r),Promise.reject(new Error("Unsupported alg: "+n));if(r=parseInt(r),256!==r&&384!==r&&512!==r)return i.Log.error("ResponseValidator._validateAccessToken: Unsupported alg:",n,r),Promise.reject(new Error("Unsupported alg: "+n));var o="sha"+r,s=this._joseUtil.hashString(t.access_token,o);if(!s)return i.Log.error("ResponseValidator._validateAccessToken: access_token hash failed:",o),Promise.reject(new Error("Failed to validate at_hash"));var a=s.substr(0,s.length/2),u=this._joseUtil.hexToBase64Url(a);return u!==t.profile.at_hash?(i.Log.error("ResponseValidator._validateAccessToken: Failed to validate at_hash",u,t.profile.at_hash),Promise.reject(new Error("Failed to validate at_hash"))):(i.Log.debug("ResponseValidator._validateAccessToken: success"),Promise.resolve(t))},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.MetadataService=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s=n(335),a=".well-known/openid-configuration";e.MetadataService=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.JsonService;if(r(this,t),!e)throw o.Log.error("MetadataService: No settings passed to MetadataService"),new Error("settings");this._settings=e,this._jsonService=new n}return t.prototype.getMetadata=function(){var t=this;return this._settings.metadata?(o.Log.debug("MetadataService.getMetadata: Returning metadata from settings"),Promise.resolve(this._settings.metadata)):this.metadataUrl?(o.Log.debug("MetadataService.getMetadata: getting metadata from",this.metadataUrl),this._jsonService.getJson(this.metadataUrl).then(function(e){return o.Log.debug("MetadataService.getMetadata: json received"),t._settings.metadata=e,e})):(o.Log.error("MetadataService.getMetadata: No authority or metadataUrl configured on settings"),Promise.reject(new Error("No authority or metadataUrl configured on settings")))},t.prototype.getIssuer=function(){return this._getMetadataProperty("issuer")},t.prototype.getAuthorizationEndpoint=function(){return this._getMetadataProperty("authorization_endpoint")},t.prototype.getUserInfoEndpoint=function(){return this._getMetadataProperty("userinfo_endpoint")},t.prototype.getTokenEndpoint=function(){return this._getMetadataProperty("token_endpoint",!0)},t.prototype.getCheckSessionIframe=function(){return this._getMetadataProperty("check_session_iframe",!0)},t.prototype.getEndSessionEndpoint=function(){return this._getMetadataProperty("end_session_endpoint",!0)},t.prototype.getRevocationEndpoint=function(){return this._getMetadataProperty("revocation_endpoint",!0)},t.prototype._getMetadataProperty=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return o.Log.debug("MetadataService.getMetadataProperty for: "+t),this.getMetadata().then(function(n){if(o.Log.debug("MetadataService.getMetadataProperty: metadata recieved"),void 0===n[t]){if(e===!0)return void o.Log.warn("MetadataService.getMetadataProperty: Metadata does not contain optional property "+t);throw o.Log.error("MetadataService.getMetadataProperty: Metadata does not contain property "+t),new Error("Metadata does not contain property "+t)}return n[t]})},t.prototype.getSigningKeys=function(){var t=this;return this._settings.signingKeys?(o.Log.debug("MetadataService.getSigningKeys: Returning signingKeys from settings"),Promise.resolve(this._settings.signingKeys)):this._getMetadataProperty("jwks_uri").then(function(e){return o.Log.debug("MetadataService.getSigningKeys: jwks_uri received",e),t._jsonService.getJson(e).then(function(e){if(o.Log.debug("MetadataService.getSigningKeys: key set received",e),!e.keys)throw o.Log.error("MetadataService.getSigningKeys: Missing keys on keyset"),new Error("Missing keys on keyset");return t._settings.signingKeys=e.keys,t._settings.signingKeys})})},i(t,[{key:"metadataUrl",get:function(){return this._metadataUrl||(this._settings.metadataUrl?this._metadataUrl=this._settings.metadataUrl:(this._metadataUrl=this._settings.authority,this._metadataUrl&&this._metadataUrl.indexOf(a)<0&&("/"!==this._metadataUrl[this._metadataUrl.length-1]&&(this._metadataUrl+="/"),this._metadataUrl+=a))),this._metadataUrl}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.JsonService=void 0;var i=n(328),o=n(332);e.JsonService=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:o.Global.XMLHttpRequest;r(this,t),this._XMLHttpRequest=e}return t.prototype.getJson=function(t,e){var n=this;if(!t)throw i.Log.error("JsonService.getJson: No url passed"),new Error("url");return i.Log.debug("JsonService.getJson, url: ",t),new Promise(function(r,o){var s=new n._XMLHttpRequest;s.open("GET",t),s.onload=function(){if(i.Log.debug("JsonService.getJson: HTTP response received, status",s.status),200===s.status){var e=s.getResponseHeader("Content-Type");if(e&&e.startsWith("application/json"))try{r(JSON.parse(s.responseText))}catch(t){i.Log.error("JsonService.getJson: Error parsing JSON response",t.message),o(t)}else o(Error("Invalid response Content-Type: "+e+", from URL: "+t))}else o(Error(s.statusText+" ("+s.status+")"))},s.onerror=function(){i.Log.error("JsonService.getJson: network error"),o(Error("Network Error"))},e&&(i.Log.debug("JsonService.getJson: token passed, setting Authorization header"),s.setRequestHeader("Authorization","Bearer "+e)),s.send()})},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.UserInfoService=void 0;var i=n(335),o=n(334),s=n(328);e.UserInfoService=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:i.JsonService,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o.MetadataService;if(r(this,t),!e)throw s.Log.error("UserInfoService.ctor: No settings passed"),new Error("settings");this._settings=e,this._jsonService=new n,this._metadataService=new a(this._settings)}return t.prototype.getClaims=function(t){var e=this;return t?this._metadataService.getUserInfoEndpoint().then(function(n){return s.Log.debug("UserInfoService.getClaims: received userinfo url",n),e._jsonService.getJson(n,t).then(function(t){return s.Log.debug("UserInfoService.getClaims: claims received",t),t})}):(s.Log.error("UserInfoService.getClaims: No token passed"),Promise.reject(new Error("A token is required")))},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorResponse=void 0;var s=n(328);e.ErrorResponse=function(t){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=n.error,a=n.error_description,u=n.error_uri,c=n.state;if(r(this,e),!o)throw s.Log.error("No error passed to ErrorResponse"),new Error("error");var f=i(this,t.call(this,a||o));return f.name="ErrorResponse",f.error=o,f.error_description=a,f.error_uri=u,f.state=c,f}return o(e,t),e}(Error)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.JoseUtil=void 0;var i=n(339),o=n(328),s=["RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];e.JoseUtil=function(){function t(){r(this,t)}return t.parseJwt=function(t){o.Log.debug("JoseUtil.parseJwt");try{var e=i.jws.JWS.parse(t);return{header:e.headerObj,payload:e.payloadObj}}catch(t){o.Log.error(t)}},t.validateJwt=function(e,n,r,s,a,u){o.Log.debug("JoseUtil.validateJwt");try{if("RSA"===n.kty)if(n.e&&n.n)n=i.KEYUTIL.getKey(n);else{if(!n.x5c||!n.x5c.length)return o.Log.error("JoseUtil.validateJwt: RSA key missing key material",n),Promise.reject(new Error("RSA key missing key material"));var c=(0,i.b64tohex)(n.x5c[0]);n=i.X509.getPublicKeyFromCertHex(c)}else{if("EC"!==n.kty)return o.Log.error("JoseUtil.validateJwt: Unsupported key type",n&&n.kty),Promise.reject(new Error("Unsupported key type: "+n&&n.kty));if(!(n.crv&&n.x&&n.y))return o.Log.error("JoseUtil.validateJwt: EC key missing key material",n),Promise.reject(new Error("EC key missing key material"));n=i.KEYUTIL.getKey(n)}return t._validateJwt(e,n,r,s,a,u)}catch(t){return o.Log.error(t&&t.message||t),Promise.reject("JWT validation failed")}},t._validateJwt=function(e,n,r,a,u,c){u||(u=0),c||(c=parseInt(Date.now()/1e3));var f=t.parseJwt(e).payload;if(!f.iss)return o.Log.error("JoseUtil._validateJwt: issuer was not provided"),Promise.reject(new Error("issuer was not provided"));if(f.iss!==r)return o.Log.error("JoseUtil._validateJwt: Invalid issuer in token",f.iss),Promise.reject(new Error("Invalid issuer in token: "+f.iss));if(!f.aud)return o.Log.error("JoseUtil._validateJwt: aud was not provided"),Promise.reject(new Error("aud was not provided"));var h=f.aud===a||Array.isArray(f.aud)&&f.aud.indexOf(a)>=0;if(!h)return o.Log.error("JoseUtil._validateJwt: Invalid audience in token",f.aud),Promise.reject(new Error("Invalid audience in token: "+f.aud));var l=c+u,p=c-u;if(!f.iat)return o.Log.error("JoseUtil._validateJwt: iat was not provided"),Promise.reject(new Error("iat was not provided"));if(l<f.iat)return o.Log.error("JoseUtil._validateJwt: iat is in the future",f.iat),Promise.reject(new Error("iat is in the future: "+f.iat));if(f.nbf&&l<f.nbf)return o.Log.error("JoseUtil._validateJwt: nbf is in the future",f.nbf),Promise.reject(new Error("nbf is in the future: "+f.nbf));if(!f.exp)return o.Log.error("JoseUtil._validateJwt: exp was not provided"),Promise.reject(new Error("exp was not provided"));if(f.exp<p)return o.Log.error("JoseUtil._validateJwt: exp is in the past",f.exp),Promise.reject(new Error("exp is in the past:"+f.exp));try{if(!i.jws.JWS.verify(e,n,s))return o.Log.error("JoseUtil._validateJwt: signature validation failed"),Promise.reject(new Error("signature validation failed"))}catch(t){return o.Log.error(t&&t.message||t),Promise.reject(new Error("signature validation failed"))}return Promise.resolve()},t.hashString=function(t,e){try{return i.crypto.Util.hashString(t,e)}catch(t){o.Log.error(t)}},t.hexToBase64Url=function(t){try{return(0,i.hextob64u)(t)}catch(t){o.Log.error(t)}},t}()},function(t,e,n){(function(t){"use strict";function n(t){var e,n,r="";for(e=0;e+3<=t.length;e+=3)n=parseInt(t.substring(e,e+3),16),r+=qn.charAt(n>>6)+qn.charAt(63&n);if(e+1==t.length?(n=parseInt(t.substring(e,e+1),16),r+=qn.charAt(n<<2)):e+2==t.length&&(n=parseInt(t.substring(e,e+2),16),r+=qn.charAt(n>>2)+qn.charAt((3&n)<<4)),Wn)for(;(3&r.length)>0;)r+=Wn;return r}function r(t){var e,n,r,i="",o=0;for(e=0;e<t.length&&t.charAt(e)!=Wn;++e)r=qn.indexOf(t.charAt(e)),r<0||(0==o?(i+=f(r>>2),n=3&r,o=1):1==o?(i+=f(n<<2|r>>4),n=15&r,o=2):2==o?(i+=f(n),i+=f(r>>2),n=3&r,o=3):(i+=f(n<<2|r>>4),i+=f(15&r),o=0));return 1==o&&(i+=f(n<<2)),i}function i(t){var e,n=r(t),i=new Array;for(e=0;2*e<n.length;++e)i[e]=parseInt(n.substring(2*e,2*e+2),16);return i}function o(t,e,n){null!=t&&("number"==typeof t?this.fromNumber(t,e,n):null==e&&"string"!=typeof t?this.fromString(t,256):this.fromString(t,e))}function s(){return new o(null)}function a(t,e,n,r,i,o){for(;--o>=0;){var s=e*this[t++]+n[r]+i;i=Math.floor(s/67108864),n[r++]=67108863&s}return i}function u(t,e,n,r,i,o){for(var s=32767&e,a=e>>15;--o>=0;){var u=32767&this[t],c=this[t++]>>15,f=a*u+c*s;u=s*u+((32767&f)<<15)+n[r]+(1073741823&i),i=(u>>>30)+(f>>>15)+a*c+(i>>>30),n[r++]=1073741823&u}return i}function c(t,e,n,r,i,o){for(var s=16383&e,a=e>>14;--o>=0;){var u=16383&this[t],c=this[t++]>>14,f=a*u+c*s;u=s*u+((16383&f)<<14)+n[r]+i,i=(u>>28)+(f>>14)+a*c,n[r++]=268435455&u}return i}function f(t){return Xn.charAt(t)}function h(t,e){var n=Zn[t.charCodeAt(e)];return null==n?-1:n}function l(t){for(var e=this.t-1;e>=0;--e)t[e]=this[e];t.t=this.t,t.s=this.s}function p(t){this.t=1,this.s=t<0?-1:0,t>0?this[0]=t:t<-1?this[0]=t+this.DV:this.t=0}function d(t){var e=s();return e.fromInt(t),e}function g(t,e){var n;if(16==e)n=4;else if(8==e)n=3;else if(256==e)n=8;else if(2==e)n=1;else if(32==e)n=5;else{if(4!=e)return void this.fromRadix(t,e);n=2}this.t=0,this.s=0;for(var r=t.length,i=!1,s=0;--r>=0;){var a=8==n?255&t[r]:h(t,r);a<0?"-"==t.charAt(r)&&(i=!0):(i=!1,0==s?this[this.t++]=a:s+n>this.DB?(this[this.t-1]|=(a&(1<<this.DB-s)-1)<<s,this[this.t++]=a>>this.DB-s):this[this.t-1]|=a<<s,s+=n,s>=this.DB&&(s-=this.DB))}8==n&&0!=(128&t[0])&&(this.s=-1,s>0&&(this[this.t-1]|=(1<<this.DB-s)-1<<s)),this.clamp(),i&&o.ZERO.subTo(this,this)}function v(){for(var t=this.s&this.DM;this.t>0&&this[this.t-1]==t;)--this.t}function y(t){if(this.s<0)return"-"+this.negate().toString(t);var e;if(16==t)e=4;else if(8==t)e=3;else if(2==t)e=1;else if(32==t)e=5;else{if(4!=t)return this.toRadix(t);e=2}var n,r=(1<<e)-1,i=!1,o="",s=this.t,a=this.DB-s*this.DB%e;if(s-- >0)for(a<this.DB&&(n=this[s]>>a)>0&&(i=!0,o=f(n));s>=0;)a<e?(n=(this[s]&(1<<a)-1)<<e-a,n|=this[--s]>>(a+=this.DB-e)):(n=this[s]>>(a-=e)&r,a<=0&&(a+=this.DB,--s)),n>0&&(i=!0),i&&(o+=f(n));return i?o:"0"}function m(){var t=s();return o.ZERO.subTo(this,t),t}function S(){return this.s<0?this.negate():this}function b(t){var e=this.s-t.s;if(0!=e)return e;var n=this.t;if(e=n-t.t,0!=e)return this.s<0?-e:e;for(;--n>=0;)if(0!=(e=this[n]-t[n]))return e;return 0}function F(t){var e,n=1;return 0!=(e=t>>>16)&&(t=e,n+=16),0!=(e=t>>8)&&(t=e,n+=8),0!=(e=t>>4)&&(t=e, n+=4),0!=(e=t>>2)&&(t=e,n+=2),0!=(e=t>>1)&&(t=e,n+=1),n}function w(){return this.t<=0?0:this.DB*(this.t-1)+F(this[this.t-1]^this.s&this.DM)}function _(t,e){var n;for(n=this.t-1;n>=0;--n)e[n+t]=this[n];for(n=t-1;n>=0;--n)e[n]=0;e.t=this.t+t,e.s=this.s}function x(t,e){for(var n=t;n<this.t;++n)e[n-t]=this[n];e.t=Math.max(this.t-t,0),e.s=this.s}function E(t,e){var n,r=t%this.DB,i=this.DB-r,o=(1<<i)-1,s=Math.floor(t/this.DB),a=this.s<<r&this.DM;for(n=this.t-1;n>=0;--n)e[n+s+1]=this[n]>>i|a,a=(this[n]&o)<<r;for(n=s-1;n>=0;--n)e[n]=0;e[s]=a,e.t=this.t+s+1,e.s=this.s,e.clamp()}function A(t,e){e.s=this.s;var n=Math.floor(t/this.DB);if(n>=this.t)return void(e.t=0);var r=t%this.DB,i=this.DB-r,o=(1<<r)-1;e[0]=this[n]>>r;for(var s=n+1;s<this.t;++s)e[s-n-1]|=(this[s]&o)<<i,e[s-n]=this[s]>>r;r>0&&(e[this.t-n-1]|=(this.s&o)<<i),e.t=this.t-n,e.clamp()}function P(t,e){for(var n=0,r=0,i=Math.min(t.t,this.t);n<i;)r+=this[n]-t[n],e[n++]=r&this.DM,r>>=this.DB;if(t.t<this.t){for(r-=t.s;n<this.t;)r+=this[n],e[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<t.t;)r-=t[n],e[n++]=r&this.DM,r>>=this.DB;r-=t.s}e.s=r<0?-1:0,r<-1?e[n++]=this.DV+r:r>0&&(e[n++]=r),e.t=n,e.clamp()}function C(t,e){var n=this.abs(),r=t.abs(),i=n.t;for(e.t=i+r.t;--i>=0;)e[i]=0;for(i=0;i<r.t;++i)e[i+n.t]=n.am(0,r[i],e,i,0,n.t);e.s=0,e.clamp(),this.s!=t.s&&o.ZERO.subTo(e,e)}function k(t){for(var e=this.abs(),n=t.t=2*e.t;--n>=0;)t[n]=0;for(n=0;n<e.t-1;++n){var r=e.am(n,e[n],t,2*n,0,1);(t[n+e.t]+=e.am(n+1,2*e[n],t,2*n+1,r,e.t-n-1))>=e.DV&&(t[n+e.t]-=e.DV,t[n+e.t+1]=1)}t.t>0&&(t[t.t-1]+=e.am(n,e[n],t,2*n,0,1)),t.s=0,t.clamp()}function T(t,e,n){var r=t.abs();if(!(r.t<=0)){var i=this.abs();if(i.t<r.t)return null!=e&&e.fromInt(0),void(null!=n&&this.copyTo(n));null==n&&(n=s());var a=s(),u=this.s,c=t.s,f=this.DB-F(r[r.t-1]);f>0?(r.lShiftTo(f,a),i.lShiftTo(f,n)):(r.copyTo(a),i.copyTo(n));var h=a.t,l=a[h-1];if(0!=l){var p=l*(1<<this.F1)+(h>1?a[h-2]>>this.F2:0),d=this.FV/p,g=(1<<this.F1)/p,v=1<<this.F2,y=n.t,m=y-h,S=null==e?s():e;for(a.dlShiftTo(m,S),n.compareTo(S)>=0&&(n[n.t++]=1,n.subTo(S,n)),o.ONE.dlShiftTo(h,S),S.subTo(a,a);a.t<h;)a[a.t++]=0;for(;--m>=0;){var b=n[--y]==l?this.DM:Math.floor(n[y]*d+(n[y-1]+v)*g);if((n[y]+=a.am(0,b,n,m,0,h))<b)for(a.dlShiftTo(m,S),n.subTo(S,n);n[y]<--b;)n.subTo(S,n)}null!=e&&(n.drShiftTo(h,e),u!=c&&o.ZERO.subTo(e,e)),n.t=h,n.clamp(),f>0&&n.rShiftTo(f,n),u<0&&o.ZERO.subTo(n,n)}}}function R(t){var e=s();return this.abs().divRemTo(t,null,e),this.s<0&&e.compareTo(o.ZERO)>0&&t.subTo(e,e),e}function I(t){this.m=t}function D(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function N(t){return t}function O(t){t.divRemTo(this.m,null,t)}function j(t,e,n){t.multiplyTo(e,n),this.reduce(n)}function L(t,e){t.squareTo(e),this.reduce(e)}function M(){if(this.t<1)return 0;var t=this[0];if(0==(1&t))return 0;var e=3&t;return e=e*(2-(15&t)*e)&15,e=e*(2-(255&t)*e)&255,e=e*(2-((65535&t)*e&65535))&65535,e=e*(2-t*e%this.DV)%this.DV,e>0?this.DV-e:-e}function B(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<<t.DB-15)-1,this.mt2=2*t.t}function H(t){var e=s();return t.abs().dlShiftTo(this.m.t,e),e.divRemTo(this.m,null,e),t.s<0&&e.compareTo(o.ZERO)>0&&this.m.subTo(e,e),e}function U(t){var e=s();return t.copyTo(e),this.reduce(e),e}function V(t){for(;t.t<=this.mt2;)t[t.t++]=0;for(var e=0;e<this.m.t;++e){var n=32767&t[e],r=n*this.mpl+((n*this.mph+(t[e]>>15)*this.mpl&this.um)<<15)&t.DM;for(n=e+this.m.t,t[n]+=this.m.am(0,r,t,e,0,this.m.t);t[n]>=t.DV;)t[n]-=t.DV,t[++n]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function K(t,e){t.squareTo(e),this.reduce(e)}function q(t,e,n){t.multiplyTo(e,n),this.reduce(n)}function W(){return 0==(this.t>0?1&this[0]:this.s)}function J(t,e){if(t>4294967295||t<1)return o.ONE;var n=s(),r=s(),i=e.convert(this),a=F(t)-1;for(i.copyTo(n);--a>=0;)if(e.sqrTo(n,r),(t&1<<a)>0)e.mulTo(r,i,n);else{var u=n;n=r,r=u}return e.revert(n)}function G(t,e){var n;return n=t<256||e.isEven()?new I(e):new B(e),this.exp(t,n)}/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function z(){var t=s();return this.copyTo(t),t}function Y(){if(this.s<0){if(1==this.t)return this[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this[0];if(0==this.t)return 0}return(this[1]&(1<<32-this.DB)-1)<<this.DB|this[0]}function $(){return 0==this.t?this.s:this[0]<<24>>24}function X(){return 0==this.t?this.s:this[0]<<16>>16}function Z(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function Q(){return this.s<0?-1:this.t<=0||1==this.t&&this[0]<=0?0:1}function tt(t){if(null==t&&(t=10),0==this.signum()||t<2||t>36)return"0";var e=this.chunkSize(t),n=Math.pow(t,e),r=d(n),i=s(),o=s(),a="";for(this.divRemTo(r,i,o);i.signum()>0;)a=(n+o.intValue()).toString(t).substr(1)+a,i.divRemTo(r,i,o);return o.intValue().toString(t)+a}function et(t,e){this.fromInt(0),null==e&&(e=10);for(var n=this.chunkSize(e),r=Math.pow(e,n),i=!1,s=0,a=0,u=0;u<t.length;++u){var c=h(t,u);c<0?"-"==t.charAt(u)&&0==this.signum()&&(i=!0):(a=e*a+c,++s>=n&&(this.dMultiply(r),this.dAddOffset(a,0),s=0,a=0))}s>0&&(this.dMultiply(Math.pow(e,s)),this.dAddOffset(a,0)),i&&o.ZERO.subTo(this,this)}function nt(t,e,n){if("number"==typeof e)if(t<2)this.fromInt(1);else for(this.fromNumber(t,n),this.testBit(t-1)||this.bitwiseTo(o.ONE.shiftLeft(t-1),ft,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(e);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(o.ONE.shiftLeft(t-1),this);else{var r=new Array,i=7&t;r.length=(t>>3)+1,e.nextBytes(r),i>0?r[0]&=(1<<i)-1:r[0]=0,this.fromString(r,256)}}function rt(){var t=this.t,e=new Array;e[0]=t
s.s;var n,r=this.DB-t*this.DB%8,i=0;if(t-- >0)for(r<this.DB&&(n=this[t]>>r)!=(this.s&this.DM)>>r&&(e[i++]=n|this.s<<this.DB-r);t>=0;)r<8?(n=(this[t]&(1<<r)-1)<<8-r,n|=this[--t]>>(r+=this.DB-8)):(n=this[t]>>(r-=8)&255,r<=0&&(r+=this.DB,--t)),0!=(128&n)&&(n|=-256),0==i&&(128&this.s)!=(128&n)&&++i,(i>0||n!=this.s)&&(e[i++]=n);return e}function it(t){return 0==this.compareTo(t)}function ot(t){return this.compareTo(t)<0?this:t}function st(t){return this.compareTo(t)>0?this:t}function at(t,e,n){var r,i,o=Math.min(t.t,this.t);for(r=0;r<o;++r)n[r]=e(this[r],t[r]);if(t.t<this.t){for(i=t.s&this.DM,r=o;r<this.t;++r)n[r]=e(this[r],i);n.t=this.t}else{for(i=this.s&this.DM,r=o;r<t.t;++r)n[r]=e(i,t[r]);n.t=t.t}n.s=e(this.s,t.s),n.clamp()}function ut(t,e){return t&e}function ct(t){var e=s();return this.bitwiseTo(t,ut,e),e}function ft(t,e){return t|e}function ht(t){var e=s();return this.bitwiseTo(t,ft,e),e}function lt(t,e){return t^e}function pt(t){var e=s();return this.bitwiseTo(t,lt,e),e}function dt(t,e){return t&~e}function gt(t){var e=s();return this.bitwiseTo(t,dt,e),e}function vt(){for(var t=s(),e=0;e<this.t;++e)t[e]=this.DM&~this[e];return t.t=this.t,t.s=~this.s,t}function yt(t){var e=s();return t<0?this.rShiftTo(-t,e):this.lShiftTo(t,e),e}function mt(t){var e=s();return t<0?this.lShiftTo(-t,e):this.rShiftTo(t,e),e}function St(t){if(0==t)return-1;var e=0;return 0==(65535&t)&&(t>>=16,e+=16),0==(255&t)&&(t>>=8,e+=8),0==(15&t)&&(t>>=4,e+=4),0==(3&t)&&(t>>=2,e+=2),0==(1&t)&&++e,e}function bt(){for(var t=0;t<this.t;++t)if(0!=this[t])return t*this.DB+St(this[t]);return this.s<0?this.t*this.DB:-1}function Ft(t){for(var e=0;0!=t;)t&=t-1,++e;return e}function wt(){for(var t=0,e=this.s&this.DM,n=0;n<this.t;++n)t+=Ft(this[n]^e);return t}function _t(t){var e=Math.floor(t/this.DB);return e>=this.t?0!=this.s:0!=(this[e]&1<<t%this.DB)}function xt(t,e){var n=o.ONE.shiftLeft(t);return this.bitwiseTo(n,e,n),n}function Et(t){return this.changeBit(t,ft)}function At(t){return this.changeBit(t,dt)}function Pt(t){return this.changeBit(t,lt)}function Ct(t,e){for(var n=0,r=0,i=Math.min(t.t,this.t);n<i;)r+=this[n]+t[n],e[n++]=r&this.DM,r>>=this.DB;if(t.t<this.t){for(r+=t.s;n<this.t;)r+=this[n],e[n++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;n<t.t;)r+=t[n],e[n++]=r&this.DM,r>>=this.DB;r+=t.s}e.s=r<0?-1:0,r>0?e[n++]=r:r<-1&&(e[n++]=this.DV+r),e.t=n,e.clamp()}function kt(t){var e=s();return this.addTo(t,e),e}function Tt(t){var e=s();return this.subTo(t,e),e}function Rt(t){var e=s();return this.multiplyTo(t,e),e}function It(){var t=s();return this.squareTo(t),t}function Dt(t){var e=s();return this.divRemTo(t,e,null),e}function Nt(t){var e=s();return this.divRemTo(t,null,e),e}function Ot(t){var e=s(),n=s();return this.divRemTo(t,e,n),new Array(e,n)}function jt(t){this[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function Lt(t,e){if(0!=t){for(;this.t<=e;)this[this.t++]=0;for(this[e]+=t;this[e]>=this.DV;)this[e]-=this.DV,++e>=this.t&&(this[this.t++]=0),++this[e]}}function Mt(){}function Bt(t){return t}function Ht(t,e,n){t.multiplyTo(e,n)}function Ut(t,e){t.squareTo(e)}function Vt(t){return this.exp(t,new Mt)}function Kt(t,e,n){var r=Math.min(this.t+t.t,e);for(n.s=0,n.t=r;r>0;)n[--r]=0;var i;for(i=n.t-this.t;r<i;++r)n[r+this.t]=this.am(0,t[r],n,r,0,this.t);for(i=Math.min(t.t,e);r<i;++r)this.am(0,t[r],n,r,0,e-r);n.clamp()}function qt(t,e,n){--e;var r=n.t=this.t+t.t-e;for(n.s=0;--r>=0;)n[r]=0;for(r=Math.max(e-this.t,0);r<t.t;++r)n[this.t+r-e]=this.am(e-r,t[r],n,0,0,this.t+r-e);n.clamp(),n.drShiftTo(1,n)}function Wt(t){this.r2=s(),this.q3=s(),o.ONE.dlShiftTo(2*t.t,this.r2),this.mu=this.r2.divide(t),this.m=t}function Jt(t){if(t.s<0||t.t>2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var e=s();return t.copyTo(e),this.reduce(e),e}function Gt(t){return t}function zt(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function Yt(t,e){t.squareTo(e),this.reduce(e)}function $t(t,e,n){t.multiplyTo(e,n),this.reduce(n)}function Xt(t,e){var n,r,i=t.bitLength(),o=d(1);if(i<=0)return o;n=i<18?1:i<48?3:i<144?4:i<768?5:6,r=i<8?new I(e):e.isEven()?new Wt(e):new B(e);var a=new Array,u=3,c=n-1,f=(1<<n)-1;if(a[1]=r.convert(this),n>1){var h=s();for(r.sqrTo(a[1],h);u<=f;)a[u]=s(),r.mulTo(h,a[u-2],a[u]),u+=2}var l,p,g=t.t-1,v=!0,y=s();for(i=F(t[g])-1;g>=0;){for(i>=c?l=t[g]>>i-c&f:(l=(t[g]&(1<<i+1)-1)<<c-i,g>0&&(l|=t[g-1]>>this.DB+i-c)),u=n;0==(1&l);)l>>=1,--u;if((i-=u)<0&&(i+=this.DB,--g),v)a[l].copyTo(o),v=!1;else{for(;u>1;)r.sqrTo(o,y),r.sqrTo(y,o),u-=2;u>0?r.sqrTo(o,y):(p=o,o=y,y=p),r.mulTo(y,a[l],o)}for(;g>=0&&0==(t[g]&1<<i);)r.sqrTo(o,y),p=o,o=y,y=p,--i<0&&(i=this.DB-1,--g)}return r.revert(o)}function Zt(t){var e=this.s<0?this.negate():this.clone(),n=t.s<0?t.negate():t.clone();if(e.compareTo(n)<0){var r=e;e=n,n=r}var i=e.getLowestSetBit(),o=n.getLowestSetBit();if(o<0)return e;for(i<o&&(o=i),o>0&&(e.rShiftTo(o,e),n.rShiftTo(o,n));e.signum()>0;)(i=e.getLowestSetBit())>0&&e.rShiftTo(i,e),(i=n.getLowestSetBit())>0&&n.rShiftTo(i,n),e.compareTo(n)>=0?(e.subTo(n,e),e.rShiftTo(1,e)):(n.subTo(e,n),n.rShiftTo(1,n));return o>0&&n.lShiftTo(o,n),n}function Qt(t){if(t<=0)return 0;var e=this.DV%t,n=this.s<0?t-1:0;if(this.t>0)if(0==e)n=this[0]%t;else for(var r=this.t-1;r>=0;--r)n=(e*n+this[r])%t;return n}function te(t){var e=t.isEven();if(this.isEven()&&e||0==t.signum())return o.ZERO;for(var n=t.clone(),r=this.clone(),i=d(1),s=d(0),a=d(0),u=d(1);0!=n.signum();){for(;n.isEven();)n.rShiftTo(1,n),e?(i.isEven()&&s.isEven()||(i.addTo(this,i),s.subTo(t,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(t,s),s.rShiftTo(1,s);for(;r.isEven();)r.rShiftTo(1,r),e?(a.isEven()&&u.isEven()||(a.addTo(this,a),u.subTo(t,u)),a.rShiftTo(1,a)):u.isEven()||u.subTo(t,u),u.rShiftTo(1,u);n.compareTo(r)>=0?(n.subTo(r,n),e&&i.subTo(a,i),s.subTo(u,s)):(r.subTo(n,r),e&&a.subTo(i,a),u.subTo(s,u))}return 0!=r.compareTo(o.ONE)?o.ZERO:u.compareTo(t)>=0?u.subtract(t):u.signum()<0?(u.addTo(t,u),u.signum()<0?u.add(t):u):u}function ee(t){var e,n=this.abs();if(1==n.t&&n[0]<=Qn[Qn.length-1]){for(e=0;e<Qn.length;++e)if(n[0]==Qn[e])return!0;return!1}if(n.isEven())return!1;for(e=1;e<Qn.length;){for(var r=Qn[e],i=e+1;i<Qn.length&&r<tr;)r*=Qn[i++];for(r=n.modInt(r);e<i;)if(r%Qn[e++]==0)return!1}return n.millerRabin(t)}function ne(t){var e=this.subtract(o.ONE),n=e.getLowestSetBit();if(n<=0)return!1;var r=e.shiftRight(n);t=t+1>>1,t>Qn.length&&(t=Qn.length);for(var i=s(),a=0;a<t;++a){i.fromInt(Qn[Math.floor(Math.random()*Qn.length)]);var u=i.modPow(r,this);if(0!=u.compareTo(o.ONE)&&0!=u.compareTo(e)){for(var c=1;c++<n&&0!=u.compareTo(e);)if(u=u.modPowInt(2,this),0==u.compareTo(o.ONE))return!1;if(0!=u.compareTo(e))return!1}}return!0}/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function re(){this.i=0,this.j=0,this.S=new Array}function ie(t){var e,n,r;for(e=0;e<256;++e)this.S[e]=e;for(n=0,e=0;e<256;++e)n=n+this.S[e]+t[e%t.length]&255,r=this.S[e],this.S[e]=this.S[n],this.S[n]=r;this.i=0,this.j=0}function oe(){var t;return this.i=this.i+1&255,this.j=this.j+this.S[this.i]&255,t=this.S[this.i],this.S[this.i]=this.S[this.j],this.S[this.j]=t,this.S[t+this.S[this.i]&255]}function se(){return new re}function ae(t){nr[rr++]^=255&t,nr[rr++]^=t>>8&255,nr[rr++]^=t>>16&255,nr[rr++]^=t>>24&255,rr>=ir&&(rr-=ir)}function ue(){ae((new Date).getTime())}function ce(){if(null==er){for(ue(),er=se(),er.init(nr),rr=0;rr<nr.length;++rr)nr[rr]=0;rr=0}return er.next()}function fe(t){var e;for(e=0;e<t.length;++e)t[e]=ce()}function he(){}/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function le(t,e){return new o(t,e)}function pe(t,e){if(e<t.length+11)throw"Message too long for RSA";for(var n=new Array,r=t.length-1;r>=0&&e>0;){var i=t.charCodeAt(r--);i<128?n[--e]=i:i>127&&i<2048?(n[--e]=63&i|128,n[--e]=i>>6|192):(n[--e]=63&i|128,n[--e]=i>>6&63|128,n[--e]=i>>12|224)}n[--e]=0;for(var s=new he,a=new Array;e>2;){for(a[0]=0;0==a[0];)s.nextBytes(a);n[--e]=a[0]}return n[--e]=2,n[--e]=0,new o(n)}function de(t,e,n){for(var r="",i=0;r.length<e;)r+=n(String.fromCharCode.apply(String,t.concat([(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i]))),i+=1;return r}function ge(t,e,n,r){var i=hr.crypto.MessageDigest,s=hr.crypto.Util,a=null;if(n||(n="sha1"),"string"==typeof n&&(a=i.getCanonicalAlgName(n),r=i.getHashLength(a),n=function(t){return fn(s.hashHex(hn(t),a))}),t.length+2*r+2>e)throw"Message too long for RSA";var u,c="";for(u=0;u<e-t.length-2*r-2;u+=1)c+="\0";var f=n("")+c+""+t,h=new Array(r);(new he).nextBytes(h);var l=de(h,f.length,n),p=[];for(u=0;u<f.length;u+=1)p[u]=f.charCodeAt(u)^l.charCodeAt(u);var d=de(p,h.length,n),g=[0];for(u=0;u<h.length;u+=1)g[u+1]=h[u]^d.charCodeAt(u);return new o(g.concat(p))}function ve(){this.n=null,this.e=0,this.d=null,this.p=null,this.q=null,this.dmp1=null,this.dmq1=null,this.coeff=null}function ye(t,e){if(this.isPublic=!0,this.isPrivate=!1,"string"!=typeof t)this.n=t,this.e=e;else{if(!(null!=t&&null!=e&&t.length>0&&e.length>0))throw"Invalid RSA public key";this.n=le(t,16),this.e=parseInt(e,16)}}function me(t){return t.modPowInt(this.e,this.n)}function Se(t){var e=pe(t,this.n.bitLength()+7>>3);if(null==e)return null;var n=this.doPublic(e);if(null==n)return null;var r=n.toString(16);return 0==(1&r.length)?r:"0"+r}function be(t,e,n){var r=ge(t,this.n.bitLength()+7>>3,e,n);if(null==r)return null;var i=this.doPublic(r);if(null==i)return null;var o=i.toString(16);return 0==(1&o.length)?o:"0"+o}/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ function Fe(t,e){this.x=e,this.q=t}function we(t){return t==this||this.q.equals(t.q)&&this.x.equals(t.x)}function _e(){return this.x}function xe(){return new Fe(this.q,this.x.negate().mod(this.q))}function Ee(t){return new Fe(this.q,this.x.add(t.toBigInteger()).mod(this.q))}function Ae(t){return new Fe(this.q,this.x.subtract(t.toBigInteger()).mod(this.q))}function Pe(t){return new Fe(this.q,this.x.multiply(t.toBigInteger()).mod(this.q))}function Ce(){return new Fe(this.q,this.x.square().mod(this.q))}function ke(t){return new Fe(this.q,this.x.multiply(t.toBigInteger().modInverse(this.q)).mod(this.q))}function Te(t,e,n,r){this.curve=t,this.x=e,this.y=n,null==r?this.z=o.ONE:this.z=r,this.zinv=null}function Re(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function Ie(){return null==this.zinv&&(this.zinv=this.z.modInverse(this.curve.q)),this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function De(t){if(t==this)return!0;if(this.isInfinity())return t.isInfinity();if(t.isInfinity())return this.isInfinity();var e,n;return e=t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q),!!e.equals(o.ZERO)&&(n=t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q),n.equals(o.ZERO))}function Ne(){return null==this.x&&null==this.y||this.z.equals(o.ZERO)&&!this.y.toBigInteger().equals(o.ZERO)}function Oe(){return new Te(this.curve,this.x,this.y.negate(),this.z)}function je(t){if(this.isInfinity())return t;if(t.isInfinity())return this;var e=t.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(t.z)).mod(this.curve.q),n=t.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(t.z)).mod(this.curve.q);if(o.ZERO.equals(n))return o.ZERO.equals(e)?this.twice():this.curve.getInfinity();var r=new o("3"),i=this.x.toBigInteger(),s=this.y.toBigInteger(),a=(t.x.toBigInteger(),t.y.toBigInteger(),n.square()),u=a.multiply(n),c=i.multiply(a),f=e.square().multiply(this.z),h=f.subtract(c.shiftLeft(1)).multiply(t.z).subtract(u).multiply(n).mod(this.curve.q),l=c.multiply(r).multiply(e).subtract(s.multiply(u)).subtract(f.multiply(e)).multiply(t.z).add(e.multiply(u)).mod(this.curve.q),p=u.multiply(this.z).multiply(t.z).mod(this.curve.q);return new Te(this.curve,this.curve.fromBigInteger(h),this.curve.fromBigInteger(l),p)}function Le(){if(this.isInfinity())return this;if(0==this.y.toBigInteger().signum())return this.curve.getInfinity();var t=new o("3"),e=this.x.toBigInteger(),n=this.y.toBigInteger(),r=n.multiply(this.z),i=r.multiply(n).mod(this.curve.q),s=this.curve.a.toBigInteger(),a=e.square().multiply(t);o.ZERO.equals(s)||(a=a.add(this.z.square().multiply(s))),a=a.mod(this.curve.q);var u=a.square().subtract(e.shiftLeft(3).multiply(i)).shiftLeft(1).multiply(r).mod(this.curve.q),c=a.multiply(t).multiply(e).subtract(i.shiftLeft(1)).shiftLeft(2).multiply(i).subtract(a.square().multiply(a)).mod(this.curve.q),f=r.square().multiply(r).shiftLeft(3).mod(this.curve.q);return new Te(this.curve,this.curve.fromBigInteger(u),this.curve.fromBigInteger(c),f)}function Me(t){if(this.isInfinity())return this;if(0==t.signum())return this.curve.getInfinity();var e,n=t,r=n.multiply(new o("3")),i=this.negate(),s=this;for(e=r.bitLength()-2;e>0;--e){s=s.twice();var a=r.testBit(e),u=n.testBit(e);a!=u&&(s=s.add(a?this:i))}return s}function Be(t,e,n){var r;r=t.bitLength()>n.bitLength()?t.bitLength()-1:n.bitLength()-1;for(var i=this.curve.getInfinity(),o=this.add(e);r>=0;)i=i.twice(),t.testBit(r)?i=n.testBit(r)?i.add(o):i.add(this):n.testBit(r)&&(i=i.add(e)),--r;return i}function He(t,e,n){this.q=t,this.a=this.fromBigInteger(e),this.b=this.fromBigInteger(n),this.infinity=new Te(this,null,null)}function Ue(){return this.q}function Ve(){return this.a}function Ke(){return this.b}function qe(t){return t==this||this.q.equals(t.q)&&this.a.equals(t.a)&&this.b.equals(t.b)}function We(){return this.infinity}function Je(t){return new Fe(this.q,t)}function Ge(t){switch(parseInt(t.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var e=(t.length-2)/2,n=t.substr(2,e),r=t.substr(e+2,e);return new Te(this,this.fromBigInteger(new o(n,16)),this.fromBigInteger(new o(r,16)));default:return null}}function ze(t){for(var e=new Array,n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}function Ye(t){for(var e="",n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e}function $e(t){for(var e="",n=0;n<t.length;n++){var r=t[n].toString(16);1==r.length&&(r="0"+r),e+=r}return e}function Xe(t){return $e(ze(t))}function Ze(t){return n(Xe(t))}function Qe(t){return en(n(Xe(t)))}function tn(t){return Ye(i(nn(t)))}function en(t){return t=t.replace(/\=/g,""),t=t.replace(/\+/g,"-"),t=t.replace(/\//g,"_")}function nn(t){return t.length%4==2?t+="==":t.length%4==3&&(t+="="),t=t.replace(/-/g,"+"),t=t.replace(/_/g,"/")}function rn(t){return t.length%2==1&&(t="0"+t),en(n(t))}function on(t){return r(nn(t))}function sn(t){return n(_n(kn(t)))}function an(t){return decodeURIComponent(xn(r(t)))}function un(t){return _n(kn(t))}function cn(t){return decodeURIComponent(xn(t))}function fn(t){for(var e="",n=0;n<t.length-1;n+=2)e+=String.fromCharCode(parseInt(t.substr(n,2),16));return e}function hn(t){for(var e="",n=0;n<t.length;n++)e+=("0"+t.charCodeAt(n).toString(16)).slice(-2);return e}function ln(t){return n(t)}function pn(t){var e=ln(t),n=e.replace(/(.{64})/g,"$1\r\n");return n=n.replace(/\r\n$/,"")}function dn(t){var e=t.replace(/[^0-9A-Za-z\/+=]*/g,""),n=r(e);return n}function gn(t,e){var n=pn(t);return"-----BEGIN "+e+"-----\r\n"+n+"\r\n-----END "+e+"-----\r\n"}function vn(t,e){if(t.indexOf("-----BEGIN ")==-1)throw"can't find PEM header: "+e;return void 0!==e?(t=t.replace("-----BEGIN "+e+"-----",""),t=t.replace("-----END "+e+"-----","")):(t=t.replace(/-----BEGIN [^-]+-----/,""),t=t.replace(/-----END [^-]+-----/,"")),dn(t)}function yn(t){if(t.length%2!=0)throw"input is not even length";if(null==t.match(/^[0-9A-Fa-f]+$/))throw"input is not hexadecimal";for(var e=new ArrayBuffer(t.length/2),n=new DataView(e),r=0;r<t.length/2;r++)n.setUint8(r,parseInt(t.substr(2*r,2),16));return e}function mn(t){for(var e="",n=new DataView(t),r=0;r<t.byteLength;r++)e+=("00"+n.getUint8(r).toString(16)).slice(-2);return e}function Sn(t){var e,n,r,i,o,s,a,u,c,f,h;if(h=t.match(/^(\d{2}|\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(|\.\d+)Z$/))return u=h[1],e=parseInt(u),2===u.length&&(50<=e&&e<100?e=1900+e:0<=e&&e<50&&(e=2e3+e)),n=parseInt(h[2])-1,r=parseInt(h[3]),i=parseInt(h[4]),o=parseInt(h[5]),s=parseInt(h[6]),a=0,c=h[7],""!==c&&(f=(c.substr(1)+"00").substr(0,3),a=parseInt(f)),Date.UTC(e,n,r,i,o,s,a);throw"unsupported zulu format: "+t}function bn(t){var e=Sn(t);return~~(e/1e3)}function Fn(t){return new Date(Sn(t))}function wn(t,e,n){var r,i=t.getUTCFullYear();if(e){if(i<1950||2049<i)throw"not proper year for UTCTime: "+i;r=(""+i).slice(-2)}else r=("000"+i).slice(-4);if(r+=("0"+(t.getUTCMonth()+1)).slice(-2),r+=("0"+t.getUTCDate()).slice(-2),r+=("0"+t.getUTCHours()).slice(-2),r+=("0"+t.getUTCMinutes()).slice(-2),r+=("0"+t.getUTCSeconds()).slice(-2),n){var o=t.getUTCMilliseconds();0!==o&&(o=("00"+o).slice(-3),o=o.replace(/0+$/g,""),r+="."+o)}return r+="Z"}function _n(t){return t.replace(/%/g,"")}function xn(t){return t.replace(/(..)/g,"%$1")}function En(t){var e="malformed IPv6 address";if(!t.match(/^[0-9A-Fa-f:]+$/))throw e;t=t.toLowerCase();var n=t.split(":").length-1;if(n<2)throw e;var r=":".repeat(7-n+2);t=t.replace("::",r);var i=t.split(":");if(8!=i.length)throw e;for(var o=0;o<8;o++)i[o]=("0000"+i[o]).slice(-4);return i.join("")}function An(t){if(!t.match(/^[0-9A-Fa-f]{32}$/))throw"malformed IPv6 address octet";t=t.toLowerCase();for(var e=t.match(/.{1,4}/g),n=0;n<8;n++)e[n]=e[n].replace(/^0+/,""),""==e[n]&&(e[n]="0");t=":"+e.join(":")+":";var r=t.match(/:(0:){2,}/g);if(null===r)return t.slice(1,-1);for(var i="",n=0;n<r.length;n++)r[n].length>i.length&&(i=r[n]);return t=t.replace(i,"::"),t.slice(1,-1)}function Pn(t){var e="malformed hex value";if(!t.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw e;if(8!=t.length)return 32==t.length?An(t):t;var n;try{return n=parseInt(t.substr(0,2),16)+"."+parseInt(t.substr(2,2),16)+"."+parseInt(t.substr(4,2),16)+"."+parseInt(t.substr(6,2),16)}catch(t){throw e}}function Cn(t){var e="malformed IP address";if(t=t.toLowerCase(t),!t.match(/^[0-9.]+$/)){if(t.match(/^[0-9a-f:]+$/)&&t.indexOf(":")!==-1)return En(t);throw e}var n=t.split(".");if(4!==n.length)throw e;var r="";try{for(var i=0;i<4;i++){var o=parseInt(n[i]);r+=("0"+o.toString(16)).slice(-2)}return r}catch(t){throw e}}function kn(t){for(var e=encodeURIComponent(t),n="",r=0;r<e.length;r++)"%"==e[r]?(n+=e.substr(r,3),r+=2):n=n+"%"+Xe(e[r]);return n}function Tn(t){return t=t.replace(/\r\n/gm,"\n")}function Rn(t){return t=t.replace(/\r\n/gm,"\n"),t=t.replace(/\n/gm,"\r\n")}function In(t){return t.length%2==1?"0"+t:t.substr(0,1)>"7"?"00"+t:t}function Dn(t){t=t.replace(/^\s*\[\s*/,""),t=t.replace(/\s*\]\s*$/,""),t=t.replace(/\s*/g,"");try{var e=t.split(/,/).map(function(t,e,n){var r=parseInt(t);if(r<0||255<r)throw"integer not in range 0-255";var i=("00"+r.toString(16)).slice(-2);return i}).join("");return e}catch(t){throw"malformed integer array string: "+t}}function Nn(t,e){for(var n="",r=e/4-t.length,i=0;i<r;i++)n+="0";return n+t}function On(t,e,n){for(var r="",i=0;r.length<e;)r+=fn(n(hn(t+String.fromCharCode.apply(String,[(4278190080&i)>>24,(16711680&i)>>16,(65280&i)>>8,255&i])))),i+=1;return r}function jn(t){for(var e in hr.crypto.Util.DIGESTINFOHEAD){var n=hr.crypto.Util.DIGESTINFOHEAD[e],r=n.length;if(t.substring(0,r)==n){var i=[e,t.substring(r)];return i}}return[]}function Ln(){var t=fr,e=t.getChildIdx,n=t.getV,r=t.getTLV,i=t.getVbyList,o=t.getTLVbyList,s=t.getIdxbyList,a=t.getVidx,u=t.oidname,c=Ln,f=vn;this.hex=null,this.version=0,this.foffset=0,this.aExtInfo=null,this.getVersion=function(){return null===this.hex||0!==this.version?this.version:"a003020102"!==o(this.hex,0,[0,0])?(this.version=1,this.foffset=-1,1):(this.version=3,3)},this.getSerialNumberHex=function(){return i(this.hex,0,[0,1+this.foffset],"02")},this.getSignatureAlgorithmField=function(){return u(i(this.hex,0,[0,2+this.foffset,0],"06"))},this.getIssuerHex=function(){return o(this.hex,0,[0,3+this.foffset],"30")},this.getIssuerString=function(){return c.hex2dn(this.getIssuerHex())},this.getSubjectHex=function(){return o(this.hex,0,[0,5+this.foffset],"30")},this.getSubjectString=function(){return c.hex2dn(this.getSubjectHex())},this.getNotBefore=function(){var t=i(this.hex,0,[0,4+this.foffset,0]);return t=t.replace(/(..)/g,"%$1"),t=decodeURIComponent(t)},this.getNotAfter=function(){var t=i(this.hex,0,[0,4+this.foffset,1]);return t=t.replace(/(..)/g,"%$1"),t=decodeURIComponent(t)},this.getPublicKeyHex=function(){return t.getTLVbyList(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyIdx=function(){return s(this.hex,0,[0,6+this.foffset],"30")},this.getPublicKeyContentIdx=function(){var t=this.getPublicKeyIdx();return s(this.hex,t,[1,0],"30")},this.getPublicKey=function(){return gr.getKey(this.getPublicKeyHex(),null,"pkcs8pub")},this.getSignatureAlgorithmName=function(){return u(i(this.hex,0,[1,0],"06"))},this.getSignatureValueHex=function(){return i(this.hex,0,[2],"03",!0)},this.verifySignature=function(t){var e=this.getSignatureAlgorithmName(),n=this.getSignatureValueHex(),r=o(this.hex,0,[0],"30"),i=new hr.crypto.Signature({alg:e});return i.init(t),i.updateHex(r),i.verify(n)},this.parseExt=function(){if(3!==this.version)return-1;var n=s(this.hex,0,[0,7,0],"30"),r=e(this.hex,n);this.aExtInfo=new Array;for(var o=0;o<r.length;o++){var u={};u.critical=!1;var c=e(this.hex,r[o]),f=0;3===c.length&&(u.critical=!0,f=1),u.oid=t.hextooidstr(i(this.hex,r[o],[0],"06"));var h=s(this.hex,r[o],[1+f]);u.vidx=a(this.hex,h),this.aExtInfo.push(u)}},this.getExtInfo=function(t){var e=this.aExtInfo,n=t;if(t.match(/^[0-9.]+$/)||(n=hr.asn1.x509.OID.name2oid(t)),""!==n)for(var r=0;r<e.length;r++)if(e[r].oid===n)return e[r]},this.getExtBasicConstraints=function(){var t=this.getExtInfo("basicConstraints");if(void 0===t)return t;var e=n(this.hex,t.vidx);if(""===e)return{};if("0101ff"===e)return{cA:!0};if("0101ff02"===e.substr(0,8)){var r=n(e,6),i=parseInt(r,16);return{cA:!0,pathLen:i}}throw"basicConstraints parse error"},this.getExtKeyUsageBin=function(){var t=this.getExtInfo("keyUsage");if(void 0===t)return"";var e=n(this.hex,t.vidx);if(e.length%2!=0||e.length<=2)throw"malformed key usage value";var r=parseInt(e.substr(0,2)),i=parseInt(e.substr(2),16).toString(2);return i.substr(0,i.length-r)},this.getExtKeyUsageString=function(){for(var t=this.getExtKeyUsageBin(),e=new Array,n=0;n<t.length;n++)"1"==t.substr(n,1)&&e.push(Ln.KEYUSAGE_NAME[n]);return e.join(",")},this.getExtSubjectKeyIdentifier=function(){var t=this.getExtInfo("subjectKeyIdentifier");return void 0===t?t:n(this.hex,t.vidx)},this.getExtAuthorityKeyIdentifier=function(){var t=this.getExtInfo("authorityKeyIdentifier");if(void 0===t)return t;for(var i={},o=r(this.hex,t.vidx),s=e(o,0),a=0;a<s.length;a++)"80"===o.substr(s[a],2)&&(i.kid=n(o,s[a]));return i},this.getExtExtKeyUsageName=function(){var t=this.getExtInfo("extKeyUsage");if(void 0===t)return t;var i=new Array,o=r(this.hex,t.vidx);if(""===o)return i;for(var s=e(o,0),a=0;a<s.length;a++)i.push(u(n(o,s[a])));return i},this.getExtSubjectAltName=function(){for(var t=this.getExtSubjectAltName2(),e=new Array,n=0;n<t.length;n++)"DNS"===t[n][0]&&e.push(t[n][1]);return e},this.getExtSubjectAltName2=function(){var t,i,o,s=this.getExtInfo("subjectAltName");if(void 0===s)return s;for(var a=new Array,u=r(this.hex,s.vidx),c=e(u,0),f=0;f<c.length;f++)o=u.substr(c[f],2),t=n(u,c[f]),"81"===o&&(i=cn(t),a.push(["MAIL",i])),"82"===o&&(i=cn(t),a.push(["DNS",i])),"84"===o&&(i=Ln.hex2dn(t,0),a.push(["DN",i])),"86"===o&&(i=cn(t),a.push(["URI",i])),"87"===o&&(i=Pn(t),a.push(["IP",i]));return a},this.getExtCRLDistributionPointsURI=function(){var t=this.getExtInfo("cRLDistributionPoints");if(void 0===t)return t;for(var n=new Array,r=e(this.hex,t.vidx),o=0;o<r.length;o++)try{var s=i(this.hex,r[o],[0,0,0],"86"),a=cn(s);n.push(a)}catch(t){}return n},this.getExtAIAInfo=function(){var t=this.getExtInfo("authorityInfoAccess");if(void 0===t)return t;for(var n={ocsp:[],caissuer:[]},r=e(this.hex,t.vidx),o=0;o<r.length;o++){var s=i(this.hex,r[o],[0],"06"),a=i(this.hex,r[o],[1],"86");"2b06010505073001"===s&&n.ocsp.push(cn(a)),"2b06010505073002"===s&&n.caissuer.push(cn(a))}return n},this.getExtCertificatePolicies=function(){var t=this.getExtInfo("certificatePolicies");if(void 0===t)return t;for(var o=r(this.hex,t.vidx),s=[],a=e(o,0),c=0;c<a.length;c++){var f={},h=e(o,a[c]);if(f.id=u(n(o,h[0])),2===h.length)for(var l=e(o,h[1]),p=0;p<l.length;p++){var d=i(o,l[p],[0],"06");"2b06010505070201"===d?f.cps=cn(i(o,l[p],[1])):"2b06010505070202"===d&&(f.unotice=cn(i(o,l[p],[1,0])))}s.push(f)}return s},this.readCertPEM=function(t){this.readCertHex(f(t))},this.readCertHex=function(t){this.hex=t,this.getVersion();try{s(this.hex,0,[0,7],"a3"),this.parseExt()}catch(t){}},this.getInfo=function(){var t,e,n;if(t="Basic Fields\n",t+=" serial number: "+this.getSerialNumberHex()+"\n",t+=" signature algorithm: "+this.getSignatureAlgorithmField()+"\n",t+=" issuer: "+this.getIssuerString()+"\n",t+=" notBefore: "+this.getNotBefore()+"\n",t+=" notAfter: "+this.getNotAfter()+"\n",t+=" subject: "+this.getSubjectString()+"\n",t+=" subject public key info: \n",e=this.getPublicKey(),t+=" key algorithm: "+e.type+"\n","RSA"===e.type&&(t+=" n="+In(e.n.toString(16)).substr(0,16)+"...\n",t+=" e="+In(e.e.toString(16))+"\n"),n=this.aExtInfo,void 0!==n&&null!==n){t+="X509v3 Extensions:\n";for(var r=0;r<n.length;r++){var i=n[r],o=hr.asn1.x509.OID.oid2name(i.oid);""===o&&(o=i.oid);var s="";if(i.critical===!0&&(s="CRITICAL"),t+=" "+o+" "+s+":\n","basicConstraints"===o){var a=this.getExtBasicConstraints();void 0===a.cA?t+=" {}\n":(t+=" cA=true",void 0!==a.pathLen&&(t+=", pathLen="+a.pathLen),t+="\n")}else if("keyUsage"===o)t+=" "+this.getExtKeyUsageString()+"\n";else if("subjectKeyIdentifier"===o)t+=" "+this.getExtSubjectKeyIdentifier()+"\n";else if("authorityKeyIdentifier"===o){var u=this.getExtAuthorityKeyIdentifier();void 0!==u.kid&&(t+=" kid="+u.kid+"\n")}else if("extKeyUsage"===o){var c=this.getExtExtKeyUsageName();t+=" "+c.join(", ")+"\n"}else if("subjectAltName"===o){var f=this.getExtSubjectAltName2();t+=" "+f+"\n"}else if("cRLDistributionPoints"===o){var h=this.getExtCRLDistributionPointsURI();t+=" "+h+"\n"}else if("authorityInfoAccess"===o){var l=this.getExtAIAInfo();void 0!==l.ocsp&&(t+=" ocsp: "+l.ocsp.join(",")+"\n"),void 0!==l.caissuer&&(t+=" caissuer: "+l.caissuer.join(",")+"\n")}else if("certificatePolicies"===o)for(var p=this.getExtCertificatePolicies(),d=0;d<p.length;d++)void 0!==p[d].id&&(t+=" policy oid: "+p[d].id+"\n"),void 0!==p[d].cps&&(t+=" cps: "+p[d].cps+"\n")}}return t+="signature algorithm: "+this.getSignatureAlgorithmName()+"\n",t+="signature: "+this.getSignatureValueHex().substr(0,16)+"...\n"}}var Mn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Bn={};Bn.userAgent=!1;var Hn={};/*! Copyright (c) 2011, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html version: 2.9.0 */ if(void 0===Un)var Un={};Un.lang={extend:function(t,e,n){if(!e||!t)throw new Error("YAHOO.lang.extend failed, please check that all dependencies are included.");var r=function(){};if(r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t,t.superclass=e.prototype,e.prototype.constructor==Object.prototype.constructor&&(e.prototype.constructor=e),n){var i;for(i in n)t.prototype[i]=n[i];var o=function(){},s=["toString","valueOf"];try{/MSIE/.test(Bn.userAgent)&&(o=function(t,e){for(i=0;i<s.length;i+=1){var n=s[i],r=e[n];"function"==typeof r&&r!=Object.prototype[n]&&(t[n]=r)}})}catch(t){}o(t.prototype,n)}}};/*! CryptoJS v3.1.2 core-fix.js * code.google.com/p/crypto-js * (c) 2009-2013 by Jeff Mott. All rights reserved. * code.google.com/p/crypto-js/wiki/License * THIS IS FIX of 'core.js' to fix Hmac issue. * https://code.google.com/p/crypto-js/issues/detail?id=84 * https://crypto-js.googlecode.com/svn-history/r667/branches/3.x/src/core.js */ var Vn=Vn||function(t,e){var n={},r=n.lib={},i=r.Base=function(){function t(){}return{extend:function(e){t.prototype=this;var n=new t;return e&&n.mixIn(e),n.hasOwnProperty("init")||(n.init=function(){n.$super.init.apply(this,arguments)}),n.init.prototype=n,n.$super=this,n},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var e in t)t.hasOwnProperty(e)&&(this[e]=t[e]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),o=r.WordArray=i.extend({init:function(t,n){t=this.words=t||[],n!=e?this.sigBytes=n:this.sigBytes=4*t.length},toString:function(t){return(t||a).stringify(this)},concat:function(t){var e=this.words,n=t.words,r=this.sigBytes,i=t.sigBytes;if(this.clamp(),r%4)for(var o=0;o<i;o++){var s=n[o>>>2]>>>24-o%4*8&255;e[r+o>>>2]|=s<<24-(r+o)%4*8}else for(var o=0;o<i;o+=4)e[r+o>>>2]=n[o>>>2];return this.sigBytes+=i,this},clamp:function(){var e=this.words,n=this.sigBytes;e[n>>>2]&=4294967295<<32-n%4*8,e.length=t.ceil(n/4)},clone:function(){var t=i.clone.call(this);return t.words=this.words.slice(0),t},random:function(e){for(var n=[],r=0;r<e;r+=4)n.push(4294967296*t.random()|0);return new o.init(n,e)}}),s=n.enc={},a=s.Hex={stringify:function(t){for(var e=t.words,n=t.sigBytes,r=[],i=0;i<n;i++){var o=e[i>>>2]>>>24-i%4*8&255;r.push((o>>>4).toString(16)),r.push((15&o).toString(16))}return r.join("")},parse:function(t){for(var e=t.length,n=[],r=0;r<e;r+=2)n[r>>>3]|=parseInt(t.substr(r,2),16)<<24-r%8*4;return new o.init(n,e/2)}},u=s.Latin1={stringify:function(t){for(var e=t.words,n=t.sigBytes,r=[],i=0;i<n;i++){var o=e[i>>>2]>>>24-i%4*8&255;r.push(String.fromCharCode(o))}return r.join("")},parse:function(t){for(var e=t.length,n=[],r=0;r<e;r++)n[r>>>2]|=(255&t.charCodeAt(r))<<24-r%4*8;return new o.init(n,e)}},c=s.Utf8={stringify:function(t){try{return decodeURIComponent(escape(u.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return u.parse(unescape(encodeURIComponent(t)))}},f=r.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=c.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(e){var n=this._data,r=n.words,i=n.sigBytes,s=this.blockSize,a=4*s,u=i/a;u=e?t.ceil(u):t.max((0|u)-this._minBufferSize,0);var c=u*s,f=t.min(4*c,i);if(c){for(var h=0;h<c;h+=s)this._doProcessBlock(r,h);var l=r.splice(0,c);n.sigBytes-=f}return new o.init(l,f)},clone:function(){var t=i.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0}),h=(r.Hasher=f.extend({cfg:i.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){f.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){t&&this._append(t);var e=this._doFinalize();return e},blockSize:16,_createHelper:function(t){return function(e,n){return new t.init(n).finalize(e)}},_createHmacHelper:function(t){return function(e,n){return new h.HMAC.init(t,n).finalize(e)}}}),n.algo={});return n}(Math);!function(t){var e=Vn,n=e.lib,r=n.Base,i=n.WordArray,e=e.x64={};e.Word=r.extend({init:function(t,e){this.high=t,this.low=e}}),e.WordArray=r.extend({init:function(e,n){e=this.words=e||[],this.sigBytes=n!=t?n:8*e.length},toX32:function(){for(var t=this.words,e=t.length,n=[],r=0;r<e;r++){var o=t[r];n.push(o.high),n.push(o.low)}return i.create(n,this.sigBytes)},clone:function(){for(var t=r.clone.call(this),e=t.words=this.words.slice(0),n=e.length,i=0;i<n;i++)e[i]=e[i].clone();return t}})}(),function(){var t=Vn,e=t.lib.WordArray;t.enc.Base64={stringify:function(t){var e=t.words,n=t.sigBytes,r=this._map;t.clamp(),t=[];for(var i=0;i<n;i+=3)for(var o=(e[i>>>2]>>>24-8*(i%4)&255)<<16|(e[i+1>>>2]>>>24-8*((i+1)%4)&255)<<8|e[i+2>>>2]>>>24-8*((i+2)%4)&255,s=0;4>s&&i+.75*s<n;s++)t.push(r.charAt(o>>>6*(3-s)&63));if(e=r.charAt(64))for(;t.length%4;)t.push(e);return t.join("")},parse:function(t){var n=t.length,r=this._map,i=r.charAt(64);i&&(i=t.indexOf(i),-1!=i&&(n=i));for(var i=[],o=0,s=0;s<n;s++)if(s%4){var a=r.indexOf(t.charAt(s-1))<<2*(s%4),u=r.indexOf(t.charAt(s))>>>6-2*(s%4);i[o>>>2]|=(a|u)<<24-8*(o%4),o++}return e.create(i,o)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),function(t){for(var e=Vn,n=e.lib,r=n.WordArray,i=n.Hasher,n=e.algo,o=[],s=[],a=function(t){return 4294967296*(t-(0|t))|0},u=2,c=0;64>c;){var f;t:{f=u;for(var h=t.sqrt(f),l=2;l<=h;l++)if(!(f%l)){f=!1;break t}f=!0}f&&(8>c&&(o[c]=a(t.pow(u,.5))),s[c]=a(t.pow(u,1/3)),c++),u++}var p=[],n=n.SHA256=i.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(t,e){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],a=n[3],u=n[4],c=n[5],f=n[6],h=n[7],l=0;64>l;l++){if(16>l)p[l]=0|t[e+l];else{var d=p[l-15],g=p[l-2];p[l]=((d<<25|d>>>7)^(d<<14|d>>>18)^d>>>3)+p[l-7]+((g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10)+p[l-16]}d=h+((u<<26|u>>>6)^(u<<21|u>>>11)^(u<<7|u>>>25))+(u&c^~u&f)+s[l]+p[l],g=((r<<30|r>>>2)^(r<<19|r>>>13)^(r<<10|r>>>22))+(r&i^r&o^i&o),h=f,f=c,c=u,u=a+d|0,a=o,o=i,i=r,r=d+g|0}n[0]=n[0]+r|0,n[1]=n[1]+i|0,n[2]=n[2]+o|0,n[3]=n[3]+a|0,n[4]=n[4]+u|0,n[5]=n[5]+c|0,n[6]=n[6]+f|0,n[7]=n[7]+h|0},_doFinalize:function(){var e=this._data,n=e.words,r=8*this._nDataBytes,i=8*e.sigBytes;return n[i>>>5]|=128<<24-i%32,n[(i+64>>>9<<4)+14]=t.floor(r/4294967296),n[(i+64>>>9<<4)+15]=r,e.sigBytes=4*n.length,this._process(),this._hash},clone:function(){var t=i.clone.call(this);return t._hash=this._hash.clone(),t}});e.SHA256=i._createHelper(n),e.HmacSHA256=i._createHmacHelper(n)}(Math),function(){function t(){return i.create.apply(i,arguments)}for(var e=Vn,n=e.lib.Hasher,r=e.x64,i=r.Word,o=r.WordArray,r=e.algo,s=[t(1116352408,3609767458),t(1899447441,602891725),t(3049323471,3964484399),t(3921009573,2173295548),t(961987163,4081628472),t(1508970993,3053834265),t(2453635748,2937671579),t(2870763221,3664609560),t(3624381080,2734883394),t(310598401,1164996542),t(607225278,1323610764),t(1426881987,3590304994),t(1925078388,4068182383),t(2162078206,991336113),t(2614888103,633803317),t(3248222580,3479774868),t(3835390401,2666613458),t(4022224774,944711139),t(264347078,2341262773),t(604807628,2007800933),t(770255983,1495990901),t(1249150122,1856431235),t(1555081692,3175218132),t(1996064986,2198950837),t(2554220882,3999719339),t(2821834349,766784016),t(2952996808,2566594879),t(3210313671,3203337956),t(3336571891,1034457026),t(3584528711,2466948901),t(113926993,3758326383),t(338241895,168717936),t(666307205,1188179964),t(773529912,1546045734),t(1294757372,1522805485),t(1396182291,2643833823),t(1695183700,2343527390),t(1986661051,1014477480),t(2177026350,1206759142),t(2456956037,344077627),t(2730485921,1290863460),t(2820302411,3158454273),t(3259730800,3505952657),t(3345764771,106217008),t(3516065817,3606008344),t(3600352804,1432725776),t(4094571909,1467031594),t(275423344,851169720),t(430227734,3100823752),t(506948616,1363258195),t(659060556,3750685593),t(883997877,3785050280),t(958139571,3318307427),t(1322822218,3812723403),t(1537002063,2003034995),t(1747873779,3602036899),t(1955562222,1575990012),t(2024104815,1125592928),t(2227730452,2716904306),t(2361852424,442776044),t(2428436474,593698344),t(2756734187,3733110249),t(3204031479,2999351573),t(3329325298,3815920427),t(3391569614,3928383900),t(3515267271,566280711),t(3940187606,3454069534),t(4118630271,4000239992),t(116418474,1914138554),t(174292421,2731055270),t(289380356,3203993006),t(460393269,320620315),t(685471733,587496836),t(852142971,1086792851),t(1017036298,365543100),t(1126000580,2618297676),t(1288033470,3409855158),t(1501505948,4234509866),t(1607167915,987167468),t(1816402316,1246189591)],a=[],u=0;80>u;u++)a[u]=t();r=r.SHA512=n.extend({_doReset:function(){this._hash=new o.init([new i.init(1779033703,4089235720),new i.init(3144134277,2227873595),new i.init(1013904242,4271175723),new i.init(2773480762,1595750129),new i.init(1359893119,2917565137),new i.init(2600822924,725511199),new i.init(528734635,4215389547),new i.init(1541459225,327033209)])},_doProcessBlock:function(t,e){for(var n=this._hash.words,r=n[0],i=n[1],o=n[2],u=n[3],c=n[4],f=n[5],h=n[6],n=n[7],l=r.high,p=r.low,d=i.high,g=i.low,v=o.high,y=o.low,m=u.high,S=u.low,b=c.high,F=c.low,w=f.high,_=f.low,x=h.high,E=h.low,A=n.high,P=n.low,C=l,k=p,T=d,R=g,I=v,D=y,N=m,O=S,j=b,L=F,M=w,B=_,H=x,U=E,V=A,K=P,q=0;80>q;q++){var W=a[q];if(16>q)var J=W.high=0|t[e+2*q],G=W.low=0|t[e+2*q+1];else{var J=a[q-15],G=J.high,z=J.low,J=(G>>>1|z<<31)^(G>>>8|z<<24)^G>>>7,z=(z>>>1|G<<31)^(z>>>8|G<<24)^(z>>>7|G<<25),Y=a[q-2],G=Y.high,$=Y.low,Y=(G>>>19|$<<13)^(G<<3|$>>>29)^G>>>6,$=($>>>19|G<<13)^($<<3|G>>>29)^($>>>6|G<<26),G=a[q-7],X=G.high,Z=a[q-16],Q=Z.high,Z=Z.low,G=z+G.low,J=J+X+(G>>>0<z>>>0?1:0),G=G+$,J=J+Y+(G>>>0<$>>>0?1:0),G=G+Z,J=J+Q+(G>>>0<Z>>>0?1:0);W.high=J,W.low=G}var X=j&M^~j&H,Z=L&B^~L&U,W=C&T^C&I^T&I,tt=k&R^k&D^R&D,z=(C>>>28|k<<4)^(C<<30|k>>>2)^(C<<25|k>>>7),Y=(k>>>28|C<<4)^(k<<30|C>>>2)^(k<<25|C>>>7),$=s[q],et=$.high,nt=$.low,$=K+((L>>>14|j<<18)^(L>>>18|j<<14)^(L<<23|j>>>9)),Q=V+((j>>>14|L<<18)^(j>>>18|L<<14)^(j<<23|L>>>9))+($>>>0<K>>>0?1:0),$=$+Z,Q=Q+X+($>>>0<Z>>>0?1:0),$=$+nt,Q=Q+et+($>>>0<nt>>>0?1:0),$=$+G,Q=Q+J+($>>>0<G>>>0?1:0),G=Y+tt,W=z+W+(G>>>0<Y>>>0?1:0),V=H,K=U,H=M,U=B,M=j,B=L,L=O+$|0,j=N+Q+(L>>>0<O>>>0?1:0)|0,N=I,O=D,I=T,D=R,T=C,R=k,k=$+G|0,C=Q+W+(k>>>0<$>>>0?1:0)|0}p=r.low=p+k,r.high=l+C+(p>>>0<k>>>0?1:0),g=i.low=g+R,i.high=d+T+(g>>>0<R>>>0?1:0),y=o.low=y+D,o.high=v+I+(y>>>0<D>>>0?1:0),S=u.low=S+O,u.high=m+N+(S>>>0<O>>>0?1:0),F=c.low=F+L,c.high=b+j+(F>>>0<L>>>0?1:0),_=f.low=_+B,f.high=w+M+(_>>>0<B>>>0?1:0),E=h.low=E+U,h.high=x+H+(E>>>0<U>>>0?1:0),P=n.low=P+K,n.high=A+V+(P>>>0<K>>>0?1:0)},_doFinalize:function(){var t=this._data,e=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return e[r>>>5]|=128<<24-r%32,e[(r+128>>>10<<5)+30]=Math.floor(n/4294967296),e[(r+128>>>10<<5)+31]=n,t.sigBytes=4*e.length,this._process(),this._hash.toX32()},clone:function(){var t=n.clone.call(this);return t._hash=this._hash.clone(),t},blockSize:32}),e.SHA512=n._createHelper(r),e.HmacSHA512=n._createHmacHelper(r)}(),function(){var t=Vn,e=t.x64,n=e.Word,r=e.WordArray,e=t.algo,i=e.SHA512,e=e.SHA384=i.extend({_doReset:function(){this._hash=new r.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var t=i._doFinalize.call(this);return t.sigBytes-=16,t}});t.SHA384=i._createHelper(e),t.HmacSHA384=i._createHmacHelper(e)}();/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ */ var Kn,qn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Wn="=",Jn=0xdeadbeefcafe,Gn=15715070==(16777215&Jn);Gn&&"Microsoft Internet Explorer"==Bn.appName?(o.prototype.am=u,Kn=30):Gn&&"Netscape"!=Bn.appName?(o.prototype.am=a,Kn=26):(o.prototype.am=c,Kn=28),o.prototype.DB=Kn,o.prototype.DM=(1<<Kn)-1,o.prototype.DV=1<<Kn;var zn=52;o.prototype.FV=Math.pow(2,zn),o.prototype.F1=zn-Kn,o.prototype.F2=2*Kn-zn;var Yn,$n,Xn="0123456789abcdefghijklmnopqrstuvwxyz",Zn=new Array;for(Yn="0".charCodeAt(0),$n=0;$n<=9;++$n)Zn[Yn++]=$n;for(Yn="a".charCodeAt(0),$n=10;$n<36;++$n)Zn[Yn++]=$n;for(Yn="A".charCodeAt(0),$n=10;$n<36;++$n)Zn[Yn++]=$n;I.prototype.convert=D,I.prototype.revert=N,I.prototype.reduce=O,I.prototype.mulTo=j,I.prototype.sqrTo=L,B.prototype.convert=H,B.prototype.revert=U,B.prototype.reduce=V,B.prototype.mulTo=q,B.prototype.sqrTo=K,o.prototype.copyTo=l,o.prototype.fromInt=p,o.prototype.fromString=g,o.prototype.clamp=v,o.prototype.dlShiftTo=_,o.prototype.drShiftTo=x,o.prototype.lShiftTo=E,o.prototype.rShiftTo=A,o.prototype.subTo=P,o.prototype.multiplyTo=C,o.prototype.squareTo=k,o.prototype.divRemTo=T,o.prototype.invDigit=M,o.prototype.isEven=W,o.prototype.exp=J,o.prototype.toString=y,o.prototype.negate=m,o.prototype.abs=S,o.prototype.compareTo=b,o.prototype.bitLength=w,o.prototype.mod=R,o.prototype.modPowInt=G,o.ZERO=d(0),o.ONE=d(1),Mt.prototype.convert=Bt,Mt.prototype.revert=Bt,Mt.prototype.mulTo=Ht,Mt.prototype.sqrTo=Ut,Wt.prototype.convert=Jt,Wt.prototype.revert=Gt,Wt.prototype.reduce=zt,Wt.prototype.mulTo=$t,Wt.prototype.sqrTo=Yt;var Qn=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997],tr=(1<<26)/Qn[Qn.length-1];o.prototype.chunkSize=Z,o.prototype.toRadix=tt,o.prototype.fromRadix=et,o.prototype.fromNumber=nt,o.prototype.bitwiseTo=at,o.prototype.changeBit=xt,o.prototype.addTo=Ct,o.prototype.dMultiply=jt,o.prototype.dAddOffset=Lt,o.prototype.multiplyLowerTo=Kt,o.prototype.multiplyUpperTo=qt,o.prototype.modInt=Qt,o.prototype.millerRabin=ne,o.prototype.clone=z,o.prototype.intValue=Y,o.prototype.byteValue=$,o.prototype.shortValue=X,o.prototype.signum=Q,o.prototype.toByteArray=rt,o.prototype.equals=it,o.prototype.min=ot,o.prototype.max=st,o.prototype.and=ct,o.prototype.or=ht,o.prototype.xor=pt,o.prototype.andNot=gt,o.prototype.not=vt,o.prototype.shiftLeft=yt,o.prototype.shiftRight=mt,o.prototype.getLowestSetBit=bt,o.prototype.bitCount=wt,o.prototype.testBit=_t,o.prototype.setBit=Et,o.prototype.clearBit=At,o.prototype.flipBit=Pt,o.prototype.add=kt,o.prototype.subtract=Tt,o.prototype.multiply=Rt,o.prototype.divide=Dt,o.prototype.remainder=Nt,o.prototype.divideAndRemainder=Ot,o.prototype.modPow=Xt,o.prototype.modInverse=te,o.prototype.pow=Vt,o.prototype.gcd=Zt,o.prototype.isProbablePrime=ee,o.prototype.square=It,re.prototype.init=ie,re.prototype.next=oe;var er,nr,rr,ir=256;if(null==nr){nr=new Array,rr=0;var or;if(void 0!==Hn&&(void 0!==Hn.crypto||void 0!==Hn.msCrypto)){var sr=Hn.crypto||Hn.msCrypto;if(sr.getRandomValues){var ar=new Uint8Array(32);for(sr.getRandomValues(ar),or=0;or<32;++or)nr[rr++]=ar[or]}else if("Netscape"==Bn.appName&&Bn.appVersion<"5"){var ur=Hn.crypto.random(32);for(or=0;or<ur.length;++or)nr[rr++]=255&ur.charCodeAt(or)}}for(;rr<ir;)or=Math.floor(65536*Math.random()),nr[rr++]=or>>>8,nr[rr++]=255&or;rr=0,ue()}he.prototype.nextBytes=fe,ve.prototype.doPublic=me,ve.prototype.setPublic=ye,ve.prototype.encrypt=Se,ve.prototype.encryptOAEP=be,ve.prototype.type="RSA",Fe.prototype.equals=we,Fe.prototype.toBigInteger=_e,Fe.prototype.negate=xe,Fe.prototype.add=Ee,Fe.prototype.subtract=Ae,Fe.prototype.multiply=Pe,Fe.prototype.square=Ce,Fe.prototype.divide=ke,Te.prototype.getX=Re,Te.prototype.getY=Ie,Te.prototype.equals=De,Te.prototype.isInfinity=Ne,Te.prototype.negate=Oe,Te.prototype.add=je,Te.prototype.twice=Le,Te.prototype.multiply=Me,Te.prototype.multiplyTwo=Be,He.prototype.getQ=Ue,He.prototype.getA=Ve,He.prototype.getB=Ke,He.prototype.equals=qe,He.prototype.getInfinity=We,He.prototype.fromBigInteger=Je,He.prototype.decodePointHex=Ge;/*! Mike Samuel (c) 2009 | code.google.com/p/json-sans-eval */ var cr=function(){function t(t,e,n){return e?s[e]:String.fromCharCode(parseInt(n,16))}var e="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",n='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))',r='(?:"'+n+'*")',i=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+e+"|"+r+")","g"),o=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),s={'"':'"',"/":"/","\\":"\\",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"},a=new String(""),u="\\",c=({"{":Object,"[":Array},Object.hasOwnProperty);return function(e,n){var r,s=e.match(i),f=s[0],h=!1;"{"===f?r={}:"["===f?r=[]:(r=[],h=!0);for(var l,p=[r],d=1-h,g=s.length;d<g;++d){f=s[d];var v;switch(f.charCodeAt(0)){default:v=p[0],v[l||v.length]=+f,l=void 0;break;case 34:if(f=f.substring(1,f.length-1),f.indexOf(u)!==-1&&(f=f.replace(o,t)),v=p[0],!l){if(!(v instanceof Array)){l=f||a;break}l=v.length}v[l]=f,l=void 0;break;case 91:v=p[0],p.unshift(v[l||v.length]=[]),l=void 0;break;case 93:p.shift();break;case 102:v=p[0],v[l||v.length]=!1,l=void 0;break;case 110:v=p[0],v[l||v.length]=null,l=void 0;break;case 116:v=p[0],v[l||v.length]=!0,l=void 0;break;case 123:v=p[0],p.unshift(v[l||v.length]={}),l=void 0;break;case 125:p.shift()}}if(h){if(1!==p.length)throw new Error;r=r[0]}else if(p.length)throw new Error;if(n){var y=function t(e,r){var i=e[r];if(i&&"object"===("undefined"==typeof i?"undefined":Mn(i))){var o=null;for(var s in i)if(c.call(i,s)&&i!==e){var a=t(i,s);void 0!==a?i[s]=a:(o||(o=[]),o.push(s))}if(o)for(var u=o.length;--u>=0;)delete i[o[u]]}return n.call(e,r,i)};r=y({"":r},"")}return r}}();"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.asn1&&hr.asn1||(hr.asn1={}),hr.asn1.ASN1Util=new function(){this.integerToByteHex=function(t){var e=t.toString(16);return e.length%2==1&&(e="0"+e),e},this.bigIntToMinTwosComplementsHex=function(t){var e=t.toString(16);if("-"!=e.substr(0,1))e.length%2==1?e="0"+e:e.match(/^[0-7]/)||(e="00"+e);else{var n=e.substr(1),r=n.length;r%2==1?r+=1:e.match(/^[0-7]/)||(r+=2);for(var i="",s=0;s<r;s++)i+="f";var a=new o(i,16),u=a.xor(t).add(o.ONE);e=u.toString(16).replace(/^-/,"")}return e},this.getPEMStringFromHex=function(t,e){return gn(t,e)},this.newObject=function(t){var e=hr,n=e.asn1,r=n.DERBoolean,i=n.DERInteger,o=n.DERBitString,s=n.DEROctetString,a=n.DERNull,u=n.DERObjectIdentifier,c=n.DEREnumerated,f=n.DERUTF8String,h=n.DERNumericString,l=n.DERPrintableString,p=n.DERTeletexString,d=n.DERIA5String,g=n.DERUTCTime,v=n.DERGeneralizedTime,y=n.DERSequence,m=n.DERSet,S=n.DERTaggedObject,b=n.ASN1Util.newObject,F=Object.keys(t);if(1!=F.length)throw"key of param shall be only one.";var w=F[0];if(":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":"+w+":")==-1)throw"undefined key: "+w;if("bool"==w)return new r(t[w]);if("int"==w)return new i(t[w]);if("bitstr"==w)return new o(t[w]);if("octstr"==w)return new s(t[w]);if("null"==w)return new a(t[w]);if("oid"==w)return new u(t[w]);if("enum"==w)return new c(t[w]);if("utf8str"==w)return new f(t[w]);if("numstr"==w)return new h(t[w]);if("prnstr"==w)return new l(t[w]);if("telstr"==w)return new p(t[w]);if("ia5str"==w)return new d(t[w]);if("utctime"==w)return new g(t[w]);if("gentime"==w)return new v(t[w]);if("seq"==w){for(var _=t[w],x=[],E=0;E<_.length;E++){var A=b(_[E]);x.push(A)}return new y({array:x})}if("set"==w){for(var _=t[w],x=[],E=0;E<_.length;E++){var A=b(_[E]);x.push(A)}return new m({array:x})}if("tag"==w){var P=t[w];if("[object Array]"===Object.prototype.toString.call(P)&&3==P.length){var C=b(P[2]);return new S({tag:P[0],explicit:P[1],obj:C})}var k={};if(void 0!==P.explicit&&(k.explicit=P.explicit),void 0!==P.tag&&(k.tag=P.tag),void 0===P.obj)throw"obj shall be specified for 'tag'.";return k.obj=b(P.obj),new S(k)}},this.jsonToASN1HEX=function(t){var e=this.newObject(t);return e.getEncodedHex()}},hr.asn1.ASN1Util.oidHexToInt=function(t){for(var e="",n=parseInt(t.substr(0,2),16),r=Math.floor(n/40),i=n%40,e=r+"."+i,s="",a=2;a<t.length;a+=2){var u=parseInt(t.substr(a,2),16),c=("00000000"+u.toString(2)).slice(-8);if(s+=c.substr(1,7),"0"==c.substr(0,1)){var f=new o(s,2);e=e+"."+f.toString(10),s=""}}return e},hr.asn1.ASN1Util.oidIntToHex=function(t){var e=function(t){var e=t.toString(16);return 1==e.length&&(e="0"+e),e},n=function(t){var n="",r=new o(t,10),i=r.toString(2),s=7-i.length%7;7==s&&(s=0);for(var a="",u=0;u<s;u++)a+="0";i=a+i;for(var u=0;u<i.length-1;u+=7){var c=i.substr(u,7);u!=i.length-7&&(c="1"+c),n+=e(parseInt(c,2))}return n};if(!t.match(/^[0-9.]+$/))throw"malformed oid string: "+t;var r="",i=t.split("."),s=40*parseInt(i[0])+parseInt(i[1]);r+=e(s),i.splice(0,2);for(var a=0;a<i.length;a++)r+=n(i[a]);return r},hr.asn1.ASN1Object=function(){var t="";this.getLengthHexFromValue=function(){if("undefined"==typeof this.hV||null==this.hV)throw"this.hV is null or undefined.";if(this.hV.length%2==1)throw"value hex must be even length: n="+t.length+",v="+this.hV;var e=this.hV.length/2,n=e.toString(16);if(n.length%2==1&&(n="0"+n),e<128)return n;var r=n.length/2;if(r>15)throw"ASN.1 length too long to represent by 8x: n = "+e.toString(16);var i=128+r;return i.toString(16)+n},this.getEncodedHex=function(){return(null==this.hTLV||this.isModified)&&(this.hV=this.getFreshValueHex(),this.hL=this.getLengthHexFromValue(),this.hTLV=this.hT+this.hL+this.hV,this.isModified=!1),this.hTLV},this.getValueHex=function(){return this.getEncodedHex(),this.hV},this.getFreshValueHex=function(){return""}},hr.asn1.DERAbstractString=function(t){hr.asn1.DERAbstractString.superclass.constructor.call(this);this.getString=function(){return this.s},this.setString=function(t){this.hTLV=null,this.isModified=!0,this.s=t,this.hV=un(this.s).toLowerCase()},this.setStringHex=function(t){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.getFreshValueHex=function(){return this.hV},"undefined"!=typeof t&&("string"==typeof t?this.setString(t):"undefined"!=typeof t.str?this.setString(t.str):"undefined"!=typeof t.hex&&this.setStringHex(t.hex))},Un.lang.extend(hr.asn1.DERAbstractString,hr.asn1.ASN1Object),hr.asn1.DERAbstractTime=function(t){hr.asn1.DERAbstractTime.superclass.constructor.call(this);this.localDateToUTC=function(t){utc=t.getTime()+6e4*t.getTimezoneOffset();var e=new Date(utc);return e},this.formatDate=function(t,e,n){var r=this.zeroPadding,i=this.localDateToUTC(t),o=String(i.getFullYear());"utc"==e&&(o=o.substr(2,2));var s=r(String(i.getMonth()+1),2),a=r(String(i.getDate()),2),u=r(String(i.getHours()),2),c=r(String(i.getMinutes()),2),f=r(String(i.getSeconds()),2),h=o+s+a+u+c+f;if(n===!0){var l=i.getMilliseconds();if(0!=l){var p=r(String(l),3);p=p.replace(/[0]+$/,""),h=h+"."+p}}return h+"Z"},this.zeroPadding=function(t,e){return t.length>=e?t:new Array(e-t.length+1).join("0")+t},this.getString=function(){return this.s},this.setString=function(t){this.hTLV=null,this.isModified=!0,this.s=t,this.hV=Xe(t)},this.setByDateValue=function(t,e,n,r,i,o){var s=new Date(Date.UTC(t,e-1,n,r,i,o,0));this.setByDate(s)},this.getFreshValueHex=function(){return this.hV}},Un.lang.extend(hr.asn1.DERAbstractTime,hr.asn1.ASN1Object),hr.asn1.DERAbstractStructured=function(t){hr.asn1.DERAbstractString.superclass.constructor.call(this);this.setByASN1ObjectArray=function(t){this.hTLV=null,this.isModified=!0,this.asn1Array=t},this.appendASN1Object=function(t){this.hTLV=null,this.isModified=!0,this.asn1Array.push(t)},this.asn1Array=new Array,"undefined"!=typeof t&&"undefined"!=typeof t.array&&(this.asn1Array=t.array)},Un.lang.extend(hr.asn1.DERAbstractStructured,hr.asn1.ASN1Object),hr.asn1.DERBoolean=function(){hr.asn1.DERBoolean.superclass.constructor.call(this),this.hT="01",this.hTLV="0101ff"},Un.lang.extend(hr.asn1.DERBoolean,hr.asn1.ASN1Object),hr.asn1.DERInteger=function(t){hr.asn1.DERInteger.superclass.constructor.call(this),this.hT="02",this.setByBigInteger=function(t){this.hTLV=null,this.isModified=!0,this.hV=hr.asn1.ASN1Util.bigIntToMinTwosComplementsHex(t)},this.setByInteger=function(t){var e=new o(String(t),10);this.setByBigInteger(e)},this.setValueHex=function(t){this.hV=t},this.getFreshValueHex=function(){return this.hV},"undefined"!=typeof t&&("undefined"!=typeof t.bigint?this.setByBigInteger(t.bigint):"undefined"!=typeof t.int?this.setByInteger(t.int):"number"==typeof t?this.setByInteger(t):"undefined"!=typeof t.hex&&this.setValueHex(t.hex))},Un.lang.extend(hr.asn1.DERInteger,hr.asn1.ASN1Object),hr.asn1.DERBitString=function(t){if(void 0!==t&&"undefined"!=typeof t.obj){var e=hr.asn1.ASN1Util.newObject(t.obj);t.hex="00"+e.getEncodedHex()}hr.asn1.DERBitString.superclass.constructor.call(this),this.hT="03",this.setHexValueIncludingUnusedBits=function(t){this.hTLV=null,this.isModified=!0,this.hV=t},this.setUnusedBitsAndHexValue=function(t,e){if(t<0||7<t)throw"unused bits shall be from 0 to 7: u = "+t;var n="0"+t;this.hTLV=null,this.isModified=!0,this.hV=n+e},this.setByBinaryString=function(t){t=t.replace(/0+$/,"");var e=8-t.length%8;8==e&&(e=0);for(var n=0;n<=e;n++)t+="0";for(var r="",n=0;n<t.length-1;n+=8){var i=t.substr(n,8),o=parseInt(i,2).toString(16);1==o.length&&(o="0"+o),r+=o}this.hTLV=null,this.isModified=!0,this.hV="0"+e+r},this.setByBooleanArray=function(t){for(var e="",n=0;n<t.length;n++)e+=1==t[n]?"1":"0";this.setByBinaryString(e)},this.newFalseArray=function(t){for(var e=new Array(t),n=0;n<t;n++)e[n]=!1;return e},this.getFreshValueHex=function(){return this.hV},"undefined"!=typeof t&&("string"==typeof t&&t.toLowerCase().match(/^[0-9a-f]+$/)?this.setHexValueIncludingUnusedBits(t):"undefined"!=typeof t.hex?this.setHexValueIncludingUnusedBits(t.hex):"undefined"!=typeof t.bin?this.setByBinaryString(t.bin):"undefined"!=typeof t.array&&this.setByBooleanArray(t.array))},Un.lang.extend(hr.asn1.DERBitString,hr.asn1.ASN1Object),hr.asn1.DEROctetString=function(t){if(void 0!==t&&"undefined"!=typeof t.obj){var e=hr.asn1.ASN1Util.newObject(t.obj);t.hex=e.getEncodedHex()}hr.asn1.DEROctetString.superclass.constructor.call(this,t),this.hT="04"},Un.lang.extend(hr.asn1.DEROctetString,hr.asn1.DERAbstractString),hr.asn1.DERNull=function(){hr.asn1.DERNull.superclass.constructor.call(this),this.hT="05",this.hTLV="0500"},Un.lang.extend(hr.asn1.DERNull,hr.asn1.ASN1Object),hr.asn1.DERObjectIdentifier=function(t){var e=function(t){var e=t.toString(16);return 1==e.length&&(e="0"+e),e},n=function(t){var n="",r=new o(t,10),i=r.toString(2),s=7-i.length%7;7==s&&(s=0);for(var a="",u=0;u<s;u++)a+="0";i=a+i;for(var u=0;u<i.length-1;u+=7){var c=i.substr(u,7);u!=i.length-7&&(c="1"+c),n+=e(parseInt(c,2))}return n};hr.asn1.DERObjectIdentifier.superclass.constructor.call(this),this.hT="06",this.setValueHex=function(t){this.hTLV=null,this.isModified=!0,this.s=null,this.hV=t},this.setValueOidString=function(t){if(!t.match(/^[0-9.]+$/))throw"malformed oid string: "+t;var r="",i=t.split("."),o=40*parseInt(i[0])+parseInt(i[1]);r+=e(o),i.splice(0,2);for(var s=0;s<i.length;s++)r+=n(i[s]);this.hTLV=null,this.isModified=!0,this.s=null,this.hV=r},this.setValueName=function(t){var e=hr.asn1.x509.OID.name2oid(t);if(""===e)throw"DERObjectIdentifier oidName undefined: "+t;this.setValueOidString(e)},this.getFreshValueHex=function(){return this.hV},void 0!==t&&("string"==typeof t?t.match(/^[0-2].[0-9.]+$/)?this.setValueOidString(t):this.setValueName(t):void 0!==t.oid?this.setValueOidString(t.oid):void 0!==t.hex?this.setValueHex(t.hex):void 0!==t.name&&this.setValueName(t.name))},Un.lang.extend(hr.asn1.DERObjectIdentifier,hr.asn1.ASN1Object),hr.asn1.DEREnumerated=function(t){hr.asn1.DEREnumerated.superclass.constructor.call(this),this.hT="0a",this.setByBigInteger=function(t){this.hTLV=null,this.isModified=!0,this.hV=hr.asn1.ASN1Util.bigIntToMinTwosComplementsHex(t)},this.setByInteger=function(t){var e=new o(String(t),10);this.setByBigInteger(e)},this.setValueHex=function(t){this.hV=t},this.getFreshValueHex=function(){return this.hV},"undefined"!=typeof t&&("undefined"!=typeof t.int?this.setByInteger(t.int):"number"==typeof t?this.setByInteger(t):"undefined"!=typeof t.hex&&this.setValueHex(t.hex))},Un.lang.extend(hr.asn1.DEREnumerated,hr.asn1.ASN1Object),hr.asn1.DERUTF8String=function(t){hr.asn1.DERUTF8String.superclass.constructor.call(this,t),this.hT="0c"},Un.lang.extend(hr.asn1.DERUTF8String,hr.asn1.DERAbstractString),hr.asn1.DERNumericString=function(t){hr.asn1.DERNumericString.superclass.constructor.call(this,t),this.hT="12"},Un.lang.extend(hr.asn1.DERNumericString,hr.asn1.DERAbstractString),hr.asn1.DERPrintableString=function(t){hr.asn1.DERPrintableString.superclass.constructor.call(this,t),this.hT="13"},Un.lang.extend(hr.asn1.DERPrintableString,hr.asn1.DERAbstractString),hr.asn1.DERTeletexString=function(t){hr.asn1.DERTeletexString.superclass.constructor.call(this,t),this.hT="14"},Un.lang.extend(hr.asn1.DERTeletexString,hr.asn1.DERAbstractString),hr.asn1.DERIA5String=function(t){hr.asn1.DERIA5String.superclass.constructor.call(this,t),this.hT="16"},Un.lang.extend(hr.asn1.DERIA5String,hr.asn1.DERAbstractString),hr.asn1.DERUTCTime=function(t){hr.asn1.DERUTCTime.superclass.constructor.call(this,t),this.hT="17",this.setByDate=function(t){this.hTLV=null,this.isModified=!0,this.date=t,this.s=this.formatDate(this.date,"utc"),this.hV=Xe(this.s)},this.getFreshValueHex=function(){return"undefined"==typeof this.date&&"undefined"==typeof this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"utc"),this.hV=Xe(this.s)),this.hV},void 0!==t&&(void 0!==t.str?this.setString(t.str):"string"==typeof t&&t.match(/^[0-9]{12}Z$/)?this.setString(t):void 0!==t.hex?this.setStringHex(t.hex):void 0!==t.date&&this.setByDate(t.date))},Un.lang.extend(hr.asn1.DERUTCTime,hr.asn1.DERAbstractTime),hr.asn1.DERGeneralizedTime=function(t){hr.asn1.DERGeneralizedTime.superclass.constructor.call(this,t),this.hT="18",this.withMillis=!1,this.setByDate=function(t){this.hTLV=null,this.isModified=!0,this.date=t,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=Xe(this.s)},this.getFreshValueHex=function(){return void 0===this.date&&void 0===this.s&&(this.date=new Date,this.s=this.formatDate(this.date,"gen",this.withMillis),this.hV=Xe(this.s)),this.hV},void 0!==t&&(void 0!==t.str?this.setString(t.str):"string"==typeof t&&t.match(/^[0-9]{14}Z$/)?this.setString(t):void 0!==t.hex?this.setStringHex(t.hex):void 0!==t.date&&this.setByDate(t.date),t.millis===!0&&(this.withMillis=!0))},Un.lang.extend(hr.asn1.DERGeneralizedTime,hr.asn1.DERAbstractTime),hr.asn1.DERSequence=function(t){hr.asn1.DERSequence.superclass.constructor.call(this,t),this.hT="30",this.getFreshValueHex=function(){for(var t="",e=0;e<this.asn1Array.length;e++){var n=this.asn1Array[e];t+=n.getEncodedHex()}return this.hV=t,this.hV}},Un.lang.extend(hr.asn1.DERSequence,hr.asn1.DERAbstractStructured),hr.asn1.DERSet=function(t){hr.asn1.DERSet.superclass.constructor.call(this,t),this.hT="31",this.sortFlag=!0,this.getFreshValueHex=function(){for(var t=new Array,e=0;e<this.asn1Array.length;e++){var n=this.asn1Array[e];t.push(n.getEncodedHex())}return 1==this.sortFlag&&t.sort(),this.hV=t.join(""),this.hV},"undefined"!=typeof t&&"undefined"!=typeof t.sortflag&&0==t.sortflag&&(this.sortFlag=!1)},Un.lang.extend(hr.asn1.DERSet,hr.asn1.DERAbstractStructured),hr.asn1.DERTaggedObject=function(t){hr.asn1.DERTaggedObject.superclass.constructor.call(this),this.hT="a0",this.hV="",this.isExplicit=!0,this.asn1Object=null,this.setASN1Object=function(t,e,n){this.hT=e,this.isExplicit=t,this.asn1Object=n,this.isExplicit?(this.hV=this.asn1Object.getEncodedHex(),this.hTLV=null,this.isModified=!0):(this.hV=null,this.hTLV=n.getEncodedHex(),this.hTLV=this.hTLV.replace(/^../,e),this.isModified=!1)},this.getFreshValueHex=function(){return this.hV},"undefined"!=typeof t&&("undefined"!=typeof t.tag&&(this.hT=t.tag),"undefined"!=typeof t.explicit&&(this.isExplicit=t.explicit),"undefined"!=typeof t.obj&&(this.asn1Object=t.obj,this.setASN1Object(this.isExplicit,this.hT,this.asn1Object)))},Un.lang.extend(hr.asn1.DERTaggedObject,hr.asn1.ASN1Object);var fr=new function(){};fr.getLblen=function(t,e){if("8"!=t.substr(e+2,1))return 1;var n=parseInt(t.substr(e+3,1));return 0==n?-1:0<n&&n<10?n+1:-2},fr.getL=function(t,e){var n=fr.getLblen(t,e);return n<1?"":t.substr(e+2,2*n)},fr.getVblen=function(t,e){var n,r;return n=fr.getL(t,e),""==n?-1:(r="8"===n.substr(0,1)?new o(n.substr(2),16):new o(n,16),r.intValue())},fr.getVidx=function(t,e){var n=fr.getLblen(t,e);return n<0?n:e+2*(n+1)},fr.getV=function(t,e){var n=fr.getVidx(t,e),r=fr.getVblen(t,e);return t.substr(n,2*r)},fr.getTLV=function(t,e){return t.substr(e,2)+fr.getL(t,e)+fr.getV(t,e)},fr.getNextSiblingIdx=function(t,e){var n=fr.getVidx(t,e),r=fr.getVblen(t,e);return n+2*r},fr.getChildIdx=function(t,e){var n=fr,r=new Array,i=n.getVidx(t,e);"03"==t.substr(e,2)?r.push(i+2):r.push(i);for(var o=n.getVblen(t,e),s=i,a=0;;){var u=n.getNextSiblingIdx(t,s);if(null==u||u-i>=2*o)break;if(a>=200)break;r.push(u),s=u,a++}return r},fr.getNthChildIdx=function(t,e,n){var r=fr.getChildIdx(t,e);return r[n]},fr.getIdxbyList=function(t,e,n,r){var i,o,s=fr;if(0==n.length){if(void 0!==r&&t.substr(e,2)!==r)throw"checking tag doesn't match: "+t.substr(e,2)+"!="+r;return e}return i=n.shift(),o=s.getChildIdx(t,e),s.getIdxbyList(t,o[i],n,r)},fr.getTLVbyList=function(t,e,n,r){var i=fr,o=i.getIdxbyList(t,e,n);if(void 0===o)throw"can't find nthList object";if(void 0!==r&&t.substr(o,2)!=r)throw"checking tag doesn't match: "+t.substr(o,2)+"!="+r;return i.getTLV(t,o)},fr.getVbyList=function(t,e,n,r,i){var o,s,a=fr;if(o=a.getIdxbyList(t,e,n,r),void 0===o)throw"can't find nthList object";return s=a.getV(t,o),i===!0&&(s=s.substr(2)),s},fr.hextooidstr=function(t){var e=function(t,e){return t.length>=e?t:new Array(e-t.length+1).join("0")+t},n=[],r=t.substr(0,2),i=parseInt(r,16);n[0]=new String(Math.floor(i/40)),n[1]=new String(i%40);for(var o=t.substr(2),s=[],a=0;a<o.length/2;a++)s.push(parseInt(o.substr(2*a,2),16));for(var u=[],c="",a=0;a<s.length;a++)128&s[a]?c+=e((127&s[a]).toString(2),7):(c+=e((127&s[a]).toString(2),7),u.push(new String(parseInt(c,2))),c="");var f=n.join(".");return u.length>0&&(f=f+"."+u.join(".")),f},fr.dump=function(t,e,n,r){var i=fr,o=i.getV,s=i.dump,a=i.getChildIdx,u=t;t instanceof hr.asn1.ASN1Object&&(u=t.getEncodedHex());var c=function(t,e){if(t.length<=2*e)return t;var n=t.substr(0,e)+"..(total "+t.length/2+"bytes).."+t.substr(t.length-e,e);return n};void 0===e&&(e={ommit_long_octet:32}),void 0===n&&(n=0),void 0===r&&(r="");var f=e.ommit_long_octet;if("01"==u.substr(n,2)){var h=o(u,n);return"00"==h?r+"BOOLEAN FALSE\n":r+"BOOLEAN TRUE\n"}if("02"==u.substr(n,2)){var h=o(u,n);return r+"INTEGER "+c(h,f)+"\n"}if("03"==u.substr(n,2)){var h=o(u,n);return r+"BITSTRING "+c(h,f)+"\n"}if("04"==u.substr(n,2)){var h=o(u,n);if(i.isASN1HEX(h)){var l=r+"OCTETSTRING, encapsulates\n";return l+=s(h,e,0,r+" ")}return r+"OCTETSTRING "+c(h,f)+"\n"}if("05"==u.substr(n,2))return r+"NULL\n";if("06"==u.substr(n,2)){var p=o(u,n),d=hr.asn1.ASN1Util.oidHexToInt(p),g=hr.asn1.x509.OID.oid2name(d),v=d.replace(/\./g," ");return""!=g?r+"ObjectIdentifier "+g+" ("+v+")\n":r+"ObjectIdentifier ("+v+")\n"}if("0c"==u.substr(n,2))return r+"UTF8String '"+cn(o(u,n))+"'\n";if("13"==u.substr(n,2))return r+"PrintableString '"+cn(o(u,n))+"'\n";if("14"==u.substr(n,2))return r+"TeletexString '"+cn(o(u,n))+"'\n";if("16"==u.substr(n,2))return r+"IA5String '"+cn(o(u,n))+"'\n";if("17"==u.substr(n,2))return r+"UTCTime "+cn(o(u,n))+"\n";if("18"==u.substr(n,2))return r+"GeneralizedTime "+cn(o(u,n))+"\n";if("30"==u.substr(n,2)){if("3000"==u.substr(n,4))return r+"SEQUENCE {}\n";var l=r+"SEQUENCE\n",y=a(u,n),m=e;if((2==y.length||3==y.length)&&"06"==u.substr(y[0],2)&&"04"==u.substr(y[y.length-1],2)){var g=i.oidname(o(u,y[0])),S=JSON.parse(JSON.stringify(e));S.x509ExtName=g,m=S}for(var b=0;b<y.length;b++)l+=s(u,m,y[b],r+" ");return l}if("31"==u.substr(n,2)){for(var l=r+"SET\n",y=a(u,n),b=0;b<y.length;b++)l+=s(u,e,y[b],r+" ");return l}var F=parseInt(u.substr(n,2),16);if(0!=(128&F)){var w=31&F;if(0!=(32&F)){for(var l=r+"["+w+"]\n",y=a(u,n),b=0;b<y.length;b++)l+=s(u,e,y[b],r+" ");return l}var h=o(u,n);"68747470"==h.substr(0,8)&&(h=cn(h)),"subjectAltName"===e.x509ExtName&&2==w&&(h=cn(h));var l=r+"["+w+"] "+h+"\n";return l}return r+"UNKNOWN("+u.substr(n,2)+") "+o(u,n)+"\n"},fr.isASN1HEX=function(t){var e=fr;if(t.length%2==1)return!1;var n=e.getVblen(t,0),r=t.substr(0,2),i=e.getL(t,0),o=t.length-r.length-i.length;return o==2*n},fr.oidname=function(t){var e=hr.asn1;hr.lang.String.isHex(t)&&(t=e.ASN1Util.oidHexToInt(t));var n=e.x509.OID.oid2name(t);return""===n&&(n=t),n},"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.asn1&&hr.asn1||(hr.asn1={}),"undefined"!=typeof hr.asn1.x509&&hr.asn1.x509||(hr.asn1.x509={}),hr.asn1.x509.Certificate=function(t){hr.asn1.x509.Certificate.superclass.constructor.call(this);var e=hr,n=(e.crypto,e.asn1),r=n.DERSequence,i=n.DERBitString;this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg;var t=new hr.crypto.Signature({alg:this.asn1SignatureAlg.nameAlg});t.init(this.prvKey),t.updateHex(this.asn1TBSCert.getEncodedHex()),this.hexSig=t.sign(),this.asn1Sig=new i({hex:"00"+this.hexSig});var e=new r({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=e.getEncodedHex(),this.isModified=!1},this.setSignatureHex=function(t){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg,this.hexSig=t,this.asn1Sig=new i({hex:"00"+this.hexSig});var e=new r({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=e.getEncodedHex(),this.isModified=!1},this.getEncodedHex=function(){if(0==this.isModified&&null!=this.hTLV)return this.hTLV;throw"not signed yet"},this.getPEMString=function(){var t=pn(this.getEncodedHex());return"-----BEGIN CERTIFICATE-----\r\n"+t+"\r\n-----END CERTIFICATE-----\r\n"},void 0!==t&&(void 0!==t.tbscertobj&&(this.asn1TBSCert=t.tbscertobj),void 0!==t.prvkeyobj&&(this.prvKey=t.prvkeyobj))},Un.lang.extend(hr.asn1.x509.Certificate,hr.asn1.ASN1Object),hr.asn1.x509.TBSCertificate=function(t){hr.asn1.x509.TBSCertificate.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERSequence,i=n.DERInteger,o=n.DERTaggedObject,s=n.x509,a=s.Time,u=s.X500Name,c=s.SubjectPublicKeyInfo;this._initialize=function(){this.asn1Array=new Array,this.asn1Version=new o({obj:new i({int:2})}),this.asn1SerialNumber=null,this.asn1SignatureAlg=null,this.asn1Issuer=null,this.asn1NotBefore=null,this.asn1NotAfter=null,this.asn1Subject=null,this.asn1SubjPKey=null,this.extensionsArray=new Array},this.setSerialNumberByParam=function(t){this.asn1SerialNumber=new i(t)},this.setSignatureAlgByParam=function(t){this.asn1SignatureAlg=new s.AlgorithmIdentifier(t)},this.setIssuerByParam=function(t){this.asn1Issuer=new u(t)},this.setNotBeforeByParam=function(t){this.asn1NotBefore=new a(t)},this.setNotAfterByParam=function(t){this.asn1NotAfter=new a(t)},this.setSubjectByParam=function(t){this.asn1Subject=new u(t)},this.setSubjectPublicKey=function(t){this.asn1SubjPKey=new c(t)},this.setSubjectPublicKeyByGetKey=function(t){var e=gr.getKey(t);this.asn1SubjPKey=new c(e)},this.appendExtension=function(t){this.extensionsArray.push(t)},this.appendExtensionByName=function(t,e){hr.asn1.x509.Extension.appendByNameToArray(t,e,this.extensionsArray)},this.getEncodedHex=function(){if(null==this.asn1NotBefore||null==this.asn1NotAfter)throw"notBefore and/or notAfter not set";var t=new r({array:[this.asn1NotBefore,this.asn1NotAfter]});if(this.asn1Array=new Array,this.asn1Array.push(this.asn1Version),this.asn1Array.push(this.asn1SerialNumber),this.asn1Array.push(this.asn1SignatureAlg),this.asn1Array.push(this.asn1Issuer),this.asn1Array.push(t),this.asn1Array.push(this.asn1Subject),this.asn1Array.push(this.asn1SubjPKey),this.extensionsArray.length>0){var e=new r({array:this.extensionsArray}),n=new o({explicit:!0,tag:"a3",obj:e});this.asn1Array.push(n)}var i=new r({array:this.asn1Array});return this.hTLV=i.getEncodedHex(),this.isModified=!1,this.hTLV},this._initialize()},Un.lang.extend(hr.asn1.x509.TBSCertificate,hr.asn1.ASN1Object),hr.asn1.x509.Extension=function(t){hr.asn1.x509.Extension.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERObjectIdentifier,i=n.DEROctetString,o=(n.DERBitString,n.DERBoolean),s=n.DERSequence;this.getEncodedHex=function(){var t=new r({oid:this.oid}),e=new i({hex:this.getExtnValueHex()}),n=new Array;n.push(t),this.critical&&n.push(new o),n.push(e);var a=new s({array:n});return a.getEncodedHex()},this.critical=!1,void 0!==t&&void 0!==t.critical&&(this.critical=t.critical)},Un.lang.extend(hr.asn1.x509.Extension,hr.asn1.ASN1Object),hr.asn1.x509.Extension.appendByNameToArray=function(t,e,n){var r=t.toLowerCase(),i=hr.asn1.x509;if("basicconstraints"==r){var o=new i.BasicConstraints(e);n.push(o)}else if("keyusage"==r){var o=new i.KeyUsage(e);n.push(o)}else if("crldistributionpoints"==r){var o=new i.CRLDistributionPoints(e);n.push(o)}else if("extkeyusage"==r){var o=new i.ExtKeyUsage(e);n.push(o)}else if("authoritykeyidentifier"==r){var o=new i.AuthorityKeyIdentifier(e);n.push(o)}else if("authorityinfoaccess"==r){var o=new i.AuthorityInfoAccess(e);n.push(o)}else if("subjectaltname"==r){var o=new i.SubjectAltName(e);n.push(o)}else{if("issueraltname"!=r)throw"unsupported extension name: "+t;var o=new i.IssuerAltName(e);n.push(o)}},hr.asn1.x509.KeyUsage=function(t){hr.asn1.x509.KeyUsage.superclass.constructor.call(this,t);var e=Ln.KEYUSAGE_NAME;if(this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.oid="2.5.29.15",void 0!==t&&(void 0!==t.bin&&(this.asn1ExtnValue=new hr.asn1.DERBitString(t)),void 0!==t.names&&void 0!==t.names.length)){for(var n=t.names,r="000000000",i=0;i<n.length;i++)for(var o=0;o<e.length;o++)n[i]===e[o]&&(r=r.substring(0,o)+"1"+r.substring(o+1,r.length));this.asn1ExtnValue=new hr.asn1.DERBitString({bin:r})}},Un.lang.extend(hr.asn1.x509.KeyUsage,hr.asn1.x509.Extension),hr.asn1.x509.BasicConstraints=function(t){hr.asn1.x509.BasicConstraints.superclass.constructor.call(this,t);this.getExtnValueHex=function(){var t=new Array;this.cA&&t.push(new hr.asn1.DERBoolean),this.pathLen>-1&&t.push(new hr.asn1.DERInteger({int:this.pathLen}));var e=new hr.asn1.DERSequence({array:t});return this.asn1ExtnValue=e,this.asn1ExtnValue.getEncodedHex()},this.oid="2.5.29.19",this.cA=!1,this.pathLen=-1,void 0!==t&&(void 0!==t.cA&&(this.cA=t.cA),void 0!==t.pathLen&&(this.pathLen=t.pathLen))},Un.lang.extend(hr.asn1.x509.BasicConstraints,hr.asn1.x509.Extension),hr.asn1.x509.CRLDistributionPoints=function(t){hr.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,t);var e=hr,n=e.asn1,r=n.x509;this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.setByDPArray=function(t){this.asn1ExtnValue=new n.DERSequence({array:t})},this.setByOneURI=function(t){var e=new r.GeneralNames([{uri:t}]),n=new r.DistributionPointName(e),i=new r.DistributionPoint({dpobj:n});this.setByDPArray([i])},this.oid="2.5.29.31",void 0!==t&&(void 0!==t.array?this.setByDPArray(t.array):void 0!==t.uri&&this.setByOneURI(t.uri))},Un.lang.extend(hr.asn1.x509.CRLDistributionPoints,hr.asn1.x509.Extension),hr.asn1.x509.ExtKeyUsage=function(t){hr.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,t);var e=hr,n=e.asn1;this.setPurposeArray=function(t){this.asn1ExtnValue=new n.DERSequence;for(var e=0;e<t.length;e++){var r=new n.DERObjectIdentifier(t[e]);this.asn1ExtnValue.appendASN1Object(r)}},this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.oid="2.5.29.37",void 0!==t&&void 0!==t.array&&this.setPurposeArray(t.array)},Un.lang.extend(hr.asn1.x509.ExtKeyUsage,hr.asn1.x509.Extension),hr.asn1.x509.AuthorityKeyIdentifier=function(t){hr.asn1.x509.AuthorityKeyIdentifier.superclass.constructor.call(this,t);var e=hr,n=e.asn1,r=n.DERTaggedObject;this.asn1KID=null,this.asn1CertIssuer=null,this.asn1CertSN=null,this.getExtnValueHex=function(){var t=new Array;this.asn1KID&&t.push(new r({explicit:!1,tag:"80",obj:this.asn1KID})),this.asn1CertIssuer&&t.push(new r({explicit:!1,tag:"a1",obj:this.asn1CertIssuer})),this.asn1CertSN&&t.push(new r({explicit:!1,tag:"82",obj:this.asn1CertSN}));var e=new n.DERSequence({array:t});return this.asn1ExtnValue=e,this.asn1ExtnValue.getEncodedHex()},this.setKIDByParam=function(t){this.asn1KID=new hr.asn1.DEROctetString(t)},this.setCertIssuerByParam=function(t){this.asn1CertIssuer=new hr.asn1.x509.X500Name(t)},this.setCertSNByParam=function(t){this.asn1CertSN=new hr.asn1.DERInteger(t)},this.oid="2.5.29.35",void 0!==t&&(void 0!==t.kid&&this.setKIDByParam(t.kid),void 0!==t.issuer&&this.setCertIssuerByParam(t.issuer),void 0!==t.sn&&this.setCertSNByParam(t.sn))},Un.lang.extend(hr.asn1.x509.AuthorityKeyIdentifier,hr.asn1.x509.Extension),hr.asn1.x509.AuthorityInfoAccess=function(t){hr.asn1.x509.AuthorityInfoAccess.superclass.constructor.call(this,t),this.setAccessDescriptionArray=function(t){for(var e=new Array,n=hr,r=n.asn1,i=r.DERSequence,o=0;o<t.length;o++){var s=new r.DERObjectIdentifier(t[o].accessMethod),a=new r.x509.GeneralName(t[o].accessLocation),u=new i({array:[s,a]});e.push(u)}this.asn1ExtnValue=new i({array:e})},this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.oid="1.3.6.1.5.5.7.1.1",void 0!==t&&void 0!==t.array&&this.setAccessDescriptionArray(t.array)},Un.lang.extend(hr.asn1.x509.AuthorityInfoAccess,hr.asn1.x509.Extension),hr.asn1.x509.SubjectAltName=function(t){hr.asn1.x509.SubjectAltName.superclass.constructor.call(this,t),this.setNameArray=function(t){this.asn1ExtnValue=new hr.asn1.x509.GeneralNames(t)},this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.oid="2.5.29.17",void 0!==t&&void 0!==t.array&&this.setNameArray(t.array)},Un.lang.extend(hr.asn1.x509.SubjectAltName,hr.asn1.x509.Extension),hr.asn1.x509.IssuerAltName=function(t){hr.asn1.x509.IssuerAltName.superclass.constructor.call(this,t),this.setNameArray=function(t){this.asn1ExtnValue=new hr.asn1.x509.GeneralNames(t)},this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()},this.oid="2.5.29.18",void 0!==t&&void 0!==t.array&&this.setNameArray(t.array)},Un.lang.extend(hr.asn1.x509.IssuerAltName,hr.asn1.x509.Extension),hr.asn1.x509.CRL=function(t){hr.asn1.x509.CRL.superclass.constructor.call(this);this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCertList.asn1SignatureAlg,sig=new hr.crypto.Signature({alg:"SHA1withRSA",prov:"cryptojs/jsrsa"}),sig.init(this.prvKey),sig.updateHex(this.asn1TBSCertList.getEncodedHex()),this.hexSig=sig.sign(),this.asn1Sig=new hr.asn1.DERBitString({hex:"00"+this.hexSig});var t=new hr.asn1.DERSequence({array:[this.asn1TBSCertList,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=t.getEncodedHex(),this.isModified=!1},this.getEncodedHex=function(){if(0==this.isModified&&null!=this.hTLV)return this.hTLV;throw"not signed yet"},this.getPEMString=function(){var t=pn(this.getEncodedHex());return"-----BEGIN X509 CRL-----\r\n"+t+"\r\n-----END X509 CRL-----\r\n"},void 0!==t&&(void 0!==t.tbsobj&&(this.asn1TBSCertList=t.tbsobj),void 0!==t.prvkeyobj&&(this.prvKey=t.prvkeyobj))},Un.lang.extend(hr.asn1.x509.CRL,hr.asn1.ASN1Object),hr.asn1.x509.TBSCertList=function(t){hr.asn1.x509.TBSCertList.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERSequence,i=n.x509,o=i.Time;this.setSignatureAlgByParam=function(t){this.asn1SignatureAlg=new i.AlgorithmIdentifier(t)},this.setIssuerByParam=function(t){this.asn1Issuer=new i.X500Name(t)},this.setThisUpdateByParam=function(t){this.asn1ThisUpdate=new o(t)},this.setNextUpdateByParam=function(t){this.asn1NextUpdate=new o(t)},this.addRevokedCert=function(t,e){var n={};void 0!=t&&null!=t&&(n.sn=t),void 0!=e&&null!=e&&(n.time=e);var r=new i.CRLEntry(n);this.aRevokedCert.push(r)},this.getEncodedHex=function(){if(this.asn1Array=new Array,null!=this.asn1Version&&this.asn1Array.push(this.asn1Version),this.asn1Array.push(this.asn1SignatureAlg),this.asn1Array.push(this.asn1Issuer),this.asn1Array.push(this.asn1ThisUpdate),null!=this.asn1NextUpdate&&this.asn1Array.push(this.asn1NextUpdate),this.aRevokedCert.length>0){ var t=new r({array:this.aRevokedCert});this.asn1Array.push(t)}var e=new r({array:this.asn1Array});return this.hTLV=e.getEncodedHex(),this.isModified=!1,this.hTLV},this._initialize=function(){this.asn1Version=null,this.asn1SignatureAlg=null,this.asn1Issuer=null,this.asn1ThisUpdate=null,this.asn1NextUpdate=null,this.aRevokedCert=new Array},this._initialize()},Un.lang.extend(hr.asn1.x509.TBSCertList,hr.asn1.ASN1Object),hr.asn1.x509.CRLEntry=function(t){hr.asn1.x509.CRLEntry.superclass.constructor.call(this);var e=hr,n=e.asn1;this.setCertSerial=function(t){this.sn=new n.DERInteger(t)},this.setRevocationDate=function(t){this.time=new n.x509.Time(t)},this.getEncodedHex=function(){var t=new n.DERSequence({array:[this.sn,this.time]});return this.TLV=t.getEncodedHex(),this.TLV},void 0!==t&&(void 0!==t.time&&this.setRevocationDate(t.time),void 0!==t.sn&&this.setCertSerial(t.sn))},Un.lang.extend(hr.asn1.x509.CRLEntry,hr.asn1.ASN1Object),hr.asn1.x509.X500Name=function(t){hr.asn1.x509.X500Name.superclass.constructor.call(this),this.asn1Array=new Array;var e=hr,n=e.asn1,r=n.x509,i=vn;if(this.setByString=function(t){var e=t.split("/");e.shift();for(var n=[],i=0;i<e.length;i++)if(e[i].match(/^[^=]+=.+$/))n.push(e[i]);else{var o=n.length-1;n[o]=n[o]+"/"+e[i]}for(var i=0;i<n.length;i++)this.asn1Array.push(new r.RDN({str:n[i]}))},this.setByLdapString=function(t){var e=r.X500Name.ldapToOneline(t);this.setByString(e)},this.setByObject=function(t){for(var e in t)if(t.hasOwnProperty(e)){var n=new hr.asn1.x509.RDN({str:e+"="+t[e]});this.asn1Array?this.asn1Array.push(n):this.asn1Array=[n]}},this.getEncodedHex=function(){if("string"==typeof this.hTLV)return this.hTLV;var t=new n.DERSequence({array:this.asn1Array});return this.hTLV=t.getEncodedHex(),this.hTLV},void 0!==t){if(void 0!==t.str?this.setByString(t.str):void 0!==t.ldapstr?this.setByLdapString(t.ldapstr):"object"===("undefined"==typeof t?"undefined":Mn(t))&&this.setByObject(t),void 0!==t.certissuer){var o=new Ln;o.hex=i(t.certissuer),this.hTLV=o.getIssuerHex()}if(void 0!==t.certsubject){var o=new Ln;o.hex=i(t.certsubject),this.hTLV=o.getSubjectHex()}}},Un.lang.extend(hr.asn1.x509.X500Name,hr.asn1.ASN1Object),hr.asn1.x509.X500Name.onelineToLDAP=function(t){if("/"!==t.substr(0,1))throw"malformed input";t=t.substr(1);var e=t.split("/");return e.reverse(),e=e.map(function(t){return t.replace(/,/,"\\,")}),e.join(",")},hr.asn1.x509.X500Name.ldapToOneline=function(t){for(var e=t.split(","),n=!1,r=[],i=0;e.length>0;i++){var o=e.shift();if(n===!0){var s=r.pop(),a=(s+","+o).replace(/\\,/g,",");r.push(a),n=!1}else r.push(o);"\\"===o.substr(-1,1)&&(n=!0)}return r=r.map(function(t){return t.replace("/","\\/")}),r.reverse(),"/"+r.join("/")},hr.asn1.x509.RDN=function(t){hr.asn1.x509.RDN.superclass.constructor.call(this),this.asn1Array=new Array,this.addByString=function(t){this.asn1Array.push(new hr.asn1.x509.AttributeTypeAndValue({str:t}))},this.addByMultiValuedString=function(t){for(var e=hr.asn1.x509.RDN.parseString(t),n=0;n<e.length;n++)this.addByString(e[n])},this.getEncodedHex=function(){var t=new hr.asn1.DERSet({array:this.asn1Array});return this.TLV=t.getEncodedHex(),this.TLV},void 0!==t&&void 0!==t.str&&this.addByMultiValuedString(t.str)},Un.lang.extend(hr.asn1.x509.RDN,hr.asn1.ASN1Object),hr.asn1.x509.RDN.parseString=function(t){for(var e=t.split(/\+/),n=!1,r=[],i=0;e.length>0;i++){var o=e.shift();if(n===!0){var s=r.pop(),a=(s+"+"+o).replace(/\\\+/g,"+");r.push(a),n=!1}else r.push(o);"\\"===o.substr(-1,1)&&(n=!0)}for(var u=!1,c=[],i=0;r.length>0;i++){var o=r.shift();if(u===!0){var f=c.pop();if(o.match(/"$/)){var a=(f+"+"+o).replace(/^([^=]+)="(.*)"$/,"$1=$2");c.push(a),u=!1}else c.push(f+"+"+o)}else c.push(o);o.match(/^[^=]+="/)&&(u=!0)}return c},hr.asn1.x509.AttributeTypeAndValue=function(t){hr.asn1.x509.AttributeTypeAndValue.superclass.constructor.call(this);var e="utf8",n=hr,r=n.asn1;this.setByString=function(t){var e=t.match(/^([^=]+)=(.+)$/);if(!e)throw"malformed attrTypeAndValueStr: "+t;this.setByAttrTypeAndValueStr(e[1],e[2])},this.setByAttrTypeAndValueStr=function(t,n){this.typeObj=hr.asn1.x509.OID.atype2obj(t);var r=e;"C"==t&&(r="prn"),this.valueObj=this.getValueObj(r,n)},this.getValueObj=function(t,e){if("utf8"==t)return new r.DERUTF8String({str:e});if("prn"==t)return new r.DERPrintableString({str:e});if("tel"==t)return new r.DERTeletexString({str:e});if("ia5"==t)return new r.DERIA5String({str:e});throw"unsupported directory string type: type="+t+" value="+e},this.getEncodedHex=function(){var t=new r.DERSequence({array:[this.typeObj,this.valueObj]});return this.TLV=t.getEncodedHex(),this.TLV},void 0!==t&&void 0!==t.str&&this.setByString(t.str)},Un.lang.extend(hr.asn1.x509.AttributeTypeAndValue,hr.asn1.ASN1Object),hr.asn1.x509.SubjectPublicKeyInfo=function(t){hr.asn1.x509.SubjectPublicKeyInfo.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERInteger,i=n.DERBitString,o=n.DERObjectIdentifier,s=n.DERSequence,a=n.ASN1Util.newObject,u=n.x509,c=u.AlgorithmIdentifier,f=e.crypto;f.ECDSA,f.DSA;this.getASN1Object=function(){if(null==this.asn1AlgId||null==this.asn1SubjPKey)throw"algId and/or subjPubKey not set";var t=new s({array:[this.asn1AlgId,this.asn1SubjPKey]});return t},this.getEncodedHex=function(){var t=this.getASN1Object();return this.hTLV=t.getEncodedHex(),this.hTLV},this.setPubKey=function(t){try{if(t instanceof ve){var e=a({seq:[{int:{bigint:t.n}},{int:{int:t.e}}]}),n=e.getEncodedHex();this.asn1AlgId=new c({name:"rsaEncryption"}),this.asn1SubjPKey=new i({hex:"00"+n})}}catch(t){}try{if(t instanceof hr.crypto.ECDSA){var s=new o({name:t.curveName});this.asn1AlgId=new c({name:"ecPublicKey",asn1params:s}),this.asn1SubjPKey=new i({hex:"00"+t.pubKeyHex})}}catch(t){}try{if(t instanceof hr.crypto.DSA){var s=new a({seq:[{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.g}}]});this.asn1AlgId=new c({name:"dsa",asn1params:s});var u=new r({bigint:t.y});this.asn1SubjPKey=new i({hex:"00"+u.getEncodedHex()})}}catch(t){}},void 0!==t&&this.setPubKey(t)},Un.lang.extend(hr.asn1.x509.SubjectPublicKeyInfo,hr.asn1.ASN1Object),hr.asn1.x509.Time=function(t){hr.asn1.x509.Time.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERUTCTime,i=n.DERGeneralizedTime;this.setTimeParams=function(t){this.timeParams=t},this.getEncodedHex=function(){var t=null;return t=null!=this.timeParams?"utc"==this.type?new r(this.timeParams):new i(this.timeParams):"utc"==this.type?new r:new i,this.TLV=t.getEncodedHex(),this.TLV},this.type="utc",void 0!==t&&(void 0!==t.type?this.type=t.type:void 0!==t.str&&(t.str.match(/^[0-9]{12}Z$/)&&(this.type="utc"),t.str.match(/^[0-9]{14}Z$/)&&(this.type="gen")),this.timeParams=t)},Un.lang.extend(hr.asn1.x509.Time,hr.asn1.ASN1Object),hr.asn1.x509.AlgorithmIdentifier=function(t){hr.asn1.x509.AlgorithmIdentifier.superclass.constructor.call(this),this.nameAlg=null,this.asn1Alg=null,this.asn1Params=null,this.paramEmpty=!1;var e=hr,n=e.asn1;if(this.getEncodedHex=function(){if(null===this.nameAlg&&null===this.asn1Alg)throw"algorithm not specified";null!==this.nameAlg&&null===this.asn1Alg&&(this.asn1Alg=n.x509.OID.name2obj(this.nameAlg));var t=[this.asn1Alg];null!==this.asn1Params&&t.push(this.asn1Params);var e=new n.DERSequence({array:t});return this.hTLV=e.getEncodedHex(),this.hTLV},void 0!==t&&(void 0!==t.name&&(this.nameAlg=t.name),void 0!==t.asn1params&&(this.asn1Params=t.asn1params),void 0!==t.paramempty&&(this.paramEmpty=t.paramempty)),null===this.asn1Params&&this.paramEmpty===!1&&null!==this.nameAlg){var r=this.nameAlg.toLowerCase();"withdsa"!==r.substr(-7,7)&&"withecdsa"!==r.substr(-9,9)&&(this.asn1Params=new n.DERNull)}},Un.lang.extend(hr.asn1.x509.AlgorithmIdentifier,hr.asn1.ASN1Object),hr.asn1.x509.GeneralName=function(t){hr.asn1.x509.GeneralName.superclass.constructor.call(this);var e={rfc822:"81",dns:"82",dn:"a4",uri:"86",ip:"87"},n=hr,r=n.asn1,i=(r.DERSequence,r.DEROctetString),o=r.DERIA5String,s=r.DERTaggedObject,a=r.ASN1Object,u=r.x509.X500Name,c=vn;this.explicit=!1,this.setByParam=function(t){var n=null;if(void 0!==t){if(void 0!==t.rfc822&&(this.type="rfc822",n=new o({str:t[this.type]})),void 0!==t.dns&&(this.type="dns",n=new o({str:t[this.type]})),void 0!==t.uri&&(this.type="uri",n=new o({str:t[this.type]})),void 0!==t.dn&&(this.type="dn",this.explicit=!0,n=new u({str:t.dn})),void 0!==t.ldapdn&&(this.type="dn",this.explicit=!0,n=new u({ldapstr:t.ldapdn})),void 0!==t.certissuer){this.type="dn",this.explicit=!0;var r=t.certissuer,f=null;if(r.match(/^[0-9A-Fa-f]+$/),r.indexOf("-----BEGIN ")!=-1&&(f=c(r)),null==f)throw"certissuer param not cert";var h=new Ln;h.hex=f;var l=h.getIssuerHex();n=new a,n.hTLV=l}if(void 0!==t.certsubj){this.type="dn",this.explicit=!0;var r=t.certsubj,f=null;if(r.match(/^[0-9A-Fa-f]+$/),r.indexOf("-----BEGIN ")!=-1&&(f=c(r)),null==f)throw"certsubj param not cert";var h=new Ln;h.hex=f;var l=h.getSubjectHex();n=new a,n.hTLV=l}if(void 0!==t.ip){this.type="ip",this.explicit=!1;var p,d=t.ip,g="malformed IP address";if(d.match(/^[0-9.]+[.][0-9.]+$/)){if(p=Dn("["+d.split(".").join(",")+"]"),8!==p.length)throw g}else if(d.match(/^[0-9A-Fa-f:]+:[0-9A-Fa-f:]+$/))p=En(d);else{if(!d.match(/^([0-9A-Fa-f][0-9A-Fa-f]){1,}$/))throw g;p=d}n=new i({hex:p})}if(null==this.type)throw"unsupported type in params="+t;this.asn1Obj=new s({explicit:this.explicit,tag:e[this.type],obj:n})}},this.getEncodedHex=function(){return this.asn1Obj.getEncodedHex()},void 0!==t&&this.setByParam(t)},Un.lang.extend(hr.asn1.x509.GeneralName,hr.asn1.ASN1Object),hr.asn1.x509.GeneralNames=function(t){hr.asn1.x509.GeneralNames.superclass.constructor.call(this);var e=hr,n=e.asn1;this.setByParamArray=function(t){for(var e=0;e<t.length;e++){var r=new n.x509.GeneralName(t[e]);this.asn1Array.push(r)}},this.getEncodedHex=function(){var t=new n.DERSequence({array:this.asn1Array});return t.getEncodedHex()},this.asn1Array=new Array,"undefined"!=typeof t&&this.setByParamArray(t)},Un.lang.extend(hr.asn1.x509.GeneralNames,hr.asn1.ASN1Object),hr.asn1.x509.DistributionPointName=function(t){hr.asn1.x509.DistributionPointName.superclass.constructor.call(this);var e=hr,n=e.asn1,r=n.DERTaggedObject;if(this.getEncodedHex=function(){if("full"!=this.type)throw"currently type shall be 'full': "+this.type;return this.asn1Obj=new r({explicit:!1,tag:this.tag,obj:this.asn1V}),this.hTLV=this.asn1Obj.getEncodedHex(),this.hTLV},void 0!==t){if(!n.x509.GeneralNames.prototype.isPrototypeOf(t))throw"This class supports GeneralNames only as argument";this.type="full",this.tag="a0",this.asn1V=t}},Un.lang.extend(hr.asn1.x509.DistributionPointName,hr.asn1.ASN1Object),hr.asn1.x509.DistributionPoint=function(t){hr.asn1.x509.DistributionPoint.superclass.constructor.call(this);var e=hr,n=e.asn1;this.getEncodedHex=function(){var t=new n.DERSequence;if(null!=this.asn1DP){var e=new n.DERTaggedObject({explicit:!0,tag:"a0",obj:this.asn1DP});t.appendASN1Object(e)}return this.hTLV=t.getEncodedHex(),this.hTLV},void 0!==t&&void 0!==t.dpobj&&(this.asn1DP=t.dpobj)},Un.lang.extend(hr.asn1.x509.DistributionPoint,hr.asn1.ASN1Object),hr.asn1.x509.OID=new function(t){this.atype2oidList={CN:"2.5.4.3",L:"2.5.4.7",ST:"2.5.4.8",O:"2.5.4.10",OU:"2.5.4.11",C:"2.5.4.6",STREET:"2.5.4.9",DC:"0.9.2342.19200300.100.1.25",UID:"0.9.2342.19200300.100.1.1",SN:"2.5.4.4",T:"2.5.4.12",DN:"2.5.4.49",E:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",serialNumber:"2.5.4.5",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3"},this.name2oidList={sha1:"1.3.14.3.2.26",sha256:"2.16.840.1.101.3.4.2.1",sha384:"2.16.840.1.101.3.4.2.2",sha512:"2.16.840.1.101.3.4.2.3",sha224:"2.16.840.1.101.3.4.2.4",md5:"1.2.840.113549.2.5",md2:"1.3.14.7.2.2.1",ripemd160:"1.3.36.3.2.1",MD2withRSA:"1.2.840.113549.1.1.2",MD4withRSA:"1.2.840.113549.1.1.3",MD5withRSA:"1.2.840.113549.1.1.4",SHA1withRSA:"1.2.840.113549.1.1.5",SHA224withRSA:"1.2.840.113549.1.1.14",SHA256withRSA:"1.2.840.113549.1.1.11",SHA384withRSA:"1.2.840.113549.1.1.12",SHA512withRSA:"1.2.840.113549.1.1.13",SHA1withECDSA:"1.2.840.10045.4.1",SHA224withECDSA:"1.2.840.10045.4.3.1",SHA256withECDSA:"1.2.840.10045.4.3.2",SHA384withECDSA:"1.2.840.10045.4.3.3",SHA512withECDSA:"1.2.840.10045.4.3.4",dsa:"1.2.840.10040.4.1",SHA1withDSA:"1.2.840.10040.4.3",SHA224withDSA:"2.16.840.1.101.3.4.3.1",SHA256withDSA:"2.16.840.1.101.3.4.3.2",rsaEncryption:"1.2.840.113549.1.1.1",commonName:"2.5.4.3",countryName:"2.5.4.6",localityName:"2.5.4.7",stateOrProvinceName:"2.5.4.8",streetAddress:"2.5.4.9",organizationName:"2.5.4.10",organizationalUnitName:"2.5.4.11",domainComponent:"0.9.2342.19200300.100.1.25",userId:"0.9.2342.19200300.100.1.1",surname:"2.5.4.4",title:"2.5.4.12",distinguishedName:"2.5.4.49",emailAddress:"1.2.840.113549.1.9.1",description:"2.5.4.13",businessCategory:"2.5.4.15",postalCode:"2.5.4.17",uniqueIdentifier:"2.5.4.45",organizationIdentifier:"2.5.4.97",jurisdictionOfIncorporationL:"1.3.6.1.4.1.311.60.2.1.1",jurisdictionOfIncorporationSP:"1.3.6.1.4.1.311.60.2.1.2",jurisdictionOfIncorporationC:"1.3.6.1.4.1.311.60.2.1.3",subjectKeyIdentifier:"2.5.29.14",keyUsage:"2.5.29.15",subjectAltName:"2.5.29.17",issuerAltName:"2.5.29.18",basicConstraints:"2.5.29.19",nameConstraints:"2.5.29.30",cRLDistributionPoints:"2.5.29.31",certificatePolicies:"2.5.29.32",authorityKeyIdentifier:"2.5.29.35",policyConstraints:"2.5.29.36",extKeyUsage:"2.5.29.37",authorityInfoAccess:"1.3.6.1.5.5.7.1.1",ocsp:"1.3.6.1.5.5.7.48.1",caIssuers:"1.3.6.1.5.5.7.48.2",anyExtendedKeyUsage:"2.5.29.37.0",serverAuth:"1.3.6.1.5.5.7.3.1",clientAuth:"1.3.6.1.5.5.7.3.2",codeSigning:"1.3.6.1.5.5.7.3.3",emailProtection:"1.3.6.1.5.5.7.3.4",timeStamping:"1.3.6.1.5.5.7.3.8",ocspSigning:"1.3.6.1.5.5.7.3.9",ecPublicKey:"1.2.840.10045.2.1",secp256r1:"1.2.840.10045.3.1.7",secp256k1:"1.3.132.0.10",secp384r1:"1.3.132.0.34",pkcs5PBES2:"1.2.840.113549.1.5.13",pkcs5PBKDF2:"1.2.840.113549.1.5.12","des-EDE3-CBC":"1.2.840.113549.3.7",data:"1.2.840.113549.1.7.1","signed-data":"1.2.840.113549.1.7.2","enveloped-data":"1.2.840.113549.1.7.3","digested-data":"1.2.840.113549.1.7.5","encrypted-data":"1.2.840.113549.1.7.6","authenticated-data":"1.2.840.113549.1.9.16.1.2",tstinfo:"1.2.840.113549.1.9.16.1.4",extensionRequest:"1.2.840.113549.1.9.14"},this.objCache={},this.name2obj=function(t){if("undefined"!=typeof this.objCache[t])return this.objCache[t];if("undefined"==typeof this.name2oidList[t])throw"Name of ObjectIdentifier not defined: "+t;var e=this.name2oidList[t],n=new hr.asn1.DERObjectIdentifier({oid:e});return this.objCache[t]=n,n},this.atype2obj=function(t){if("undefined"!=typeof this.objCache[t])return this.objCache[t];if("undefined"==typeof this.atype2oidList[t])throw"AttributeType name undefined: "+t;var e=this.atype2oidList[t],n=new hr.asn1.DERObjectIdentifier({oid:e});return this.objCache[t]=n,n}},hr.asn1.x509.OID.oid2name=function(t){var e=hr.asn1.x509.OID.name2oidList;for(var n in e)if(e[n]==t)return n;return""},hr.asn1.x509.OID.oid2atype=function(t){var e=hr.asn1.x509.OID.atype2oidList;for(var n in e)if(e[n]==t)return n;return t},hr.asn1.x509.OID.name2oid=function(t){var e=hr.asn1.x509.OID.name2oidList;return void 0===e[t]?"":e[t]},hr.asn1.x509.X509Util={},hr.asn1.x509.X509Util.newCertPEM=function(t){var e=hr.asn1.x509,n=e.TBSCertificate,r=e.Certificate,i=new n;if(void 0===t.serial)throw"serial number undefined.";if(i.setSerialNumberByParam(t.serial),"string"!=typeof t.sigalg.name)throw"unproper signature algorithm name";if(i.setSignatureAlgByParam(t.sigalg),void 0===t.issuer)throw"issuer name undefined.";if(i.setIssuerByParam(t.issuer),void 0===t.notbefore)throw"notbefore undefined.";if(i.setNotBeforeByParam(t.notbefore),void 0===t.notafter)throw"notafter undefined.";if(i.setNotAfterByParam(t.notafter),void 0===t.subject)throw"subject name undefined.";if(i.setSubjectByParam(t.subject),void 0===t.sbjpubkey)throw"subject public key undefined.";if(i.setSubjectPublicKeyByGetKey(t.sbjpubkey),void 0!==t.ext&&void 0!==t.ext.length)for(var o=0;o<t.ext.length;o++)for(key in t.ext[o])i.appendExtensionByName(key,t.ext[o][key]);if(void 0===t.cakey&&void 0===t.sighex)throw"param cakey and sighex undefined.";var s=null,a=null;return t.cakey&&(s=t.cakey.isPrivate===!0?t.cakey:gr.getKey.apply(null,t.cakey),a=new r({tbscertobj:i,prvkeyobj:s}),a.sign()),t.sighex&&(a=new r({tbscertobj:i}),a.setSignatureHex(t.sighex)),a.getPEMString()};var hr;"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.lang&&hr.lang||(hr.lang={}),hr.lang.String=function(){};var lr,pr;"function"==typeof t?(lr=function(e){return en(new t(e,"utf8").toString("base64"))},pr=function(e){return new t(nn(e),"base64").toString("utf8")}):(lr=function(t){return rn(_n(kn(t)))},pr=function(t){return decodeURIComponent(xn(on(t)))}),hr.lang.String.isInteger=function(t){return!!t.match(/^[0-9]+$/)||!!t.match(/^-[0-9]+$/)},hr.lang.String.isHex=function(t){return!(t.length%2!=0||!t.match(/^[0-9a-f]+$/)&&!t.match(/^[0-9A-F]+$/))},hr.lang.String.isBase64=function(t){return t=t.replace(/\s+/g,""),!(!t.match(/^[0-9A-Za-z+\/]+={0,3}$/)||t.length%4!=0)},hr.lang.String.isBase64URL=function(t){return!t.match(/[+\/=]/)&&(t=nn(t),hr.lang.String.isBase64(t))},hr.lang.String.isIntegerArray=function(t){return t=t.replace(/\s+/g,""),!!t.match(/^\[[0-9,]+\]$/)};var dr=function(t,e){var n=t.length;t.length>e.length&&(n=e.length);for(var r=0;r<n;r++)if(t.charCodeAt(r)!=e.charCodeAt(r))return r;return t.length!=e.length?n:-1};"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.crypto&&hr.crypto||(hr.crypto={}),hr.crypto.Util=new function(){this.DIGESTINFOHEAD={sha1:"3021300906052b0e03021a05000414",sha224:"302d300d06096086480165030402040500041c",sha256:"3031300d060960864801650304020105000420",sha384:"3041300d060960864801650304020205000430",sha512:"3051300d060960864801650304020305000440",md2:"3020300c06082a864886f70d020205000410",md5:"3020300c06082a864886f70d020505000410",ripemd160:"3021300906052b2403020105000414"},this.DEFAULTPROVIDER={md5:"cryptojs",sha1:"cryptojs",sha224:"cryptojs",sha256:"cryptojs",sha384:"cryptojs",sha512:"cryptojs",ripemd160:"cryptojs",hmacmd5:"cryptojs",hmacsha1:"cryptojs",hmacsha224:"cryptojs",hmacsha256:"cryptojs",hmacsha384:"cryptojs",hmacsha512:"cryptojs",hmacripemd160:"cryptojs",MD5withRSA:"cryptojs/jsrsa",SHA1withRSA:"cryptojs/jsrsa",SHA224withRSA:"cryptojs/jsrsa",SHA256withRSA:"cryptojs/jsrsa",SHA384withRSA:"cryptojs/jsrsa",SHA512withRSA:"cryptojs/jsrsa",RIPEMD160withRSA:"cryptojs/jsrsa",MD5withECDSA:"cryptojs/jsrsa",SHA1withECDSA:"cryptojs/jsrsa",SHA224withECDSA:"cryptojs/jsrsa",SHA256withECDSA:"cryptojs/jsrsa",SHA384withECDSA:"cryptojs/jsrsa",SHA512withECDSA:"cryptojs/jsrsa",RIPEMD160withECDSA:"cryptojs/jsrsa",SHA1withDSA:"cryptojs/jsrsa",SHA224withDSA:"cryptojs/jsrsa",SHA256withDSA:"cryptojs/jsrsa",MD5withRSAandMGF1:"cryptojs/jsrsa",SHA1withRSAandMGF1:"cryptojs/jsrsa",SHA224withRSAandMGF1:"cryptojs/jsrsa",SHA256withRSAandMGF1:"cryptojs/jsrsa",SHA384withRSAandMGF1:"cryptojs/jsrsa",SHA512withRSAandMGF1:"cryptojs/jsrsa",RIPEMD160withRSAandMGF1:"cryptojs/jsrsa"},this.CRYPTOJSMESSAGEDIGESTNAME={md5:Vn.algo.MD5,sha1:Vn.algo.SHA1,sha224:Vn.algo.SHA224,sha256:Vn.algo.SHA256,sha384:Vn.algo.SHA384,sha512:Vn.algo.SHA512,ripemd160:Vn.algo.RIPEMD160},this.getDigestInfoHex=function(t,e){if("undefined"==typeof this.DIGESTINFOHEAD[e])throw"alg not supported in Util.DIGESTINFOHEAD: "+e;return this.DIGESTINFOHEAD[e]+t},this.getPaddedDigestInfoHex=function(t,e,n){var r=this.getDigestInfoHex(t,e),i=n/4;if(r.length+22>i)throw"key is too short for SigAlg: keylen="+n+","+e;for(var o="0001",s="00"+r,a="",u=i-o.length-s.length,c=0;c<u;c+=2)a+="ff";var f=o+a+s;return f},this.hashString=function(t,e){var n=new hr.crypto.MessageDigest({alg:e});return n.digestString(t)},this.hashHex=function(t,e){var n=new hr.crypto.MessageDigest({alg:e});return n.digestHex(t)},this.sha1=function(t){var e=new hr.crypto.MessageDigest({alg:"sha1",prov:"cryptojs"});return e.digestString(t)},this.sha256=function(t){var e=new hr.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});return e.digestString(t)},this.sha256Hex=function(t){var e=new hr.crypto.MessageDigest({alg:"sha256",prov:"cryptojs"});return e.digestHex(t)},this.sha512=function(t){var e=new hr.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"});return e.digestString(t)},this.sha512Hex=function(t){var e=new hr.crypto.MessageDigest({alg:"sha512",prov:"cryptojs"});return e.digestHex(t)}},hr.crypto.Util.md5=function(t){var e=new hr.crypto.MessageDigest({alg:"md5",prov:"cryptojs"});return e.digestString(t)},hr.crypto.Util.ripemd160=function(t){var e=new hr.crypto.MessageDigest({alg:"ripemd160",prov:"cryptojs"});return e.digestString(t)},hr.crypto.Util.SECURERANDOMGEN=new he,hr.crypto.Util.getRandomHexOfNbytes=function(t){var e=new Array(t);return hr.crypto.Util.SECURERANDOMGEN.nextBytes(e),$e(e)},hr.crypto.Util.getRandomBigIntegerOfNbytes=function(t){return new o(hr.crypto.Util.getRandomHexOfNbytes(t),16)},hr.crypto.Util.getRandomHexOfNbits=function(t){var e=t%8,n=(t-e)/8,r=new Array(n+1);return hr.crypto.Util.SECURERANDOMGEN.nextBytes(r),r[0]=(255<<e&255^255)&r[0],$e(r)},hr.crypto.Util.getRandomBigIntegerOfNbits=function(t){return new o(hr.crypto.Util.getRandomHexOfNbits(t),16)},hr.crypto.Util.getRandomBigIntegerZeroToMax=function(t){for(var e=t.bitLength();;){var n=hr.crypto.Util.getRandomBigIntegerOfNbits(e);if(t.compareTo(n)!=-1)return n}},hr.crypto.Util.getRandomBigIntegerMinToMax=function(t,e){var n=t.compareTo(e);if(1==n)throw"biMin is greater than biMax";if(0==n)return t;var r=e.subtract(t),i=hr.crypto.Util.getRandomBigIntegerZeroToMax(r);return i.add(t)},hr.crypto.MessageDigest=function(t){this.setAlgAndProvider=function(t,e){if(t=hr.crypto.MessageDigest.getCanonicalAlgName(t),null!==t&&void 0===e&&(e=hr.crypto.Util.DEFAULTPROVIDER[t]),":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(t)!=-1&&"cryptojs"==e){try{this.md=hr.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[t].create()}catch(e){throw"setAlgAndProvider hash alg set fail alg="+t+"/"+e}this.updateString=function(t){this.md.update(t)},this.updateHex=function(t){var e=Vn.enc.Hex.parse(t);this.md.update(e)},this.digest=function(){var t=this.md.finalize();return t.toString(Vn.enc.Hex)},this.digestString=function(t){return this.updateString(t),this.digest()},this.digestHex=function(t){return this.updateHex(t),this.digest()}}if(":sha256:".indexOf(t)!=-1&&"sjcl"==e){try{this.md=new sjcl.hash.sha256}catch(e){throw"setAlgAndProvider hash alg set fail alg="+t+"/"+e}this.updateString=function(t){this.md.update(t)},this.updateHex=function(t){var e=sjcl.codec.hex.toBits(t);this.md.update(e)},this.digest=function(){var t=this.md.finalize();return sjcl.codec.hex.fromBits(t)},this.digestString=function(t){return this.updateString(t),this.digest()},this.digestHex=function(t){return this.updateHex(t),this.digest()}}},this.updateString=function(t){throw"updateString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.updateHex=function(t){throw"updateHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digest=function(){throw"digest() not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestString=function(t){throw"digestString(str) not supported for this alg/prov: "+this.algName+"/"+this.provName},this.digestHex=function(t){throw"digestHex(hex) not supported for this alg/prov: "+this.algName+"/"+this.provName},void 0!==t&&void 0!==t.alg&&(this.algName=t.alg,void 0===t.prov&&(this.provName=hr.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName))},hr.crypto.MessageDigest.getCanonicalAlgName=function(t){return"string"==typeof t&&(t=t.toLowerCase(),t=t.replace(/-/,"")),t},hr.crypto.MessageDigest.getHashLength=function(t){var e=hr.crypto.MessageDigest,n=e.getCanonicalAlgName(t);if(void 0===e.HASHLENGTH[n])throw"not supported algorithm: "+t;return e.HASHLENGTH[n]},hr.crypto.MessageDigest.HASHLENGTH={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,ripemd160:20},hr.crypto.Mac=function(t){this.setAlgAndProvider=function(t,e){if(t=t.toLowerCase(),null==t&&(t="hmacsha1"),t=t.toLowerCase(),"hmac"!=t.substr(0,4))throw"setAlgAndProvider unsupported HMAC alg: "+t;void 0===e&&(e=hr.crypto.Util.DEFAULTPROVIDER[t]),this.algProv=t+"/"+e;var n=t.substr(4);if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(n)!=-1&&"cryptojs"==e){try{var r=hr.crypto.Util.CRYPTOJSMESSAGEDIGESTNAME[n];this.mac=Vn.algo.HMAC.create(r,this.pass)}catch(t){throw"setAlgAndProvider hash alg set fail hashAlg="+n+"/"+t}this.updateString=function(t){this.mac.update(t)},this.updateHex=function(t){var e=Vn.enc.Hex.parse(t);this.mac.update(e)},this.doFinal=function(){var t=this.mac.finalize();return t.toString(Vn.enc.Hex)},this.doFinalString=function(t){return this.updateString(t),this.doFinal()},this.doFinalHex=function(t){return this.updateHex(t),this.doFinal()}}},this.updateString=function(t){throw"updateString(str) not supported for this alg/prov: "+this.algProv},this.updateHex=function(t){throw"updateHex(hex) not supported for this alg/prov: "+this.algProv},this.doFinal=function(){throw"digest() not supported for this alg/prov: "+this.algProv},this.doFinalString=function(t){throw"digestString(str) not supported for this alg/prov: "+this.algProv},this.doFinalHex=function(t){throw"digestHex(hex) not supported for this alg/prov: "+this.algProv},this.setPassword=function(t){if("string"==typeof t){var e=t;return t.length%2!=1&&t.match(/^[0-9A-Fa-f]+$/)||(e=hn(t)),void(this.pass=Vn.enc.Hex.parse(e))}if("object"!=("undefined"==typeof t?"undefined":Mn(t)))throw"KJUR.crypto.Mac unsupported password type: "+t;var e=null;if(void 0!==t.hex){if(t.hex.length%2!=0||!t.hex.match(/^[0-9A-Fa-f]+$/))throw"Mac: wrong hex password: "+t.hex;e=t.hex}if(void 0!==t.utf8&&(e=un(t.utf8)),void 0!==t.rstr&&(e=hn(t.rstr)),void 0!==t.b64&&(e=r(t.b64)),void 0!==t.b64u&&(e=on(t.b64u)),null==e)throw"KJUR.crypto.Mac unsupported password type: "+t;this.pass=Vn.enc.Hex.parse(e)},void 0!==t&&(void 0!==t.pass&&this.setPassword(t.pass),void 0!==t.alg&&(this.algName=t.alg,void 0===t.prov&&(this.provName=hr.crypto.Util.DEFAULTPROVIDER[this.algName]),this.setAlgAndProvider(this.algName,this.provName)))},hr.crypto.Signature=function(t){var e=null;if(this._setAlgNames=function(){var t=this.algName.match(/^(.+)with(.+)$/);t&&(this.mdAlgName=t[1].toLowerCase(),this.pubkeyAlgName=t[2].toLowerCase())},this._zeroPaddingOfSignature=function(t,e){for(var n="",r=e/4-t.length,i=0;i<r;i++)n+="0";return n+t},this.setAlgAndProvider=function(t,e){if(this._setAlgNames(),"cryptojs/jsrsa"!=e)throw"provider not supported: "+e;if(":md5:sha1:sha224:sha256:sha384:sha512:ripemd160:".indexOf(this.mdAlgName)!=-1){try{this.md=new hr.crypto.MessageDigest({alg:this.mdAlgName})}catch(t){throw"setAlgAndProvider hash alg set fail alg="+this.mdAlgName+"/"+t}this.init=function(t,e){var n=null;try{n=void 0===e?gr.getKey(t):gr.getKey(t,e)}catch(t){throw"init failed:"+t}if(n.isPrivate===!0)this.prvKey=n,this.state="SIGN";else{if(n.isPublic!==!0)throw"init failed.:"+n;this.pubKey=n,this.state="VERIFY"}},this.updateString=function(t){this.md.updateString(t)},this.updateHex=function(t){this.md.updateHex(t)},this.sign=function(){if(this.sHashHex=this.md.digest(),"undefined"!=typeof this.ecprvhex&&"undefined"!=typeof this.eccurvename){var t=new hr.crypto.ECDSA({curve:this.eccurvename});this.hSign=t.signHex(this.sHashHex,this.ecprvhex)}else if(this.prvKey instanceof ve&&"rsaandmgf1"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHashPSS(this.sHashHex,this.mdAlgName,this.pssSaltLen);else if(this.prvKey instanceof ve&&"rsa"===this.pubkeyAlgName)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex,this.mdAlgName);else if(this.prvKey instanceof hr.crypto.ECDSA)this.hSign=this.prvKey.signWithMessageHash(this.sHashHex);else{if(!(this.prvKey instanceof hr.crypto.DSA))throw"Signature: unsupported private key alg: "+this.pubkeyAlgName;this.hSign=this.prvKey.signWithMessageHash(this.sHashHex)}return this.hSign},this.signString=function(t){return this.updateString(t),this.sign()},this.signHex=function(t){return this.updateHex(t),this.sign()},this.verify=function(t){if(this.sHashHex=this.md.digest(),"undefined"!=typeof this.ecpubhex&&"undefined"!=typeof this.eccurvename){var e=new hr.crypto.ECDSA({curve:this.eccurvename});return e.verifyHex(this.sHashHex,t,this.ecpubhex)}if(this.pubKey instanceof ve&&"rsaandmgf1"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHashPSS(this.sHashHex,t,this.mdAlgName,this.pssSaltLen);if(this.pubKey instanceof ve&&"rsa"===this.pubkeyAlgName)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);if(void 0!==hr.crypto.ECDSA&&this.pubKey instanceof hr.crypto.ECDSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);if(void 0!==hr.crypto.DSA&&this.pubKey instanceof hr.crypto.DSA)return this.pubKey.verifyWithMessageHash(this.sHashHex,t);throw"Signature: unsupported public key alg: "+this.pubkeyAlgName}}},this.init=function(t,e){throw"init(key, pass) not supported for this alg:prov="+this.algProvName},this.updateString=function(t){throw"updateString(str) not supported for this alg:prov="+this.algProvName},this.updateHex=function(t){throw"updateHex(hex) not supported for this alg:prov="+this.algProvName},this.sign=function(){throw"sign() not supported for this alg:prov="+this.algProvName},this.signString=function(t){throw"digestString(str) not supported for this alg:prov="+this.algProvName},this.signHex=function(t){throw"digestHex(hex) not supported for this alg:prov="+this.algProvName},this.verify=function(t){throw"verify(hSigVal) not supported for this alg:prov="+this.algProvName},this.initParams=t,void 0!==t&&(void 0!==t.alg&&(this.algName=t.alg,void 0===t.prov?this.provName=hr.crypto.Util.DEFAULTPROVIDER[this.algName]:this.provName=t.prov,this.algProvName=this.algName+":"+this.provName,this.setAlgAndProvider(this.algName,this.provName),this._setAlgNames()),void 0!==t.psssaltlen&&(this.pssSaltLen=t.psssaltlen),void 0!==t.prvkeypem)){if(void 0!==t.prvkeypas)throw"both prvkeypem and prvkeypas parameters not supported";try{var e=gr.getKey(t.prvkeypem);this.init(e)}catch(t){throw"fatal error to load pem private key: "+t}}},hr.crypto.Cipher=function(t){},hr.crypto.Cipher.encrypt=function(t,e,n){if(e instanceof ve&&e.isPublic){var r=hr.crypto.Cipher.getAlgByKeyAndName(e,n);if("RSA"===r)return e.encrypt(t);if("RSAOAEP"===r)return e.encryptOAEP(t,"sha1");var i=r.match(/^RSAOAEP(\d+)$/);if(null!==i)return e.encryptOAEP(t,"sha"+i[1]);throw"Cipher.encrypt: unsupported algorithm for RSAKey: "+n}throw"Cipher.encrypt: unsupported key or algorithm"},hr.crypto.Cipher.decrypt=function(t,e,n){if(e instanceof ve&&e.isPrivate){var r=hr.crypto.Cipher.getAlgByKeyAndName(e,n);if("RSA"===r)return e.decrypt(t);if("RSAOAEP"===r)return e.decryptOAEP(t,"sha1");var i=r.match(/^RSAOAEP(\d+)$/);if(null!==i)return e.decryptOAEP(t,"sha"+i[1]);throw"Cipher.decrypt: unsupported algorithm for RSAKey: "+n}throw"Cipher.decrypt: unsupported key or algorithm"},hr.crypto.Cipher.getAlgByKeyAndName=function(t,e){if(t instanceof ve){if(":RSA:RSAOAEP:RSAOAEP224:RSAOAEP256:RSAOAEP384:RSAOAEP512:".indexOf(e)!=-1)return e;if(null===e||void 0===e)return"RSA";throw"getAlgByKeyAndName: not supported algorithm name for RSAKey: "+e}throw"getAlgByKeyAndName: not supported algorithm name: "+e},hr.crypto.OID=new function(){this.oidhex2name={"2a864886f70d010101":"rsaEncryption","2a8648ce3d0201":"ecPublicKey","2a8648ce380401":"dsa","2a8648ce3d030107":"secp256r1","2b8104001f":"secp192k1","2b81040021":"secp224r1","2b8104000a":"secp256k1","2b81040023":"secp521r1","2b81040022":"secp384r1","2a8648ce380403":"SHA1withDSA","608648016503040301":"SHA224withDSA","608648016503040302":"SHA256withDSA"}},"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.crypto&&hr.crypto||(hr.crypto={}),hr.crypto.ECDSA=function(t){var e="secp256r1",n=new he; this.type="EC",this.isPrivate=!1,this.isPublic=!1,this.getBigRandom=function(t){return new o(t.bitLength(),n).mod(t.subtract(o.ONE)).add(o.ONE)},this.setNamedCurve=function(t){this.ecparams=hr.crypto.ECParameterDB.getByName(t),this.prvKeyHex=null,this.pubKeyHex=null,this.curveName=t},this.setPrivateKeyHex=function(t){this.isPrivate=!0,this.prvKeyHex=t},this.setPublicKeyHex=function(t){this.isPublic=!0,this.pubKeyHex=t},this.getPublicKeyXYHex=function(){var t=this.pubKeyHex;if("04"!==t.substr(0,2))throw"this method supports uncompressed format(04) only";var e=this.ecparams.keylen/4;if(t.length!==2+2*e)throw"malformed public key hex length";var n={};return n.x=t.substr(2,e),n.y=t.substr(2+e),n},this.getShortNISTPCurveName=function(){var t=this.curveName;return"secp256r1"===t||"NIST P-256"===t||"P-256"===t||"prime256v1"===t?"P-256":"secp384r1"===t||"NIST P-384"===t||"P-384"===t?"P-384":null},this.generateKeyPairHex=function(){var t=this.ecparams.n,e=this.getBigRandom(t),n=this.ecparams.G.multiply(e),r=n.getX().toBigInteger(),i=n.getY().toBigInteger(),o=this.ecparams.keylen/4,s=("0000000000"+e.toString(16)).slice(-o),a=("0000000000"+r.toString(16)).slice(-o),u=("0000000000"+i.toString(16)).slice(-o),c="04"+a+u;return this.setPrivateKeyHex(s),this.setPublicKeyHex(c),{ecprvhex:s,ecpubhex:c}},this.signWithMessageHash=function(t){return this.signHex(t,this.prvKeyHex)},this.signHex=function(t,e){var n=new o(e,16),r=this.ecparams.n,i=new o(t,16);do var s=this.getBigRandom(r),a=this.ecparams.G,u=a.multiply(s),c=u.getX().toBigInteger().mod(r);while(c.compareTo(o.ZERO)<=0);var f=s.modInverse(r).multiply(i.add(n.multiply(c))).mod(r);return hr.crypto.ECDSA.biRSSigToASN1Sig(c,f)},this.sign=function(t,e){var n=e,r=this.ecparams.n,i=o.fromByteArrayUnsigned(t);do var s=this.getBigRandom(r),a=this.ecparams.G,u=a.multiply(s),c=u.getX().toBigInteger().mod(r);while(c.compareTo(o.ZERO)<=0);var f=s.modInverse(r).multiply(i.add(n.multiply(c))).mod(r);return this.serializeSig(c,f)},this.verifyWithMessageHash=function(t,e){return this.verifyHex(t,e,this.pubKeyHex)},this.verifyHex=function(t,e,n){var r,i,s=hr.crypto.ECDSA.parseSigHex(e);r=s.r,i=s.s;var a;a=Te.decodeFromHex(this.ecparams.curve,n);var u=new o(t,16);return this.verifyRaw(u,r,i,a)},this.verify=function(t,e,n){var r,i;if(Bitcoin.Util.isArray(e)){var s=this.parseSig(e);r=s.r,i=s.s}else{if("object"!==("undefined"==typeof e?"undefined":Mn(e))||!e.r||!e.s)throw"Invalid value for signature";r=e.r,i=e.s}var a;if(n instanceof Te)a=n;else{if(!Bitcoin.Util.isArray(n))throw"Invalid format for pubkey value, must be byte array or ECPointFp";a=Te.decodeFrom(this.ecparams.curve,n)}var u=o.fromByteArrayUnsigned(t);return this.verifyRaw(u,r,i,a)},this.verifyRaw=function(t,e,n,r){var i=this.ecparams.n,s=this.ecparams.G;if(e.compareTo(o.ONE)<0||e.compareTo(i)>=0)return!1;if(n.compareTo(o.ONE)<0||n.compareTo(i)>=0)return!1;var a=n.modInverse(i),u=t.multiply(a).mod(i),c=e.multiply(a).mod(i),f=s.multiply(u).add(r.multiply(c)),h=f.getX().toBigInteger().mod(i);return h.equals(e)},this.serializeSig=function(t,e){var n=t.toByteArraySigned(),r=e.toByteArraySigned(),i=[];return i.push(2),i.push(n.length),i=i.concat(n),i.push(2),i.push(r.length),i=i.concat(r),i.unshift(i.length),i.unshift(48),i},this.parseSig=function(t){var e;if(48!=t[0])throw new Error("Signature not a valid DERSequence");if(e=2,2!=t[e])throw new Error("First element in signature must be a DERInteger");var n=t.slice(e+2,e+2+t[e+1]);if(e+=2+t[e+1],2!=t[e])throw new Error("Second element in signature must be a DERInteger");var r=t.slice(e+2,e+2+t[e+1]);e+=2+t[e+1];var i=o.fromByteArrayUnsigned(n),s=o.fromByteArrayUnsigned(r);return{r:i,s:s}},this.parseSigCompact=function(t){if(65!==t.length)throw"Signature has the wrong length";var e=t[0]-27;if(e<0||e>7)throw"Invalid signature type";var n=this.ecparams.n,r=o.fromByteArrayUnsigned(t.slice(1,33)).mod(n),i=o.fromByteArrayUnsigned(t.slice(33,65)).mod(n);return{r:r,s:i,i:e}},this.readPKCS5PrvKeyHex=function(t){var e=fr,n=hr.crypto.ECDSA.getName,r=e.getVbyList;if(e.isASN1HEX(t)===!1)throw"not ASN.1 hex string";var i,o,s;try{i=r(t,0,[2,0],"06"),o=r(t,0,[1],"04");try{s=r(t,0,[3,0],"03").substr(2)}catch(t){}}catch(t){throw"malformed PKCS#1/5 plain ECC private key"}if(this.curveName=n(i),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(s),this.setPrivateKeyHex(o),this.isPublic=!1},this.readPKCS8PrvKeyHex=function(t){var e=fr,n=hr.crypto.ECDSA.getName,r=e.getVbyList;if(e.isASN1HEX(t)===!1)throw"not ASN.1 hex string";var i,o,s,a;try{i=r(t,0,[1,0],"06"),o=r(t,0,[1,1],"06"),s=r(t,0,[2,0,1],"04");try{a=r(t,0,[2,0,2,0],"03").substr(2)}catch(t){}}catch(t){throw"malformed PKCS#8 plain ECC private key"}if(this.curveName=n(o),void 0===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(a),this.setPrivateKeyHex(s),this.isPublic=!1},this.readPKCS8PubKeyHex=function(t){var e=fr,n=hr.crypto.ECDSA.getName,r=e.getVbyList;if(e.isASN1HEX(t)===!1)throw"not ASN.1 hex string";var i,o,s;try{i=r(t,0,[0,0],"06"),o=r(t,0,[0,1],"06"),s=r(t,0,[1],"03").substr(2)}catch(t){throw"malformed PKCS#8 ECC public key"}if(this.curveName=n(o),null===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(s)},this.readCertPubKeyHex=function(t,e){5!==e&&(e=6);var n=fr,r=hr.crypto.ECDSA.getName,i=n.getVbyList;if(n.isASN1HEX(t)===!1)throw"not ASN.1 hex string";var o,s;try{o=i(t,0,[0,e,0,1],"06"),s=i(t,0,[0,e,1],"03").substr(2)}catch(t){throw"malformed X.509 certificate ECC public key"}if(this.curveName=r(o),null===this.curveName)throw"unsupported curve name";this.setNamedCurve(this.curveName),this.setPublicKeyHex(s)},void 0!==t&&void 0!==t.curve&&(this.curveName=t.curve),void 0===this.curveName&&(this.curveName=e),this.setNamedCurve(this.curveName),void 0!==t&&(void 0!==t.prv&&this.setPrivateKeyHex(t.prv),void 0!==t.pub&&this.setPublicKeyHex(t.pub))},hr.crypto.ECDSA.parseSigHex=function(t){var e=hr.crypto.ECDSA.parseSigHexInHexRS(t),n=new o(e.r,16),r=new o(e.s,16);return{r:n,s:r}},hr.crypto.ECDSA.parseSigHexInHexRS=function(t){var e=fr,n=e.getChildIdx,r=e.getV;if("30"!=t.substr(0,2))throw"signature is not a ASN.1 sequence";var i=n(t,0);if(2!=i.length)throw"number of signature ASN.1 sequence elements seem wrong";var o=i[0],s=i[1];if("02"!=t.substr(o,2))throw"1st item of sequene of signature is not ASN.1 integer";if("02"!=t.substr(s,2))throw"2nd item of sequene of signature is not ASN.1 integer";var a=r(t,o),u=r(t,s);return{r:a,s:u}},hr.crypto.ECDSA.asn1SigToConcatSig=function(t){var e=hr.crypto.ECDSA.parseSigHexInHexRS(t),n=e.r,r=e.s;if("00"==n.substr(0,2)&&n.length%32==2&&(n=n.substr(2)),"00"==r.substr(0,2)&&r.length%32==2&&(r=r.substr(2)),n.length%32==30&&(n="00"+n),r.length%32==30&&(r="00"+r),n.length%32!=0)throw"unknown ECDSA sig r length error";if(r.length%32!=0)throw"unknown ECDSA sig s length error";return n+r},hr.crypto.ECDSA.concatSigToASN1Sig=function(t){if(t.length/2*8%128!=0)throw"unknown ECDSA concatinated r-s sig length error";var e=t.substr(0,t.length/2),n=t.substr(t.length/2);return hr.crypto.ECDSA.hexRSSigToASN1Sig(e,n)},hr.crypto.ECDSA.hexRSSigToASN1Sig=function(t,e){var n=new o(t,16),r=new o(e,16);return hr.crypto.ECDSA.biRSSigToASN1Sig(n,r)},hr.crypto.ECDSA.biRSSigToASN1Sig=function(t,e){var n=hr.asn1,r=new n.DERInteger({bigint:t}),i=new n.DERInteger({bigint:e}),o=new n.DERSequence({array:[r,i]});return o.getEncodedHex()},hr.crypto.ECDSA.getName=function(t){return"2a8648ce3d030107"===t?"secp256r1":"2b8104000a"===t?"secp256k1":"2b81040022"===t?"secp384r1":"|secp256r1|NIST P-256|P-256|prime256v1|".indexOf(t)!==-1?"secp256r1":"|secp256k1|".indexOf(t)!==-1?"secp256k1":"|secp384r1|NIST P-384|P-384|".indexOf(t)!==-1?"secp384r1":null},"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.crypto&&hr.crypto||(hr.crypto={}),hr.crypto.ECParameterDB=new function(){function t(t){return new o(t,16)}var e={},n={};this.getByName=function(t){var r=t;if("undefined"!=typeof n[r]&&(r=n[t]),"undefined"!=typeof e[r])return e[r];throw"unregistered EC curve name: "+r},this.regist=function(r,i,o,s,a,u,c,f,h,l,p,d){e[r]={};var g=t(o),v=t(s),y=t(a),m=t(u),S=t(c),b=new He(g,v,y),F=b.decodePointHex("04"+f+h);e[r].name=r,e[r].keylen=i,e[r].curve=b,e[r].G=F,e[r].n=m,e[r].h=S,e[r].oid=p,e[r].info=d;for(var w=0;w<l.length;w++)n[l[w]]=r}},hr.crypto.ECParameterDB.regist("secp128r1",128,"FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC","E87579C11079F43DD824993C2CEE5ED3","FFFFFFFE0000000075A30D1B9038A115","1","161FF7528B899B2D0C28607CA52C5B86","CF5AC8395BAFEB13C02DA292DDED7A83",[],"","secp128r1 : SECG curve over a 128 bit prime field"),hr.crypto.ECParameterDB.regist("secp160k1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73","0","7","0100000000000000000001B8FA16DFAB9ACA16B6B3","1","3B4C382CE37AA192A4019E763036F4F5DD4D7EBB","938CF935318FDCED6BC28286531733C3F03C4FEE",[],"","secp160k1 : SECG curve over a 160 bit prime field"),hr.crypto.ECParameterDB.regist("secp160r1",160,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC","1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45","0100000000000000000001F4C8F927AED3CA752257","1","4A96B5688EF573284664698968C38BB913CBFC82","23A628553168947D59DCC912042351377AC5FB32",[],"","secp160r1 : SECG curve over a 160 bit prime field"),hr.crypto.ECParameterDB.regist("secp192k1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37","0","3","FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D","1","DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D","9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D",[]),hr.crypto.ECParameterDB.regist("secp192r1",192,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC","64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1","FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831","1","188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012","07192B95FFC8DA78631011ED6B24CDD573F977A11E794811",[]),hr.crypto.ECParameterDB.regist("secp224r1",224,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE","B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4","FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D","1","B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21","BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34",[]),hr.crypto.ECParameterDB.regist("secp256k1",256,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F","0","7","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141","1","79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798","483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",[]),hr.crypto.ECParameterDB.regist("secp256r1",256,"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF","FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC","5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B","FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551","1","6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296","4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",["NIST P-256","P-256","prime256v1"]),hr.crypto.ECParameterDB.regist("secp384r1",384,"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC","B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973","1","AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7","3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f",["NIST P-384","P-384"]),hr.crypto.ECParameterDB.regist("secp521r1",521,"1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC","051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00","1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409","1","C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66","011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650",["NIST P-521","P-521"]);var gr=function(){var t=function(t,e,n){return r(Vn.AES,t,e,n)},e=function(t,e,n){return r(Vn.TripleDES,t,e,n)},n=function(t,e,n){return r(Vn.DES,t,e,n)},r=function(t,e,n,r){var i=Vn.enc.Hex.parse(e),o=Vn.enc.Hex.parse(n),s=Vn.enc.Hex.parse(r),a={};a.key=o,a.iv=s,a.ciphertext=i;var u=t.decrypt(a,o,{iv:s});return Vn.enc.Hex.stringify(u)},i=function(t,e,n){return a(Vn.AES,t,e,n)},o=function(t,e,n){return a(Vn.TripleDES,t,e,n)},s=function(t,e,n){return a(Vn.DES,t,e,n)},a=function(t,e,n,r){var i=Vn.enc.Hex.parse(e),o=Vn.enc.Hex.parse(n),s=Vn.enc.Hex.parse(r),a=t.encrypt(i,o,{iv:s}),u=Vn.enc.Hex.parse(a.toString()),c=Vn.enc.Base64.stringify(u);return c},u={"AES-256-CBC":{proc:t,eproc:i,keylen:32,ivlen:16},"AES-192-CBC":{proc:t,eproc:i,keylen:24,ivlen:16},"AES-128-CBC":{proc:t,eproc:i,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:e,eproc:o,keylen:24,ivlen:8},"DES-CBC":{proc:n,eproc:s,keylen:8,ivlen:8}},c=function(t){var e=Vn.lib.WordArray.random(t),n=Vn.enc.Hex.stringify(e);return n},f=function(t){var e={},n=t.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"));n&&(e.cipher=n[1],e.ivsalt=n[2]);var r=t.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"));r&&(e.type=r[1]);var i=-1,o=0;t.indexOf("\r\n\r\n")!=-1&&(i=t.indexOf("\r\n\r\n"),o=2),t.indexOf("\n\n")!=-1&&(i=t.indexOf("\n\n"),o=1);var s=t.indexOf("-----END");if(i!=-1&&s!=-1){var a=t.substring(i+2*o,s-o);a=a.replace(/\s+/g,""),e.data=a}return e},h=function(t,e,n){for(var r=n.substring(0,16),i=Vn.enc.Hex.parse(r),o=Vn.enc.Utf8.parse(e),s=u[t].keylen+u[t].ivlen,a="",c=null;;){var f=Vn.algo.MD5.create();if(null!=c&&f.update(c),f.update(o),f.update(i),c=f.finalize(),a+=Vn.enc.Hex.stringify(c),a.length>=2*s)break}var h={};return h.keyhex=a.substr(0,2*u[t].keylen),h.ivhex=a.substr(2*u[t].keylen,2*u[t].ivlen),h},l=function(t,e,n,r){var i=Vn.enc.Base64.parse(t),o=Vn.enc.Hex.stringify(i),s=u[e].proc,a=s(o,n,r);return a},p=function(t,e,n,r){var i=u[e].eproc,o=i(t,n,r);return o};return{version:"1.0.0",parsePKCS5PEM:function(t){return f(t)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(t,e,n){return h(t,e,n)},decryptKeyB64:function(t,e,n,r){return l(t,e,n,r)},getDecryptedKeyHex:function(t,e){var n=f(t),r=(n.type,n.cipher),i=n.ivsalt,o=n.data,s=h(r,e,i),a=s.keyhex,u=l(o,r,a,i);return u},getEncryptedPKCS5PEMFromPrvKeyHex:function(t,e,n,r,i){var o="";if("undefined"!=typeof r&&null!=r||(r="AES-256-CBC"),"undefined"==typeof u[r])throw"KEYUTIL unsupported algorithm: "+r;if("undefined"==typeof i||null==i){var s=u[r].ivlen,a=c(s);i=a.toUpperCase()}var f=h(r,n,i),l=f.keyhex,d=p(e,r,l,i),g=d.replace(/(.{64})/g,"$1\r\n"),o="-----BEGIN "+t+" PRIVATE KEY-----\r\n";return o+="Proc-Type: 4,ENCRYPTED\r\n",o+="DEK-Info: "+r+","+i+"\r\n",o+="\r\n",o+=g,o+="\r\n-----END "+t+" PRIVATE KEY-----\r\n"},parseHexOfEncryptedPKCS8:function(t){var e=fr,n=e.getChildIdx,r=e.getV,i={},o=n(t,0);if(2!=o.length)throw"malformed format: SEQUENCE(0).items != 2: "+o.length;i.ciphertext=r(t,o[1]);var s=n(t,o[0]);if(2!=s.length)throw"malformed format: SEQUENCE(0.0).items != 2: "+s.length;if("2a864886f70d01050d"!=r(t,s[0]))throw"this only supports pkcs5PBES2";var a=n(t,s[1]);if(2!=s.length)throw"malformed format: SEQUENCE(0.0.1).items != 2: "+a.length;var u=n(t,a[1]);if(2!=u.length)throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+u.length;if("2a864886f70d0307"!=r(t,u[0]))throw"this only supports TripleDES";i.encryptionSchemeAlg="TripleDES",i.encryptionSchemeIV=r(t,u[1]);var c=n(t,a[0]);if(2!=c.length)throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+c.length;if("2a864886f70d01050c"!=r(t,c[0]))throw"this only supports pkcs5PBKDF2";var f=n(t,c[1]);if(f.length<2)throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+f.length;i.pbkdf2Salt=r(t,f[0]);var h=r(t,f[1]);try{i.pbkdf2Iter=parseInt(h,16)}catch(t){throw"malformed format pbkdf2Iter: "+h}return i},getPBKDF2KeyHexFromParam:function(t,e){var n=Vn.enc.Hex.parse(t.pbkdf2Salt),r=t.pbkdf2Iter,i=Vn.PBKDF2(e,n,{keySize:6,iterations:r}),o=Vn.enc.Hex.stringify(i);return o},_getPlainPKCS8HexFromEncryptedPKCS8PEM:function(t,e){var n=vn(t,"ENCRYPTED PRIVATE KEY"),r=this.parseHexOfEncryptedPKCS8(n),i=gr.getPBKDF2KeyHexFromParam(r,e),o={};o.ciphertext=Vn.enc.Hex.parse(r.ciphertext);var s=Vn.enc.Hex.parse(i),a=Vn.enc.Hex.parse(r.encryptionSchemeIV),u=Vn.TripleDES.decrypt(o,s,{iv:a}),c=Vn.enc.Hex.stringify(u);return c},getKeyFromEncryptedPKCS8PEM:function(t,e){var n=this._getPlainPKCS8HexFromEncryptedPKCS8PEM(t,e),r=this.getKeyFromPlainPrivatePKCS8Hex(n);return r},parsePlainPrivatePKCS8Hex:function(t){var e=fr,n=e.getChildIdx,r=e.getV,i={};if(i.algparam=null,"30"!=t.substr(0,2))throw"malformed plain PKCS8 private key(code:001)";var o=n(t,0);if(3!=o.length)throw"malformed plain PKCS8 private key(code:002)";if("30"!=t.substr(o[1],2))throw"malformed PKCS8 private key(code:003)";var s=n(t,o[1]);if(2!=s.length)throw"malformed PKCS8 private key(code:004)";if("06"!=t.substr(s[0],2))throw"malformed PKCS8 private key(code:005)";if(i.algoid=r(t,s[0]),"06"==t.substr(s[1],2)&&(i.algparam=r(t,s[1])),"04"!=t.substr(o[2],2))throw"malformed PKCS8 private key(code:006)";return i.keyidx=e.getVidx(t,o[2]),i},getKeyFromPlainPrivatePKCS8PEM:function(t){var e=vn(t,"PRIVATE KEY"),n=this.getKeyFromPlainPrivatePKCS8Hex(e);return n},getKeyFromPlainPrivatePKCS8Hex:function(t){var e,n=this.parsePlainPrivatePKCS8Hex(t);if("2a864886f70d010101"==n.algoid)e=new ve;else if("2a8648ce380401"==n.algoid)e=new hr.crypto.DSA;else{if("2a8648ce3d0201"!=n.algoid)throw"unsupported private key algorithm";e=new hr.crypto.ECDSA}return e.readPKCS8PrvKeyHex(t),e},_getKeyFromPublicPKCS8Hex:function(t){var e,n=fr.getVbyList(t,0,[0,0],"06");if("2a864886f70d010101"===n)e=new ve;else if("2a8648ce380401"===n)e=new hr.crypto.DSA;else{if("2a8648ce3d0201"!==n)throw"unsupported PKCS#8 public key hex";e=new hr.crypto.ECDSA}return e.readPKCS8PubKeyHex(t),e},parsePublicRawRSAKeyHex:function(t){var e=fr,n=e.getChildIdx,r=e.getV,i={};if("30"!=t.substr(0,2))throw"malformed RSA key(code:001)";var o=n(t,0);if(2!=o.length)throw"malformed RSA key(code:002)";if("02"!=t.substr(o[0],2))throw"malformed RSA key(code:003)";if(i.n=r(t,o[0]),"02"!=t.substr(o[1],2))throw"malformed RSA key(code:004)";return i.e=r(t,o[1]),i},parsePublicPKCS8Hex:function(t){var e=fr,n=e.getChildIdx,r=e.getV,i={};i.algparam=null;var o=n(t,0);if(2!=o.length)throw"outer DERSequence shall have 2 elements: "+o.length;var s=o[0];if("30"!=t.substr(s,2))throw"malformed PKCS8 public key(code:001)";var a=n(t,s);if(2!=a.length)throw"malformed PKCS8 public key(code:002)";if("06"!=t.substr(a[0],2))throw"malformed PKCS8 public key(code:003)";if(i.algoid=r(t,a[0]),"06"==t.substr(a[1],2)?i.algparam=r(t,a[1]):"30"==t.substr(a[1],2)&&(i.algparam={},i.algparam.p=e.getVbyList(t,a[1],[0],"02"),i.algparam.q=e.getVbyList(t,a[1],[1],"02"),i.algparam.g=e.getVbyList(t,a[1],[2],"02")),"03"!=t.substr(o[1],2))throw"malformed PKCS8 public key(code:004)";return i.key=r(t,o[1]).substr(2),i}}}();gr.getKey=function(t,e,n){var r=fr,i=r.getChildIdx,s=(r.getV,r.getVbyList),a=hr.crypto,u=a.ECDSA,c=a.DSA,f=ve,h=vn,l=gr;if("undefined"!=typeof f&&t instanceof f)return t;if("undefined"!=typeof u&&t instanceof u)return t;if("undefined"!=typeof c&&t instanceof c)return t;if(void 0!==t.curve&&void 0!==t.xy&&void 0===t.d)return new u({pub:t.xy,curve:t.curve});if(void 0!==t.curve&&void 0!==t.d)return new u({prv:t.d,curve:t.curve});if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0===t.d){var p=new f;return p.setPublic(t.n,t.e),p}if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0!==t.p&&void 0!==t.q&&void 0!==t.dp&&void 0!==t.dq&&void 0!==t.co&&void 0===t.qi){var p=new f;return p.setPrivateEx(t.n,t.e,t.d,t.p,t.q,t.dp,t.dq,t.co),p}if(void 0===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0===t.p){var p=new f;return p.setPrivate(t.n,t.e,t.d),p}if(void 0!==t.p&&void 0!==t.q&&void 0!==t.g&&void 0!==t.y&&void 0===t.x){var p=new c;return p.setPublic(t.p,t.q,t.g,t.y),p}if(void 0!==t.p&&void 0!==t.q&&void 0!==t.g&&void 0!==t.y&&void 0!==t.x){var p=new c;return p.setPrivate(t.p,t.q,t.g,t.y,t.x),p}if("RSA"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0===t.d){var p=new f;return p.setPublic(on(t.n),on(t.e)),p}if("RSA"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d&&void 0!==t.p&&void 0!==t.q&&void 0!==t.dp&&void 0!==t.dq&&void 0!==t.qi){var p=new f;return p.setPrivateEx(on(t.n),on(t.e),on(t.d),on(t.p),on(t.q),on(t.dp),on(t.dq),on(t.qi)),p}if("RSA"===t.kty&&void 0!==t.n&&void 0!==t.e&&void 0!==t.d){var p=new f;return p.setPrivate(on(t.n),on(t.e),on(t.d)),p}if("EC"===t.kty&&void 0!==t.crv&&void 0!==t.x&&void 0!==t.y&&void 0===t.d){var d=new u({curve:t.crv}),g=d.ecparams.keylen/4,v=("0000000000"+on(t.x)).slice(-g),y=("0000000000"+on(t.y)).slice(-g),m="04"+v+y;return d.setPublicKeyHex(m),d}if("EC"===t.kty&&void 0!==t.crv&&void 0!==t.x&&void 0!==t.y&&void 0!==t.d){var d=new u({curve:t.crv}),g=d.ecparams.keylen/4,v=("0000000000"+on(t.x)).slice(-g),y=("0000000000"+on(t.y)).slice(-g),m="04"+v+y,S=("0000000000"+on(t.d)).slice(-g);return d.setPublicKeyHex(m),d.setPrivateKeyHex(S),d}if("pkcs5prv"===n){var b,p,F=t,r=fr;if(b=i(F,0),9===b.length)p=new f,p.readPKCS5PrvKeyHex(F);else if(6===b.length)p=new c,p.readPKCS5PrvKeyHex(F);else{if(!(b.length>2&&"04"===F.substr(b[1],2)))throw"unsupported PKCS#1/5 hexadecimal key";p=new u,p.readPKCS5PrvKeyHex(F)}return p}if("pkcs8prv"===n){var p=l.getKeyFromPlainPrivatePKCS8Hex(t);return p}if("pkcs8pub"===n)return l._getKeyFromPublicPKCS8Hex(t);if("x509pub"===n)return Ln.getPublicKeyFromCertHex(t);if(t.indexOf("-END CERTIFICATE-",0)!=-1||t.indexOf("-END X509 CERTIFICATE-",0)!=-1||t.indexOf("-END TRUSTED CERTIFICATE-",0)!=-1)return Ln.getPublicKeyFromCertPEM(t);if(t.indexOf("-END PUBLIC KEY-")!=-1){var w=vn(t,"PUBLIC KEY");return l._getKeyFromPublicPKCS8Hex(w)}if(t.indexOf("-END RSA PRIVATE KEY-")!=-1&&t.indexOf("4,ENCRYPTED")==-1){var _=h(t,"RSA PRIVATE KEY");return l.getKey(_,null,"pkcs5prv")}if(t.indexOf("-END DSA PRIVATE KEY-")!=-1&&t.indexOf("4,ENCRYPTED")==-1){var x=h(t,"DSA PRIVATE KEY"),E=s(x,0,[1],"02"),A=s(x,0,[2],"02"),P=s(x,0,[3],"02"),C=s(x,0,[4],"02"),k=s(x,0,[5],"02"),p=new c;return p.setPrivate(new o(E,16),new o(A,16),new o(P,16),new o(C,16),new o(k,16)),p}if(t.indexOf("-END PRIVATE KEY-")!=-1)return l.getKeyFromPlainPrivatePKCS8PEM(t);if(t.indexOf("-END RSA PRIVATE KEY-")!=-1&&t.indexOf("4,ENCRYPTED")!=-1){var T=l.getDecryptedKeyHex(t,e),R=new ve;return R.readPKCS5PrvKeyHex(T),R}if(t.indexOf("-END EC PRIVATE KEY-")!=-1&&t.indexOf("4,ENCRYPTED")!=-1){var x=l.getDecryptedKeyHex(t,e),p=s(x,0,[1],"04"),I=s(x,0,[2,0],"06"),D=s(x,0,[3,0],"03").substr(2),N="";if(void 0===hr.crypto.OID.oidhex2name[I])throw"undefined OID(hex) in KJUR.crypto.OID: "+I;N=hr.crypto.OID.oidhex2name[I];var d=new u({curve:N});return d.setPublicKeyHex(D),d.setPrivateKeyHex(p),d.isPublic=!1,d}if(t.indexOf("-END DSA PRIVATE KEY-")!=-1&&t.indexOf("4,ENCRYPTED")!=-1){var x=l.getDecryptedKeyHex(t,e),E=s(x,0,[1],"02"),A=s(x,0,[2],"02"),P=s(x,0,[3],"02"),C=s(x,0,[4],"02"),k=s(x,0,[5],"02"),p=new c;return p.setPrivate(new o(E,16),new o(A,16),new o(P,16),new o(C,16),new o(k,16)),p}if(t.indexOf("-END ENCRYPTED PRIVATE KEY-")!=-1)return l.getKeyFromEncryptedPKCS8PEM(t,e);throw"not supported argument"},gr.generateKeypair=function(t,e){if("RSA"==t){var n=e,r=new ve;r.generate(n,"10001"),r.isPrivate=!0,r.isPublic=!0;var i=new ve,o=r.n.toString(16),s=r.e.toString(16);i.setPublic(o,s),i.isPrivate=!1,i.isPublic=!0;var a={};return a.prvKeyObj=r,a.pubKeyObj=i,a}if("EC"==t){var u=e,c=new hr.crypto.ECDSA({curve:u}),f=c.generateKeyPairHex(),r=new hr.crypto.ECDSA({curve:u});r.setPublicKeyHex(f.ecpubhex),r.setPrivateKeyHex(f.ecprvhex),r.isPrivate=!0,r.isPublic=!1;var i=new hr.crypto.ECDSA({curve:u});i.setPublicKeyHex(f.ecpubhex),i.isPrivate=!1,i.isPublic=!0;var a={};return a.prvKeyObj=r,a.pubKeyObj=i,a}throw"unknown algorithm: "+t},gr.getPEM=function(t,e,n,r,i,o){function s(t){var e=p({seq:[{int:0},{int:{bigint:t.n}},{int:t.e},{int:{bigint:t.d}},{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.dmp1}},{int:{bigint:t.dmq1}},{int:{bigint:t.coeff}}]});return e}function a(t){var e=p({seq:[{int:1},{octstr:{hex:t.prvKeyHex}},{tag:["a0",!0,{oid:{name:t.curveName}}]},{tag:["a1",!0,{bitstr:{hex:"00"+t.pubKeyHex}}]}]});return e}function u(t){var e=p({seq:[{int:0},{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.g}},{int:{bigint:t.y}},{int:{bigint:t.x}}]});return e}var c=hr,f=c.asn1,h=f.DERObjectIdentifier,l=f.DERInteger,p=f.ASN1Util.newObject,d=f.x509,g=d.SubjectPublicKeyInfo,v=c.crypto,y=v.DSA,m=v.ECDSA,S=ve;if((void 0!==S&&t instanceof S||void 0!==y&&t instanceof y||void 0!==m&&t instanceof m)&&1==t.isPublic&&(void 0===e||"PKCS8PUB"==e)){var b=new g(t),F=b.getEncodedHex();return gn(F,"PUBLIC KEY")}if("PKCS1PRV"==e&&void 0!==S&&t instanceof S&&(void 0===n||null==n)&&1==t.isPrivate){var b=s(t),F=b.getEncodedHex();return gn(F,"RSA PRIVATE KEY")}if("PKCS1PRV"==e&&void 0!==m&&t instanceof m&&(void 0===n||null==n)&&1==t.isPrivate){var w=new h({name:t.curveName}),_=w.getEncodedHex(),x=a(t),E=x.getEncodedHex(),A="";return A+=gn(_,"EC PARAMETERS"),A+=gn(E,"EC PRIVATE KEY")}if("PKCS1PRV"==e&&void 0!==y&&t instanceof y&&(void 0===n||null==n)&&1==t.isPrivate){var b=u(t),F=b.getEncodedHex();return gn(F,"DSA PRIVATE KEY")}if("PKCS5PRV"==e&&void 0!==S&&t instanceof S&&void 0!==n&&null!=n&&1==t.isPrivate){var b=s(t),F=b.getEncodedHex();return void 0===r&&(r="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",F,n,r,o)}if("PKCS5PRV"==e&&void 0!==m&&t instanceof m&&void 0!==n&&null!=n&&1==t.isPrivate){var b=a(t),F=b.getEncodedHex();return void 0===r&&(r="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",F,n,r,o)}if("PKCS5PRV"==e&&void 0!==y&&t instanceof y&&void 0!==n&&null!=n&&1==t.isPrivate){var b=u(t),F=b.getEncodedHex();return void 0===r&&(r="DES-EDE3-CBC"),this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",F,n,r,o)}var P=function(t,e){var n=C(t,e),r=new p({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:n.pbkdf2Salt}},{int:n.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:n.encryptionSchemeIV}}]}]}]},{octstr:{hex:n.ciphertext}}]});return r.getEncodedHex()},C=function(t,e){var n=100,r=Vn.lib.WordArray.random(8),i="DES-EDE3-CBC",o=Vn.lib.WordArray.random(8),s=Vn.PBKDF2(e,r,{keySize:6,iterations:n}),a=Vn.enc.Hex.parse(t),u=Vn.TripleDES.encrypt(a,s,{iv:o})+"",c={};return c.ciphertext=u,c.pbkdf2Salt=Vn.enc.Hex.stringify(r),c.pbkdf2Iter=n,c.encryptionSchemeAlg=i,c.encryptionSchemeIV=Vn.enc.Hex.stringify(o),c};if("PKCS8PRV"==e&&void 0!=S&&t instanceof S&&1==t.isPrivate){var k=s(t),T=k.getEncodedHex(),b=p({seq:[{int:0},{seq:[{oid:{name:"rsaEncryption"}},{null:!0}]},{octstr:{hex:T}}]}),F=b.getEncodedHex();if(void 0===n||null==n)return gn(F,"PRIVATE KEY");var E=P(F,n);return gn(E,"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==e&&void 0!==m&&t instanceof m&&1==t.isPrivate){var k=new p({seq:[{int:1},{octstr:{hex:t.prvKeyHex}},{tag:["a1",!0,{bitstr:{hex:"00"+t.pubKeyHex}}]}]}),T=k.getEncodedHex(),b=p({seq:[{int:0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:t.curveName}}]},{octstr:{hex:T}}]}),F=b.getEncodedHex();if(void 0===n||null==n)return gn(F,"PRIVATE KEY");var E=P(F,n);return gn(E,"ENCRYPTED PRIVATE KEY")}if("PKCS8PRV"==e&&void 0!==y&&t instanceof y&&1==t.isPrivate){var k=new l({bigint:t.x}),T=k.getEncodedHex(),b=p({seq:[{int:0},{seq:[{oid:{name:"dsa"}},{seq:[{int:{bigint:t.p}},{int:{bigint:t.q}},{int:{bigint:t.g}}]}]},{octstr:{hex:T}}]}),F=b.getEncodedHex();if(void 0===n||null==n)return gn(F,"PRIVATE KEY");var E=P(F,n);return gn(E,"ENCRYPTED PRIVATE KEY")}throw"unsupported object nor format"},gr.getKeyFromCSRPEM=function(t){var e=vn(t,"CERTIFICATE REQUEST"),n=gr.getKeyFromCSRHex(e);return n},gr.getKeyFromCSRHex=function(t){var e=gr.parseCSRHex(t),n=gr.getKey(e.p8pubkeyhex,null,"pkcs8pub");return n},gr.parseCSRHex=function(t){var e=fr,n=e.getChildIdx,r=e.getTLV,i={},o=t;if("30"!=o.substr(0,2))throw"malformed CSR(code:001)";var s=n(o,0);if(s.length<1)throw"malformed CSR(code:002)";if("30"!=o.substr(s[0],2))throw"malformed CSR(code:003)";var a=n(o,s[0]);if(a.length<3)throw"malformed CSR(code:004)";return i.p8pubkeyhex=r(o,a[2]),i},gr.getJWKFromKey=function(t){var e={};if(t instanceof ve&&t.isPrivate)return e.kty="RSA",e.n=rn(t.n.toString(16)),e.e=rn(t.e.toString(16)),e.d=rn(t.d.toString(16)),e.p=rn(t.p.toString(16)),e.q=rn(t.q.toString(16)),e.dp=rn(t.dmp1.toString(16)),e.dq=rn(t.dmq1.toString(16)),e.qi=rn(t.coeff.toString(16)),e;if(t instanceof ve&&t.isPublic)return e.kty="RSA",e.n=rn(t.n.toString(16)),e.e=rn(t.e.toString(16)),e;if(t instanceof hr.crypto.ECDSA&&t.isPrivate){var n=t.getShortNISTPCurveName();if("P-256"!==n&&"P-384"!==n)throw"unsupported curve name for JWT: "+n;var r=t.getPublicKeyXYHex();return e.kty="EC",e.crv=n,e.x=rn(r.x),e.y=rn(r.y),e.d=rn(t.prvKeyHex),e}if(t instanceof hr.crypto.ECDSA&&t.isPublic){var n=t.getShortNISTPCurveName();if("P-256"!==n&&"P-384"!==n)throw"unsupported curve name for JWT: "+n;var r=t.getPublicKeyXYHex();return e.kty="EC",e.crv=n,e.x=rn(r.x),e.y=rn(r.y),e}throw"not supported key object"},ve.getPosArrayOfChildrenFromHex=function(t){return fr.getChildIdx(t,0)},ve.getHexValueArrayOfChildrenFromHex=function(t){var e=fr,n=e.getV,r=ve.getPosArrayOfChildrenFromHex(t),i=n(t,r[0]),o=n(t,r[1]),s=n(t,r[2]),a=n(t,r[3]),u=n(t,r[4]),c=n(t,r[5]),f=n(t,r[6]),h=n(t,r[7]),l=n(t,r[8]),r=new Array;return r.push(i,o,s,a,u,c,f,h,l),r},ve.prototype.readPrivateKeyFromPEMString=function(t){var e=vn(t),n=ve.getHexValueArrayOfChildrenFromHex(e);this.setPrivateEx(n[1],n[2],n[3],n[4],n[5],n[6],n[7],n[8])},ve.prototype.readPKCS5PrvKeyHex=function(t){var e=ve.getHexValueArrayOfChildrenFromHex(t);this.setPrivateEx(e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8])},ve.prototype.readPKCS8PrvKeyHex=function(t){var e,n,r,i,o,s,a,u,c=fr,f=c.getVbyList;if(c.isASN1HEX(t)===!1)throw"not ASN.1 hex string";try{e=f(t,0,[2,0,1],"02"),n=f(t,0,[2,0,2],"02"),r=f(t,0,[2,0,3],"02"),i=f(t,0,[2,0,4],"02"),o=f(t,0,[2,0,5],"02"),s=f(t,0,[2,0,6],"02"),a=f(t,0,[2,0,7],"02"),u=f(t,0,[2,0,8],"02")}catch(t){throw"malformed PKCS#8 plain RSA private key"}this.setPrivateEx(e,n,r,i,o,s,a,u)},ve.prototype.readPKCS5PubKeyHex=function(t){var e=fr,n=e.getV;if(e.isASN1HEX(t)===!1)throw"keyHex is not ASN.1 hex string";var r=e.getChildIdx(t,0);if(2!==r.length||"02"!==t.substr(r[0],2)||"02"!==t.substr(r[1],2))throw"wrong hex for PKCS#5 public key";var i=n(t,r[0]),o=n(t,r[1]);this.setPublic(i,o)},ve.prototype.readPKCS8PubKeyHex=function(t){var e=fr;if(e.isASN1HEX(t)===!1)throw"not ASN.1 hex string";if("06092a864886f70d010101"!==e.getTLVbyList(t,0,[0,0]))throw"not PKCS8 RSA public key";var n=e.getTLVbyList(t,0,[1,0]);this.readPKCS5PubKeyHex(n)},ve.prototype.readCertPubKeyHex=function(t,e){var n,r;n=new Ln,n.readCertHex(t),r=n.getPublicKeyHex(),this.readPKCS8PubKeyHex(r)};var vr=new RegExp("");vr.compile("[^0-9a-f]","gi"),ve.prototype.sign=function(t,e){var n=function(t){return hr.crypto.Util.hashString(t,e)},r=n(t);return this.signWithMessageHash(r,e)},ve.prototype.signWithMessageHash=function(t,e){var n=hr.crypto.Util.getPaddedDigestInfoHex(t,e,this.n.bitLength()),r=le(n,16),i=this.doPrivate(r),o=i.toString(16);return Nn(o,this.n.bitLength()); },ve.prototype.signPSS=function(t,e,n){var r=function(t){return hr.crypto.Util.hashHex(t,e)},i=r(hn(t));return void 0===n&&(n=-1),this.signWithMessageHashPSS(i,e,n)},ve.prototype.signWithMessageHashPSS=function(t,e,n){var r,i=fn(t),s=i.length,a=this.n.bitLength()-1,u=Math.ceil(a/8),c=function(t){return hr.crypto.Util.hashHex(t,e)};if(n===-1||void 0===n)n=s;else if(n===-2)n=u-s-2;else if(n<-2)throw"invalid salt length";if(u<s+n+2)throw"data too long";var f="";n>0&&(f=new Array(n),(new he).nextBytes(f),f=String.fromCharCode.apply(String,f));var h=fn(c(hn("\0\0\0\0\0\0\0\0"+i+f))),l=[];for(r=0;r<u-n-s-2;r+=1)l[r]=0;var p=String.fromCharCode.apply(String,l)+""+f,d=On(h,p.length,c),g=[];for(r=0;r<p.length;r+=1)g[r]=p.charCodeAt(r)^d.charCodeAt(r);var v=65280>>8*u-a&255;for(g[0]&=~v,r=0;r<s;r++)g.push(h.charCodeAt(r));return g.push(188),Nn(this.doPrivate(new o(g)).toString(16),this.n.bitLength())},ve.prototype.verify=function(t,e){e=e.replace(vr,""),e=e.replace(/[ \n]+/g,"");var n=le(e,16);if(n.bitLength()>this.n.bitLength())return 0;var r=this.doPublic(n),i=r.toString(16).replace(/^1f+00/,""),o=jn(i);if(0==o.length)return!1;var s=o[0],a=o[1],u=function(t){return hr.crypto.Util.hashString(t,s)},c=u(t);return a==c},ve.prototype.verifyWithMessageHash=function(t,e){e=e.replace(vr,""),e=e.replace(/[ \n]+/g,"");var n=le(e,16);if(n.bitLength()>this.n.bitLength())return 0;var r=this.doPublic(n),i=r.toString(16).replace(/^1f+00/,""),o=jn(i);if(0==o.length)return!1;var s=(o[0],o[1]);return s==t},ve.prototype.verifyPSS=function(t,e,n,r){var i=function(t){return hr.crypto.Util.hashHex(t,n)},o=i(hn(t));return void 0===r&&(r=-1),this.verifyWithMessageHashPSS(o,e,n,r)},ve.prototype.verifyWithMessageHashPSS=function(t,e,n,r){var i=new o(e,16);if(i.bitLength()>this.n.bitLength())return!1;var s,a=function(t){return hr.crypto.Util.hashHex(t,n)},u=fn(t),c=u.length,f=this.n.bitLength()-1,h=Math.ceil(f/8);if(r===-1||void 0===r)r=c;else if(r===-2)r=h-c-2;else if(r<-2)throw"invalid salt length";if(h<c+r+2)throw"data too long";var l=this.doPublic(i).toByteArray();for(s=0;s<l.length;s+=1)l[s]&=255;for(;l.length<h;)l.unshift(0);if(188!==l[h-1])throw"encoded message does not end in 0xbc";l=String.fromCharCode.apply(String,l);var p=l.substr(0,h-c-1),d=l.substr(p.length,c),g=65280>>8*h-f&255;if(0!==(p.charCodeAt(0)&g))throw"bits beyond keysize not zero";var v=On(d,p.length,a),y=[];for(s=0;s<p.length;s+=1)y[s]=p.charCodeAt(s)^v.charCodeAt(s);y[0]&=~g;var m=h-c-r-2;for(s=0;s<m;s+=1)if(0!==y[s])throw"leftmost octets not zero";if(1!==y[m])throw"0x01 marker not found";return d===fn(a(hn("\0\0\0\0\0\0\0\0"+u+String.fromCharCode.apply(String,y.slice(-r)))))},ve.SALT_LEN_HLEN=-1,ve.SALT_LEN_MAX=-2,ve.SALT_LEN_RECOVER=-2,Ln.hex2dn=function(t,e){if(void 0===e&&(e=0),"30"!==t.substr(e,2))throw"malformed DN";for(var n=new Array,r=fr.getChildIdx(t,e),i=0;i<r.length;i++)n.push(Ln.hex2rdn(t,r[i]));return n=n.map(function(t){return t.replace("/","\\/")}),"/"+n.join("/")},Ln.hex2rdn=function(t,e){if(void 0===e&&(e=0),"31"!==t.substr(e,2))throw"malformed RDN";for(var n=new Array,r=fr.getChildIdx(t,e),i=0;i<r.length;i++)n.push(Ln.hex2attrTypeValue(t,r[i]));return n=n.map(function(t){return t.replace("+","\\+")}),n.join("+")},Ln.hex2attrTypeValue=function(t,e){var n=fr,r=n.getV;if(void 0===e&&(e=0),"30"!==t.substr(e,2))throw"malformed attribute type and value";var i=n.getChildIdx(t,e);2!==i.length||"06"!==t.substr(i[0],2);var o=r(t,i[0]),s=hr.asn1.ASN1Util.oidHexToInt(o),a=hr.asn1.x509.OID.oid2atype(s),u=r(t,i[1]),c=fn(u);return a+"="+c},Ln.getPublicKeyFromCertHex=function(t){var e=new Ln;return e.readCertHex(t),e.getPublicKey()},Ln.getPublicKeyFromCertPEM=function(t){var e=new Ln;return e.readCertPEM(t),e.getPublicKey()},Ln.getPublicKeyInfoPropOfCertPEM=function(t){var e,n,r=fr,i=r.getVbyList,o={};return o.algparam=null,e=new Ln,e.readCertPEM(t),n=e.getPublicKeyHex(),o.keyhex=i(n,0,[1],"03").substr(2),o.algoid=i(n,0,[0,0],"06"),"2a8648ce3d0201"===o.algoid&&(o.algparam=i(n,0,[0,1],"06")),o},Ln.KEYUSAGE_NAME=["digitalSignature","nonRepudiation","keyEncipherment","dataEncipherment","keyAgreement","keyCertSign","cRLSign","encipherOnly","decipherOnly"],"undefined"!=typeof hr&&hr||(hr={}),"undefined"!=typeof hr.jws&&hr.jws||(hr.jws={}),hr.jws.JWS=function(){var t=hr,e=t.jws.JWS,n=e.isSafeJSONString;this.parseJWS=function(t,e){if(void 0===this.parsedJWS||!e&&void 0===this.parsedJWS.sigvalH){var r=t.match(/^([^.]+)\.([^.]+)\.([^.]+)$/);if(null==r)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";var i=r[1],o=r[2],s=r[3],a=i+"."+o;if(this.parsedJWS={},this.parsedJWS.headB64U=i,this.parsedJWS.payloadB64U=o,this.parsedJWS.sigvalB64U=s,this.parsedJWS.si=a,!e){var u=on(s),c=le(u,16);this.parsedJWS.sigvalH=u,this.parsedJWS.sigvalBI=c}var f=pr(i),h=pr(o);if(this.parsedJWS.headS=f,this.parsedJWS.payloadS=h,!n(f,this.parsedJWS,"headP"))throw"malformed JSON string for JWS Head: "+f}}},hr.jws.JWS.sign=function(t,e,n,r,i){var o,s,a,u=hr,c=u.jws,f=c.JWS,h=f.readSafeJSONString,l=f.isSafeJSONString,p=u.crypto,d=(p.ECDSA,p.Mac),g=p.Signature,v=JSON;if("string"!=typeof e&&"object"!=("undefined"==typeof e?"undefined":Mn(e)))throw"spHeader must be JSON string or object: "+e;if("object"==("undefined"==typeof e?"undefined":Mn(e))&&(s=e,o=v.stringify(s)),"string"==typeof e){if(o=e,!l(o))throw"JWS Head is not safe JSON string: "+o;s=h(o)}if(a=n,"object"==("undefined"==typeof n?"undefined":Mn(n))&&(a=v.stringify(n)),""!=t&&null!=t||void 0===s.alg||(t=s.alg),""!=t&&null!=t&&void 0===s.alg&&(s.alg=t,o=v.stringify(s)),t!==s.alg)throw"alg and sHeader.alg doesn't match: "+t+"!="+s.alg;var y=null;if(void 0===f.jwsalg2sigalg[t])throw"unsupported alg name: "+t;y=f.jwsalg2sigalg[t];var m=lr(o),S=lr(a),b=m+"."+S,F="";if("Hmac"==y.substr(0,4)){if(void 0===r)throw"mac key shall be specified for HS* alg";var w=new d({alg:y,prov:"cryptojs",pass:r});w.updateString(b),F=w.doFinal()}else if(y.indexOf("withECDSA")!=-1){var _=new g({alg:y});_.init(r,i),_.updateString(b),hASN1Sig=_.sign(),F=hr.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig)}else if("none"!=y){var _=new g({alg:y});_.init(r,i),_.updateString(b),F=_.sign()}var x=rn(F);return b+"."+x},hr.jws.JWS.verify=function(t,e,n){var r,i=hr,o=i.jws,s=o.JWS,a=s.readSafeJSONString,u=i.crypto,c=u.ECDSA,f=u.Mac,h=u.Signature;void 0!==("undefined"==typeof ve?"undefined":Mn(ve))&&(r=ve);var l=t.split(".");if(3!==l.length)return!1;var p=l[0],d=l[1],g=p+"."+d,v=on(l[2]),y=a(pr(l[0])),m=null,S=null;if(void 0===y.alg)throw"algorithm not specified in header";if(m=y.alg,S=m.substr(0,2),null!=n&&"[object Array]"===Object.prototype.toString.call(n)&&n.length>0){var b=":"+n.join(":")+":";if(b.indexOf(":"+m+":")==-1)throw"algorithm '"+m+"' not accepted in the list"}if("none"!=m&&null===e)throw"key shall be specified to verify.";if("string"==typeof e&&e.indexOf("-----BEGIN ")!=-1&&(e=gr.getKey(e)),!("RS"!=S&&"PS"!=S||e instanceof r))throw"key shall be a RSAKey obj for RS* and PS* algs";if("ES"==S&&!(e instanceof c))throw"key shall be a ECDSA obj for ES* algs";var F=null;if(void 0===s.jwsalg2sigalg[y.alg])throw"unsupported alg name: "+m;if(F=s.jwsalg2sigalg[m],"none"==F)throw"not supported";if("Hmac"==F.substr(0,4)){var w=null;if(void 0===e)throw"hexadecimal key shall be specified for HMAC";var _=new f({alg:F,pass:e});return _.updateString(g),w=_.doFinal(),v==w}if(F.indexOf("withECDSA")!=-1){var x=null;try{x=c.concatSigToASN1Sig(v)}catch(t){return!1}var E=new h({alg:F});return E.init(e),E.updateString(g),E.verify(x)}var E=new h({alg:F});return E.init(e),E.updateString(g),E.verify(v)},hr.jws.JWS.parse=function(t){var e,n,r,i=t.split("."),o={};if(2!=i.length&&3!=i.length)throw"malformed sJWS: wrong number of '.' splitted elements";return e=i[0],n=i[1],3==i.length&&(r=i[2]),o.headerObj=hr.jws.JWS.readSafeJSONString(pr(e)),o.payloadObj=hr.jws.JWS.readSafeJSONString(pr(n)),o.headerPP=JSON.stringify(o.headerObj,null," "),null==o.payloadObj?o.payloadPP=pr(n):o.payloadPP=JSON.stringify(o.payloadObj,null," "),void 0!==r&&(o.sigHex=on(r)),o},hr.jws.JWS.verifyJWT=function(t,e,n){var r=hr,i=r.jws,o=i.JWS,s=o.readSafeJSONString,a=o.inArray,u=o.includedArray,c=t.split("."),f=c[0],h=c[1],l=(on(c[2]),s(pr(f))),p=s(pr(h));if(void 0===l.alg)return!1;if(void 0===n.alg)throw"acceptField.alg shall be specified";if(!a(l.alg,n.alg))return!1;if(void 0!==p.iss&&"object"===Mn(n.iss)&&!a(p.iss,n.iss))return!1;if(void 0!==p.sub&&"object"===Mn(n.sub)&&!a(p.sub,n.sub))return!1;if(void 0!==p.aud&&"object"===Mn(n.aud))if("string"==typeof p.aud){if(!a(p.aud,n.aud))return!1}else if("object"==Mn(p.aud)&&!u(p.aud,n.aud))return!1;var d=i.IntDate.getNow();return void 0!==n.verifyAt&&"number"==typeof n.verifyAt&&(d=n.verifyAt),void 0!==n.gracePeriod&&"number"==typeof n.gracePeriod||(n.gracePeriod=0),!(void 0!==p.exp&&"number"==typeof p.exp&&p.exp+n.gracePeriod<d)&&(!(void 0!==p.nbf&&"number"==typeof p.nbf&&d<p.nbf-n.gracePeriod)&&(!(void 0!==p.iat&&"number"==typeof p.iat&&d<p.iat-n.gracePeriod)&&((void 0===p.jti||void 0===n.jti||p.jti===n.jti)&&!!o.verify(t,e,n.alg))))},hr.jws.JWS.includedArray=function(t,e){var n=hr.jws.JWS.inArray;if(null===t)return!1;if("object"!==("undefined"==typeof t?"undefined":Mn(t)))return!1;if("number"!=typeof t.length)return!1;for(var r=0;r<t.length;r++)if(!n(t[r],e))return!1;return!0},hr.jws.JWS.inArray=function(t,e){if(null===e)return!1;if("object"!==("undefined"==typeof e?"undefined":Mn(e)))return!1;if("number"!=typeof e.length)return!1;for(var n=0;n<e.length;n++)if(e[n]==t)return!0;return!1},hr.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS384:"HmacSHA384",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none"},hr.jws.JWS.isSafeJSONString=function(t,e,n){var r=null;try{return r=cr(t),"object"!=("undefined"==typeof r?"undefined":Mn(r))?0:r.constructor===Array?0:(e&&(e[n]=r),1)}catch(t){return 0}},hr.jws.JWS.readSafeJSONString=function(t){var e=null;try{return e=cr(t),"object"!=("undefined"==typeof e?"undefined":Mn(e))?null:e.constructor===Array?null:e}catch(t){return null}},hr.jws.JWS.getEncodedSignatureValueFromJWS=function(t){var e=t.match(/^[^.]+\.[^.]+\.([^.]+)$/);if(null==e)throw"JWS signature is not a form of 'Head.Payload.SigValue'.";return e[1]},hr.jws.JWS.getJWKthumbprint=function(t){if("RSA"!==t.kty&&"EC"!==t.kty&&"oct"!==t.kty)throw"unsupported algorithm for JWK Thumprint";var e="{";if("RSA"===t.kty){if("string"!=typeof t.n||"string"!=typeof t.e)throw"wrong n and e value for RSA key";e+='"e":"'+t.e+'",',e+='"kty":"'+t.kty+'",',e+='"n":"'+t.n+'"}'}else if("EC"===t.kty){if("string"!=typeof t.crv||"string"!=typeof t.x||"string"!=typeof t.y)throw"wrong crv, x and y value for EC key";e+='"crv":"'+t.crv+'",',e+='"kty":"'+t.kty+'",',e+='"x":"'+t.x+'",',e+='"y":"'+t.y+'"}'}else if("oct"===t.kty){if("string"!=typeof t.k)throw"wrong k value for oct(symmetric) key";e+='"kty":"'+t.kty+'",',e+='"k":"'+t.k+'"}'}var n=hn(e),r=hr.crypto.Util.hashHex(n,"sha256"),i=rn(r);return i},hr.jws.IntDate={},hr.jws.IntDate.get=function(t){var e=hr.jws.IntDate,n=e.getNow,r=e.getZulu;if("now"==t)return n();if("now + 1hour"==t)return n()+3600;if("now + 1day"==t)return n()+86400;if("now + 1month"==t)return n()+2592e3;if("now + 1year"==t)return n()+31536e3;if(t.match(/Z$/))return r(t);if(t.match(/^[0-9]+$/))return parseInt(t);throw"unsupported format: "+t},hr.jws.IntDate.getZulu=function(t){return bn(t)},hr.jws.IntDate.getNow=function(){var t=~~(new Date/1e3);return t},hr.jws.IntDate.intDate2UTCString=function(t){var e=new Date(1e3*t);return e.toUTCString()},hr.jws.IntDate.intDate2Zulu=function(t){var e=new Date(1e3*t),n=("0000"+e.getUTCFullYear()).slice(-4),r=("00"+(e.getUTCMonth()+1)).slice(-2),i=("00"+e.getUTCDate()).slice(-2),o=("00"+e.getUTCHours()).slice(-2),s=("00"+e.getUTCMinutes()).slice(-2),a=("00"+e.getUTCSeconds()).slice(-2);return n+r+i+o+s+a+"Z"},e.SecureRandom=he,e.rng_seed_time=ue,e.BigInteger=o,e.RSAKey=ve,e.ECDSA=hr.crypto.ECDSA,e.DSA=hr.crypto.DSA,e.Signature=hr.crypto.Signature,e.MessageDigest=hr.crypto.MessageDigest,e.Mac=hr.crypto.Mac,e.Cipher=hr.crypto.Cipher,e.KEYUTIL=gr,e.ASN1HEX=fr,e.X509=Ln,e.CryptoJS=Vn,e.b64tohex=r,e.b64toBA=i,e.stoBA=ze,e.BAtos=Ye,e.BAtohex=$e,e.stohex=Xe,e.stob64=Ze,e.stob64u=Qe,e.b64utos=tn,e.b64tob64u=en,e.b64utob64=nn,e.hex2b64=n,e.hextob64u=rn,e.b64utohex=on,e.utf8tob64u=lr,e.b64utoutf8=pr,e.utf8tob64=sn,e.b64toutf8=an,e.utf8tohex=un,e.hextoutf8=cn,e.hextorstr=fn,e.rstrtohex=hn,e.hextob64=ln,e.hextob64nl=pn,e.b64nltohex=dn,e.hextopem=gn,e.pemtohex=vn,e.hextoArrayBuffer=yn,e.ArrayBuffertohex=mn,e.zulutomsec=Sn,e.zulutosec=bn,e.zulutodate=Fn,e.datetozulu=wn,e.uricmptohex=_n,e.hextouricmp=xn,e.ipv6tohex=En,e.hextoipv6=An,e.hextoip=Pn,e.iptohex=Cn,e.encodeURIComponentAll=kn,e.newline_toUnix=Tn,e.newline_toDos=Rn,e.hextoposhex=In,e.intarystrtohex=Dn,e.strdiffidx=dr,e.KJUR=hr,e.crypto=hr.crypto,e.asn1=hr.asn1,e.jws=hr.jws,e.lang=hr.lang}).call(e,n(340).Buffer)},function(t,e){},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SigninRequest=void 0;var i=n(328),o=n(342),s=n(343);e.SigninRequest=function(){function t(e){var n=e.url,a=e.client_id,u=e.redirect_uri,c=e.response_type,f=e.scope,h=e.authority,l=e.data,p=e.prompt,d=e.display,g=e.max_age,v=e.ui_locales,y=e.id_token_hint,m=e.login_hint,S=e.acr_values,b=e.resource,F=e.request,w=e.request_uri,_=e.extraQueryParams;if(r(this,t),!n)throw i.Log.error("SigninRequest.ctor: No url passed"),new Error("url");if(!a)throw i.Log.error("SigninRequest.ctor: No client_id passed"),new Error("client_id");if(!u)throw i.Log.error("SigninRequest.ctor: No redirect_uri passed"),new Error("redirect_uri");if(!c)throw i.Log.error("SigninRequest.ctor: No response_type passed"),new Error("response_type");if(!f)throw i.Log.error("SigninRequest.ctor: No scope passed"),new Error("scope");if(!h)throw i.Log.error("SigninRequest.ctor: No authority passed"),new Error("authority");var x=t.isOidc(c);this.state=new s.SigninState({nonce:x,data:l,client_id:a,authority:h}),n=o.UrlUtility.addQueryParam(n,"client_id",a),n=o.UrlUtility.addQueryParam(n,"redirect_uri",u),n=o.UrlUtility.addQueryParam(n,"response_type",c),n=o.UrlUtility.addQueryParam(n,"scope",f),n=o.UrlUtility.addQueryParam(n,"state",this.state.id),x&&(n=o.UrlUtility.addQueryParam(n,"nonce",this.state.nonce));var E={prompt:p,display:d,max_age:g,ui_locales:v,id_token_hint:y,login_hint:m,acr_values:S,resource:b,request:F,request_uri:w};for(var A in E)E[A]&&(n=o.UrlUtility.addQueryParam(n,A,E[A]));for(var P in _)n=o.UrlUtility.addQueryParam(n,P,_[P]);this.url=n}return t.isOidc=function(t){var e=t.split(/\s+/g).filter(function(t){return"id_token"===t});return!!e[0]},t.isOAuth=function(t){var e=t.split(/\s+/g).filter(function(t){return"token"===t});return!!e[0]},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.UrlUtility=void 0;var i=n(328),o=n(332);e.UrlUtility=function(){function t(){r(this,t)}return t.addQueryParam=function(t,e,n){return t.indexOf("?")<0&&(t+="?"),"?"!==t[t.length-1]&&(t+="&"),t+=encodeURIComponent(e),t+="=",t+=encodeURIComponent(n)},t.parseUrlFragment=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"#",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o.Global;"string"!=typeof t&&(t=n.location.href);var r=t.lastIndexOf(e);r>=0&&(t=t.substr(r+1));for(var s,a={},u=/([^&=]+)=([^&]*)/g,c=0;s=u.exec(t);)if(a[decodeURIComponent(s[1])]=decodeURIComponent(s[2]),c++>50)return i.Log.error("UrlUtility.parseUrlFragment: response exceeded expected number of parameters",t),{error:"Response exceeded expected number of parameters"};for(var f in a)return a;return{}},t}()},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.SigninState=void 0;var a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),u=n(328),c=n(344),f=n(345),h=r(f);e.SigninState=function(t){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=n.nonce,s=n.authority,a=n.client_id;i(this,e);var u=o(this,t.call(this,arguments[0]));return r===!0?u._nonce=(0,h.default)():r&&(u._nonce=r),u._authority=s,u._client_id=a,u}return s(e,t),e.prototype.toStorageString=function(){return u.Log.debug("SigninState.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created,nonce:this.nonce,authority:this.authority,client_id:this.client_id})},e.fromStorageString=function(t){u.Log.debug("SigninState.fromStorageString");var n=JSON.parse(t);return new e(n)},a(e,[{key:"nonce",get:function(){return this._nonce}},{key:"authority",get:function(){return this._authority}},{key:"client_id",get:function(){return this._client_id}}]),e}(c.State)},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.State=void 0;var o=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=n(328),a=n(345),u=r(a);e.State=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.id,r=e.data,o=e.created;i(this,t),this._id=n||(0,u.default)(),this._data=r,"number"==typeof o&&o>0?this._created=o:this._created=parseInt(Date.now()/1e3)}return t.prototype.toStorageString=function(){return s.Log.debug("State.toStorageString"),JSON.stringify({id:this.id,data:this.data,created:this.created})},t.fromStorageString=function(e){return s.Log.debug("State.fromStorageString"),new t(JSON.parse(e))},t.clearStaleState=function(e,n){var r=Date.now()/1e3-n;return e.getAllKeys().then(function(n){s.Log.debug("State.clearStaleState: got keys",n);for(var i=[],o=function(o){var a=n[o];u=e.get(a).then(function(n){var i=!1;if(n)try{var o=t.fromStorageString(n);s.Log.debug("State.clearStaleState: got item from key: ",a,o.created),o.created<=r&&(i=!0)}catch(t){s.Log.error("State.clearStaleState: Error parsing state for key",a,t.message),i=!0}else s.Log.debug("State.clearStaleState: no item in storage for key: ",a),i=!0;if(i)return s.Log.debug("State.clearStaleState: removed item for key: ",a),e.remove(a)}),i.push(u)},a=0;a<n.length;a++){var u;o(a)}return s.Log.debug("State.clearStaleState: waiting on promise count:",i.length),Promise.all(i)})},o(t,[{key:"id",get:function(){return this._id}},{key:"data",get:function(){return this._data}},{key:"created",get:function(){return this._created}}]),t}()},function(t,e){"use strict"; // @preserve Copyright (c) Microsoft Open Technologies, Inc. function n(){for(var t="xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx",e="0123456789abcdef",n=0,r="",i=0;i<t.length;i++)"-"!==t[i]&&"4"!==t[i]&&(n=16*Math.random()|0),"x"===t[i]?r+=e[n]:"y"===t[i]?(n&=3,n|=8,r+=e[n]):r+=t[i];return r}Object.defineProperty(e,"__esModule",{value:!0}),e.default=n,t.exports=e.default},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SigninResponse=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(342),s="openid";e.SigninResponse=function(){function t(e){r(this,t);var n=o.UrlUtility.parseUrlFragment(e,"#");this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.state=n.state,this.id_token=n.id_token,this.session_state=n.session_state,this.access_token=n.access_token,this.token_type=n.token_type,this.scope=n.scope,this.profile=void 0;var i=parseInt(n.expires_in);if("number"==typeof i&&i>0){var s=parseInt(Date.now()/1e3);this.expires_at=s+i}}return i(t,[{key:"expires_in",get:function(){if(this.expires_at){var t=parseInt(Date.now()/1e3);return this.expires_at-t}}},{key:"expired",get:function(){var t=this.expires_in;if(void 0!==t)return t<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}},{key:"isOpenIdConnect",get:function(){return this.scopes.indexOf(s)>=0||!!this.id_token}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SignoutRequest=void 0;var i=n(328),o=n(342),s=n(344);e.SignoutRequest=function t(e){var n=e.url,a=e.id_token_hint,u=e.post_logout_redirect_uri,c=e.data;if(r(this,t),!n)throw i.Log.error("SignoutRequest.ctor: No url passed"),new Error("url");a&&(n=o.UrlUtility.addQueryParam(n,"id_token_hint",a)),u&&(n=o.UrlUtility.addQueryParam(n,"post_logout_redirect_uri",u),c&&(this.state=new s.State({data:c}),n=o.UrlUtility.addQueryParam(n,"state",this.state.id))),this.url=n}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SignoutResponse=void 0;var i=n(342);e.SignoutResponse=function t(e){r(this,t);var n=i.UrlUtility.parseUrlFragment(e,"?");this.error=n.error,this.error_description=n.error_description,this.error_uri=n.error_uri,this.state=n.state}},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.InMemoryWebStorage=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328);e.InMemoryWebStorage=function(){function t(){r(this,t),this._data={}}return t.prototype.getItem=function(t){return o.Log.debug("InMemoryWebStorage.getItem",t),this._data[t]},t.prototype.setItem=function(t,e){o.Log.debug("InMemoryWebStorage.setItem",t),this._data[t]=e},t.prototype.removeItem=function(t){o.Log.debug("InMemoryWebStorage.removeItem",t),delete this._data[t]},t.prototype.key=function(t){return Object.getOwnPropertyNames(this._data)[t]},i(t,[{key:"length",get:function(){return Object.getOwnPropertyNames(this._data).length}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.UserManager=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=n(328),u=n(329),c=n(351),f=n(357),h=n(358),l=n(362),p=n(363),d=n(365);e.UserManager=function(t){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:l.SilentRenewService,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p.SessionMonitor,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:d.TokenRevocationClient;r(this,e),n instanceof c.UserManagerSettings||(n=new c.UserManagerSettings(n));var f=i(this,t.call(this,n));return f._events=new h.UserManagerEvents(n),f._silentRenewService=new o(f),f.settings.automaticSilentRenew&&(a.Log.debug("UserManager.ctor: automaticSilentRenew is configured, setting up silent renew"),f.startSilentRenew()),f.settings.monitorSession&&(a.Log.debug("UserManager.ctor: monitorSession is configured, setting up session monitor"),f._sessionMonitor=new s(f)),f._tokenRevocationClient=new u(f._settings),f}return o(e,t),e.prototype.getUser=function(){var t=this;return this._loadUser().then(function(e){return e?(a.Log.info("UserManager.getUser: user loaded"),t._events.load(e,!1),e):(a.Log.info("UserManager.getUser: user not found in storage"),null)})},e.prototype.removeUser=function(){var t=this;return this.storeUser(null).then(function(){a.Log.info("UserManager.removeUser: user removed from storage"),t._events.unload()})},e.prototype.signinRedirect=function(t){return this._signinStart(t,this._redirectNavigator).then(function(){a.Log.info("UserManager.signinRedirect: successful")})},e.prototype.signinRedirectCallback=function(t){return this._signinEnd(t||this._redirectNavigator.url).then(function(t){return t&&(t.profile&&t.profile.sub?a.Log.info("UserManager.signinRedirectCallback: successful, signed in sub: ",t.profile.sub):a.Log.info("UserManager.signinRedirectCallback: no sub")),t})},e.prototype.signinPopup=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.redirect_uri||this.settings.popup_redirect_uri||this.settings.redirect_uri;return e?(t.redirect_uri=e,t.display="popup",this._signin(t,this._popupNavigator,{startUrl:e,popupWindowFeatures:t.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:t.popupWindowTarget||this.settings.popupWindowTarget}).then(function(t){return t&&(t.profile&&t.profile.sub?a.Log.info("UserManager.signinPopup: signinPopup successful, signed in sub: ",t.profile.sub):a.Log.info("UserManager.signinPopup: no sub")),t})):(a.Log.error("UserManager.signinPopup: No popup_redirect_uri or redirect_uri configured"),Promise.reject(new Error("No popup_redirect_uri or redirect_uri configured")))},e.prototype.signinPopupCallback=function(t){return this._signinCallback(t,this._popupNavigator).then(function(t){return t&&(t.profile&&t.profile.sub?a.Log.info("UserManager.signinPopupCallback: successful, signed in sub: ",t.profile.sub):a.Log.info("UserManager.signinPopupCallback: no sub")),t})},e.prototype.signinSilent=function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.redirect_uri||this.settings.silent_redirect_uri;if(!n)return a.Log.error("UserManager.signinSilent: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured"));e.redirect_uri=n,e.prompt="none";var r=void 0;return r=e.id_token_hint||!this.settings.includeIdTokenInSilentRenew?Promise.resolve():this._loadUser().then(function(t){e.id_token_hint=t&&t.id_token}),r.then(function(){return t._signin(e,t._iframeNavigator,{startUrl:n,silentRequestTimeout:e.silentRequestTimeout||t.settings.silentRequestTimeout})}).then(function(t){return t&&(t.profile&&t.profile.sub?a.Log.info("UserManager.signinSilent: successful, signed in sub: ",t.profile.sub):a.Log.info("UserManager.signinSilent: no sub")),t})},e.prototype.signinSilentCallback=function(t){return this._signinCallback(t,this._iframeNavigator).then(function(t){return t&&(t.profile&&t.profile.sub?a.Log.info("UserManager.signinSilentCallback: successful, signed in sub: ",t.profile.sub):a.Log.info("UserManager.signinSilentCallback: no sub")),t})},e.prototype.querySessionStatus=function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.redirect_uri||this.settings.silent_redirect_uri;return n?(e.redirect_uri=n,e.prompt="none",e.response_type="id_token",e.scope="openid",this._signinStart(e,this._iframeNavigator,{startUrl:n,silentRequestTimeout:e.silentRequestTimeout||this.settings.silentRequestTimeout}).then(function(e){return t.processSigninResponse(e.url).then(function(t){return a.Log.debug("UserManager.querySessionStatus: got signin response"),t.session_state&&t.profile.sub&&t.profile.sid?(a.Log.info("UserManager.querySessionStatus: querySessionStatus success for sub: ",t.profile.sub),{session_state:t.session_state,sub:t.profile.sub,sid:t.profile.sid}):void a.Log.info("querySessionStatus successful, user not authenticated")})})):(a.Log.error("UserManager.querySessionStatus: No silent_redirect_uri configured"),Promise.reject(new Error("No silent_redirect_uri configured")))},e.prototype._signin=function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signinStart(t,e,r).then(function(t){return n._signinEnd(t.url)})},e.prototype._signinStart=function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e.prepare(r).then(function(e){return a.Log.debug("UserManager._signinStart: got navigator window handle"),n.createSigninRequest(t).then(function(t){return a.Log.debug("UserManager._signinStart: got signin request"),r.url=t.url,r.id=t.state.id,e.navigate(r)}).catch(function(t){throw e.close&&(a.Log.debug("UserManager._signinStart: Error after preparing navigator, closing navigator window"),e.close()),t})})},e.prototype._signinEnd=function(t){var e=this;return this.processSigninResponse(t).then(function(t){a.Log.debug("UserManager._signinEnd: got signin response");var n=new f.User(t);return e.storeUser(n).then(function(){return a.Log.debug("UserManager._signinEnd: user stored"),e._events.load(n),n})})},e.prototype._signinCallback=function(t,e){return a.Log.debug("UserManager._signinCallback"),e.callback(t)},e.prototype.signoutRedirect=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return e&&(t.post_logout_redirect_uri=e),this._signoutStart(t,this._redirectNavigator).then(function(){a.Log.info("UserManager.signoutRedirect: successful")})},e.prototype.signoutRedirectCallback=function(t){return this._signoutEnd(t||this._redirectNavigator.url).then(function(t){return a.Log.info("UserManager.signoutRedirectCallback: successful"),t})},e.prototype.signoutPopup=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=t.post_logout_redirect_uri||this.settings.popup_post_logout_redirect_uri||this.settings.post_logout_redirect_uri;return t.post_logout_redirect_uri=e,t.display="popup",t.post_logout_redirect_uri&&(t.state=t.state||{}),this._signout(t,this._popupNavigator,{startUrl:e,popupWindowFeatures:t.popupWindowFeatures||this.settings.popupWindowFeatures,popupWindowTarget:t.popupWindowTarget||this.settings.popupWindowTarget}).then(function(){a.Log.info("UserManager.signinPopup: successful")})},e.prototype.signoutPopupCallback=function(t,e){"undefined"==typeof e&&"boolean"==typeof t&&(t=null,e=!0);var n="?";return this._popupNavigator.callback(t,e,n).then(function(){a.Log.info("UserManager.signoutPopupCallback: successful")})},e.prototype._signout=function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this._signoutStart(t,e,r).then(function(t){return n._signoutEnd(t.url)})},e.prototype._signoutStart=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=this,n=arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return n.prepare(r).then(function(n){return a.Log.debug("UserManager._signoutStart: got navigator window handle"),e._loadUser().then(function(i){a.Log.debug("UserManager._signoutStart: loaded current user from storage");var o=e._settings.revokeAccessTokenOnSignout?e._revokeInternal(i):Promise.resolve();return o.then(function(){var o=t.id_token_hint||i&&i.id_token;return o&&(a.Log.debug("UserManager._signoutStart: Setting id_token into signout request"),t.id_token_hint=o),e.removeUser().then(function(){return a.Log.debug("UserManager._signoutStart: user removed, creating signout request"),e.createSignoutRequest(t).then(function(t){return a.Log.debug("UserManager._signoutStart: got signout request"),r.url=t.url,t.state&&(r.id=t.state.id),n.navigate(r)})})})}).catch(function(t){throw n.close&&(a.Log.debug("UserManager._signoutStart: Error after preparing navigator, closing navigator window"),n.close()),t})})},e.prototype._signoutEnd=function(t){return this.processSignoutResponse(t).then(function(t){return a.Log.debug("UserManager._signoutEnd: got signout response"),t})},e.prototype.revokeAccessToken=function(){var t=this;return this._loadUser().then(function(e){return t._revokeInternal(e,!0).then(function(n){if(n)return a.Log.debug("UserManager.revokeAccessToken: removing token properties from user and re-storing"),e.access_token=null,e.expires_at=null,e.token_type=null,t.storeUser(e).then(function(){a.Log.debug("UserManager.revokeAccessToken: user stored"),t._events.load(e)})})}).then(function(){a.Log.info("UserManager.revokeAccessToken: access token revoked successfully")})},e.prototype._revokeInternal=function(t,e){var n=t&&t.access_token;return!n||n.indexOf(".")>=0?(a.Log.debug("UserManager.revokeAccessToken: no need to revoke due to no user, token, or JWT format"),Promise.resolve(!1)):this._tokenRevocationClient.revoke(n,e).then(function(){return!0})},e.prototype.startSilentRenew=function(){this._silentRenewService.start()},e.prototype.stopSilentRenew=function(){this._silentRenewService.stop()},e.prototype._loadUser=function(){return this._userStore.get(this._userStoreKey).then(function(t){return t?(a.Log.debug("UserManager._loadUser: user storageString loaded"),f.User.fromStorageString(t)):(a.Log.debug("UserManager._loadUser: no user storageString"),null)})},e.prototype.storeUser=function(t){if(t){a.Log.debug("UserManager.storeUser: storing user");var e=t.toStorageString();return this._userStore.set(this._userStoreKey,e)}return a.Log.debug("storeUser.storeUser: removing user"),this._userStore.remove(this._userStoreKey)},s(e,[{key:"_redirectNavigator",get:function(){return this.settings.redirectNavigator}},{key:"_popupNavigator",get:function(){return this.settings.popupNavigator}},{key:"_iframeNavigator",get:function(){return this.settings.iframeNavigator}},{key:"_userStore",get:function(){return this.settings.userStore}},{key:"events",get:function(){return this._events}},{key:"_userStoreKey",get:function(){return"user:"+this.settings.authority+":"+this.settings.client_id}}]),e}(u.OidcClient)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.UserManagerSettings=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=(n(328),n(330)),u=n(352),c=n(353),f=n(355),h=n(331),l=n(332),p=60,d=2e3;e.UserManagerSettings=function(t){function e(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},o=n.popup_redirect_uri,s=n.popup_post_logout_redirect_uri,a=n.popupWindowFeatures,g=n.popupWindowTarget,v=n.silent_redirect_uri,y=n.silentRequestTimeout,m=n.automaticSilentRenew,S=void 0!==m&&m,b=n.includeIdTokenInSilentRenew,F=void 0===b||b,w=n.monitorSession,_=void 0===w||w,x=n.checkSessionInterval,E=void 0===x?d:x,A=n.stopCheckSessionOnError,P=void 0===A||A,C=n.revokeAccessTokenOnSignout,k=void 0!==C&&C,T=n.accessTokenExpiringNotificationTime,R=void 0===T?p:T,I=n.redirectNavigator,D=void 0===I?new u.RedirectNavigator:I,N=n.popupNavigator,O=void 0===N?new c.PopupNavigator:N,j=n.iframeNavigator,L=void 0===j?new f.IFrameNavigator:j,M=n.userStore,B=void 0===M?new h.WebStorageStateStore({store:l.Global.sessionStorage}):M;r(this,e);var H=i(this,t.call(this,arguments[0]));return H._popup_redirect_uri=o,H._popup_post_logout_redirect_uri=s,H._popupWindowFeatures=a,H._popupWindowTarget=g,H._silent_redirect_uri=v,H._silentRequestTimeout=y,H._automaticSilentRenew=!!S,H._includeIdTokenInSilentRenew=F,H._accessTokenExpiringNotificationTime=R,H._monitorSession=_,H._checkSessionInterval=E,H._stopCheckSessionOnError=P,H._revokeAccessTokenOnSignout=k,H._redirectNavigator=D,H._popupNavigator=O,H._iframeNavigator=L,H._userStore=B,H}return o(e,t),s(e,[{key:"popup_redirect_uri",get:function(){return this._popup_redirect_uri}},{key:"popup_post_logout_redirect_uri",get:function(){return this._popup_post_logout_redirect_uri}},{key:"popupWindowFeatures",get:function(){return this._popupWindowFeatures}},{key:"popupWindowTarget",get:function(){return this._popupWindowTarget}},{key:"silent_redirect_uri",get:function(){return this._silent_redirect_uri}},{key:"silentRequestTimeout",get:function(){return this._silentRequestTimeout}},{key:"automaticSilentRenew",get:function(){return!(!this.silent_redirect_uri||!this._automaticSilentRenew)}},{key:"includeIdTokenInSilentRenew",get:function(){return this._includeIdTokenInSilentRenew}},{key:"accessTokenExpiringNotificationTime",get:function(){return this._accessTokenExpiringNotificationTime}},{key:"monitorSession",get:function(){return this._monitorSession}},{key:"checkSessionInterval",get:function(){return this._checkSessionInterval}},{key:"stopCheckSessionOnError",get:function(){return this._stopCheckSessionOnError}},{key:"revokeAccessTokenOnSignout",get:function(){return this._revokeAccessTokenOnSignout}},{key:"redirectNavigator",get:function(){return this._redirectNavigator}},{key:"popupNavigator",get:function(){return this._popupNavigator}},{key:"iframeNavigator",get:function(){return this._iframeNavigator}},{key:"userStore",get:function(){return this._userStore}}]),e}(a.OidcClientSettings)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.RedirectNavigator=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328);e.RedirectNavigator=function(){function t(){r(this,t)}return t.prototype.prepare=function(){return Promise.resolve(this)},t.prototype.navigate=function(t){return t&&t.url?(window.location=t.url,Promise.resolve()):(o.Log.error("RedirectNavigator.navigate: No url provided"),Promise.reject(new Error("No url provided")))},i(t,[{key:"url",get:function(){return window.location.href}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PopupNavigator=void 0;var i=n(328),o=n(354);e.PopupNavigator=function(){function t(){r(this,t)}return t.prototype.prepare=function(t){var e=new o.PopupWindow(t);return Promise.resolve(e)},t.prototype.callback=function(t,e,n){i.Log.debug("PopupNavigator.callback");try{return o.PopupWindow.notifyOpener(t,e,n),Promise.resolve()}catch(t){return Promise.reject(t)}},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.PopupWindow=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s=n(342),a=500,u="location=no,toolbar=no,width=500,height=500,left=100,top=100;",c="_blank";e.PopupWindow=function(){function t(e){var n=this;r(this,t),this._promise=new Promise(function(t,e){n._resolve=t,n._reject=e});var i=e.popupWindowTarget||c,s=e.popupWindowFeatures||u;this._popup=window.open("",i,s),this._popup&&(o.Log.debug("PopupWindow.ctor: popup successfully created"),this._checkForPopupClosedTimer=window.setInterval(this._checkForPopupClosed.bind(this),a))}return t.prototype.navigate=function(t){return this._popup?t&&t.url?(o.Log.debug("PopupWindow.navigate: Setting URL in popup"),this._id=t.id,this._id&&(window["popupCallback_"+t.id]=this._callback.bind(this)),this._popup.focus(),this._popup.window.location=t.url):(this._error("PopupWindow.navigate: no url provided"),this._error("No url provided")):this._error("PopupWindow.navigate: Error opening popup window"),this.promise},t.prototype._success=function(t){this._cleanup(),o.Log.debug("PopupWindow.callback: Successful response from popup window"),this._resolve(t)},t.prototype._error=function(t){this._cleanup(),o.Log.debug("PopupWindow.error: ",t),o.Log.error(t),this._reject(new Error(t))},t.prototype.close=function(){this._cleanup(!1)},t.prototype._cleanup=function(t){o.Log.debug("PopupWindow.cleanup"),window.clearInterval(this._checkForPopupClosedTimer),this._checkForPopupClosedTimer=null,delete window["popupCallback_"+this._id],this._popup&&!t&&this._popup.close(),this._popup=null},t.prototype._checkForPopupClosed=function(){this._popup&&!this._popup.closed||this._error("PopupWindow.checkForPopupClosed: Popup window closed")},t.prototype._callback=function(t,e){this._cleanup(e),t?(o.Log.debug("PopupWindow.callback success"),this._success({url:t})):(o.Log.debug("PopupWindow.callback: Invalid response from popup"),this._error("Invalid response from popup"))},t.notifyOpener=function(t,e,n){if(window.opener&&(t=t||window.location.href)){var r=s.UrlUtility.parseUrlFragment(t,n);if(r.state){var i="popupCallback_"+r.state,a=window.opener[i];a?(o.Log.debug("PopupWindow.notifyOpener: passing url message to opener"),a(t,e)):o.Log.warn("PopupWindow.notifyOpener: no matching callback found on opener")}else o.Log.warn("PopupWindow.notifyOpener: no state found in response url")}},i(t,[{key:"promise",get:function(){return this._promise}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.IFrameNavigator=void 0;var i=n(328),o=n(356);e.IFrameNavigator=function(){function t(){r(this,t)}return t.prototype.prepare=function(t){var e=new o.IFrameWindow(t);return Promise.resolve(e)},t.prototype.callback=function(t){i.Log.debug("IFrameNavigator.callback");try{return o.IFrameWindow.notifyParent(t),Promise.resolve()}catch(t){return Promise.reject(t)}},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.IFrameWindow=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s=1e4;e.IFrameWindow=function(){function t(e){var n=this;r(this,t),this._promise=new Promise(function(t,e){n._resolve=t,n._reject=e}),this._boundMessageEvent=this._message.bind(this),window.addEventListener("message",this._boundMessageEvent,!1),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.style.width=0,this._frame.style.height=0,window.document.body.appendChild(this._frame)}return t.prototype.navigate=function(t){if(t&&t.url){var e=t.silentRequestTimeout||s;o.Log.debug("IFrameWindow.navigate: Using timeout of:",e),this._timer=window.setTimeout(this._timeout.bind(this),e),this._frame.src=t.url}else this._error("No url provided");return this.promise},t.prototype._success=function(t){this._cleanup(),o.Log.debug("IFrameWindow: Successful response from frame window"),this._resolve(t)},t.prototype._error=function(t){this._cleanup(),o.Log.error(t),this._reject(new Error(t))},t.prototype.close=function(){this._cleanup()},t.prototype._cleanup=function(){this._frame&&(o.Log.debug("IFrameWindow: cleanup"),window.removeEventListener("message",this._boundMessageEvent,!1),window.clearTimeout(this._timer),window.document.body.removeChild(this._frame),this._timer=null,this._frame=null,this._boundMessageEvent=null)},t.prototype._timeout=function(){o.Log.debug("IFrameWindow.timeout"),this._error("Frame window timed out")},t.prototype._message=function(t){if(o.Log.debug("IFrameWindow.message"),this._timer&&t.origin===this._origin&&t.source===this._frame.contentWindow){var e=t.data;e?this._success({url:e}):this._error("Invalid response from frame")}},t.notifyParent=function(t){o.Log.debug("IFrameWindow.notifyParent"),window.parent&&window!==window.parent&&(t=t||window.location.href,t&&(o.Log.debug("IFrameWindow.notifyParent: posting url message to parent"),window.parent.postMessage(t,location.protocol+"//"+location.host)))},i(t,[{key:"promise",get:function(){return this._promise}},{key:"_origin",get:function(){return location.protocol+"//"+location.host}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.User=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328);e.User=function(){function t(e){var n=e.id_token,i=e.session_state,o=e.access_token,s=e.token_type,a=e.scope,u=e.profile,c=e.expires_at,f=e.state;r(this,t),this.id_token=n,this.session_state=i,this.access_token=o,this.token_type=s,this.scope=a,this.profile=u,this.expires_at=c,this.state=f}return t.prototype.toStorageString=function(){return o.Log.debug("User.toStorageString"),JSON.stringify({id_token:this.id_token,session_state:this.session_state,access_token:this.access_token,token_type:this.token_type,scope:this.scope,profile:this.profile,expires_at:this.expires_at})},t.fromStorageString=function(e){return o.Log.debug("User.fromStorageString"),new t(JSON.parse(e))},i(t,[{key:"expires_in",get:function(){if(this.expires_at){var t=parseInt(Date.now()/1e3);return this.expires_at-t}}},{key:"expired",get:function(){var t=this.expires_in;if(void 0!==t)return t<=0}},{key:"scopes",get:function(){return(this.scope||"").split(" ")}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.UserManagerEvents=void 0;var s=n(328),a=n(359),u=n(361);e.UserManagerEvents=function(t){function e(n){r(this,e);var o=i(this,t.call(this,n));return o._userLoaded=new u.Event("User loaded"),o._userUnloaded=new u.Event("User unloaded"),o._silentRenewError=new u.Event("Silent renew error"),o._userSignedOut=new u.Event("User signed out"),o._userSessionChanged=new u.Event("User session changed"),o}return o(e,t),e.prototype.load=function(e){var n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];s.Log.debug("UserManagerEvents.load"),t.prototype.load.call(this,e),n&&this._userLoaded.raise(e)},e.prototype.unload=function(){s.Log.debug("UserManagerEvents.unload"),t.prototype.unload.call(this),this._userUnloaded.raise()},e.prototype.addUserLoaded=function(t){this._userLoaded.addHandler(t)},e.prototype.removeUserLoaded=function(t){this._userLoaded.removeHandler(t)},e.prototype.addUserUnloaded=function(t){this._userUnloaded.addHandler(t)},e.prototype.removeUserUnloaded=function(t){this._userUnloaded.removeHandler(t)},e.prototype.addSilentRenewError=function(t){this._silentRenewError.addHandler(t)},e.prototype.removeSilentRenewError=function(t){this._silentRenewError.removeHandler(t)},e.prototype._raiseSilentRenewError=function(t){s.Log.debug("UserManagerEvents._raiseSilentRenewError",t.message),this._silentRenewError.raise(t)},e.prototype.addUserSignedOut=function(t){this._userSignedOut.addHandler(t)},e.prototype.removeUserSignedOut=function(t){this._userSignedOut.removeHandler(t)},e.prototype._raiseUserSignedOut=function(t){s.Log.debug("UserManagerEvents._raiseUserSignedOut"),this._userSignedOut.raise(t)},e.prototype.addUserSessionChanged=function(t){this._userSessionChanged.addHandler(t)},e.prototype.removeUserSessionChanged=function(t){this._userSessionChanged.removeHandler(t)},e.prototype._raiseUserSessionChanged=function(t){s.Log.debug("UserManagerEvents._raiseUserSessionChanged"),this._userSessionChanged.raise(t)},e}(a.AccessTokenEvents)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.AccessTokenEvents=void 0;var i=n(328),o=n(360),s=60;e.AccessTokenEvents=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.accessTokenExpiringNotificationTime,i=void 0===n?s:n,a=e.accessTokenExpiringTimer,u=void 0===a?new o.Timer("Access token expiring"):a,c=e.accessTokenExpiredTimer,f=void 0===c?new o.Timer("Access token expired"):c;r(this,t),this._accessTokenExpiringNotificationTime=i,this._accessTokenExpiring=u,this._accessTokenExpired=f}return t.prototype.load=function(t){if(t.access_token&&void 0!==t.expires_in){var e=t.expires_in;if(i.Log.debug("AccessTokenEvents.load: access token present, remaining duration:",e),e>0){var n=e-this._accessTokenExpiringNotificationTime;n<=0&&(n=1),i.Log.debug("AccessTokenEvents.load: registering expiring timer in:",n),this._accessTokenExpiring.init(n)}else i.Log.debug("AccessTokenEvents.load: canceling existing expiring timer becase we're past expiration."),this._accessTokenExpiring.cancel();var r=e+1;i.Log.debug("AccessTokenEvents.load: registering expired timer in:",r),this._accessTokenExpired.init(r)}else this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},t.prototype.unload=function(){i.Log.debug("AccessTokenEvents.unload: canceling existing access token timers"), this._accessTokenExpiring.cancel(),this._accessTokenExpired.cancel()},t.prototype.addAccessTokenExpiring=function(t){this._accessTokenExpiring.addHandler(t)},t.prototype.removeAccessTokenExpiring=function(t){this._accessTokenExpiring.removeHandler(t)},t.prototype.addAccessTokenExpired=function(t){this._accessTokenExpired.addHandler(t)},t.prototype.removeAccessTokenExpired=function(t){this._accessTokenExpired.removeHandler(t)},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.Timer=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=n(328),u=n(332),c=n(361),f=5;e.Timer=function(t){function e(n){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u.Global.timer,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;r(this,e);var a=i(this,t.call(this,n));return a._timer=o,s?a._nowFunc=s:a._nowFunc=function(){return Date.now()/1e3},a}return o(e,t),e.prototype.init=function(t){t<=0&&(t=1),t=parseInt(t);var e=this.now+t;if(this.expiration===e&&this._timerHandle)return void a.Log.debug("Timer.init timer "+this._name+" skipping initialization since already initialized for expiration:",this.expiration);this.cancel(),a.Log.debug("Timer.init timer "+this._name+" for duration:",t),this._expiration=e;var n=f;t<n&&(n=t),this._timerHandle=this._timer.setInterval(this._callback.bind(this),1e3*n)},e.prototype.cancel=function(){this._timerHandle&&(a.Log.debug("Timer.cancel: ",this._name),this._timer.clearInterval(this._timerHandle),this._timerHandle=null)},e.prototype._callback=function(){var e=this._expiration-this.now;a.Log.debug("Timer.callback; "+this._name+" timer expires in:",e),this._expiration<=this.now&&(this.cancel(),t.prototype.raise.call(this))},s(e,[{key:"now",get:function(){return parseInt(this._nowFunc())}},{key:"expiration",get:function(){return this._expiration}}]),e}(c.Event)},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.Event=void 0;var i=n(328);e.Event=function(){function t(e){r(this,t),this._name=e,this._callbacks=[]}return t.prototype.addHandler=function(t){this._callbacks.push(t)},t.prototype.removeHandler=function(t){var e=this._callbacks.findIndex(function(e){return e===t});e>=0&&this._callbacks.splice(e,1)},t.prototype.raise=function(){i.Log.debug("Event: Raising event: "+this._name);for(var t=0;t<this._callbacks.length;t++){var e;(e=this._callbacks)[t].apply(e,arguments)}},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SilentRenewService=void 0;var i=n(328);e.SilentRenewService=function(){function t(e){r(this,t),this._userManager=e}return t.prototype.start=function(){this._callback||(this._callback=this._tokenExpiring.bind(this),this._userManager.events.addAccessTokenExpiring(this._callback),this._userManager.getUser().then(function(t){}).catch(function(t){i.Log.error("SilentRenewService.start: Error from getUser:",t.message)}))},t.prototype.stop=function(){this._callback&&(this._userManager.events.removeAccessTokenExpiring(this._callback),delete this._callback)},t.prototype._tokenExpiring=function(){var t=this;this._userManager.signinSilent().then(function(t){i.Log.debug("SilentRenewService._tokenExpiring: Silent token renewal successful")},function(e){i.Log.error("SilentRenewService._tokenExpiring: Error from signinSilent:",e.message),t._userManager.events._raiseSilentRenewError(e)})},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.SessionMonitor=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s=n(364);e.SessionMonitor=function(){function t(e){var n=this,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.CheckSessionIFrame;if(r(this,t),!e)throw o.Log.error("SessionMonitor.ctor: No user manager passed to SessionMonitor"),new Error("userManager");this._userManager=e,this._CheckSessionIFrameCtor=i,this._userManager.events.addUserLoaded(this._start.bind(this)),this._userManager.events.addUserUnloaded(this._stop.bind(this)),this._userManager.getUser().then(function(t){t&&n._start(t)}).catch(function(t){o.Log.error("SessionMonitor ctor: error from getUser:",t.message)})}return t.prototype._start=function(t){var e=this,n=t.session_state;n&&(this._sub=t.profile.sub,this._sid=t.profile.sid,o.Log.debug("SessionMonitor._start: session_state:",n,", sub:",this._sub),this._checkSessionIFrame?this._checkSessionIFrame.start(n):this._metadataService.getCheckSessionIframe().then(function(t){if(t){o.Log.debug("SessionMonitor._start: Initializing check session iframe");var r=e._client_id,i=e._checkSessionInterval,s=e._stopCheckSessionOnError;e._checkSessionIFrame=new e._CheckSessionIFrameCtor(e._callback.bind(e),r,t,i,s),e._checkSessionIFrame.load().then(function(){e._checkSessionIFrame.start(n)})}else o.Log.warn("SessionMonitor._start: No check session iframe found in the metadata")}).catch(function(t){o.Log.error("SessionMonitor._start: Error from getCheckSessionIframe:",t.message)}))},t.prototype._stop=function(){this._sub=null,this._sid=null,this._checkSessionIFrame&&(o.Log.debug("SessionMonitor._stop"),this._checkSessionIFrame.stop())},t.prototype._callback=function(){var t=this;this._userManager.querySessionStatus().then(function(e){var n=!0;e?e.sub===t._sub?(n=!1,t._checkSessionIFrame.start(e.session_state),e.sid===t._sid?o.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, restarting check session iframe; session_state:",e.session_state):(o.Log.debug("SessionMonitor._callback: Same sub still logged in at OP, session state has changed, restarting check session iframe; session_state:",e.session_state),t._userManager.events._raiseUserSessionChanged())):o.Log.debug("SessionMonitor._callback: Different subject signed into OP:",e.sub):o.Log.debug("SessionMonitor._callback: Subject no longer signed into OP"),n&&(o.Log.debug("SessionMonitor._callback: SessionMonitor._callback; raising signed out event"),t._userManager.events._raiseUserSignedOut())}).catch(function(e){o.Log.debug("SessionMonitor._callback: Error calling queryCurrentSigninSession; raising signed out event",e.message),t._userManager.events._raiseUserSignedOut()})},i(t,[{key:"_settings",get:function(){return this._userManager.settings}},{key:"_metadataService",get:function(){return this._userManager.metadataService}},{key:"_client_id",get:function(){return this._settings.client_id}},{key:"_checkSessionInterval",get:function(){return this._settings.checkSessionInterval}},{key:"_stopCheckSessionOnError",get:function(){return this._settings.stopCheckSessionOnError}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.CheckSessionIFrame=void 0;var i=n(328),o=2e3;e.CheckSessionIFrame=function(){function t(e,n,i,s){var a=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];r(this,t),this._callback=e,this._client_id=n,this._url=i,this._interval=s||o,this._stopOnError=a;var u=i.indexOf("/",i.indexOf("//")+2);this._frame_origin=i.substr(0,u),this._frame=window.document.createElement("iframe"),this._frame.style.visibility="hidden",this._frame.style.position="absolute",this._frame.style.display="none",this._frame.style.width=0,this._frame.style.height=0,this._frame.src=i}return t.prototype.load=function(){var t=this;return new Promise(function(e){t._frame.onload=function(){e()},window.document.body.appendChild(t._frame),t._boundMessageEvent=t._message.bind(t),window.addEventListener("message",t._boundMessageEvent,!1)})},t.prototype._message=function(t){t.origin===this._frame_origin&&t.source===this._frame.contentWindow&&("error"===t.data?(i.Log.error("CheckSessionIFrame: error message from check session op iframe"),this._stopOnError&&this.stop()):"changed"===t.data?(i.Log.debug("CheckSessionIFrame: changed message from check session op iframe"),this.stop(),this._callback()):i.Log.debug("CheckSessionIFrame: "+t.data+" message from check session op iframe"))},t.prototype.start=function(t){var e=this;this._session_state!==t&&(i.Log.debug("CheckSessionIFrame.start"),this.stop(),this._session_state=t,this._timer=window.setInterval(function(){e._frame.contentWindow.postMessage(e._client_id+" "+e._session_state,e._frame_origin)},this._interval))},t.prototype.stop=function(){this._session_state=null,this._timer&&(i.Log.debug("CheckSessionIFrame.stop"),window.clearInterval(this._timer),this._timer=null)},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.TokenRevocationClient=void 0;var i=n(328),o=n(334),s=n(332),a="access_token";e.TokenRevocationClient=function(){function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.Global.XMLHttpRequest,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:o.MetadataService;if(r(this,t),!e)throw i.Log.error("TokenRevocationClient.ctor: No settings provided"),new Error("No settings provided.");this._settings=e,this._XMLHttpRequestCtor=n,this._metadataService=new a(this._settings)}return t.prototype.revoke=function(t,e){var n=this;if(!t)throw i.Log.error("TokenRevocationClient.revoke: No accessToken provided"),new Error("No accessToken provided.");return this._metadataService.getRevocationEndpoint().then(function(r){if(r){i.Log.error("TokenRevocationClient.revoke: Revoking access token");var o=n._settings.client_id,s=n._settings.client_secret;return n._revoke(r,o,s,t)}if(e)throw i.Log.error("TokenRevocationClient.revoke: Revocation not supported"),new Error("Revocation not supported")})},t.prototype._revoke=function(t,e,n,r){var o=this;return new Promise(function(s,u){var c=new o._XMLHttpRequestCtor;c.open("POST",t),c.onload=function(){i.Log.debug("TokenRevocationClient.revoke: HTTP response received, status",c.status),200===c.status?s():u(Error(c.statusText+" ("+c.status+")"))};var f="client_id="+encodeURIComponent(e);n&&(f+="&client_secret="+encodeURIComponent(n)),f+="&token_type_hint="+encodeURIComponent(a),f+="&token="+encodeURIComponent(r),c.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),c.send(f)})},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.CordovaPopupNavigator=void 0;var i=n(367);e.CordovaPopupNavigator=function(){function t(){r(this,t)}return t.prototype.prepare=function(t){var e=new i.CordovaPopupWindow(t);return Promise.resolve(e)},t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.CordovaPopupWindow=void 0;var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(328),s="location=no,toolbar=no,zoom=no",a="_blank";e.CordovaPopupWindow=function(){function t(e){var n=this;r(this,t),this._promise=new Promise(function(t,e){n._resolve=t,n._reject=e}),this.features=e.popupWindowFeatures||s,this.target=e.popupWindowTarget||a,this.redirect_uri=e.startUrl,o.Log.debug("CordovaPopupWindow.ctor: redirect_uri: "+this.redirect_uri)}return t.prototype._isInAppBrowserInstalled=function(t){return["cordova-plugin-inappbrowser","cordova-plugin-inappbrowser.inappbrowser","org.apache.cordova.inappbrowser"].some(function(e){return t.hasOwnProperty(e)})},t.prototype.navigate=function(t){if(t&&t.url){if(!window.cordova)return this._error("cordova is undefined");var e=window.cordova.require("cordova/plugin_list").metadata;if(this._isInAppBrowserInstalled(e)===!1)return this._error("InAppBrowser plugin not found");this._popup=cordova.InAppBrowser.open(t.url,this.target,this.features),this._popup?(o.Log.debug("CordovaPopupWindow.navigate: popup successfully created"),this._exitCallbackEvent=this._exitCallback.bind(this),this._loadStartCallbackEvent=this._loadStartCallback.bind(this),this._popup.addEventListener("exit",this._exitCallbackEvent,!1),this._popup.addEventListener("loadstart",this._loadStartCallbackEvent,!1)):this._error("Error opening popup window")}else this._error("No url provided");return this.promise},t.prototype._loadStartCallback=function(t){0===t.url.indexOf(this.redirect_uri)&&this._success({url:t.url})},t.prototype._exitCallback=function(t){this._error(t)},t.prototype._success=function(t){this._cleanup(),o.Log.debug("CordovaPopupWindow: Successful response from cordova popup window"),this._resolve(t)},t.prototype._error=function(t){this._cleanup(),o.Log.error(t),this._reject(new Error(t))},t.prototype.close=function(){this._cleanup()},t.prototype._cleanup=function(){this._popup&&(o.Log.debug("CordovaPopupWindow: cleaning up popup"),this._popup.removeEventListener("exit",this._exitCallbackEvent,!1),this._popup.removeEventListener("loadstart",this._loadStartCallbackEvent,!1),this._popup.close()),this._popup=null},i(t,[{key:"promise",get:function(){return this._promise}}]),t}()},function(t,e,n){"use strict";function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0}),e.CordovaIFrameNavigator=void 0;var i=n(367);e.CordovaIFrameNavigator=function(){function t(){r(this,t)}return t.prototype.prepare=function(t){t.popupWindowFeatures="hidden=yes";var e=new i.CordovaPopupWindow(t);return Promise.resolve(e)},t}()}]);
hi
currency_info.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ access_path::AccessPath, account_config::constants::{ libra_root_address, type_tag_for_currency_code, CORE_CODE_ADDRESS, }, event::EventHandle, }; use anyhow::Result; use move_core_types::{ identifier::{IdentStr, Identifier}, language_storage::{ResourceKey, StructTag}, move_resource::MoveResource, }; use serde::{Deserialize, Serialize}; /// Struct that represents a CurrencyInfo resource #[derive(Debug, Serialize, Deserialize)] pub struct CurrencyInfoResource { total_value: u128, preburn_value: u64, to_lbr_exchange_rate: u64, is_synthetic: bool, scaling_factor: u64, fractional_part: u64, currency_code: Identifier, can_mint: bool, mint_events: EventHandle, burn_events: EventHandle, preburn_events: EventHandle, cancel_burn_events: EventHandle, exchange_rate_update_events: EventHandle, } impl MoveResource for CurrencyInfoResource { const MODULE_NAME: &'static str = "Libra"; const STRUCT_NAME: &'static str = "CurrencyInfo"; } impl CurrencyInfoResource { pub fn currency_code(&self) -> &IdentStr { &self.currency_code } pub fn scaling_factor(&self) -> u64
pub fn fractional_part(&self) -> u64 { self.fractional_part } pub fn exchange_rate(&self) -> f32 { // Exchange rates are represented as 32|32 fixed-point numbers on-chain, so we divide by the scaling // factor (2^32) of the number to arrive at the floating point representation of the number. (self.to_lbr_exchange_rate as f32) / 2f32.powf(32f32) } pub fn convert_to_lbr(&self, amount: u64) -> u64 { (self.exchange_rate() * (amount as f32)) as u64 } pub fn struct_tag_for(currency_code: Identifier) -> StructTag { StructTag { address: CORE_CODE_ADDRESS, module: CurrencyInfoResource::module_identifier(), name: CurrencyInfoResource::struct_identifier(), type_params: vec![type_tag_for_currency_code(currency_code)], } } pub fn resource_path_for(currency_code: Identifier) -> AccessPath { let resource_key = ResourceKey::new( libra_root_address(), CurrencyInfoResource::struct_tag_for(currency_code), ); AccessPath::resource_access_path(&resource_key) } pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> { lcs::from_bytes(bytes).map_err(Into::into) } pub fn total_value(&self) -> u128 { self.total_value } pub fn preburn_value(&self) -> u64 { self.preburn_value } pub fn mint_events(&self) -> &EventHandle { &self.mint_events } pub fn burn_events(&self) -> &EventHandle { &self.burn_events } pub fn preburn_events(&self) -> &EventHandle { &self.preburn_events } pub fn cancel_burn_events(&self) -> &EventHandle { &self.cancel_burn_events } pub fn exchange_rate_update_events(&self) -> &EventHandle { &self.exchange_rate_update_events } }
{ self.scaling_factor }
interval_function.rs
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::BTreeMap; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; use common_datavalues2::chrono::Datelike; use common_datavalues2::chrono::Duration; use common_datavalues2::chrono::NaiveDate; use common_datavalues2::chrono::NaiveDateTime; use common_datavalues2::prelude::*; use common_datavalues2::with_match_primitive_types_error; use common_exception::ErrorCode; use common_exception::Result; use num_traits::AsPrimitive; use crate::define_date_add_year_months; use crate::define_datetime32_add_year_months; use crate::define_datetime64_add_year_months; use crate::impl_interval_year_month; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::ArithmeticCreator; use crate::scalars::ArithmeticDescription; use crate::scalars::EvalContext; use crate::scalars::Function2; use crate::scalars::ScalarBinaryExpression; use crate::scalars::ScalarBinaryFunction; pub struct IntervalFunctionCreator<T> { t: PhantomData<T>, } impl<T> IntervalFunctionCreator<T> where T: IntervalArithmeticImpl + Send + Sync + Clone + 'static { pub fn try_create_func( display_name: &str, factor: i64, args: &[&DataTypePtr], ) -> Result<Box<dyn Function2>> { let left_arg = remove_nullable(args[0]); let right_arg = remove_nullable(args[1]); let left_type = left_arg.data_type_id(); let right_type = right_arg.data_type_id(); with_match_primitive_types_error!(right_type, |$R| { match left_type { TypeID::Date16 => IntervalFunction::<u16, $R, T::Date16Result, _>::try_create_func( display_name, T::Date16Result::to_date_type(), T::eval_date16::<$R>, factor, None, ), TypeID::Date32 => IntervalFunction::<i32, $R, T::Date32Result, _>::try_create_func( display_name, T::Date32Result::to_date_type(), T::eval_date32::<$R>, factor, None, ), TypeID::DateTime32 => IntervalFunction::<u32, $R, u32, _>::try_create_func( display_name, left_arg, T::eval_datetime32::<$R>, factor, None, ), TypeID::DateTime64 => { let mut mp = BTreeMap::new(); let datetime = left_arg.as_any().downcast_ref::<DateTime64Type>().unwrap(); let precision = datetime.precision().to_string(); mp.insert("precision".to_string(), precision); IntervalFunction::<i64, $R, i64, _>::try_create_func( display_name, left_arg, T::eval_datetime64::<$R>, factor, Some(mp), ) }, _=> Err(ErrorCode::BadDataValueType(format!( "DataValue Error: Unsupported arithmetic {}({:?}, {:?})", display_name, left_type, right_type ))), } }) } pub fn desc(factor: i64) -> ArithmeticDescription { let function_creator: ArithmeticCreator = Box::new(move |display_name, args| Self::try_create_func(display_name, factor, args)); ArithmeticDescription::creator(function_creator) .features(FunctionFeatures::default().deterministic().num_arguments(2)) } } #[derive(Clone)] pub struct IntervalFunction<L: DateType, R: PrimitiveType, O: DateType, F> { display_name: String, result_type: DataTypePtr, binary: ScalarBinaryExpression<L, R, O, F>, factor: i64, metadata: Option<BTreeMap<String, String>>, } impl<L, R, O, F> IntervalFunction<L, R, O, F> where L: DateType + Send + Sync + Clone, R: PrimitiveType + Send + Sync + Clone, O: DateType + Send + Sync + Clone, F: ScalarBinaryFunction<L, R, O> + Send + Sync + Clone + 'static, { pub fn try_create_func( display_name: &str, result_type: DataTypePtr, func: F, factor: i64, metadata: Option<BTreeMap<String, String>>, ) -> Result<Box<dyn Function2>> { let binary = ScalarBinaryExpression::<L, R, O, _>::new(func); Ok(Box::new(Self { display_name: display_name.to_string(), result_type, binary, factor, metadata, })) } } impl<L, R, O, F> Function2 for IntervalFunction<L, R, O, F> where L: DateType + Send + Sync + Clone, R: PrimitiveType + Send + Sync + Clone, O: DateType + Send + Sync + Clone, F: ScalarBinaryFunction<L, R, O> + Send + Sync + Clone + 'static, { fn name(&self) -> &str { self.display_name.as_str() } fn return_type(&self, _args: &[&DataTypePtr]) -> Result<DataTypePtr> { Ok(self.result_type.clone()) } fn eval(&self, columns: &ColumnsWithField, _input_rows: usize) -> Result<ColumnRef> { // Todo(zhyass): define the ctx out of the eval. let mut ctx = EvalContext::new(self.factor, None, self.metadata.clone()); let col = self .binary .eval(columns[0].column(), columns[1].column(), &mut ctx)?; Ok(Arc::new(col)) } } impl<L, R, O, F> fmt::Display for IntervalFunction<L, R, O, F> where L: DateType + Send + Sync + Clone, R: PrimitiveType + Send + Sync + Clone, O: DateType + Send + Sync + Clone, F: ScalarBinaryFunction<L, R, O> + Send + Sync + Clone + 'static, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}()", self.display_name) } } pub trait IntervalArithmeticImpl { type Date16Result: DateType + ToDateType; type Date32Result: DateType + ToDateType; fn eval_date16<R: PrimitiveType + AsPrimitive<i64>>( l: u16, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date16Result; fn eval_date32<R: PrimitiveType + AsPrimitive<i64>>( l: i32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date32Result; fn eval_datetime32<R: PrimitiveType + AsPrimitive<i64>>( l: u32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> u32; fn eval_datetime64<R: PrimitiveType + AsPrimitive<i64>>( l: i64, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> i64; } impl_interval_year_month!(AddYearsImpl, add_years_base); impl_interval_year_month!(AddMonthsImpl, add_months_base); #[derive(Clone)] pub struct AddDaysImpl; impl IntervalArithmeticImpl for AddDaysImpl { type Date16Result = u16; type Date32Result = i32; fn eval_date16<R: PrimitiveType + AsPrimitive<i64>>( l: u16, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date16Result { (l as i64 + r.to_owned_scalar().as_() * ctx.factor) as Self::Date16Result } fn eval_date32<R: PrimitiveType + AsPrimitive<i64>>( l: i32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date32Result { (l as i64 + r.to_owned_scalar().as_() * ctx.factor) as Self::Date32Result } fn eval_datetime32<R: PrimitiveType + AsPrimitive<i64>>( l: u32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> u32 { let factor = ctx.factor * 24 * 3600; (l as i64 + r.to_owned_scalar().as_() * factor) as u32 } fn eval_datetime64<R: PrimitiveType + AsPrimitive<i64>>( l: i64, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> i64 { let precision = ctx .get_meta_value("precision".to_string()) .map_or(0, |v| v.parse::<u32>().unwrap()); let base = 10_i64.pow(precision); let factor = ctx.factor * 24 * 3600 * base; l as i64 + r.to_owned_scalar().as_() * factor } } #[derive(Clone)] pub struct AddTimesImpl; impl IntervalArithmeticImpl for AddTimesImpl { type Date16Result = u32; type Date32Result = i64; fn eval_date16<R: PrimitiveType + AsPrimitive<i64>>( l: u16, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date16Result { (l as i64 * 3600 * 24 + r.to_owned_scalar().as_() * ctx.factor) as Self::Date16Result
l: i32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> Self::Date32Result { l as i64 * 3600 * 24 + r.to_owned_scalar().as_() * ctx.factor } fn eval_datetime32<R: PrimitiveType + AsPrimitive<i64>>( l: u32, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> u32 { (l as i64 + r.to_owned_scalar().as_() * ctx.factor) as u32 } fn eval_datetime64<R: PrimitiveType + AsPrimitive<i64>>( l: i64, r: R::RefType<'_>, ctx: &mut EvalContext, ) -> i64 { let precision = ctx .get_meta_value("precision".to_string()) .map_or(0, |v| v.parse::<u32>().unwrap()); let base = 10_i64.pow(precision); let factor = ctx.factor * base; l as i64 + r.to_owned_scalar().as_() * factor } } fn add_years_base(year: i32, month: u32, day: u32, delta: i64) -> Result<NaiveDate> { let new_year = year + delta as i32; let mut new_day = day; if std::intrinsics::unlikely(month == 2 && day == 29) { new_day = last_day_of_year_month(new_year, month); } NaiveDate::from_ymd_opt(new_year, month, new_day).ok_or_else(|| { ErrorCode::Overflow(format!( "Overflow on date YMD {}-{}-{}.", new_year, month, new_day )) }) } fn add_months_base(year: i32, month: u32, day: u32, delta: i64) -> Result<NaiveDate> { let total_months = month as i64 + delta - 1; let mut new_year = year + (total_months / 12) as i32; let mut new_month0 = total_months % 12; if new_month0 < 0 { new_year -= 1; new_month0 += 12; } // Handle month last day overflow, "2020-2-29" + "1 year" should be "2021-2-28", or "1990-1-31" + "3 month" should be "1990-4-30". let new_day = std::cmp::min::<u32>( day, last_day_of_year_month(new_year, (new_month0 + 1) as u32), ); NaiveDate::from_ymd_opt(new_year, (new_month0 + 1) as u32, new_day).ok_or_else(|| { ErrorCode::Overflow(format!( "Overflow on date YMD {}-{}-{}.", new_year, new_month0 + 1, new_day )) }) } // Get the last day of the year month, could be 28(non leap Feb), 29(leap year Feb), 30 or 31 fn last_day_of_year_month(year: i32, month: u32) -> u32 { let is_leap_year = NaiveDate::from_ymd_opt(year, 2, 29).is_some(); if std::intrinsics::unlikely(month == 2 && is_leap_year) { return 29; } let last_day_lookup = [0u32, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; last_day_lookup[month as usize] } pub type AddYearsFunction = IntervalFunctionCreator<AddYearsImpl>; pub type AddMonthsFunction = IntervalFunctionCreator<AddMonthsImpl>; pub type AddDaysFunction = IntervalFunctionCreator<AddDaysImpl>; pub type AddTimesFunction = IntervalFunctionCreator<AddTimesImpl>;
} fn eval_date32<R: PrimitiveType + AsPrimitive<i64>>(
getOrganization.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package v20200301preview import ( "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) // Organization resource. func
(ctx *pulumi.Context, args *LookupOrganizationArgs, opts ...pulumi.InvokeOption) (*LookupOrganizationResult, error) { var rv LookupOrganizationResult err := ctx.Invoke("azure-nextgen:confluent/v20200301preview:getOrganization", args, &rv, opts...) if err != nil { return nil, err } return &rv, nil } type LookupOrganizationArgs struct { // Organization resource name OrganizationName string `pulumi:"organizationName"` // Resource group name ResourceGroupName string `pulumi:"resourceGroupName"` } // Organization resource. type LookupOrganizationResult struct { // The creation time of the resource. CreatedTime string `pulumi:"createdTime"` // The ARM id of the resource. Id string `pulumi:"id"` // Location of Organization resource Location *string `pulumi:"location"` // The name of the resource. Name string `pulumi:"name"` // Confluent offer detail OfferDetail *OrganizationResourcePropertiesResponseOfferDetail `pulumi:"offerDetail"` // Id of the Confluent organization. OrganizationId string `pulumi:"organizationId"` // Provision states for confluent RP ProvisioningState string `pulumi:"provisioningState"` // SSO url for the Confluent organization. SsoUrl string `pulumi:"ssoUrl"` // Organization resource tags Tags map[string]string `pulumi:"tags"` // The type of the resource. Type string `pulumi:"type"` // Subscriber detail UserDetail *OrganizationResourcePropertiesResponseUserDetail `pulumi:"userDetail"` }
LookupOrganization
state.js
export default () => ({ request: { method: "GET", url: "https://httpbin.org", path: "/get", label: "", auth: "None", httpUser: "", httpPassword: "", passwordFieldType: "password", bearerToken: "", headers: [], params: [], bodyParams: [],
rawParams: "", rawInput: false, requestType: "", contentType: "" }, gql: { url: "https://rickandmortyapi.com/graphql", headers: [], variablesJSONString: "", query: "" }, oauth2: { tokens: [], tokenReqs: [], tokenReqSelect: "", tokenReqName: "", accessTokenName: "", oidcDiscoveryUrl: "", authUrl: "", accessTokenUrl: "", clientId: "", scope: "" } });
train_classifier.py
import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 import glob import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from extract_feature import * # NOTE: the next import is only valid for scikit-learn version <= 0.17 # for scikit-learn >= 0.18 use: # from sklearn.model_selection import train_test_split from sklearn.cross_validation import train_test_split import pickle # Read in cars and notcars cars = glob.glob('./train_data/vehicles/*/*.png'); train_data_tpye = 'png'; notcars = glob.glob('./train_data/non-vehicles/*/*.png') #cars = glob.glob('./hog_test_imgs/vehicles_smallset/*/*.jpeg'); train_data_tpye = 'jpeg'; #notcars = glob.glob('./hog_test_imgs/non-vehicles_smallset/*/*.jpeg') sample_size = None cars = cars[0:sample_size] notcars = notcars[0:sample_size] color_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb orient = 9 # HOG orientations pix_per_cell = 8 # HOG pixels per cell cell_per_block = 2 # HOG cells per block hog_channel = "ALL" # Can be 0, 1, 2, or "ALL" spatial_size = (32, 32) # Spatial binning dimensions hist_bins = 32 # Number of histogram bins spatial_feat = True # Spatial features on or off hist_feat = True # Histogram features on or off hog_feat = True # HOG features on or off y_start_stop = [None, None] # Min and max in y to search in slide_window() t = time.time() print("start extract car_features") car_features = extract_features(cars, train_data_tpye, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) print("start extract notcar_features") notcar_features = extract_features(notcars, train_data_tpye, color_space=color_space, spatial_size=spatial_size, hist_bins=hist_bins, orient=orient, pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel, spatial_feat=spatial_feat, hist_feat=hist_feat, hog_feat=hog_feat) X = np.vstack((car_features, notcar_features)).astype(np.float64) # Define the labels vector y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features)))) # Split up data into randomized training and test sets rand_state = np.random.randint(0, 100) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=rand_state)
print(round(t2-t, 2), 'Seconds to extract features SVC...') print("X_train shape: {} \X_test shape: {}".format(X_train.shape, X_test.shape)) # Fit a per-column scaler X_scaler = StandardScaler().fit(X_train) # Apply the scaler to X X_train = X_scaler.transform(X_train) X_test = X_scaler.transform(X_test) print('Using:',orient,'orientations',pix_per_cell, 'pixels per cell and', cell_per_block,'cells per block') print('Feature vector length:', len(X_train[0])) # Use a linear SVC svc = LinearSVC() t=time.time() svc.fit(X_train, y_train) t2 = time.time() print(round(t2-t, 2), 'Seconds to train SVC...') # Check the score of the SVC print('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4)) # pickle SVC pickle_file = 'svc_acc_%f.p'%round(svc.score(X_test, y_test), 4) try: with open(pickle_file, 'wb') as pfile: pickle.dump( { 'svc': svc, 'scaler': X_scaler, 'color_space': color_space, 'orient': orient, 'pix_per_cell': pix_per_cell, 'cell_per_block': cell_per_block, 'spatial_size': spatial_size, 'hist_bins': hist_bins, 'spatial_feat': spatial_feat, 'hist_feat': hist_feat, }, pfile, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', pickle_file, ':', e) raise
t2 = time.time()
user.go
package forum // import "github.com/BenLubar/wtdwtf-science/forum" import ( "time" "github.com/lib/pq" ) type User interface { ID() int64 Login() string DisplayName() string Email() string Slug() string CreatedAt() time.Time
Signature() string Location() string Bio() string WebAddress() string DateOfBirth() pq.NullTime Imported() map[Forum]int64 }
LastSeen() pq.NullTime