UNPKG

@stratusjs/angularjs

Version:

This is the AngularJS package for StratusJS.

1 lines 36.4 kB
System.register(["angular","@stratusjs/runtime/stratus","lodash","angular-material","@stratusjs/core/errors/errorBase","@stratusjs/core/misc","@stratusjs/core/datastore/modelBase","@stratusjs/core/environment","@stratusjs/core/datastore/xhr","@stratusjs/core/events/eventManager","toastify-js","@stratusjs/core/conversion","angular-sanitize"],function(exports){"use strict";var element,Stratus,throttle,extend,isObject,isArray,forEach,get,isUndefined,set,clone,isEmpty,find,isFunction,map,reduce,has,cloneDeep,once,isNumber,head,isString,filter,isEqual,union,kebabCase,size,_,isDate,isElement,ErrorBase,ucfirst,isJSON,setUrlParams,getAnchorParams,getUrlParams,serializeUrlParams,patch,strcmp,poll,flatten,safeUniqueId,ModelBase,cookie,XHR,EventManager,Toastify,sanitize;return{setters:[function(module){element=module.element},function(module){Stratus=module.Stratus},function(module){throttle=module.throttle,extend=module.extend,isObject=module.isObject,isArray=module.isArray,forEach=module.forEach,get=module.get,isUndefined=module.isUndefined,set=module.set,clone=module.clone,isEmpty=module.isEmpty,find=module.find,isFunction=module.isFunction,map=module.map,reduce=module.reduce,has=module.has,cloneDeep=module.cloneDeep,once=module.once,isNumber=module.isNumber,head=module.head,isString=module.isString,filter=module.filter,isEqual=module.isEqual,union=module.union,kebabCase=module.kebabCase,size=module.size,_=module.default,isDate=module.isDate,isElement=module.isElement},null,function(module){ErrorBase=module.ErrorBase},function(module){ucfirst=module.ucfirst,isJSON=module.isJSON,setUrlParams=module.setUrlParams,getAnchorParams=module.getAnchorParams,getUrlParams=module.getUrlParams,serializeUrlParams=module.serializeUrlParams,patch=module.patch,strcmp=module.strcmp,poll=module.poll,flatten=module.flatten,safeUniqueId=module.safeUniqueId},function(module){ModelBase=module.ModelBase},function(module){cookie=module.cookie},function(module){XHR=module.XHR},function(module){EventManager=module.EventManager},function(module){Toastify=module.default},function(module){sanitize=module.sanitize},null],execute:function(){const getInjector=exports("getInjector",()=>{const $root=element(document.documentElement);return $root&&$root.injector?$root.injector():null});var __awaiter$3=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};const CollectionOptionKeys=exports("CollectionOptionKeys",["autoSave","autoSaveInterval","cache","direct","target","targetSuffix","urlRoot","watch","payload","convoy","headers"]);class Collection extends EventManager{constructor(options={}){if(super(),this.name="Collection",this.direct=!1,this.target=null,this.targetSuffix=null,this.urlRoot="/Api",this.toast=!0,this.qualifier="",this.serviceId=null,this.infinite=!1,this.threshold=.5,this.decay=0,this.header=new ModelBase,this.meta=new ModelBase,this.model=Model,this.models=[],this.types=[],this.withCredentials=!1,this.headers={},this.cacheResponse={},this.cacheHeaders={},this.cache=!1,this.pending=!1,this.error=!1,this.completed=!1,this.filtering=!1,this.paginate=!1,this.watch=!1,this.autoSave=!1,this.autoSaveInterval=2500,this.throttle=throttle(this.fetch,1e3),extend(this,options=options&&"object"==typeof options?options:{}),this.target&&(this.urlRoot+="/"+ucfirst(this.target)),options.convoy){const convoy=isJSON(options.convoy)?JSON.parse(options.convoy):options.convoy;if(isObject(convoy)){this.meta.set(convoy.meta||{});const models=convoy.payload;isArray(models)?(this.inject(models),this.completed=!0):console.error("malformed payload:",models)}else console.error("malformed convoy:",convoy)}if(options.payload){const models=isJSON(options.payload)?JSON.parse(options.payload):options.payload;isArray(models)?(this.inject(models),this.completed=!0):console.error("malformed payload:",models)}}sanitizeOptions(options){const sanitizedOptions={};return forEach(CollectionOptionKeys,key=>{const data=get(options,key);isUndefined(data)||set(sanitizedOptions,key,data)}),sanitizedOptions}serialize(obj,chain){const str=[];return forEach(obj=obj||{},(value,key)=>{if(isObject(value))chain&&(key=chain+"["+key+"]"),str.push(this.serialize(value,key));else{let encoded="";chain&&(encoded+=chain+"["),encoded+=key,chain&&(encoded+="]"),str.push(encoded+"="+value)}}),str.join("&")}url(){return this.urlRoot+(this.targetSuffix||"")}inject(data,type){isArray(data)&&(this.types&&-1===this.types.indexOf(type)&&this.types.push(type),this.direct||data.forEach(target=>{this.models.push(new Model({autoSave:this.autoSave,autoSaveInterval:this.autoSaveInterval,collection:this,completed:!0,received:!0,toast:this.toast,type:type||null,watch:this.watch},target))}))}sync(action,data,options){return this.pending=!0,new Promise((resolve,reject)=>__awaiter$3(this,void 0,void 0,function*(){options=options||{};const request={method:action=action||"GET",url:this.url(),headers:clone(this.headers),withCredentials:this.withCredentials};isUndefined(data)||("GET"===action?isObject(data)&&Object.keys(data).length&&(request.url+=request.url.includes("?")?"&":"?",request.url+=this.serialize(data)):(request.headers["Content-Type"]="application/json",request.data=JSON.stringify(data))),Object.prototype.hasOwnProperty.call(options,"headers")&&"object"==typeof options.headers&&Object.keys(options.headers).forEach(headerKey=>{request.headers[headerKey]=options.headers[headerKey]});const queryHash=`${request.method}:${request.url}`;options.nocache&&(queryHash in this.cacheResponse&&delete this.cacheResponse[queryHash],queryHash in this.cacheHeaders&&delete this.cacheHeaders[queryHash]),this.xhr=new XHR(request);const handler=response=>{if(!isObject(response)&&!isArray(response)){const error=new ErrorBase({payload:response,message:`Invalid Payload: ${request.method} ${request.url}`},{});return this.error=!0,this.pending=!1,this.throttleTrigger("change"),this.trigger("error",error),void reject(error)}let responseHeaders=null;this.cache&&"GET"===request.method&&(queryHash in this.cacheResponse||(this.cacheResponse[queryHash]=cloneDeep(response)),queryHash in this.cacheHeaders?responseHeaders=this.cacheHeaders[queryHash]:this.cacheHeaders[queryHash]=this.xhr.getAllResponseHeaders()),this.header.set(responseHeaders||this.xhr.getAllResponseHeaders()),this.meta.set(response.meta||{}),this.models=[];const payload=response.payload||response;this.error=!1,this.meta.has("success")&&!this.meta.get("success")?this.error=!0:this.direct?this.models=payload:isArray(payload)?this.inject(payload):isObject(payload)?forEach(payload,(value,key)=>{this.inject(value,key)}):(this.meta.has("status")||this.meta.has("success")||(this.error=!0),console.warn(`Invalid Payload: ${request.method} ${request.url}`)),this.pending=!1,this.completed=!0,this.filtering=!isEmpty(this.meta.get("api.q")),this.paginate=!isEmpty(this.meta.get("api.p")),this.meta.clearTemp(),this.throttleTrigger("change"),this.trigger("complete"),resolve(this.models)};this.cache&&"GET"===request.method&&queryHash in this.cacheResponse?handler(this.cacheResponse[queryHash]):this.xhr.send().then(handler).catch(error=>{console.error(`XHR: ${request.method} ${request.url}`),this.throttleTrigger("change"),this.trigger("error",error),reject(error)})}))}fetch(action,data,options){return new Promise((resolve,reject)=>__awaiter$3(this,void 0,void 0,function*(){this.sync(action,data||this.meta.get("api"),options).then(resolve).catch(error=>__awaiter$3(this,void 0,void 0,function*(){if(console.error("FETCH:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";Toastify({text:`Unable to Fetch ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)}))}))}filter(query){return this.filtering=!isEmpty(query),this.meta.set("api.q",isUndefined(query)?"":query),this.meta.set("api.p",1),this.fetch()}throttleFilter(query){return this.meta.set("api.q",isUndefined(query)?"":query),new Promise((resolve,reject)=>{const request=this.throttle();cookie("env")&&console.log("request:",request),request.then(models=>{cookie("env"),resolve(models)}).catch(reject)})}page(page){this.paginate=!isEmpty(page),this.meta.set("api.p",page),this.fetch().then(),delete this.meta.get("api").p}toJSON(){return this.direct?this.models:this.models.map(model=>model.toJSON())}add(target,options){if(isObject(target))return options&&"object"==typeof options||(options={}),target instanceof Model?target.collection=this:(options.collection=this,(target=new Model(options,target)).initialize(),(options.autoSave||options.watch)&&(target.isNew()?target.save():target.completed||target.fetch())),options.save&&target.save(),options.prepend?this.models.unshift(target):this.models.push(target),options.trigger&&this.trigger("add",target),this.throttleTrigger("change"),target;console.error("collection.add: target object not set!")}remove(target){return this.direct||(this.models.splice(this.models.indexOf(target),1),this.throttleTrigger("change")),this}find(predicate){return find(this.models,isFunction(predicate)?predicate:model=>model.get("id")===predicate)}map(predicate){return map(this.models,model=>model instanceof Model?model.get(predicate):null)}pluck(attribute){return map(this.models,model=>model instanceof Model?model.pluck(attribute):null)}exists(attribute){return!!reduce(this.pluck(attribute)||[],(memo,data)=>memo||!isUndefined(data))}errorMessage(error){if(error instanceof ErrorBase)return console.error(`[${error.code}] ${error.message}`,error),"Internal"!==error.code?error.message:null;const digest=error.responseText&&isJSON(error.responseText)?JSON.parse(error.responseText):null;if(!digest)return null;const message=get(digest,"meta.status[0].message")||get(digest,"error.exception[0].message")||null;return message?!cookie("env")&&has(digest,"error.exception[0].message")?(console.error("[xhr] server:",message),null):message:null}}exports("Collection",Collection),Stratus.Services.Collection=["$provide",$provide=>{$provide.factory("Collection",[()=>Collection])}],Stratus.Data.Collection=Collection;var __awaiter$2=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};let $rootScope,injector$1=getInjector();const serviceVerify$1=()=>__awaiter$2(void 0,void 0,void 0,function*(){return new Promise((resolve,_reject)=>__awaiter$2(void 0,void 0,void 0,function*(){$rootScope?resolve(!0):(injector$1||(injector$1=getInjector()),injector$1&&($rootScope=injector$1.get("$rootScope")),$rootScope?resolve(!0):setTimeout(()=>{cookie("env")&&console.log("wait for $rootScope service:",{$rootScope}),serviceVerify$1().then(resolve)},250))}))}),ModelOptionKeys=exports("ModelOptionKeys",["autoSave","autoSaveInterval","autoSaveHalt","collection","completed","manifest","serviceId","stagger","target","targetSuffix","toast","type","urlRoot","urlSync","watch","withCredentials","payload","convoy","headers","ignoreKeys","received"]);class Model extends ModelBase{constructor(options={},attributes){if(super(attributes),this.name="Model",this.target=null,this.type=null,this.manifest=!1,this.stagger=!1,this.toast=!0,this.identifier=null,this.urlRoot="/Api",this.targetSuffix=null,this.serviceId=null,this.header=new ModelBase,this.meta=new ModelBase,this.route=new ModelBase,this.collection=null,this.withCredentials=!1,this.headers={},this.pending=!1,this.error=!1,this.completed=!1,this.saving=!1,this.changedExternal=!1,this.watch=!0,this.status=null,this.autoSave=!1,this.autoSaveInterval=4e3,this.autoSaveHalt=!0,this.autoSaveTimeout=null,this.urlSync=!1,this.bracket={match:/\[[\d+]]/,search:/\[([\d+])]/g,attr:/(^[^[]+)/},this.throttle=throttle(this.fetch,1e3),this.initialize=null,(options="object"!=typeof options?{}:options).received=options.received||!1,extend(this,this.sanitizeOptions(options)),options.convoy){const convoy=isJSON(options.convoy)?JSON.parse(options.convoy):options.convoy;if(isObject(convoy)){this.meta.set(convoy.meta||{});const payload=convoy.payload;isObject(payload)?(extend(this.data,payload),this.completed=!0,options.received=!0):console.error("malformed payload:",payload)}else console.error("malformed convoy:",convoy)}if(options.payload){const payload=isJSON(options.payload)?JSON.parse(options.payload):options.payload;isObject(payload)?(extend(this.data,payload),this.completed=!0,options.received=!0):console.error("malformed payload:",payload)}this.header=new ModelBase,this.meta=new ModelBase,this.route=new ModelBase,isEmpty(this.collection)||(this.collection.target&&(this.target=this.collection.target),this.collection.meta.has("api")&&this.meta.set("api",this.collection.meta.get("api"))),this.recv=options.received?cloneDeep(this.data):{},this.sent={},this.ignoreKeys=options.ignoreKeys||["$$hashKey"],this.target&&(this.urlRoot+="/"+ucfirst(this.target));const that=this;this.initialize=once(this.initialize||function(){that.completed&&(that.watch||that.autoSave)&&that.watcher().then(),that.manifest&&!that.getIdentifier()&&that.sync("POST",that.meta.has("api")?{meta:that.meta.get("api"),payload:{}}:{}).catch(error=>__awaiter$2(this,void 0,void 0,function*(){if(console.error("MANIFEST:",error),!that.toast)return;const errorMessage=that.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";Toastify({text:`Unable to Manifest ${that.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),that.errorMessage(error)}))}),this.stagger||this.initialize()}resetXHRFlags(){this.pending=!1,this.saving=!1}sanitizeOptions(options){const sanitizedOptions={};return forEach(ModelOptionKeys,key=>{const data=get(options,key);isUndefined(data)||set(sanitizedOptions,key,data)}),sanitizedOptions}watcher(){return __awaiter$2(this,void 0,void 0,function*(){if(this.watching)return!0;this.watching=!0,$rootScope||(yield serviceVerify$1()),$rootScope.$watch(()=>this.data,(_newData,_priorData)=>this.handleChanges(),!0)})}handleChanges(changeSet){const isUserChangeSet=isUndefined(changeSet);if(isUserChangeSet&&(changeSet=super.handleChanges()),!changeSet||isEmpty(changeSet))return changeSet;if(this.error&&!this.completed&&this.getIdentifier()){const action=isUserChangeSet?"save":"sync url for";return void console.warn(`Blocked attempt to ${action} a persisted model that has not been fetched successfully.`)}if(isUserChangeSet||cookie("env")&&console.info("Attempting URL Sync for non-User ChangeSet:",changeSet),this.urlSync){if(get(changeSet,"id")){const newUrl=setUrlParams({id:get(changeSet,"id")||this.getIdentifier()});newUrl!==document.location.href&&window.location.replace(newUrl)}const version=getAnchorParams("version"),versionId=isEmpty(version)?0:parseInt(version,10);versionId&&versionId!==get(changeSet,"version.id")&&cookie("env")&&console.warn("replacing version:",versionId)}return isUserChangeSet?(this.saveIdle(),this.throttleTrigger("change",this),this.collection&&this.collection.throttleTrigger("change",this),changeSet):void 0}getIdentifier(){return this.identifier=this.get("id")||this.route.get("identifier")||this.identifier}getType(){return this.type=this.type||this.target||"orphan"}getHash(){return this.getType()+(isNumber(this.getIdentifier())?this.getIdentifier().toString():this.getIdentifier())}isNew(){return!this.getIdentifier()}url(){let url=this.getIdentifier()?`${this.urlRoot}/${this.getIdentifier()}`:`${this.urlRoot}${this.targetSuffix||""}`;return getUrlParams("version")&&(url+=url.includes("?")?"&":"?",url+="options[version]="+getUrlParams("version")),url}serialize(obj,chain){return serializeUrlParams(obj,chain)}sync(action,data,options){return this.pending=!0,this.trigger("change",this),this.collection&&(this.collection.pending=!0,this.collection.throttleTrigger("change")),this.sent=cloneDeep(this.data),new Promise((resolve,reject)=>__awaiter$2(this,void 0,void 0,function*(){options=options||{};const request={method:action=action||"GET",url:this.url(),headers:clone(this.headers),withCredentials:this.withCredentials};isUndefined(data)||(["GET","DELETE"].includes(action)?isObject(data)&&Object.keys(data).length&&(request.url+=request.url.includes("?")?"&":"?",request.url+=this.serialize(data)):(request.headers["Content-Type"]="application/json",request.data=data)),cookie("env")&&console.log("Prototype:",request),Object.prototype.hasOwnProperty.call(options,"headers")&&"object"==typeof options.headers&&Object.keys(options.headers).forEach(headerKey=>{request.headers[headerKey]=options.headers[headerKey]}),this.xhr=new XHR(request),this.xhr.send().then(response=>{this.status=this.xhr.status,(this.watch||this.autoSave)&&this.watcher();const propagateError=()=>{this.error=!0,this.resetXHRFlags(),this.collection&&(this.collection.pending=!1),this.trigger("error",this),this.trigger("complete",this),this.collection instanceof Collection&&this.collection.throttleTrigger("change")};if(!isObject(response)&&!isArray(response)){const error=new ErrorBase({payload:response,message:`Invalid Payload: ${request.method} ${request.url}`},{});return propagateError(),void reject(error)}this.header.set(this.xhr.getAllResponseHeaders()||{}),this.meta.set(response.meta||{}),this.route.set(response.route||{});const payload=response.payload||response;if(this.error=!1,this.meta.has("success")&&!this.meta.get("success")?this.error=!0:isArray(payload)&&payload.length?this.recv=head(payload):isObject(payload)&&!isArray(payload)?this.recv=payload:(this.meta.has("status")||this.meta.has("success")||(this.error=!0),console.warn(`Invalid Payload: ${request.method} ${request.url}`)),this.error){const error=new ErrorBase({payload,message:`Invalid Payload: ${request.method} ${request.url}`},{});return propagateError(),void reject(error)}const incomingChangeSet=this.completed?cloneDeep(patch(this.recv,this.sent)):{};isEmpty(incomingChangeSet)||(cookie("env")&&console.log("Incoming ChangeSet detected:",cookie("debug_change_set")?JSON.stringify(incomingChangeSet):incomingChangeSet),this.handleChanges(incomingChangeSet));const intermediateData=cloneDeep(this.recv),intermediateChangeSet=cloneDeep(patch(this.data,this.sent));isEmpty(intermediateChangeSet)||(cookie("env")&&console.log("Intermediate ChangeSet detected:",cookie("debug_change_set")?JSON.stringify(intermediateChangeSet):intermediateChangeSet),forEach(intermediateChangeSet,(element,key)=>{set(intermediateData,key,element)})),this.data=cloneDeep(intermediateData),this.changed=!1,this.changedExternal=!1,this.saving=!1,this.handleChanges(),this.patch={},this.resetXHRFlags(),this.completed=!0,this.collection&&(this.collection.pending=!1),this.meta.clearTemp(),this.trigger("success",this),this.trigger("change",this),this.trigger("complete",this),this.collection instanceof Collection&&this.collection.throttleTrigger("change"),resolve(this.data)}).catch(error=>{this.status=500,this.error=!0,this.resetXHRFlags(),console.error(`XHR: ${request.method} ${request.url}`,error),reject(error)})}))}fetch(action,data,options){return new Promise((resolve,reject)=>__awaiter$2(this,void 0,void 0,function*(){this.sync(action,data||this.meta.get("api"),options).then(resolve).catch(error=>__awaiter$2(this,void 0,void 0,function*(){if(this.status=500,this.error=!0,this.resetXHRFlags(),console.error("FETCH:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";Toastify({text:`Unable to Fetch ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)}))}))}save(options){return this.saving=!0,isObject(options=options||{})||(console.warn("invalid options supplied:",options),options={}),has(options,"force")&&options.force?(options.patch=!!has(options,"patch")&&options.patch,this.doSave(options)):this.isNew()||!this.pending&&this.completed&&!isEmpty(this.toPatch())?this.doSave(options):(console.warn(`Blocked attempt to save ${isEmpty(this.toPatch())?"an empty payload":"a duplicate XHR"} to a persisted model.`),new Promise((resolve,_reject)=>{this.saving=!1,resolve(this.data)}))}doSave(options){return isObject(options=options||{})||(console.warn("invalid options supplied:",options),options={}),options.patch=!has(options,"patch")||options.patch,new Promise((resolve,reject)=>__awaiter$2(this,void 0,void 0,function*(){this.sync(this.getIdentifier()?"PUT":"POST",this.toJSON({patch:options.patch})).then(resolve).catch(error=>__awaiter$2(this,void 0,void 0,function*(){if(this.error=!0,this.resetXHRFlags(),console.error("SAVE:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";Toastify({text:`Unable to Save ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)}))}))}saveIdle(){this.autoSaveTimeout&&clearTimeout(this.autoSaveTimeout),this.pending||!this.completed||this.isNew()||isEmpty(this.toPatch())||this.autoSaveHalt&&!this.autoSave||(this.autoSaveTimeout=setTimeout(()=>{this.autoSaveHalt||this.autoSave?this.save().then():this.saveIdle()},this.autoSaveInterval))}throttleSave(){return new Promise((resolve,reject)=>{const request=this.throttle();console.log("throttle request:",request),request.then(data=>{console.log("throttle received:",data),resolve(data)}).catch(reject)})}toJSON(options){isObject(options=options||{})||(options={}),options.patch=options.patch&&!this.isNew();let data=super.toJSON(options);const metaData=this.meta.get("api");return metaData&&(data={meta:metaData,payload:data}),data}buildPath(path){const acc=[];if(!isString(path))return acc;let cur,search;return forEach(path.split("."),link=>{if(link.match(this.bracket.match))for(cur=this.bracket.attr.exec(link),null!==cur?(acc.push(cur[1]),cur=null):cur=!1,search=this.bracket.search.exec(link);null!==search;)!1!==cur&&(cur=parseInt(search[1],10),isNaN(cur)?cur=!1:acc.push(cur)),search=this.bracket.search.exec(link);else acc.push(link)}),acc}get(attr){if("string"==typeof attr&&this.data&&"object"==typeof this.data)return get(this.data,attr)}find(attr,key,value){return"string"==typeof attr&&(attr=this.get(attr)),isArray(attr)?attr.find(obj=>obj[key]===value):attr}set(attr,value){return attr?"object"==typeof attr?(forEach(attr,(v,k)=>this.setAttribute(k,v)),this):(this.setAttribute(attr,value),this):(console.warn("No attr for model.set()!"),this)}setAttribute(attr,value){if("string"!=typeof attr)return console.warn("Malformed attr for model.setAttribute()!"),!1;set(this.data,attr,value),this.throttleTrigger("change",this),this.throttleTrigger(`change:${attr}`,value)}toggle(attribute,item,options){"object"==typeof options&&!isUndefined(options.multiple)&&isUndefined(options.strict)&&(options.strict=!0),options=extend({multiple:!0},isObject(options)?options:{});const request=attribute.split("[].");let target=this.get(request.length>1?request[0]:attribute);return(isUndefined(target)||options.strict&&isArray(target)!==options.multiple)&&(target=options.multiple?[]:null,this.set(request.length>1?request[0]:attribute,target)),isArray(target)?isUndefined(item)?this.set(attribute,null):this.exists(attribute,item)?forEach(target,(element,key)=>{const child=request.length>1&&"object"==typeof element&&request[1]in element?element[request[1]]:element,childId="object"==typeof child&&child.id?child.id:child,itemId="object"==typeof item&&item.id?item.id:item;(childId===itemId||isString(childId)&&isString(itemId)&&0===strcmp(childId,itemId))&&target.splice(key,1)}):target.push(item):"object"==typeof target||"number"==typeof target?this.set(attribute,this.exists(attribute,item)?null:item):isUndefined(item)&&this.set(attribute,!target),this.get(attribute)}pluck(attr){if("string"!=typeof attr||-1===attr.indexOf("[]."))return this.get(attr);const request=attr.split("[].");if(request.length<=1)return;if(!(attr=this.get(request[0]))||!isArray(attr))return;const list=filter(map(attr,element=>get(element,request[1])));return list.length?list:void 0}exists(attribute,item){return item?!("string"!=typeof attribute||!item)&&(attribute=this.pluck(attribute),isArray(attribute)?void 0!==attribute.find(element=>element===item||"object"==typeof element&&element.id&&element.id===item||isEqual(element,item)):attribute===item||"object"==typeof attribute&&attribute.id&&(isEqual(attribute,item)||attribute.id===item)):void 0!==(attribute=this.get(attribute))&&attribute}destroy(){return this.isNew()?new Promise((resolve,_reject)=>{this.throttleTrigger("change"),this.collection&&this.collection.remove(this),resolve(this.data)}):new Promise((_resolve,reject)=>__awaiter$2(this,void 0,void 0,function*(){let deleteData={};isEmpty(this.meta.get("api"))||(deleteData=this.meta.get("api")),this.sync("DELETE",deleteData).then(_data=>{this.error?reject(this.error):(this.throttleTrigger("change"),this.collection&&this.collection.remove(this),_resolve(this.data))}).catch(error=>__awaiter$2(this,void 0,void 0,function*(){if(this.error=!0,this.resetXHRFlags(),console.error("DESTROY:",error),!this.toast)return void reject(error);const errorMessage=this.errorMessage(error),formatMessage=errorMessage?`: ${errorMessage}`:".";Toastify({text:`Unable to Delete ${this.target}${formatMessage}`,duration:12e3,close:!0,stopOnFocus:!0,style:{background:"#E14D45"}}).showToast(),reject(error)}))}))}errorMessage(error){if(error instanceof ErrorBase)return console.error(`[${error.code}] ${error.message}`,error),"Internal"!==error.code?error.message:null;const digest=error.responseText&&isJSON(error.responseText)?JSON.parse(error.responseText):null;if(!digest)return null;const message=get(digest,"meta.status[0].message")||get(digest,"error.exception[0].message")||null;return message?!cookie("env")&&has(digest,"error.exception[0].message")?(console.error("[xhr] server:",message),null):message:null}}exports("Model",Model),Stratus.Services.Model=["$provide",$provide=>{$provide.factory("Model",[()=>Model])}],Stratus.Data.Model=Model;var __awaiter$1=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};let $interpolate,injector=getInjector();const serviceVerify=()=>__awaiter$1(void 0,void 0,void 0,function*(){return new Promise((resolve,_reject)=>__awaiter$1(void 0,void 0,void 0,function*(){$interpolate?resolve(!0):(injector||(injector=getInjector()),injector&&($interpolate=injector.get("$interpolate")),$interpolate?resolve(!0):setTimeout(()=>{cookie("env")&&console.log("wait for $interpolate service:",$interpolate),serviceVerify().then(resolve)},250))}))});class Registry{constructor(){}fetch($element,$scope){return new Promise((resolve,_reject)=>__awaiter$1(this,void 0,void 0,function*(){"string"==typeof $element&&($element={target:$element});const inputs={};forEach(union(ModelOptionKeys,CollectionOptionKeys,["id","api","temp","decouple","fetch"]),option=>set(inputs,option,"data-"+kebabCase(option)));const options=forEach(inputs,(value,key,list)=>{list[key]=$element.attr?$element.attr(value):$element[key],isJSON(list[key])&&(list[key]=JSON.parse(list[key]))});options.api=sanitize(options.api),options.temp=sanitize(options.temp);let completed=0;const verify=()=>{isNumber(completed)&&completed===size(options)&&resolve(this.build(options,$scope))};$interpolate||(yield serviceVerify()),forEach(options,(element,key)=>__awaiter$1(this,void 0,void 0,function*(){if(!element||"string"!=typeof element||!$scope||!$scope.$parent)return completed++,void verify();const interpreter=$interpolate(element,!1,null,!0),initial=interpreter($scope.$parent);if(void 0!==initial)return options[key]=initial,completed++,void verify();let value;cookie("env")&&console.log(`poll (${key}): start`);try{value=yield poll(()=>interpreter($scope.$parent),1500,250)}catch(err){(cookie("env")||"Timeout"!==err.name)&&console.error(err)}cookie("env")&&console.log(`poll (${key}):`,value),options[key]=value,completed++,verify()}))}))}build(options,$scope){let data;if((options.payload||options.convoy)&&(options.fetch=!1),options.target){if(options.target=ucfirst(options.target),options.manifest||options.id){Stratus.Catalog[options.target]||(Stratus.Catalog[options.target]={});const id=options.id||"manifest";if(options.decouple||!Stratus.Catalog[options.target][id]){const modelOptions={stagger:!0};forEach(ModelOptionKeys,element=>{const optionValue=get(options,element);isUndefined(optionValue)||set(modelOptions,element,optionValue)}),data=new Model(modelOptions,{id:options.id}),options.decouple||(Stratus.Catalog[options.target][id]=data)}else Stratus.Catalog[options.target][id]&&(data=Stratus.Catalog[options.target][id])}else{const registry=options.direct?"Compendium":"Catalog";if(Stratus[registry][options.target]||(Stratus[registry][options.target]={}),options.decouple||!Stratus[registry][options.target].collection){const collectionOptions={};forEach(CollectionOptionKeys,element=>{const optionValue=get(options,element);isUndefined(optionValue)||set(collectionOptions,element,optionValue)}),data=new Collection(collectionOptions),options.decouple||(Stratus[registry][options.target].collection=data)}else Stratus[registry][options.target].collection&&(data=Stratus[registry][options.target].collection)}options.api&&data.meta.set("api",isJSON(options.api)?JSON.parse(options.api):options.api),options.temp&&isObject(options.temp)&&!data.completed&&forEach(flatten(options.temp),(v,k)=>{console.log("setting temp:",`api.${k}`,v),data.meta.temp(`api.${k}`,v)}),data instanceof Model&&data.stagger&&"function"==typeof data.initialize&&data.initialize()}return"object"==typeof data&&null!==data&&(void 0!==$scope&&($scope.data=data,data instanceof Model?$scope.model=data:data instanceof Collection&&($scope.collection=data),data instanceof EventManager&&"function"==typeof $scope.$applyAsync&&(data.on("change",()=>{$scope.$applyAsync()}),data.on("error",()=>{$scope.$applyAsync()}),data.completed&&$scope.$applyAsync())),data.pending||data.completed||!isUndefined(options.fetch)&&!options.fetch||data.fetch().then()),data}}exports("Registry",Registry),Stratus.Services.Registry=["$provide",$provide=>{$provide.factory("Registry",[()=>new Registry])}],Stratus.Data.Registry=Registry;const min$1=cookie("env")?"":".min",localPath$1="@stratusjs/angularjs/src/components";Stratus.Components.Base={transclude:{model:"?stratusBaseModel"},bindings:{elementId:"@",ngModel:"=",property:"@",target:"@",id:"@",manifest:"@",decouple:"@",direct:"@",api:"@",urlRoot:"@",limit:"@",options:"<"},controller($scope,$attrs){$scope.uid=safeUniqueId("base"),Stratus.Instances[$scope.uid]=$scope,$scope.elementId=$attrs.elementId||$scope.uid,Stratus.Internals.CssLoader(`${Stratus.BaseUrl+Stratus.BundlePath+localPath$1}/base${min$1}.css`).then(),$scope.initialized=!1,$scope.property=$attrs.property||null,$scope.data=null,$scope.model=null,$scope.collection=null,$attrs.target&&($scope.registry=$scope.registry||new Registry,$scope.registry.fetch($attrs,$scope).then()),$scope.$watch("$ctrl.ngModel",data=>{data instanceof Model&&data!==$scope.model?$scope.model=data:data instanceof Collection&&data!==$scope.collection&&($scope.collection=data)}),$scope.initialize=()=>{$scope.initialized||($scope.model&&($scope.initialized=!0,$scope.model.on("change",()=>{console.log("model changed:",$scope.model.patch)})),$scope.collection&&($scope.initialized=!0,console.log("collection available")))},$scope.$watch("$scope.model.completed",(newVal,oldVal)=>{newVal&&!isEqual(newVal,oldVal)&&$scope.initialize()}),$scope.$watch("$scope.collection.completed",(newVal,oldVal)=>{newVal&&!isEqual(newVal,oldVal)&&$scope.initialize()}),cookie("env")&&console.log("base","component:",$scope,$attrs)},templateUrl:`${Stratus.BaseUrl}${Stratus.DeploymentPath}${localPath$1}/base${min$1}.html`};var __awaiter=function(thisArg,_arguments,P,generator){return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})};Stratus.Modules.ngSanitize=!0,Stratus.Controllers.Generic=["$scope","$element","$log","$sce","$parse","$window","Registry",($scope,$element,$log,$sce,$parse,$window,R)=>__awaiter(void 0,void 0,void 0,function*(){if($scope.uid=safeUniqueId("controller_generic_"),Stratus.Instances[$scope.uid]=$scope,yield R.fetch($element,$scope),$scope.ctrlParent=$scope.$parent,$scope.Stratus=Stratus,$scope._=_,$scope.cookie=cookie,$scope.$window=$window,$scope.getUrlParams=getUrlParams,$scope.setUrlParams=setUrlParams,$scope.$log=$log,$scope.Math=Math,$scope.isArray=isArray,$scope.isDate=isDate,$scope.isDefined=value=>!isUndefined(value),$scope.isElement=isElement,$scope.isFunction=isFunction,$scope.isNumber=isNumber,$scope.isObject=isObject,$scope.isString=isString,$scope.isUndefined=isUndefined,$scope.getHTML=$sce.trustAsHtml,$scope.getURL=$sce.trustAsResourceUrl,$scope.getAnchor=()=>{const url=window.location.href;if(!url||!url.length)return!1;const anchor=url.indexOf("#");return!(anchor<0)&&(!(anchor+1>=url.length)&&url.substring(anchor+1,url.length))},$scope.scrollToAnchor=(anchor,inUrl,delay)=>{if(!anchor||isEmpty(anchor))return $log.warn("anchor id not set!"),!1;if(isUndefined(inUrl)&&(inUrl=!1),inUrl&&anchor!==$scope.getAnchor())return!1;const el=$window.document.getElementById(anchor);return el?delay?setTimeout(()=>{$scope.scrollToAnchor(anchor,inUrl,--delay)},1):(el.scrollIntoView({behavior:"smooth"}),!0):($log.warn(`element not found: ${anchor}`),!1)},$scope.data&&isFunction($scope.data.on)&&$scope.data.on("change",()=>$scope.$applyAsync()),!($scope.collection&&$scope.collection instanceof Collection))return;const selected={id:$element.attr("data-selected"),raw:$element.attr("data-raw")};if(selected.id&&isString(selected.id))if(isJSON(selected.id))selected.id=JSON.parse(selected.id),$scope.$watch("collection.models",models=>{$scope.selected||$scope.selectedInit||forEach(models,model=>{selected.id===model.getIdentifier()&&($scope.selected=selected.raw?model.data:model,$scope.selectedInit=!0)})});else{if(selected.model=$parse(selected.id),selected.value=selected.model($scope.$parent),!isArray(selected.value))return;if(selected.value=selected.value.filter(n=>n),selected.value.length)return;$scope.selected=head(selected.value)}})];const min=cookie("env")?"":".min",localPath="@stratusjs/angularjs/src/directives";Stratus.Directives.Base=function(){return{restrict:"A",scope:{ngModel:"="},link:($scope,$element,$attrs)=>{$scope.uid=safeUniqueId("base"),Stratus.Instances[$scope.uid]=$scope,$scope.elementId=$element.elementId||$scope.uid,Stratus.Internals.CssLoader(Stratus.BaseUrl+Stratus.BundlePath+localPath+"base"+min+".css").then(),$scope.initialized=!1,console.log("directive:",this,$scope,$element,$attrs)},templateUrl:Stratus.BaseUrl+Stratus.BundlePath+localPath+"base"+min+".html"}}}}});