@medplum/fhir-router 5.1.36 → 5.1.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var ma=Object.create;var Vt=Object.defineProperty;var ha=Object.getOwnPropertyDescriptor;var ya=Object.getOwnPropertyNames;var Ta=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Ea=(t,e,r)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Eo=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})},Io=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ya(e))!ga.call(t,i)&&i!==r&&Vt(t,i,{get:()=>e[i],enumerable:!(n=ha(e,i))||n.enumerable});return t};var No=(t,e,r)=>(r=t!=null?ma(Ta(t)):{},Io(e||!t||!t.__esModule?Vt(r,"default",{value:t,enumerable:!0}):r,t)),Ia=t=>Io(Vt({},"__esModule",{value:!0}),t);var $=(t,e,r)=>Ea(t,typeof e!="symbol"?e+"":e,r);var Ul={};Eo(Ul,{BatchProcessor:()=>$t,FhirRepository:()=>mn,FhirRouter:()=>ho,MAX_QUERY_STRING_LENGTH:()=>mo,MemoryRepository:()=>no,RepositoryMode:()=>fr,Router:()=>hr,buildBatchResponseBundle:()=>vo,createResourceImpl:()=>la,getExtraEntries:()=>ro,getSearchIncludeEntries:()=>Js,getSearchRevIncludeEntries:()=>Xs,makeSimpleRequest:()=>Vl,processBatch:()=>Tr,updateResourceImpl:()=>fa});module.exports=Ia(Ul);var R=require("@medplum/core");var Na=50,ba=8,va=/urn(:|%3A)uuid(:|%3A)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;async function Tr(t,e,r,n){return new $t(r,e,n,t).run()}var $t=class t{constructor(e,r,n,i){$(this,"router");$(this,"repo");$(this,"bundle");$(this,"req");$(this,"resolvedIdentities");$(this,"bundleInfo");$(this,"state");this.router=e,this.repo=r,this.bundle=n,this.req=i,this.resolvedIdentities=Object.create(null),this.state={position:0,resultEntries:new Array(n.entry?.length??0),pendingIndices:[],errors:[]}}static fromState(e,r,n,i,o){let s=new t(e,r,i.bundle,n);return s.resolvedIdentities=i.resolvedIdentities,s.bundleInfo={...i.bundleInfo},s.state.position=o,s}async run(){await this.preprocess();let e=this.bundleInfo;if(!this.isTransaction())return this.processEntriesAndBuild();let r=bo(this.state);return this.repo.withTransaction(n=>this.withRepo(n,()=>(this.state=bo(r),this.processEntriesAndBuild())),{serializable:e.requiresStrongTransaction,resourceTypes:e.resourceTypes})}async preprocess(){let e=this.bundle.type;if(e!=="batch"&&e!=="transaction")throw new R.OperationOutcomeError((0,R.badRequest)("Unrecognized bundle type: "+e));if(this.bundleInfo=await this.preprocessBundle(),this.isTransaction()){if(this.bundleInfo.updates>Na)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction contains more update operations than allowed"));if(this.bundleInfo.requiresStrongTransaction&&this.state.resultEntries.length>ba)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction requires strict isolation but has too many entries"))}let r=Object.create(null);for(let n=0;n<this.state.resultEntries.length;n++)this.state.resultEntries[n]&&(r[n]=this.state.resultEntries[n]);return{bundle:this.bundle,bundleInfo:{ordering:this.bundleInfo.ordering,resourceTypes:this.bundleInfo.resourceTypes,requiresStrongTransaction:this.bundleInfo.requiresStrongTransaction,updates:this.bundleInfo.updates},resolvedIdentities:this.resolvedIdentities,preprocessResults:r}}hasMoreEntries(){return this.bundleInfo!==void 0&&this.state.position<this.bundleInfo.ordering.length}getPosition(){return this.state.position}takePendingResults(){if(this.state.pendingIndices.length===0)return;let e=Object.create(null);for(let r of this.state.pendingIndices)e[r]=this.state.resultEntries[r];return this.state.pendingIndices=[],e}async processEntriesAndBuild(){for(this.dispatchPreEvent();this.hasMoreEntries();)await this.processNextEntryImpl();return this.dispatchPostEvent(),this.buildResultBundle()}dispatchPreEvent(){let e={type:"batch",bundleType:this.bundle.type,count:this.bundle.entry?.length,size:JSON.stringify(this.bundle).length};this.router.dispatchEvent(e)}dispatchPostEvent(){let e={type:"batch",bundleType:this.bundle.type,errors:this.state.errors.length?this.state.errors:void 0};this.router.dispatchEvent(e)}buildResultBundle(){return{resourceType:"Bundle",type:`${this.bundle.type}-response`,entry:this.state.resultEntries}}async withRepo(e,r){let n=this.repo;this.repo=e;try{return await r()}finally{this.repo=n}}async preprocessBundle(){let e=this.bundle.entry;if(!e?.length)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entries"));let r={transaction:[],batch:[],delete:[],create:[],update:[],patch:[],operation:[],"search-system":[],"search-type":[],read:[],vread:[],"history-system":[],"history-type":[],"history-instance":[]},n=new Set,i=new Set,o=!1,s=0;for(let c=0;c<e.length;c++){let u=e[c];if(!u.request?.method){this.state.resultEntries[c]=Ut((0,R.badRequest)("Missing Bundle entry request method",`Bundle.entry[${c}].request.method`));continue}let f=await this.preprocessEntry(u,c,n);if(f){if(!this.isTransaction()){this.state.resultEntries[c]=Ut(f);continue}throw new R.OperationOutcomeError(f)}let m=this.getRouteForEntry(u),g=m?.data?.interaction;if(!g||!r[g])throw new R.OperationOutcomeError((0,R.badRequest)(`Invalid REST interaction in batch: ${u.request?.method} ${u.request?.url}`));let y=m?.params?.resourceType;y&&i.add(y),g==="create"&&u.request?.ifNoneExist?o=!0:g==="update"?(u.request?.url.includes("?")&&(o=!0),s++):g==="delete"&&u.request?.url.includes("?")&&(o=!0),r[g].push(c)}let a=[];for(let c of Object.values(r))a.push(...c);return{ordering:a,requiresStrongTransaction:o,updates:s,resourceTypes:i}}async preprocessEntry(e,r,n){if(!e.request?.url)return(0,R.badRequest)("Missing Bundle entry request URL",`Bundle.entry[${r}].request.url`);let i;try{i=await this.resolveIdentity(e,`Bundle.entry[${r}]`)}catch(o){if(o instanceof R.OperationOutcomeError)return o.outcome;throw o}if(i&&(this.resolvedIdentities[i.placeholder]=i.reference,this.isTransaction())){if(n.has(i.reference))throw new R.OperationOutcomeError((0,R.badRequest)("Duplicate resource identity found in Bundle"));n.add(i.reference)}}async resolveIdentity(e,r){let i=this.getRouteForEntry(e)?.data?.interaction;if(!i)throw new R.OperationOutcomeError(R.notFound);switch(i){case"create":return this.resolveCreateIdentity(e);case"delete":case"update":case"patch":return this.resolveModificationIdentity(e,r);default:return}}getRouteForEntry(e){return this.router.find(e.request?.method,e.request?.url??"")}async resolveCreateIdentity(e){let r=e.fullUrl??"";if(e.request?.ifNoneExist){let n=await this.repo.searchResources((0,R.parseSearchRequest)(e.request.url+"?"+e.request.ifNoneExist));if(n.length===1)return{placeholder:r,reference:(0,R.getReferenceString)(n[0])}}if(e.resource)return e.resource.id=this.repo.generateId(),{placeholder:r,reference:(0,R.getReferenceString)(e.resource)}}async resolveModificationIdentity(e,r){let n=e.fullUrl??"";if(e.request?.url?.includes("?")){let i=e.request.method,o=(0,R.parseSearchRequest)(e.request.url);o.count=2,o.offset=0,o.sortRules=void 0;let[s,a]=await this.repo.searchResources(o);if(!s)switch(i){case"DELETE":return;case"PUT":if(e.resource){if(e.resource.id)throw new R.OperationOutcomeError((0,R.badRequest)("Cannot provide ID for create by update"));return e.resource.id=this.repo.generateId(),{placeholder:n,reference:(0,R.getReferenceString)(e.resource)}}return;default:throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} did not match any resources`,r+".request.url"))}if(a)throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} matched multiple resources`,r+".request.url"));let c=(0,R.getReferenceString)(s);return e.request.url=c,e.resource&&(e.resource.id=s.id),{placeholder:n,reference:c}}if(e.request?.url.includes("/"))return{placeholder:n,reference:e.request.url}}async processNextEntry(){if(this.isTransaction())throw new Error("Re-entrant batch processing does not support transaction semantics");await this.processNextEntryImpl()}async processNextEntryImpl(){let e=this.bundleInfo;if(!e)throw new Error("processNextEntry called before preprocess()/fromState()");let r=this.bundle.entry;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entry"));if(this.state.position>=e.ordering.length)return;let n=this.state.position,i=e.ordering[n],o=r[i],s=this.rewriteIdsInObject(o);try{this.setResult(i,await this.processBatchEntry(s)),this.state.position=n+1}catch(a){if(this.isTransaction())throw a;if(this.state.errors.push(a.message),a instanceof R.OperationOutcomeError&&(0,R.getStatus)(a.outcome)===429){for(let c=n;c<e.ordering.length;c++)this.setResult(e.ordering[c],Ut(a.outcome));this.state.position=e.ordering.length;return}this.setResult(i,Ut((0,R.normalizeOperationOutcome)(a))),this.state.position=n+1}}setResult(e,r){this.state.resultEntries[e]=r,this.state.pendingIndices.push(e)}async processBatchEntry(e){let r=this.getRouteForEntry(e);if(!r)throw new R.OperationOutcomeError(R.notFound);let n=this.parseBatchRequest(e,r),[i,o]=await r.handler(n,this.repo,this.router,{batch:!0});if(!(0,R.isOk)(i)&&this.isTransaction())throw new R.OperationOutcomeError(i);return Ut(i,o)}parseBatchRequest(e,r){let n=e.request,i=Object.create(null);n.ifNoneExist&&(i["if-none-exist"]=n.ifNoneExist),n.ifMatch&&(i["if-match"]=n.ifMatch),n.ifNoneMatch&&(i["if-none-match"]=n.ifNoneMatch),n.ifModifiedSince&&(i["if-modified-since"]=n.ifModifiedSince);let o;return n.method==="PATCH"?o=this.parsePatchBody(e):o=e.resource,{method:n.method,url:r?.query?n.url.slice(0,n.url.indexOf("?")):n.url,pathname:"",params:r?.params??Object.create(null),query:r?.query??Object.create(null),body:o,headers:i,config:this.req.config}}parsePatchBody(e){let r=e.resource,n;if(r?.resourceType==="Binary"){if(!r.data)throw new R.OperationOutcomeError((0,R.badRequest)("Missing entry.resource.data"));n=JSON.parse(Buffer.from(r.data,"base64").toString("utf8"))}else if(r?.resourceType==="Parameters"){if(Ra(r))return this.rewriteIds(r);if(r.parameter){n=[];for(let i of r.parameter)if(i.name==="operation"){let o=this.parsePatchParameter(i);n.push(o)}}}else throw new R.OperationOutcomeError((0,R.badRequest)("Patch entry must include a Binary or Parameters resource"));if(!Array.isArray(n))throw new R.OperationOutcomeError((0,R.badRequest)("Decoded PATCH body must be an array"));return this.rewriteIdsInArray(n)}parsePatchParameter(e){let r=e.part?.find(i=>i.name==="op")?.valueCode;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("PATCH Parameters missing op"));let n={op:r};switch(r){case"add":case"replace":case"test":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="value"&&(n.value=JSON.parse(i.valueString??""));break;case"copy":case"move":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="from"&&(n.from=i.valueString);break;case"remove":n.path=e.part?.find(i=>i.name==="path")?.valueString;break}return n}rewriteIds(e){return Array.isArray(e)?this.rewriteIdsInArray(e):typeof e=="string"?this.rewriteIdsInString(e):typeof e=="object"&&e!==null?this.rewriteIdsInObject(e):e}rewriteIdsInArray(e){return e.map(r=>this.rewriteIds(r))}rewriteIdsInObject(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,this.rewriteIds(n)]))}rewriteIdsInString(e){let r=va.exec(e)?.[0];if(!r)return e;let n=r.replaceAll("%3A",":"),i=this.resolvedIdentities[n];return i?e.replaceAll(r,i):e}isTransaction(){return this.bundle.type==="transaction"&&!!this.req.config?.transactions}};function Ra(t){return!!t.parameter?.some(e=>e.name==="operation"&&e.part?.some(r=>r.name==="type"))}function Ut(t,e){return{response:{outcome:t,status:(0,R.getStatus)(t).toString(),location:(0,R.isOk)(t)&&e?.id?(0,R.getReferenceString)(e):void 0},resource:e}}function vo(t,e,r){let n=new Array(e);for(let i=0;i<e;i++)n[i]=r[i];return{resourceType:"Bundle",type:`${t}-response`,entry:n}}function bo(t){return{position:t.position,resultEntries:t.resultEntries.slice(),pendingIndices:t.pendingIndices.slice(),errors:t.errors.slice()}}var O=require("@medplum/core");var M=require("@medplum/core"),ca=No(require("dataloader"),1);function E(t){return gr(t,[])}function gr(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return Sa(t,e);default:return String(t)}}function Sa(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(xa(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:gr(n,r)}else if(Array.isArray(t))return wa(t,r);return Oa(t,r)}function xa(t){return typeof t.toJSON=="function"}function Oa(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+_a(t)+"]":"{ "+r.map(([i,o])=>i+": "+gr(o,e)).join(", ")+" }"}function wa(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let o=0;o<r;++o)i.push(gr(t[o],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}function _a(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}function Da(t,e){return t?.__kind===e}var ne=Da;function we(t){return t instanceof Promise}function de(t){return typeof t?.then=="function"}function Er(t){return t instanceof Error?t:new En(t)}var En=class extends Error{constructor(e){super("Unexpected error value: "+E(e)),this.name="NonErrorThrown",this.thrownValue=e}};function H(t){return typeof t=="object"&&t!==null}function L(t,e){if(!t)throw new Error(e??"Unexpected invariant triggered.")}var La=/\r\n|[\n\r]/g;function Nt(t,e){let r=0,n=1;for(let i of t.body.matchAll(La)){if(typeof i.index!="number"&&L(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}function In(t){return Ir(t.source,Nt(t.source,t.start))}function Ir(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?r:0,c=e.column+a,u=`${t.name}:${s}:${c}
1
+ "use strict";var ma=Object.create;var Vt=Object.defineProperty;var ha=Object.getOwnPropertyDescriptor;var ya=Object.getOwnPropertyNames;var Ta=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Ea=(t,e,r)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Eo=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})},Io=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ya(e))!ga.call(t,i)&&i!==r&&Vt(t,i,{get:()=>e[i],enumerable:!(n=ha(e,i))||n.enumerable});return t};var No=(t,e,r)=>(r=t!=null?ma(Ta(t)):{},Io(e||!t||!t.__esModule?Vt(r,"default",{value:t,enumerable:!0}):r,t)),Ia=t=>Io(Vt({},"__esModule",{value:!0}),t);var $=(t,e,r)=>Ea(t,typeof e!="symbol"?e+"":e,r);var Ul={};Eo(Ul,{BatchProcessor:()=>$t,FhirRepository:()=>mn,FhirRouter:()=>ho,MAX_QUERY_STRING_LENGTH:()=>mo,MemoryRepository:()=>no,RepositoryMode:()=>fr,Router:()=>hr,buildBatchResponseBundle:()=>vo,createResourceImpl:()=>la,getExtraEntries:()=>ro,getSearchIncludeEntries:()=>Js,getSearchRevIncludeEntries:()=>Xs,makeSimpleRequest:()=>Vl,processBatch:()=>Tr,updateResourceImpl:()=>fa});module.exports=Ia(Ul);var R=require("@medplum/core");var Na=50,ba=8,va=/urn(:|%3A)uuid(:|%3A)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;async function Tr(t,e,r,n){return new $t(r,e,n,t).run()}var $t=class t{constructor(e,r,n,i){$(this,"router");$(this,"repo");$(this,"bundle");$(this,"req");$(this,"resolvedIdentities");$(this,"bundleInfo");$(this,"state");this.router=e,this.repo=r,this.bundle=n,this.req=i,this.resolvedIdentities=Object.create(null),this.state={position:0,resultEntries:new Array(n.entry?.length??0),pendingIndices:[],errors:[]}}static fromState(e,r,n,i,o){let s=new t(e,r,i.bundle,n);return s.resolvedIdentities=i.resolvedIdentities,s.bundleInfo={...i.bundleInfo},s.state.position=o,s}async run(){await this.preprocess();let e=this.bundleInfo;if(!this.isTransaction()){let i=await this.processEntriesAndBuild();return this.dispatchPostEvent(),i}let r=bo(this.state),n=await this.repo.withTransaction(i=>this.withRepo(i,()=>(this.state=bo(r),this.processEntriesAndBuild())),{serializable:e.requiresStrongTransaction,resourceTypes:e.resourceTypes});return this.dispatchPostEvent(),n}async preprocess(){let e=this.bundle.type;if(e!=="batch"&&e!=="transaction")throw new R.OperationOutcomeError((0,R.badRequest)("Unrecognized bundle type: "+e));if(this.bundleInfo=await this.preprocessBundle(),this.isTransaction()){if(this.bundleInfo.updates>Na)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction contains more update operations than allowed"));if(this.bundleInfo.requiresStrongTransaction&&this.state.resultEntries.length>ba)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction requires strict isolation but has too many entries"))}this.dispatchPreEvent();let r=Object.create(null);for(let n=0;n<this.state.resultEntries.length;n++)this.state.resultEntries[n]&&(r[n]=this.state.resultEntries[n]);return{bundle:this.bundle,bundleInfo:{ordering:this.bundleInfo.ordering,resourceTypes:this.bundleInfo.resourceTypes,requiresStrongTransaction:this.bundleInfo.requiresStrongTransaction,updates:this.bundleInfo.updates},resolvedIdentities:this.resolvedIdentities,preprocessResults:r}}hasMoreEntries(){return this.bundleInfo!==void 0&&this.state.position<this.bundleInfo.ordering.length}getPosition(){return this.state.position}takePendingResults(){if(this.state.pendingIndices.length===0)return;let e=Object.create(null);for(let r of this.state.pendingIndices)e[r]=this.state.resultEntries[r];return this.state.pendingIndices=[],e}async processEntriesAndBuild(){for(;this.hasMoreEntries();)await this.processNextEntryImpl();return this.buildResultBundle()}dispatchPreEvent(){let e={type:"batch",bundleType:this.bundle.type,count:this.bundle.entry?.length,size:JSON.stringify(this.bundle).length};this.router.dispatchEvent(e)}dispatchPostEvent(){let e={type:"batch",bundleType:this.bundle.type,errors:this.state.errors.length?this.state.errors:void 0};this.router.dispatchEvent(e)}buildResultBundle(){return{resourceType:"Bundle",type:`${this.bundle.type}-response`,entry:this.state.resultEntries}}async withRepo(e,r){let n=this.repo;this.repo=e;try{return await r()}finally{this.repo=n}}async preprocessBundle(){let e=this.bundle.entry;if(!e?.length)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entries"));let r={transaction:[],batch:[],delete:[],create:[],update:[],patch:[],operation:[],"search-system":[],"search-type":[],read:[],vread:[],"history-system":[],"history-type":[],"history-instance":[]},n=new Set,i=new Set,o=!1,s=0;for(let c=0;c<e.length;c++){let u=e[c];if(!u.request?.method){this.state.resultEntries[c]=Ut((0,R.badRequest)("Missing Bundle entry request method",`Bundle.entry[${c}].request.method`));continue}let f=await this.preprocessEntry(u,c,n);if(f){if(!this.isTransaction()){this.state.resultEntries[c]=Ut(f);continue}throw new R.OperationOutcomeError(f)}let m=this.getRouteForEntry(u),g=m?.data?.interaction;if(!g||!r[g])throw new R.OperationOutcomeError((0,R.badRequest)(`Invalid REST interaction in batch: ${u.request?.method} ${u.request?.url}`));let y=m?.params?.resourceType;y&&i.add(y),g==="create"&&u.request?.ifNoneExist?o=!0:g==="update"?(u.request?.url.includes("?")&&(o=!0),s++):g==="delete"&&u.request?.url.includes("?")&&(o=!0),r[g].push(c)}let a=[];for(let c of Object.values(r))a.push(...c);return{ordering:a,requiresStrongTransaction:o,updates:s,resourceTypes:i}}async preprocessEntry(e,r,n){if(!e.request?.url)return(0,R.badRequest)("Missing Bundle entry request URL",`Bundle.entry[${r}].request.url`);let i;try{i=await this.resolveIdentity(e,`Bundle.entry[${r}]`)}catch(o){if(o instanceof R.OperationOutcomeError)return o.outcome;throw o}if(i&&(this.resolvedIdentities[i.placeholder]=i.reference,this.isTransaction())){if(n.has(i.reference))throw new R.OperationOutcomeError((0,R.badRequest)("Duplicate resource identity found in Bundle"));n.add(i.reference)}}async resolveIdentity(e,r){let i=this.getRouteForEntry(e)?.data?.interaction;if(!i)throw new R.OperationOutcomeError(R.notFound);switch(i){case"create":return this.resolveCreateIdentity(e);case"delete":case"update":case"patch":return this.resolveModificationIdentity(e,r);default:return}}getRouteForEntry(e){return this.router.find(e.request?.method,e.request?.url??"")}async resolveCreateIdentity(e){let r=e.fullUrl??"";if(e.request?.ifNoneExist){let n=await this.repo.searchResources((0,R.parseSearchRequest)(e.request.url+"?"+e.request.ifNoneExist));if(n.length===1)return{placeholder:r,reference:(0,R.getReferenceString)(n[0])}}if(e.resource)return e.resource.id=this.repo.generateId(),{placeholder:r,reference:(0,R.getReferenceString)(e.resource)}}async resolveModificationIdentity(e,r){let n=e.fullUrl??"";if(e.request?.url?.includes("?")){let i=e.request.method,o=(0,R.parseSearchRequest)(e.request.url);o.count=2,o.offset=0,o.sortRules=void 0;let[s,a]=await this.repo.searchResources(o);if(!s)switch(i){case"DELETE":return;case"PUT":if(e.resource){if(e.resource.id)throw new R.OperationOutcomeError((0,R.badRequest)("Cannot provide ID for create by update"));return e.resource.id=this.repo.generateId(),{placeholder:n,reference:(0,R.getReferenceString)(e.resource)}}return;default:throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} did not match any resources`,r+".request.url"))}if(a)throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} matched multiple resources`,r+".request.url"));let c=(0,R.getReferenceString)(s);return e.request.url=c,e.resource&&(e.resource.id=s.id),{placeholder:n,reference:c}}if(e.request?.url.includes("/"))return{placeholder:n,reference:e.request.url}}async processNextEntry(){if(this.isTransaction())throw new Error("Re-entrant batch processing does not support transaction semantics");await this.processNextEntryImpl()}async processNextEntryImpl(){let e=this.bundleInfo;if(!e)throw new Error("processNextEntry called before preprocess()/fromState()");let r=this.bundle.entry;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entry"));if(this.state.position>=e.ordering.length)return;let n=this.state.position,i=e.ordering[n],o=r[i],s=this.rewriteIdsInObject(o);try{this.setResult(i,await this.processBatchEntry(s)),this.state.position=n+1}catch(a){if(this.isTransaction())throw a;if(this.state.errors.push(a.message),a instanceof R.OperationOutcomeError&&(0,R.getStatus)(a.outcome)===429){for(let c=n;c<e.ordering.length;c++)this.setResult(e.ordering[c],Ut(a.outcome));this.state.position=e.ordering.length;return}this.setResult(i,Ut((0,R.normalizeOperationOutcome)(a))),this.state.position=n+1}}setResult(e,r){this.state.resultEntries[e]=r,this.state.pendingIndices.push(e)}async processBatchEntry(e){let r=this.getRouteForEntry(e);if(!r)throw new R.OperationOutcomeError(R.notFound);let n=this.parseBatchRequest(e,r),[i,o]=await r.handler(n,this.repo,this.router,{batch:!0});if(!(0,R.isOk)(i)&&this.isTransaction())throw new R.OperationOutcomeError(i);return Ut(i,o)}parseBatchRequest(e,r){let n=e.request,i=Object.create(null);n.ifNoneExist&&(i["if-none-exist"]=n.ifNoneExist),n.ifMatch&&(i["if-match"]=n.ifMatch),n.ifNoneMatch&&(i["if-none-match"]=n.ifNoneMatch),n.ifModifiedSince&&(i["if-modified-since"]=n.ifModifiedSince);let o;return n.method==="PATCH"?o=this.parsePatchBody(e):o=e.resource,{method:n.method,url:r?.query?n.url.slice(0,n.url.indexOf("?")):n.url,pathname:"",params:r?.params??Object.create(null),query:r?.query??Object.create(null),body:o,headers:i,config:this.req.config}}parsePatchBody(e){let r=e.resource,n;if(r?.resourceType==="Binary"){if(!r.data)throw new R.OperationOutcomeError((0,R.badRequest)("Missing entry.resource.data"));n=JSON.parse(Buffer.from(r.data,"base64").toString("utf8"))}else if(r?.resourceType==="Parameters"){if(Ra(r))return this.rewriteIds(r);if(r.parameter){n=[];for(let i of r.parameter)if(i.name==="operation"){let o=this.parsePatchParameter(i);n.push(o)}}}else throw new R.OperationOutcomeError((0,R.badRequest)("Patch entry must include a Binary or Parameters resource"));if(!Array.isArray(n))throw new R.OperationOutcomeError((0,R.badRequest)("Decoded PATCH body must be an array"));return this.rewriteIdsInArray(n)}parsePatchParameter(e){let r=e.part?.find(i=>i.name==="op")?.valueCode;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("PATCH Parameters missing op"));let n={op:r};switch(r){case"add":case"replace":case"test":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="value"&&(n.value=JSON.parse(i.valueString??""));break;case"copy":case"move":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="from"&&(n.from=i.valueString);break;case"remove":n.path=e.part?.find(i=>i.name==="path")?.valueString;break}return n}rewriteIds(e){return Array.isArray(e)?this.rewriteIdsInArray(e):typeof e=="string"?this.rewriteIdsInString(e):typeof e=="object"&&e!==null?this.rewriteIdsInObject(e):e}rewriteIdsInArray(e){return e.map(r=>this.rewriteIds(r))}rewriteIdsInObject(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,this.rewriteIds(n)]))}rewriteIdsInString(e){let r=va.exec(e)?.[0];if(!r)return e;let n=r.replaceAll("%3A",":"),i=this.resolvedIdentities[n];return i?e.replaceAll(r,i):e}isTransaction(){return this.bundle.type==="transaction"&&!!this.req.config?.transactions}};function Ra(t){return!!t.parameter?.some(e=>e.name==="operation"&&e.part?.some(r=>r.name==="type"))}function Ut(t,e){return{response:{outcome:t,status:(0,R.getStatus)(t).toString(),location:(0,R.isOk)(t)&&e?.id?(0,R.getReferenceString)(e):void 0},resource:e}}function vo(t,e,r){let n=new Array(e);for(let i=0;i<e;i++)n[i]=r[i];return{resourceType:"Bundle",type:`${t}-response`,entry:n}}function bo(t){return{position:t.position,resultEntries:t.resultEntries.slice(),pendingIndices:t.pendingIndices.slice(),errors:t.errors.slice()}}var O=require("@medplum/core");var M=require("@medplum/core"),ca=No(require("dataloader"),1);function E(t){return gr(t,[])}function gr(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return Sa(t,e);default:return String(t)}}function Sa(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(xa(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:gr(n,r)}else if(Array.isArray(t))return wa(t,r);return Oa(t,r)}function xa(t){return typeof t.toJSON=="function"}function Oa(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+_a(t)+"]":"{ "+r.map(([i,o])=>i+": "+gr(o,e)).join(", ")+" }"}function wa(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let o=0;o<r;++o)i.push(gr(t[o],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}function _a(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}function Da(t,e){return t?.__kind===e}var ne=Da;function we(t){return t instanceof Promise}function de(t){return typeof t?.then=="function"}function Er(t){return t instanceof Error?t:new En(t)}var En=class extends Error{constructor(e){super("Unexpected error value: "+E(e)),this.name="NonErrorThrown",this.thrownValue=e}};function H(t){return typeof t=="object"&&t!==null}function L(t,e){if(!t)throw new Error(e??"Unexpected invariant triggered.")}var La=/\r\n|[\n\r]/g;function Nt(t,e){let r=0,n=1;for(let i of t.body.matchAll(La)){if(typeof i.index!="number"&&L(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}function In(t){return Ir(t.source,Nt(t.source,t.start))}function Ir(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?r:0,c=e.column+a,u=`${t.name}:${s}:${c}
2
2
  `,l=n.split(/\r\n|[\n\r]/g),f=l[i];if(f.length>120){let m=Math.floor(c/80),g=c%80,y=[];for(let x=0;x<f.length;x+=80)y.push(f.slice(x,x+80));return u+Ro([[`${s} |`,y[0]],...y.slice(1,m+1).map(x=>["|",x]),["|","^".padStart(g)],["|",y[m+1]]])}return u+Ro([[`${s-1} |`,l[i-1]],[`${s} |`,f],["|","^".padStart(c)],[`${s+1} |`,l[i+1]]])}function Ro(t){let e=t.filter(([n,i])=>i!==void 0),r=Math.max(...e.map(([n])=>n.length));return e.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
3
3
  `)}var d=class t extends Error{constructor(e,r={}){let{nodes:n,source:i,positions:o,path:s,originalError:a,cause:c,extensions:u}=r,l="cause"in r,f=l?c:a,m=l||a!=null?{cause:f}:void 0;super(e,m),this.name="GraphQLError",this.path=s??void 0;let g=a??(c instanceof Error?c:void 0);this.originalError=g,this.nodes=So(Array.isArray(n)?n:n?[n]:void 0);let y=So(this.nodes?.map(S=>S.loc).filter(S=>S!=null));this.source=i??y?.[0]?.source,this.positions=o??y?.map(S=>S.start),this.locations=o&&i?o.map(S=>Nt(i,S)):y?.map(S=>Nt(S.source,S.start));let x=H(g?.extensions)?g.extensions:void 0;this.extensions=u??x??Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),a?.stack!=null?Object.defineProperty(this,"stack",{value:a.stack,writable:!0,configurable:!0}):Error.captureStackTrace!=null?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(e+=`
4
4