text: !function(e,t){var n=function(){return t(e)};"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):breeze=n()}(this,function(e){"use strict";function t(e,t){for(var n in e)ot(e,n)&&t(n,e[n])}function n(e,t){var n=[];for(var r in e)if(ot(e,r)){var i=t?t(r,e[r]):e[r];void 0!==i&&n.push(i)}return n}function r(e,t){for(var n in e)if(ot(e,n)){var r=e[n];if(t(n,r))return{key:n,value:r}}return null}function i(e,t){var n=a(e,t);return null==n?!0:!(!n.writable&&!n.set)}function a(e,t){if(!ut)return null;if(e.hasOwnProperty(t))return Object.getOwnPropertyDescriptor(e,t);var n=Object.getPrototypeOf(e);return null==n?null:a(n,t)}function o(e,t){return function(n){return n[e]===t}}function s(e){return function(t){return t[e]}}function u(e){var t=[];for(var n in e)ot(e,n)&&t.push(e[n]);return t}function p(e,t,n){if(!t)return e;if(n)n.forEach(function(n){e[n]=t[n]});else for(var r in t)ot(t,r)&&(e[r]=t[r]);return e}function c(e,t){for(var n in t)void 0===e[n]&&(e[n]=t[n]);return e}function l(e,t){return t.defaultInstance=c(new t(e),t.defaultInstance),e}function y(e,t,n){n=n||{};for(var r in t){var i=r.split(","),a=t[r];i.some(function(t){if(!(t in e))return!1;var r=e[t];return"function"==typeof r?!1:r==a?!0:Array.isArray(r)&&0===r.length?!0:("function"==typeof a?r=a(r):"object"==typeof r&&r&&r.parentEnum&&(r=r.name),void 0===r?!0:(n[i[0]]=r,!0))})}return n}function f(e,t){if(e!==Object(e))return e;if(e._$visited)return void 0;if(e.toJSON){var n=e.toJSON();if(n!==Object(n))return n;if(n!==e)return f(n);e=n}e._$visited=!0;var r;if(e instanceof Array)r=e.map(function(e){return f(e,t)});else if("function"==typeof e)r=void 0;else{r={};for(var i in e)if("_$visited"!==i){var a=e[i];t&&(a=t(i,a),void 0===a)||(a=f(a),void 0!==a&&(r[i]=a))}}return delete e._$visited,r}function h(e,t){var n={},r=e.length;return t.forEach(function(t){for(var i=0;r>i;i++){var a=e[i];if(a){var o=a[t];if(void 0!==o){n[t]=o;break}}}}),n}function d(e){return null==e?[]:Array.isArray(e)?e:[e]}function m(e,t,n){if(n=null==n?!0:n,null==e)return e;var r;return Array.isArray(e)?(r=[],e.forEach(function(e,i){var a=t(e,i);(null!=a||n)&&(r[i]=a)})):r=t(e),r}function v(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return e[n];return null}function g(e,t){for(var n=0,r=e.length;r>n;n++)if(t(e[n]))return n;return-1}function E(e,t){var n=e.indexOf(t);-1===n&&e.push(t)}function w(e,t,n){for(var r=V(t)?t:void 0,i=e.length-1,a=!1,o=i;o>=0;o--)if((r?r(e[o]):e[o]===t)&&(e.splice(o,1),a=!0,!n))return!0;return a}function S(e,t,n){for(var r=[],i=Math.min(e.length,t.length),a=0;i>a;++a)r.push(n(e[a],t[a]));return r}function P(e,t,n){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(Array.isArray(e[r])){if(!P(e[r],t[r]))return!1}else if(n){if(!n(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1;return!0}function T(e,t){var n=e[t];return n||(n=[],e[t]=n),n}function N(e,t){for(var n=e.split(";"),r=0,i=n.length;i>r;r++){var a=_(n[r]);if(a)return a}if(t)throw new Error("Unable to initialize "+e+".  "+t)}function _(t){var n=e.window;if(n){var r=n[t];if(r)return r;var i=n.require;if(i){if(i.defined)return i.defined(t)?i(t):void 0;try{return i(t)}catch(a){return}}}}function b(e,t,n,r){var i=e[t];if(n===i)return r();e[t]=n;try{return r()}finally{void 0===i?delete e[t]:e[t]=i}}function O(e,t,n){var r;try{return r=e(),n()}catch(i){throw"object"==typeof r&&(r.error=i),i}finally{t(r)}}function A(e){return function(){for(var t=st(arguments),n="",r=t.length,i=null;r--;)i=t[r],n+=i===Object(i)?JSON.stringify(i):i,e.memoize||(e.memoize={});return n in e.memoize?e.memoize[n]:e.memoize[n]=e.apply(this,t)}}function C(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0,n="x"==e?t:3&t|8;return n.toString(16)})}function x(e){if("string"!=typeof e)throw new Error("Invalid ISO8601 duration '"+e+"'");var t=/^P((\d+Y)?(\d+M)?(\d+D)?)?(T(\d+H)?(\d+M)?(\d+S)?)?$/.exec(e);if(!t)throw new Error("Invalid ISO8601 duration '"+e+"'");for(var n=[2,3,4,6,7,8],r=[31104e3,2592e3,86400,3600,60,1],i=0,a=0;6>a;a++){var o=t[n[a]];o=o?+o.replace(/[A-Za-z]+/g,""):0,i+=o*r[a]}return i}function F(){}function M(e){return e}function D(e){return null===e?"null":void 0===e?"undefined":Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function k(e){return"date"===D(e)&&!isNaN(e.getTime())}function I(e){var t=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;return"string"==typeof e&&t.test(e)}function V(e){return"function"===D(e)}function R(e){return"string"==typeof e}function K(e){return"object"==typeof e}function j(e){return"string"==typeof e&&/[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(e)}function B(e){return"string"==typeof e&&/^(-|)?P[T]?[\d\.,\-]+[YMDTHS]/.test(e)}function L(e){if(null===e||void 0===e)return!0;for(var t in e)if(ot(e,t))return!1;return!0}function q(e){return!isNaN(parseFloat(e))&&isFinite(e)}function U(e,t){return e?""==t||null==t?!0:0===e.indexOf(t,0):!1}function z(e,t){return e?""==t||null==t?!0:-1!==e.indexOf(t,e.length-t.length):!1}function G(e){var t=arguments,n=RegExp("%([1-"+(arguments.length-1)+"])","g");return e.replace(n,function(e,n){return t[n]})}function $(e){var t=Function.call;return function(){return t.apply(e,arguments)}}function J(e,t,n){void 0===t&&(t=null);var r=n(),i=e.dataType;if(i&&i.parse&&(t=Array.isArray(t)&&!e.isScalar?t.map(function(e){return i.parse(e,typeof e)}):i.parse(t,typeof t)),!(t===r||i&&i.isDate&&t&&r&&t.valueOf()===r.valueOf())){var a,o=this.entityAspect;if(o)a=e.name;else{var s=this.complexAspect;if(!s)return void n(t);o=s.getEntityAspect(),a=s.getPropertyPath(e.name)}var u=o._inProcess=o._inProcess||[];if(!(u.indexOf(e)>=0)){u.push(e);try{var p={parent:this,property:e,newValue:t,oldValue:r,propertyName:a,entityAspect:o};e.isComplexProperty?Z(p,n):e.isDataProperty?Q(p,n):H(p,n),Y(p)}finally{u.pop()}}}}function Q(e,t){var n=e.parent,r=e.property,i=e.entityAspect,a=e.oldValue,o=e.newValue,s=i.entityManager,u=n.entityType;if(!r.isScalar)throw new Error("Nonscalar data properties are readonly - items may be added or removed but the collection may not be changed.");if(i.entityState.isUnchangedOrModified()){var p=r.name,c=n.entityAspect||n.complexAspect;void 0===c.originalValues[p]&&(c.originalValues[p]=void 0!==a?a:r.defaultValue)}if(r.isPartOfKey&&s&&!s.isLoading){var l=u.keyProperties,y=l.map(function(e){return e===r?o:n.getProperty(e.name)}),f=new _t(u,y);if(s.findEntityByKey(f))throw new Error("An entity with this key is already in the cache: "+f.toString());var h=n.entityAspect.getKey(),d=s._findEntityGroup(u);d._replaceKey(h,f)}var m=r.relatedNavigationProperty;if(m&&s)if(null!=o){var v=new _t(m.entityType,[o]),g=s.findEntityByKey(v);g?n.setProperty(m.name,g):(s._unattachedChildrenMap.addChild(v,m,n),n.setProperty(m.name,null))}else n.setProperty(m.name,null);else if(r.inverseNavigationProperty&&s&&!s._inKeyFixup){var E=r.inverseNavigationProperty;if(null!=a&&(v=new _t(E.parentType,[a]),g=s.findEntityByKey(v)))if(E.isScalar)g.setProperty(E.name,null);else{var w=g.getProperty(E.name);w.splice(w.indexOf(n),1)}null!=o&&(v=new _t(E.parentType,[o]),g=s.findEntityByKey(v),g?E.isScalar?g.setProperty(E.name,n):g.getProperty(E.name).push(n):s._unattachedChildrenMap.addChild(v,E,n))}if(t(o),W(e),r.isPartOfKey){var S=u.keyProperties.indexOf(r);u.navigationProperties.forEach(function(e){var t=e.inverse,r=t?t.foreignKeyNames:e.invForeignKeyNames;if(0!==r.length){var i=n.getProperty(e.name);if(i){var a=r[S];e.isScalar?i.setProperty(a,o):i.forEach(function(e){e.setProperty(a,o)})}}}),s&&u.inverseForeignKeyProperties.forEach(function(e){null==e.relatedNavigationProperty.inverse&&s._updateFkVal(e,a,o)}),i.getKey(!0)}}function Z(e,t){var n=e.property,r=e.oldValue,i=e.newValue,a=n.dataType;if(!n.isScalar)throw new Error(G("You cannot set the non-scalar complex property: '%1' on the type: '%2'.Instead get the property and use array functions like 'push' or 'splice' to change its contents.",n.name,n.parentType.name));if(!i)throw new Error(G("You cannot set the '%1' property to null because it's datatype is the ComplexType: '%2'",n.name,n.dataType.name));if(!r){var o=a.getCtor();r=new o,t(r)}a.dataProperties.forEach(function(e){var t=e.name,n=i.getProperty(t);r.setProperty(t,n)})}function H(e,t){var n=e.parent,r=e.property,i=e.entityAspect,a=e.oldValue,o=e.newValue;if(!r.isScalar)throw new Error("Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed.");var s=i.entityManager,u=r.inverse;if(null!=o){var p=o.entityAspect;if(s){if(p.entityState.isDetached())s.isLoading||s.attachEntity(o,bt.Added);else if(p.entityManager!==s)throw new Error("An Entity cannot be attached to an entity in another EntityManager. One of the two entities must be detached first.")}else p&&p.entityManager&&(s=p.entityManager,s.isLoading||s.attachEntity(i.entity,bt.Added))}if(u)if(u.isScalar)null!=a&&a.setProperty(u.name,null),null!=o&&o.setProperty(u.name,n);else{if(null!=a){var c=a.getProperty(u.name),l=c.indexOf(n);-1!==l&&c.splice(l,1)}if(null!=o){var y=o.getProperty(u.name);y.push(n)}}else if(r.invForeignKeyNames&&s&&!s._inKeyFixup){var f=r.invForeignKeyNames;if(null!=o){var h=n.entityAspect.getKey().values;f.forEach(function(e,t){o.setProperty(e,h[t])})}else null!=a&&f.forEach(function(e){var t=a.entityType.getProperty(e);t.isPartOfKey||a.setProperty(e,null)})}if(t(o),W(e),r.relatedDataProperties){var d=i.entityState;if(null==o&&(d.isDetached()||a.entityAspect.entityState.isDetached()))return;if(d.isDeleted())return;var m=r.entityType.keyProperties;m.forEach(function(e,t){var i=r.relatedDataProperties[t];if(o||!i.isPartOfKey){var a=o?o.getProperty(e.name):i.defaultValue;n.setProperty(i.name,a)}})}}function Y(e){var t=e.entityAspect,n=t.entityManager,r=t.entity,i={entity:r,parent:e.parent,property:e.property,propertyName:e.propertyName,oldValue:e.oldValue,newValue:e.newValue};n?n.isLoading||n.isRejectingChanges||(t.propertyChanged.publish(i),n.entityChanged.publish({entityAction:Pt.PropertyChange,entity:r,args:i})):t.propertyChanged.publish(i)}function W(e){var t=e.entityAspect,n=t.entityManager;if(null!=n&&!n.isLoading){var r=e.property;t.entityState.isUnchanged()&&!r.isUnmapped&&t.setModified(),n.validationOptions.validateOnPropertyChange&&t._validateProperty(e.newValue,{entity:t.entity,property:r,propertyName:e.propertyName,oldValue:e.oldValue})}}function X(e){if(!e)return null;var t=e.split(":#");if(t.length>1)return et(t[0],t[1]);if(U(e,Ft.ANONTYPE_PREFIX)){var n=et(e);return n.isAnonymous=!0,n}var r=e.split(",")[0],t=r.split(".");if(t.length>1){var i=t[t.length-1],a=t.slice(0,t.length-1),o=a.join(".");return et(i,o)}return et(e)}function et(e,t){return{shortTypeName:e,namespace:t,typeName:nt(e,t)}}function tt(e){return e.indexOf(":#")>=0}function nt(e,t){return t&&t.length>0?e+":#"+t:e}function rt(e,t,n){if(t)if(Array.isArray(t))t.forEach(e._addPropertyCore.bind(e));else{if("object"!=typeof t)throw new Error("The 'dataProperties' or 'navigationProperties' values must be either an array of data/nav properties or an object where each property defines a data/nav property");for(var r in t)if(ot(t,r)){var i=t[r];i.name=r;var a=new n(i);e._addPropertyCore(a)}}}function it(e,t){var n=Array.isArray(t)?t:t.split(".");if(1===n.length)return e.getProperty(t);var r=e;return n.some(function(e){return r=r.getProperty(e),null==r}),r}var at={version:"1.5.4",metadataVersion:"1.0.5"},ot=$(Object.prototype.hasOwnProperty),st=$(Array.prototype.slice),ut=function(){try{return!(!Object.getPrototypeOf||!Object.defineProperty({},"x",{}))}catch(e){return!1}}();Object.create||(Object.create=function(e){var t=function(){};return t.prototype=e,new t});var pt={};pt.__isES5Supported=ut,pt.objectForEach=t,pt.extend=p,pt.propEq=o,pt.pluck=s,pt.arrayEquals=P,pt.arrayFirst=v,pt.arrayIndexOf=g,pt.arrayRemoveItem=w,pt.arrayZip=S,pt.requireLib=N,pt.using=b,pt.memoize=A,pt.getUuid=C,pt.durationToSeconds=x,pt.isDate=k,pt.isGuid=j,pt.isDuration=B,pt.isFunction=V,pt.isEmpty=L,pt.isNumeric=q,pt.stringStartsWith=U,pt.stringEndsWith=z,pt.formatString=G,pt.getPropertyDescriptor=a,pt.toJSONSafe=f,pt.parent=at,at.core=pt;var ct=function(){function e(e,t){return null==t?!1:"string"==typeof t&&t.length>0}function t(e,t){return null==t?!1:typeof t===e.typeName?!0:!1}function n(e,t){return null==t?!1:t instanceof e.type}function r(e,t){return null==t?!1:void 0!==t[e.propertyName]}function i(e,t){return null==t?!1:e.enumType.contains(t)}function a(e,t){return e.allowNull?void 0!==t:null!=t}function o(e,t){if(null==t)return!0;var n=e.prevContext;return n?n.fn(n,t):!0}function s(e,t){var n=e.prevContext,r=n?" or it "+l(n,t):"";return"is optional"+r}function u(e,t){if(!Array.isArray(t))return!1;if(e.mustNotBeEmpty&&0===t.length)return!1;var n=e.prevContext;return n?t.every(function(e){return n.fn(n,e)}):!0}function c(e,t){var n=e.mustNotBeEmpty?"a nonEmpty array":"an array",r=e.prevContext,i=r?" where each element "+l(r,t):"";return" must be "+n+i}function l(e,t){var n=e.msg;return"function"==typeof n&&(n=n(e,t)),n}function y(e,t){if(e._context){for(var n=e._context;null!=n.prevContext;)n=n.prevContext;if(null===n.prevContext)return n.prevContext=t,e;if(null!=t.prevContext)throw new Error("Illegal construction - use 'or' to combine checks");t.prevContext=e._context}return f(e,t)}function f(e,t){return e._contexts[e._contexts.length-1]=t,e._context=t,e}function h(e){var t=e._contexts;return null==t[t.length-1]&&t.pop(),0===t.length?void 0:t.some(function(t){return t.fn(t,e.v)})}function d(e,t){throw new Error(G("Error configuring an instance of '%1'. %2",e&&e._$typeName||"object",t))}var m=function(e,t){this.v=e,this.name=t,this._contexts=[null]},v=m.prototype;return v.isObject=function(){return this.isTypeOf("object")},v.isBoolean=function(){return this.isTypeOf("boolean")},v.isString=function(){return this.isTypeOf("string")},v.isNonEmptyString=function(){return y(this,{fn:e,msg:"must be a nonEmpty string"})},v.isNumber=function(){return this.isTypeOf("number")},v.isFunction=function(){return this.isTypeOf("function")},v.isTypeOf=function(e){return y(this,{fn:t,typeName:e,msg:"must be a '"+e+"'"})},v.isInstanceOf=function(e,t){return t=t||e.prototype._$typeName,y(this,{fn:n,type:e,typeName:t,msg:"must be an instance of '"+t+"'"})},v.hasProperty=function(e){return y(this,{fn:r,propertyName:e,msg:"must have a '"+e+"' property"})},v.isEnumOf=function(e){return y(this,{fn:i,enumType:e,msg:"must be an instance of the '"+e.name+"' enumeration"})},v.isRequired=function(e){return y(this,{fn:a,allowNull:e,msg:"is required"})},v.isOptional=function(){var e={fn:o,prevContext:null,msg:s};return y(this,e)},v.isNonEmptyArray=function(){return this.isArray(!0)},v.isArray=function(e){var t={fn:u,mustNotBeEmpty:e,prevContext:null,msg:c};return y(this,t)},v.or=function(){return this._contexts.push(null),this._context=null,this},v.check=function(e){var t=h(this);if(void 0!==t){if(!t)throw new Error(this.getMessage());return void 0!==this.v?this.v:e}},v._addContext=function(e){return y(this,e)},v.getMessage=function(){var e=this,t=this._contexts.map(function(t){return l(t,e.v)}).join(", or it ");return G(this.MESSAGE_PREFIX,this.name)+" "+t},v.withDefault=function(e){return this.defaultValue=e,this},v.whereParam=function(e){return this.parent.whereParam(e)},v.applyAll=function(e,t){var n=e._$typeName,r=n&&this.parent.config._$typeName===n,i=p({},this.parent.config);if(this.parent.params.forEach(function(n){r||delete i[n.name];try{n.check()}catch(a){d(e,a.message)}!t&&n._applyOne(e)}),!r)for(var a in i)void 0!==i[a]&&d(e,G("Unknown property: '%1'.",a))},v._applyOne=function(e){void 0!==this.v?e[this.name]=this.v:void 0!==this.defaultValue&&(e[this.name]=this.defaultValue)},v.MESSAGE_PREFIX="The '%1' parameter ",m}(),lt=function(e,t){return new ct(e,t)},yt=function(){var e=function(e){if("object"!=typeof e)throw new Error("Configuration parameter should be an object, instead it is a: "+typeof e);this.config=e,this.params=[]},t=e.prototype;return t.whereParam=function(e){var t=new ct(this.config[e],e);return t.parent=this,this.params.push(t),t},e}(),ft=function(e){return new yt(e)};pt.Param=ct,pt.assertParam=lt,pt.assertConfig=ft;var ht=function(){function e(){}var t=function(t,n){this.name=t;var r=new e(n);r.parentEnum=this,this._symbolPrototype=r,n&&Object.keys(n).forEach(function(e){r[e]=n[e]})},n=t.prototype;return t.isSymbol=function(t){return t instanceof e},n.fromName=function(e){return this[e]},n.addSymbol=function(e){var t=Object.create(this._symbolPrototype);return e&&Object.keys(e).forEach(function(n){t[n]=e[n]}),setTimeout(function(){t.getName()},0),t},n.resolveSymbols=function(){this.getSymbols().forEach(function(e){return e.getName()})},n.getSymbols=function(){return this.getNames().map(function(e){return this[e]},this)},n.getNames=function(){var e=[];for(var t in this)this.hasOwnProperty(t)&&("name"===t||"_"===t.substr(0,1)||V(this[t])||e.push(t));return e},n.contains=function(t){return t instanceof e?this[t.getName()]===t:!1},e.prototype.getName=function(){if(!this.name){var e=this;this.name=v(this.parentEnum.getNames(),function(t){return e.parentEnum[t]===e})}return this.name},e.prototype.toString=function(){return this.getName()},e.prototype.toJSON=function(){return{_$typeName:this.parentEnum.name,name:this.name}},t}();pt.Enum=ht;var dt=function(){function e(e,n,r){var i=e._subscribers;return i?void i.forEach(function(i){try{i.callback(n)}catch(a){a.context="unable to publish on topic: "+e.name,r?r(a):e._defaultErrorCallback?e._defaultErrorCallback(a):t(a)}}):!0}function t(){}var n={},r=1,i=function(e,t,r){lt(e,"eventName").isNonEmptyString().check(),lt(t,"publisher").isObject().check(),this.name=e,n[e]=!0,this.publisher=t,r&&(this._defaultErrorCallback=r)},a=i.prototype;return a.publish=function(t,n,r){return i._isEnabled(this.name,this.publisher)?(n===!0?setTimeout(e,0,this,t,r):e(this,t,r),!0):!1},a.publishAsync=function(e,t){this.publish(e,!0,t)},a.subscribe=function(e){this._subscribers||(this._subscribers=[]);var t=r;return this._subscribers.push({unsubKey:t,callback:e}),++r,t},a.unsubscribe=function(e){if(!this._subscribers)return!1;var t=this._subscribers,n=g(t,function(t){return t.unsubKey===e});return-1!==n?(t.splice(n,1),0===t.length&&(this._subscribers=null),!0):!1},a.clear=function(){this._subscribers=null},i.bubbleEvent=function(e,t){e._getEventParent=t},i.enable=function(e,t,n){lt(e,"eventName").isNonEmptyString().check(),lt(t,"obj").isObject().check(),lt(n,"isEnabled").isBoolean().isOptional().or().isFunction().check(),t._$eventMap||(t._$eventMap={}),t._$eventMap[e]=n},i.isEnabled=function(e,t){if(lt(e,"eventName").isNonEmptyString().check(),lt(t,"obj").isObject().check(),void 0===t._getEventParent)throw new Error("This object does not support event enabling/disabling");return i._isEnabled(e,t)},i._isEnabled=function(e,t){var n=null,r=t._$eventMap;if(r&&(n=r[e]),null!=n)return"function"==typeof n?n(t):!!n;var a=t._getEventParent&&t._getEventParent();return a?i._isEnabled(e,a):!0},i}();pt.Event=dt;var mt=function(){function e(e,t,n){var r=t.defaultInstance;return r||(r=new t.ctor,t.defaultInstance=r,r._$impl=t),r.initialize(),n&&(e.defaultInstance=r),i.interfaceInitialized.publish({interfaceName:e.name,instance:r,isDefault:!0}),r.checkForRecomposition&&i.interfaceInitialized.subscribe(function(e){r.checkForRecomposition(e)}),r}function t(e){var t=e.toLowerCase(),n=r(i.interfaceRegistry||{},function(e){return e.toLowerCase()===t});if(!n)throw new Error("Unknown interface name: "+e);return n.value}var i={};i.functionRegistry={},i.typeRegistry={},i.objectRegistry={},i.interfaceInitialized=new dt("interfaceInitialized",i);var a=function(e){this.name=e,this.defaultInstance=null,this._implMap={}};return a.prototype.registerCtor=function(e,t){this._implMap[e.toLowerCase()]={ctor:t,defaultInstance:null}},a.prototype.getImpl=function(e){return this._implMap[e.toLowerCase()]},a.prototype.getFirstImpl=function(){var e=r(this._implMap,function(){return!0});return e?e.value:null},i.interfaceRegistry={ajax:new a("ajax"),modelLibrary:new a("modelLibrary"),dataService:new a("dataService"),uriBuilder:new a("uriBuilder")},i.interfaceRegistry.modelLibrary.getDefaultInstance=function(){if(!this.defaultInstance)throw new Error("Unable to locate the default implementation of the '"+this.name+"' interface.  Possible options are 'ko', 'backingStore' or 'backbone'. See the breeze.config.initializeAdapterInstances method.");return this.defaultInstance},i.setProperties=function(e){ft(e).whereParam("remoteAccessImplementation").isOptional().whereParam("trackingImplementation").isOptional().whereParam("ajaxImplementation").isOptional().applyAll(e),e.remoteAccessImplementation&&i.initializeAdapterInstance("dataService",e.remoteAccessImplementation),e.trackingImplementation&&i.initializeAdapterInstance("modelLibrary",e.trackingImplementation),e.ajaxImplementation&&i.initializeAdapterInstance("ajax",e.ajaxImplementation)},i.registerAdapter=function(e,n){lt(e,"interfaceName").isNonEmptyString().check(),lt(n,"adapterCtor").isFunction().check();var r=new n,i=r.name;if(!i)throw new Error("Unable to locate a 'name' property on the constructor passed into the 'registerAdapter' call.");var a=t(e);a.registerCtor(i,n)},i.getAdapter=function(e,n){var r=t(e);if(n){var i=r.getImpl(n);return i?i.ctor:null}return r.defaultInstance?r.defaultInstance._$impl.ctor:null},i.initializeAdapterInstances=function(e){return ft(e).whereParam("dataService").isOptional().whereParam("modelLibrary").isOptional().whereParam("ajax").isOptional().whereParam("uriBuilder").isOptional().applyAll(this,!1),n(e,i.initializeAdapterInstance)},i.initializeAdapterInstance=function(n,r,i){i=void 0===i?!0:i,lt(n,"interfaceName").isNonEmptyString().check(),lt(r,"adapterName").isNonEmptyString().check(),lt(i,"isDefault").isBoolean().check();var a=t(n),o=a.getImpl(r);if(!o)throw new Error("Unregistered adapter.  Interface: "+n+" AdapterName: "+r);return e(a,o,i)},i.getAdapterInstance=function(n,r){var i,a=t(n),o=null==r||""==r;if(o){if(a.defaultInstance)return a.defaultInstance;i=a.getFirstImpl()}else i=a.getImpl(r);return i?i.defaultInstance?i.defaultInstance:e(a,i,o):null},i.registerFunction=function(e,t){lt(e,"fn").isFunction().check(),lt(t,"fnName").isString().check(),e.prototype._$fnName=t,i.functionRegistry[t]=e},i.getRegisteredFunction=function(e){return i.functionRegistry[e]},i._storeObject=function(e,t,n){var r=("string"==typeof t?t:t.prototype._$typeName)+"."+n;i.objectRegistry[r]=e},i._fetchObject=function(e,t){if(!t)return void 0;var n=("string"==typeof e?e:e.prototype._$typeName)+"."+t,r=i.objectRegistry[n];if(!r)throw new Error("Unable to locate a registered object by the name: "+n);return r},i.registerType=function(e,t){lt(e,"ctor").isFunction().check(),lt(t,"typeName").isString().check(),e.prototype._$typeName=t,i.typeRegistry[t]=e},i.stringifyPad="",i}(),vt=mt.interfaceRegistry.modelLibrary;pt.config=mt,at.config=mt;var gt=function(){function e(e){var t=e.getEntityAspect();t.entityState.isUnchanged()&&t.setModified(),t.entityState.isModified()&&!e._origValues&&(e._origValues=e.slice(0))}function t(e,t){e._processAdds(t),r(e,"arrayChanged",{array:e,added:t})}function n(e,t){e._processRemoves(t),r(e,"arrayChanged",{array:e,removed:t})}function r(e,t,n){var r=e._getPendingPubs();r?e._pendingArgs?i(e._pendingArgs,n):(e._pendingArgs=n,r.push(function(){e[t].publish(e._pendingArgs),e._pendingArgs=null})):e[t].publish(n)}function i(e,t){for(var n in t)if("array"!==n&&e.hasOwnProperty(n)){var r=t[n],i=e[n];if(i){if(!Array.isArray(i))throw new Error("Cannot combine non array args");Array.prototype.push.apply(i,r)}else e[n]=r}}function a(e,t,n){e.parent=t,e.parentProperty=n}var o={};return o.push=function(){if(this._inProgress)return-1;var e=this._getGoodAdds(st(arguments));if(!e.length)return this.length;this._beforeChange();var n=Array.prototype.push.apply(this,e);return t(this,e),n},o._push=function(){if(this._inProgress)return-1;var e=st(arguments);this._beforeChange();var n=Array.prototype.push.apply(this,e);return t(this,e),n},o.unshift=function(){var e=this._getGoodAdds(st(arguments));if(!e.length)return this.length;this._beforeChange();var n=Array.prototype.unshift.apply(this,e);return t(this,st(e)),n},o.pop=function(){this._beforeChange();var e=Array.prototype.pop.apply(this);return n(this,[e]),e},o.shift=function(){this._beforeChange();var e=Array.prototype.shift.apply(this);return n(this,[e]),e},o.splice=function(){var e=this._getGoodAdds(st(arguments,2)),r=st(arguments,0,2).concat(e);this._beforeChange();var i=Array.prototype.splice.apply(this,r);return n(this,i),e.length&&t(this,e),i},o.getEntityAspect=function(){return this.parent.entityAspect||this.parent.complexAspect.getEntityAspect()},o._getEventParent=function(){return this.getEntityAspect()},o._getPendingPubs=function(){var e=this.getEntityAspect().entityManager;return e&&e._pendingPubs},o._beforeChange=function(){},{mixin:o,publish:r,updateEntityState:e,initializeParent:a}}(),Et=function(){function e(e,t,n,r,i){for(r=+e[t=e.length-1],i=0;t--;)n=+e[t],r+=++i%2?2*n%10+(n>4):n;return!(r%10)}function n(e,t,n,r){n&&(f.messageTemplates[e]=n);var i="string"==typeof t?new RegExp(t):t,a=function(e){return null==e||""===e?!0:"string"!=typeof e?!1:i.test(e)};return new f(e,a,r)}function r(e,t,n){return t?e.replace(/%([^%]+)%/g,function(e,r){var i;return i=n?t.hasOwnProperty(r)?t[r]:"":t[r],null!=i?V(i)?i(t):i:""}):e}function i(e,t,n,r){r=r||{},void 0!==t&&(r.min=t),void 0!==n&&(r.max=n);var i=r.messageTemplate||f.messageTemplates[e];return i||(f.messageTemplates[e]=G("'%displayName%' must be an integer between the values of %1 and %2",t,n)),function(){var i=function(e,r){return null==e?!0:("string"==typeof e&&r&&r.allowString&&(e=parseInt(e,0)),"number"!=typeof e||isNaN(e)||Math.floor(e)!==e?!1:null!=t&&t>e?!1:null!=n&&e>n?!1:!0)};return new f(e,i,r)}}var a=-32768,o=32767,s=-2147483648,u=2147483647,c=0,l=255,y={displayName:function(e){return e.property?e.property.resolveProperty("displayName")||e.propertyName||e.property.name:"Value"}},f=function(e,t,n){this._baseContext=n||{},this._baseContext.name=e,n=p(Object.create(y),this._baseContext),n.messageTemplate=n.messageTemplate||f.messageTemplates[e],this.name=e,this.valFn=t,this.context=n},h=f.prototype;return h._$typeName="Validator",h.validate=function(e,t){var n;n=t?p(Object.create(this.context),t):this.context,this.currentContext=n;try{return this.valFn(e,n)?null:(n.value=e,new wt(this,n,this.getMessage()))}catch(r){return new wt(this,n,"Exception occured while executing this validator: "+this.name)}},h.getMessage=function(){try{var e=this.currentContext,t=e.message;return t?"function"==typeof t?t(e):t:e.messageTemplate?r(e.messageTemplate,e):"invalid value: "+(this.name||"{unnamed validator}")}catch(n){return"Unable to format error message"+n.toString()}},h.toJSON=function(){return this._baseContext},f.fromJSON=function(e){if(Array.isArray(e))return e.map(function(e){return f.fromJSON(e)});var t="Validator."+e.name,n=mt.getRegisteredFunction(t);if(!n)throw new Error("Unable to locate a validator named:"+e.name);return n(e)},f.register=function(e){mt.registerFunction(function(){return e},"Validator."+e.name)},f.registerFactory=function(e,t){mt.registerFunction(e,"Validator."+t)},f.messageTemplates={bool:"'%displayName%' must be a 'true' or 'false' value",creditCard:"The %displayName% is not a valid credit card number",date:"'%displayName%' must be a date",duration:"'%displayName%' must be a ISO8601 duration string, such as 'P3H24M60S'",emailAddress:"The %displayName% '%value%' is not a valid email address",guid:"'%displayName%' must be a GUID",integer:"'%displayName%' must be an integer",integerRange:"'%displayName%' must be an integer between the values of %minValue% and %maxValue%",maxLength:"'%displayName%' must be a string with %maxLength% characters or less",number:"'%displayName%' must be a number",phone:"The %displayName% '%value%' is not a valid phone number",regularExpression:"The %displayName% '%value%' does not match '%expression%'",required:"'%displayName%' is required",string:"'%displayName%' must be a string",stringLength:"'%displayName%' must be a string with between %minLength% and %maxLength% characters",url:"The %displayName% '%value%' is not a valid url"},f.required=function(e){var t=function(e,t){return"string"==typeof e?t&&t.allowEmptyStrings?!0:e.length>0:null!=e};return new f("required",t,e)},f.maxLength=function(e){var t=function(e,t){return null==e?!0:"string"!=typeof e?!1:e.length<=t.maxLength};return new f("maxLength",t,e)},f.stringLength=function(e){var t=function(e,t){return null==e?!0:"string"!=typeof e?!1:null!=t.minLength&&e.length<t.minLength?!1:null!=t.maxLength&&e.length>t.maxLength?!1:!0};return new f("stringLength",t,e)},f.string=function(){var e=function(e){return null==e?!0:"string"==typeof e};return new f("string",e)},f.guid=function(){var e=function(e){return null==e?!0:j(e)};return new f("guid",e)},f.duration=function(){var e=function(e){return null==e?!0:B(e)};return new f("duration",e)},f.number=f.double=f.single=function(e){var t=function(e,t){return null==e?!0:("string"==typeof e&&t&&t.allowString&&(e=parseFloat(e,10)),"number"==typeof e&&!isNaN(e))};return new f("number",t,e)},f.integer=f.int64=function(e){var t=function(e,t){return null==e?!0:("string"==typeof e&&t&&t.allowString&&(e=parseInt(e,10)),"number"==typeof e&&!isNaN(e)&&Math.floor(e)===e)};return new f("integer",t,e)},f.int32=function(e){return i("int32",s,u,e)()},f.int16=function(e){return i("int16",a,o,e)()},f.byte=function(e){return i("byte",c,l,e)()},f.bool=function(){var e=function(e){return null==e?!0:e===!0||e===!1};return new f("bool",e)},f.none=function(){var e=function(){return!0};return new f("none",e)},f.date=function(){var e=function(e){if(null==e)return!0;if("string"!=typeof e)return k(e);try{return!isNaN(Date.parse(e))}catch(t){return!1}};return new f("date",e)},f.creditCard=function(t){function n(t){return null==t||""===t?!0:"string"!=typeof t?!1:(t=t.replace(/(\-|\s)/g,""),!t||/\D/.test(t)?!1:e(t))}return new f("creditCard",n,t)},f.regularExpression=function(e){function t(e,t){if(null==e||""===e)return!0;if("string"!=typeof e)return!1;try{var n=new RegExp(t.expression)}catch(r){throw new Error("Missing or invalid expression parameter to regExp validator")}return n.test(e)}return new f("regularExpression",t,e)},f.emailAddress=function(e){var t=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;return n("emailAddress",t,null,e)},f.phone=function(e){var t=/^((\+|(0(\d+)?[-/.\s]?))[1-9]\d{0,2}[-/.\s]?)?((\(\d{1,6}\)|\d{1,6})[-/.\s]?)?(\d+[-/.\s]?)+\d+$/;return n("phone",t,null,e)},f.url=function(e){var t=/^(https?|ftp):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|([a-zA-Z][\-a-zA-Z0-9]*)|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-fA-F]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/;
  return n("url",t,null,e)},f.makeRegExpValidator=n,t(f,function(e,t){"function"==typeof t&&"fromJSON"!==e&&"register"!==e&&"registerFactory"!==e&&"makeRegExpValidator"!==e&&mt.registerFunction(t,"Validator."+e)}),f}(),wt=function(){var e=function t(e,n,r,i){lt(e,"validator").isOptional().isInstanceOf(Et).check(),lt(r,"errorMessage").isNonEmptyString().check(),lt(i,"key").isOptional().isNonEmptyString().check(),this.validator=e,n=n||{},this.context=n,this.errorMessage=r,this.property=n.property,this.propertyName=n.propertyName||n.property&&n.property.name,this.key=i?i:t.getKey(e||r,this.propertyName),this.isServerError=!1};return e.getKey=function(e,t){return(e.name||e)+(t?":"+t:"")},e}();at.Validator=Et,at.ValidationError=wt;var St=function(){function e(e,t){return t&&ft(t).whereParam("validateOnAttach").isBoolean().isOptional().whereParam("validateOnSave").isBoolean().isOptional().whereParam("validateOnQuery").isBoolean().isOptional().whereParam("validateOnPropertyChange").isBoolean().isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="ValidationOptions",n.using=function(t){if(!t)return this;var n=new St(this);return e(n,t),n},n.setAsDefault=function(){return l(this,t)},t.defaultInstance=new t({validateOnAttach:!0,validateOnSave:!0,validateOnQuery:!1,validateOnPropertyChange:!0}),t}();at.ValidationOptions=St,at.makeComplexArray=function(){function e(e,t){return t.filter(function(t){return t.parent!==e.parent})}function t(e,t){t.forEach(function(t){if(null!=t.parent)throw new Error("The complexObject is already attached. Either clone it or remove it from its current owner");i(t,e)})}function n(e,t){t.forEach(function(t){r(t,e)})}function r(e,t){var n=e.complexAspect;return n.parent!==t.parent?null:(n.parent=null,n.parentProperty=null,n)}function i(e,t){var n=e.complexAspect;return n.parent===t.parent?null:(n.parent=t.parent,n.parentProperty=t.parentProperty,n)}function a(e,t,n){return gt.initializeParent(e,t,n),e.arrayChanged=new dt("arrayChanged",e),p(e,gt.mixin),p(e,o)}var o={};return o._getGoodAdds=function(t){return e(this,t)},o._beforeChange=function(){gt.updateEntityState(this)},o._processAdds=function(e){t(this,e)},o._processRemoves=function(e){n(this,e)},o._rejectChanges=function(){if(this._origValues){var e=this;this.forEach(function(t){r(t,e)}),this.length=0,this._origValues.forEach(function(t){e.push(t)})}},o._acceptChanges=function(){this._origValues=null},a}();var Pt=function(){var e={isAttach:function(){return!!this.isAttach},isDetach:function(){return!!this.isDetach},isModification:function(){return!!this.isModification}},t=new ht("EntityAction",e);return t.Attach=t.addSymbol({isAttach:!0}),t.AttachOnQuery=t.addSymbol({isAttach:!0}),t.AttachOnImport=t.addSymbol({isAttach:!0}),t.Detach=t.addSymbol({isDetach:!0}),t.MergeOnQuery=t.addSymbol({isModification:!0}),t.MergeOnImport=t.addSymbol({isModification:!0}),t.MergeOnSave=t.addSymbol({isModification:!0}),t.PropertyChange=t.addSymbol({isModification:!0}),t.EntityStateChange=t.addSymbol(),t.AcceptChanges=t.addSymbol(),t.RejectChanges=t.addSymbol({isModification:!0}),t.Clear=t.addSymbol({isDetach:!0}),t.resolveSymbols(),t}();at.EntityAction=Pt;var Tt=function(){function e(t){var n=t.entityAspect||t.complexAspect,r=t.entityType||t.complexType,i=n.originalValues;for(var a in i)t.setProperty(a,i[a]);r.complexProperties.forEach(function(n){var r=t.getProperty(n.name);n.isScalar?e(r):(r._rejectChanges(),r.forEach(e))})}function n(e){var t=e.entityAspect||e.complexAspect;t.originalValues={};var r=e.entityType||e.complexType;r.complexProperties.forEach(function(t){var r=e.getProperty(t.name);t.isScalar?n(r):(r._acceptChanges(),r.forEach(n))})}function r(e,t){var n=!0,i=e.entityType||e.complexType,a=e.entityAspect||e.complexAspect,s=e.entityAspect||e.complexAspect.getEntityAspect(),u={entity:s.entity};return void 0!==t&&(u.index=t),i.getProperties().forEach(function(t){var i=e.getProperty(t.name),o=t.getAllValidators();o.length>0&&(u.property=t,u.propertyName=a.getPropertyPath(t.name),n=s._validateProperty(i,u)&&n),t.isComplexProperty&&(n=t.isScalar?r(i)&&n:i.reduce(function(e,t,n){return r(t,n)&&e},n))}),i.getAllValidators().forEach(function(t){n=o(s,t,e)&&n}),n}function i(e,t){var n=t.isDeleted();n?a(e):b(e.entityAspect.entityManager,"isLoading",!0,function(){a(e)})}function a(e){e.entityType.navigationProperties.forEach(function(t){var n=t.inverse,r=e.getProperty(t.name);if(t.isScalar){if(r){if(n)if(n.isScalar)r.setProperty(n.name,null);else{var i=r.getProperty(n.name);i.length&&w(i,e)}e.setProperty(t.name,null)}}else n&&r.slice(0).forEach(function(e){n.isScalar&&e.setProperty(n.name,null)}),r.length=0})}function o(e,t,n,r){var i=t.validate(n,r);if(i)return e._addValidationError(i),!1;var a=wt.getKey(t,r?r.propertyName:null);return e._removeValidationError(a),!0}var s=function c(e){if(null===e){var t=c._nullInstance;if(t)return t;c._nullInstance=this}else{if(void 0===e)throw new Error("The EntityAspect ctor requires an entity as its only argument.");if(e.entityAspect)return e.entityAspect}if(!(this instanceof c))return new c(e);if(this.entity=e,this.entityGroup=null,this.entityManager=null,this.entityState=bt.Detached,this.isBeingSaved=!1,this.originalValues={},this.hasValidationErrors=!1,this._validationErrors={},this.validationErrorsChanged=new dt("validationErrorsChanged",this),this.propertyChanged=new dt("propertyChanged",this),null!=e){e.entityAspect=this;var n=e.entityType||e._$entityType;if(!n){var r=e.prototype._$typeName;throw new Error(r?"Metadata for this entityType has not yet been resolved: "+r:"This entity is not registered as a valid EntityType")}var i=n.getEntityCtor();vt.getDefaultInstance().startTracking(e,i.prototype)}},p=s.prototype;return dt.bubbleEvent(p,function(){return this.entityManager}),p.getKey=function(e){if(e=lt(e,"forceRefresh").isBoolean().isOptional().check(!1),e||!this._entityKey){var t=this.entity.entityType,n=t.keyProperties,r=n.map(function(e){return this.entity.getProperty(e.name)},this);this._entityKey=new _t(t,r)}return this._entityKey},p.acceptChanges=function(){this._checkOperation("acceptChanges");var e=this.entityManager;this.entityState.isDeleted()?e.detachEntity(this.entity):this.setUnchanged(),e.entityChanged.publish({entityAction:Pt.AcceptChanges,entity:this.entity})},p.rejectChanges=function(){this._checkOperation("rejectChanges");var t=this.entity,n=this.entityManager;b(n,"isRejectingChanges",!0,function(){e(t)}),this.entityState.isAdded()?(n.detachEntity(t),n._notifyStateChange(t,!1)):(this.entityState.isDeleted()&&this.entityManager._linkRelatedEntities(t),this.setUnchanged(),this.propertyChanged.publish({entity:t,propertyName:null}),this.entityManager.entityChanged.publish({entityAction:Pt.RejectChanges,entity:t}))},p.getPropertyPath=function(e){return e},p.setAdded=function(){return this.setEntityState(bt.Added)},p.setUnchanged=function(){return this.setEntityState(bt.Unchanged)},p.setModified=function(){return this.setEntityState(bt.Modified)},p.setDeleted=function(){return this.setEntityState(bt.Deleted)},p.setDetached=function(){return this.setEntityState(bt.Detached)},p.setEntityState=function(e){if(this.entityState===e)return!1;if(this._checkOperation("setEntityState"),this.entityState.isDetached())throw new Error("You cannot set the 'entityState' of an entity when it is detached - except by first attaching it to an EntityManager");var t=this.entity,r=this.entityManager,a=!0;if(e===bt.Unchanged)n(t),delete this.hasTempKey,a=!1;else if(e===bt.Added)n(t);else if(e===bt.Deleted){if(this.entityState.isAdded())return this.setEntityState(bt.Detached),!0;this.entityState=bt.Deleted,i(t,bt.Deleted)}else if(e===bt.Modified);else if(e===bt.Detached){var o=this.entityGroup;if(!o)return!1;o.detachEntity(t),this.entityState=e,i(t,bt.Detached),this._detach(),r.entityChanged.publish({entityAction:Pt.Detach,entity:t}),a=!1}return this.entityState=e,r._notifyStateChange(t,a),!0},p.loadNavigationProperty=function(e,t,n){var r=this.entity,i=r.entityType._checkNavProperty(e),a=qt.fromEntityNavigation(r,i),o=r.entityAspect.entityManager.executeQuery(a),s=this;return o.then(function(e){return s._markAsLoaded(i.name),t&&t(e),xt.resolve(e)},function(e){return n&&n(e),xt.reject(e)})},p.markNavigationPropertyAsLoaded=function(e){var t=this.entity.entityType._checkNavProperty(e);this._markAsLoaded(t.name)},p.isNavigationPropertyLoaded=function(e){var t=this.entity.entityType._checkNavProperty(e);return t.isScalar&&null!=this.entity.getProperty(t.name)?!0:this._loadedNps&&this._loadedNps.indexOf(t.name)>=0},p._markAsLoaded=function(e){this._loadedNps=this._loadedNps||[],E(this._loadedNps,e)},p.validateEntity=function(){var e=!0;return this._processValidationOpAndPublish(function(t){e=r(t.entity)}),e},p.validateProperty=function(e,t){var n=this.getPropertyValue(e);return n&&n.complexAspect?r(n):(t=t||{},t.entity=this.entity,"string"==typeof e?(t.property=this.entity.entityType.getProperty(e,!0),t.propertyName=e):(t.property=e,t.propertyName=e.name),this._validateProperty(n,t))},p.getValidationErrors=function(e){lt(e,"property").isOptional().isEntityProperty().or().isString().check();var t=u(this._validationErrors);if(e){var n="string"==typeof e?e:e.name;t=t.filter(function(e){return e.property&&(e.property.name===n||-1!=n.indexOf(".")&&e.propertyName==n)})}return t},p.addValidationError=function(e){lt(e,"validationError").isInstanceOf(wt).check(),this._processValidationOpAndPublish(function(t){t._addValidationError(e)})},p.removeValidationError=function(e){lt(e,"validationErrorOrKey").isString().or().isInstanceOf(wt).or().isInstanceOf(Et).check();var t="string"==typeof e?e:e.key;this._processValidationOpAndPublish(function(e){e._removeValidationError(t)})},p.clearValidationErrors=function(){this._processValidationOpAndPublish(function(e){t(e._validationErrors,function(t,n){n&&(delete e._validationErrors[t],e._pendingValidationResult.removed.push(n))}),e.hasValidationErrors=!L(e._validationErrors)})},p.getParentKey=function(e){var t=e.foreignKeyNames;if(0===t.length)return null;var n=this,r=t.map(function(e){return n.entity.getProperty(e)});return new _t(e.entityType,r)},p.getPropertyValue=function(e){lt(e,"property").isString().or().isEntityProperty().check();var t;if("string"==typeof e){var n=e.trim().split("."),r=n.shift();for(t=this.entity,t=t.getProperty(r);n.length>0;)r=n.shift(),t=t.getProperty(r)}else{if(!(e.parentType instanceof Dt))throw new Error("The validateProperty method does not accept a 'property' parameter whose parentType is a ComplexType; Pass a 'property path' string as the 'property' parameter instead ");t=this.entity.getProperty(e.name)}return t},p._checkOperation=function(e){if(this.isBeingSaved)throw new Error("Cannot perform a '"+e+"' on an entity that is in the process of being saved");return this},p._detach=function(){this.entityGroup=null,this.entityManager=null,this.entityState=bt.Detached,this.originalValues={},this._validationErrors={},this.hasValidationErrors=!1,this.validationErrorsChanged.clear(),this.propertyChanged.clear()},p._validateProperty=function(e,t){var n=!0;return this._processValidationOpAndPublish(function(r){t.property.getAllValidators().forEach(function(i){n=o(r,i,e,t)&&n})}),n},p._processValidationOpAndPublish=function(e){if(this._pendingValidationResult)e(this);else try{this._pendingValidationResult={entity:this.entity,added:[],removed:[]},e(this),(this._pendingValidationResult.added.length>0||this._pendingValidationResult.removed.length>0)&&(this.validationErrorsChanged.publish(this._pendingValidationResult),this.entityManager&&this.entityManager.validationErrorsChanged.publish(this._pendingValidationResult))}finally{this._pendingValidationResult=void 0}},p._addValidationError=function(e){this._validationErrors[e.key]=e,this.hasValidationErrors=!0,this._pendingValidationResult.added.push(e)},p._removeValidationError=function(e){var t=this._validationErrors[e];t&&(delete this._validationErrors[e],this.hasValidationErrors=!L(this._validationErrors),this._pendingValidationResult.removed.push(t))},s}(),Nt=function(){var e=function n(e,t,r){if(!e)throw new Error("The  ComplexAspect ctor requires an entity as its only argument.");if(e.complexAspect)return e.complexAspect;if(!(this instanceof n))return new n(e,t,r);this.complexObject=e,e.complexAspect=this,this.originalValues={},null!=t&&(this.parent=t,this.parentProperty=r);var i=e.complexType;if(!i){var a=e.prototype._$typeName;throw new Error(a?"Metadata for this complexType has not yet been resolved: "+a:"This entity is not registered as a valid ComplexType")}var o=i.getCtor();vt.getDefaultInstance().startTracking(e,o.prototype)},t=e.prototype;return t.getEntityAspect=function(){var e=this.parent;if(!e)return new Tt(null);for(var t=e.entityAspect;e&&!t;)e=e.complexAspect&&e.complexAspect.parent,t=e&&e.entityAspect;return t||new Tt(null)},t.getPropertyPath=function(e){var t=this.parent;if(!t)return null;var n=t.complexAspect||t.entityAspect;return n.getPropertyPath(this.parentProperty.name+"."+e)},e}();at.EntityAspect=Tt,at.ComplexAspect=Nt;var _t=function(){function e(e){return e.join(t)}var t=":::",n=function(t,n){lt(t,"entityType").isInstanceOf(Dt).check();var r=t.getSelfAndSubtypes();r.length>1&&(this._subtypes=r.filter(function(e){return e.isAbstract===!1})),Array.isArray(n)||(n=st(arguments,1)),this.entityType=t,t.keyProperties.forEach(function(e,t){e.dataType===Ot.Guid&&(n[t]=n[t]&&n[t].toLowerCase())}),this.values=n,this._keyInGroup=e(n)};n._$typeName="EntityKey";var r=n.prototype;return r.toJSON=function(){return{entityType:this.entityType.name,values:this.values}},n.fromJSON=function(e,t){var n=t._getEntityType(e.entityType,!0);return new _t(n,e.values)},r.equals=function(e){return e instanceof _t?this.entityType===e.entityType&&P(this.values,e.values):!1},r.toString=function(e){return(e||this.entityType).name+"-"+this._keyInGroup},n.equals=function(e,t){return e instanceof _t?e.equals(t):!1},r._isEmpty=function(){return 0===this.values.join("").length},n.createKeyString=e,n}();at.EntityKey=_t;var bt=function(){var e={isUnchanged:function(){return this===t.Unchanged},isAdded:function(){return this===t.Added},isModified:function(){return this===t.Modified},isDeleted:function(){return this===t.Deleted},isDetached:function(){return this===t.Detached},isUnchangedOrModified:function(){return this===t.Unchanged||this===t.Modified},isAddedModifiedOrDeleted:function(){return this===t.Added||this===t.Modified||this===t.Deleted}},t=new ht("EntityState",e);return t.Unchanged=t.addSymbol(),t.Added=t.addSymbol(),t.Modified=t.addSymbol(),t.Deleted=t.addSymbol(),t.Detached=t.addSymbol(),t.resolveSymbols(),t}();at.EntityState=bt,at.makePrimitiveArray=function(){function e(e,n,r){return gt.initializeParent(e,n,r),e.arrayChanged=new dt("arrayChanged",e),p(e,gt.mixin),p(e,t)}var t={};return t._getGoodAdds=function(e){return e},t._beforeChange=function(){var e=this.getEntityAspect();e.entityState.isUnchanged()&&e.setModified(),e.entityState.isModified()&&!this._origValues&&(this._origValues=this.slice(0))},t._processAdds=function(){},t._processRemoves=function(){},t._rejectChanges=function(){this._origValues&&(this.length=0,Array.prototype.push.apply(this,this._origValues))},t._acceptChanges=function(){this._origValues=null},e}(),at.makeRelationArray=function(){function e(e,t){var n=r(e,t);if(!n.length)return n;var i=e.parentEntity,a=i.entityAspect.entityManager;return a&&!a.isLoading&&n.forEach(function(t){if(t.entityAspect.entityState.isDetached()){e._inProgress=!0;try{a.attachEntity(t,bt.Added)}finally{e._inProgress=!1}}}),n}function t(e,t){var n=e.parentEntity,r=e.navigationProperty,i=e._addsInProcess,a=r.inverse,o=i.length;try{t.forEach(function(e){if(i.push(e),a)e.setProperty(a.name,n);else{var t=n.entityType.keyProperties;r.invForeignKeyNames.forEach(function(r,i){e.setProperty(r,n.getProperty(t[i].name))})}})}finally{i.splice(o,t.length)}}function n(e,t){var n=e.navigationProperty.inverse;n&&t.forEach(function(e){e.setProperty(n.name,null)})}function r(e,t){var n,r=e.parentEntity,i=e.navigationProperty,a=i.inverse;if(a)n=t.filter(function(t){if(e._addsInProcess.indexOf(t)>=0)return!1;var n=t.getProperty(a.name);return n!==r});else{var o=i.invForeignKeyNames,s=r.entityType.keyProperties;n=t.filter(function(t){return e._addsInProcess.indexOf(t)>=0?!1:o.some(function(e,n){var i=s[n].name,a=r.getProperty(i),o=t.getProperty(e);return a!==o})})}return n}function i(e,t,n){return e.parentEntity=t,e.navigationProperty=n,e.arrayChanged=new dt("arrayChanged",e),e._addsInProcess=[],p(e,gt.mixin),p(e,a)}var a={};return a.load=function(e,t){var n=this.parentEntity,r=qt.fromEntityNavigation(this.parentEntity,this.navigationProperty),i=n.entityAspect.entityManager;return i.executeQuery(r,e,t)},a._getEventParent=function(){return this.parentEntity.entityAspect},a._getPendingPubs=function(){var e=this.parentEntity.entityAspect.entityManager;return e&&e._pendingPubs},a._getGoodAdds=function(t){return e(this,t)},a._processAdds=function(e){t(this,e)},a._processRemoves=function(e){n(this,e)},i}();var Ot=function(){function e(e,t){throw e=G(e,t),new Error(e)}function t(e){switch(e){case _.String:return Et.string;case _.Int64:return Et.int64;case _.Int32:return Et.int32;case _.Int16:return Et.int16;case _.Decimal:return Et.number;case _.Double:return Et.number;case _.Single:return Et.number;case _.DateTime:return Et.date;case _.DateTimeOffset:return Et.date;case _.Boolean:return Et.bool;case _.Guid:return Et.guid;case _.Byte:return Et.byte;case _.Binary:return Et.none;case _.Time:return Et.duration;case _.Undefined:return Et.none}}var n,r={},i=function(){n={stringPrefix:"K_",nextNumber:-1,nextNumberIncrement:-1}};i();var a=function(){return n.stringPrefix+o().toString()},o=function(){var e=n.nextNumber;return n.nextNumber+=n.nextNumberIncrement,e},s=function(){return C()},u=function(){return new Date},p=function(e){return null==e?e:e.toString()},c=function(e,t){return"string"===t?e.trim().toLowerCase():e},l=function(e,t){if("string"===t){var n=e.trim();if(""===n)return null;var r=parseInt(n,10);return isNaN(r)?e:r}return"number"===t?Math.round(e):e},y=function(e,t){if("string"===t){var n=e.trim();if(""===n)return null;var r=parseFloat(n);return isNaN(r)?e:r}return e},f=function(e,t){var n;if("string"===t){var r=e.trim();return""===r?null:(n=new Date(Date.parse(r)),k(n)?n:e)}return"number"===t?(n=new Date(e),k(n)?n:e):e},h=function(e,t){if("string"===t){var n=e.trim().toLowerCase();return"false"===n||""===n?!1:"true"===n?!0:e}return e},d=function(e){return null==e?null:"'"+e.replace(/'/g,"''")+"'"},m=function(e){return null==e?null:"string"==typeof e?parseInt(e,10):e},v=function(e){return function(t){return null==t?null:("string"==typeof t&&(t=parseFloat(t)),t+e)}},g=function(t){if(null==t)return null;try{return"datetime'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},E=function(t){if(null==t)return null;try{return"datetimeoffset'"+t.toISOString()+"'"}catch(n){e("'%1' is not a valid dateTime",t)}},w=function(t){return null==t?null:(B(t)||e("'%1' is not a valid ISO 8601 duration",t),"time'"+t+"'")},S=function(t){return null==t?null:(j(t)||e("'%1' is not a valid guid",t),"guid'"+t+"'")},P=function(e){return null==e?null:"string"==typeof e?"true"===e.trim().toLowerCase():!!e},T=function(e){return null==e?e:"binary'"+e+"'"},N=function(e){return e},_=new ht("DataType",r);_.String=_.addSymbol({defaultValue:"",parse:p,fmtOData:d,getNext:a}),_.Int64=_.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,quoteJsonOData:!0,parse:l,fmtOData:v("L"),getNext:o}),_.Int32=_.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:l,fmtOData:m,getNext:o}),_.Int16=_.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:l,fmtOData:m,getNext:o}),_.Byte=_.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:l,fmtOData:m}),_.Decimal=_.addSymbol({defaultValue:0,isNumeric:!0,quoteJsonOData:!0,isFloat:!0,parse:y,fmtOData:v("m"),getNext:o}),_.Double=_.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:y,fmtOData:v("d"),getNext:o}),_.Single=_.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:y,fmtOData:v("f"),getNext:o}),_.DateTime=_.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:f,fmtOData:g,getNext:u}),_.DateTimeOffset=_.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:f,fmtOData:E,getNext:u}),_.Time=_.addSymbol({defaultValue:"PT0S",fmtOData:w}),_.Boolean=_.addSymbol({defaultValue:!1,parse:h,fmtOData:P}),_.Guid=_.addSymbol({defaultValue:"00000000-0000-0000-0000-000000000000",parse:c,fmtOData:S,getNext:s}),_.Binary=_.addSymbol({defaultValue:null,fmtOData:T}),_.Undefined=_.addSymbol({defaultValue:void 0,fmtOData:N}),_.resolveSymbols(),_.getComparableFn=function(e){return e&&e.isDate?function(e){return e&&e.getTime()}:e===_.Time?function(e){return e&&x(e)}:function(e){return e}},_.fromEdmDataType=function(e){var t=null,n=e.split(".");if(n.length>1){var r=n[1];t="image"===r?_.Byte:2===n.length?_.fromName(r)||_.Undefined:_.String}return t},_.fromValue=function(e){if(k(e))return _.DateTime;switch(typeof e){case"string":return j(e)?_.Guid:B(e)&&e.length>3?_.Time:I(e)?_.DateTime:_.String;case"boolean":return _.Boolean;case"number":return _.Double}return _.Undefined};var b=/.\d{3}$/;return _.parseTimeFromServer=function(e){if("string"==typeof e)return e;if(e&&"Edm.Time"===e.__edmType){var t=Math.floor(e.ms/1e3);return"PT"+t+"S"}return e},_.parseDateAsUTC=function(e){if("string"==typeof e){var t=b.test(e);e=t?e+"Z":e}return e=new Date(Date.parse(e))},_.parseDateFromServer=_.parseDateAsUTC,_.parseRawValue=function(e,t){return void 0===e?void 0:(t.isDate&&e?k(e)||(e=_.parseDateFromServer(e)):t===_.Binary?e&&void 0!==e.$value&&(e=e.$value):t===_.Time?e=_.parseTimeFromServer(e):e&&t===_.Guid&&(e=e.toLowerCase()),e)},_.constants=n,_._resetConstants=i,_.getSymbols().forEach(function(e){e.validatorCtor=t(e)}),_}();at.DataType=Ot;var At=function(){function e(e,t){return t&&(ft(t).whereParam("serviceName").isOptional().whereParam("adapterName").isString().isOptional().whereParam("uriBuilderName").isString().isOptional().whereParam("hasServerMetadata").isBoolean().isOptional().whereParam("jsonResultsAdapter").isInstanceOf(Ct).isOptional().whereParam("useJsonp").isBoolean().isOptional().applyAll(e),e.serviceName=e.serviceName&&At._normalizeServiceName(e.serviceName),e.adapterInstance=e.adapterName&&mt.getAdapterInstance("dataService",e.adapterName),e.uriBuilder=e.uriBuilderName&&mt.getAdapterInstance("uriBuilder",e.uriBuilderName)),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="DataService",n.using=function(t){if(!t)return this;var n=new At(this);return e(n,t)},t.resolve=function(e){e.push({hasServerMetadata:!0,useJsonp:!1});var t=new At(h(e,["serviceName","adapterName","uriBuilderName","hasServerMetadata","jsonResultsAdapter","useJsonp"]));if(!t.serviceName)throw new Error("Unable to resolve a 'serviceName' for this dataService");return t.adapterInstance=t.adapterInstance||mt.getAdapterInstance("dataService",t.adapterName),t.jsonResultsAdapter=t.jsonResultsAdapter||t.adapterInstance.jsonResultsAdapter,t.uriBuilder=t.uriBuilder||mt.getAdapterInstance("uriBuilder",t.uriBuilderName),t},t._normalizeServiceName=function(e){return e=e.trim(),"/"!==e.substr(-1)?e+"/":e},n.toJSON=function(){return y(this,{serviceName:null,adapterName:null,uriBuilderName:null,hasServerMetadata:null,jsonResultsAdapter:function(e){return e&&e.name},useJsonp:null})},t.fromJSON=function(e){return e.jsonResultsAdapter=mt._fetchObject(Ct,e.jsonResultsAdapter),new At(e)},n.qualifyUrl=function(e){var t=this.serviceName;return pt.stringEndsWith(t,"/")&&(t=t.substr(0,t.length-1)),e="/"+e,pt.stringEndsWith(t,e)||(t+=e),t},t}(),Ct=function(){function e(e){return e.results}var t=function(t){if(1!==arguments.length)throw new Error("The JsonResultsAdapter ctor should be called with a single argument that is a configuration object.");ft(t).whereParam("name").isNonEmptyString().whereParam("extractResults").isFunction().isOptional().withDefault(e).whereParam("visitNode").isFunction().applyAll(this),mt._storeObject(this,n._$typeName,this.name)},n=t.prototype;return n._$typeName="JsonResultsAdapter",t}();at.DataService=At,at.JsonResultsAdapter=Ct;var xt=_("Q");xt||(xt=function(){var e="Q is undefined. Are you missing Q.js? See https://github.com/kriskowal/q";throw new Error(e)},xt.defer=xt.resolve=xt.reject=xt),at.config.setQ=function(e){at.Q=xt=e},at.Q=xt;var Ft=function(){function e(e){var t=[];for(var n in e){var r=e[n];n===r.name&&t.push(e[n])}return t}function t(e,t,n){var i=nt(t.shortName,t.namespace),o=e._getEntityType(i,!0);if(o)return n?r(o,t):o;var s={shortName:t.shortName,namespace:t.namespace,isAbstract:t.isAbstract,autoGeneratedKeyType:Rt.fromName(t.autoGeneratedKeyType),defaultResourceName:t.defaultResourceName,custom:t.custom};if(o=t.isComplexType?new kt(s):new Dt(s),t.baseTypeName){o.baseTypeName=t.baseTypeName;var u=e._getEntityType(t.baseTypeName,!0);u?a(e,t,o,u):T(e._deferredTypes,t.baseTypeName).push({json:t,stype:o})}else a(e,t,o);return o}function r(e,t){return t.custom&&(e.custom=t.custom),i(e,t.dataProperties),i(e,t.navigationProperties),e}function i(e,t){t&&t.forEach(function(t){var n=t.name;if(!n){if(!t.nameOnServer)throw new Error("Unable to complete 'importMetadata' - cannot locate a 'name' or 'nameOnServer' for one of the imported property nodes");n=e.metadataStore.namingConvention.serverPropertyNameToClient(t.nameOnServer,{})}if(t.custom){var r=e.getProperty(n,!0);r.custom=t.custom}})}function a(e,t,n){t.validators&&(n.validators=t.validators.map(Et.fromJSON)),t.dataProperties.forEach(function(e){n._addPropertyCore(It.fromJSON(e))});var r=!t.isComplexType;r&&t.navigationProperties&&t.navigationProperties.forEach(function(e){n._addPropertyCore(Vt.fromJSON(e))}),e.addEntityType(n);var i=e._deferredTypes,o=i[n.name];o&&(o.forEach(function(t){a(e,t.json,t.stype)}),delete i[n.name])}function o(e,t,n){if(tt(t))return t;var r=e._shortNameMap[t];if(!r&&n)throw new Error("Unable to locate 'entityTypeName' of: "+t);return r}var s=0,u=function(e){e=e||{},ft(e).whereParam("namingConvention").isOptional().isInstanceOf(Bt).withDefault(Bt.defaultInstance).whereParam("localQueryComparisonOptions").isOptional().isInstanceOf(jt).withDefault(jt.defaultInstance).whereParam("serializerFn").isOptional().isFunction().applyAll(this),this.dataServices=[],this._resourceEntityTypeMap={},this._structuralTypeMap={},this._shortNameMap={},this._ctorRegistry={},this._incompleteTypeMap={},this._incompleteComplexTypeMap={},this._id=s++,this.metadataFetched=new dt("metadataFetched",this)},c=u.prototype;return c._$typeName="MetadataStore",dt.bubbleEvent(c,null),u.ANONTYPE_PREFIX="_IB_",u.normalizeTypeName=A(function(e){return e&&X(e).typeName}),c.setProperties=function(e){ft(e).whereParam("name").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().applyAll(this)},c.addDataService=function(e,t){lt(e,"dataService").isInstanceOf(At).check(),lt(t,"shouldOverwrite").isBoolean().isOptional().check();var n=this._getDataServiceIndex(e.serviceName);if(n>=0){if(!t)throw new Error("A dataService with this name '"+e.serviceName+"' already exists in this MetadataStore");this.dataServices[n]=e}else this.dataServices.push(e)},c._getDataServiceIndex=function(e){return g(this.dataServices,function(t){return t.serviceName===e})},c.addEntityType=function(e){if(e instanceof Dt||e instanceof kt||(e=e.isComplexType?new kt(e):new Dt(e)),!e.isComplexType){if(e.baseTypeName&&!e.baseEntityType){var t=this._getEntityType(e.baseTypeName,!0);e._updateFromBase(t)}if(0===e.keyProperties.length&&!e.isAbstract)throw new Error("Unable to add "+e.name+" to this MetadataStore.  An EntityType must have at least one property designated as a key property - See the 'DataProperty.isPartOfKey' property.")}if(e.metadataStore=this,!e.isAnonymous){if(this._structuralTypeMap[e.name])throw new Error("Type "+e.name+" already exists in this MetadataStore.");this._structuralTypeMap[e.name]=e,this._shortNameMap[e.shortName]=e.name}if(e.getProperties().forEach(function(t){e._updateNames(t),t.isUnmapped||e._mappedPropertiesCount++}),e._updateCps(),!e.isComplexType){e._updateNps();var n=e.defaultResourceName||e.baseEntityType&&e.baseEntityType.defaultResourceName;n&&!this.getEntityTypeNameForResourceName(n)&&this.setEntityTypeForResourceName(n,e.name),e.defaultResourceName=n,e.getEntityCtor()}},c.exportMetadata=function(){var e=JSON.stringify({metadataVersion:at.metadataVersion,name:this.name,namingConvention:this.namingConvention.name,localQueryComparisonOptions:this.localQueryComparisonOptions.name,dataServices:this.dataServices,structuralTypes:n(this._structuralTypeMap),resourceEntityTypeMap:this._resourceEntityTypeMap},null,mt.stringifyPad);return e},c.importMetadata=function(e,n){lt(n,"allowMerge").isOptional().isBoolean().check(),this._deferredTypes={};var r="string"==typeof e?JSON.parse(e):e;if(r.schema)return Mt.parse(this,r.schema,r.altMetadata);if(r.metadataVersion&&r.metadataVersion!==at.metadataVersion){var i=G("Cannot import metadata with a different 'metadataVersion' (%1) than the current 'breeze.metadataVersion' (%2) ",r.metadataVersion,at.metadataVersion);throw new Error(i)}var a=r.namingConvention,o=r.localQueryComparisonOptions;if(this.isEmpty())this.namingConvention=mt._fetchObject(Bt,a)||this.namingConvention,this.localQueryComparisonOptions=mt._fetchObject(jt,o)||this.localQueryComparisonOptions;else{if(a&&this.namingConvention.name!==a)throw new Error("Cannot import metadata with a different 'namingConvention' from the current MetadataStore");if(o&&this.localQueryComparisonOptions.name!==o)throw new Error("Cannot import metadata with different 'localQueryComparisonOptions' from the current MetadataStore")}var s=this;r.dataServices&&r.dataServices.forEach(function(e){e=At.fromJSON(e),s.addDataService(e,!0)});this._structuralTypeMap;return r.structuralTypes&&r.structuralTypes.forEach(function(e){t(s,e,n)}),p(this._resourceEntityTypeMap,r.resourceEntityTypeMap),p(this._incompleteTypeMap,r.incompleteTypeMap),this},u.importMetadata=function(e){var t=new Ft;return t.importMetadata(e),t},c.hasMetadataFor=function(e){return!!this.getDataService(e)},c.getDataService=function(e){return lt(e,"serviceName").isString().check(),e=At._normalizeServiceName(e),v(this.dataServices,function(t){return t.serviceName===e})},c.fetchMetadata=function(e,t,n){try{if(lt(e,"dataService").isString().or().isInstanceOf(At).check(),lt(t,"callback").isFunction().isOptional().check(),lt(n,"errorCallback").isFunction().isOptional().check(),"string"==typeof e&&(e=this.getDataService(e)||new At({serviceName:e})),e=At.resolve([e]),this.hasMetadataFor(e.serviceName))throw new Error("Metadata for a specific serviceName may only be fetched once per MetadataStore. ServiceName: "+e.serviceName);var r=this;return e.adapterInstance.fetchMetadata(this,e).then(function(n){return r.metadataFetched.publish({metadataStore:r,dataService:e,rawMetadata:n}),t&&t(n),xt.resolve(n)},function(e){return n&&n(e),xt.reject(e)})}catch(i){return xt.reject(i)}},c.trackUnmappedType=function(e,t){lt(e,"entityCtor").isFunction().check(),lt(t,"interceptor").isFunction().isOptional().check();var n=new Dt(this);n._setCtor(e,t)},c.registerEntityTypeCtor=function(e,t,n,r){lt(e,"structuralTypeName").isString().check(),lt(t,"aCtor").isFunction().isOptional().check(),lt(n,"initFn").isOptional().isFunction().or().isString().check(),lt(r,"noTrackingFn").isOptional().isFunction().check();var i=o(this,e,!1),a=i||e;if(this._ctorRegistry[a]={ctor:t,initFn:n,noTrackingFn:r},i){var s=this._structuralTypeMap[i];s&&s.getCtor(!0)}},c.isEmpty=function(){return L(this._structuralTypeMap)},c.getEntityType=function(e,t){return lt(e,"structuralTypeName").isString().check(),lt(t,"okIfNotFound").isBoolean().isOptional().check(!1),this._getEntityType(e,t)},c._getEntityType=function(e,t){var n=o(this,e,!1),r=this._structuralTypeMap[n];
  if(!r){if(t)return null;var i=G("Unable to locate a 'Type' by the name: '%1'. Be sure to execute a query or call fetchMetadata first.",e);throw new Error(i)}if(r.length){var a=r.join(",");throw new Error("There are multiple types with this 'shortName': "+a)}return r},c.getEntityTypes=function(){return e(this._structuralTypeMap)},c.getIncompleteNavigationProperties=function(){return n(this._incompleteTypeMap,function(e,t){return t})},c.getEntityTypeNameForResourceName=function(e){return lt(e,"resourceName").isString().check(),this._resourceEntityTypeMap[e]},c.setEntityTypeForResourceName=function(e,t){lt(e,"resourceName").isString().check(),lt(t,"entityTypeOrName").isInstanceOf(Dt).or().isString().check();var n;n=t instanceof Dt?t.name:o(this,t,!0),this._resourceEntityTypeMap[e]=n;var r=this._getEntityType(n,!0);r&&!r.defaultResourceName&&(r.defaultResourceName=e)},c._checkEntityType=function(e){if(!e.entityType){var t=e.prototype._$typeName;if(!t)throw new Error("This entity has not been registered. See the MetadataStore.registerEntityTypeCtor method");var n=this._getEntityType(t);n&&(e.entityType=n)}},u}(),Mt=function(){function e(e,n,i){e._entityTypeResourceMap={},d(n).forEach(function(n){if(n.cSpaceOSpaceMapping){var i=JSON.parse(n.cSpaceOSpaceMapping),a={};i.forEach(function(e){a[e[0]]=e[1]}),n.cSpaceOSpaceMapping=a}n.entityContainer&&d(n.entityContainer).forEach(function(t){d(t.entitySet).forEach(function(t){var r=m(t.entityType,n).typeName;e.setEntityTypeForResourceName(t.name,r),e._entityTypeResourceMap[r]=t.name})}),n.complexType&&d(n.complexType).forEach(function(t){r(t,n,e)}),n.entityType&&d(n.entityType).forEach(function(r){t(r,n,e)})});var a=e.getIncompleteNavigationProperties();if(a.length>0){var o=a.map(function(e){return e.parentType.name+":"+e.name}).join(", ");throw new Error("Incomplete navigation properties: "+o)}return i&&e.importMetadata(i,!0),e}function t(e,t,r){var i=e.name,a=g(i,t),o=new Dt({shortName:i,namespace:a,isAbstract:e.abstract&&"true"===e.abstract});if(e.baseType){var s=m(e.baseType,t).typeName;o.baseTypeName=s;var u=r._getEntityType(s,!0);if(u)n(o,e,t,r);else{var p=r._deferredTypes[s];p||(p=[],r._deferredTypes[s]=p),p.push({entityType:o,csdlEntityType:e})}}else n(o,e,t,r);return o}function n(e,t,r,a){var o=t.key?d(t.key.propertyRef).map(s("name")):[];d(t.property).forEach(function(t){i(e,t,r,o)}),d(t.navigationProperty).forEach(function(t){u(e,t,r)}),a.addEntityType(e),e.defaultResourceName=a._entityTypeResourceMap[e.name];var p=a._deferredTypes,c=p[e.name];c&&(c.forEach(function(e){n(e.entityType,e.csdlEntityType,r,a)}),delete p[e.name])}function r(e,t,n){var r=e.name,a=g(r,t),o=new kt({shortName:r,namespace:a});return d(e.property).forEach(function(e){i(o,e,t)}),n.addEntityType(o),o}function i(e,t,n,r){var i,s=t.type.split(".");return"Edm"===s[0]&&2===s.length?i=a(e,t,r):p(t,n)?(i=a(e,t,r),i&&(i.enumType=t.type)):i=o(e,t,n),i&&(e._addPropertyCore(i),y(i)),i}function a(e,t,n){var r=Ot.fromEdmDataType(t.type);if(null==r)return e.warnings.push("Unable to recognize DataType for property: "+t.name+" DateType: "+t.type),null;var i="true"===t.nullable||null==t.nullable,a=null!=n&&n.indexOf(t.name)>=0;a&&e.autoGeneratedKeyType===Rt.None&&f(t)&&(e.autoGeneratedKeyType=Rt.Identity);var o=t.maxLength;o=null==o||"Max"===o?null:parseInt(o,10);var s=new It({nameOnServer:t.name,dataType:r,isNullable:i,isPartOfKey:a,maxLength:o,defaultValue:t.defaultValue,concurrencyMode:t.concurrencyMode});return r===Ot.Undefined&&(s.rawTypeName=t.type),s}function o(e,t,n){var r=m(t.type,n).typeName,i=new It({nameOnServer:t.name,complexTypeName:r,isNullable:!1});return i}function u(e,t,n){var r=h(t,n),i=v(r.end,function(e){return e.role===t.toRole}),a="*"!==i.multiplicity,o=m(i.type,n).typeName,u=r.referentialConstraint;if(u||"*"!=r.end[0].multiplicity||"*"!=r.end[1].multiplicity){var p={nameOnServer:t.name,entityTypeName:o,isScalar:a,associationName:r.name};if(u){var c=u.principal,l=u.dependent,y=d(l.propertyRef),f=y.map(s("name"));t.fromRole===c.role?p.invForeignKeyNamesOnServer=f:p.foreignKeyNamesOnServer=f}var g=new Vt(p);return e._addPropertyCore(g),g}}function p(e,t){return t.enumType?c(e,t):t.extensions?l(e,t):!1}function c(e,t){var n=d(t.enumType),r=e.type.split("."),i=r[r.length-1];return n.some(function(e){return e.name===i})}function l(e,t){var n=t.extensions.filter(function(e){return"EnumType"===e.name}),r=e.type.split("."),i=r[r.length-1];return n.some(function(e){return e.attributes.some(function(e){return"Name"===e.name&&e.value===i})})}function y(e){var t;if(e.isNullable||e.validators.push(Et.required()),!e.isComplexProperty){if(e.dataType===Ot.String)if(e.maxLength){var n={maxLength:e.maxLength};t=Et.maxLength(n)}else t=Et.string();else t=e.dataType.validatorCtor();e.validators.push(t)}}function f(e){var t=v(Object.keys(e),function(e){return e.indexOf("StoreGeneratedPattern")>=0});if(t)return"Identity"===e[t];var n=e.extensions;if(!n)return!1;var r=v(n,function(e){return"StoreGeneratedPattern"===e.name&&"Identity"===e.value});return!!r}function h(e,t){var n=m(e.relationship,t).shortTypeName,r=t.association;if(!r)return null;Array.isArray(r)||(r=[r]);var i=v(r,function(e){return e.name===n});return i}function m(e,t){var n=X(e);if(t){var r=g(n.shortTypeName,t);r&&(n=et(n.shortTypeName,r))}return n}function g(e,t){var n,r=t.cSpaceOSpaceMapping;if(r){var i=r[t.namespace+"."+e];if(n=i&&i.substr(0,i.length-(e.length+1)))return n}return t.entityType||"Default"!=t.namespace?t.namespace:null}return{parse:e}}(),Dt=function(){function e(e,t){return e.entityAspect||e.complexAspect?e.getProperty(t.name):e[t.name]}function t(e){var t=e.name.replace(/\W/g,"_");return Function("return function "+t+"(){}")()}function n(e,t){var r=e.complexAspect.parentProperty.dataType.dataProperties,i=r.every(function(r){if(!r.isSettable)return!0;var i=e.getProperty(r.name),a=t.getProperty(r.name);if(r.isComplexProperty)return n(i,a);var o=r.dataType;return i===a||o&&o.isDate&&i&&a&&i.valueOf()===a.valueOf()});return i}function r(e){return e.filter(function(e){return null==e.baseProperty})}function a(e,t,n){var r=n+"OnServer",i=t[n];if(i&&i.length){var a=d(i).map(function(n){var r=e.clientPropertyNameToServer(n,t),i=e.serverPropertyNameToClient(r,t);if(n!==i)throw new Error("NamingConvention for this client property name does not roundtrip properly:"+n+"-->"+i);return r});t[r]=Array.isArray(i)?a:a[0]}else{var o=t[r];if(!o||0===o.length)return;var s=d(o).map(function(n){var r=e.serverPropertyNameToClient(n,t),i=e.clientPropertyNameToServer(r,t);if(n!==i)throw new Error("NamingConvention for this server property name does not roundtrip properly:"+n+"-->"+i);return r});t[n]=Array.isArray(o)?s:s[0]}}function u(e,t){var n=t._getEntityType(e.complexTypeName,!0);if(!n)return!1;if(!(n instanceof kt))throw new Error("Unable to resolve ComplexType with the name: "+e.complexTypeName+" for the property: "+property.name);return e.dataType=n,e.defaultValue=null,!0}function p(e,t){if(e.entityType)return!0;var n=t._getEntityType(e.entityTypeName,!0);if(n)e.entityType=n,e._resolveNp();else{var r=T(t._incompleteTypeMap,e.entityTypeName);E(r,e)}return!!n}function c(e,t){var n=e.getPropertyNames(),r=vt.getDefaultInstance(),a=r.getTrackablePropertyNames(t);a.forEach(function(r){if(-1===n.indexOf(r)){var a=t[r];try{"function"==typeof a&&(a=a())}catch(o){}var s=Ot.fromValue(a),u=new It({name:r,dataType:s,isNullable:!0,isUnmapped:!0});u.isSettable=i(t,r),e.subtypes?e.getSelfAndSubtypes().forEach(function(e){e._addPropertyCore(new It(u))}):e._addPropertyCore(u)}})}var l=0,f=function(e){if(arguments.length>1)throw new Error("The EntityType ctor has a single argument that is either a 'MetadataStore' or a configuration object.");"MetadataStore"===e._$typeName?(this.metadataStore=e,this.shortName="Anon_"+ ++l,this.namespace="",this.isAnonymous=!0):ft(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("baseTypeName").isString().isOptional().whereParam("isAbstract").isBoolean().isOptional().withDefault(!1).whereParam("autoGeneratedKeyType").isEnumOf(Rt).isOptional().withDefault(Rt.None).whereParam("defaultResourceName").isNonEmptyString().isOptional().withDefault(null).whereParam("dataProperties").isOptional().whereParam("navigationProperties").isOptional().whereParam("serializerFn").isOptional().isFunction().whereParam("custom").isOptional().applyAll(this),this.name=nt(this.shortName,this.namespace),this.dataProperties=[],this.navigationProperties=[],this.complexProperties=[],this.keyProperties=[],this.foreignKeyProperties=[],this.inverseForeignKeyProperties=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.validators=[],this.warnings=[],this._mappedPropertiesCount=0,this.subtypes=[],rt(this,e.dataProperties,It),rt(this,e.navigationProperties,Vt)},h=f.prototype,m=Ot.parseRawValue;return h._$typeName="EntityType",f.qualifyTypeName=nt,h.setProperties=function(e){ft(e).whereParam("autoGeneratedKeyType").isEnumOf(Rt).isOptional().whereParam("defaultResourceName").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().whereParam("custom").isOptional().applyAll(this),e.defaultResourceName&&(this.defaultResourceName=e.defaultResourceName)},h.isSubtypeOf=function(e){lt(e,"entityType").isInstanceOf(Dt).check();var t=this;do{if(t===e)return!0;t=t.baseEntityType}while(t);return!1},h.getSelfAndSubtypes=function(){var e=[this];return this.subtypes.forEach(function(t){var n=t.getSelfAndSubtypes();e.push.apply(e,n)}),e},h.getAllValidators=function(){for(var e=this.validators.slice(0),t=this.baseEntityType;t;)e.push.apply(e,t.validators),t=t.baseEntityType;return e},h.addProperty=function(e){return lt(e,"property").isInstanceOf(It).or().isInstanceOf(Vt).check(),this._addPropertyCore(e,!0)},h._updateFromBase=function(e){this.baseEntityType=e,this.autoGeneratedKeyType===Rt.None&&(this.autoGeneratedKeyType=e.autoGeneratedKeyType),e.dataProperties.forEach(function(e){var t=new It(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.navigationProperties.forEach(function(e){var t=new Vt(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.subtypes.push(this)},h._addPropertyCore=function(e,t){if(this.isFrozen)throw new Error("The '"+this.name+"' EntityType/ComplexType has been frozen. You can only add properties to an EntityType/ComplexType before any instances of that type have been created and attached to an entityManager.");var n=e.parentType;if(n){if(n!==this)throw new Error("This property: "+e.name+" has already been added to "+e.parentType.name);return this}e.parentType=this;var r=this.metadataStore;if(e.isDataProperty?this._addDataProperty(e):(this._addNavigationProperty(e),t&&r&&p(e,r)),!r||e.name&&e.nameOnServer||a(r.namingConvention,e,"name"),r&&this._extra&&this._extra.alreadyWrappedProps){var i=this._ctor.prototype;vt.getDefaultInstance().initializeEntityPrototype(i)}return this},h.createEntity=function(t){if(t&&t._$eref&&!t._$eref.entityAspect.entityManager)return t._$eref;var n=this._createInstanceCore();return t&&(this.keyProperties.every(function(e){return null!=t[e.name]})&&(t._$eref=n),this._updateTargetFromRaw(n,t,e),this.navigationProperties.forEach(function(e){var r,i=t[e.name];if(void 0!=i){var a=e.entityType;if(e.isScalar)r=i.entityAspect?i:a.createEntity(i),n.setProperty(e.name,r);else{var o=n.getProperty(e.name);i.forEach(function(e){r=e.entityAspect?e:a.createEntity(e),o.push(r)})}}})),this._initializeInstance(n),n},h._createInstanceCore=function(){var e=this.getEntityCtor(),t=new e;return new Tt(t),t},h._initializeInstance=function(e){this.baseEntityType&&this.baseEntityType._initializeInstance(e);var t=this.initFn;t&&("string"==typeof t&&(t=e[t]),t(e)),this.complexProperties&&this.complexProperties.forEach(function(t){var n=e.getProperty(t.name);Array.isArray(n)?n.forEach(function(e){t.dataType._initializeInstance(e)}):t.dataType._initializeInstance(n)}),e.entityAspect&&(e.entityAspect._initialized=!0)},h.getCtor=h.getEntityCtor=function(e){if(this._ctor&&!e)return this._ctor;var n=this.metadataStore._ctorRegistry,r=n[this.name]||n[this.shortName]||{},i=r.ctor||this._ctor,a=i&&i.prototype&&(i.prototype.entityType||i.prototype.complexType);if(a&&a.metadataStore!==this.metadataStore)throw new Error("Cannot register the same constructor for "+this.name+" in different metadata stores.  Please define a separate constructor for each metadata store.");if(r.ctor&&e&&(this._extra=void 0),!i){var o=vt.getDefaultInstance().createCtor;i=o?o(this):t(this)}return this.initFn=r.initFn,this.noTrackingFn=r.noTrackingFn,i.prototype._$typeName=this.name,this._setCtor(i),i},h._setCtor=function(e,t){var n=e.prototype;this._extra=this._extra||{};var r=new e;c(this,r),"EntityType"===this._$typeName?n.entityType=this:n.complexType=this,n._$interceptor=t||J,vt.getDefaultInstance().initializeEntityPrototype(n),this._ctor=e},h.addValidator=function(e,t){lt(e,"validator").isInstanceOf(Et).check(),lt(t,"property").isOptional().isString().or().isEntityProperty().check(),t?("string"==typeof t&&(t=this.getProperty(t,!0)),t.validators.push(e)):this.validators.push(e)},h.getProperties=function(){return this.dataProperties.concat(this.navigationProperties)},h.getPropertyNames=function(){return this.getProperties().map(s("name"))},h.getDataProperty=function(e){return v(this.dataProperties,o("name",e))},h.getNavigationProperty=function(e){return v(this.navigationProperties,o("name",e))},h.getProperty=function(e,t){var n=this.getPropertiesOnPath(e,!1,t);return n?n[n.length-1]:null},h.getPropertiesOnPath=function(e,t,n){n=n||!1;var r=Array.isArray(e)?e:e.trim().split("."),i=!0,a=this,s=t?"nameOnServer":"name",u=r.map(function(e){var t=v(a.getProperties(),o(s,e));if(t)a=t.isNavigationProperty?t.entityType:t.dataType;else{if(n)throw new Error("unable to locate property: "+e+" on entityType: "+a.name);i=!1}return t});return i?u:null},h.clientPropertyPathToServer=function(e,t){var n,t=t||".";if(this.isAnonymous){var r=this.metadataStore.namingConvention.clientPropertyNameToServer;n=e.split(".").map(function(e){return r(e)})}else n=this.getPropertiesOnPath(e,!1,!0).map(function(e){return e.nameOnServer});return n.join(t)},h.getEntityKeyFromRawEntity=function(e,t){var n=this.keyProperties.map(function(n){var r=t(e,n);return m(r,n.dataType)});return new _t(this,n)},h._updateTargetFromRaw=function(e,t,r){this.dataProperties.forEach(function(i){if(i.isSettable){var a=r(t,i);if(void 0!==a){var o,s=i.dataType;if(i.isComplexProperty){if(null===a)return;if(o=e.getProperty(i.name),i.isScalar)s._updateTargetFromRaw(o,a,r);else if(Array.isArray(a)){var u=a.map(function(t){var n=s._createInstanceCore(e,i);return s._updateTargetFromRaw(n,t,r),s._initializeInstance(n),n});P(o,u,n)||(o.length=0,u.forEach(function(e){o.push(e)}))}else o.length=0}else{if(i.isScalar){var u=m(a,s);e.setProperty(i.name,u)}else if(o=e.getProperty(i.name),Array.isArray(a)){var u=a.map(function(e){return m(e,s)});P(o,u)||(o.length=0,u.forEach(function(e){o.push(e)}))}else o.length=0}}}});var i=t.entityAspect||t.complexAspect;if(i){var a=e.entityAspect||e.complexAspect;i.originalValuesMap&&(a.originalValues=i.originalValuesMap),i.extraMetadata&&(a.extraMetadata=i.extraMetadata)}},h.toString=function(){return this.name},h.toJSON=function(){return y(this,{shortName:null,namespace:null,baseTypeName:null,isAbstract:!1,autoGeneratedKeyType:null,defaultResourceName:null,dataProperties:r,navigationProperties:r,validators:null,custom:null})},h._updateNames=function(e){var t=this.metadataStore.namingConvention;a(t,e,"name"),e.isNavigationProperty&&(a(t,e,"foreignKeyNames"),a(t,e,"invForeignKeyNames"))},h._checkNavProperty=function(e){if(e.isNavigationProperty){if(e.parentType!==this)throw new Error(G("The navigationProperty '%1' is not a property of entity type '%2'",e.name,this.name));return e}if("string"==typeof e){var t=this.getProperty(e);if(t&&t.isNavigationProperty)return t}throw new Error("The 'navigationProperty' parameter must either be a NavigationProperty or the name of a NavigationProperty")},h._addDataProperty=function(e){this.dataProperties.push(e),e.isPartOfKey&&this.keyProperties.push(e),e.isComplexProperty&&this.complexProperties.push(e),e.concurrencyMode&&"None"!==e.concurrencyMode&&this.concurrencyProperties.push(e),e.isUnmapped&&this.unmappedProperties.push(e)},h._addNavigationProperty=function(e){this.navigationProperties.push(e),tt(e.entityTypeName)||(e.entityTypeName=nt(e.entityTypeName,this.namespace))},h._updateCps=function(){var e=this.metadataStore,t=e._incompleteComplexTypeMap;this.complexProperties.forEach(function(n){n.complexType||u(n,e)||T(t,n.complexTypeName).push(n)}),this.isComplexType&&((t[this.name]||[]).forEach(function(t){u(t,e)}),delete t[this.name])},h._updateNps=function(){var e=this.metadataStore;this.navigationProperties.forEach(function(t){p(t,e)});var t=e._incompleteTypeMap;(t[this.name]||[]).forEach(function(t){p(t,e)}),delete t[this.name]},f}(),kt=function(){var e=function(e){if(arguments.length>1)throw new Error("The ComplexType ctor has a single argument that is a configuration object.");ft(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("dataProperties").isOptional().whereParam("isComplexType").isOptional().isBoolean().whereParam("custom").isOptional().applyAll(this),this.name=nt(this.shortName,this.namespace),this.isComplexType=!0,this.dataProperties=[],this.complexProperties=[],this.validators=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.navigationProperties=[],this.keyProperties=[],rt(this,e.dataProperties,It)},t=e.prototype;return t.setProperties=function(e){ft(e).whereParam("custom").isOptional().applyAll(this)},t.getAllValidators=function(){return this.validators},t._createInstanceCore=function(e,t){var n=this.getCtor(),r=new n;return new Nt(r,e,t),r},t.addProperty=function(e){return lt(e,"dataProperty").isInstanceOf(It).check(),this._addPropertyCore(e)},t.getProperties=function(){return this.dataProperties},t=p(t,Dt.prototype,["addValidator","getProperty","getPropertiesOnPath","getPropertyNames","_addPropertyCore","_addDataProperty","_updateNames","_updateCps","_initializeInstance","_updateTargetFromRaw","_setCtor"]),t.createInstance=Dt.prototype.createEntity,t.getCtor=Dt.prototype.getEntityCtor,t.toJSON=function(){return y(this,{shortName:null,namespace:null,isComplexType:null,dataProperties:null,validators:null,custom:null})},t._$typeName="ComplexType",e}(),It=function(){var e=function(e){ft(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("dataType").isEnumOf(Ot).isOptional().or().isString().or().isInstanceOf(kt).whereParam("complexTypeName").isOptional().whereParam("isNullable").isBoolean().isOptional().withDefault(!0).whereParam("isScalar").isOptional().withDefault(!0).whereParam("defaultValue").isOptional().whereParam("isPartOfKey").isBoolean().isOptional().whereParam("isUnmapped").isBoolean().isOptional().whereParam("isSettable").isBoolean().isOptional().withDefault(!0).whereParam("concurrencyMode").isString().isOptional().whereParam("maxLength").isNumber().isOptional().whereParam("validators").isInstanceOf(Et).isArray().isOptional().withDefault([]).whereParam("displayName").isOptional().whereParam("enumType").isOptional().whereParam("rawTypeName").isOptional().whereParam("custom").isOptional().applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw new Error("A DataProperty must be instantiated with either a 'name' or a 'nameOnServer' property");if(this.complexTypeName)this.isComplexProperty=!0,this.dataType=null;else if("string"==typeof this.dataType){var n=Ot.fromName(this.dataType);if(!n)throw new Error("Unable to find a DataType enumeration by the name of: "+this.dataType);this.dataType=n}else this.dataType||(this.dataType=Ot.String);if(null==this.defaultValue){if(this.isNullable)this.defaultValue=null;else if(this.isComplexProperty);else if(this.dataType===Ot.Binary)this.defaultValue="AAAAAAAAJ3U=";else if(this.defaultValue=this.dataType.defaultValue,null==this.defaultValue)throw new Error("A nonnullable DataProperty cannot have a null defaultValue. Name: "+(this.name||this.nameOnServer))}else this.dataType.isNumeric&&"string"==typeof this.defaultValue&&(this.defaultValue=parseFloat(this.defaultValue));this.isComplexProperty&&(this.isScalar=null==this.isScalar||this.isScalar===!0)},t=e.prototype;return t._$typeName="DataProperty",e.getRawValueFromServer=function(e,t){if(t.isUnmapped)return e[t.nameOnServer||t.name];var n=e[t.nameOnServer];return void 0!==n?n:t.defaultValue},e.getRawValueFromClient=function(e,t){var n=e[t.name];return void 0!==n?n:t.defaultValue},t.isDataProperty=!0,t.isNavigationProperty=!1,t.resolveProperty=function(e){for(var t=this[e],n=this.baseProperty;void 0==t&&null!=n;)t=n[e],n=n.baseProperty;return t},t.formatName=function(){return this.parentType.name+"--"+this.name},t.setProperties=function(e){ft(e).whereParam("displayName").isOptional().whereParam("custom").isOptional().applyAll(this)},t.getAllValidators=function(){for(var e=this.validators.slice(0),t=this.baseProperty;t;)e.push.apply(e,t.validators),t=t.baseProperty;return e},t.toJSON=function(){return y(this,{name:null,dataType:function(e){return e&&e.parentEnum?e.name:void 0},complexTypeName:null,isNullable:!0,defaultValue:null,isPartOfKey:!1,isUnmapped:!1,isSettable:!0,concurrencyMode:null,maxLength:null,validators:null,displayName:null,enumType:null,rawTypeName:null,isScalar:!0,custom:null})},e.fromJSON=function(e){return e.dataType=Ot.fromName(e.dataType),e.defaultValue&&e.dataType&&e.dataType.isDate&&(e.defaultValue=new Date(Date.parse(e.defaultValue))),e.validators&&(e.validators=e.validators.map(Et.fromJSON)),new It(e)},e}(),Vt=function(){function e(e,t){throw new Error("Cannot set the inverse property for: "+e.formatName()+". "+t)}function t(e,t){throw new Error("Cannot create inverse for: "+e.formatName()+". The entityType for this navigation property "+t)}function n(e){var t=e.foreignKeyNames;if(0!==t.length){var n=e.parentType,r=t.map(function(e){return n.getDataProperty(e)}),i=n.foreignKeyProperties;r.forEach(function(t){E(i,t),t.relatedNavigationProperty=e,E(e.entityType.inverseForeignKeyProperties,t),e.relatedDataProperties?E(e.relatedDataProperties,t):e.relatedDataProperties=[t]})}}var r=function(e){ft(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("entityTypeName").isString().whereParam("isScalar").isBoolean().isOptional().withDefault(!0).whereParam("associationName").isString().isOptional().whereParam("foreignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("foreignKeyNamesOnServer").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNamesOnServer").isArray().isString().isOptional().withDefault([]).whereParam("validators").isInstanceOf(Et).isArray().isOptional().withDefault([]).whereParam("displayName").isOptional().whereParam("custom").isOptional().applyAll(this);var t=!(!this.name&&!this.nameOnServer);if(!t)throw new Error("A Navigation property must be instantiated with either a 'name' or a 'nameOnServer' property")},i=r.prototype;return i._$typeName="NavigationProperty",i.isDataProperty=!1,i.isNavigationProperty=!0,p(i,It.prototype,["formatName","getAllValidators","resolveProperty"]),i.setProperties=function(e){if(!this.parentType)throw new Error("Cannot call NavigationProperty.setProperties until the parent EntityType of the NavigationProperty has been set.");var t=e.inverse;t&&delete e.inverse,ft(e).whereParam("displayName").isOptional().whereParam("foreignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("invForeignKeyNames").isArray().isString().isOptional().withDefault([]).whereParam("custom").isOptional().applyAll(this),this.parentType._updateNames(this),this._resolveNp(),t&&this.setInverse(t)},i.setInverse=function(t){var n;if(n="string"==typeof t?this.entityType.getNavigationProperty(t):t,!n)throw e(this,"Unable to find inverse property: "+invNpName);(this.inverse||n.inverse)&&e(this,"It has already been set on one side or the other."),n.entityType!=this.parentType&&e(this,n.formatName+" is not a valid inverse property for this."),this.associationName?n.associationName=this.associationName:(n.associationName||(n.associationName=this.formatName()+"_"+n.formatName()),this.associationName=n.associationName),this._resolveNp(),n._resolveNp()},i.createInverse=function(e){this.entityType||t(this,"has not yet been defined."),this.entityType.isFrozen&&t(this,"is frozen.");var n=this.entityType.metadataStore;null==n&&t(this,"has not yet been added to the metadataStore."),e.entityTypeName=this.parentEntityType.name,e.associationName=this.associationName;var r=new Vt(e);return this.parentEntityType.addNavigationProperty(r),r},i.toJSON=function(){return y(this,{name:null,entityTypeName:null,isScalar:null,associationName:null,validators:null,displayName:null,foreignKeyNames:null,invForeignKeyNames:null,custom:null})},r.fromJSON=function(e){return e.validators&&(e.validators=e.validators.map(Et.fromJSON)),new Vt(e)},i._resolveNp=function(){var e=this,t=e.entityType,r=v(t.navigationProperties,function(t){return t.associationName===e.associationName&&(t.name!==e.name||t.entityTypeName!==e.entityTypeName)});e.inverse=r,r||e.invForeignKeyNames.forEach(function(n){var r=t.getDataProperty(n);if(!r)throw new Error("EntityType '"+e.entityTypeName+"' has no foreign key matching '"+n+"'");var i=e.parentType;r.inverseNavigationProperty=v(i.navigationProperties,function(e){return e.invForeignKeyNames&&e.invForeignKeyNames.indexOf(r.name)>=0&&e.entityType===r.parentType}),E(t.foreignKeyProperties,r)}),n(e)},r}(),Rt=function(){var e=new ht("AutoGeneratedKeyType");return e.None=e.addSymbol(),e.Identity=e.addSymbol(),e.KeyGenerator=e.addSymbol(),e.resolveSymbols(),e}();!function(){function e(e,t){return null==t?!1:void 0!==t.entityType}function t(e,t){return null==t?!1:t.isDataProperty||t.isNavigationProperty}var n=ct.prototype;n.isEntity=function(){return this._addContext({fn:e,msg:" must be an entity"})},n.isEntityProperty=function(){return this._addContext({fn:t,msg:" must be either a DataProperty or a NavigationProperty"})}}(),at.MetadataStore=Ft,at.EntityType=Dt,at.ComplexType=kt,at.DataProperty=It,at.NavigationProperty=Vt,at.AutoGeneratedKeyType=Rt;var Kt=function(){function e(e,t,n){var r=t.name+".."+t.parentType.name,i=e._tempIdMap[r];return i||n&&(i={entityType:t.parentType,propertyName:t.name,keyMap:{}},e._tempIdMap[r]=i),i}var t=function(){this._tempIdMap={}},n=t.prototype;return n.generateTempKeyValue=function(t,n){var r=t.keyProperties;if(r.length>1)throw new Error("Ids can not be autogenerated for entities with multipart keys");var i,a=r[0],o=e(this,a,!0);if(null!=n&&(o.keyMap[n.toString()]||(i=n)),void 0===i){var s=a.dataType;if(!s.getNext)throw new Error("Cannot use a property with a dataType of: "+s.toString()+" for id generation");for(i=s.getNext(this);null!=o.keyMap[i.toString()];)i=s.getNext(this)}return o.keyMap[i.toString()]=!0,i},n.getTempKeys=function(){var e=[];for(var t in this._tempIdMap){var n=this._tempIdMap[t],r=n.entityType;for(var i in n.keyMap)e.push(new _t(r,[i]))}return e},n.isTempKey=function(t){var n=t.entityType.keyProperties;if(n.length>1)return!1;var r=n[0],i=e(this,r);return i?void 0!==i.keyMap[t.values[0].toString()]:!1},mt.registerType(t,"KeyGenerator"),t}();at.KeyGenerator=Kt;var jt=function(){var e=function(e){ft(e||{}).whereParam("name").isOptional().isString().whereParam("isCaseSensitive").isOptional().isBoolean().whereParam("usesSql92CompliantStringComparison").isBoolean().applyAll(this),this.name||(this.name=C()),mt._storeObject(this,t._$typeName,this.name)},t=e.prototype;return t._$typeName="LocalQueryComparisonOptions",e.caseInsensitiveSQL=new e({name:"caseInsensitiveSQL",isCaseSensitive:!1,usesSql92CompliantStringComparison:!0}),e.defaultInstance=new e(e.caseInsensitiveSQL),t.setAsDefault=function(){return l(this,e)},e}();at.LocalQueryComparisonOptions=jt;var Bt=function(){var e=function(e){ft(e||{}).whereParam("name").isOptional().isString().whereParam("serverPropertyNameToClient").isFunction().whereParam("clientPropertyNameToServer").isFunction().applyAll(this),this.name||(this.name=C()),mt._storeObject(this,t._$typeName,this.name)},t=e.prototype;return t._$typeName="NamingConvention",e.none=new e({name:"noChange",serverPropertyNameToClient:function(e){return e},clientPropertyNameToServer:function(e){return e}}),e.camelCase=new e({name:"camelCase",serverPropertyNameToClient:function(e){return e.substr(0,1).toLowerCase()+e.substr(1)},clientPropertyNameToServer:function(e){return e.substr(0,1).toUpperCase()+e.substr(1)}}),e.defaultInstance=new e(e.none),t.setAsDefault=function(){return l(this,e)},e}();at.NamingConvention=Bt;var Lt=function(){function e(e,r){var i=r.entityType;if(Array.isArray(e)){if(!r.isRHS)throw new Error("Array expressions are only permitted on the right hand side of a BinaryPredicate");return new y(e,r.dataType)}if(!R(e)){if(null!=e&&K(e)&&!e.toISOString){if(void 0===e.value)throw new Error("Unable to resolve an expression for: "+e+" on entityType: "+i.name);return e.isProperty?new f(e.value):new y(e.value,e.dataType||r.dataType,!0)}return new y(e,r.dataType)}if(r.isRHS)return null==i||i.isAnonymous?new y(e,r.dataType):n(e,r);for(var a,o=/\([^()]*\)/,s=[],u=0;a=o.exec(e);){var p=a[0];s.push(p);var c=g+u++;e=e.replace(p,c)}var l=t(e,s,r);return l._validate(i,r.usesNameOnServer),l}function t(e,t,i){var a=e.split(g);return 1===a.length?n(a[0],i):r(e,a,t,i)}function n(e,t){e=e.trim();var n=e.substr(0,1),r=("'"===n||'"'===n)&&e.length>1&&e.substr(e.length-1)===n;if(r){var i=e.substr(1,e.length-2);return new y(i,t.dataType||Ot.String)}var a=t.entityType;if(null==a||a.isAnonymous)return new f(e);var o=d.test(e);return o&&null!=a.getPropertiesOnPath(e,t.usesNameOnServer,!1)?new f(e):new y(e,t.dataType)}function r(e,n,r,i){try{var a=n[0].trim().toLowerCase(),o=r[n[1]].trim();"("===o.substr(0,1)&&(o=o.substr(1,o.length-2));var s=e.indexOf("'")>=0?m:v,u=o.match(s),c=p({},i);c.dataType=Ot.Undefined,c.isFnArg=!0;var l=u.map(function(e){return t(e,r,c)});return new h(a,l)}catch(y){return null}}var i=function(){function e(e,t){var n=t[0];return n instanceof i?n=st(t):Array.isArray(n)||(n=[i(st(t))]),[e].concat(n)}function t(e,t,n){var r=t.toLowerCase();n.key=r,e[r]=n,n.aliases&&n.aliases.forEach(function(t){e[t.toLowerCase()]=n})}function n(e){var t={},i={};t[e[0]]=i;var a=e[1];return a=a.operator||a,i[a]=3==e.length?e[2]:n(e.splice(2)),r(t)}function r(e){if(e instanceof i)return e;if("object"!=typeof e)throw new Error("Unable to convert to a Predicate: "+e);var t=Object.keys(e),n=t.map(function(t){return p(t,e[t])});return 1===n.length?n[0]:new u("and",n)}function p(e,t){if(u.prototype._resolveOp(e,!0))return new u(e,t);if(o.prototype._resolveOp(e,!0))return new o(e,t);if("object"!=typeof t||null==t||k(t))return new s("eq",e,t);if(ot(t,"value"))return new s("eq",e,t);if(Array.isArray(t))throw new Error("Unable to resolve predicate after the phrase: "+e);var n=e,r=Object.keys(t),i=r.map(function(e){if(c.prototype._resolveOp(e,!0))return new c(e,n,t[e]);if(s.prototype._resolveOp(e,!0))return new s(e,n,t[e]);if(ot(t[e],"value"))return new s("eq",n,t[e]);var r=G("Unable to resolve predicate after the phrase: '%1' for operator: '%2'  and value: '%3'",n,e,t[e]);throw new Error(r)});return 1===i.length?i[0]:new u("and",i)}var l=function(){if(0!==arguments.length){if(1===arguments.length){var e=arguments[0];return Array.isArray(e)?1===e.length?i(e[0]):n(e):e instanceof i?e:"string"==typeof e?new a(e):r(e)}return n(Array.prototype.slice.call(arguments,0))}},y=l.prototype;return l.create=l,l.and=function(){var e=new u("and",st(arguments));
  return e.op&&e},l.or=function(){var e=new u("or",st(arguments));return e.op&&e},l.not=function(e){return e.not()},l.extendBinaryPredicateFn=function(e,n){var r=E.binaryPredicate;for(var i in e||{}){var a=e[i];a.visitorFn=n,t(s.prototype.aliasMap,i,e[i])}E.isExtended||(E.binaryPredicate=function(e,t,n){var i=this.aliasMap[this.op.key].visitorFn;return i?i(e,t,n):r(e,t,n)},E.isExtended=!0)},y.and=function(){return new u("and",e(this,arguments))},y.or=function(){return new u("or",e(this,arguments))},y.not=function(){return new o("not",this)},y.toJSON=function(){return this.toJSONExt({entityType:this._entityType})},y.toJSONExt=function(e){return this.visit(e,w)},y.toFunction=function(e){return this.visit(e,E)},y.toString=function(){return JSON.stringify(this)},y.visit=function(e,t){if(L(e))e={entityType:null};else if(e instanceof Dt)e={entityType:e};else if(!ot(e,"entityType"))throw new Error("All visitor methods must be called with a context object containing at least an 'entityType' property");t?e.visitor=t:t=e.visitor;var n=t[this.visitorMethodName];if(null==n)throw new Error("Unable to locate method: "+this.visitorMethodName+" on visitor");var r=e.entityType;(this._validate&&null==r||this._entityType!==r)&&(this._validate(r,e.usesNameOnServer),this._entityType=r);Array.prototype.slice.call(arguments,1);return n.call(this,e)},y._initialize=function(e,n){this.visitorMethodName=e;var r=this.aliasMap={};for(var i in n||{})t(r,i,n[i])},y._resolveOp=function(e,t){e=e.operator||e;var n=this.aliasMap[e.toLowerCase()];if(!n&&!t)throw new Error("Unable to resolve operator: "+e);return n},l}(),a=function(){var e=function(e){this.value=e},t=e.prototype=new i;return t._initialize("passthruPredicate"),t._validate=F,e}(),o=function(){var e=function(e,t){this.op=this._resolveOp(e),this.pred=i(t)},t=e.prototype=new i;return t._initialize("unaryPredicate",{not:{aliases:["!","~"]}}),t._validate=function(e,t){this.pred._validate(e,t)},e}(),s=function(){var t=function(e,t,n){this.op=this._resolveOp(e),this.expr1Source=t,this.expr2Source=n},n=t.prototype=new i;return n._initialize("binaryPredicate",{eq:{aliases:["==","equals"]},ne:{aliases:["!=","~=","notequals"]},lt:{aliases:["<","lessthan"]},le:{aliases:["<=","lessthanorequal"]},gt:{aliases:[">","greaterthan"]},ge:{aliases:[">=","greaterthanorequal"]},startswith:{isFunction:!0},endswith:{isFunction:!0},contains:{aliases:["substringof"],isFunction:!0},"in":{}}),n._validate=function(t,n){var r={entityType:t,usesNameOnServer:n};if(this.expr1=e(this.expr1Source,r),null==this.expr1)throw new Error("Unable to validate 1st expression: "+this.expr1Source);if(this.expr1 instanceof y)throw new Error("The left hand side of a binary predicate cannot be a literal expression, it must be a valid property or functional predicate expression: "+this.expr1Source);if("in"==this.op.key&&!Array.isArray(this.expr2Source))throw new Error("The 'in' operator requires that its right hand argument be an array");var i=p(r,{isRHS:!0,dataType:this.expr1.dataType});if(this.expr2=e(this.expr2Source,i),null==this.expr2)throw new Error("Unable to validate 2nd expression: "+this.expr2Source);null==this.expr1.dataType&&(this.expr1.dataType=this.expr2.dataType)},t}(),u=function(){var e=function(e,t){return this.op=this._resolveOp(e),1==t.length&&Array.isArray(t[0])&&(t=t[0]),this.preds=t.filter(function(e){return null!=e}).map(function(e){return i(e)}),0==this.preds.length&&(this.op=null),1==this.preds.length?this.preds[0]:void 0},t=e.prototype=new i;return t._initialize("andOrPredicate",{and:{aliases:["&&"]},or:{aliases:["||"]}}),t._validate=function(e,t){this.preds.every(function(n){n._validate(e,t)})},e}(),c=function(){var t=function(e,t,n){this.op=this._resolveOp(e),this.exprSource=t,this.pred=i(n)},n=t.prototype=new i;return n._initialize("anyAllPredicate",{any:{aliases:["some"]},all:{aliases:["every"]}}),n._validate=function(t,n){this.expr=e(this.exprSource,{entityType:t,usesNameOnServer:n}),(null==t||t.isAnonymous)&&(this.expr.dataType=null),this.pred._validate(this.expr.dataType,n)},t}(),l=function(e){this.visitorMethodName=e,this.visit=i.prototype.visit,this._validate=F},y=function(){function e(e){if(null==e)return e;if(Ot.contains(e))return e;if(R(e)){var t=Ot.fromName(e);if(t)return t;throw new Error("Unable to resolve a dataType named: "+e)}throw new Error("The dataType parameter passed into this literal expression is not a 'DataType'"+e)}var t=function(t,n,r){n=e(n),n=n||Ot.fromValue(t),this.value=n&&n.parse?Array.isArray(t)?t.map(function(e){return n.parse(e,typeof e)}):n.parse(t,typeof t):t,this.dataType=n,this.hasExplicitDataType=r},n=t.prototype=new l("litExpr");return n.toString=function(){return" LitExpr - value: "+this.value.toString()+" dataType: "+this.dataType.toString()},t}(),f=function(){var e=function(e){this.propertyPath=e},t=e.prototype=new l("propExpr");return t.toString=function(){return" PropExpr - "+this.propertyPath},t._validate=function(e,t){if(null!=e&&!e.isAnonymous){var n=e.getPropertiesOnPath(this.propertyPath,t,!1);if(!n){var r=G("Unable to resolve propertyPath.  EntityType: '%1'   PropertyPath: '%2'",e.name,this.propertyPath);throw new Error(r)}var i=n[n.length-1];this.dataType=i.isDataProperty?i.dataType:i.entityType}},e}(),h=function(){var e=function(e,t){this.fnName=e,this.exprs=t;var r=n[e];if(null==r)throw new Error("Unknown function: "+e);this.localFn=r.fn,this.dataType=r.dataType},t=e.prototype=new l("fnExpr");t.toString=function(){var e=this.exprs.map(function(e){e.toString()}).toString();return"FnExpr - "+this.fnName+"("+e+")"},t._validate=function(e,t){this.exprs.forEach(function(n){n._validate(e,t)})};var n=e.funcMap={toupper:{fn:function(e){return e.toUpperCase()},dataType:Ot.String},tolower:{fn:function(e){return e.toLowerCase()},dataType:Ot.String},substring:{fn:function(e,t,n){return e.substring(t,n)},dataType:Ot.String},substringof:{fn:function(e,t){return t.indexOf(e)>=0},dataType:Ot.Boolean},length:{fn:function(e){return e.length},dataType:Ot.Int32},trim:{fn:function(e){return e.trim()},dataType:Ot.String},concat:{fn:function(e,t){return e.concat(t)},dataType:Ot.String},replace:{fn:function(e,t,n){return e.replace(t,n)},dataType:Ot.String},startswith:{fn:function(e,t){return U(e,t)},dataType:Ot.Boolean},endswith:{fn:function(e,t){return z(e,t)},dataType:Ot.Boolean},indexof:{fn:function(e,t){return e.indexOf(t)},dataType:Ot.Int32},round:{fn:function(e){return Math.round(e)},dataType:Ot.Int32},ceiling:{fn:function(e){return Math.ceil(e)},dataType:Ot.Int32},floor:{fn:function(e){return Math.floor(e)},dataType:Ot.Int32},second:{fn:function(e){return e.getSeconds()},dataType:Ot.Int32},minute:{fn:function(e){return e.getMinutes()},dataType:Ot.Int32},day:{fn:function(e){return e.getDate()},dataType:Ot.Int32},month:{fn:function(e){return e.getMonth()+1},dataType:Ot.Int32},year:{fn:function(e){return e.getFullYear()},dataType:Ot.Int32}};return e}(),d=/^[a-z_][\w.$]*$/i,m=/('[^']*'|[^,]+)/g,v=/("[^"]*"|[^,]+)/g,g=String.fromCharCode(191),E=function(){function e(e){switch(e.key){case"any":return function(e,t){return e.some(function(e){return t(e)})};case"all":return function(e,t){return e.every(function(e){return t(e)})};default:throw new Error("Unknown operator: "+e.key)}}function t(e,t,o){var s,u=e.op,p=Ot.getComparableFn(t);switch(u.key){case"eq":s=function(e,t){return e&&"string"==typeof e?n(e,t,o):p(e)==p(t)};break;case"ne":s=function(e,t){return e&&"string"==typeof e?!n(e,t,o):p(e)!=p(t)};break;case"gt":s=function(e,t){return p(e)>p(t)};break;case"ge":s=function(e,t){return p(e)>=p(t)};break;case"lt":s=function(e,t){return p(e)<p(t)};break;case"le":s=function(e,t){return p(e)<=p(t)};break;case"startswith":s=function(e,t){return r(e,t,o)};break;case"endswith":s=function(e,t){return i(e,t,o)};break;case"contains":s=function(e,t){return a(e,t,o)};break;case"in":s=function(e,t){return e=p(e),t=t.map(function(e){return p(e)}),t.indexOf(e)>=0};break;default:return null}return s}function n(e,t,n){return null==t?!1:("string"!=typeof t&&(t=t.toString()),n.usesSql92CompliantStringComparison&&(e=(e||"").trim(),t=(t||"").trim()),n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e===t)}function r(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),U(e,t)}function i(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),z(e,t)}function a(e,t,n){return n.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e.indexOf(t)>=0}var o={passthruPredicate:function(){throw new Error("Cannot execute an PassthruPredicate expression against the local cache: "+this.value)},unaryPredicate:function(e){var t=this.pred.visit(e);switch(this.op.key){case"not":return function(e){return!t(e)};default:throw new Error("Invalid unary operator:"+this.op.key)}},binaryPredicate:function(e){var n=this.expr1.visit(e),r=this.expr2.visit(e),i=this.expr1.dataType||this.expr2.dataType,a=e.entityType.metadataStore.localQueryComparisonOptions,o=t(this,i,a);if(null==o)throw new Error("Invalid binaryPredicate operator:"+this.op.key);return function(e){return o(n(e),r(e))}},andOrPredicate:function(e){var t=this.preds.map(function(t){return t.visit(e)});switch(this.op.key){case"and":return function(e){var n=t.reduce(function(t,n){return t&&n(e)},!0);return n};case"or":return function(e){var n=t.reduce(function(t,n){return t||n(e)},!1);return n};default:throw new Error("Invalid boolean operator:"+op.key)}},anyAllPredicate:function(t){var n=this.expr.visit(t),r=p({},t);r.entityType=this.expr.dataType;var i=this.pred.visit(r),a=e(this.op);return function(e){return a(n(e),i)}},litExpr:function(){var e=this.value;return function(){return e}},propExpr:function(){var e=this.propertyPath,t=e.split(".");return 1===t.length?function(t){return t.getProperty(e)}:function(e){return it(e,t)}},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)}),n=this;return function(e){var r=t.map(function(t){var n=t(e);return n}),i=n.localFn.apply(null,r);return i}}};return o}(),w=function(){function e(t,n){var r=Object.keys(n).every(function(r){if(t.hasOwnProperty(r)){if("object"!=typeof n[r])return!1;if(null==e(t[r],n[r]))return!1}else t[r]=n[r];return!0});return r?t:null}var t={passthruPredicate:function(){return this.value},unaryPredicate:function(e){var t=this.pred.visit(e),n={};return n[this.op.key]=t,n},binaryPredicate:function(e){var t=this.expr1.visit(e),n=this.expr2.visit(e),r={};if(this.expr2 instanceof f&&(n={value:n,isProperty:!0}),"eq"===this.op.key)r[t]=n;else{var i={};r[t]=i,i[this.op.key]=n}return r},andOrPredicate:function(t){var n,r=this.preds.map(function(e){return e.visit(t)});return"and"!==this.op.key||2!==r.length||r.some(R)||(n=r.reduce(e)),null==n&&(n={},n[this.op.key]=r),n},anyAllPredicate:function(e){var t=this.expr.visit(e),n=p({},e);n.entityType=this.expr.dataType;var r=this.pred.visit(n),i={},a={};return a[this.op.key]=r,i[t]=a,i},litExpr:function(e){return this.hasExplicitDataType||e.useExplicitDataType?{value:this.value,dataType:this.dataType.name}:this.value},propExpr:function(e){return e.toNameOnServer?e.entityType.clientPropertyPathToServer(this.propertyPath):this.propertyPath},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)});return this.fnName+"("+t.join(",")+")"}};return t}();return i}();at.Predicate=Lt;var qt=function(){function e(e,t){return y(t,{"resourceName,from":null,"resultEntityType,toType":null,"wherePredicate,where":function(e){return e?new Lt(e):void 0},"orderByClause,orderBy":function(e){return e?new zt(e):void 0},"selectClause,select":function(e){return e?new Gt(e):void 0},"expandClause,expand":function(e){return e?new $t(e):void 0},"skipCount,skip":null,"takeCount,take":null,parameters:function(e){return L(e)?void 0:e},"inlineCountEnabled,inlineCount":!1,"noTrackingEnabled,noTracking":!1,queryOptions:function(e){return e?Zt.fromJSON(e):void 0}},e),e}function n(e,t,n){if(t&&e[t]===n)return e;var r=p(new qt,e,["resourceName","fromEntityType","wherePredicate","orderByClause","selectClause","skipCount","takeCount","expandClause","inlineCountEnabled","noTrackingEnabled","usesNameOnServer","queryOptions","entityManager","dataService","resultEntityType"]);return r.parameters=p({},e.parameters),t&&(r[t]=n),r}function r(e,n,i,a){var o=i._$typeName||i.parentEnum&&i.parentEnum.name,s=o&&o.substr(0,1).toLowerCase()+o.substr(1);if(a&&s!=a)throw new Error("Invalid value for property: "+a);if(s){var u=n[s];if(void 0===u)throw new Error("Invalid config property: "+s);null===u?e[s]=i:u(e,i)}else t(i,function(t,i){r(e,n,i,t)})}function i(e){return lt(e,"propertyPaths").isOptional().isString().or().isArray().isString().check(),"string"==typeof e&&(e=e.split(",")),e=e.map(function(e){return e.trim()})}function a(e){var t=e.entityType,n=t.keyProperties.map(function(t){return Lt.create(t.name,Ut.Equals,e.getProperty(t.name))}),r=Lt.and(n);return r}function o(e){var t=e.entityType.keyProperties,n=S(t,e.values,function(e,t){return Lt.create(e.name,Ut.Equals,t)}),r=Lt.and(n);return r}function s(e,t){if(t.isScalar){if(0===t.foreignKeyNames.length)return null;var n=t.foreignKeyNames.map(function(t){return e.getProperty(t)}),r=new _t(t.entityType,n);return o(r)}var i=t.inverse,a=i?i.foreignKeyNames:t.invForeignKeyNames;if(0===a.length)return null;var s=e.entityAspect.getKey().values,u=S(a,s,function(e,t){return Lt.create(e,Ut.Equals,t)});return Lt.and(u)}var u=function(t){return null==t||R(t)?(this.resourceName=t,this.fromEntityType=null,this.wherePredicate=null,this.orderByClause=null,this.selectClause=null,this.skipCount=null,this.takeCount=null,this.expandClause=null,this.parameters={},this.inlineCountEnabled=!1,this.noTrackingEnabled=!1,void(this.entityManager=null)):e(this,t)},c=u.prototype;return c._$typeName="EntityQuery",c.from=function(e){return lt(e,"resourceName").isString().check(),n(this,"resourceName",e)},u.from=function(e){return lt(e,"resourceName").isString().check(),new qt(e)},c.toType=function(e){return lt(e,"entityType").isString().or().isInstanceOf(Dt).check(),n(this,"resultEntityType",e)},c.where=function(e){return null!=e&&(e=Lt.create(st(arguments)),this.fromEntityType&&e._validate(this.fromEntityType),this.wherePredicate&&(e=this.wherePredicate.and(e))),n(this,"wherePredicate",e)},c.orderBy=function(e,t){var r=null==e?null:new zt(i(e),t);return this.orderByClause&&r&&(r=new zt([this.orderByClause,r])),n(this,"orderByClause",r)},c.orderByDesc=function(e){return this.orderBy(e,!0)},c.select=function(e){var t=null==e?null:new Gt(i(e));return n(this,"selectClause",t)},c.skip=function(e){return lt(e,"count").isOptional().isNumber().check(),n(this,"skipCount",null==e?null:e)},c.top=function(e){return this.take(e)},c.take=function(e){return lt(e,"count").isOptional().isNumber().check(),n(this,"takeCount",null==e?null:e)},c.expand=function(e){var t=null==e?null:new $t(i(e));return n(this,"expandClause",t)},c.withParameters=function(e){return lt(e,"parameters").isObject().check(),n(this,"parameters",e)},c.inlineCount=function(e){return lt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"inlineCountEnabled",e)},c.useNameOnServer=function(e){return lt(e,"usesNameOnServer").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"usesNameOnServer",e)},c.noTracking=function(e){return lt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,n(this,"noTrackingEnabled",e)},c.using=function(e){if(!e)return this;var t=n(this);return r(t,{entityManager:null,dataService:null,queryOptions:null,fetchStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Zt).using(t)},mergeStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Zt).using(t)},jsonResultsAdapter:function(e,t){e.dataService=(e.dataService||new At).using({jsonResultsAdapter:t})}},e),t},c.execute=function(e,t){if(!this.entityManager)throw new Error("An EntityQuery must have its EntityManager property set before calling 'execute'");return this.entityManager.executeQuery(this,e,t)},c.executeLocally=function(){if(!this.entityManager)throw new Error("An EntityQuery must have its EntityManager property set before calling 'executeLocally'");return this.entityManager.executeQueryLocally(this)},c.toJSON=function(){return this.toJSONExt()},c.toJSONExt=function(e){e=e||{},e.entityType=e.entityType||this.fromEntityType,e.propertyPathFn=e.toNameOnServer?e.entityType.clientPropertyPathToServer.bind(e.entityType):M;var t=function(t){return t?t.toJSONExt(e):void 0};return y(this,{"from,resourceName":null,"toType,resultEntityType":function(e){return e?R(e)?e:e.name:void 0},"where,wherePredicate":t,"orderBy,orderByClause":t,"select,selectClause":t,"expand,expandClause":t,"skip,skipCount":null,"take,takeCount":null,parameters:function(e){return L(e)?void 0:e},"inlineCount,inlineCountEnabled":!1,"noTracking,noTrackingEnabled":!1,queryOptions:null})},u.fromEntities=function(e){lt(e,"entities").isEntity().or().isNonEmptyArray().isEntity().check(),Array.isArray(e)||(e=st(arguments));var t=e[0],n=t.entityType;if(e.some(function(e){return e.entityType!==n}))throw new Error("All 'fromEntities' must be the same type; at least one is not of type "+n.name);var r=new qt(n.defaultResourceName),i=e.map(function(e){return a(e)}),o=Lt.or(i);r=r.where(o);var s=t.entityAspect.entityManager;return s&&(r=r.using(s)),r},u.fromEntityKey=function(e){lt(e,"entityKey").isInstanceOf(_t).check();var t=new qt(e.entityType.defaultResourceName),n=o(e);return t=t.where(n).toType(e.entityType)},u.fromEntityNavigation=function(e,t){lt(e,"entity").isEntity().check();var n=e.entityType._checkNavProperty(t),r=new qt(n.entityType.defaultResourceName),i=s(e,n);r=r.where(i);var a=e.entityAspect.entityManager;return a?r.using(a):r},c._getFromEntityType=function(e,t){var n=this.fromEntityType;if(n)return n;var r=this.resourceName;if(!r)throw new Error("There is no resourceName for this query");if(e.isEmpty()){if(t)throw new Error("There is no metadata available for this query. Are you querying the local cache before you've fetched metadata?");return null}var i=e.getEntityTypeNameForResourceName(r);if(n=i?e._getEntityType(i):this._getToEntityType(e,!0),!n){if(t)throw new Error(G("Cannot find an entityType for resourceName: '%1'.  Consider adding an 'EntityQuery.toType' call to your query or calling the MetadataStore.setEntityTypeForResourceName method to register an entityType for this resourceName.",r));return null}return this.fromEntityType=n,n},c._getToEntityType=function(e,t){return this.resultEntityType instanceof Dt?this.resultEntityType:this.resultEntityType?(this.resultEntityType=e._getEntityType(this.resultEntityType,!1),this.resultEntityType):t?null:!this.selectClause&&this._getFromEntityType(e,!1)},c._toUri=function(e){var t=At.resolve([e.dataService]);return t.uriBuilder.buildUri(this,e.metadataStore)},u}(),Ut=function(){var e=new ht("FilterQueryOp");return e.Equals=e.addSymbol({operator:"eq"}),e.NotEquals=e.addSymbol({operator:"ne"}),e.GreaterThan=e.addSymbol({operator:"gt"}),e.LessThan=e.addSymbol({operator:"lt"}),e.GreaterThanOrEqual=e.addSymbol({operator:"ge"}),e.LessThanOrEqual=e.addSymbol({operator:"le"}),e.Contains=e.addSymbol({operator:"contains"}),e.StartsWith=e.addSymbol({operator:"startswith"}),e.EndsWith=e.addSymbol({operator:"endswith"}),e.Any=e.addSymbol({operator:"any"}),e.All=e.addSymbol({operator:"all"}),e.IsTypeOf=e.addSymbol({operator:"isof"}),e.resolveSymbols(),e}(),zt=(function(){var e=new ht("BooleanQueryOp");return e.And=e.addSymbol({operator:"and"}),e.Or=e.addSymbol({operator:"or"}),e.Not=e.addSymbol({operator:"not"}),e.resolveSymbols(),e}(),function(){var e=function(e,t){if(e.length>1){if(e[0]instanceof zt)return void(this.items=Array.prototype.concat.apply(e[0].items,e.slice(1).map(s("items"))));var r=e.map(function(e){return new n(e,t)})}else var r=[new n(e[0],t)];this.items=r},t=e.prototype;t.validate=function(e){null==e||e.isAnonymous||this.items.forEach(function(t){t.validate(e)})},t.getComparer=function(e){var t=this.items.map(function(t){return t.getComparer(e)});return function(e,n){for(var r=0;r<t.length;r++){var i=t[r](e,n);if(0!==i)return i}return 0}},t.toJSONExt=function(e){return this.items.map(function(t){return e.propertyPathFn(t.propertyPath)+(t.isDesc?" desc":"")})};var n=function(e,t){if("string"!=typeof e)throw new Error("propertyPath is not a string");e=e.trim();var n=e.split(" ");if(n.length>1&&t!==!0&&t!==!1&&(t=U(n[1].toLowerCase(),"desc"),!t)){var r=U(n[1].toLowerCase(),"asc");if(!r)throw new Error("the second word in the propertyPath must begin with 'desc' or 'asc'")}this.propertyPath=n[0],this.isDesc=t},r=n.prototype;return r.validate=function(e){null==e||e.isAnonymous||(this.lastProperty=e.getProperty(this.propertyPath,!0))},r.getComparer=function(e){if(this.lastProperty||this.validate(e),this.lastProperty)var t=this.lastProperty.dataType,n=this.lastProperty.parentType.metadataStore.localQueryComparisonOptions.isCaseSensitive;var r=this.propertyPath,i=this.isDesc;return function(e,a){var o=it(e,r),s=it(a,r),u=t||o&&Ot.fromValue(o)||Ot.fromValue(s);if(u===Ot.String)n?(o=o||"",s=s||""):(o=(o||"").toLowerCase(),s=(s||"").toLowerCase());else{var p=Ot.getComparableFn(u);o=p(o),s=p(s)}return o===s?0:o>s||void 0===s?i?-1:1:i?1:-1}},e}()),Gt=function(){var e=function(e){this.propertyPaths=e,this._pathNames=e.map(function(e){return e.replace(".","_")})},t=e.prototype;return t.validate=function(e){null==e||e.isAnonymous||this.propertyPaths.forEach(function(t){e.getProperty(t,!0)})},t.toFunction=function(){var e=this;return function(t){var n={};return e.propertyPaths.forEach(function(r,i){n[e._pathNames[i]]=it(t,r)}),n}},t.toJSONExt=function(e){return this.propertyPaths.map(function(t){return e.propertyPathFn(t)})},e}(),$t=function(){var e=function(e){this.propertyPaths=e},t=e.prototype;return t.toJSONExt=function(e){return this.propertyPaths.map(function(t){return e.propertyPathFn(t)})},e}();at.FilterQueryOp=Ut,at.EntityQuery=qt,at.OrderByClause=zt;var Jt=function(){var e=new ht("MergeStrategy");return e.PreserveChanges=e.addSymbol(),e.OverwriteChanges=e.addSymbol(),e.SkipMerge=e.addSymbol(),e.Disallowed=e.addSymbol(),e.resolveSymbols(),e}(),Qt=function(){var e=new ht("FetchStrategy");return e.FromServer=e.addSymbol(),e.FromLocalCache=e.addSymbol(),e.resolveSymbols(),e}(),Zt=function(){function e(e,t){return t&&ft(t).whereParam("fetchStrategy").isEnumOf(Qt).isOptional().whereParam("mergeStrategy").isEnumOf(Jt).isOptional().whereParam("includeDeleted").isBoolean().isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="QueryOptions",t.resolve=function(e){return new Zt(h(e,["fetchStrategy","mergeStrategy","includeDeleted"]))},t.defaultInstance=new t({fetchStrategy:Qt.FromServer,mergeStrategy:Jt.PreserveChanges,includeDeleted:!1}),n.using=function(t){if(!t)return this;var n=new Zt(this);return Jt.contains(t)?t={mergeStrategy:t}:Qt.contains(t)&&(t={fetchStrategy:t}),e(n,t)},n.setAsDefault=function(){return l(this,t)},n.toJSON=function(){return y(this,{fetchStrategy:null,mergeStrategy:null,includeDeleted:!1})},t.fromJSON=function(e){return new Zt({fetchStrategy:Qt.fromName(e.fetchStrategy),mergeStrategy:Jt.fromName(e.mergeStrategy),includeDeleted:e.includeDeleted===!0})},t}();at.QueryOptions=Zt,at.FetchStrategy=Qt,at.MergeStrategy=Jt;var Ht=function(){function e(e){if(e){if(1===e.length){var t=e[0];return function(e){return!!e&&e.entityAspect.entityState===t}}return function(t){return!!t&&-1!==e.indexOf(t.entityAspect.entityState)}}return function(e){return!!e}}var t=function(e,t){this.entityManager=e,this.entityType=t,this.entityType.isFrozen=!0,this._indexMap={},this._entities=[],this._emptyIndexes=[]},n=t.prototype;return n.attachEntity=function(e,t,n){var r=e.entityAspect;r._initialized||this.entityType._initializeInstance(e),delete r._initialized;var i=r.getKey()._keyInGroup,a=this._indexMap[i];if(a>=0){var o=this._entities[a],s=o.entityAspect.entityState,u=s.isUnchanged();if(o===e)r.entityState=t;else{if(n===Jt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' does not allow you to attach an entity when an entity with the same key is already attached: "+r.getKey());if(n===Jt.OverwriteChanges||n===Jt.PreserveChanges&&u){var p=this.entityManager.helper.unwrapInstance(e);this.entityType._updateTargetFromRaw(o,p,It.getRawValueFromServer),o.entityAspect.setEntityState(t)}}return o}return 0===this._emptyIndexes.length?a=this._entities.push(e)-1:(a=this._emptyIndexes.pop(),this._entities[a]=e),this._indexMap[i]=a,r.entityState=t,r.entityGroup=this,r.entityManager=this.entityManager,e},n.detachEntity=function(e){var t=e.entityAspect,n=t.getKey()._keyInGroup,r=this._indexMap[n];if(void 0===r)throw new Error("internal error - entity cannot be found in group");return delete this._indexMap[n],this._emptyIndexes.push(r),this._entities[r]=null,e},n.findEntityByKey=function(e){var t;t=e instanceof _t?e._keyInGroup:_t.createKeyString(e);var n=this._indexMap[t];return void 0!==n?this._entities[n]:null},n.hasChanges=function(){for(var e=this._entities,t=bt.Unchanged,n=0,r=e.length;r>n;n++){var i=e[n];if(i&&i.entityAspect.entityState!==t)return!0}return!1},n.getChanges=function(){for(var e=this._entities,t=bt.Unchanged,n=[],r=0,i=e.length;i>r;r++){var a=e[r];a&&a.entityAspect.entityState!==t&&n.push(a)}return n},n.getEntities=function(t){var n=e(t);return this._entities.filter(n)},n._checkOperation=function(e){return this._entities.forEach(function(t){t&&t.entityAspect._checkOperation(e)}),this},n._clear=function(){this._entities.forEach(function(e){null!=e&&e.entityAspect._detach()}),this._entities=null,this._indexMap=null,this._emptyIndexes=null},n._updateFkVal=function(e,t,n){var r=e.name;this._entities.forEach(function(e){null!=e&&e.getProperty(r)==t&&e.setProperty(r,n)})},n._fixupKey=function(e,t){var n=this._indexMap[e];if(void 0===n)throw new Error("Internal Error in key fixup - unable to locate entity");var r=this._entities[n],i=r.entityType.keyProperties[0].name;r.setProperty(i,t),delete r.entityAspect.hasTempKey,delete this._indexMap[e],this._indexMap[t]=n},n._replaceKey=function(e,t){var n=this._indexMap[e._keyInGroup];delete this._indexMap[e._keyInGroup],this._indexMap[t._keyInGroup]=n},t}(),Yt=function(){function e(e,t,n){var r=n?Zt.defaultInstance:e.queryOptions,i=n?Xt.defaultInstance:e.saveOptions,a=n?St.defaultInstance:e.validationOptions,o=ft(t).whereParam("serviceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(At).whereParam("queryOptions").isInstanceOf(Zt).isOptional().withDefault(r).whereParam("saveOptions").isInstanceOf(Xt).isOptional().withDefault(i).whereParam("validationOptions").isInstanceOf(St).isOptional().withDefault(a).whereParam("keyGeneratorCtor").isFunction().isOptional();n&&(o=o.whereParam("metadataStore").isInstanceOf(Ft).isOptional().withDefault(new Ft)),o.applyAll(e),c(e.queryOptions,r),c(e.saveOptions,i),c(e.validationOptions,a),t.serviceName&&(e.dataService=new At({serviceName:e.serviceName})),e.serviceName=e.dataService&&e.dataService.serviceName,e.keyGeneratorCtor=e.keyGeneratorCtor||Kt,(n||t.keyGeneratorCtor)&&(e.keyGenerator=new e.keyGeneratorCtor)}function r(e,t){lt(t,"query").isInstanceOf(qt).check();var n=e.metadataStore,r=t._getFromEntityType(n,!0),i=$(e,r),a=t.wherePredicate&&t.wherePredicate.toFunction({entityType:r}),o=Zt.resolve([t.queryOptions,e.queryOptions,Zt.defaultInstance]),s=o.includeDeleted===!0,u=function(e){return e&&(s||!e.entityAspect.entityState.isDeleted())&&(a?a(e):!0)},p=[];i.forEach(function(e){p.push.apply(p,e._entities.filter(u))});var c=t.orderByClause&&t.orderByClause.getComparer(r);if(c&&p.sort(c),t.inlineCountEnabled)var l=p.length;var y=t.skipCount;y&&(p=p.slice(y));var f=t.takeCount;f&&(p=p.slice(0,f));var h=t.selectClause;if(h){var d=h.toFunction();p=p.map(d)}return{results:p,inlineCount:l}}function i(e){e.forEach(function(e){var n=[],r=e.entityAspect;t(r._validationErrors,function(e,t){t.isServerError&&n.push(e)}),0!==n.length&&r._processValidationOpAndPublish(function(){n.forEach(function(e){r._removeValidationError(e)})})})}function a(e){var n=[];return e.forEach(function(e){t(e.entityAspect._validationErrors,function(t,r){var i=p({entity:e,errorName:r.validator.name},r,["errorMessage","propertyName","isServerError"]);n.push(i)})}),n}function o(e,t){var n=t.entityErrors;if(n){var r=e.entityManager,i=r.metadataStore;t.entityErrors=n.map(function(e){var t=null;if(e.keyValues){var n=i._getEntityType(e.entityTypeName),a=new _t(n,e.keyValues);t=r.findEntityByKey(a)}if(t){var o=e.propertyName?{propertyName:e.propertyName,property:n.getProperty(e.propertyName)}:{},s=wt.getKey(e.errorName||e.errorMessage,e.propertyName),u=new wt(null,o,e.errorMessage,s);u.isServerError=!0,t.entityAspect.addValidationError(u)}var c=p({entity:t,isServerError:!0},e,["errorName","errorMessage","propertyName"]);return c})}}function s(e,t){var n,r=g(e,t),i=r.entityKey,a=0===r.remainingArgs.length?!1:!!r.remainingArgs[0],o=!1;return a&&(n=e.getEntityByKey(i),o=!!n,o&&!e.queryOptions.includeDeleted&&n.entityAspect.entityState.isDeleted()&&(n=null,o=e.queryOptions.mergeStrategy!==Jt.OverwriteChanges)),o?xt.resolve({entity:n,entityKey:i,fromCache:!0}):qt.fromEntityKey(i).using(e).execute().then(function(e){return n=0===e.results.length?null:e.results[0],xt.resolve({entity:n,entityKey:i,fromCache:!1})})}function l(e,t){return lt(t,"entityTypes").isString().isOptional().or().isNonEmptyArray().isString().or().isInstanceOf(Dt).or().isNonEmptyArray().isInstanceOf(Dt).check(),"string"==typeof t?t=e.metadataStore._getEntityType(t,!1):Array.isArray(t)&&"string"==typeof t[0]&&(t=t.map(function(t){return e.metadataStore._getEntityType(t,!1)})),t}function y(e,t){var n,r=I(e,t);return r.forEach(function(e){if(e){var t=e.getChanges();n?n.push.apply(n,t):n=t}}),n||[]}function h(e,t,n){var r,i=I(e,t);return i.forEach(function(e){if(e){var t=e.getEntities(n);r?r.push.apply(r,t):r=t}}),r||[]}function g(e,t){try{if(t[0]instanceof _t)return{entityKey:t[0],remainingArgs:st(t,1)};if(t.length>=2){var n="string"==typeof t[0]?e.metadataStore._getEntityType(t[0],!1):t[0];return{entityKey:new _t(n,t[1]),remainingArgs:st(t,2)}}}catch(r){}throw new Error("Must supply an EntityKey OR an EntityType name or EntityType followed by a key value or an array of key values.")}function E(e,t){e.forEach(function(e){e.entityAspect.isBeingSaved=t})}function P(e,n){var r,i=n&&n[0];if(i)if(r={},i.entityType)n.forEach(function(e){if(e.entityAspect.entityState==bt.Detached)throw new Error("Unable to export an entity with an EntityState of 'Detached'");var t=r[e.entityType.name];t||(t={},t.entityType=e.entityType,t._entities=[],r[e.entityType.name]=t),t._entities.push(e)});else{var a=l(e,n);a.forEach(function(t){var n=e._entityGroupMap[t.name];n&&n._entities.length&&(r[t.name]=n)})}else r=e._entityGroupMap;var o=[],s={};return t(r,function(e,t){s[e]=N(t,o)}),{entityGroupMap:s,tempKeys:o}}function N(e,t){var n={},r=e.entityType,i=r.dataProperties,a=W(r),o=[];return e._entities.forEach(function(e){if(e){var n=_(e,i,a,t);o.push(n)}}),n.entities=o,n}function _(e,t,n,r){var i={};t.forEach(function(t){var r=t.name,a=e.getProperty(r);if(null!=a||null!=t.defaultValue){if(a&&t.isComplexProperty){var o=t.dataType.dataProperties;a=m(a,function(e){return _(e,o,n)})}else a=n?n(t,a):a,t.isUnmapped&&(a=f(a));void 0!==a&&(i[r]=a)}});var a,o;if(e.entityAspect){a=e.entityAspect;var s=a.entityState;o={tempNavPropNames:A(a,r),entityState:s.name},a.extraMetadata&&(o.extraMetadata=a.extraMetadata),(s.isModified()||s.isDeleted())&&(o.originalValuesMap=a.originalValues),i.entityAspect=o}else a=e.complexAspect,o={},a.originalValues&&!L(a.originalValues)&&(o.originalValuesMap=a.originalValues),i.complexAspect=o;return i}function A(e,t){var n=e.entity;e.hasTempKey&&t.push(e.getKey().toJSON());var r;return n.entityType.navigationProperties.forEach(function(e){if(e.relatedDataProperties){var t=n.getProperty(e.name);t&&t.entityAspect.hasTempKey&&(r=r||[],r.push(e.name))
  }}),r}function x(e,t,n){var r=n.tempKeyMap,i=e.entityType,a=n.mergeStrategy,o=null,s=e.entityManager,u=s.entityChanged,p=[],c=It.getRawValueFromClient;return t.entities.forEach(function(t){var n=t.entityAspect,l=i.getEntityKeyFromRawEntity(t,c),y=bt.fromName(n.entityState);if(!y||y==bt.Detached)throw new Error("Only entities with a non detached entity state may be imported.");var f=y.isAdded()&&F(r,l);if(o=f?null:e.findEntityByKey(l))if(a===Jt.SkipMerge);else{if(a===Jt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+l.toString()+" from being merged");var h=o.entityAspect.entityState,d=h.isUnchanged();(a===Jt.OverwriteChanges||d)&&(i._updateTargetFromRaw(o,t,c),o.entityAspect.setEntityState(y),u.publish({entityAction:Pt.MergeOnImport,entity:o}))}else o=i._createInstanceCore(),i._updateTargetFromRaw(o,t,c),f&&(o.entityAspect.hasTempKey=!0,o.setProperty(i.keyProperties[0].name,f.values[0]),n.tempNavPropNames&&n.tempNavPropNames.forEach(function(e){var t=i.getNavigationProperty(e),n=t.relatedDataProperties[0].name,a=o.getProperty(n),s=new _t(t.entityType,[a]),u=F(r,s);o.setProperty(n,u.values[0])})),o=e.attachEntity(o,y),u.publish({entityAction:Pt.AttachOnImport,entity:o}),y.isUnchanged()||s._notifyStateChange(o,!0);p.push(o)}),p}function F(e,t){var n=e[t.toString()];if(n)return n;var r=t._subtypes;if(!r)return null;for(var i=0,a=r.length;a>i;i++)if(n=e[t.toString(r[i])])return n;return null}function M(e,t,n){return e=e.then(function(e){return t&&t(e),xt.resolve(e)},function(e){return n&&n(e),xt.reject(e)})}function D(e,t){var n;return n=t?t.filter(function(t){if(t.entityAspect.entityManager!==e)throw new Error("Only entities in this entityManager may be saved");return!t.entityAspect.entityState.isDetached()}):e.getChanges()}function k(e,t){e._inKeyFixup=!0,t.forEach(function(t){var n=e._entityGroupMap[t.entityTypeName];if(!n)throw new Error("Unable to locate the following fully qualified EntityType name: "+t.entityTypeName);n._fixupKey(t.tempValue,t.realValue)}),e._inKeyFixup=!1}function I(e,t){var n=e._entityGroupMap;return t?d(t).map(function(e){if(e instanceof Dt)return n[e.name];throw new Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null")}):u(n)}function V(e,t){var n=t.entityAspect.getKey(),r=S(t.entityType.keyProperties,n.values,function(e,t){return e.defaultValue===t?e:null}).filter(function(e){return null!==e});if(r.length)if(t.entityType.autoGeneratedKeyType!==Rt.None)e.generateTempKeyValue(t);else if(r.length===n.values.length)throw new Error("Cannot attach an object of type  ("+t.entityType.name+") to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'")}function R(e,t){return t?(t=d(t),t.forEach(function(e){if(!bt.contains(e))throw new Error("The EntityManager.getChanges() 'entityStates' parameter must either be null, an entityState or an array of entityStates")}),t):null}function K(e,t,n,r){var i=t.entityType.navigationProperties;i.forEach(function(i){var a=t.getProperty(i.name);if(i.isScalar){if(!a)return;e.attachEntity(a,n,r)}else a.forEach(function(t){e.attachEntity(t,n,r)})})}function j(e,t,i,a){try{var o,s=e.metadataStore;if(s.isEmpty()&&a.hasServerMetadata)throw new Error("cannot execute _executeQueryCore until metadataStore is populated.");if(i.fetchStrategy===Qt.FromLocalCache)try{var u=r(e,t);return xt.resolve({results:u.results,entityManager:e,inlineCount:u.inlineCount,query:t})}catch(p){return xt.reject(p)}var c=new Wt({query:t,entityManager:e,dataService:a,mergeOptions:{mergeStrategy:i.mergeStrategy,noTracking:!!t.noTrackingEnabled,includeDeleted:i.includeDeleted}}),l=e.validationOptions.validateOnQuery;return a.adapterInstance.executeQuery(c).then(function(r){var i=O(function(){var t={isLoading:e.isLoading};return e.isLoading=!0,e._pendingPubs=[],t},function(n){e.isLoading=n.isLoading,e._pendingPubs.forEach(function(e){e()}),e._pendingPubs=null,e._hasChangesAction&&e._hasChangesAction(),t=null,c=null,n.error&&xt.reject(n.error)},function(){var i=a.jsonResultsAdapter.extractResults(r);i=d(i),o=c.visitAndMerge(i,{nodeType:"root"}),l&&o.forEach(function(e){e.entityAspect&&e.entityAspect.validateEntity()}),c.processDeferred(),B(o,t);var s=n(c.refMap);return{results:o,query:t,entityManager:e,httpResponse:r.httpResponse,inlineCount:r.inlineCount,retrievedEntities:s}});return xt.resolve(i)},function(n){return n&&(n.query=t,n.entityManager=e),xt.reject(n)})}catch(p){return p&&(p.query=t),xt.reject(p)}}function B(e,t){if(!t.noTrackingEnabled){var n=t.expandClause;null!=n&&n.propertyPaths.forEach(function(t){var n=t.split(".");q(e,n)})}}function q(e,t){var n=t[0];e.forEach(function(e){var r=e.entityAspect;if(r&&(r._markAsLoaded(n),1!==t.length)){var i=e.getProperty(n);i&&(i.arrayChanged||(i=[i]),q(i,t.slice(1)))}})}function U(e){var t=e.filter(function(e){return e.entityAspect.isBeingSaved=!0,e.entityAspect.entityState.isModified()&&e.entityType.concurrencyProperties.length>0});0!==t.length&&t.forEach(function(e){e.entityType.concurrencyProperties.forEach(function(t){z(e,t)})})}function z(e,t){if(!e.entityAspect.originalValues[t.name]){var n=e.getProperty(t.name);if(n||(n=t.dataType.defaultValue),t.dataType.isNumeric)e.setProperty(t.name,n+1);else if(t.dataType.isDate){for(var r=new Date,i=new Date;r.getTime()===i.getTime();)i=new Date;e.setProperty(t.name,i)}else{if(t.dataType!==Ot.Guid){if(t.dataType===Ot.Binary)return;throw new Error("Unable to update the value of concurrency property before saving: "+t.name)}e.setProperty(t.name,C())}}}function G(e,t){var n=e._entityGroupMap[t.name];return n||(n=new Ht(e,t),e._entityGroupMap[t.name]=n),n}function $(e,t){var n=t.getSelfAndSubtypes();return n.map(function(t){return G(e,t)})}function J(e,t){var n={},r=e.entityType||e.complexType,i=W(r),a={};return r.dataProperties.forEach(function(r){if(r.isComplexProperty)n[r.nameOnServer]=m(e.getProperty(r.name),function(e){return J(e,t)});else{var o=e.getProperty(r.name);if(o=t?t(r,o):o,void 0===o)return;o=i?i(r,o):o,void 0!==o&&(r.isUnmapped?a[r.nameOnServer]=f(o):n[r.nameOnServer]=o)}}),L(a)||(n.__unmapped=a),n}function Q(e,n,r){var i=e.entityType||e.complexType,a=e.entityAspect||e.complexAspect,o=n.namingConvention.clientPropertyNameToServer,s={};return t(a.originalValues,function(e,t){var n=i.getProperty(e);t=r?r(n,t):t,void 0!==t&&(s[o(e,n)]=t)}),i.complexProperties.forEach(function(t){var i=e.getProperty(t.name);if(t.isScalar){var a=Q(i,n,r);L(a)||(s[o(t.name,t)]=a)}else{var u=i.map(function(e){return Q(e,n,r)});s[o(t.name,t)]=u}}),s}function Z(e,n,r){var i=e.entityType,a=W(i),o=n.namingConvention.clientPropertyNameToServer,s={};return t(e.entityAspect.originalValues,function(t){var n=i.getProperty(t),u=e.getProperty(t);u=r?r(n,u):u,void 0!==u&&(u=a?a(n,u):u,void 0!==u&&(s[o(t,n)]=u))}),i.complexProperties.forEach(function(t){if(H(e,t)){var n=e.getProperty(t.name);s[o(t.name,t)]=m(n,function(e){return J(e,r)})}}),s}function H(e,t){var n=e.getProperty(t.name);return t.isScalar?Y(n):n._origValues?!0:n.some(function(e){return Y(e)})}function Y(e){return L(e.complexAspect.originalValues)?e.complexType.complexProperties.some(function(t){return H(e,t)}):!0}function W(e){return e.serializerFn||e.metadataStore&&e.metadataStore.serializerFn}function X(){this.map={}}var et=function(t){if(arguments.length>1)throw new Error("The EntityManager ctor has a single optional argument that is either a 'serviceName' or a configuration object.");0===arguments.length?t={serviceName:""}:"string"==typeof t&&(t={serviceName:t}),e(this,t,!0),this.entityChanged=new dt("entityChanged",this),this.validationErrorsChanged=new dt("validationErrorsChanged",this),this.hasChangesChanged=new dt("hasChangesChanged",this),this.clear()},tt=et.prototype;return tt._$typeName="EntityManager",dt.bubbleEvent(tt,null),tt.setProperties=function(t){e(this,t,!1)},tt.createEntity=function(e,t,n,r){lt(e,"entityType").isString().or().isInstanceOf(Dt).check(),lt(n,"entityState").isEnumOf(bt).isOptional().check(),lt(r,"mergeStrategy").isEnumOf(Jt).isOptional().check(),"string"==typeof e&&(e=this.metadataStore._getEntityType(e)),n=n||bt.Added;var i;return b(this,"isLoading",!0,function(){i=e.createEntity(t)}),n!==bt.Detached&&(i=this.attachEntity(i,n,r)),i},et.importEntities=function(e,t){var n=new Yt;return n.importEntities(e,t),n},tt.acceptChanges=function(){this.getChanges().map(function(e){return e.entityAspect._checkOperation("acceptChanges")}).forEach(function(e){e.acceptChanges()})},tt.exportEntities=function(e,t){lt(e,"entities").isArray().isEntity().or().isNonEmptyArray().isInstanceOf(Dt).or().isNonEmptyArray().isString().or().isOptional().check(),lt(t,"config").isObject().or().isBoolean().or().isOptional().check(),null==t?t={includeMetadata:!0,asString:!0}:"boolean"==typeof t&&(t={includeMetadata:t,asString:!0}),ft(t).whereParam("asString").isBoolean().isOptional().withDefault(!0).whereParam("includeMetadata").isBoolean().isOptional().withDefault(!0).applyAll(t);var n=P(this,e),r=p({},n,["tempKeys","entityGroupMap"]);t.includeMetadata?(r=p(r,this,["dataService","saveOptions","queryOptions","validationOptions"]),r.metadataStore=this.metadataStore.exportMetadata()):(r.metadataVersion=at.metadataVersion,r.metadataStoreName=this.metadataStore.name);var i=t.asString?JSON.stringify(r,null,mt.stringifyPad):r;return i},tt.importEntities=function(e,n){n=n||{},ft(n).whereParam("mergeStrategy").isEnumOf(Jt).isOptional().withDefault(this.queryOptions.mergeStrategy).whereParam("metadataVersionFn").isFunction().isOptional().applyAll(n);var r=this,i="string"==typeof e?JSON.parse(e):e;i.metadataStore?(this.metadataStore.importMetadata(i.metadataStore),this.dataService=i.dataService&&At.fromJSON(i.dataService)||new At({serviceName:i.serviceName}),this.saveOptions=new Xt(i.saveOptions),this.queryOptions=Zt.fromJSON(i.queryOptions),this.validationOptions=new St(i.validationOptions)):n.metadataVersionFn&&n.metadataVersionFn({metadataVersion:i.metadataVersion,metadataStoreName:i.metadataStoreName});var a={};i.tempKeys.forEach(function(e){var t=_t.fromJSON(e,r.metadataStore);a[t.toString()]=new _t(t.entityType,r.keyGenerator.generateTempKeyValue(t.entityType,t.values[0]))});var o=[];return n.tempKeyMap=a,O(function(){r._pendingPubs=[]},function(){r._pendingPubs.forEach(function(e){e()}),r._pendingPubs=null,r._hasChangesAction&&r._hasChangesAction()},function(){t(i.entityGroupMap,function(e,t){var i=r.metadataStore._getEntityType(e,!0),a=G(r,i),s=x(a,t,n);Array.prototype.push.apply(o,s)}),o.forEach(function(e){e.entityAspect.entityState.isDeleted()||r._linkRelatedEntities(e)})}),{entities:o,tempKeyMapping:a}},tt.clear=function(){n(this._entityGroupMap,function(e,t){return t._checkOperation()}).forEach(function(e){e._clear()}),this._entityGroupMap={},this._unattachedChildrenMap=new X,this.keyGenerator=new this.keyGeneratorCtor,this.entityChanged.publish({entityAction:Pt.Clear}),this._setHasChanges(!1)},tt.createEmptyCopy=function(){var e=new et(p({},this,["dataService","metadataStore","queryOptions","saveOptions","validationOptions","keyGeneratorCtor"]));return e},tt.addEntity=function(e){return this.attachEntity(e,bt.Added)},tt.attachEntity=function(e,t,n){if(lt(e,"entity").isRequired().check(),this.metadataStore._checkEntityType(e),t=lt(t,"entityState").isEnumOf(bt).isOptional().check(bt.Unchanged),n=lt(n,"mergeStrategy").isEnumOf(Jt).isOptional().check(Jt.Disallowed),e.entityType.metadataStore!==this.metadataStore)throw new Error("Cannot attach this entity because the EntityType ("+e.entityType.name+") and MetadataStore associated with this entity does not match this EntityManager's MetadataStore.");var r=e.entityAspect;if(r){if(r._inProcessEntity)return r._inProcessEntity}else r=new Tt(e);var i=r.entityManager;if(i){if(i===this)return e;throw new Error("This entity already belongs to another EntityManager")}var a,o=this;return b(this,"isLoading",!0,function(){t.isAdded()&&V(o,e),a=o._attachEntityCore(e,t,n),r._inProcessEntity=a;try{K(o,e,t,n)}finally{r._inProcessEntity=null}}),this.validationOptions.validateOnAttach&&a.entityAspect.validateEntity(),t.isUnchanged()||this._notifyStateChange(a,!0),this.entityChanged.publish({entityAction:Pt.Attach,entity:a}),a},tt.detachEntity=function(e){lt(e,"entity").isEntity().check();var t=e.entityAspect;if(!t)return!1;if(t.entityManager!==this)throw new Error("This entity does not belong to this EntityManager.");return t.setDetached()},tt.fetchMetadata=function(e,t,n){"function"==typeof e?(n=t,t=e,e=null):(lt(e,"dataService").isInstanceOf(At).isOptional().check(),lt(t,"callback").isFunction().isOptional().check(),lt(n,"errorCallback").isFunction().isOptional().check());var r=this.metadataStore.fetchMetadata(e||this.dataService);return M(r,t,n)},tt.executeQuery=function(e,t,n){lt(e,"query").isInstanceOf(qt).or().isString().check(),lt(t,"callback").isFunction().isOptional().check(),lt(n,"errorCallback").isFunction().isOptional().check();var r,i=Zt.resolve([e.queryOptions,this.queryOptions,Zt.defaultInstance]),a=At.resolve([e.dataService,this.dataService]);if(!a.hasServerMetadata||this.metadataStore.hasMetadataFor(a.serviceName))r=j(this,e,i,a);else{var o=this;r=this.fetchMetadata(a).then(function(){return j(o,e,i,a)})}return M(r,t,n)},tt.executeQueryLocally=function(e){return r(this,e).results},tt.saveChanges=function(e,t,n,r){function a(e){var t=d.entityManager;E(p,!1);e.entities=d.processSavedEntities(e);return t._setHasChanges(null),n&&n(e),xt.resolve(e)}function s(e){var t=e.entities;if(0===t.length)return[];var n=e.keyMappings,r=d.entityManager;return k(r,n),b(r,"isLoading",!0,function(){var e=new Wt({query:null,entityManager:r,mergeOptions:{mergeStrategy:Jt.OverwriteChanges},dataService:h});t=e.visitAndMerge(t,{nodeType:"root"})}),t}function u(e){return E(p,!1),o(d,e),r&&r(e),xt.reject(e)}lt(e,"entities").isOptional().isArray().isEntity().check(),lt(t,"saveOptions").isInstanceOf(Xt).isOptional().check(),lt(n,"callback").isFunction().isOptional().check(),lt(r,"errorCallback").isFunction().isOptional().check(),t=t||this.saveOptions||Xt.defaultInstance;var p=D(this,e);if(0===p.length){var c={entities:[],keyMappings:[]};return n&&n(c),xt.resolve(c)}if(!t.allowConcurrentSaves){var l=p.some(function(e){return e.entityAspect.isBeingSaved});if(l){var y=new Error("Concurrent saves not allowed - SaveOptions.allowConcurrentSaves is false");return r&&r(y),xt.reject(y)}}i(p);var f=this.saveChangesValidateOnClient(p);if(f)return r&&r(f),xt.reject(f);var h=At.resolve([t.dataService,this.dataService]),d={entityManager:this,dataService:h,processSavedEntities:s,resourceName:t.resourceName||this.saveOptions.resourceName||"SaveChanges"},m={entities:p,saveOptions:t};try{return U(p),h.adapterInstance.saveChanges(d,m).then(a).then(null,u)}catch(y){return E(p,!1),r&&r(y),xt.reject(y)}},tt.saveChangesValidateOnClient=function(e){if(this.validationOptions.validateOnSave){var t=e.filter(function(e){var t=e.entityAspect,n=t.entityState.isDeleted()||t.validateEntity();return!n});if(t.length>0){var n=new Error("Client side validation errors encountered - see the entityErrors collection on this object for more detail");return n.entityErrors=a(t),n}}return null},tt._findEntityGroup=function(e){return this._entityGroupMap[e.name]},tt.getEntityByKey=function(){var e=g(this,arguments).entityKey,t=e._subtypes||[e.entityType],n=null;return t.some(function(t){var r=this._findEntityGroup(t);return n=r&&r.findEntityByKey(e)},this),n},tt.fetchEntityByKey=function(){var e=At.resolve([this.dataService]);if(!e.hasServerMetadata||this.metadataStore.hasMetadataFor(e.serviceName))return s(this,arguments);var t=this,n=arguments;return this.fetchMetadata(e).then(function(){return s(t,n)})},tt.findEntityByKey=function(e){return this.getEntityByKey(e)},tt.generateTempKeyValue=function(e){lt(e,"entity").isEntity().check();var t=e.entityType,n=this.keyGenerator.generateTempKeyValue(t),r=t.keyProperties[0];return e.setProperty(r.name,n),e.entityAspect.hasTempKey=!0,n},tt.hasChanges=function(e){return this._hasChanges?void 0===e?this._hasChanges:this._hasChangesCore(e):!1},tt._hasChangesCore=function(e){e=l(this,e);var t=I(this,e);return t.some(function(e){return e&&e.hasChanges()})},tt.getChanges=function(e){return e=l(this,e),y(this,e)},tt.rejectChanges=function(){if(!this._hasChanges)return[];var e=y(this,null),t=e.map(function(e){return e.entityAspect._checkOperation("rejectChanges")});return this._hasChanges=!1,t.forEach(function(e){e.rejectChanges()}),this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}),e},tt.getEntities=function(e,t){return e=l(this,e),lt(t,"entityStates").isOptional().isEnumOf(bt).or().isNonEmptyArray().isEnumOf(bt).check(),t=t&&R(this,t),h(this,e,t)},tt._notifyStateChange=function(e,t){var n={entityAction:Pt.EntityStateChange,entity:e};if(t)this._hasChanges||this._setHasChanges(!0);else if(this._hasChanges){if(this.isLoading)return void(this._hasChangesAction=this._hasChangesAction||function(){this._setHasChanges(null),this.entityChanged.publish(n)}.bind(this));this._setHasChanges(null)}this.entityChanged.publish(n)},tt._setHasChanges=function(e){null==e&&(e=this._hasChangesCore());var t=this._hasChanges;this._hasChanges=e,e!=t&&this.hasChangesChanged.publish({entityManager:this,hasChanges:e}),this._hasChangesAction=null},tt._linkRelatedEntities=function(e){var t=this,n=e.entityAspect;b(t,"isLoading",!0,function(){var r=t._unattachedChildrenMap,i=n.getKey(),a=r.getTuples(i);a&&a.slice(0).forEach(function(t){var n,a,o=t.children.filter(function(e){return e.entityAspect.entityState!==bt.Detached}),s=t.navigationProperty;if(s.inverse)if(n=s,a=s.inverse,a.isScalar){var u=o[0];e.setProperty(a.name,u),u.setProperty(n.name,e)}else{var p=e.getProperty(a.name);o.forEach(function(t){p.push(t),t.setProperty(n.name,e)})}else if(s.isScalar)n=s,o.forEach(function(t){t.setProperty(n.name,e)});else{a=s;var p=e.getProperty(a.name);o.forEach(function(e){p._push(e)})}r.removeChildren(i,n)}),e.entityType.navigationProperties.forEach(function(i){if(i.isScalar){var a=e.getProperty(i.name);if(a)return}var o=n.getParentKey(i);if(o){if(o._isEmpty())return;var s=t.findEntityByKey(o);s?e.setProperty(i.name,s):r.addChild(o,i,e)}}),e.entityType.foreignKeyProperties.forEach(function(n){var i=n.inverseNavigationProperty;if(i){var a=e.getProperty(n.name),o=new _t(i.parentType,[a]),s=t.findEntityByKey(o);s?i.isScalar?s.setProperty(i.name,e):t.isLoading?s.getProperty(i.name)._push(e):s.getProperty(i.name).push(e):r.addChild(o,i,e)}})})},tt._attachEntityCore=function(e,t,n){var r=G(this,e.entityType),i=r.attachEntity(e,t,n);return this._linkRelatedEntities(i),i},tt._updateFkVal=function(e,t,n){var r=this._entityGroupMap[e.parentType.name];r&&r._updateFkVal(e,t,n)},tt.helper={unwrapInstance:J,unwrapOriginalValues:Q,unwrapChangedValues:Z},X.prototype.addChild=function(e,t,n){var r=this.getTuple(e,t);r||(r={navigationProperty:t,children:[]},T(this.map,e.toString()).push(r)),r.children.push(n)},X.prototype.removeChildren=function(e,t){var n=this.getTuples(e);n&&(w(n,function(e){return e.navigationProperty===t}),n.length||delete this.map[e.toString()])},X.prototype.getChildren=function(e,t){var n=this.getTuple(e,t);return n?n.children.filter(function(e){return!e.entityAspect.entityState.isDetached()}):null},X.prototype.getTuple=function(e,t){var n=this.getTuples(e);if(!n)return null;var r=v(n,function(e){return e.navigationProperty===t});return r},X.prototype.getTuples=function(e){for(var t=this.map[e.toString()],n=e.entityType;!t&&n.baseEntityType;){n=n.baseEntityType;var r=e.toString(n);t=this.map[r]}return t},et}();at.EntityManager=Yt;var Wt=function(){function e(e,t,i,o){if(i.ignore||null==t)return null;if(i.nodeRefId){var u=a(e,i.nodeRefId);return"function"==typeof u&&null!=o?void e.deferredFns.push(function(){o(u)}):u}if(i.entityType){var p=i.entityType;return e.mergeOptions.noTracking?(t=n(e,p,t),p.noTrackingFn&&(t=p.noTrackingFn(t,p)),i.nodeId&&(e.refMap[i.nodeId]=t),t):p.isComplexType?n(e,p,t):s(e,t,i)}return i.passThru||"object"!=typeof t||k(t)||(t=r(e,t)),i.nodeId&&(e.refMap[i.nodeId]=t),t}function n(e,t,r){var a={};return t.dataProperties.forEach(function(t){a[t.name]=t.isComplexProperty?m(r[t.nameOnServer],function(r){return n(e,t.dataType,r)}):w(r[t.nameOnServer],t.dataType)}),t.navigationProperties&&t.navigationProperties.forEach(function(t){var n={nodeType:"navProp",navigationProperty:t};i(r[t.nameOnServer],e,n,a,t.name)}),a}function r(e,n){var r=e.metadataStore.namingConvention.serverPropertyNameToClient,a={};return t(n,function(t,n){var o=r(t),s={nodeType:"anonProp",propertyName:o};i(n,e,s,a,o)}),a}function i(t,n,r,i,a){var o=n.jsonResultsAdapter,s=o.visitNode(t,n,r)||{};return t=s.node||t,s.ignore?void 0:s.passThru?t:void(Array.isArray(t)?(r.nodeType=r.nodeType+"Item",i[a]=t.map(function(t,u){return s=o.visitNode(t,n,r)||{},t=s.node||t,e(n,t,s,function(e){i[a][u]=e()})})):i[a]=e(n,t,s,function(e){i[a]=e()}))}function a(e,t){var n=e.refMap[t];return void 0===n?function(){return e.refMap[t]}:n}function o(e,t,n){var r=n._$meta.nodeId;null!=r&&(e.refMap[r]=t)}function s(e,t,n){t._$meta=n;var r=e.entityManager,i=n.entityType;"string"==typeof i&&(i=e.metadataStore._getEntityType(i,!1)),t.entityType=i;var a=e.mergeOptions.mergeStrategy,o=null==e.query,s=i.getEntityKeyFromRawEntity(t,e.rawValueFn),p=r.findEntityByKey(s);if(p){if(o&&p.entityAspect.entityState.isDeleted())return r.detachEntity(p),p;var l=p.entityAspect.entityState;if(a===Jt.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+s.toString()+" from being merged");if(a===Jt.SkipMerge)u(e,p,t);else if(a===Jt.OverwriteChanges||l.isUnchanged()){c(e,p,t),p.entityAspect.wasLoaded=!0,n.extraMetadata&&(p.entityAspect.extraMetadata=n.extraMetadata),p.entityAspect.entityState=bt.Unchanged,p.entityAspect.originalValues={},p.entityAspect.propertyChanged.publish({entity:p,propertyName:null});var y=o?Pt.MergeOnSave:Pt.MergeOnQuery;r.entityChanged.publish({entityAction:y,entity:p}),l.isUnchanged()||r._notifyStateChange(p,!1)}else{if(l==bt.Deleted&&!e.mergeOptions.includeDeleted)return null;u(e,p,t)}}else p=i._createInstanceCore(),c(e,p,t),n.extraMetadata&&(p.entityAspect.extraMetadata=n.extraMetadata),r._attachEntityCore(p,bt.Unchanged,a),p.entityAspect.wasLoaded=!0,r.entityChanged.publish({entityAction:Pt.AttachOnQuery,entity:p});return p}function u(e,t,n){o(e,t,n),n.entityType.navigationProperties.forEach(function(t){t.isScalar?f(e,n,t):h(e,n,t)})}function c(e,t,n){o(e,t,n);var r=t.entityType;r._updateTargetFromRaw(t,n,e.rawValueFn),r.navigationProperties.forEach(function(r){r.isScalar?l(e,r,t,n):y(e,r,t,n)})}function l(e,t,n,r){var i=f(e,r,t);null!=i&&("function"==typeof i?e.deferredFns.push(function(){i=i(),d(i,n,t)}):d(i,n,t))}function y(e,t,n,r){var i=h(e,r,t);if(null!=i){var a=t.inverse;if(a){var o=n.getProperty(t.name);o.wasLoaded=!0,i.forEach(function(t){"function"==typeof t?e.deferredFns.push(function(){t=t(),v(t,o,n,a)}):v(t,o,n,a)})}}}function f(e,t,n){var r=t[n.nameOnServer];if(!r)return null;var i=e.visitAndMerge(r,{nodeType:"navProp",navigationProperty:n});return i}function h(e,t,n){var r=t[n.nameOnServer];if(!r)return null;if(!Array.isArray(r)&&(r=r.results,!r))return null;var i=e.visitAndMerge(r,{nodeType:"navPropItem",navigationProperty:n});return i}function d(e,t,n){if(e){var r=n.name,i=t.getProperty(r);if(i!==e){t.setProperty(r,e);var a=n.inverse;if(!a)return;if(a.isScalar)e.setProperty(a.name,t);else{var o=e.getProperty(a.name);o.push(t)}}}}function v(e,t,n,r){if(e){var i=e.getProperty(r.name);i!==n&&(t.push(e),e.setProperty(r.name,n))}}var g=function(e){p(this,e,["query","entityManager","dataService","mergeOptions"]),this.refMap={},this.deferredFns=[],this.jsonResultsAdapter=this.dataService.jsonResultsAdapter,this.metadataStore=this.entityManager.metadataStore,this.rawValueFn=It.getRawValueFromServer},E=g.prototype,w=Ot.parseRawValue;return E._$typeName="MappingContext",E.getUrl=function(){var e=this.query;if(!e)throw new Error("query cannot be empty");var t;if("string"==typeof e)t=e;else{if(!(e instanceof qt))throw new Error("unable to recognize query parameter as either a string or an EntityQuery");t=this.dataService.uriBuilder.buildUri(e,this.metadataStore)}return this.dataService.qualifyUrl(t)},E.visitAndMerge=function(t,n){var r=this.query,i=this.jsonResultsAdapter;n=n||{};var a=this;return m(t,function(t){if(null==r&&t.entityAspect)return t.entityAspect.entityState.isDeleted()?a.entityManager.detachEntity(t):t.entityAspect.acceptChanges(),t;var o=i.visitNode(t,a,n)||{};return t=o.node||t,r&&"root"===n.nodeType&&!o.entityType&&(o.entityType=r._getToEntityType&&r._getToEntityType(a.metadataStore)),e(a,t,o)},this.mergeOptions.includeDeleted)},E.processDeferred=function(){this.deferredFns.length>0&&this.deferredFns.forEach(function(e){e()})},g}(),Xt=function(){function e(e,t){return t&&ft(t).whereParam("resourceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(At).whereParam("allowConcurrentSaves").isBoolean().isOptional().whereParam("tag").isOptional().applyAll(e),e}var t=function(t){e(this,t)},n=t.prototype;return n._$typeName="SaveOptions",n.setAsDefault=function(){return l(this,t)},n.using=function(t){return e(this,t)},t.defaultInstance=new t({allowConcurrentSaves:!1}),t}();return at.SaveOptions=Xt,at.AbstractDataServiceAdapter=function(){function e(){this.getRequest=function(e){return e},this.done=function(){}}function t(e,t,r){var i=n(t);return a._catchNoConnectionError(i),r&&(i.message=r+"; "+i.message),e.reject(i)}function n(e){var t=new Error;t.httpResponse=e,t.status=e.status;var n=e.data;if(!n)return t.message=e.error&&e.error.toString(),t;if("string"==typeof n)try{n=JSON.parse(n)}catch(r){return t.message=n,t}var i,a,o=e.saveContext,s=n.Message||n.ExceptionMessage||n.EntityErrors||n.Errors,u=!!s;if(u){var s=n;do i=s.ExceptionMessage||s.Message,s=s.InnerException;while(s);a=n.Errors||n.EntityErrors,a=a&&a.map(function(e){return{errorName:e.ErrorName,entityTypeName:Ft.normalizeTypeName(e.EntityTypeName),keyValues:e.KeyValues,propertyName:e.PropertyName,errorMessage:e.ErrorMessage}})}else i=n.message,a=n.errors||n.entityErrors;if(o&&a){var p=o.entityManager.metadataStore.namingConvention.serverPropertyNameToClient;a.forEach(function(e){e.propertyName=e.propertyName&&p(e.propertyName)}),t.entityErrors=a}return t.message=i||"Server side errors encountered - see the entityErrors collection on this object for more detail",t}var r,i=function(){},a=i.prototype;return a.checkForRecomposition=function(e){"ajax"===e.interfaceName&&e.isDefault&&this.initialize()},a.initialize=function(){if(r=at.config.getAdapterInstance("ajax"),!r||!r.ajax)throw new Error("Unable to find ajax adapter for dataservice adapter '"+(this.name||"")+"'.")},a.fetchMetadata=function(e,n){var i=n.serviceName,a=n.qualifyUrl("Metadata"),o=xt.defer();return r.ajax({type:"GET",url:a,dataType:"json",success:function(r){if(e.hasMetadataFor(i))return o.resolve("already fetched");var s=r.data;try{var u="string"==typeof s?JSON.parse(s):s;e.importMetadata(u)}catch(p){var c="Unable to either parse or import metadata: "+p.message;return t(o,r,"Metadata query failed for: "+a+". "+c)}return e.hasMetadataFor(i)||e.addDataService(n),o.resolve(u)},error:function(e){t(o,e,"Metadata query failed for: "+a)}}),o.promise},a.executeQuery=function(e){var n=(e.adapter=this,xt.defer()),i=e.getUrl(),a={type:"GET",url:i,params:e.query.parameters,dataType:"json",success:function(e){var r=e.data;try{var i,a=r&&(r.results||r.Results);i=a?{results:a,inlineCount:r.inlineCount||r.InlineCount,httpResponse:e}:{results:r,httpResponse:e},n.resolve(i)}catch(o){o instanceof Error?n.reject(o):t(n,e)}},error:function(e){t(n,e)}};return e.dataService.useJsonp&&(a.dataType="jsonp",a.crossDomain=!0),r.ajax(a),n.promise},a.saveChanges=function(e,n){var i=e.adapter=this,a=xt.defer();n=i._prepareSaveBundle(e,n);var o=JSON.stringify(n),s=e.dataService.qualifyUrl(e.resourceName);return r.ajax({type:"POST",url:s,dataType:"json",contentType:"application/json",data:o,success:function(n){n.saveContext=e;var r=n.data;if(r.Errors||r.errors)t(a,n);else{var o=i._prepareSaveResult(e,r);o.httpResponse=n,a.resolve(o)}},error:function(n){n.saveContext=e,t(a,n)}}),a.promise},a._prepareSaveBundle=function(){throw new Error("Need a concrete implementation of _prepareSaveBundle")},a.changeRequestInterceptor=e,a._createChangeRequestInterceptor=function(t,n){var r=t.adapter,i=r.changeRequestInterceptor,a=V;if(a(i)){var o=r.name+" DataServiceAdapter's ChangeRequestInterceptor",s=" is missing or not a function.",u=new i(t,n);if(!a(u.getRequest))throw new Error(o+".getRequest"+s);if(!a(u.done))throw new Error(o+".done"+s);return u}return new e(t,n)},a._prepareSaveResult=function(){throw new Error("Need a concrete implementation of _prepareSaveResult")},a.jsonResultsAdapter=new Ct({name:"noop",visitNode:function(){return{}}}),a._catchNoConnectionError=function(e){0==e.status&&null==e.message&&(e.message="HTTP response status 0 and no message.  Likely did not or could not reach server. Is the server running?")},i}(),at});