-
Notifications
You must be signed in to change notification settings - Fork 4
/
breeze.min.js
6 lines (6 loc) · 173 KB
/
breeze.min.js
1
2
3
4
5
6
!function(e,t){var r=function(){return t(e)};"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):breeze=r()}(this,function(e){"use strict";function t(e,t){for(var r in e)at(e,r)&&t(r,e[r])}function r(e,t){var r=[];for(var n in e)if(at(e,n)){var a=t?t(n,e[n]):e[n];void 0!==a&&r.push(a)}return r}function n(e,t){for(var r in e)if(at(e,r)){var n=e[r];if(t(r,n))return{key:r,value:n}}return null}function a(e,t){var r=i(e,t);return null==r?!0:!(!r.writable&&!r.set)}function i(e,t){if(!ot)return null;if(e.hasOwnProperty(t))return Object.getOwnPropertyDescriptor(e,t);var r=Object.getPrototypeOf(e);return null==r?null:i(r,t)}function o(e,t){return function(r){return r[e]===t}}function s(e){return function(t){return t[e]}}function u(e){var t=[];for(var r in e)at(e,r)&&t.push(e[r]);return t}function p(e,t,r){if(!t)return e;if(r)r.forEach(function(r){e[r]=t[r]});else for(var n in t)at(t,n)&&(e[n]=t[n]);return e}function c(e,t){for(var r in t)void 0===e[r]&&(e[r]=t[r]);return e}function l(e,t){return t.defaultInstance=c(new t(e),t.defaultInstance),e}function y(e,t,r){r=r||{};for(var n in t){var a=n.split(","),i=t[n];a.some(function(t){if(!(t in e))return!1;var n=e[t];return"function"==typeof n?!1:n==i?!0:Array.isArray(n)&&0===n.length?!0:("function"==typeof i?n=i(n):"object"==typeof n&&n&&n.parentEnum&&(n=n.name),void 0===n?!0:(r[a[0]]=n,!0))})}return r}function f(e,t){if(e!==Object(e))return e;if(e._$visited)return void 0;if(e.toJSON){var r=e.toJSON();if(r!==Object(r))return r;if(r!==e)return f(r);e=r}e._$visited=!0;var n;if(e instanceof Array)n=e.map(function(e){return f(e,t)});else if("function"==typeof e)n=void 0;else{n={};for(var a in e)if("_$visited"!==a){var i=e[a];t&&(i=t(a,i),void 0===i)||(i=f(i),void 0!==i&&(n[a]=i))}}return delete e._$visited,n}function h(e,t){var r={},n=e.length;return t.forEach(function(t){for(var a=0;n>a;a++){var i=e[a];if(i){var o=i[t];if(void 0!==o){r[t]=o;break}}}}),r}function d(e){return null==e?[]:Array.isArray(e)?e:[e]}function m(e,t,r){if(r=null==r?!0:r,null==e)return e;var n;return Array.isArray(e)?(n=[],e.forEach(function(e,a){var i=t(e,a);(null!=i||r)&&(n[a]=i)})):n=t(e),n}function v(e,t){for(var r=0,n=e.length;n>r;r++)if(t(e[r]))return e[r];return null}function g(e,t){for(var r=0,n=e.length;n>r;r++)if(t(e[r]))return r;return-1}function w(e,t){var r=e.indexOf(t);-1===r&&e.push(t)}function E(e,t,r){for(var n=V(t)?t:void 0,a=e.length-1,i=!1,o=a;o>=0;o--)if((n?n(e[o]):e[o]===t)&&(e.splice(o,1),i=!0,!r))return!0;return i}function S(e,t,r){for(var n=[],a=Math.min(e.length,t.length),i=0;a>i;++i)n.push(r(e[i],t[i]));return n}function T(e,t,r){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(Array.isArray(e[n])){if(!T(e[n],t[n]))return!1}else if(r){if(!r(e[n],t[n]))return!1}else if(e[n]!==t[n])return!1;return!0}function P(e,t){var r=e[t];return r||(r=[],e[t]=r),r}function b(e,t){for(var r=e.split(";"),n=0,a=r.length;a>n;n++){var i=_(r[n]);if(i)return i}if(t)throw new Error("Unable to initialize "+e+". "+t)}function _(t){var r=e.window;if(r){var n=r[t];if(n)return n;var a=r.require;if(a){if(a.defined)return a.defined(t)?a(t):void 0;try{return a(t)}catch(i){return}}}}function N(e,t,r,n){var a=e[t];if(r===a)return n();e[t]=r;try{return n()}finally{void 0===a?delete e[t]:e[t]=a}}function O(e,t,r){var n;try{return n=e(),r()}catch(a){throw"object"==typeof n&&(n.error=a),a}finally{t(n)}}function A(e){return function(){for(var t=it(arguments),r="",n=t.length,a=null;n--;)a=t[n],r+=a===Object(a)?JSON.stringify(a):a,e.memoize||(e.memoize={});return r in e.memoize?e.memoize[r]:e.memoize[r]=e.apply(this,t)}}function C(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0,r="x"==e?t:3&t|8;return r.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 r=[2,3,4,6,7,8],n=[31104e3,2592e3,86400,3600,60,1],a=0,i=0;6>i;i++){var o=t[r[i]];o=o?+o.replace(/[A-Za-z]+/g,""):0,a+=o*n[i]}return a}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 j(e){return"string"==typeof e}function R(e){return"object"==typeof e}function K(e){return"string"==typeof e&&/[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/.test(e)}function q(e){return"string"==typeof e&&/^(-|)?P[T]?[\d\.,\-]+[YMDTHS]/.test(e)}function z(e){if(null===e||void 0===e)return!0;for(var t in e)if(at(e,t))return!1;return!0}function B(e){return!isNaN(parseFloat(e))&&isFinite(e)}function L(e,t){return e?""==t||null==t?!0:0===e.indexOf(t,0):!1}function U(e,t){return e?""==t||null==t?!0:-1!==e.indexOf(t,e.length-t.length):!1}function $(e){var t=arguments,r=RegExp("%([1-"+(arguments.length-1)+"])","g");return e.replace(r,function(e,r){return t[r]})}function G(e){var t=Function.call;return function(){return t.apply(e,arguments)}}function J(e,t,r){void 0===t&&(t=null);var n=r(),a=e.dataType;if(a&&a.parse&&(t=Array.isArray(t)&&!e.isScalar?t.map(function(e){return a.parse(e,typeof e)}):a.parse(t,typeof t)),!(t===n||a&&a.isDate&&t&&n&&t.valueOf()===n.valueOf())){var i,o=this.entityAspect;if(o)i=e.name;else{var s=this.complexAspect;if(!s)return void r(t);o=s.getEntityAspect(),i=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:n,propertyName:i,entityAspect:o};e.isComplexProperty?H(p,r):e.isDataProperty?Q(p,r):Z(p,r),W(p)}finally{u.pop()}}}}function Q(e,t){var r=e.parent,n=e.property,a=e.entityAspect,i=e.oldValue,o=e.newValue,s=a.entityManager,u=r.entityType;if(!n.isScalar)throw new Error("Nonscalar data properties are readonly - items may be added or removed but the collection may not be changed.");if(a.entityState.isUnchangedOrModified()){var p=n.name,c=r.entityAspect||r.complexAspect;void 0===c.originalValues[p]&&(c.originalValues[p]=void 0!==i?i:n.defaultValue)}if(n.isPartOfKey&&s&&!s.isLoading){var l=u.keyProperties,y=l.map(function(e){return e===n?o:r.getProperty(e.name)}),f=new Pt(u,y);if(s.findEntityByKey(f))throw new Error("An entity with this key is already in the cache: "+f.toString());var h=r.entityAspect.getKey(),d=s._findEntityGroup(u);d._replaceKey(h,f)}var m=n.relatedNavigationProperty;if(m&&s)if(null!=o){var v=new Pt(m.entityType,[o]),g=s.findEntityByKey(v);g?r.setProperty(m.name,g):(s._unattachedChildrenMap.addChild(v,m,r),r.setProperty(m.name,null))}else r.setProperty(m.name,null);else if(n.inverseNavigationProperty&&s&&!s._inKeyFixup){var w=n.inverseNavigationProperty;if(null!=i&&(v=new Pt(w.parentType,[i]),g=s.findEntityByKey(v)))if(w.isScalar)g.setProperty(w.name,null);else{var E=g.getProperty(w.name);E.splice(E.indexOf(r),1)}null!=o&&(v=new Pt(w.parentType,[o]),g=s.findEntityByKey(v),g?w.isScalar?g.setProperty(w.name,r):g.getProperty(w.name).push(r):s._unattachedChildrenMap.addChild(v,w,r))}if(t(o),Y(e),n.isPartOfKey){var S=u.keyProperties.indexOf(n);u.navigationProperties.forEach(function(e){var t=e.inverse,n=t?t.foreignKeyNames:e.invForeignKeyNames;if(0!==n.length){var a=r.getProperty(e.name),i=n[S];if(e.isScalar){if(!a)return;a.setProperty(i,o)}else a.forEach(function(e){e.setProperty(i,o)})}}),s&&u.inverseForeignKeyProperties.forEach(function(e){null==e.relatedNavigationProperty.inverse&&s._updateFkVal(e,i,o)}),a.getKey(!0)}}function H(e,t){var r=e.property,n=e.oldValue,a=e.newValue,i=r.dataType;if(!r.isScalar)throw new Error($("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.",r.name,r.parentType.name));if(!a)throw new Error($("You cannot set the '%1' property to null because it's datatype is the ComplexType: '%2'",r.name,r.dataType.name));if(!n){var o=i.getCtor();n=new o,t(n)}i.dataProperties.forEach(function(e){var t=e.name,r=a.getProperty(t);n.setProperty(t,r)})}function Z(e,t){var r=e.parent,n=e.property,a=e.entityAspect,i=e.oldValue,o=e.newValue;if(!n.isScalar)throw new Error("Nonscalar navigation properties are readonly - entities can be added or removed but the collection may not be changed.");var s=a.entityManager,u=n.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(a.entity,bt.Added))}if(u)if(u.isScalar)null!=i&&i.setProperty(u.name,null),null!=o&&o.setProperty(u.name,r);else{if(null!=i){var c=i.getProperty(u.name),l=c.indexOf(r);-1!==l&&c.splice(l,1)}if(null!=o){var y=o.getProperty(u.name);y.push(r)}}else if(n.invForeignKeyNames&&s&&!s._inKeyFixup){var f=n.invForeignKeyNames;if(null!=o){var h=r.entityAspect.getKey().values;f.forEach(function(e,t){o.setProperty(e,h[t])})}else null!=i&&f.forEach(function(e){var t=i.entityType.getProperty(e);t.isPartOfKey||i.setProperty(e,null)})}if(t(o),Y(e),n.relatedDataProperties){var d=a.entityState;if(null==o&&(d.isDetached()||i.entityAspect.entityState.isDetached()))return;if(d.isDeleted())return;var m=n.entityType.keyProperties;m.forEach(function(e,t){var a=n.relatedDataProperties[t];if(o||!a.isPartOfKey){var i=o?o.getProperty(e.name):a.defaultValue;r.setProperty(a.name,i)}})}}function W(e){var t=e.entityAspect,r=t.entityManager,n=t.entity,a={entity:n,parent:e.parent,property:e.property,propertyName:e.propertyName,oldValue:e.oldValue,newValue:e.newValue};r?r.isLoading||r.isRejectingChanges||(t.propertyChanged.publish(a),r.entityChanged.publish({entityAction:Et.PropertyChange,entity:n,args:a})):t.propertyChanged.publish(a)}function Y(e){var t=e.entityAspect,r=t.entityManager;if(null!=r&&!r.isLoading){var n=e.property;t.entityState.isUnchanged()&&!n.isUnmapped&&t.setModified(),r.validationOptions.validateOnPropertyChange&&t._validateProperty(e.newValue,{entity:t.entity,property:n,propertyName:e.propertyName,oldValue:e.oldValue})}}function X(e){return e.indexOf(":#")>=0}function et(e,t){return e+":#"+t}function tt(e,t,r){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 n in t)if(at(t,n)){var a=t[n];a.name=n;var i=new r(a);e._addPropertyCore(i)}}}function rt(e,t){var r=Array.isArray(t)?t:t.split(".");if(1===r.length)return e.getProperty(t);var n=e;return r.some(function(e){return n=n.getProperty(e),null==n}),n}var nt={version:"1.5.2",metadataVersion:"1.0.5"},at=G(Object.prototype.hasOwnProperty),it=G(Array.prototype.slice),ot=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 st={};st.__isES5Supported=ot,st.objectForEach=t,st.extend=p,st.propEq=o,st.pluck=s,st.arrayEquals=T,st.arrayFirst=v,st.arrayIndexOf=g,st.arrayRemoveItem=E,st.arrayZip=S,st.requireLib=b,st.using=N,st.memoize=A,st.getUuid=C,st.durationToSeconds=x,st.isDate=k,st.isGuid=K,st.isDuration=q,st.isFunction=V,st.isEmpty=z,st.isNumeric=B,st.stringStartsWith=L,st.stringEndsWith=U,st.formatString=$,st.getPropertyDescriptor=i,st.toJSONSafe=f,st.parent=nt,nt.core=st;var ut=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 r(e,t){return null==t?!1:t instanceof e.type}function n(e,t){return null==t?!1:void 0!==t[e.propertyName]}function a(e,t){return null==t?!1:e.enumType.contains(t)}function i(e,t){return e.allowNull?void 0!==t:null!=t}function o(e,t){if(null==t)return!0;var r=e.prevContext;return r?r.fn(r,t):!0}function s(e,t){var r=e.prevContext,n=r?" or it "+l(r,t):"";return"is optional"+n}function u(e,t){if(!Array.isArray(t))return!1;if(e.mustNotBeEmpty&&0===t.length)return!1;var r=e.prevContext;return r?t.every(function(e){return r.fn(r,e)}):!0}function c(e,t){var r=e.mustNotBeEmpty?"a nonEmpty array":"an array",n=e.prevContext,a=n?" where each element "+l(n,t):"";return" must be "+r+a}function l(e,t){var r=e.msg;return"function"==typeof r&&(r=r(e,t)),r}function y(e,t){if(e._context){for(var r=e._context;null!=r.prevContext;)r=r.prevContext;if(null===r.prevContext)return r.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($("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 '%1'",e)})},v.isInstanceOf=function(e,t){return t=t||e.prototype._$typeName,y(this,{fn:r,type:e,typeName:t,msg:$("must be an instance of '%1'",t)})},v.hasProperty=function(e){return y(this,{fn:n,propertyName:e,msg:$("must have a '%1' property ",e)})},v.isEnumOf=function(e){return y(this,{fn:a,enumType:e,msg:$("must be an instance of the '%1' enumeration",e.name)})},v.isRequired=function(e){return y(this,{fn:i,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 $(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 r=e._$typeName,n=r&&this.parent.config._$typeName===r,a=p({},this.parent.config);if(this.parent.params.forEach(function(r){n||delete a[r.name];try{r.check()}catch(i){d(e,i.message)}!t&&r._applyOne(e)}),!n)for(var i in a)void 0!==a[i]&&d(e,$("Unknown property: '%1'.",i))},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}(),pt=function(e,t){return new ut(e,t)},ct=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 ut(this.config[e],e);return t.parent=this,this.params.push(t),t},e}(),lt=function(e){return new ct(e)};st.Param=ut,st.assertParam=pt,st.assertConfig=lt;var yt=function(){function e(){}var t=function(t,r){this.name=t;var n=new e(r);n.parentEnum=this,this._symbolPrototype=n,r&&Object.keys(r).forEach(function(e){n[e]=r[e]})},r=t.prototype;return t.isSymbol=function(t){return t instanceof e},r.fromName=function(e){return this[e]},r.addSymbol=function(e){var t=Object.create(this._symbolPrototype);return e&&Object.keys(e).forEach(function(r){t[r]=e[r]}),setTimeout(function(){t.getName()},0),t},r.resolveSymbols=function(){this.getSymbols().forEach(function(e){return e.getName()})},r.getSymbols=function(){return this.getNames().map(function(e){return this[e]},this)},r.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},r.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}();st.Enum=yt;var ft=function(){function e(e,r,n){var a=e._subscribers;return a?void a.forEach(function(a){try{a.callback(r)}catch(i){i.context="unable to publish on topic: "+e.name,n?n(i):e._defaultErrorCallback?e._defaultErrorCallback(i):t(i)}}):!0}function t(){}var r={},n=1,a=function(e,t,n){pt(e,"eventName").isNonEmptyString().check(),pt(t,"publisher").isObject().check(),this.name=e,r[e]=!0,this.publisher=t,n&&(this._defaultErrorCallback=n)},i=a.prototype;return i.publish=function(t,r,n){return a._isEnabled(this.name,this.publisher)?(r===!0?setTimeout(e,0,this,t,n):e(this,t,n),!0):!1},i.publishAsync=function(e,t){this.publish(e,!0,t)},i.subscribe=function(e){this._subscribers||(this._subscribers=[]);var t=n;return this._subscribers.push({unsubKey:t,callback:e}),++n,t},i.unsubscribe=function(e){if(!this._subscribers)return!1;var t=this._subscribers,r=g(t,function(t){return t.unsubKey===e});return-1!==r?(t.splice(r,1),0===t.length&&(this._subscribers=null),!0):!1},i.clear=function(){this._subscribers=null},a.bubbleEvent=function(e,t){e._getEventParent=t},a.enable=function(e,t,r){pt(e,"eventName").isNonEmptyString().check(),pt(t,"obj").isObject().check(),pt(r,"isEnabled").isBoolean().isOptional().or().isFunction().check(),t._$eventMap||(t._$eventMap={}),t._$eventMap[e]=r},a.isEnabled=function(e,t){if(pt(e,"eventName").isNonEmptyString().check(),pt(t,"obj").isObject().check(),void 0===t._getEventParent)throw new Error("This object does not support event enabling/disabling");return a._isEnabled(t,e)},a._isEnabled=function(e,t){var r=null,n=t._$eventMap;if(n&&(r=n[e]),null!=r)return"function"==typeof r?r(t):!!r;var i=t._getEventParent&&t._getEventParent();return i?a._isEnabled(e,i):!0},a}();st.Event=ft;var ht=function(){function e(e,t,r){var n=t.defaultInstance;return n||(n=new t.ctor,t.defaultInstance=n,n._$impl=t),n.initialize(),r&&(e.defaultInstance=n),a.interfaceInitialized.publish({interfaceName:e.name,instance:n,isDefault:!0}),n.checkForRecomposition&&a.interfaceInitialized.subscribe(function(e){n.checkForRecomposition(e)}),n}function t(e){var t=e.toLowerCase(),r=n(a.interfaceRegistry||{},function(e){return e.toLowerCase()===t});if(!r)throw new Error("Unknown interface name: "+e);return r.value}var a={};a.functionRegistry={},a.typeRegistry={},a.objectRegistry={},a.interfaceInitialized=new ft("interfaceInitialized",a);var i=function(e){this.name=e,this.defaultInstance=null,this._implMap={}};return i.prototype.registerCtor=function(e,t){this._implMap[e.toLowerCase()]={ctor:t,defaultInstance:null}},i.prototype.getImpl=function(e){return this._implMap[e.toLowerCase()]},i.prototype.getFirstImpl=function(){var e=n(this._implMap,function(){return!0});return e?e.value:null},a.interfaceRegistry={ajax:new i("ajax"),modelLibrary:new i("modelLibrary"),dataService:new i("dataService"),uriBuilder:new i("uriBuilder")},a.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},a.setProperties=function(e){lt(e).whereParam("remoteAccessImplementation").isOptional().whereParam("trackingImplementation").isOptional().whereParam("ajaxImplementation").isOptional().applyAll(e),e.remoteAccessImplementation&&a.initializeAdapterInstance("dataService",e.remoteAccessImplementation),e.trackingImplementation&&a.initializeAdapterInstance("modelLibrary",e.trackingImplementation),e.ajaxImplementation&&a.initializeAdapterInstance("ajax",e.ajaxImplementation)},a.registerAdapter=function(e,r){pt(e,"interfaceName").isNonEmptyString().check(),pt(r,"adapterCtor").isFunction().check();var n=new r,a=n.name;if(!a)throw new Error("Unable to locate a 'name' property on the constructor passed into the 'registerAdapter' call.");var i=t(e);i.registerCtor(a,r)},a.getAdapter=function(e,r){var n=t(e);if(r){var a=n.getImpl(r);return a?a.ctor:null}return n.defaultInstance?n.defaultInstance._$impl.ctor:null},a.initializeAdapterInstances=function(e){return lt(e).whereParam("dataService").isOptional().whereParam("modelLibrary").isOptional().whereParam("ajax").isOptional().whereParam("uriBuilder").isOptional().applyAll(this,!1),r(e,a.initializeAdapterInstance)},a.initializeAdapterInstance=function(r,n,a){a=void 0===a?!0:a,pt(r,"interfaceName").isNonEmptyString().check(),pt(n,"adapterName").isNonEmptyString().check(),pt(a,"isDefault").isBoolean().check();var i=t(r),o=i.getImpl(n);if(!o)throw new Error("Unregistered adapter. Interface: "+r+" AdapterName: "+n);return e(i,o,a)},a.getAdapterInstance=function(r,n){var a,i=t(r),o=null==n||""==n;if(o){if(i.defaultInstance)return i.defaultInstance;a=i.getFirstImpl()}else a=i.getImpl(n);return a?a.defaultInstance?a.defaultInstance:e(i,a,o):null},a.registerFunction=function(e,t){pt(e,"fn").isFunction().check(),pt(t,"fnName").isString().check(),e.prototype._$fnName=t,a.functionRegistry[t]=e},a.getRegisteredFunction=function(e){return a.functionRegistry[e]},a._storeObject=function(e,t,r){var n=("string"==typeof t?t:t.prototype._$typeName)+"."+r;a.objectRegistry[n]=e},a._fetchObject=function(e,t){if(!t)return void 0;var r=("string"==typeof e?e:e.prototype._$typeName)+"."+t,n=a.objectRegistry[r];if(!n)throw new Error("Unable to locate a registered object by the name: "+r);return n},a.registerType=function(e,t){pt(e,"ctor").isFunction().check(),pt(t,"typeName").isString().check(),e.prototype._$typeName=t,a.typeRegistry[t]=e},a.stringifyPad="",a}(),dt=ht.interfaceRegistry.modelLibrary;st.config=ht,nt.config=ht;var mt=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),n(e,"arrayChanged",{array:e,added:t})}function r(e,t){e._processRemoves(t),n(e,"arrayChanged",{array:e,removed:t})}function n(e,t,r){var n=e._getPendingPubs();n?e._pendingArgs?a(e._pendingArgs,r):(e._pendingArgs=r,n.push(function(){e[t].publish(e._pendingArgs),e._pendingArgs=null})):e[t].publish(r)}function a(e,t){for(var r in t)if("array"!==r&&e.hasOwnProperty(r)){var n=t[r],a=e[r];if(a){if(!Array.isArray(a))throw new Error("Cannot combine non array args");Array.prototype.push.apply(a,n)}else e[r]=n}}function i(e,t,r){e.parent=t,e.parentProperty=r}var o={};return o.push=function(){if(this._inProgress)return-1;var e=this._getGoodAdds(it(arguments));if(!e.length)return this.length;this._beforeChange();var r=Array.prototype.push.apply(this,e);return t(this,e),r},o._push=function(){if(this._inProgress)return-1;var e=it(arguments);this._beforeChange();var r=Array.prototype.push.apply(this,e);return t(this,e),r},o.unshift=function(){var e=this._getGoodAdds(it(arguments));if(!e.length)return this.length;this._beforeChange();var r=Array.prototype.unshift.apply(this,e);return t(this,it(e)),r},o.pop=function(){this._beforeChange();var e=Array.prototype.pop.apply(this);return r(this,[e]),e},o.shift=function(){this._beforeChange();var e=Array.prototype.shift.apply(this);return r(this,[e]),e},o.splice=function(){var e=this._getGoodAdds(it(arguments,2)),n=it(arguments,0,2).concat(e);this._beforeChange();var a=Array.prototype.splice.apply(this,n);return r(this,a),e.length&&t(this,e),a},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:n,updateEntityState:e,initializeParent:i}}(),vt=function(){function e(e,t,r,n,a){for(n=+e[t=e.length-1],a=0;t--;)r=+e[t],n+=++a%2?2*r%10+(r>4):r;return!(n%10)}function r(e,t,r,n){r&&(f.messageTemplates[e]=r);var a="string"==typeof t?new RegExp(t):t,i=function(e){return null==e||""===e?!0:"string"!=typeof e?!1:a.test(e)};return new f(e,i,n)}function n(e,t,r){return t?e.replace(/%([^%]+)%/g,function(e,n){var a;return a=r?t.hasOwnProperty(n)?t[n]:"":t[n],null!=a?V(a)?a(t):a:""}):e}function a(e,t,r,n){var a=n&&n.messageTemplate||f.messageTemplates[e];return a||(f.messageTemplates[e]=$("'%displayName%' must be an integer between the values of %1 and %2",t,r)),function(){var a=function(e,n){return null==e?!0:("string"==typeof e&&n&&n.allowString&&(e=parseInt(e,0)),"number"!=typeof e||isNaN(e)||Math.floor(e)!==e?!1:null!=t&&t>e?!1:null!=r&&e>r?!1:!0)};return new f(e,a,n)}}var i=-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,r){this._baseContext=r||{},this._baseContext.name=e,r=p(Object.create(y),this._baseContext),r.messageTemplate=r.messageTemplate||f.messageTemplates[e],this.name=e,this.valFn=t,this.context=r},h=f.prototype;return h._$typeName="Validator",h.validate=function(e,t){var r;r=t?p(Object.create(this.context),t):this.context,this.currentContext=r;try{return this.valFn(e,r)?null:(r.value=e,new gt(this,r,this.getMessage()))}catch(n){return new gt(this,r,"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?n(e.messageTemplate,e):"invalid value: "+(this.name||"{unnamed validator}")}catch(r){return"Unable to format error message"+r.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,r=ht.getRegisteredFunction(t);if(!r)throw new Error("Unable to locate a validator named:"+e.name);return r(e)},f.register=function(e){ht.registerFunction(function(){return e},"Validator."+e.name)},f.registerFactory=function(e,t){ht.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:K(e)};return new f("guid",e)},f.duration=function(){var e=function(e){return null==e?!0:q(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 a("int32",s,u,e)()},f.int16=function(e){return a("int16",i,o,e)()},f.byte=function(e){return a("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 r(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",r,t)},f.regularExpression=function(e){function t(e,t){if(null==e||""===e)return!0;if("string"!=typeof e)return!1;try{var r=new RegExp(t.expression)}catch(n){throw new Error("Missing or invalid expression parameter to regExp validator")}return r.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 r("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 r("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 r("url",t,null,e)},f.makeRegExpValidator=r,t(f,function(e,t){"function"==typeof t&&"fromJSON"!==e&&"register"!==e&&"registerFactory"!==e&&"makeRegExpValidator"!==e&&ht.registerFunction(t,"Validator."+e)}),f}(),gt=function(){var e=function t(e,r,n,a){pt(e,"validator").isOptional().isInstanceOf(vt).check(),pt(n,"errorMessage").isNonEmptyString().check(),pt(a,"key").isOptional().isNonEmptyString().check(),this.validator=e,r=r||{},this.context=r,this.errorMessage=n,this.property=r.property,this.propertyName=r.propertyName||r.property&&r.property.name,this.key=a?a:t.getKey(e||n,this.propertyName),this.isServerError=!1};return e.getKey=function(e,t){return(e.name||e)+(t?":"+t:"")},e}();nt.Validator=vt,nt.ValidationError=gt;var wt=function(){function e(e,t){return t&<(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)},r=t.prototype;return r._$typeName="ValidationOptions",r.using=function(t){if(!t)return this;var r=new wt(this);return e(r,t),r},r.setAsDefault=function(){return l(this,t)},t.defaultInstance=new t({validateOnAttach:!0,validateOnSave:!0,validateOnQuery:!1,validateOnPropertyChange:!0}),t}();nt.ValidationOptions=wt,nt.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");a(t,e)})}function r(e,t){t.forEach(function(t){n(t,e)})}function n(e,t){var r=e.complexAspect;return r.parent!==t.parent?null:(r.parent=null,r.parentProperty=null,r)}function a(e,t){var r=e.complexAspect;return r.parent===t.parent?null:(r.parent=t.parent,r.parentProperty=t.parentProperty,r)}function i(e,t,r){return mt.initializeParent(e,t,r),e.arrayChanged=new ft("arrayChanged",e),p(e,mt.mixin),p(e,o)}var o={};return o._getGoodAdds=function(t){return e(this,t)},o._beforeChange=function(){mt.updateEntityState(this)},o._processAdds=function(e){t(this,e)},o._processRemoves=function(e){r(this,e)},o._rejectChanges=function(){if(this._origValues){var e=this;this.forEach(function(t){n(t,e)}),this.length=0,this._origValues.forEach(function(t){e.push(t)})}},o._acceptChanges=function(){this._origValues=null},i}();var Et=function(){var e={isAttach:function(){return!!this.isAttach},isDetach:function(){return!!this.isDetach},isModification:function(){return!!this.isModification}},t=new yt("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}();nt.EntityAction=Et;var St=function(){function e(t){var r=t.entityAspect||t.complexAspect,n=t.entityType||t.complexType,a=r.originalValues;for(var i in a)t.setProperty(i,a[i]);n.complexProperties.forEach(function(r){var n=t.getProperty(r.name);r.isScalar?e(n):(n._rejectChanges(),n.forEach(e))})}function r(e){var t=e.entityAspect||e.complexAspect;t.originalValues={};var n=e.entityType||e.complexType;n.complexProperties.forEach(function(t){var n=e.getProperty(t.name);t.isScalar?r(n):(n._acceptChanges(),n.forEach(r))})}function n(e,t){var r=!0,a=e.entityType||e.complexType,i=e.entityAspect||e.complexAspect,s=e.entityAspect||e.complexAspect.getEntityAspect(),u={entity:s.entity};return void 0!==t&&(u.index=t),a.getProperties().forEach(function(t){var a=e.getProperty(t.name),o=t.getAllValidators();o.length>0&&(u.property=t,u.propertyName=i.getPropertyPath(t.name),r=s._validateProperty(a,u)&&r),t.isComplexProperty&&(r=t.isScalar?n(a)&&r:a.reduce(function(e,t,r){return n(t,r)&&e},r))}),a.getAllValidators().forEach(function(t){r=o(s,t,e)&&r}),r}function a(e,t){var r=t.isDeleted();r?i(e):N(e.entityAspect.entityManager,"isLoading",!0,function(){i(e)})}function i(e){e.entityType.navigationProperties.forEach(function(t){var r=t.inverse,n=e.getProperty(t.name);if(t.isScalar){if(n){if(r)if(r.isScalar)n.setProperty(r.name,null);else{var a=n.getProperty(r.name);a.length&&E(a,e)}e.setProperty(t.name,null)}}else r&&n.slice(0).forEach(function(e){r.isScalar&&e.setProperty(r.name,null)}),n.length=0})}function o(e,t,r,n){var a=t.validate(r,n);if(a)return e._addValidationError(a),!1;var i=gt.getKey(t,n?n.propertyName:null);return e._removeValidationError(i),!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 ft("validationErrorsChanged",this),this.propertyChanged=new ft("propertyChanged",this),null!=e){e.entityAspect=this;var r=e.entityType||e._$entityType;if(!r){var n=e.prototype._$typeName;throw new Error(n?"Metadata for this entityType has not yet been resolved: "+n:"This entity is not registered as a valid EntityType")}var a=r.getEntityCtor();dt.getDefaultInstance().startTracking(e,a.prototype)}},p=s.prototype;return ft.bubbleEvent(p,function(){return this.entityManager}),p.getKey=function(e){if(e=pt(e,"forceRefresh").isBoolean().isOptional().check(!1),e||!this._entityKey){var t=this.entity.entityType,r=t.keyProperties,n=r.map(function(e){return this.entity.getProperty(e.name)},this);this._entityKey=new Pt(t,n)}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:Et.AcceptChanges,entity:this.entity})},p.rejectChanges=function(){this._checkOperation("rejectChanges");var t=this.entity,r=this.entityManager;N(r,"isRejectingChanges",!0,function(){e(t)}),this.entityState.isAdded()?(r.detachEntity(t),r._notifyStateChange(t,!1)):(this.entityState.isDeleted()&&this.entityManager._linkRelatedEntities(t),this.setUnchanged(),this.propertyChanged.publish({entity:t,propertyName:null}),this.entityManager.entityChanged.publish({entityAction:Et.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,n=this.entityManager,i=!0;if(e===bt.Unchanged)r(t),delete this.hasTempKey,i=!1;else if(e===bt.Added)r(t);else if(e===bt.Deleted){if(this.entityState.isAdded())return this.setEntityState(bt.Detached),!0;this.entityState=bt.Deleted,a(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,a(t,bt.Detached),this._detach(),n.entityChanged.publish({entityAction:Et.Detach,entity:t}),i=!1}return this.entityState=e,n._notifyStateChange(t,i),!0},p.loadNavigationProperty=function(e,t,r){var n=this.entity,a=n.entityType._checkNavProperty(e),i=qt.fromEntityNavigation(n,a),o=n.entityAspect.entityManager.executeQuery(i),s=this;return o.then(function(e){return s._markAsLoaded(a.name),t&&t(e),At.resolve(e)},function(e){return r&&r(e),At.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||[],w(this._loadedNps,e)},p.validateEntity=function(){var e=!0;return this._processValidationOpAndPublish(function(t){e=n(t.entity)}),e},p.validateProperty=function(e,t){var r=this.getPropertyValue(e);return r&&r.complexAspect?n(r):(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(r,t))},p.getValidationErrors=function(e){pt(e,"property").isOptional().isEntityProperty().or().isString().check();var t=u(this._validationErrors);if(e){var r="string"==typeof e?e:e.name;t=t.filter(function(e){return e.property&&(e.property.name===r||-1!=r.indexOf(".")&&e.propertyName==r)})}return t},p.addValidationError=function(e){pt(e,"validationError").isInstanceOf(gt).check(),this._processValidationOpAndPublish(function(t){t._addValidationError(e)})},p.removeValidationError=function(e){pt(e,"validationErrorOrKey").isString().or().isInstanceOf(gt).or().isInstanceOf(vt).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,r){r&&(delete e._validationErrors[t],e._pendingValidationResult.removed.push(r))}),e.hasValidationErrors=!z(e._validationErrors)})},p.getParentKey=function(e){var t=e.foreignKeyNames;if(0===t.length)return null;var r=this,n=t.map(function(e){return r.entity.getProperty(e)});return new Pt(e.entityType,n)},p.getPropertyValue=function(e){pt(e,"property").isString().or().isEntityProperty().check();var t;if("string"==typeof e){var r=e.trim().split("."),n=r.shift();for(t=this.entity,t=t.getProperty(n);r.length>0;)n=r.shift(),t=t.getProperty(n)}else{if(!(e.parentType instanceof Ft))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 r=!0;return this._processValidationOpAndPublish(function(n){t.property.getAllValidators().forEach(function(a){r=o(n,a,e,t)&&r})}),r},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=!z(this._validationErrors),this._pendingValidationResult.removed.push(t))},s}(),Tt=function(){var e=function r(e,t,n){if(!e)throw new Error("The ComplexAspect ctor requires an entity as its only argument.");if(e.complexAspect)return e.complexAspect;if(!(this instanceof r))return new r(e,t,n);this.complexObject=e,e.complexAspect=this,this.originalValues={},null!=t&&(this.parent=t,this.parentProperty=n);var a=e.complexType;if(!a){var i=e.prototype._$typeName;throw new Error(i?"Metadata for this complexType has not yet been resolved: "+i:"This entity is not registered as a valid ComplexType")}var o=a.getCtor();dt.getDefaultInstance().startTracking(e,o.prototype)},t=e.prototype;return t.getEntityAspect=function(){var e=this.parent;if(!e)return new St(null);for(var t=e.entityAspect;e&&!t;)e=e.complexAspect&&e.complexAspect.parent,t=e&&e.entityAspect;return t||new St(null)},t.getPropertyPath=function(e){var t=this.parent;if(!t)return null;var r=t.complexAspect||t.entityAspect;return r.getPropertyPath(this.parentProperty.name+"."+e)},e}();nt.EntityAspect=St,nt.ComplexAspect=Tt;var Pt=function(){function e(e){return e.join(t)}var t=":::",r=function(t,r){pt(t,"entityType").isInstanceOf(Ft).check();var n=t.getSelfAndSubtypes();n.length>1&&(this._subtypes=n.filter(function(e){return e.isAbstract===!1})),Array.isArray(r)||(r=it(arguments,1)),this.entityType=t,t.keyProperties.forEach(function(e,t){e.dataType===_t.Guid&&(r[t]=r[t]&&r[t].toLowerCase())}),this.values=r,this._keyInGroup=e(r)};r._$typeName="EntityKey";var n=r.prototype;return n.toJSON=function(){return{entityType:this.entityType.name,values:this.values}},r.fromJSON=function(e,t){var r=t._getEntityType(e.entityType,!0);return new Pt(r,e.values)},n.equals=function(e){return e instanceof Pt?this.entityType===e.entityType&&T(this.values,e.values):!1},n.toString=function(e){return(e||this.entityType).name+"-"+this._keyInGroup},r.equals=function(e,t){return e instanceof Pt?e.equals(t):!1},n._isEmpty=function(){return 0===this.values.join("").length},r.createKeyString=e,r}();nt.EntityKey=Pt;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 yt("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}();nt.EntityState=bt,nt.makePrimitiveArray=function(){function e(e,r,n){return mt.initializeParent(e,r,n),e.arrayChanged=new ft("arrayChanged",e),p(e,mt.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}(),nt.makeRelationArray=function(){function e(e,t){var r=n(e,t);if(!r.length)return r;var a=e.parentEntity,i=a.entityAspect.entityManager;return i&&!i.isLoading&&r.forEach(function(t){if(t.entityAspect.entityState.isDetached()){e._inProgress=!0;try{i.attachEntity(t,bt.Added)}finally{e._inProgress=!1}}}),r}function t(e,t){var r=e.parentEntity,n=e.navigationProperty,a=e._addsInProcess,i=n.inverse,o=a.length;try{t.forEach(function(e){if(a.push(e),i)e.setProperty(i.name,r);else{var t=r.entityType.keyProperties;n.invForeignKeyNames.forEach(function(n,a){e.setProperty(n,r.getProperty(t[a].name))})}})}finally{a.splice(o,t.length)}}function r(e,t){var r=e.navigationProperty.inverse;r&&t.forEach(function(e){e.setProperty(r.name,null)})}function n(e,t){var r,n=e.parentEntity,a=e.navigationProperty,i=a.inverse;if(i)r=t.filter(function(t){if(e._addsInProcess.indexOf(t)>=0)return!1;var r=t.getProperty(i.name);return r!==n});else{var o=a.invForeignKeyNames,s=n.entityType.keyProperties;r=t.filter(function(t){return e._addsInProcess.indexOf(t)>=0?!1:o.some(function(e,r){var a=s[r].name,i=n.getProperty(a),o=t.getProperty(e);return i!==o})})}return r}function a(e,t,r){return e.parentEntity=t,e.navigationProperty=r,e.arrayChanged=new ft("arrayChanged",e),e._addsInProcess=[],p(e,mt.mixin),p(e,i)}var i={};return i.load=function(e,t){var r=this.parentEntity,n=qt.fromEntityNavigation(this.parentEntity,this.navigationProperty),a=r.entityAspect.entityManager;return a.executeQuery(n,e,t)},i._getEventParent=function(){return this.parentEntity.entityAspect},i._getPendingPubs=function(){var e=this.parentEntity.entityAspect.entityManager;return e&&e._pendingPubs},i._getGoodAdds=function(t){return e(this,t)},i._processAdds=function(e){t(this,e)},i._processRemoves=function(e){r(this,e)},a}();var _t=function(){function e(e,t){throw e=$(e,t),new Error(e)}function t(e){switch(e){case b.String:return vt.string;case b.Int64:return vt.int64;case b.Int32:return vt.int32;case b.Int16:return vt.int16;case b.Decimal:return vt.number;case b.Double:return vt.number;case b.Single:return vt.number;case b.DateTime:return vt.date;case b.DateTimeOffset:return vt.date;case b.Boolean:return vt.bool;case b.Guid:return vt.guid;case b.Byte:return vt.byte;case b.Binary:return vt.none;case b.Time:return vt.duration;case b.Undefined:return vt.none}}var r,n={},a=function(){r={stringPrefix:"K_",nextNumber:-1,nextNumberIncrement:-1}};a();var i=function(){return r.stringPrefix+o().toString()},o=function(){var e=r.nextNumber;return r.nextNumber+=r.nextNumberIncrement,e},s=function(){return C()},u=function(){return new Date},p=function(e){return null==e?e:e.toString()},c=function(e,t){if("string"===t){var r=e.trim();if(""===r)return null;var n=parseInt(r,10);return isNaN(n)?e:n}return"number"===t?Math.round(e):e},l=function(e,t){if("string"===t){var r=e.trim();if(""===r)return null;var n=parseFloat(r);return isNaN(n)?e:n}return e},y=function(e,t){var r;if("string"===t){var n=e.trim();return""===n?null:(r=new Date(Date.parse(n)),k(r)?r:e)}return"number"===t?(r=new Date(e),k(r)?r:e):e},f=function(e,t){if("string"===t){var r=e.trim().toLowerCase();return"false"===r||""===r?!1:"true"===r?!0:e}return e},h=function(e){return null==e?null:"'"+e.replace(/'/g,"''")+"'"},d=function(e){return null==e?null:"string"==typeof e?parseInt(e,10):e},m=function(e){return function(t){return null==t?null:("string"==typeof t&&(t=parseFloat(t)),t+e)}},v=function(t){if(null==t)return null;try{return"datetime'"+t.toISOString()+"'"}catch(r){e("'%1' is not a valid dateTime",t)}},g=function(t){if(null==t)return null;try{return"datetimeoffset'"+t.toISOString()+"'"}catch(r){e("'%1' is not a valid dateTime",t)}},w=function(t){return null==t?null:(q(t)||e("'%1' is not a valid ISO 8601 duration",t),"time'"+t+"'")},E=function(t){return null==t?null:(K(t)||e("'%1' is not a valid guid",t),"guid'"+t+"'")},S=function(e){return null==e?null:"string"==typeof e?"true"===e.trim().toLowerCase():!!e},T=function(e){return null==e?e:"binary'"+e+"'"},P=function(e){return e},b=new yt("DataType",n);b.String=b.addSymbol({defaultValue:"",parse:p,fmtOData:h,getNext:i}),b.Int64=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,quoteJsonOData:!0,parse:c,fmtOData:m("L"),getNext:o}),b.Int32=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d,getNext:o}),b.Int16=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d,getNext:o}),b.Byte=b.addSymbol({defaultValue:0,isNumeric:!0,isInteger:!0,parse:c,fmtOData:d}),b.Decimal=b.addSymbol({defaultValue:0,isNumeric:!0,quoteJsonOData:!0,isFloat:!0,parse:l,fmtOData:m("m"),getNext:o}),b.Double=b.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:l,fmtOData:m("d"),getNext:o}),b.Single=b.addSymbol({defaultValue:0,isNumeric:!0,isFloat:!0,parse:l,fmtOData:m("f"),getNext:o}),b.DateTime=b.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:v,getNext:u}),b.DateTimeOffset=b.addSymbol({defaultValue:new Date(1900,0,1),isDate:!0,parse:y,fmtOData:g,getNext:u}),b.Time=b.addSymbol({defaultValue:"PT0S",fmtOData:w}),b.Boolean=b.addSymbol({defaultValue:!1,parse:f,fmtOData:S}),b.Guid=b.addSymbol({defaultValue:"00000000-0000-0000-0000-000000000000",fmtOData:E,getNext:s}),b.Binary=b.addSymbol({defaultValue:null,fmtOData:T}),b.Undefined=b.addSymbol({defaultValue:void 0,fmtOData:P}),b.resolveSymbols(),b.getComparableFn=function(e){return e&&e.isDate?function(e){return e&&e.getTime()}:e===b.Time?function(e){return e&&x(e)}:function(e){return e}},b.fromEdmDataType=function(e){var t=null,r=e.split(".");if(r.length>1){var n=r[1];t="image"===n?b.Byte:2===r.length?b.fromName(n)||b.Undefined:b.String}return t},b.fromValue=function(e){if(k(e))return b.DateTime;switch(typeof e){case"string":return K(e)?b.Guid:q(e)&&e.length>3?b.Time:I(e)?b.DateTime:b.String;case"boolean":return b.Boolean;case"number":return b.Double}return b.Undefined};var _=/.\d{3}$/;return b.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},b.parseDateAsUTC=function(e){if("string"==typeof e){var t=_.test(e);e=t?e+"Z":e}return e=new Date(Date.parse(e))},b.parseDateFromServer=b.parseDateAsUTC,b.parseRawValue=function(e,t){return void 0===e?void 0:(t.isDate&&e?k(e)||(e=b.parseDateFromServer(e)):t===b.Binary?e&&void 0!==e.$value&&(e=e.$value):t===b.Time&&(e=b.parseTimeFromServer(e)),e)},b.constants=r,b._resetConstants=a,b.getSymbols().forEach(function(e){e.validatorCtor=t(e)}),b}();nt.DataType=_t;var Nt=function(){function e(e,t){return t&&(lt(t).whereParam("serviceName").isOptional().whereParam("adapterName").isString().isOptional().whereParam("uriBuilderName").isString().isOptional().whereParam("hasServerMetadata").isBoolean().isOptional().whereParam("jsonResultsAdapter").isInstanceOf(Ot).isOptional().whereParam("useJsonp").isBoolean().isOptional().applyAll(e),e.serviceName=e.serviceName&&Nt._normalizeServiceName(e.serviceName),e.adapterInstance=e.adapterName&&ht.getAdapterInstance("dataService",e.adapterName),e.uriBuilder=e.uriBuilderName&&ht.getAdapterInstance("uriBuilder",e.uriBuilderName)),e}var t=function(t){e(this,t)},r=t.prototype;return r._$typeName="DataService",r.using=function(t){if(!t)return this;var r=new Nt(this);return e(r,t)},t.resolve=function(e){e.push({hasServerMetadata:!0,useJsonp:!1});var t=new Nt(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||ht.getAdapterInstance("dataService",t.adapterName),t.jsonResultsAdapter=t.jsonResultsAdapter||t.adapterInstance.jsonResultsAdapter,t.uriBuilder=t.uriBuilder||ht.getAdapterInstance("uriBuilder",t.uriBuilderName),t},t._normalizeServiceName=function(e){return e=e.trim(),"/"!==e.substr(-1)?e+"/":e},r.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=ht._fetchObject(Ot,e.jsonResultsAdapter),new Nt(e)},r.qualifyUrl=function(e){var t=this.serviceName;return st.stringEndsWith(t,"/")&&(t=t.substr(0,t.length-1)),e="/"+e,st.stringEndsWith(t,e)||(t+=e),t},t}(),Ot=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.");lt(t).whereParam("name").isNonEmptyString().whereParam("extractResults").isFunction().isOptional().withDefault(e).whereParam("visitNode").isFunction().applyAll(this),ht._storeObject(this,r._$typeName,this.name)},r=t.prototype;return r._$typeName="JsonResultsAdapter",t}();nt.DataService=Nt,nt.JsonResultsAdapter=Ot;var At=_("Q");At||(At=function(){var e="Q is undefined. Are you missing Q.js? See https://github.com/kriskowal/q";throw new Error(e)},At.defer=At.resolve=At.reject=At),nt.config.setQ=function(e){nt.Q=At=e},nt.Q=At;var Ct=function(){function e(e){var t=[];for(var r in e){var n=e[r];r===n.name&&t.push(e[r])}return t}function t(e,t,r){var a=et(t.shortName,t.namespace),o=e._getEntityType(a,!0);if(o)return r?n(o,t):o;var s={shortName:t.shortName,namespace:t.namespace,isAbstract:t.isAbstract,autoGeneratedKeyType:It.fromName(t.autoGeneratedKeyType),defaultResourceName:t.defaultResourceName,custom:t.custom};if(o=t.isComplexType?new Mt(s):new Ft(s),t.baseTypeName){o.baseTypeName=t.baseTypeName;var u=e._getEntityType(t.baseTypeName,!0);u?i(e,t,o,u):P(e._deferredTypes,t.baseTypeName).push({json:t,stype:o})}else i(e,t,o);return o}function n(e,t){return t.custom&&(e.custom=t.custom),a(e,t.dataProperties),a(e,t.navigationProperties),e}function a(e,t){t&&t.forEach(function(t){var r=t.name;if(!r){if(!t.nameOnServer)throw new Error("Unable to complete 'importMetadata' - cannot locate a 'name' or 'nameOnServer' for one of the imported property nodes");r=e.metadataStore.namingConvention.serverPropertyNameToClient(t.nameOnServer,{})}if(t.custom){var n=e.getProperty(r,!0);n.custom=t.custom}})}function i(e,t,r){t.validators&&(r.validators=t.validators.map(vt.fromJSON)),t.dataProperties.forEach(function(e){r._addPropertyCore(Dt.fromJSON(e))});var n=!t.isComplexType;n&&t.navigationProperties&&t.navigationProperties.forEach(function(e){r._addPropertyCore(kt.fromJSON(e))}),e.addEntityType(r);var a=e._deferredTypes,o=a[r.name];o&&(o.forEach(function(t){i(e,t.json,t.stype)}),delete a[r.name])}function o(e,t,r){if(X(t))return t;var n=e._shortNameMap[t];if(!n&&r)throw new Error("Unable to locate 'entityTypeName' of: "+t);return n}var s=0,u=function(e){e=e||{},lt(e).whereParam("namingConvention").isOptional().isInstanceOf(Rt).withDefault(Rt.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 ft("metadataFetched",this)},c=u.prototype;return c._$typeName="MetadataStore",ft.bubbleEvent(c,null),u.ANONTYPE_PREFIX="_IB_",c.setProperties=function(e){lt(e).whereParam("name").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().applyAll(this)},c.addDataService=function(e,t){pt(e,"dataService").isInstanceOf(Nt).check(),pt(t,"shouldOverwrite").isBoolean().isOptional().check();var r=this._getDataServiceIndex(e.serviceName);if(r>=0){if(!t)throw new Error("A dataService with this name '"+e.serviceName+"' already exists in this MetadataStore");this.dataServices[r]=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 Ft||e instanceof Mt||(e=e.isComplexType?new Mt(e):new Ft(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 r=e.defaultResourceName||e.baseEntityType&&e.baseEntityType.defaultResourceName;r&&!this.getEntityTypeNameForResourceName(r)&&this.setEntityTypeForResourceName(r,e.name),e.defaultResourceName=r,e.getEntityCtor()}},c.exportMetadata=function(){var e=JSON.stringify({metadataVersion:nt.metadataVersion,name:this.name,namingConvention:this.namingConvention.name,localQueryComparisonOptions:this.localQueryComparisonOptions.name,dataServices:this.dataServices,structuralTypes:r(this._structuralTypeMap),resourceEntityTypeMap:this._resourceEntityTypeMap},null,ht.stringifyPad);return e},c.importMetadata=function(e,r){pt(r,"allowMerge").isOptional().isBoolean().check(),this._deferredTypes={};var n="string"==typeof e?JSON.parse(e):e;if(n.schema)return xt.parse(this,n.schema,n.altMetadata);if(n.metadataVersion&&n.metadataVersion!==nt.metadataVersion){var a=$("Cannot import metadata with a different 'metadataVersion' (%1) than the current 'breeze.metadataVersion' (%2) ",n.metadataVersion,nt.metadataVersion);throw new Error(a)}var i=n.namingConvention,o=n.localQueryComparisonOptions;if(this.isEmpty())this.namingConvention=ht._fetchObject(Rt,i)||this.namingConvention,this.localQueryComparisonOptions=ht._fetchObject(jt,o)||this.localQueryComparisonOptions;else{if(i&&this.namingConvention.name!==i)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;n.dataServices&&n.dataServices.forEach(function(e){e=Nt.fromJSON(e),s.addDataService(e,!0)});this._structuralTypeMap;return n.structuralTypes&&n.structuralTypes.forEach(function(e){t(s,e,r)}),p(this._resourceEntityTypeMap,n.resourceEntityTypeMap),p(this._incompleteTypeMap,n.incompleteTypeMap),this},u.importMetadata=function(e){var t=new Ct;return t.importMetadata(e),t},c.hasMetadataFor=function(e){return!!this.getDataService(e)},c.getDataService=function(e){return pt(e,"serviceName").isString().check(),e=Nt._normalizeServiceName(e),v(this.dataServices,function(t){return t.serviceName===e})},c.fetchMetadata=function(e,t,r){try{if(pt(e,"dataService").isString().or().isInstanceOf(Nt).check(),pt(t,"callback").isFunction().isOptional().check(),pt(r,"errorCallback").isFunction().isOptional().check(),"string"==typeof e&&(e=this.getDataService(e)||new Nt({serviceName:e})),e=Nt.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 n=this;return e.adapterInstance.fetchMetadata(this,e).then(function(r){return n.metadataFetched.publish({metadataStore:n,dataService:e,rawMetadata:r}),t&&t(r),At.resolve(r)},function(e){return r&&r(e),At.reject(e)})}catch(a){return At.reject(a)}},c.trackUnmappedType=function(e,t){pt(e,"entityCtor").isFunction().check(),pt(t,"interceptor").isFunction().isOptional().check();var r=new Ft(this);r._setCtor(e,t)},c.registerEntityTypeCtor=function(e,t,r,n){pt(e,"structuralTypeName").isString().check(),pt(t,"aCtor").isFunction().isOptional().check(),pt(r,"initFn").isOptional().isFunction().or().isString().check(),pt(n,"noTrackingFn").isOptional().isFunction().check();var a=o(this,e,!1),i=a||e;if(this._ctorRegistry[i]={ctor:t,initFn:r,noTrackingFn:n},a){var s=this._structuralTypeMap[a];s&&s.getCtor(!0)}},c.isEmpty=function(){return z(this._structuralTypeMap)},c.getEntityType=function(e,t){return pt(e,"structuralTypeName").isString().check(),pt(t,"okIfNotFound").isBoolean().isOptional().check(!1),this._getEntityType(e,t)},c._getEntityType=function(e,t){var r=o(this,e,!1),n=this._structuralTypeMap[r];if(!n){if(t)return null;var a=$("Unable to locate a 'Type' by the name: '%1'. Be sure to execute a query or call fetchMetadata first.",e);
throw new Error(a)}if(n.length){var i=n.join(",");throw new Error("There are multiple types with this 'shortName': "+i)}return n},c.getEntityTypes=function(){return e(this._structuralTypeMap)},c.getIncompleteNavigationProperties=function(){return r(this._incompleteTypeMap,function(e,t){return t})},c.getEntityTypeNameForResourceName=function(e){return pt(e,"resourceName").isString().check(),this._resourceEntityTypeMap[e]},c.setEntityTypeForResourceName=function(e,t){pt(e,"resourceName").isString().check(),pt(t,"entityTypeOrName").isInstanceOf(Ft).or().isString().check();var r;r=t instanceof Ft?t.name:o(this,t,!0),this._resourceEntityTypeMap[e]=r;var n=this._getEntityType(r,!0);n&&!n.defaultResourceName&&(n.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 r=this._getEntityType(t);r&&(e.entityType=r)}},u}(),xt=function(){function e(e,r,a){e._entityTypeResourceMap={},d(r).forEach(function(r){if(r.cSpaceOSpaceMapping){var a=JSON.parse(r.cSpaceOSpaceMapping),i={};a.forEach(function(e){i[e[0]]=e[1]}),r.cSpaceOSpaceMapping=i}r.entityContainer&&d(r.entityContainer).forEach(function(t){d(t.entitySet).forEach(function(t){var n=m(t.entityType,r).typeName;e.setEntityTypeForResourceName(t.name,n),e._entityTypeResourceMap[n]=t.name})}),r.complexType&&d(r.complexType).forEach(function(t){n(t,r,e)}),r.entityType&&d(r.entityType).forEach(function(n){t(n,r,e)})});var i=e.getIncompleteNavigationProperties();if(i.length>0){var o=i.map(function(e){return e.parentType.name+":"+e.name}).join(", ");throw new Error("Incomplete navigation properties: "+o)}return a&&e.importMetadata(a,!0),e}function t(e,t,n){var a=e.name,i=g(a,t),o=new Ft({shortName:a,namespace:i,isAbstract:e.abstract&&"true"===e.abstract});if(e.baseType){var s=m(e.baseType,t).typeName;o.baseTypeName=s;var u=n._getEntityType(s,!0);if(u)r(o,e,t,n);else{var p=n._deferredTypes[s];p||(p=[],n._deferredTypes[s]=p),p.push({entityType:o,csdlEntityType:e})}}else r(o,e,t,n);return o}function r(e,t,n,i){var o=t.key?d(t.key.propertyRef).map(s("name")):[];d(t.property).forEach(function(t){a(e,t,n,o)}),d(t.navigationProperty).forEach(function(t){u(e,t,n)}),i.addEntityType(e),e.defaultResourceName=i._entityTypeResourceMap[e.name];var p=i._deferredTypes,c=p[e.name];c&&(c.forEach(function(e){r(e.entityType,e.csdlEntityType,n,i)}),delete p[e.name])}function n(e,t,r){var n=e.name,i=g(n,t),o=new Mt({shortName:n,namespace:i});return d(e.property).forEach(function(e){a(o,e,t)}),r.addEntityType(o),o}function a(e,t,r,n){var a,s=t.type.split(".");return"Edm"===s[0]&&2===s.length?a=i(e,t,n):p(t,r)?(a=i(e,t,n),a&&(a.enumType=t.type)):a=o(e,t,r),a&&(e._addPropertyCore(a),y(a)),a}function i(e,t,r){var n=_t.fromEdmDataType(t.type);if(null==n)return e.warnings.push("Unable to recognize DataType for property: "+t.name+" DateType: "+t.type),null;var a="true"===t.nullable||null==t.nullable,i=null!=r&&r.indexOf(t.name)>=0;i&&e.autoGeneratedKeyType===It.None&&f(t)&&(e.autoGeneratedKeyType=It.Identity);var o=t.maxLength;o=null==o||"Max"===o?null:parseInt(o,10);var s=new Dt({nameOnServer:t.name,dataType:n,isNullable:a,isPartOfKey:i,maxLength:o,defaultValue:t.defaultValue,concurrencyMode:t.concurrencyMode});return n===_t.Undefined&&(s.rawTypeName=t.type),s}function o(e,t,r){var n=m(t.type,r).typeName,a=new Dt({nameOnServer:t.name,complexTypeName:n,isNullable:!1});return a}function u(e,t,r){var n=h(t,r),a=v(n.end,function(e){return e.role===t.toRole}),i="*"!==a.multiplicity,o=m(a.type,r).typeName,u=n.referentialConstraint;if(u||"*"!=n.end[0].multiplicity||"*"!=n.end[1].multiplicity){var p={nameOnServer:t.name,entityTypeName:o,isScalar:i,associationName:n.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 kt(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 r=d(t.enumType),n=e.type.split("."),a=n[n.length-1];return r.some(function(e){return e.name===a})}function l(e,t){var r=t.extensions.filter(function(e){return"EnumType"===e.name}),n=e.type.split("."),a=n[n.length-1];return r.some(function(e){return e.attributes.some(function(e){return"Name"===e.name&&e.value===a})})}function y(e){var t;if(e.isNullable||e.validators.push(vt.required()),!e.isComplexProperty){if(e.dataType===_t.String)if(e.maxLength){var r={maxLength:e.maxLength};t=vt.maxLength(r)}else t=vt.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 r=e.extensions;if(!r)return!1;var n=v(r,function(e){return"StoreGeneratedPattern"===e.name&&"Identity"===e.value});return!!n}function h(e,t){var r=m(e.relationship,t).shortTypeName,n=t.association;if(!n)return null;Array.isArray(n)||(n=[n]);var a=v(n,function(e){return e.name===r});return a}function m(e,t){if(!e)return null;if(L(e,Ct.ANONTYPE_PREFIX))return{shortTypeName:e,namespace:"",typeName:e,isAnonymous:!0};var r=e.split(",")[0],n=r.split(".");if(n.length>1){var a=n[n.length-1],i=null;if(t&&(i=g(a,t)),!i){var o=n.slice(0,n.length-1);i=o.join(".")}return{shortTypeName:a,namespace:i,typeName:et(a,i)}}return{shortTypeName:e,namespace:"",typeName:e}}function g(e,t){var r,n=t.cSpaceOSpaceMapping;if(n){var a=n[t.namespace+"."+e];if(r=a&&a.substr(0,a.length-(e.length+1)))return r}return t.entityType||"Default"!=t.namespace?t.namespace:null}var w=A(function(e){return e&&m(e).typeName});return{parse:e,normalizeTypeName:w}}(),Ft=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 r(e){return e.filter(function(e){return null==e.baseProperty})}function n(e,t,r){var n=r+"OnServer",a=t[r];if(a&&a.length){var i=d(a).map(function(r){var n=e.clientPropertyNameToServer(r,t),a=e.serverPropertyNameToClient(n,t);if(r!==a)throw new Error("NamingConvention for this client property name does not roundtrip properly:"+r+"-->"+a);return n});t[n]=Array.isArray(a)?i:i[0]}else{var o=t[n];if(!o||0===o.length)return;var s=d(o).map(function(r){var n=e.serverPropertyNameToClient(r,t),a=e.clientPropertyNameToServer(n,t);if(r!==a)throw new Error("NamingConvention for this server property name does not roundtrip properly:"+r+"-->"+a);return n});t[r]=Array.isArray(o)?s:s[0]}}function i(e,t){var r=t._getEntityType(e.complexTypeName,!0);if(!r)return!1;if(!(r instanceof Mt))throw new Error("Unable to resolve ComplexType with the name: "+e.complexTypeName+" for the property: "+property.name);return e.dataType=r,e.defaultValue=null,!0}function u(e,t){if(e.entityType)return!0;var r=t._getEntityType(e.entityTypeName,!0);if(r)e.entityType=r,e._resolveNp();else{var n=P(t._incompleteTypeMap,e.entityTypeName);w(n,e)}return!!r}function p(e,t){var r=e.getPropertyNames(),n=dt.getDefaultInstance(),i=n.getTrackablePropertyNames(t);i.forEach(function(n){if(-1===r.indexOf(n)){var i=t[n];try{"function"==typeof i&&(i=i())}catch(o){}var s=_t.fromValue(i),u=new Dt({name:n,dataType:s,isNullable:!0,isUnmapped:!0});u.isSettable=a(t,n),e.subtypes?e.getSelfAndSubtypes().forEach(function(e){e._addPropertyCore(new Dt(u))}):e._addPropertyCore(u)}})}var c=0,l=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_"+ ++c,this.namespace="",this.isAnonymous=!0):lt(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("baseTypeName").isString().isOptional().whereParam("isAbstract").isBoolean().isOptional().withDefault(!1).whereParam("autoGeneratedKeyType").isEnumOf(It).isOptional().withDefault(It.None).whereParam("defaultResourceName").isNonEmptyString().isOptional().withDefault(null).whereParam("dataProperties").isOptional().whereParam("navigationProperties").isOptional().whereParam("serializerFn").isOptional().isFunction().whereParam("custom").isOptional().applyAll(this),this.name=et(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=[],tt(this,e.dataProperties,Dt),tt(this,e.navigationProperties,kt)},f=l.prototype,h=_t.parseRawValue;return f._$typeName="EntityType",l.qualifyTypeName=et,f.setProperties=function(e){lt(e).whereParam("autoGeneratedKeyType").isEnumOf(It).isOptional().whereParam("defaultResourceName").isString().isOptional().whereParam("serializerFn").isFunction().isOptional().whereParam("custom").isOptional().applyAll(this),e.defaultResourceName&&(this.defaultResourceName=e.defaultResourceName)},f.isSubtypeOf=function(e){pt(e,"entityType").isInstanceOf(Ft).check();var t=this;do{if(t===e)return!0;t=t.baseEntityType}while(t);return!1},f.getSelfAndSubtypes=function(){var e=[this];return this.subtypes.forEach(function(t){var r=t.getSelfAndSubtypes();e.push.apply(e,r)}),e},f.getAllValidators=function(){for(var e=this.validators.slice(0),t=this.baseEntityType;t;)e.push.apply(e,t.validators),t=t.baseEntityType;return e},f.addProperty=function(e){return pt(e,"property").isInstanceOf(Dt).or().isInstanceOf(kt).check(),this._addPropertyCore(e,!0)},f._updateFromBase=function(e){this.baseEntityType=e,this.autoGeneratedKeyType===It.None&&(this.autoGeneratedKeyType=e.autoGeneratedKeyType),e.dataProperties.forEach(function(e){var t=new Dt(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.navigationProperties.forEach(function(e){var t=new kt(e);t.validators=[],t.baseProperty=e,this._addPropertyCore(t)},this),e.subtypes.push(this)},f._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 r=e.parentType;if(r){if(r!==this)throw new Error("This property: "+e.name+" has already been added to "+e.parentType.name);return this}e.parentType=this;var a=this.metadataStore;return e.isDataProperty?this._addDataProperty(e):(this._addNavigationProperty(e),t&&a&&u(e,a)),!a||e.name&&e.nameOnServer||n(a.namingConvention,e,"name"),this},f.createEntity=function(t){if(t&&t._$eref&&!t._$eref.entityAspect.entityManager)return t._$eref;var r=this._createInstanceCore();return t&&(this.keyProperties.every(function(e){return null!=t[e.name]})&&(t._$eref=r),this._updateTargetFromRaw(r,t,e),this.navigationProperties.forEach(function(e){var n,a=t[e.name];if(void 0!=a){var i=e.entityType;if(e.isScalar)n=a.entityAspect?a:i.createEntity(a),r.setProperty(e.name,n);else{var o=r.getProperty(e.name);a.forEach(function(e){n=e.entityAspect?e:i.createEntity(e),o.push(n)})}}})),this._initializeInstance(r),r},f._createInstanceCore=function(){var e=this.getEntityCtor(),t=new e;return new St(t),t},f._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 r=e.getProperty(t.name);Array.isArray(r)?r.forEach(function(e){t.dataType._initializeInstance(e)}):t.dataType._initializeInstance(r)}),e.entityAspect&&(e.entityAspect._initialized=!0)},f.getCtor=f.getEntityCtor=function(e){if(this._ctor&&!e)return this._ctor;var r=this.metadataStore._ctorRegistry,n=r[this.name]||r[this.shortName]||{},a=n.ctor||this._ctor,i=a&&a.prototype&&(a.prototype.entityType||a.prototype.complexType);if(i&&i.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(n.ctor&&e&&(this._extra=void 0),!a){var o=dt.getDefaultInstance().createCtor;a=o?o(this):t(this)}return this.initFn=n.initFn,this.noTrackingFn=n.noTrackingFn,a.prototype._$typeName=this.name,this._setCtor(a),a},f._setCtor=function(e,t){var r=e.prototype;this._extra=this._extra||{};var n=new e;p(this,n),"EntityType"===this._$typeName?r.entityType=this:r.complexType=this,r._$interceptor=t||J,dt.getDefaultInstance().initializeEntityPrototype(r),this._ctor=e},f.addValidator=function(e,t){pt(e,"validator").isInstanceOf(vt).check(),pt(t,"property").isOptional().isString().or().isEntityProperty().check(),t?("string"==typeof t&&(t=this.getProperty(t,!0)),t.validators.push(e)):this.validators.push(e)},f.getProperties=function(){return this.dataProperties.concat(this.navigationProperties)},f.getPropertyNames=function(){return this.getProperties().map(s("name"))},f.getDataProperty=function(e){return v(this.dataProperties,o("name",e))},f.getNavigationProperty=function(e){return v(this.navigationProperties,o("name",e))},f.getProperty=function(e,t){var r=this.getPropertiesOnPath(e,!1,t);return r?r[r.length-1]:null},f.getPropertiesOnPath=function(e,t,r){r=r||!1;var n=Array.isArray(e)?e:e.trim().split("."),a=!0,i=this,s=t?"nameOnServer":"name",u=n.map(function(e){var t=v(i.getProperties(),o(s,e));if(t)i=t.isNavigationProperty?t.entityType:t.dataType;else{if(r)throw new Error("unable to locate property: "+e+" on entityType: "+i.name);a=!1}return t});return a?u:null},f.clientPropertyPathToServer=function(e,t){var r,t=t||".";if(this.isAnonymous){var n=this.metadataStore.namingConvention.clientPropertyNameToServer;r=e.split(".").map(function(e){return n(e)})}else r=this.getPropertiesOnPath(e,!1,!0).map(function(e){return e.nameOnServer});return r.join(t)},f.getEntityKeyFromRawEntity=function(e,t){var r=this.keyProperties.map(function(r){var n=t(e,r);return h(n,r.dataType)});return new Pt(this,r)},f._updateTargetFromRaw=function(e,t,r){this.dataProperties.forEach(function(n){if(n.isSettable){var a=r(t,n);if(void 0!==a){var i,o=n.dataType;if(n.isComplexProperty){if(null===a)return;i=e.getProperty(n.name),n.isScalar?o._updateTargetFromRaw(i,a,r):(i.length=0,Array.isArray(a)&&a.forEach(function(t){var a=o._createInstanceCore(e,n);o._updateTargetFromRaw(a,t,r),o._initializeInstance(a),i.push(a)}))}else{var s;n.isScalar?(s=h(a,o),e.setProperty(n.name,s)):(i=e.getProperty(n.name),i.length=0,Array.isArray(a)&&a.forEach(function(e){s=h(e,o),i.push(s)}))}}}});var n=t.entityAspect||t.complexAspect;if(n){var a=e.entityAspect||e.complexAspect;n.originalValuesMap&&(a.originalValues=n.originalValuesMap),n.extraMetadata&&(a.extraMetadata=n.extraMetadata)}},f.toString=function(){return this.name},f.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})},f._updateNames=function(e){var t=this.metadataStore.namingConvention;n(t,e,"name"),e.isNavigationProperty&&(n(t,e,"foreignKeyNames"),n(t,e,"invForeignKeyNames"))},f._checkNavProperty=function(e){if(e.isNavigationProperty){if(e.parentType!==this)throw new Error($("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")},f._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)},f._addNavigationProperty=function(e){this.navigationProperties.push(e),X(e.entityTypeName)||(e.entityTypeName=et(e.entityTypeName,this.namespace))},f._updateCps=function(){var e=this.metadataStore,t=e._incompleteComplexTypeMap;this.complexProperties.forEach(function(r){r.complexType||i(r,e)||P(t,r.complexTypeName).push(r)}),this.isComplexType&&((t[this.name]||[]).forEach(function(t){i(t,e)}),delete t[this.name])},f._updateNps=function(){var e=this.metadataStore;this.navigationProperties.forEach(function(t){u(t,e)});var t=e._incompleteTypeMap;(t[this.name]||[]).forEach(function(t){u(t,e)}),delete t[this.name]},l}(),Mt=function(){var e=function(e){if(arguments.length>1)throw new Error("The ComplexType ctor has a single argument that is a configuration object.");lt(e).whereParam("shortName").isNonEmptyString().whereParam("namespace").isString().isOptional().withDefault("").whereParam("dataProperties").isOptional().whereParam("isComplexType").isOptional().isBoolean().whereParam("custom").isOptional().applyAll(this),this.name=et(this.shortName,this.namespace),this.isComplexType=!0,this.dataProperties=[],this.complexProperties=[],this.validators=[],this.concurrencyProperties=[],this.unmappedProperties=[],this.navigationProperties=[],this.keyProperties=[],tt(this,e.dataProperties,Dt)},t=e.prototype;return t.setProperties=function(e){lt(e).whereParam("custom").isOptional().applyAll(this)},t.getAllValidators=function(){return this.validators},t._createInstanceCore=function(e,t){var r=this.getCtor(),n=new r;return new Tt(n,e,t),n},t.addProperty=function(e){return pt(e,"dataProperty").isInstanceOf(Dt).check(),this._addPropertyCore(e)},t.getProperties=function(){return this.dataProperties},t=p(t,Ft.prototype,["addValidator","getProperty","getPropertiesOnPath","getPropertyNames","_addPropertyCore","_addDataProperty","_updateNames","_updateCps","_initializeInstance","_updateTargetFromRaw","_setCtor"]),t.createInstance=Ft.prototype.createEntity,t.getCtor=Ft.prototype.getEntityCtor,t.toJSON=function(){return y(this,{shortName:null,namespace:null,isComplexType:null,dataProperties:null,validators:null,custom:null})},t._$typeName="ComplexType",e}(),Dt=function(){var e=function(e){lt(e).whereParam("name").isString().isOptional().whereParam("nameOnServer").isString().isOptional().whereParam("dataType").isEnumOf(_t).isOptional().or().isString().or().isInstanceOf(Mt).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(vt).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 r=_t.fromName(this.dataType);if(!r)throw new Error("Unable to find a DataType enumeration by the name of: "+this.dataType);this.dataType=r}else this.dataType||(this.dataType=_t.String);if(null==this.defaultValue){if(this.isNullable)this.defaultValue=null;else if(this.isComplexProperty);else if(this.dataType===_t.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 r=e[t.nameOnServer];return void 0!==r?r:t.defaultValue},e.getRawValueFromClient=function(e,t){var r=e[t.name];return void 0!==r?r:t.defaultValue},t.isDataProperty=!0,t.isNavigationProperty=!1,t.resolveProperty=function(e){for(var t=this[e],r=this.baseProperty;void 0==t&&null!=r;)t=r[e],r=r.baseProperty;return t},t.formatName=function(){return this.parentType.name+"--"+this.name},t.setProperties=function(e){lt(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=_t.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(vt.fromJSON)),new Dt(e)},e}(),kt=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 r(e){var t=e.foreignKeyNames;if(0!==t.length){var r=e.parentType,n=t.map(function(e){return r.getDataProperty(e)}),a=r.foreignKeyProperties;n.forEach(function(t){w(a,t),t.relatedNavigationProperty=e,w(e.entityType.inverseForeignKeyProperties,t),e.relatedDataProperties?w(e.relatedDataProperties,t):e.relatedDataProperties=[t]})}}var n=function(e){lt(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(vt).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")},a=n.prototype;return a._$typeName="NavigationProperty",a.isDataProperty=!1,a.isNavigationProperty=!0,p(a,Dt.prototype,["formatName","getAllValidators","resolveProperty"]),a.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,lt(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)},a.setInverse=function(t){var r;if(r="string"==typeof t?this.entityType.getNavigationProperty(t):t,!r)throw e(this,"Unable to find inverse property: "+invNpName);(this.inverse||r.inverse)&&e(this,"It has already been set on one side or the other."),r.entityType!=this.parentType&&e(this,r.formatName+" is not a valid inverse property for this."),this.associationName?r.associationName=this.associationName:(r.associationName||(r.associationName=this.formatName()+"_"+r.formatName()),this.associationName=r.associationName),this._resolveNp(),r._resolveNp()},a.createInverse=function(e){this.entityType||t(this,"has not yet been defined."),this.entityType.isFrozen&&t(this,"is frozen.");var r=this.entityType.metadataStore;null==r&&t(this,"has not yet been added to the metadataStore."),e.entityTypeName=this.parentEntityType.name,e.associationName=this.associationName;var n=new kt(e);return this.parentEntityType.addNavigationProperty(n),n},a.toJSON=function(){return y(this,{name:null,entityTypeName:null,isScalar:null,associationName:null,validators:null,displayName:null,foreignKeyNames:null,invForeignKeyNames:null,custom:null})},n.fromJSON=function(e){return e.validators&&(e.validators=e.validators.map(vt.fromJSON)),new kt(e)},a._resolveNp=function(){var e=this,t=e.entityType,n=v(t.navigationProperties,function(t){return t.associationName===e.associationName&&(t.name!==e.name||t.entityTypeName!==e.entityTypeName)});e.inverse=n,n||e.invForeignKeyNames.forEach(function(r){var n=t.getDataProperty(r);if(!n)throw new Error("EntityType '"+e.entityTypeName+"' has no foreign key matching '"+r+"'");var a=e.parentType;n.inverseNavigationProperty=v(a.navigationProperties,function(e){return e.invForeignKeyNames&&e.invForeignKeyNames.indexOf(n.name)>=0&&e.entityType===n.parentType}),w(t.foreignKeyProperties,n)}),r(e)},n}(),It=function(){var e=new yt("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 r=ut.prototype;r.isEntity=function(){return this._addContext({fn:e,msg:" must be an entity"})},r.isEntityProperty=function(){return this._addContext({fn:t,msg:" must be either a DataProperty or a NavigationProperty"})}}(),nt.MetadataStore=Ct,nt.EntityType=Ft,nt.ComplexType=Mt,nt.DataProperty=Dt,nt.NavigationProperty=kt,nt.AutoGeneratedKeyType=It,Ct.normalizeTypeName=xt.normalizeTypeName;var Vt=function(){function e(e,t,r){var n=t.name+".."+t.parentType.name,a=e._tempIdMap[n];return a||r&&(a={entityType:t.parentType,propertyName:t.name,keyMap:{}},e._tempIdMap[n]=a),a}var t=function(){this._tempIdMap={}},r=t.prototype;return r.generateTempKeyValue=function(t,r){var n=t.keyProperties;if(n.length>1)throw new Error("Ids can not be autogenerated for entities with multipart keys");var a,i=n[0],o=e(this,i,!0);if(null!=r&&(o.keyMap[r.toString()]||(a=r)),void 0===a){var s=i.dataType;if(!s.getNext)throw new Error("Cannot use a property with a dataType of: "+s.toString()+" for id generation");for(a=s.getNext(this);null!=o.keyMap[a.toString()];)a=s.getNext(this)}return o.keyMap[a.toString()]=!0,a},r.getTempKeys=function(){var e=[];for(var t in this._tempIdMap){var r=this._tempIdMap[t],n=r.entityType;for(var a in r.keyMap)e.push(new Pt(n,[a]))}return e},r.isTempKey=function(t){var r=t.entityType.keyProperties;if(r.length>1)return!1;var n=r[0],a=e(this,n);return a?void 0!==a.keyMap[t.values[0].toString()]:!1},ht.registerType(t,"KeyGenerator"),t}();nt.KeyGenerator=Vt;var jt=function(){var e=function(e){lt(e||{}).whereParam("name").isOptional().isString().whereParam("isCaseSensitive").isOptional().isBoolean().whereParam("usesSql92CompliantStringComparison").isBoolean().applyAll(this),this.name||(this.name=C()),ht._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}();nt.LocalQueryComparisonOptions=jt;var Rt=function(){var e=function(e){lt(e||{}).whereParam("name").isOptional().isString().whereParam("serverPropertyNameToClient").isFunction().whereParam("clientPropertyNameToServer").isFunction().applyAll(this),this.name||(this.name=C()),ht._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}();nt.NamingConvention=Rt;var Kt=function(){function e(e,n){var a=n.entityType;if(Array.isArray(e)){if(!n.isRHS)throw new Error("Array expressions are only permitted on the right hand side of a BinaryPredicate");return new y(e,n.dataType)}if(!j(e)){if(null!=e&&R(e)&&!k(e)){if(void 0===e.value)throw new Error("Unable to resolve an expression for: "+e+" on entityType: "+a.name);return e.isProperty?new f(e.value):new y(e.value,e.dataType||n.dataType,!0)}return new y(e,n.dataType)}if(n.isRHS)return null==a||a.isAnonymous?new y(e,n.dataType):r(e,n);for(var i,o=/\([^()]*\)/,s=[],u=0;i=o.exec(e);){var p=i[0];s.push(p);var c=g+u++;e=e.replace(p,c)}var l=t(e,s,n);return l._validate(a,n.usesNameOnServer),l}function t(e,t,a){var i=e.split(g);return 1===i.length?r(i[0],a):n(e,i,t,a)}function r(e,t){e=e.trim();var r=e.substr(0,1),n=("'"===r||'"'===r)&&e.length>1&&e.substr(e.length-1)===r;if(n){var a=e.substr(1,e.length-2);return new y(a,t.dataType||_t.String)}var i=t.entityType;if(null==i||i.isAnonymous)return new f(e);var o=d.test(e);return o&&null!=i.getPropertiesOnPath(e,t.usesNameOnServer,!1)?new f(e):new y(e,t.dataType)}function n(e,r,n,a){try{var i=r[0].trim().toLowerCase(),o=n[r[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({},a);c.dataType=_t.Undefined,c.isFnArg=!0;var l=u.map(function(e){return t(e,n,c)});return new h(i,l)}catch(y){return null}}var a=function(){function e(e,t,r){var n=t.toLowerCase();r.key=n,e[n]=r,r.aliases&&r.aliases.forEach(function(t){e[t.toLowerCase()]=r})}function t(e){var n={},a={};n[e[0]]=a;var i=e[1];return i=i.operator||i,a[i]=3==e.length?e[2]:t(e.splice(2)),r(n)}function r(e){if(e instanceof a)return e;if("object"!=typeof e)throw new Error("Unable to convert to a Predicate: "+e);var t=Object.keys(e),r=t.map(function(t){return n(t,e[t])});return 1===r.length?r[0]:new u("and",r)}function n(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(at(t,"value"))return new s("eq",e,t);if(Array.isArray(t))throw new Error("Unable to resolve predicate after the phrase: "+e);var r=e,n=Object.keys(t),a=n.map(function(e){if(c.prototype._resolveOp(e,!0))return new c(e,r,t[e]);if(s.prototype._resolveOp(e,!0))return new s(e,r,t[e]);if(at(t[e],"value"))return new s("eq",r,t[e]);var n=$("Unable to resolve predicate after the phrase: '%1' for operator: '%2' and value: '%3'",r,e,t[e]);throw new Error(n)});return 1===a.length?a[0]:new u("and",a)}var p=function(){if(0!==arguments.length){if(1===arguments.length){var e=arguments[0];return Array.isArray(e)?1===e.length?a(e[0]):t(e):e instanceof a?e:"string"==typeof e?new i(e):r(e)}return t(Array.prototype.slice.call(arguments,0))}},l=p.prototype;return p.create=p,p.and=function(){var e=new u("and",it(arguments));return e.op&&e},p.or=function(){var e=new u("or",it(arguments));return e.op&&e},p.not=function(e){return e.not()},p.extendBinaryPredicateFn=function(t,r){var n=w.binaryPredicate;for(var a in t||{}){var i=t[a];i.visitorFn=r,e(s.prototype.aliasMap,a,t[a])}w.isExtended||(w.binaryPredicate=function(e,t,r){var a=this.aliasMap[this.op.key].visitorFn;return a?a(e,t,r):n(e,t,r)},w.isExtended=!0)},l.and=function(){var e=a(it(arguments));
return new u("and",[this,e])},l.or=function(){var e=a(it(arguments));return new u("or",[this,e])},l.not=function(){return new o("not",this)},l.toJSON=function(){return this.toJSONExt({entityType:this._entityType})},l.toJSONExt=function(e){return this.visit(e,E)},l.toFunction=function(e){return this.visit(e,w)},l.toString=function(){return JSON.stringify(this)},l.visit=function(e,t){if(z(e))e={entityType:null};else if(e instanceof Ft)e={entityType:e};else if(!at(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 r=t[this.visitorMethodName];if(null==r)throw new Error("Unable to locate method: "+this.visitorMethodName+" on visitor");var n=e.entityType;(this._validate&&null==n||this._entityType!==n)&&(this._validate(n,e.usesNameOnServer),this._entityType=n);Array.prototype.slice.call(arguments,1);return r.call(this,e)},l._initialize=function(t,r){this.visitorMethodName=t;var n=this.aliasMap={};for(var a in r||{})e(n,a,r[a])},l._resolveOp=function(e,t){e=e.operator||e;var r=this.aliasMap[e.toLowerCase()];if(!r&&!t)throw new Error("Unable to resolve operator: "+e);return r},p}(),i=function(){var e=function(e){this.value=e},t=e.prototype=new a;return t._initialize("passthruPredicate"),t._validate=F,e}(),o=function(){var e=function(e,t){this.op=this._resolveOp(e),this.pred=a(t)},t=e.prototype=new a;return t._initialize("unaryPredicate",{not:{aliases:["!","~"]}}),t._validate=function(e,t){this.pred._validate(e,t)},e}(),s=function(){var t=function(e,t,r){this.op=this._resolveOp(e),this.expr1Source=t,this.expr2Source=r},r=t.prototype=new a;return r._initialize("binaryPredicate",{eq:{aliases:["=="]},ne:{aliases:["!=","~="]},lt:{aliases:["<"]},le:{aliases:["<="]},gt:{aliases:[">"]},ge:{aliases:[">="]},startswith:{isFunction:!0},endswith:{isFunction:!0},contains:{aliases:["substringof"],isFunction:!0},"in":{}}),r._validate=function(t,r){var n={entityType:t,usesNameOnServer:r};if(this.expr1=e(this.expr1Source,n),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 a=p(n,{isRHS:!0,dataType:this.expr1.dataType});if(this.expr2=e(this.expr2Source,a),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 a(e)}),0==this.preds.length&&(this.op=null),1==this.preds.length?this.preds[0]:void 0},t=e.prototype=new a;return t._initialize("andOrPredicate",{and:{aliases:["&&"]},or:{aliases:["||"]}}),t._validate=function(e,t){this.preds.every(function(r){r._validate(e,t)})},e}(),c=function(){var t=function(e,t,r){this.op=this._resolveOp(e),this.exprSource=t,this.pred=a(r)},r=t.prototype=new a;return r._initialize("anyAllPredicate",{any:{aliases:["some"]},all:{aliases:["every"]}}),r._validate=function(t,r){this.expr=e(this.exprSource,{entityType:t,usesNameOnServer:r}),(null==t||t.isAnonymous)&&(this.expr.dataType=null),this.pred._validate(this.expr.dataType,r)},t}(),l=function(e){this.visitorMethodName=e,this.visit=a.prototype.visit,this._validate=F},y=function(){function e(e){if(null==e)return e;if(_t.contains(e))return e;if(j(e)){var t=_t.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,r,n){r=e(r),r=r||_t.fromValue(t),this.value=r&&r.parse?Array.isArray(t)?t.map(function(e){return r.parse(e,typeof e)}):r.parse(t,typeof t):t,this.dataType=r,this.hasExplicitDataType=n},r=t.prototype=new l("litExpr");return r.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 r=e.getPropertiesOnPath(this.propertyPath,t,!1);if(!r){var n=$("Unable to resolve propertyPath. EntityType: '%1' PropertyPath: '%2'",e.name,this.propertyPath);throw new Error(n)}var a=r[r.length-1];this.dataType=a.isDataProperty?a.dataType:a.entityType}},e}(),h=function(){var e=function(e,t){this.fnName=e,this.exprs=t;var n=r[e];if(null==n)throw new Error("Unknown function: "+e);this.localFn=n.fn,this.dataType=n.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(r){r._validate(e,t)})};var r=e.funcMap={toupper:{fn:function(e){return e.toUpperCase()},dataType:_t.String},tolower:{fn:function(e){return e.toLowerCase()},dataType:_t.String},substring:{fn:function(e,t,r){return e.substring(t,r)},dataType:_t.String},substringof:{fn:function(e,t){return t.indexOf(e)>=0},dataType:_t.Boolean},length:{fn:function(e){return e.length},dataType:_t.Int32},trim:{fn:function(e){return e.trim()},dataType:_t.String},concat:{fn:function(e,t){return e.concat(t)},dataType:_t.String},replace:{fn:function(e,t,r){return e.replace(t,r)},dataType:_t.String},startswith:{fn:function(e,t){return L(e,t)},dataType:_t.Boolean},endswith:{fn:function(e,t){return U(e,t)},dataType:_t.Boolean},indexof:{fn:function(e,t){return e.indexOf(t)},dataType:_t.Int32},round:{fn:function(e){return Math.round(e)},dataType:_t.Int32},ceiling:{fn:function(e){return Math.ceil(e)},dataType:_t.Int32},floor:{fn:function(e){return Math.floor(e)},dataType:_t.Int32},second:{fn:function(e){return e.getSeconds()},dataType:_t.Int32},minute:{fn:function(e){return e.getMinutes()},dataType:_t.Int32},day:{fn:function(e){return e.getDate()},dataType:_t.Int32},month:{fn:function(e){return e.getMonth()+1},dataType:_t.Int32},year:{fn:function(e){return e.getFullYear()},dataType:_t.Int32}};return e}(),d=/^[a-z_][\w.$]*$/i,m=/('[^']*'|[^,]+)/g,v=/("[^"]*"|[^,]+)/g,g=String.fromCharCode(191),w=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=_t.getComparableFn(t);switch(u.key){case"eq":s=function(e,t){return e&&"string"==typeof e?r(e,t,o):p(e)==p(t)};break;case"ne":s=function(e,t){return e&&"string"==typeof e?!r(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 n(e,t,o)};break;case"endswith":s=function(e,t){return a(e,t,o)};break;case"contains":s=function(e,t){return i(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 r(e,t,r){return null==t?!1:("string"!=typeof t&&(t=t.toString()),r.usesSql92CompliantStringComparison&&(e=(e||"").trim(),t=(t||"").trim()),r.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),e===t)}function n(e,t,r){return r.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),L(e,t)}function a(e,t,r){return r.isCaseSensitive||(e=(e||"").toLowerCase(),t=(t||"").toLowerCase()),U(e,t)}function i(e,t,r){return r.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 r=this.expr1.visit(e),n=this.expr2.visit(e),a=this.expr1.dataType||this.expr2.dataType,i=e.entityType.metadataStore.localQueryComparisonOptions,o=t(this,a,i);if(null==o)throw new Error("Invalid binaryPredicate operator:"+this.op.key);return function(e){return o(r(e),n(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 r=t.reduce(function(t,r){return t&&r(e)},!0);return r};case"or":return function(e){var r=t.reduce(function(t,r){return t||r(e)},!1);return r};default:throw new Error("Invalid boolean operator:"+op.key)}},anyAllPredicate:function(t){var r=this.expr.visit(t),n=p({},t);n.entityType=this.expr.dataType;var a=this.pred.visit(n),i=e(this.op);return function(e){return i(r(e),a)}},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 rt(e,t)}},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)}),r=this;return function(e){var n=t.map(function(t){var r=t(e);return r}),a=r.localFn.apply(null,n);return a}}};return o}(),E=function(){function e(t,r){var n=Object.keys(r).every(function(n){if(t.hasOwnProperty(n)){if("object"!=typeof r[n])return!1;if(null==e(t[n],r[n]))return!1}else t[n]=r[n];return!0});return n?t:null}var t={passthruPredicate:function(){return this.value},unaryPredicate:function(e){var t=this.pred.visit(e),r={};return r[this.op.key]=t,r},binaryPredicate:function(e){var t=this.expr1.visit(e),r=this.expr2.visit(e),n={};if(this.expr2 instanceof f&&(r={value:r,isProperty:!0}),"eq"===this.op.key)n[t]=r;else{var a={};n[t]=a,a[this.op.key]=r}return n},andOrPredicate:function(t){var r,n=this.preds.map(function(e){return e.visit(t)});return"and"!==this.op.key||2!==n.length||n.some(j)||(r=n.reduce(e)),null==r&&(r={},r[this.op.key]=n),r},anyAllPredicate:function(e){var t=this.expr.visit(e),r=p({},e);r.entityType=this.expr.dataType;var n=this.pred.visit(r),a={},i={};return i[this.op.key]=n,a[t]=i,a},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 a}();nt.Predicate=Kt;var qt=function(){function e(e,t){return y(t,{"resourceName,from":null,"resultEntityType,toType":null,"wherePredicate,where":function(e){return e?new Kt(e):void 0},"orderByClause,orderBy":function(e){return e?new Bt(e):void 0},"selectClause,select":function(e){return e?new Lt(e):void 0},"expandClause,expand":function(e){return e?new Ut(e):void 0},"skipCount,skip":null,"takeCount,take":null,parameters:function(e){return z(e)?void 0:e},"inlineCountEnabled,inlineCount":!1,"noTrackingEnabled,noTracking":!1,queryOptions:function(e){return e?Jt.fromJSON(e):void 0}},e),e}function r(e,t,r){if(t&&e[t]===r)return e;var n=p(new qt,e,["resourceName","fromEntityType","wherePredicate","orderByClause","selectClause","skipCount","takeCount","expandClause","inlineCountEnabled","noTrackingEnabled","usesNameOnServer","queryOptions","entityManager","dataService","resultEntityType"]);return n.parameters=p({},e.parameters),t&&(n[t]=r),n}function n(e,r,a,i){var o=a._$typeName||a.parentEnum&&a.parentEnum.name,s=o&&o.substr(0,1).toLowerCase()+o.substr(1);if(i&&s!=i)throw new Error("Invalid value for property: "+i);if(s){var u=r[s];if(void 0===u)throw new Error("Invalid config property: "+s);null===u?e[s]=a:u(e,a)}else t(a,function(t,a){n(e,r,a,t)})}function a(e){return pt(e,"propertyPaths").isOptional().isString().or().isArray().isString().check(),"string"==typeof e&&(e=e.split(",")),e=e.map(function(e){return e.trim()})}function i(e){var t=e.entityType,r=t.keyProperties.map(function(t){return Kt.create(t.name,zt.Equals,e.getProperty(t.name))}),n=Kt.and(r);return n}function o(e){var t=e.entityType.keyProperties,r=S(t,e.values,function(e,t){return Kt.create(e.name,zt.Equals,t)}),n=Kt.and(r);return n}function s(e,t){if(t.isScalar){if(0===t.foreignKeyNames.length)return null;var r=t.foreignKeyNames.map(function(t){return e.getProperty(t)}),n=new Pt(t.entityType,r);return o(n)}var a=t.inverse,i=a?a.foreignKeyNames:t.invForeignKeyNames;if(0===i.length)return null;var s=e.entityAspect.getKey().values,u=S(i,s,function(e,t){return Kt.create(e,zt.Equals,t)});return Kt.and(u)}var u=function(t){return null==t||j(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 pt(e,"resourceName").isString().check(),r(this,"resourceName",e)},u.from=function(e){return pt(e,"resourceName").isString().check(),new qt(e)},c.toType=function(e){return pt(e,"entityType").isString().or().isInstanceOf(Ft).check(),r(this,"resultEntityType",e)},c.where=function(e){return null!=e&&(e=Kt.create(it(arguments)),this.fromEntityType&&e._validate(this.fromEntityType),this.wherePredicate&&(e=this.wherePredicate.and(e))),r(this,"wherePredicate",e)},c.orderBy=function(e,t){var n=null==e?null:new Bt(a(e),t);return this.orderByClause&&n&&(n=new Bt([this.orderByClause,n])),r(this,"orderByClause",n)},c.orderByDesc=function(e){return this.orderBy(e,!0)},c.select=function(e){var t=null==e?null:new Lt(a(e));return r(this,"selectClause",t)},c.skip=function(e){return pt(e,"count").isOptional().isNumber().check(),r(this,"skipCount",null==e?null:e)},c.top=function(e){return this.take(e)},c.take=function(e){return pt(e,"count").isOptional().isNumber().check(),r(this,"takeCount",null==e?null:e)},c.expand=function(e){var t=null==e?null:new Ut(a(e));return r(this,"expandClause",t)},c.withParameters=function(e){return pt(e,"parameters").isObject().check(),r(this,"parameters",e)},c.inlineCount=function(e){return pt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,r(this,"inlineCountEnabled",e)},c.useNameOnServer=function(e){return pt(e,"usesNameOnServer").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,r(this,"usesNameOnServer",e)},c.noTracking=function(e){return pt(e,"enabled").isBoolean().isOptional().check(),e=void 0===e?!0:!!e,r(this,"noTrackingEnabled",e)},c.using=function(e){if(!e)return this;var t=r(this);return n(t,{entityManager:null,dataService:null,queryOptions:null,fetchStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Jt).using(t)},mergeStrategy:function(e,t){e.queryOptions=(e.queryOptions||new Jt).using(t)},jsonResultsAdapter:function(e,t){e.dataService=(e.dataService||new Nt).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?j(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 z(e)?void 0:e},"inlineCount,inlineCountEnabled":!1,"noTracking,noTrackingEnabled":!1,queryOptions:null})},u.fromEntities=function(e){pt(e,"entities").isEntity().or().isNonEmptyArray().isEntity().check(),Array.isArray(e)||(e=it(arguments));var t=e[0],r=new qt(t.entityType.defaultResourceName),n=e.map(function(e){return i(e)}),a=Kt.or(n);r=r.where(a);var o=t.entityAspect.entityManager;return o&&(r=r.using(o)),r},u.fromEntityKey=function(e){pt(e,"entityKey").isInstanceOf(Pt).check();var t=new qt(e.entityType.defaultResourceName),r=o(e);return t=t.where(r).toType(e.entityType)},u.fromEntityNavigation=function(e,t){pt(e,"entity").isEntity().check();var r=e.entityType._checkNavProperty(t),n=new qt(r.entityType.defaultResourceName),a=s(e,r);n=n.where(a);var i=e.entityAspect.entityManager;return i?n.using(i):n},c._getFromEntityType=function(e,t){var r=this.fromEntityType;if(r)return r;var n=this.resourceName;if(!n)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 a=e.getEntityTypeNameForResourceName(n);if(r=a?e._getEntityType(a):this._getToEntityType(e,!0),!r){if(t)throw new Error($("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.",n));return null}return this.fromEntityType=r,r},c._getToEntityType=function(e,t){return this.resultEntityType instanceof Ft?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=Nt.resolve([e.dataService]);return t.uriBuilder.buildUri(this,e.metadataStore)},u}(),zt=function(){var e=new yt("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._map=function(){var t={};return e.getSymbols().forEach(function(e){t[e.name.toLowerCase()]=e,t[e.operator.toLowerCase()]=e,e.aliases&&e.aliases.forEach(function(r){t[r.toLowerCase()]=e})}),t}(),e.from=function(t){return e.contains(t)?t:e._map[t.toLowerCase()]},e}(),Bt=(function(){var e=new yt("BooleanQueryOp");return e.And=e.addSymbol({operator:"and"}),e.Or=e.addSymbol({operator:"or"}),e.Not=e.addSymbol({operator:"not"}),e.resolveSymbols(),e._map=function(){var t={};return e.getSymbols().forEach(function(e){t[e.name.toLowerCase()]=e,t[e.operator.toLowerCase()]=e,e.aliases&&e.aliases.forEach(function(r){t[r.toLowerCase()]=e})}),t}(),e.from=function(t){return e.contains(t)?t:e._map[t.toLowerCase()]},e}(),function(){var e=function(e,t){if(e.length>1){if(e[0]instanceof Bt)return void(this.items=Array.prototype.concat.apply(e[0].items,e.slice(1).map(s("items"))));var n=e.map(function(e){return new r(e,t)})}else var n=[new r(e[0],t)];this.items=n},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,r){for(var n=0;n<t.length;n++){var a=t[n](e,r);if(0!==a)return a}return 0}},t.toJSONExt=function(e){return this.items.map(function(t){return e.propertyPathFn(t.propertyPath)+(t.isDesc?" desc":"")})};var r=function(e,t){if("string"!=typeof e)throw new Error("propertyPath is not a string");e=e.trim();var r=e.split(" ");if(r.length>1&&t!==!0&&t!==!1&&(t=L(r[1].toLowerCase(),"desc"),!t)){var n=L(r[1].toLowerCase(),"asc");if(!n)throw new Error("the second word in the propertyPath must begin with 'desc' or 'asc'")}this.propertyPath=r[0],this.isDesc=t},n=r.prototype;return n.validate=function(e){null==e||e.isAnonymous||(this.lastProperty=e.getProperty(this.propertyPath,!0))},n.getComparer=function(e){if(this.lastProperty||this.validate(e),this.lastProperty)var t=this.lastProperty.dataType,r=this.lastProperty.parentType.metadataStore.localQueryComparisonOptions.isCaseSensitive;var n=this.propertyPath,a=this.isDesc;return function(e,i){var o=rt(e,n),s=rt(i,n),u=t||o&&_t.fromValue(o)||_t.fromValue(s);if(u===_t.String)r?(o=o||"",s=s||""):(o=(o||"").toLowerCase(),s=(s||"").toLowerCase());else{var p=_t.getComparableFn(u);o=p(o),s=p(s)}return o===s?0:o>s||void 0===s?a?-1:1:a?1:-1}},e}()),Lt=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 r={};return e.propertyPaths.forEach(function(n,a){r[e._pathNames[a]]=rt(t,n)}),r}},t.toJSONExt=function(e){return this.propertyPaths.map(function(t){return e.propertyPathFn(t)})},e}(),Ut=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}();nt.FilterQueryOp=zt,nt.EntityQuery=qt,nt.OrderByClause=Bt;var $t=function(){var e=new yt("MergeStrategy");return e.PreserveChanges=e.addSymbol(),e.OverwriteChanges=e.addSymbol(),e.SkipMerge=e.addSymbol(),e.Disallowed=e.addSymbol(),e.resolveSymbols(),e}(),Gt=function(){var e=new yt("FetchStrategy");return e.FromServer=e.addSymbol(),e.FromLocalCache=e.addSymbol(),e.resolveSymbols(),e}(),Jt=function(){function e(e,t){return t&<(t).whereParam("fetchStrategy").isEnumOf(Gt).isOptional().whereParam("mergeStrategy").isEnumOf($t).isOptional().whereParam("includeDeleted").isBoolean().isOptional().applyAll(e),e}var t=function(t){e(this,t)},r=t.prototype;return r._$typeName="QueryOptions",t.resolve=function(e){return new Jt(h(e,["fetchStrategy","mergeStrategy","includeDeleted"]))},t.defaultInstance=new t({fetchStrategy:Gt.FromServer,mergeStrategy:$t.PreserveChanges,includeDeleted:!1}),r.using=function(t){if(!t)return this;var r=new Jt(this);return $t.contains(t)?t={mergeStrategy:t}:Gt.contains(t)&&(t={fetchStrategy:t}),e(r,t)},r.setAsDefault=function(){return l(this,t)},r.toJSON=function(){return y(this,{fetchStrategy:null,mergeStrategy:null,includeDeleted:!1})},t.fromJSON=function(e){return new Jt({fetchStrategy:Gt.fromName(e.fetchStrategy),mergeStrategy:$t.fromName(e.mergeStrategy),includeDeleted:e.includeDeleted===!0})},t}();nt.QueryOptions=Jt,nt.FetchStrategy=Gt,nt.MergeStrategy=$t;var Qt=function(){function e(e){if(e){if(1===e.length){var t=e[0];return function(e){return e?e.entityAspect.entityState===t:!1}}return function(t){return t?e.some(function(e){return t.entityAspect.entityState===e}):!1}}return function(e){return!!e}}var t=e([bt.Added,bt.Modified,bt.Deleted]),r=function(e,t){this.entityManager=e,this.entityType=t,this.entityType.isFrozen=!0,this._indexMap={},this._entities=[],this._emptyIndexes=[]},n=r.prototype;return n.attachEntity=function(e,t,r){var n=e.entityAspect;n._initialized||this.entityType._initializeInstance(e),delete n._initialized;var a=n.getKey()._keyInGroup,i=this._indexMap[a];if(i>=0){var o=this._entities[i],s=o.entityAspect.entityState,u=s.isUnchanged();if(o===e)n.entityState=t;else{if(r===$t.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: "+n.getKey());if(r===$t.OverwriteChanges||r===$t.PreserveChanges&&u){var p=this.entityManager.helper.unwrapInstance(e);this.entityType._updateTargetFromRaw(o,p,Dt.getRawValueFromServer),o.entityAspect.setEntityState(t)}}return o}return 0===this._emptyIndexes.length?i=this._entities.push(e)-1:(i=this._emptyIndexes.pop(),this._entities[i]=e),this._indexMap[a]=i,n.entityState=t,n.entityGroup=this,n.entityManager=this.entityManager,e},n.detachEntity=function(e){var t=e.entityAspect,r=t.getKey()._keyInGroup,n=this._indexMap[r];if(void 0===n)throw new Error("internal error - entity cannot be found in group");return delete this._indexMap[r],this._emptyIndexes.push(n),this._entities[n]=null,e},n.findEntityByKey=function(e){var t;t=e instanceof Pt?e._keyInGroup:Pt.createKeyString(e);var r=this._indexMap[t];return void 0!==r?this._entities[r]:null},n.hasChanges=function(){return this._entities.some(t)},n.getEntities=function(t){var r=e(t);return this._entities.filter(r)},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,r){var n=e.name;this._entities.forEach(function(e){null!=e&&e.getProperty(n)==t&&e.setProperty(n,r)})},n._fixupKey=function(e,t){var r=this._indexMap[e];if(void 0===r)throw new Error("Internal Error in key fixup - unable to locate entity");var n=this._entities[r],a=n.entityType.keyProperties[0].name;n.setProperty(a,t),delete n.entityAspect.hasTempKey,delete this._indexMap[e],this._indexMap[t]=r},n._replaceKey=function(e,t){var r=this._indexMap[e._keyInGroup];delete this._indexMap[e._keyInGroup],this._indexMap[t._keyInGroup]=r},r}(),Ht=function(){function e(e,t,r){var n=r?Jt.defaultInstance:e.queryOptions,a=r?Wt.defaultInstance:e.saveOptions,i=r?wt.defaultInstance:e.validationOptions,o=lt(t).whereParam("serviceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(Nt).whereParam("queryOptions").isInstanceOf(Jt).isOptional().withDefault(n).whereParam("saveOptions").isInstanceOf(Wt).isOptional().withDefault(a).whereParam("validationOptions").isInstanceOf(wt).isOptional().withDefault(i).whereParam("keyGeneratorCtor").isFunction().isOptional();r&&(o=o.whereParam("metadataStore").isInstanceOf(Ct).isOptional().withDefault(new Ct)),o.applyAll(e),c(e.queryOptions,n),c(e.saveOptions,a),c(e.validationOptions,i),t.serviceName&&(e.dataService=new Nt({serviceName:e.serviceName})),e.serviceName=e.dataService&&e.dataService.serviceName,e.keyGeneratorCtor=e.keyGeneratorCtor||Vt,(r||t.keyGeneratorCtor)&&(e.keyGenerator=new e.keyGeneratorCtor)}function n(e){e.forEach(function(e){var r=[],n=e.entityAspect;t(n._validationErrors,function(e,t){t.isServerError&&r.push(e)}),0!==r.length&&n._processValidationOpAndPublish(function(){r.forEach(function(e){n._removeValidationError(e)})})})}function a(e){var r=[];return e.forEach(function(e){t(e.entityAspect._validationErrors,function(t,n){var a=p({entity:e,errorName:n.validator.name},n,["errorMessage","propertyName","isServerError"]);r.push(a)})}),r}function i(e,t){var r=t.entityErrors;if(r){var n=e.entityManager,a=n.metadataStore;t.entityErrors=r.map(function(e){var t=null;if(e.keyValues){var r=a._getEntityType(e.entityTypeName),i=new Pt(r,e.keyValues);t=n.findEntityByKey(i)}if(t){var o=e.propertyName?{propertyName:e.propertyName,property:r.getProperty(e.propertyName)}:{},s=gt.getKey(e.errorName||e.errorMessage,e.propertyName),u=new gt(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 o(e,t){var r,n=y(e,t),a=n.entityKey,i=0===n.remainingArgs.length?!1:!!n.remainingArgs[0],o=!1;return i&&(r=e.getEntityByKey(a),o=!!r,o&&!e.queryOptions.includeDeleted&&r.entityAspect.entityState.isDeleted()&&(r=null,o=e.queryOptions.mergeStrategy!==$t.OverwriteChanges)),o?At.resolve({entity:r,entityKey:a,fromCache:!0}):qt.fromEntityKey(a).using(e).execute().then(function(e){return r=0===e.results.length?null:e.results[0],At.resolve({entity:r,entityKey:a,fromCache:!1})})}function s(e,t){return pt(t,"entityTypes").isString().isOptional().or().isNonEmptyArray().isString().or().isInstanceOf(Ft).or().isNonEmptyArray().isInstanceOf(Ft).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 l(e,t,r){var n,a=D(e,t);return a.forEach(function(e){if(e){var t=e.getEntities(r);n?n.push.apply(n,t):n=t}}),n||[]}function y(e,t){try{if(t[0]instanceof Pt)return{entityKey:t[0],remainingArgs:it(t,1)};if(t.length>=2){var r="string"==typeof t[0]?e.metadataStore._getEntityType(t[0],!1):t[0];return{entityKey:new Pt(r,t[1]),remainingArgs:it(t,2)}}}catch(n){}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 h(e,t){e.forEach(function(e){e.entityAspect.isBeingSaved=t})}function g(e,r){var n;r?(n={},r.forEach(function(e){var t=n[e.entityType.name];t||(t={},t.entityType=e.entityType,t._entities=[],n[e.entityType.name]=t),t._entities.push(e)})):n=e._entityGroupMap;var a=[],i={};return t(n,function(e,t){i[e]=w(t,a)}),{entityGroupMap:i,tempKeys:a}}function w(e,t){var r={},n=e.entityType,a=n.dataProperties,i=Z(n),o=[];return e._entities.forEach(function(e){if(e){var r=T(e,a,i,t);o.push(r)}}),r.entities=o,r}function T(e,t,r,n){var a={};t.forEach(function(t){var n=t.name,i=e.getProperty(n);if(null!=i||null!=t.defaultValue){if(i&&t.isComplexProperty){var o=t.dataType.dataProperties;i=m(i,function(e){return T(e,o,r)})}else i=r?r(t,i):i,t.isUnmapped&&(i=f(i));void 0!==i&&(a[n]=i)}});var i,o;if(e.entityAspect){i=e.entityAspect;var s=i.entityState;o={tempNavPropNames:b(i,n),entityState:s.name},i.extraMetadata&&(o.extraMetadata=i.extraMetadata),(s.isModified()||s.isDeleted())&&(o.originalValuesMap=i.originalValues),a.entityAspect=o}else i=e.complexAspect,o={},i.originalValues&&!z(i.originalValues)&&(o.originalValuesMap=i.originalValues),a.complexAspect=o;return a}function b(e,t){var r=e.entity;e.hasTempKey&&t.push(e.getKey().toJSON());var n;return r.entityType.navigationProperties.forEach(function(e){if(e.relatedDataProperties){var t=r.getProperty(e.name);t&&t.entityAspect.hasTempKey&&(n=n||[],n.push(e.name))}}),n}function _(e,t,r){var n=r.tempKeyMap,a=e.entityType,i=r.mergeStrategy,o=null,s=e.entityManager,u=s.entityChanged,p=[],c=Dt.getRawValueFromClient;return t.entities.forEach(function(t){var r=t.entityAspect,l=a.getEntityKeyFromRawEntity(t,c),y=bt.fromName(r.entityState),f=y.isAdded()&&A(n,l);if(o=f?null:e.findEntityByKey(l))if(i===$t.SkipMerge);else{if(i===$t.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+l.toString()+" from being merged");var h=o.entityAspect.entityState,d=h.isUnchanged();(i===$t.OverwriteChanges||d)&&(a._updateTargetFromRaw(o,t,c),o.entityAspect.setEntityState(y),u.publish({entityAction:Et.MergeOnImport,entity:o}))}else o=a._createInstanceCore(),a._updateTargetFromRaw(o,t,c),f&&(o.entityAspect.hasTempKey=!0,o.setProperty(a.keyProperties[0].name,f.values[0]),r.tempNavPropNames&&r.tempNavPropNames.forEach(function(e){var t=a.getNavigationProperty(e),r=t.relatedDataProperties[0].name,i=o.getProperty(r),s=new Pt(t.entityType,[i]),u=A(n,s);o.setProperty(r,u.values[0])})),o=e.attachEntity(o,y),u.publish({entityAction:Et.AttachOnImport,entity:o}),y.isUnchanged()||s._notifyStateChange(o,!0);p.push(o)}),p}function A(e,t){var r=e[t.toString()];if(r)return r;var n=t._subtypes;if(!n)return null;for(var a=0,i=n.length;i>a;a++)if(r=e[t.toString(n[a])])return r;return null}function x(e,t,r){return e=e.then(function(e){return t&&t(e),At.resolve(e)
},function(e){return r&&r(e),At.reject(e)})}function F(e,t){var r;return r=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 M(e,t){e._inKeyFixup=!0,t.forEach(function(t){var r=e._entityGroupMap[t.entityTypeName];if(!r)throw new Error("Unable to locate the following fully qualified EntityType name: "+t.entityTypeName);r._fixupKey(t.tempValue,t.realValue)}),e._inKeyFixup=!1}function D(e,t){var r=e._entityGroupMap;return t?d(t).map(function(e){if(e instanceof Ft)return r[e.name];throw new Error("The EntityManager.getChanges() 'entityTypes' parameter must be either an entityType or an array of entityTypes or null")}):u(r)}function k(e,t){var r=t.entityAspect.getKey(),n=S(t.entityType.keyProperties,r.values,function(e,t){return e.defaultValue===t?e:null}).filter(function(e){return null!==e});if(n.length)if(t.entityType.autoGeneratedKeyType!==It.None)e.generateTempKeyValue(t);else if(n.length===r.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 I(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 V(e,t,r,n){var a=t.entityType.navigationProperties;a.forEach(function(a){var i=t.getProperty(a.name);if(a.isScalar){if(!i)return;e.attachEntity(i,r,n)}else i.forEach(function(t){e.attachEntity(t,r,n)})})}function j(e,t,n,a){try{var i,o=e.metadataStore;if(o.isEmpty()&&a.hasServerMetadata)throw new Error("cannot execute _executeQueryCore until metadataStore is populated.");if(n.fetchStrategy===Gt.FromLocalCache)try{return i=e.executeQueryLocally(t),At.resolve({results:i,query:t})}catch(s){return At.reject(s)}var u=new Zt({query:t,entityManager:e,dataService:a,mergeOptions:{mergeStrategy:n.mergeStrategy,noTracking:!!t.noTrackingEnabled,includeDeleted:n.includeDeleted}}),p=e.validationOptions.validateOnQuery;return a.adapterInstance.executeQuery(u).then(function(n){var o=O(function(){var t={isLoading:e.isLoading};return e.isLoading=!0,e._pendingPubs=[],t},function(r){e.isLoading=r.isLoading,e._pendingPubs.forEach(function(e){e()}),e._pendingPubs=null,e._hasChangesAction&&e._hasChangesAction(),t=null,u=null,r.error&&At.reject(r.error)},function(){var o=a.jsonResultsAdapter.extractResults(n);o=d(o),i=u.visitAndMerge(o,{nodeType:"root"}),p&&i.forEach(function(e){e.entityAspect&&e.entityAspect.validateEntity()}),u.processDeferred(),R(i,t);var s=r(u.refMap);return{results:i,query:t,entityManager:e,httpResponse:n.httpResponse,inlineCount:n.inlineCount,retrievedEntities:s}});return At.resolve(o)},function(r){return r&&(r.query=t,r.entityManager=e),At.reject(r)})}catch(s){return s&&(s.query=t),At.reject(s)}}function R(e,t){if(!t.noTrackingEnabled){var r=t.expandClause;null!=r&&r.propertyPaths.forEach(function(t){var r=t.split(".");K(e,r)})}}function K(e,t){var r=t[0];e.forEach(function(e){var n=e.entityAspect;if(n&&(n._markAsLoaded(r),1!==t.length)){var a=e.getProperty(r);a&&(a.arrayChanged||(a=[a]),K(a,t.slice(1)))}})}function q(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){B(e,t)})})}function B(e,t){if(!e.entityAspect.originalValues[t.name]){var r=e.getProperty(t.name);if(r||(r=t.dataType.defaultValue),t.dataType.isNumeric)e.setProperty(t.name,r+1);else if(t.dataType.isDate){for(var n=new Date,a=new Date;n.getTime()===a.getTime();)a=new Date;e.setProperty(t.name,a)}else{if(t.dataType!==_t.Guid){if(t.dataType===_t.Binary)return;throw new Error("Unable to update the value of concurrency property before saving: "+t.name)}e.setProperty(t.name,C())}}}function L(e,t){var r=e._entityGroupMap[t.name];return r||(r=new Qt(e,t),e._entityGroupMap[t.name]=r),r}function U(e,t){var r=t.getSelfAndSubtypes();return r.map(function(t){return L(e,t)})}function $(e,t){var r={},n=e.entityType||e.complexType,a=Z(n),i={};return n.dataProperties.forEach(function(n){if(n.isComplexProperty)r[n.nameOnServer]=m(e.getProperty(n.name),function(e){return $(e,t)});else{var o=e.getProperty(n.name);if(o=t?t(n,o):o,void 0===o)return;o=a?a(n,o):o,void 0!==o&&(n.isUnmapped?i[n.nameOnServer]=f(o):r[n.nameOnServer]=o)}}),z(i)||(r.__unmapped=i),r}function G(e,r,n){var a=e.entityType||e.complexType,i=e.entityAspect||e.complexAspect,o=r.namingConvention.clientPropertyNameToServer,s={};return t(i.originalValues,function(e,t){var r=a.getProperty(e);t=n?n(r,t):t,void 0!==t&&(s[o(e,r)]=t)}),a.complexProperties.forEach(function(t){var a=e.getProperty(t.name);if(t.isScalar){var i=G(a,r,n);z(i)||(s[o(t.name,t)]=i)}else{var u=a.map(function(e){return G(e,r,n)});s[o(t.name,t)]=u}}),s}function J(e,r,n){var a=e.entityType,i=Z(a),o=r.namingConvention.clientPropertyNameToServer,s={};return t(e.entityAspect.originalValues,function(t){var r=a.getProperty(t),u=e.getProperty(t);u=n?n(r,u):u,void 0!==u&&(u=i?i(r,u):u,void 0!==u&&(s[o(t,r)]=u))}),a.complexProperties.forEach(function(t){if(Q(e,t)){var r=e.getProperty(t.name);s[o(t.name,t)]=m(r,function(e){return $(e,n)})}}),s}function Q(e,t){var r=e.getProperty(t.name);return t.isScalar?H(r):r._origValues?!0:r.some(function(e){return H(e)})}function H(e){return z(e.complexAspect.originalValues)?e.complexType.complexProperties.some(function(t){return Q(e,t)}):!0}function Z(e){return e.serializerFn||e.metadataStore&&e.metadataStore.serializerFn}function W(){this.map={}}var Y=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 ft("entityChanged",this),this.validationErrorsChanged=new ft("validationErrorsChanged",this),this.hasChangesChanged=new ft("hasChangesChanged",this),this.clear()},X=Y.prototype;return X._$typeName="EntityManager",ft.bubbleEvent(X,null),X.setProperties=function(t){e(this,t,!1)},X.createEntity=function(e,t,r,n){pt(e,"entityType").isString().or().isInstanceOf(Ft).check(),pt(r,"entityState").isEnumOf(bt).isOptional().check(),pt(n,"mergeStrategy").isEnumOf($t).isOptional().check(),"string"==typeof e&&(e=this.metadataStore._getEntityType(e)),r=r||bt.Added;var a;return N(this,"isLoading",!0,function(){a=e.createEntity(t)}),r!==bt.Detached&&(a=this.attachEntity(a,r,n)),a},Y.importEntities=function(e,t){var r=new Ht;return r.importEntities(e,t),r},X.acceptChanges=function(){this.getChanges().map(function(e){return e.entityAspect._checkOperation("acceptChanges")}).forEach(function(e){e.acceptChanges()})},X.exportEntities=function(e,t){pt(t,"includeMetadata").isBoolean().isOptional().check(),t=null==t?!0:t;var r=g(this,e),n=p({},r,["tempKeys","entityGroupMap"]);t?(n=p(n,this,["dataService","saveOptions","queryOptions","validationOptions"]),n.metadataStore=this.metadataStore.exportMetadata()):(n.metadataVersion=nt.metadataVersion,n.metadataStoreName=this.metadataStore.name);var a=JSON.stringify(n,null,ht.stringifyPad);return a},X.importEntities=function(e,r){r=r||{},lt(r).whereParam("mergeStrategy").isEnumOf($t).isOptional().withDefault(this.queryOptions.mergeStrategy).whereParam("metadataVersionFn").isFunction().isOptional().applyAll(r);var n=this,a="string"==typeof e?JSON.parse(e):e;a.metadataStore?(this.metadataStore.importMetadata(a.metadataStore),this.dataService=a.dataService&&Nt.fromJSON(a.dataService)||new Nt({serviceName:a.serviceName}),this.saveOptions=new Wt(a.saveOptions),this.queryOptions=Jt.fromJSON(a.queryOptions),this.validationOptions=new wt(a.validationOptions)):r.metadataVersionFn&&r.metadataVersionFn({metadataVersion:a.metadataVersion,metadataStoreName:a.metadataStoreName});var i={};a.tempKeys.forEach(function(e){var t=Pt.fromJSON(e,n.metadataStore);i[t.toString()]=new Pt(t.entityType,n.keyGenerator.generateTempKeyValue(t.entityType,t.values[0]))});var o=[];return r.tempKeyMap=i,O(function(){n._pendingPubs=[]},function(){n._pendingPubs.forEach(function(e){e()}),n._pendingPubs=null,n._hasChangesAction&&n._hasChangesAction()},function(){t(a.entityGroupMap,function(e,t){var a=n.metadataStore._getEntityType(e,!0),i=L(n,a),s=_(i,t,r);Array.prototype.push.apply(o,s)}),o.forEach(function(e){n._linkRelatedEntities(e)})}),{entities:o,tempKeyMapping:i}},X.clear=function(){r(this._entityGroupMap,function(e,t){return t._checkOperation()}).forEach(function(e){e._clear()}),this._entityGroupMap={},this._unattachedChildrenMap=new W,this.keyGenerator=new this.keyGeneratorCtor,this.entityChanged.publish({entityAction:Et.Clear}),this._setHasChanges(!1)},X.createEmptyCopy=function(){var e=new Y(p({},this,["dataService","metadataStore","queryOptions","saveOptions","validationOptions","keyGeneratorCtor"]));return e},X.addEntity=function(e){return this.attachEntity(e,bt.Added)},X.attachEntity=function(e,t,r){if(pt(e,"entity").isRequired().check(),this.metadataStore._checkEntityType(e),t=pt(t,"entityState").isEnumOf(bt).isOptional().check(bt.Unchanged),r=pt(r,"mergeStrategy").isEnumOf($t).isOptional().check($t.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 n=e.entityAspect;if(n){if(n._inProcessEntity)return n._inProcessEntity}else n=new St(e);var a=n.entityManager;if(a){if(a===this)return e;throw new Error("This entity already belongs to another EntityManager")}var i,o=this;return N(this,"isLoading",!0,function(){t.isAdded()&&k(o,e),i=o._attachEntityCore(e,t,r),n._inProcessEntity=i;try{V(o,e,t,r)}finally{n._inProcessEntity=null}}),this.validationOptions.validateOnAttach&&i.entityAspect.validateEntity(),t.isUnchanged()||this._notifyStateChange(i,!0),this.entityChanged.publish({entityAction:Et.Attach,entity:i}),i},X.detachEntity=function(e){pt(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()},X.fetchMetadata=function(e,t,r){"function"==typeof e?(r=t,t=e,e=null):(pt(e,"dataService").isInstanceOf(Nt).isOptional().check(),pt(t,"callback").isFunction().isOptional().check(),pt(r,"errorCallback").isFunction().isOptional().check());var n=this.metadataStore.fetchMetadata(e||this.dataService);return x(n,t,r)},X.executeQuery=function(e,t,r){pt(e,"query").isInstanceOf(qt).or().isString().check(),pt(t,"callback").isFunction().isOptional().check(),pt(r,"errorCallback").isFunction().isOptional().check();var n,a=Jt.resolve([e.queryOptions,this.queryOptions,Jt.defaultInstance]),i=Nt.resolve([e.dataService,this.dataService]);if(!i.hasServerMetadata||this.metadataStore.hasMetadataFor(i.serviceName))n=j(this,e,a,i);else{var o=this;n=this.fetchMetadata(i).then(function(){return j(o,e,a,i)})}return x(n,t,r)},X.executeQueryLocally=function(e){pt(e,"query").isInstanceOf(qt).check();var t=this.metadataStore,r=e._getFromEntityType(t,!0),n=U(this,r),a=e.wherePredicate&&e.wherePredicate.toFunction({entityType:r}),i=Jt.resolve([e.queryOptions,this.queryOptions,Jt.defaultInstance]),o=i.includeDeleted===!0,s=function(e){return e&&(o||!e.entityAspect.entityState.isDeleted())&&(a?a(e):!0)},u=[];n.forEach(function(e){u.push.apply(u,e._entities.filter(s))});var p=e.orderByClause&&e.orderByClause.getComparer(r);p&&u.sort(p);var c=e.skipCount;c&&(u=u.slice(c));var l=e.takeCount;l&&(u=u.slice(0,l));var y=e.selectClause;if(y){var f=y.toFunction();u=u.map(f)}return u},X.saveChanges=function(e,t,r,o){function s(e){var t=g.entityManager;h(c,!1);e.entities=g.processSavedEntities(e);return t._setHasChanges(null),r&&r(e),At.resolve(e)}function u(e){var t=e.entities;if(0===t.length)return[];var r=e.keyMappings,n=g.entityManager;return M(n,r),N(n,"isLoading",!0,function(){var e=new Zt({query:null,entityManager:n,mergeOptions:{mergeStrategy:$t.OverwriteChanges},dataService:v});t=e.visitAndMerge(t,{nodeType:"root"})}),t}function p(e){return h(c,!1),i(g,e),o&&o(e),At.reject(e)}pt(e,"entities").isOptional().isArray().isEntity().check(),pt(t,"saveOptions").isInstanceOf(Wt).isOptional().check(),pt(r,"callback").isFunction().isOptional().check(),pt(o,"errorCallback").isFunction().isOptional().check(),t=t||this.saveOptions||Wt.defaultInstance;var c=F(this,e);if(0===c.length){var l={entities:[],keyMappings:[]};return r&&r(l),At.resolve(l)}if(!t.allowConcurrentSaves){var y=c.some(function(e){return e.entityAspect.isBeingSaved});if(y){var f=new Error("Concurrent saves not allowed - SaveOptions.allowConcurrentSaves is false");return o&&o(f),At.reject(f)}}if(n(c),this.validationOptions.validateOnSave){var d=c.filter(function(e){var t=e.entityAspect,r=t.entityState.isDeleted()||t.validateEntity();return!r});if(d.length>0){var m=new Error("Client side validation errors encountered - see the entityErrors collection on this object for more detail");return m.entityErrors=a(d),o&&o(m),At.reject(m)}}var v=Nt.resolve([t.dataService,this.dataService]),g={entityManager:this,dataService:v,processSavedEntities:u,resourceName:t.resourceName||this.saveOptions.resourceName||"SaveChanges"},w={entities:c,saveOptions:t};try{return q(c),v.adapterInstance.saveChanges(g,w).then(s).then(null,p)}catch(f){return h(c,!1),o&&o(f),At.reject(f)}},X._findEntityGroup=function(e){return this._entityGroupMap[e.name]},X.getEntityByKey=function(){var e=y(this,arguments).entityKey,t=e._subtypes||[e.entityType],r=null;return t.some(function(t){var n=this._findEntityGroup(t);return r=n&&n.findEntityByKey(e)},this),r},X.fetchEntityByKey=function(){var e=Nt.resolve([this.dataService]);if(!e.hasServerMetadata||this.metadataStore.hasMetadataFor(e.serviceName))return o(this,arguments);var t=this,r=arguments;return this.fetchMetadata(e).then(function(){return o(t,r)})},X.findEntityByKey=function(e){return this.getEntityByKey(e)},X.generateTempKeyValue=function(e){pt(e,"entity").isEntity().check();var t=e.entityType,r=this.keyGenerator.generateTempKeyValue(t),n=t.keyProperties[0];return e.setProperty(n.name,r),e.entityAspect.hasTempKey=!0,r},X.hasChanges=function(e){return this._hasChanges?void 0===e?this._hasChanges:this._hasChangesCore(e):!1},X._hasChangesCore=function(e){e=s(this,e);var t=D(this,e);return t.some(function(e){return e.hasChanges()})},X.getChanges=function(e){e=s(this,e);var t=[bt.Added,bt.Modified,bt.Deleted];return l(this,e,t)},X.rejectChanges=function(){if(!this._hasChanges)return[];var e=[bt.Added,bt.Modified,bt.Deleted],t=l(this,null,e),r=t.map(function(e){return e.entityAspect._checkOperation("rejectChanges")});return this._hasChanges=!1,r.forEach(function(e){e.rejectChanges()}),this.hasChangesChanged.publish({entityManager:this,hasChanges:!1}),t},X.getEntities=function(e,t){return e=s(this,e),pt(t,"entityStates").isOptional().isEnumOf(bt).or().isNonEmptyArray().isEnumOf(bt).check(),t=t&&I(this,t),l(this,e,t)},X._notifyStateChange=function(e,t){var r={entityAction:Et.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(r)}.bind(this));this._setHasChanges(null)}this.entityChanged.publish(r)},X._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},X._linkRelatedEntities=function(e){var t=this,r=e.entityAspect;N(t,"isLoading",!0,function(){var n=t._unattachedChildrenMap,a=r.getKey(),i=n.getTuples(a);i&&i.slice(0).forEach(function(t){var r,i,o=t.children.filter(function(e){return e.entityAspect.entityState!==bt.Detached}),s=t.navigationProperty;if(s.inverse)if(r=s,i=s.inverse,i.isScalar){var u=o[0];e.setProperty(i.name,u),u.setProperty(r.name,e)}else{var p=e.getProperty(i.name);o.forEach(function(t){p.push(t),t.setProperty(r.name,e)})}else if(s.parentType===e.entityType)if(i=s,i.isScalar)e.setProperty(i.name,o[0]);else{var p=e.getProperty(i.name);o.forEach(function(e){p._push(e)})}else r=s,o.forEach(function(t){t.setProperty(r.name,e)});n.removeChildren(a,r)}),e.entityType.navigationProperties.forEach(function(a){if(a.isScalar){var i=e.getProperty(a.name);if(i)return}var o=r.getParentKey(a);if(o){if(o._isEmpty())return;var s=t.findEntityByKey(o);s?e.setProperty(a.name,s):n.addChild(o,a,e)}}),e.entityType.foreignKeyProperties.forEach(function(r){var a=r.inverseNavigationProperty;if(a){var i=e.getProperty(r.name),o=new Pt(a.parentType,[i]),s=t.findEntityByKey(o);s?a.isScalar?s.setProperty(a.name,e):t.isLoading?s.getProperty(a.name)._push(e):s.getProperty(a.name).push(e):n.addChild(o,a,e)}})})},X._attachEntityCore=function(e,t,r){var n=L(this,e.entityType),a=n.attachEntity(e,t,r);return this._linkRelatedEntities(a),a},X._updateFkVal=function(e,t,r){var n=this._entityGroupMap[e.parentType.name];n&&n._updateFkVal(e,t,r)},X.helper={unwrapInstance:$,unwrapOriginalValues:G,unwrapChangedValues:J},W.prototype.addChild=function(e,t,r){var n=this.getTuple(e,t);n||(n={navigationProperty:t,children:[]},P(this.map,e.toString()).push(n)),n.children.push(r)},W.prototype.removeChildren=function(e,t){var r=this.getTuples(e);r&&(E(r,function(e){return e.navigationProperty===t}),r.length||delete this.map[e.toString()])},W.prototype.getChildren=function(e,t){var r=this.getTuple(e,t);return r?r.children.filter(function(e){return!e.entityAspect.entityState.isDetached()}):null},W.prototype.getTuple=function(e,t){var r=this.getTuples(e);if(!r)return null;var n=v(r,function(e){return e.navigationProperty===t});return n},W.prototype.getTuples=function(e){for(var t=this.map[e.toString()],r=e.entityType;!t&&r.baseEntityType;){r=r.baseEntityType;var n=e.toString(r);t=this.map[n]}return t},Y}();nt.EntityManager=Ht;var Zt=function(){function e(e,t,a,o){if(a.ignore||null==t)return null;if(a.nodeRefId){var u=i(e,a.nodeRefId);return"function"==typeof u&&null!=o?void e.deferredFns.push(function(){o(u)}):u}if(a.entityType){var p=a.entityType;return e.mergeOptions.noTracking?(t=r(e,p,t),p.noTrackingFn&&(t=p.noTrackingFn(t,p)),a.nodeId&&(e.refMap[a.nodeId]=t),t):p.isComplexType?r(e,p,t):s(e,t,a)}return"object"!=typeof t||k(t)||(t=n(e,t)),a.nodeId&&(e.refMap[a.nodeId]=t),t}function r(e,t,n){var i={};return t.dataProperties.forEach(function(t){i[t.name]=t.isComplexProperty?m(n[t.nameOnServer],function(n){return r(e,t.dataType,n)}):E(n[t.nameOnServer],t.dataType)}),t.navigationProperties&&t.navigationProperties.forEach(function(t){var r={nodeType:"navProp",navigationProperty:t};a(n[t.nameOnServer],e,r,i,t.name)}),i}function n(e,r){var n=e.metadataStore.namingConvention.serverPropertyNameToClient,i={};return t(r,function(t,r){var o=n(t),s={nodeType:"anonProp",propertyName:o};a(r,e,s,i,o)}),i}function a(t,r,n,a,i){var o=r.jsonResultsAdapter,s=o.visitNode(t,r,n)||{};t=s.node||t,s.ignore||(Array.isArray(t)?(n.nodeType=n.nodeType+"Item",a[i]=t.map(function(t,u){return s=o.visitNode(t,r,n)||{},t=s.node||t,e(r,t,s,function(e){a[i][u]=e()})})):a[i]=e(r,t,s,function(e){a[i]=e()}))}function i(e,t){var r=e.refMap[t];return void 0===r?function(){return e.refMap[t]}:r}function o(e,t,r){var n=r._$meta.nodeId;null!=n&&(e.refMap[n]=t)}function s(e,t,r){t._$meta=r;var n=e.entityManager,a=r.entityType;"string"==typeof a&&(a=e.metadataStore._getEntityType(a,!1)),t.entityType=a;var i=e.mergeOptions.mergeStrategy,o=null==e.query,s=a.getEntityKeyFromRawEntity(t,e.rawValueFn),p=n.findEntityByKey(s);if(p){if(o&&p.entityAspect.entityState.isDeleted())return n.detachEntity(p),p;var l=p.entityAspect.entityState;if(i===$t.Disallowed)throw new Error("A MergeStrategy of 'Disallowed' prevents "+s.toString()+" from being merged");if(i===$t.SkipMerge)u(e,p,t);else if(i===$t.OverwriteChanges||l.isUnchanged()){c(e,p,t),p.entityAspect.wasLoaded=!0,r.extraMetadata&&(p.entityAspect.extraMetadata=r.extraMetadata),p.entityAspect.entityState=bt.Unchanged,p.entityAspect.originalValues={},p.entityAspect.propertyChanged.publish({entity:p,propertyName:null});var y=o?Et.MergeOnSave:Et.MergeOnQuery;n.entityChanged.publish({entityAction:y,entity:p}),l.isUnchanged()||n._notifyStateChange(p,!1)}else{if(l==bt.Deleted&&!e.mergeOptions.includeDeleted)return null;u(e,p,t)}}else p=a._createInstanceCore(),c(e,p,t),r.extraMetadata&&(p.entityAspect.extraMetadata=r.extraMetadata),n._attachEntityCore(p,bt.Unchanged,i),p.entityAspect.wasLoaded=!0,n.entityChanged.publish({entityAction:Et.AttachOnQuery,entity:p});return p}function u(e,t,r){o(e,t,r),r.entityType.navigationProperties.forEach(function(t){t.isScalar?f(e,r,t):h(e,r,t)})}function c(e,t,r){o(e,t,r);var n=t.entityType;n._updateTargetFromRaw(t,r,e.rawValueFn),n.navigationProperties.forEach(function(n){n.isScalar?l(e,n,t,r):y(e,n,t,r)})}function l(e,t,r,n){var a=f(e,n,t);null!=a&&("function"==typeof a?e.deferredFns.push(function(){a=a(),d(a,r,t)}):d(a,r,t))}function y(e,t,r,n){var a=h(e,n,t);if(null!=a){var i=t.inverse;if(i){var o=r.getProperty(t.name);o.wasLoaded=!0,a.forEach(function(t){"function"==typeof t?e.deferredFns.push(function(){t=t(),v(t,o,r,i)}):v(t,o,r,i)})}}}function f(e,t,r){var n=t[r.nameOnServer];if(!n)return null;var a=e.visitAndMerge(n,{nodeType:"navProp",navigationProperty:r});return a}function h(e,t,r){var n=t[r.nameOnServer];if(!n)return null;if(!Array.isArray(n)&&(n=n.results,!n))return null;var a=e.visitAndMerge(n,{nodeType:"navPropItem",navigationProperty:r});return a}function d(e,t,r){if(e){var n=r.name,a=t.getProperty(n);if(a!==e){t.setProperty(n,e);var i=r.inverse;if(!i)return;if(i.isScalar)e.setProperty(i.name,t);else{var o=e.getProperty(i.name);o.push(t)}}}}function v(e,t,r,n){if(e){var a=e.getProperty(n.name);a!==r&&(t.push(e),e.setProperty(n.name,r))}}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=Dt.getRawValueFromServer},w=g.prototype,E=_t.parseRawValue;return w._$typeName="MappingContext",w.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)},w.visitAndMerge=function(t,r){var n=this.query,a=this.jsonResultsAdapter;r=r||{};var i=this;return m(t,function(t){if(null==n&&t.entityAspect)return t.entityAspect.entityState.isDeleted()?i.entityManager.detachEntity(t):t.entityAspect.acceptChanges(),t;var o=a.visitNode(t,i,r)||{};return t=o.node||t,n&&"root"===r.nodeType&&!o.entityType&&(o.entityType=n._getToEntityType&&n._getToEntityType(i.metadataStore)),e(i,t,o)},this.mergeOptions.includeDeleted)},w.processDeferred=function(){this.deferredFns.length>0&&this.deferredFns.forEach(function(e){e()})},g}(),Wt=function(){function e(e,t){return t&<(t).whereParam("resourceName").isOptional().isString().whereParam("dataService").isOptional().isInstanceOf(Nt).whereParam("allowConcurrentSaves").isBoolean().isOptional().whereParam("tag").isOptional().applyAll(e),e}var t=function(t){e(this,t)},r=t.prototype;return r._$typeName="SaveOptions",r.setAsDefault=function(){return l(this,t)},r.using=function(t){return e(this,t)},t.defaultInstance=new t({allowConcurrentSaves:!1}),t}();nt.SaveOptions=Wt,nt.AbstractDataServiceAdapter=function(){function e(){this.getRequest=function(e){return e},this.done=function(){}}function t(e,t,n){var a=r(t);return i._catchNoConnectionError(a),n&&(a.message=n+"; "+a.message),e.reject(a)}function r(e){var t=new Error;t.httpResponse=e,t.status=e.status;var r=e.data;if(!r)return t.message=e.error&&e.error.toString(),t;if("string"==typeof r)try{r=JSON.parse(r)}catch(n){return t.message=r,t}var a,i,o=e.saveContext,s=r.Message||r.ExceptionMessage||r.EntityErrors||r.Errors,u=!!s;if(u){var s=r;do a=s.ExceptionMessage||s.Message,s=s.InnerException;while(s);i=r.Errors||r.EntityErrors,i=i&&i.map(function(e){return{errorName:e.ErrorName,entityTypeName:Ct.normalizeTypeName(e.EntityTypeName),keyValues:e.KeyValues,propertyName:e.PropertyName,errorMessage:e.ErrorMessage}})}else a=r.message,i=r.errors||r.entityErrors;if(o&&i){var p=o.entityManager.metadataStore.namingConvention.serverPropertyNameToClient;i.forEach(function(e){e.propertyName=e.propertyName&&p(e.propertyName)}),t.entityErrors=i}return t.message=a||"Server side errors encountered - see the entityErrors collection on this object for more detail",t}var n,a=function(){},i=a.prototype;return i.checkForRecomposition=function(e){"ajax"===e.interfaceName&&e.isDefault&&this.initialize()},i.initialize=function(){if(n=nt.config.getAdapterInstance("ajax"),!n||!n.ajax)throw new Error("Unable to find ajax adapter for dataservice adapter '"+(this.name||"")+"'.")},i.fetchMetadata=function(e,r){var a=r.serviceName,i=r.qualifyUrl("Metadata"),o=At.defer();return n.ajax({type:"GET",url:i,dataType:"json",success:function(n){if(e.hasMetadataFor(a))return o.resolve("already fetched");var s=n.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,n,"Metadata query failed for: "+i+". "+c)}return e.hasMetadataFor(a)||e.addDataService(r),o.resolve(u)},error:function(e){t(o,e,"Metadata query failed for: "+i)}}),o.promise},i.executeQuery=function(e){var r=At.defer(),a=e.getUrl(),i={type:"GET",url:a,params:e.query.parameters,dataType:"json",success:function(e){var n=e.data;try{var a,i=n&&(n.results||n.Results);a=i?{results:i,inlineCount:n.inlineCount||n.InlineCount,httpResponse:e}:{results:n,httpResponse:e},r.resolve(a)}catch(o){o instanceof Error?r.reject(o):t(r,e)}},error:function(e){t(r,e)}};return e.dataService.useJsonp&&(i.dataType="jsonp",i.crossDomain=!0),n.ajax(i),r.promise},i.saveChanges=function(e,r){var a=e.adapter=this,i=At.defer();r=a._prepareSaveBundle(e,r);var o=JSON.stringify(r),s=e.dataService.qualifyUrl(e.resourceName);return n.ajax({type:"POST",url:s,dataType:"json",contentType:"application/json",data:o,success:function(r){r.saveContext=e;var n=r.data;if(n.Errors||n.errors)t(i,r);else{var o=a._prepareSaveResult(e,n);o.httpResponse=r,i.resolve(o)}},error:function(r){r.saveContext=e,t(i,r)}}),i.promise},i._prepareSaveBundle=function(){throw new Error("Need a concrete implementation of _prepareSaveBundle")},i.changeRequestInterceptor=e,i._createChangeRequestInterceptor=function(t,r){var n=t.adapter,a=V,i=n.changeRequestInterceptor,o=n.name+" DataServiceAdapter's ChangeRequestInterceptor",s=" is missing or not a function.";if(a(i)){var u=new i(t,r);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,r)},i._prepareSaveResult=function(){throw new Error("Need a concrete implementation of _prepareSaveResult")},i.jsonResultsAdapter=new Ot({name:"noop",visitNode:function(){return{}}}),i._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?")},a}(),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&define(["breeze"],e)}(function(e){function t(e){var r,n,a,i="";for(var o in e){var s=e[o];if(s instanceof Array)for(var u=0;u<s.length;++u)r=s[u],a=o+"["+u+"]",n={},n[a]=r,i+=t(n)+"&";else if(s instanceof Date)i+=encodeURIComponent(o)+"="+encodeURIComponent(s.toISOString())+"&";else if(s instanceof Object)for(var p in s)r=s[p],a=o+"["+p+"]",n={},n[a]=r,i+=t(n)+"&";else null===s?i+=encodeURIComponent(o)+"=&":void 0!==s&&(i+=encodeURIComponent(o)+"="+encodeURIComponent(s)+"&")}return i.length?i.substr(0,i.length-1):i}var r=e.core,n=function(){this.name="angular",this.defaultSettings={},this.requestInterceptor=null,this.$http,this.$rootScope},a=n.prototype;a.initialize=function(){var e=r.requireLib("angular");if(e){var t,n,a=e.injector(["ng"]);a.invoke(["$http","$rootScope",function(e,r){t=e,n=r}]),this.$http=t,this.$rootScope=n}},a.setHttp=function(e){this.$http=e,this.$rootScope=null},a.ajax=function(e){function n(t,r,n,a,i){"null"===t&&(t=null);var o={config:e,data:t,getHeaders:n,status:r,statusText:i};e.success(o)}function a(t,r,n,a,i){0===r&&null==t&&(t="timeout");var o={config:e,data:t,getHeaders:n,status:r,statusText:i};e.error(o)}if(!this.$http)throw new Error("Unable to locate angular for ajax adapter");var i={method:e.type,url:e.url,dataType:e.dataType,contentType:e.contentType,crossDomain:e.crossDomain,headers:e.headers||{}};if(e.params){var o=i.url.indexOf("?")>=0?"&":"?";i.url=i.url+o+t(e.params)}if(e.data&&(i.data=e.data),!r.isEmpty(this.defaultSettings)){var s=r.extend({},this.defaultSettings);i=r.extend(s,i);var u=r.extend({},this.defaultSettings.headers);i.headers=r.extend(u,i.headers)}var p={adapter:this,config:i,zConfig:e,success:n,error:a};r.isFunction(this.requestInterceptor)&&(this.requestInterceptor(p),this.requestInterceptor.oneTime&&(this.requestInterceptor=null)),p.config&&(this.$http(p.config).success(p.success).error(p.error),this.$rootScope&&this.$rootScope.$digest())},e.config.registerAdapter("ajax",n)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&define(["breeze"],e)}(function(e){function t(e){return 0===e.status?function(e){return e&&e.length>0?"":{}}:function(t){return t&&t.length>0?e.getResponseHeader(t):e.getAllResponseHeaders()}}var r,n=e.core,a=function(){this.name="jQuery",this.defaultSettings={},this.requestInterceptor=null},i=a.prototype;i.initialize=function(){r=n.requireLib("jQuery")},i.ajax=function(e){function a(r,n,a){var i={config:e,data:r,getHeaders:t(a),status:a.status,statusText:n};e.success(i),a.onreadystatechange=null,a.abort=null}function i(r,n,a){var i={config:e,data:r.responseText,error:a,getHeaders:t(r),status:r.status,statusText:n};e.error(i),r.onreadystatechange=null,r.abort=null}if(!r)throw new Error("Unable to locate jQuery");var o={type:e.type,url:e.url,data:e.params||e.data,dataType:e.dataType,contentType:e.contentType,crossDomain:e.crossDomain,headers:e.headers||{}};if(!n.isEmpty(this.defaultSettings)){var s=n.extend({},this.defaultSettings);o=n.extend(s,o);var u=n.extend({},this.defaultSettings.headers);o.headers=n.extend(u,o.headers)}var p={adapter:this,config:o,zConfig:e,success:a,error:i};n.isFunction(this.requestInterceptor)&&(this.requestInterceptor(p),this.requestInterceptor.oneTime&&(this.requestInterceptor=null)),p.config&&(p.jqXHR=r.ajax(p.config).done(p.success).fail(p.error))},e.config.registerAdapter("ajax",a)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){function t(e,t){return e.isUnmapped?void 0:(e.dataType===_t.DateTimeOffset?t=t&&new Date(t.getTime()-6e4*t.getTimezoneOffset()):e.dataType.quoteJsonOData&&(t=null!=t?t.toString():t),t)}function r(e,r){var a=e.adapter._createChangeRequestInterceptor(e,r),i=[],o=[],s=[],u=e.entityManager,p=u.helper,c=0,l=e.routePrefix;return r.entities.forEach(function(e,r){var y=e.entityAspect;c+=1;var f={headers:{"Content-ID":c,DataServiceVersion:"2.0"}};
if(s[c]=e,y.entityState.isAdded())f.requestUri=l+e.entityType.defaultResourceName,f.method="POST",f.data=p.unwrapInstance(e,t),o[c]=y.getKey();else if(y.entityState.isModified())n(f,y,l),f.method="MERGE",f.data=p.unwrapChangedValues(e,u.metadataStore,t);else{if(!y.entityState.isDeleted())return;n(f,y,l),f.method="DELETE"}f=a.getRequest(f,e,r),i.push(f)}),e.contentKeys=s,e.tempKeys=o,a.done(i),{__batchRequests:[{__changeRequests:i}]}}function n(e,t,r){var n,i=t.extraMetadata;null==i?(n=a(t),t.extraMetadata={uriKey:n}):(n=i.uriKey,i.etag&&(e.headers["If-Match"]=i.etag)),e.requestUri=n.indexOf("//")>0?n:r+n}function a(e){var t=e.entity.entityType,r=t.defaultResourceName,n=t.keyProperties,a=r+"(";if(1===n.length)a=a+i(n[0],e)+")";else{var o="";n.forEach(function(t){a=a+o+t.nameOnServer+"="+i(t,e),o=","}),a+=")"}return a}function i(e,t){return e.dataType.fmtOData(t.getPropertyValue(e.name))}function o(e,t){var r=new Error,n=e&&e.response;if(!n)return r.message=e,r.statusText=e,r;if(r.message=n.statusText,r.statusText=n.statusText,r.status=n.statusCode,t&&(r.url=t),r.body=n.body,n.body){var a;try{var i=JSON.parse(n.body);r.body=i,i["odata.error"]&&(i=i["odata.error"]);var o="";do a=i.error||i.innererror,a||(o+=s(i)),a=a||i.internalexception,i=a||i;while(a);o.length>0&&(r.message=o)}catch(u){}}return h._catchNoConnectionError(r),r}function s(e){var t=e.message||"";return("string"==typeof t?t:t.value)+"; "}var u,p=e.core,c=e.MetadataStore,l=e.JsonResultsAdapter,y=e.DataProperty,f=function(){this.name="OData"},h=f.prototype;h.initialize=function(){u=p.requireLib("OData","Needed to support remote OData services"),u.jsonHandler.recognizeDates=!0};var d=e.AbstractDataServiceAdapter.prototype;h._catchNoConnectionError=d._catchNoConnectionError,h.changeRequestInterceptor=d.changeRequestInterceptor,h._createChangeRequestInterceptor=d._createChangeRequestInterceptor,h.headers={DataServiceVersion:"2.0"},h.executeQuery=function(e){var t=At.defer(),r=e.getUrl();return u.read({requestUri:r,headers:this.headers},function(e,r){var n;return e.__count&&(n=parseInt(e.__count,10)),t.resolve({results:e.results,inlineCount:n,httpResponse:r})},function(e){return t.reject(o(e,r))}),t.promise},h.fetchMetadata=function(e,t){var r=At.defer(),n=t.serviceName,a=t.qualifyUrl("$metadata");return u.read({requestUri:a,headers:{Accept:"application/json;odata.metadata=full"}},function(i){if(!i||!i.dataServices){var o=new Error("Metadata query failed for: "+a);return r.reject(o)}var s=i.dataServices;if(!e.hasMetadataFor(n)){try{e.importMetadata(s)}catch(u){return r.reject(new Error("Metadata query failed for "+a+"; Unable to process returned metadata: "+u.message))}e.addDataService(t)}return r.resolve(s)},function(e){var t=o(e,a);return t.message="Metadata query failed for: "+a+"; "+(t.message||""),r.reject(t)},u.metadataHandler),r.promise},h.getRoutePrefix=function(){return""},h.saveChanges=function(e,t){var n=e.adapter=this,a=At.defer();e.routePrefix=n.getRoutePrefix(e.dataService);var i=e.dataService.qualifyUrl("$batch"),s=r(e,t),p=e.tempKeys,c=e.contentKeys;return u.request({headers:{DataServiceVersion:"2.0"},requestUri:i,method:"POST",data:s},function(e){var t=[],r=[],n={entities:t,keyMappings:r};return e.__batchResponses.forEach(function(e){e.__changeResponses.forEach(function(e){var n=e.response||e,s=n.statusCode;if(!s||s>=400)return void a.reject(o(e,i));var u=e.headers["Content-ID"],l=e.data;if(l){var f=p[u];if(f){var h=f.entityType;if(h.autoGeneratedKeyType!==It.None){var d=f.values[0],m=h.getEntityKeyFromRawEntity(l,y.getRawValueFromServer),v={entityTypeName:h.name,tempValue:d,realValue:m.values[0]};r.push(v)}}t.push(l)}else{var g=c[u];t.push(g)}})}),a.resolve(n)},function(e){return a.reject(o(e,i))},u.batchHandler),a.promise},h.jsonResultsAdapter=new l({name:"OData_default",visitNode:function(e,t,r){var n={};if(null==e)return n;var a=e.__metadata;if(null!=a){var i=c.normalizeTypeName(a.type),o=i&&t.entityManager.metadataStore.getEntityType(i,!0);if(o&&o._mappedPropertiesCount<=Object.keys(e).length-1){n.entityType=o;var s=a.uri||a.id;if(s){var u=new RegExp("^"+t.dataService.serviceName,"i");s=s.replace(u,"")}n.extraMetadata={uriKey:s,etag:a.etag}}}e.results&&(n.node=e.results);var l=r.propertyName;return n.ignore=null!=e.__deferred||"__metadata"===l||"EntityKey"===l&&e.$type&&p.stringStartsWith(e.$type,"System.Data"),n}}),e.config.registerAdapter("dataService",f);var m=function(){this.name="webApiOData"};e.core.extend(m.prototype,h),m.prototype.getRoutePrefix=function(e){if("object"==typeof document){var t=document.createElement("a");t.href=e.serviceName}else t=url.parse(e.serviceName);var r=t.pathname;return"/"===r[0]&&(r=r.substr(1)),"/"!==r.substr(-1)&&(r+="/"),r},e.config.registerAdapter("dataService",m);var v=function(){this.name="webApiOData4"};e.core.extend(v.prototype,m.prototype),v.prototype.initialize=function(){var e=p.requireLib("datajs","Needed to support remote OData v4 services");u=e.V4.oData,u.json.jsonHandler.recognizeDates=!0},v.prototype.headers={"OData-Version":"4.0"},e.config.registerAdapter("dataService",v)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){var t=e.MetadataStore,r=e.JsonResultsAdapter,n=e.AbstractDataServiceAdapter,a=function(){this.name="webApi"},i=a.prototype=new n;i._prepareSaveBundle=function(e,t){var r=this._createChangeRequestInterceptor(e,t),n=e.entityManager,a=n.metadataStore,i=n.helper;return t.entities=t.entities.map(function(e,t){var n=i.unwrapInstance(e),o=null;e.entityType.autoGeneratedKeyType!==It.None&&(o={propertyName:e.entityType.keyProperties[0].nameOnServer,autoGeneratedKeyType:e.entityType.autoGeneratedKeyType.name});var s=i.unwrapOriginalValues(e,a);return n.entityAspect={entityTypeName:e.entityType.name,defaultResourceName:e.entityType.defaultResourceName,entityState:e.entityAspect.entityState.name,originalValuesMap:s,autoGeneratedKey:o},n=r.getRequest(n,e,t)}),t.saveOptions={tag:t.saveOptions.tag},r.done(t.entities),t},i._prepareSaveResult=function(e,r){if(r.entities)return r;var n=r.KeyMappings.map(function(e){var r=t.normalizeTypeName(e.EntityTypeName);return{entityTypeName:r,tempValue:e.TempValue,realValue:e.RealValue}});return{entities:r.Entities,keyMappings:n}},i.jsonResultsAdapter=new r({name:"webApi_default",visitNode:function(e,r,n){if(null==e)return{};var a=t.normalizeTypeName(e.$type),i=a&&r.entityManager.metadataStore._getEntityType(a,!0),o=n.propertyName,s=o&&"$"===o.substr(0,1);return{entityType:i,nodeId:e.$id,nodeRefId:e.$ref,ignore:s}}}),e.config.registerAdapter("dataService",a)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){function t(e){var t=e.entityType||e.complexType,r=t._extra,a=r.alreadyWrappedProps||{};t.getProperties().forEach(function(t){var r=t.name;if(!a[r]){var o;o=r in e?i(e,t):n(e,t),null!=o&&Object.defineProperty(e,r,o),a[r]=!0}}),r.alreadyWrappedProps=a}function r(e){var t=o(e),r=Object.getPrototypeOf(e),a=r.entityType||r.complexType;return a.getProperties().forEach(function(t){var a=t.name;if(t.isUnmapped&&!p.getPropertyDescriptor(r,a)){var i=n(r,t);Object.defineProperty(r,a,i)}if(e.hasOwnProperty(a)){var o=e[a];delete e[a],e[a]=o}}),t}function n(e,t){var r=t.name,n=e._pendingBackingStores;n||(n=[],e._pendingBackingStores=n);var i={get:function(){var e=this._backingStore||o(this);return e[r]},set:function(e){var n=this._backingStore||s(this),i=a(n,r);this._$interceptor(t,e,i)},enumerable:!0,configurable:!0};return i.set.rawSet=function(e){var t=this._backingStore||s(this),n=a(t,r);n(e)},i}function a(e,t){return function(){return 0==arguments.length?e[t]:void(e[t]=arguments[0])}}function i(e,t){if(!e.hasOwnProperty(t.name)){var r=Object.getPrototypeOf(e);return i(r,t)}var n=Object.getOwnPropertyDescriptor(e,t.name);if(n.configurable&&!n.value&&n.set){var a=function(e){return function(){if(0==arguments.length)return n.get.bind(e)();var t=n.set,r=t.rawSet||t;r.bind(e)(arguments[0])}},o={get:function(){return n.get.bind(this)()},set:function(e){this._$interceptor(t,e,a(this))},enumerable:n.enumerable,configurable:!0};return o.set.rawSet=n.set,o}}function o(e){var t=Object.getPrototypeOf(e);u(t);var r=e._backingStore;return r||(r={},e._backingStore=r),r}function s(e){var t=Object.getPrototypeOf(e),r=t._pendingBackingStores,n=p.arrayFirst(r,function(t){return t.entity===e});if(n)return n.backingStore;var a={};return r.push({entity:e,backingStore:a}),a}function u(e){var t=e._pendingBackingStores;t&&(t.forEach(function(e){e.entity._backingStore=e.backingStore}),t.length=0)}var p=e.core,c=function(){this.name="backingStore"},l=c.prototype;l.initialize=function(){},l.getTrackablePropertyNames=function(e){var t=[];for(var r in e)if("entityType"!==r&&"_$typeName"!==r&&"_pendingSets"!==r&&"_backingStore"!==r){var n=e[r];p.isFunction(n)||t.push(r)}return t},l.initializeEntityPrototype=function(e){e.getProperty=function(e){return this[e]},e.setProperty=function(e,t){return this[e]=t,this},t(e)},l.startTracking=function(t){var n=r(t),a=t.entityType||t.complexType;a.getProperties().forEach(function(r){var a=r.name,i=t[a];if(r.isDataProperty)r.isComplexProperty?i=r.isScalar?r.dataType._createInstanceCore(t,r):e.makeComplexArray([],t,r):r.isScalar?void 0===i&&(i=r.defaultValue):i=e.makePrimitiveArray([],t,r);else{if(!r.isNavigationProperty)throw new Error("unknown property: "+a);if(void 0!==i)throw new Error("Cannot assign a navigation property in an entity ctor.: "+r.Name);i=r.isScalar?null:e.makeRelationArray([],t,r)}(r.isSettable||r.isNavigationProperty)&&(n[a]=i)})},e.config.registerAdapter("modelLibrary",c)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){function t(){try{return Object.getPrototypeOf&&Object.defineProperty({},"x",{})}catch(e){return!1}}function r(e){var t=e.entityType||e.complexType,r={};if(t.getProperties().forEach(function(t){var a=n(e,t.name);a&&(r[t.name]=a)}),!z(r)){var a=t._extra;a.es5Descriptors=r,t._koDummy=s.observable(null)}}function n(e,r){if(!t())return null;if(e.hasOwnProperty(r))return Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(e,r);var a=Object.getPrototypeOf(e);return a?n(a,r):null}function a(t,r,n){if(r.isDataProperty)r.isComplexProperty?n=r.isScalar?r.dataType._createInstanceCore(t,r):e.makeComplexArray([],t,r):r.isScalar?void 0===n&&(n=r.defaultValue):n=e.makePrimitiveArray([],t,r);else{if(!r.isNavigationProperty)throw new Error("unknown property: "+r.name);if(void 0!==n)throw new Error("Cannot assign a navigation property in an entity ctor.: "+r.name);n=r.isScalar?null:e.makeRelationArray([],t,r)}return n}function i(e){e._koObj._suppressBreeze=!0}function o(e){var t=e.array._koObj;t._suppressBreeze?t._suppressBreeze=!1:t.valueHasMutated()}var s,u=e.core,p=function(){this.name="ko"},c=p.prototype;c.initialize=function(){s=u.requireLib("ko","The Knockout library"),s.extenders.intercept=function(e,t){var r,n=t.instance,a=t.property;return r=s.computed(e.splice?{read:e}:{read:e,write:function(t){return n._$interceptor(a,t,e),n}})}},c.getTrackablePropertyNames=function(e){var t=[];for(var r in e)if("entityType"!==r&&"_$typeName"!==r){var a=n(e,r);if(a&&a.get)t.push(r);else{var i=e[r];s.isObservable(i)?t.push(r):u.isFunction(i)||t.push(r)}}return t},c.initializeEntityPrototype=function(e){e.getProperty=function(e){return this[e]()},e.setProperty=function(e,t){return this[e](t),this},t()&&r(e)},c.startTracking=function(e){var t=e.entityType||e.complexType,r=t._extra.es5Descriptors||{};t.getProperties().sort(function(e,t){var r=e.isUnmapped?1:0,n=t.isUnmapped?1:0;return r-n}).forEach(function(n){var u,p=n.name,c=e[p],l=r[p];if(l){var y=l.get.bind(e);if(l.set){var f=l.set.bind(e),h=function(e){return 0===arguments.length?y():void f(e)};u=s.computed({read:function(){return t._koDummy(),y()},write:function(r){return e._$interceptor(n,r,h),t._koDummy.valueHasMutated(),e}})}else u=s.computed({read:y,write:function(){}})}else if(s.isObservable(c)){if(n.isNavigationProperty)throw new Error("Cannot assign a navigation property in an entity ctor.: "+p);u=c}else c=a(e,n,c),u=n.isScalar?s.observable(c):s.observableArray(c);if(n.isScalar)if(l)Object.defineProperty(e,p,{enumerable:!0,configurable:!0,writable:!0,value:u});else{var d=u.extend({intercept:{instance:e,property:n}});e[p]=d}else c._koObj=u,u.subscribe(i,null,"beforeChange"),c.arrayChanged.subscribe(o),u.equalityComparer=function(){throw new Error("Collection navigation properties may NOT be set.")},e[p]=u})},e.config.registerAdapter("modelLibrary",p)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){var t=function(){this.name="json"},r=t.prototype;r.initialize=function(){},r.buildUri=function(e,t){var r=e._getFromEntityType(t,!1);r||(r=new Ft(t));var n=e.toJSONExt({entityType:r,toNameOnServer:!0});n.from=void 0,n.queryOptions=void 0;var a=JSON.stringify(n),i=encodeURIComponent(a);return e.resourceName+"?"+i},e.config.registerAdapter("uriBuilder",t)}),function(e){nt?e(nt):"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?e(require("breeze")):"function"==typeof define&&define.amd&&!nt&&define(["breeze"],e)}(function(e){var t=e.EntityType,r=function(){this.name="odata"},n=r.prototype;n.initialize=function(){},n.buildUri=function(e,r){function n(e){return e?e.visit({entityType:p},a):void 0}function i(e){if(e){e.validate(p);var t=e.items.map(function(e){return p.clientPropertyPathToServer(e.propertyPath,"/")+(e.isDesc?" desc":"")});return t.join(",")}}function o(e){if(e){e.validate(p);var t=e.propertyPaths.map(function(e){return p.clientPropertyPathToServer(e,"/")}).join(",");return t}}function s(e){if(e){var t=e.propertyPaths.map(function(e){return p.clientPropertyPathToServer(e,"/")}).join(",");return t}}function u(e){var t=[];for(var r in e){var n=e[r];void 0!==n&&(n instanceof Array?n.forEach(function(e){t.push(r+"="+encodeURIComponent(e))}):t.push(r+"="+encodeURIComponent(n)))}return t.length>0?"?"+t.join("&"):""}var p=e._getFromEntityType(r,!1);p||(p=new t(r));var c={};c.$filter=n(e.wherePredicate),c.$orderby=i(e.orderByClause),e.skipCount&&(c.$skip=e.skipCount),null!=e.takeCount&&(c.$top=e.takeCount),c.$expand=s(e.expandClause),c.$select=o(e.selectClause),e.inlineCountEnabled&&(c.$inlinecount="allpages");var l=u(c);return e.resourceName+l},e.Predicate.prototype.toODataFragment=function(e){return this.visit(e,a)};var a=function(){function t(e){var t=e.op.key,r=n[t];return r||t}var r={passthruPredicate:function(){return this.value},unaryPredicate:function(e){var r=this.pred.visit(e);return t(this)+" ("+r+")"},binaryPredicate:function(e){var r=this.expr1.visit(e),n=this.expr2.visit(e),a=e.prefix;a&&(r=a+"/"+r);var i=t(this);if("in"==this.op.key){var o=n.map(function(e){return"("+r+" eq "+e+")"}).join(" or ");return o}return this.op.isFunction?"substringof"==i?i+"("+n+","+r+") eq true":i+"("+r+","+n+") eq true":r+" "+i+" "+n},andOrPredicate:function(e){var r=this.preds.map(function(t){var r=t.visit(e);return"("+r+")"}).join(" "+t(this)+" ");return r},anyAllPredicate:function(r){var n=this.expr.visit(r),a=r.prefix;a?(n=a+"/"+n,a="x"+(parseInt(a.substring(1))+1)):a="x1";var i=e.core.extend({},r);i.entityType=this.expr.dataType,i.prefix=a;var o=this.pred.visit(i);return n+"/"+t(this)+"("+a+": "+o+")"},litExpr:function(){return Array.isArray(this.value)?this.value.map(function(e){return this.dataType.fmtOData(e)},this):this.dataType.fmtOData(this.value)},propExpr:function(e){var t=e.entityType;return t?t.clientPropertyPathToServer(this.propertyPath,"/"):this.propertyPath},fnExpr:function(e){var t=this.exprs.map(function(t){return t.visit(e)});return this.fnName+"("+t.join(",")+")"}},n={contains:"substringof"};return r}();e.config.registerAdapter("uriBuilder",r)}),nt.config.initializeAdapterInstances({dataService:"webApi",ajax:"jQuery",uriBuilder:"odata"});var Yt=_("ko");return Yt?nt.config.initializeAdapterInstance("modelLibrary","ko"):nt.config.initializeAdapterInstance("modelLibrary","backingStore"),nt});