exlo 0.0.22 → 0.0.24

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.
@@ -28,7 +28,7 @@ import{SNS as Te}from"@aws-sdk/client-sns";var a=class s extends Error{Code;Send
28
28
  <RequestId>${s}</RequestId>
29
29
  </ResponseMetadata>
30
30
  </PublishBatchResponse>`};function I(s){if(typeof s!="string")return null;let e=s.split(":");if(e.length<6||e[0]!=="arn")return null;let[t,i,r,n,o,...l]=e;if(!["aws","aws-cn","aws-us-gov"].includes(i))return null;let p=l.join(":"),f,g;return p.indexOf("/")!==-1?[f,g]=p.split("/"):p.indexOf(":")!==-1?[f,g]=p.split(":"):g=p,{partition:i,service:r,region:n,accountId:o,resourceType:f,resourceId:g}}function x(s){return s?s.service=="sqs"&&!s.resourceType:!1}function z(s){return s?s.service=="lambda"&&s.resourceType=="function":!1}function $(s){if(typeof s?.SubscriptionArn!="string")throw new u("Invalid parameter: SubscriptionArn Reason: An ARN must be a string");let e=s.SubscriptionArn.split(":");if(e<6)throw new u(`Invalid parameter: SubscriptionArn Reason: An ARN must have at least 6 elements, not ${e}`);let t=I(s.SubscriptionArn);if(t?.service!="sns"||!t.resourceType||!t.resourceId)throw new u("Invalid parameter: SubscriptionId");let i=s.SubscriptionArn;return{topicArn:i.slice(0,i.indexOf(`:${t.resourceId}`)),topicName:t.resourceType,subscriptionId:t.resourceId,SubscriptionArn:i}}import{randomUUID as k}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";function ne(s,e){if(typeof e!="number")return!1;for(let t=0;t<s.length;t+=2){let i=s[t],r=s[t+1];if(!re(e,i,r))return!1}return!0}function re(s,e,t){switch(e){case"=":return s===t;case">":return s>t;case">=":return s>=t;case"<":return s<t;case"<=":return s<=t;default:return!1}}function G(s){return s.split(".").map(Number).reduce((e,t)=>(e<<8)+t,0)>>>0}function oe(s,e){let[t,i]=s.split("/"),r=G(e),n=G(t),o=~(2**(32-Number(i))-1)>>>0;return(r&o)===(n&o)}function R(s,e){if(s&&typeof s=="object"&&!Array.isArray(s)){if(s["anything-but"])return Array.isArray(s["anything-but"])?s["anything-but"].indexOf(e)==-1:!R(s["anything-but"],e);if(s["equals-ignore-case"])return typeof e=="string"&&e.toLowerCase()==s["equals-ignore-case"].toLowerCase();if(s.cidr)return typeof e!="string"?!1:oe(s.cidr,e);if(s.prefix)return typeof e=="string"&&e.startsWith(s.prefix);if(s.suffix)return typeof e=="string"&&e.endsWith(s.suffix);if(s.exists!==void 0)return s.exists?e!==void 0:e===void 0;if(s.numeric)return ne(s.numeric,e);if(s.$or)return s.$or.some(t=>A(t,e))}if(Array.isArray(s))if(Array.isArray(e)){if(!e.length){let t=s[0];if(m(t)&&"exists"in t)return!!t.exists}return s.some(t=>e.some(i=>R(t,i)))}else return s.some(t=>R(t,e));return e===s}function A(s,e){let t=[];for(let[i,r]of Object.entries(s)){if(Array.isArray(r)){if(i=="$or"){if(!r.some(o=>A(o,e)))return!1;t.push(!0)}else{if(!R(r,e?.[i]))return!1;t.push(!0)}continue}t.push(A(r,e?.[i]))}return!t.some(i=>!i)}var d=class extends u{constructor(e){super(`Invalid parameter: FilterPolicy: ${e}`),this.name="SnsFilterPolicyError"}},J=["<",">","<=",">="],ae=["exists","numeric","anything-but","equals-ignore-case","prefix","suffix","cidr"],ce=/^(?:(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\/(?:3[0-2]|[12]?[0-9])$/;function ue(s){if(typeof s!="boolean")throw new d("exists match pattern must be either true or false")}function le(s){if(typeof s!="string")throw new d("equals-ignore-case match pattern must be a string")}function _(s){if(typeof s!="string")throw new d("prefix match pattern must be a string");if(!s)throw new d("Null prefix not allowed")}function pe(s){if(typeof s!="string")throw new d("suffix match pattern must be a string");if(!s)throw new d("Null suffix not allowed")}function de(s){if(typeof s=="boolean"||s===null)throw new d("Value of anything-but must be an array or single string/number value");if(m(s)){let e=Object.keys(s);if(!e.length)throw new d("Anything-But expression name not found");if(e.length>1)throw new d("Only one key allowed in match expression");let t=e[0];if(t!="prefix")throw new d(`Unsupported anything-but pattern: ${t}`);_(s.prefix)}if(Array.isArray(s)){let e;for(let t of s){let i=typeof t;if(i=="string"||i=="number"){if(e||(e=i),e!=i)throw new d("Inside anything but list, either all values are number or string, mixed type is not supported");continue}throw new d("Inside anything but list, start|null|boolean is not supported")}}}function fe(s){if(!Array.isArray(s))throw new d("Value of numeric must be an array");if(!s.length)throw new d("Invalid member in numeric match");let e=s[0];if(e!="=")throw new d(`Unrecognized numeric range operator: ${e}`);if(e!="="&&!J.includes(e))throw new d(`Unrecognized numeric range operator: ${e}`);if(typeof s[1]!="number")throw new d("Value of equals must be numeric");if(s.length>2){if(e=="=")throw new d("Too many elements in numeric expression");let i=s[2];if(e==i||!J.includes(i)||s.length==3)throw new d(`Bad numeric range operator: ${i}`);if(typeof s[4]!="number")throw new d(`Value of ${i} must be numeric`);if(s.length!=4)throw new d("Too many terms in numeric range expression")}}function ge(s){if(typeof s!="string")throw new d("cidr match pattern must be a string");if(!ce.test(s))throw s.includes("/")?new d("Malformed CIDR"):new d("Malformed CIDR, one '/' required")}function he(s,e){switch(s){case"exists":ue(e);break;case"numeric":fe(e);break;case"anything-but":de(e);break;case"equals-ignore-case":le(e);break;case"prefix":_(e);break;case"suffix":pe(e);break;case"cidr":ge(e);break;default:throw new d(`Unrecognized match type ${s}`)}}function me(s,e,t){let i=0;for(let r of s){if(typeof r=="string"||typeof r=="number"||typeof r=="boolean"||r===null){i++;continue}if(Array.isArray(r))throw new d("Match value must be String, number, true, false, or null");let n=Object.keys(r);if(!n.length)throw new d("Empty objects are not allowed");if(n.length>1)throw new d("Only one key allowed in match expression");let o=n[0];he(o,r[o]),i++}i&&(e.values=e.values*t*i)}function be(s,e,t){if(s.length<2)throw new d("There must have at least 2 Objects in $or relationship.");let i=e.isTopLevel,r=e.values,n=[];for(let l of s){if(!m(l))throw new d("Only JSON object is allowed in array of $or relationship.");let p=Object.keys(l);if(!p.length)throw new d("Empty objects are not allowed");let f=p.find(g=>ae.includes(g));if(f)throw new d(`${f} is Ruler reserved fieldName which cannot be used inside $or.`);e.isTopLevel=i,e.values=1,q(l,e,t),n.push(e.values)}let o=n.reduce((l,p)=>l+=p,0);e.values=r*o}function q(s,e,t){let i=e.isTopLevel,r=Object.keys(s);if(e.isTopLevel){for(let n of r)n!="$or"&&e.keys.add(n);e.isTopLevel=!1}else e.hasNestedField=!0;for(let[n,o]of Object.entries(s)){if(Array.isArray(o)){if(!o.length)throw new d("Empty arrays are not allowed");n=="$or"?(e.isTopLevel=i,be(o,e,t)):me(o,e,t);continue}if(m(o)){q(o,e,t+1);continue}throw new d(`"${n}" must be an object or an array`)}e.isTopLevel=!1}function B(s){if(Buffer.from(s,"utf-8").byteLength>262144)throw new d("Filter policy too big");let e;try{e=JSON.parse(s)}catch{throw new d("failed to parse JSON")}if(!m(e))throw new d("Filter is not an object");let t={keys:new Set,values:1,isTopLevel:!0,hasNestedField:!1};if(q(e,t,1),t.keys.size>5)throw new d("Filter policy can not have more than 5 keys");if(t.values>150)throw new d("Filter policy is too complex");return{pattern:e,counters:t}}function H(s){let e=B(s);if(e.counters.hasNestedField)throw new d("Filter policy scope MessageAttributes does not support nested filter policy");return e}var N=class{constructor(e,t,i,r,n){this.config=e;this.topicArn=t;this.getLambdas=r;this.getSqsClient=n;this.id=k(),this.arn=`${t}:${this.id}`,this.validateProtocol(),this.validateAttributes(),this.internalAttributes={ConfirmationWasAuthenticated:this.config.Protocol.startsWith("http")?"false":"true",PendingConfirmation:this.config.Protocol.startsWith("http")?"true":"false",Owner:i,SubscriptionPrincipal:`arn:aws:iam::${i}:user/exlo`}}id;arn;deleted=!1;filterPattern;fitlerScope="MessageAttributes";queueName="";lambdaName="";queueUrl;confirmationToken;internalAttributes;validateProtocol(){if(this.config.Protocol=="sqs"){let e=I(this.config.Endpoint);if(!x(e))throw new u("Invalid SQS ARN: Must be an arn string (example: 'arn:aws:sqs:eu-west-1:123456789012:MyQueue')");this.queueName=e.resourceId;return}if(this.config.Protocol=="lambda"){let e=I(this.config.Endpoint);if(!z(e))throw new u("Invalid parameter: Lambda endpoint ARN");this.lambdaName=e.resourceId;return}if(this.config.Protocol=="http"){if(!this.config.Endpoint.startsWith("http://"))throw new u("Invalid parameter: Endpoint must match the specified protocol");return}if(this.config.Protocol=="https"&&!this.config.Endpoint.startsWith("https://"))throw new u("Invalid parameter: Endpoint must match the specified protocol");console.warn("Only SQS, Lambda and HTTP/S Endpoints are currently supported.")}validateAttributes(){if(this.config.Attributes){if("RedrivePolicy"in this.config.Attributes)try{let e=JSON.parse(this.config.Attributes.RedrivePolicy);x(I(e.deadLetterTargetArn))}catch{}if("RawMessageDelivery"in this.config.Attributes){if(!["true","false"].includes(this.config.Attributes.RawMessageDelivery))throw new u(`Invalid parameter: Attributes Reason: RawMessageDelivery: Invalid value [${this.config.Attributes.RawMessageDelivery}]. Must be true or false.`);if(!["sqs","http","https"].includes(this.config.Protocol))throw new u(`Invalid parameter: Attributes Reason: Delivery protocol [${this.config.Protocol}] does not support raw message delivery.`)}if("FilterPolicyScope"in this.config.Attributes){if(!["MessageBody","MessageAttributes"].includes(this.config.Attributes.FilterPolicyScope))throw new u(`Invalid parameter: Attributes Reason: FilterPolicyScope: Invalid value [${this.config.Attributes.FilterPolicyScope}]. Please use either MessageBody or MessageAttributes`);this.fitlerScope=this.config.Attributes.FilterPolicyScope}if(this.config.Attributes.FilterPolicy)if(this.fitlerScope=="MessageAttributes"){let{pattern:e}=H(this.config.Attributes.FilterPolicy);this.filterPattern=e}else{let{pattern:e}=B(this.config.Attributes.FilterPolicy);this.filterPattern=e}}}async notify(e){let t=e.message;if(e.messageStructure=="json"){if(t=e.defaultMessage,this.config.Protocol=="sqs"){if(e.sqsMessage=="")return;e.sqsMessage&&(t=e.sqsMessage)}else if(this.config.Protocol=="http"){if(e.httpMessage=="")return;e.httpMessage&&(t=e.httpMessage)}else if(this.config.Protocol=="https"){if(e.httpsMessage=="")return;e.httpsMessage&&(t=e.httpsMessage)}else if(this.config.Protocol=="lambda"){if(e.lambdaMessage=="")return;e.lambdaMessage&&(t=e.lambdaMessage)}}if(!this.shouldNotify(e.messageAttributes,t))return;let i={};for(let[n,o]of Object.entries(e.messageAttributes))this.config.Protocol=="lambda"?o.Type.startsWith("String")||o.Type.startsWith("Number")?i[n]={Type:"String",Value:o.Value}:o.Type.startsWith("Binary")?i[n]={Type:"Binary",Value:o.Value}:i[n]={Type:o.Type,Value:o.Value}:i[n]={Type:o.Type,Value:o.Value};let r={Type:"Notification",MessageId:e.messageId,TopicArn:this.topicArn,Message:t,Timestamp:e.timestamp,UnsubscribeUrl:`${e.serverHost}/?Action=Unsubscribe&SubscriptionArn=${this.arn}`,MessageAttributes:i};this.config.Protocol=="lambda"?(r.SignatureVersion="1",r.Signature="fakeandinvalidsignature",r.SigningCertUrl=`${e.serverHost}/SimpleNotificationService-fakecert.pem`,e.subject?r.Subject=e.subject:r.Subject=null,await this.notifyLambda(r)):this.config.Protocol=="sqs"?(e.subject&&(r.Subject=e.subject),await this.notifySqs(r,e)):(this.config.Protocol=="http"||this.config.Protocol=="https")&&(e.subject&&(r.Subject=e.subject),await this.notifyHttp(r))}getAttributes(){return{...this.config.Attributes,...this.internalAttributes,Endpoint:this.config.Endpoint,Protocol:this.config.Protocol,SubscriptionArn:this.arn}}shouldNotify(e,t){if(this.internalAttributes.PendingConfirmation!="true"){if(!this.filterPattern)return!0;if(this.fitlerScope=="MessageAttributes"){let i={};for(let[r,n]of Object.entries(e)){if(n.Type.startsWith("Binary."))return!1;if(!n.Type.startsWith("Binary")){if(n.Type.startsWith("Number")){i[r]=Number(n.Value);continue}if(n.Type=="String.Array")try{i[r]=JSON.parse(n.Value);continue}catch{}n.Type.startsWith("String")&&(i[r]=n.Value)}}return A(this.filterPattern,i)}if(!t)return!1;try{let i=JSON.parse(t);return m(i)?A(this.filterPattern,i):!1}catch{return!1}}}async notifyLambda(e){let t=this.getLambdas().find(r=>r.name==this.lambdaName);if(!t)return;let i={Records:[{EventSource:"aws:sns",EventVersion:"1.0",EventSubscriptionArn:this.arn,Sns:e}]};await t.invoke(i)}async getQueueUrl(){if(!this.queueUrl){let e=this.getSqsClient(),{QueueUrl:t}=await e.getQueueUrl({QueueName:this.queueName});this.queueUrl=t}return this.queueUrl}async notifyHttp(e){let t={"content-type":"text/plain; charset=UTF-8","user-agent":"Amazon Simple Notification Service Agent","x-amz-sns-subscription-arn":this.arn,"x-amz-sns-message-type":"Notification","x-amz-sns-message-id":e.MessageId,"x-amz-sns-topic-arn":this.topicArn},i;if(this.config.Attributes?.RawMessageDelivery=="true")i=e.Message,t["x-amz-sns-rawdelivery"]="true";else{let r=Object.keys(e.MessageAttributes).length;i=JSON.stringify({...e,MessageAttributes:r?e.MessageAttributes:void 0})}try{await K(this.config.Endpoint,{method:"POST",body:i,headers:t},3)}catch{console.error(`Unable to publish SNS Message for Endpoint: ${this.config.Endpoint}`)}}async notifySqs(e,t){let i=this.getSqsClient(),r=await this.getQueueUrl(),n={QueueUrl:r,MessageAttributes:{}};if(this.config.Attributes?.RawMessageDelivery=="true"){n.MessageBody=e.Message;let o=0;for(let[l,p]of Object.entries(e.MessageAttributes))o++,n.MessageAttributes[l]={DataType:p.Type},p.Type.startsWith("Binary")?n.MessageAttributes[l].BinaryValue=Buffer.from(p.Value,"base64"):n.MessageAttributes[l].StringValue=p.Value;if(o>10)throw new a({Code:"ServiceError",Message:"Can not send more than 10 message attributes to SQS endpoint with RawMessageDelivery enabled"})}else n.MessageBody=JSON.stringify(e);t.messageGroupId&&(n.MessageGroupId=t.messageGroupId),r.endsWith(".fifo")&&(n.MessageDeduplicationId=t.messageDeduplicationId),await i.sendMessage(n)}async redrive(){}requestConfirmation(e){if(!["http","https"].includes(this.config.Protocol))return;let t=k(),i=Buffer.from(JSON.stringify({u:k(),a:this.arn,d:Date.now()})).toString("base64url"),r=JSON.stringify({Type:"SubscriptionConfirmation",MessageId:t,Token:i,TopicArn:this.topicArn,Message:`You have chosen to subscribe to the topic ${this.topicArn}.
31
- To confirm the subscription, visit the SubscribeURL included in this message.`,SubscribeURL:`${e}/?Action=ConfirmSubscription&TopicArn=${this.topicArn}&Token=${i}`,Timestamp:new Date().toISOString(),SignatureVersion:"1",Signature:"fakeandinvalidsignature",SigningCertURL:`${e}/SimpleNotificationService-fakecert.pem`}),n=this.config,o=this.internalAttributes;this.confirmationToken=i,K(this.config.Endpoint,{method:"POST",body:r,headers:{"x-amz-sns-message-id":t,"x-amz-sns-topic-arn":this.topicArn,"user-agent":"Amazon Simple Notification Service Agent","x-amz-sns-message-type":"SubscriptionConfirmation"}}).then(()=>{o.ConfirmationWasAuthenticated="true"}).catch(()=>{console.error(`Unable to request SNS Confirmation for Endpoint: ${n.Endpoint}`)})}confirm(){this.internalAttributes.PendingConfirmation="false"}};async function K(s,e={},t=30,i=1e3){let r=0;for(;r<=t;)try{let n=await fetch(s,e);if(n.ok)return n;throw new Error(`Non-200 response: ${n.statusText}`)}catch(n){if(r<t)await ye(i),r++;else throw new Error(`Failed after ${t} attempts: ${String(n)}`)}throw new Error("Unknown error.")}import{randomUUID as Se}from"node:crypto";import{createHash as we}from"node:crypto";var Ie=s=>we("sha256").update(s).digest("hex"),V=class{policy={http:{defaultHealthyRetryPolicy:{minDelayTarget:20,maxDelayTarget:20,numRetries:3,numMaxDelayRetries:0,numNoDelayRetries:0,numMinDelayRetries:0,backoffFunction:"linear"},disableSubscriptionOverrides:!1,defaultRequestPolicy:{headerContentType:"text/plain; charset=UTF-8"}}};toString(){return JSON.stringify(this.policy)}},F=class{constructor(e,t){this.topicArn=e;this.accountId=t;this.policy={Version:"2008-10-17",Id:"__default_policy_ID",Statement:[{Sid:"__default_statement_ID",Effect:"Allow",Principal:{AWS:"*"},Action:["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],Resource:this.topicArn,Condition:{StringEquals:{"AWS:SourceOwner":this.accountId}}}]}}policy;toString(){return JSON.stringify(this.policy)}},P=class{constructor(e,t,i,r){this.config=e;this.serverHost=t;this.region=i;this.accountId=r;this.validateTopic(),this.setTopicDefaultAttributes(),this.TopicArn=`arn:aws:sns:${this.region}:${this.accountId}:${this.config.Name}`,this.internalAttributes={Policy:new F(this.TopicArn,r),EffectiveDeliveryPolicy:new V,Owner:this.accountId,TopicArn:this.TopicArn}}internalAttributes;TopicArn;subscribers=[];sequenceNumber=0;getAttributes(){let e=0,t=0,i=0;for(let n of this.subscribers){if(n.deleted){t++;continue}n.internalAttributes.PendingConfirmation=="true"?i++:e++}return{...this.config.Attributes,...this.internalAttributes,SubscriptionsConfirmed:e,SubscriptionsDeleted:t,SubscriptionsPending:i}}setTopicDefaultAttributes(){this.config.Attributes??={},this.config.Attributes.DisplayName||(this.config.Attributes.DisplayName=""),this.config.Attributes.TracingConfig||(this.config.Attributes.TracingConfig="PassThrough"),this.config.Attributes.SignatureVersion||(this.config.Attributes.SignatureVersion="1"),this.config.Attributes.FifoTopic?(this.config.Attributes.ContentBasedDeduplication==null&&(this.config.Attributes.ContentBasedDeduplication=!1),this.config.Attributes.FifoThroughputScope||(this.config.Attributes.FifoThroughputScope="Topic")):this.config.Attributes.FifoTopic=!1}validateTopic(){if(!this.isValidSnsTopicName(this.config.Name))throw new u("Invalid parameter: Topic Name");if(this.config.Name.endsWith(".fifo")&&!this.config.Attributes?.FifoTopic||this.config.Attributes?.FifoTopic&&!this.config.Name.endsWith(".fifo"))throw new u("Invalid parameter: Topic Name");if(this.config.Attributes?.TracingConfig!=null&&!["PassThrough","Active"].includes(this.config.Attributes?.TracingConfig))throw new u(`Attributes Reason: Invalid tracing config value: ${this.config.Attributes?.TracingConfig}`);this.config.Name.endsWith(".fifo")?this.validateFifoTopic():this.validateStandartTopic()}isValidSnsTopicName(e){return!(e.length<1||e.length>256||!/^[A-Za-z0-9_-]+(\.fifo)?$/.test(e)||e.endsWith(".fifo")&&e.slice(0,-5).length<1)}validateFifoTopic(){}validateStandartTopic(){if(this.config.Attributes){if("ContentBasedDeduplication"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute ContentBasedDeduplication");if("ArchivePolicy"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute ArchivePolicy");if("FifoThroughputScope"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute FifoThroughputScope")}}getSequenceNumber(){return this.sequenceNumber++,`1${`${this.sequenceNumber}000`.padStart(19,"0")}`}validateMsg(e){if(e.messageSize>262144)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: Message too long"});if(this.config.Name.endsWith(".fifo")){if(!e.messageGroupId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: The MessageGroupId parameter is required for FIFO topics"});if(!e.messageDeduplicationId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: The topic should either have ContentBasedDeduplication enabled or MessageDeduplicationId provided explicitly"})}else{if(e.messageGroupId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: MessageGroupId Reason: The request includes MessageGroupId parameter that is not valid for this topic type"});if(e.messageDeduplicationId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: MessageDeduplicationId Reason: The request includes MessageDeduplicationId parameter that is not valid for this topic type"})}}createTopicMessage(e){let t=Se(),i={...e,messageId:t,timestamp:new Date().toISOString(),serverHost:this.serverHost};return this.config.Name.endsWith(".fifo")&&this.config.Attributes?.ContentBasedDeduplication&&(i.messageDeduplicationId||(i.messageDeduplicationId=Ie(i.message))),this.validateMsg(i),i}publish(e){let t=this.createTopicMessage(e),i=this.config.Name.endsWith(".fifo")?this.getSequenceNumber():void 0;for(let r of this.subscribers)r.deleted||r.notify(t).catch(n=>{console.error(n)});return{messageId:t.messageId,sequenceNumber:i}}publishBatchFifo(e){let t=[];for(let r of e.parsedMessages)t.push({id:r.Id,msg:this.createTopicMessage({...r.message,topicArn:e.topicArn,topicName:e.topicName})});let i=[];for(let r of t){i.push({Id:r.id,MessageId:r.msg.messageId,SequenceNumber:this.getSequenceNumber()});for(let n of this.subscribers)n.deleted||n.notify(r.msg).catch(o=>{console.error(o)})}return{successful:i,failed:[]}}publishBatch(e){if(e.parsedMessages.reduce((r,n)=>r+n.message.messageSize,0)>262144)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: Message too long"});if(this.config.Name.endsWith(".fifo"))return this.publishBatchFifo(e);let i={successful:[],failed:[]};for(let r of e.parsedMessages)try{let{messageId:n}=this.publish({...r.message,topicArn:e.topicArn,topicName:e.topicName});i.successful.push({Id:r.Id,MessageId:n})}catch(n){n instanceof a?i.failed.push({Id:r.Id,Code:n.Code,Message:n.message,SenderFault:n.SenderFault}):i.failed.push({Id:r.Id,Code:"UnexpectedError",Message:n?.toString?.()??"Unknown error",SenderFault:!1})}return i}subscribe(e){let t=e.config.Endpoint=="sqs"&&e.config.Endpoint.endsWith(".fifo");if(this.config.Name.endsWith(".fifo")){if(!t)throw new u("Only FIFO SQS is allowed to subscribe to FIFO Topic.")}else if(t)throw new u("FIFO SQS is not allowed to subscribe to Standart Topic.");this.subscribers.push(e)}};var E=class s{constructor(e,t,i,r,n){this.port=e;this.region=t;this.accountId=i;this.getLambdas=r;this.getSqsClient=n}server;topics=[];async start(){this.server=Ae((e,t)=>{this.requestHandler(e,t)}),await new Promise(e=>{this.server.listen(this.port,e)}),this.port=this.server.address().port,this.server.unref()}createTopic(e){let t=new P(e,`http://localhost:${this.port}`,this.region,this.accountId),i=this.topics.find(r=>r.config.Name==e.Name);if(!i)return this.topics.push(t),t;if(!ve(t.config,i.config))throw new u("Attributes Reason: Topic already exists with different attributes");return i}subscribe(e,t){let i=e.subscribers.find(n=>n.config.Endpoint==t.Endpoint&&!n.deleted);if(i)return i;let r=new N(t,e.TopicArn,this.accountId,this.getLambdas,this.getSqsClient);return e.subscribe(r),r}stop(){this.server?.close()}getTopicByName(e){let t=this.topics.find(i=>i.config.Name==e);if(!t)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});return t}requestSubscriptionsConfirmation(){let e=`http://localhost:${this.port}`;for(let t of this.topics)for(let i of t.subscribers)i.requestConfirmation(e)}static async collectBody(e){let t=Buffer.alloc(0);return e.on("data",i=>{t=Buffer.concat([t,i])}),new Promise(i=>{e.on("end",async()=>{i(t?t.toString("utf-8"):void 0)})})}static async getRequestBody(e){let{method:t,url:i}=e,r;if(t=="GET")try{let n=new URL(i,"http://localhost:300");n.search&&(r=n.search.slice(1))}catch{}else t=="POST"&&(r=await s.collectBody(e));return r}async requestHandler(e,t){let i=C();t.setHeader("x-amzn-requestid",i),t.setHeader("Content-Type","application/xml");let r="";try{let n=await s.getRequestBody(e);if(n){let o=Me(n);switch(typeof o.Action=="string"&&(r=o.Action),r){case"Publish":return this.handlePublishRequest(o,t,i);case"PublishBatch":return this.handlePublishBatchRequest(o,t,i);case"CreateTopic":return this.handleCreateTopicRequest(o,t,i);case"GetTopicAttributes":return this.handleGetTopicAttributes(o,t,i);case"DeleteTopic":return this.handleDeleteTopic(o,t,i);case"ListTopics":return this.handleListTopics(o,t,i);case"Subscribe":return this.handleSubscribe(o,t,i);case"Unsubscribe":return this.handleUnsubscribe(o,t,i);case"ListSubscriptions":return this.handleListSubscriptions(o,t,i);case"ListSubscriptionsByTopic":return this.handleListSubscriptionsByTopic(o,t,i);case"GetSubscriptionAttributes":return this.handleGetSubscriptionAttributes(o,t,i);case"ConfirmSubscription":return this.handleConfirmSubscription(o,t,i);default:break}}}catch(n){n instanceof a?(t.statusCode=n.statusCode,t.end(n.toXml(i))):(t.statusCode=500,t.end(a.genericErrorResponse({Code:"InternalError",RequestId:i,Message:n?.toString?.()??"Unknown error"})));return}t.statusCode=500,t.end(new a({Code:"UnsupportedOperation",Message:`This Action ${r?`(${r})`:""} is currently not supported`}).toXml(i))}handlePublishRequest(e,t,i){let r=L(e),n=this.topics.find(f=>f.config.Name==r.topicName);if(!n)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});let{messageId:o,sequenceNumber:l}=n.publish(r),p=W(o,i,l);t.statusCode=200,t.end(p)}handlePublishBatchRequest(e,t,i){let r=U(e),n=this.topics.find(p=>p.config.Name==r.topicName);if(!n)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});let o=n.publishBatch(r),l=Q(i,o.successful,o.failed);t.statusCode=200,t.end(l)}handleCreateTopicRequest(e,t,i){let r=O(e),n=this.createTopic(r);t.statusCode=200,t.end(`<CreateTopicResponse xmlns="https://sns.amazonaws.com/doc/2010-03-31/">
31
+ To confirm the subscription, visit the SubscribeURL included in this message.`,SubscribeURL:`${e}/?Action=ConfirmSubscription&TopicArn=${this.topicArn}&Token=${i}`,Timestamp:new Date().toISOString(),SignatureVersion:"1",Signature:"fakeandinvalidsignature",SigningCertURL:`${e}/SimpleNotificationService-fakecert.pem`}),n=this.config,o=this.internalAttributes;this.confirmationToken=i,K(this.config.Endpoint,{method:"POST",body:r,headers:{"x-amz-sns-message-id":t,"x-amz-sns-topic-arn":this.topicArn,"user-agent":"Amazon Simple Notification Service Agent","x-amz-sns-message-type":"SubscriptionConfirmation"}}).then(()=>{o.ConfirmationWasAuthenticated="true"}).catch(()=>{console.error(`Unable to request SNS Confirmation for Endpoint: ${n.Endpoint}`)})}confirm(){this.internalAttributes.PendingConfirmation="false"}};async function K(s,e={},t=30,i=1e3){let r=0;for(;r<=t;)try{let n=await fetch(s,e);if(n.ok)return n;throw new Error(`Non-200 response: ${n.statusText}`)}catch(n){if(r<t)await ye(i),r++;else throw new Error(`Failed after ${t} attempts: ${String(n)}`)}throw new Error("Unknown error.")}import{randomUUID as Se}from"node:crypto";import{createHash as we}from"node:crypto";var Ie=s=>we("sha256").update(s).digest("hex"),V=class{policy={http:{defaultHealthyRetryPolicy:{minDelayTarget:20,maxDelayTarget:20,numRetries:3,numMaxDelayRetries:0,numNoDelayRetries:0,numMinDelayRetries:0,backoffFunction:"linear"},disableSubscriptionOverrides:!1,defaultRequestPolicy:{headerContentType:"text/plain; charset=UTF-8"}}};toString(){return JSON.stringify(this.policy)}},F=class{constructor(e,t){this.topicArn=e;this.accountId=t;this.policy={Version:"2008-10-17",Id:"__default_policy_ID",Statement:[{Sid:"__default_statement_ID",Effect:"Allow",Principal:{AWS:"*"},Action:["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission","SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic","SNS:Publish"],Resource:this.topicArn,Condition:{StringEquals:{"AWS:SourceOwner":this.accountId}}}]}}policy;toString(){return JSON.stringify(this.policy)}},P=class{constructor(e,t,i,r){this.config=e;this.serverHost=t;this.region=i;this.accountId=r;this.validateTopic(),this.setTopicDefaultAttributes(),this.TopicArn=`arn:aws:sns:${this.region}:${this.accountId}:${this.config.Name}`,this.internalAttributes={Policy:new F(this.TopicArn,r),EffectiveDeliveryPolicy:new V,Owner:this.accountId,TopicArn:this.TopicArn}}internalAttributes;TopicArn;subscribers=[];sequenceNumber=0;getAttributes(){let e=0,t=0,i=0;for(let n of this.subscribers){if(n.deleted){t++;continue}n.internalAttributes.PendingConfirmation=="true"?i++:e++}return{...this.config.Attributes,...this.internalAttributes,SubscriptionsConfirmed:e,SubscriptionsDeleted:t,SubscriptionsPending:i}}setTopicDefaultAttributes(){this.config.Attributes??={},this.config.Attributes.DisplayName||(this.config.Attributes.DisplayName=""),this.config.Attributes.TracingConfig||(this.config.Attributes.TracingConfig="PassThrough"),this.config.Attributes.SignatureVersion||(this.config.Attributes.SignatureVersion="1"),this.config.Attributes.FifoTopic?(this.config.Attributes.ContentBasedDeduplication==null&&(this.config.Attributes.ContentBasedDeduplication=!1),this.config.Attributes.FifoThroughputScope||(this.config.Attributes.FifoThroughputScope="Topic")):this.config.Attributes.FifoTopic=!1}validateTopic(){if(!this.isValidSnsTopicName(this.config.Name))throw new u("Invalid parameter: Topic Name");if(this.config.Name.endsWith(".fifo")&&!this.config.Attributes?.FifoTopic||this.config.Attributes?.FifoTopic&&!this.config.Name.endsWith(".fifo"))throw new u("Invalid parameter: Topic Name");if(this.config.Attributes?.TracingConfig!=null&&!["PassThrough","Active"].includes(this.config.Attributes?.TracingConfig))throw new u(`Attributes Reason: Invalid tracing config value: ${this.config.Attributes?.TracingConfig}`);this.config.Name.endsWith(".fifo")?this.validateFifoTopic():this.validateStandartTopic()}isValidSnsTopicName(e){return!(e.length<1||e.length>256||!/^[A-Za-z0-9_-]+(\.fifo)?$/.test(e)||e.endsWith(".fifo")&&e.slice(0,-5).length<1)}validateFifoTopic(){}validateStandartTopic(){if(this.config.Attributes){if("ContentBasedDeduplication"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute ContentBasedDeduplication");if("ArchivePolicy"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute ArchivePolicy");if("FifoThroughputScope"in this.config.Attributes)throw new u("Attributes Reason: Unknown attribute FifoThroughputScope")}}getSequenceNumber(){return this.sequenceNumber++,`1${`${this.sequenceNumber}000`.padStart(19,"0")}`}validateMsg(e){if(e.messageSize>262144)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: Message too long"});if(this.config.Name.endsWith(".fifo")){if(!e.messageGroupId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: The MessageGroupId parameter is required for FIFO topics"});if(!e.messageDeduplicationId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: The topic should either have ContentBasedDeduplication enabled or MessageDeduplicationId provided explicitly"})}else{if(e.messageGroupId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: MessageGroupId Reason: The request includes MessageGroupId parameter that is not valid for this topic type"});if(e.messageDeduplicationId)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: MessageDeduplicationId Reason: The request includes MessageDeduplicationId parameter that is not valid for this topic type"})}}createTopicMessage(e){let t=Se(),i={...e,messageId:t,timestamp:new Date().toISOString(),serverHost:this.serverHost};return this.config.Name.endsWith(".fifo")&&this.config.Attributes?.ContentBasedDeduplication&&(i.messageDeduplicationId||(i.messageDeduplicationId=Ie(i.message))),this.validateMsg(i),i}publish(e){let t=this.createTopicMessage(e),i=this.config.Name.endsWith(".fifo")?this.getSequenceNumber():void 0;for(let r of this.subscribers)r.deleted||r.notify(t).catch(n=>{console.error(n)});return{messageId:t.messageId,sequenceNumber:i}}publishBatchFifo(e){let t=[];for(let r of e.parsedMessages)t.push({id:r.Id,msg:this.createTopicMessage({...r.message,topicArn:e.topicArn,topicName:e.topicName})});let i=[];for(let r of t){i.push({Id:r.id,MessageId:r.msg.messageId,SequenceNumber:this.getSequenceNumber()});for(let n of this.subscribers)n.deleted||n.notify(r.msg).catch(o=>{console.error(o)})}return{successful:i,failed:[]}}publishBatch(e){if(e.parsedMessages.reduce((r,n)=>r+n.message.messageSize,0)>262144)throw new a({Code:"InvalidParameter",Message:"Invalid parameter: Message too long"});if(this.config.Name.endsWith(".fifo"))return this.publishBatchFifo(e);let i={successful:[],failed:[]};for(let r of e.parsedMessages)try{let{messageId:n}=this.publish({...r.message,topicArn:e.topicArn,topicName:e.topicName});i.successful.push({Id:r.Id,MessageId:n})}catch(n){n instanceof a?i.failed.push({Id:r.Id,Code:n.Code,Message:n.message,SenderFault:n.SenderFault}):i.failed.push({Id:r.Id,Code:"UnexpectedError",Message:n?.toString?.()??"Unknown error",SenderFault:!1})}return i}subscribe(e){let t=e.config.Endpoint=="sqs"&&e.config.Endpoint.endsWith(".fifo");if(this.config.Name.endsWith(".fifo")){if(!t)throw new u("Only FIFO SQS is allowed to subscribe to FIFO Topic.")}else if(t)throw new u("FIFO SQS is not allowed to subscribe to Standart Topic.");this.subscribers.push(e)}};var E=class s{constructor(e,t,i,r,n){this.port=e;this.region=t;this.accountId=i;this.getLambdas=r;this.getSqsClient=n}server;topics=[];async start(){this.server=Ae((e,t)=>{this.requestHandler(e,t)}),await new Promise(e=>{this.server.listen(this.port,e)}),this.port=this.server.address().port,this.server.unref()}stop(){this.server?.close()}static async collectBody(e){let t=Buffer.alloc(0);return e.on("data",i=>{t=Buffer.concat([t,i])}),new Promise(i=>{e.on("end",async()=>{i(t?t.toString("utf-8"):void 0)})})}static async getRequestBody(e){let{method:t,url:i}=e,r;if(t=="GET")try{let n=new URL(i,"http://localhost:300");n.search&&(r=n.search.slice(1))}catch{}else t=="POST"&&(r=await s.collectBody(e));return r}async requestHandler(e,t){let i=C();t.setHeader("x-amzn-requestid",i),t.setHeader("Content-Type","application/xml");let r="";try{let n=await s.getRequestBody(e);if(n){let o=Me(n);switch(typeof o.Action=="string"&&(r=o.Action),r){case"Publish":return this.handlePublishRequest(o,t,i);case"PublishBatch":return this.handlePublishBatchRequest(o,t,i);case"CreateTopic":return this.handleCreateTopicRequest(o,t,i);case"GetTopicAttributes":return this.handleGetTopicAttributes(o,t,i);case"DeleteTopic":return this.handleDeleteTopic(o,t,i);case"ListTopics":return this.handleListTopics(o,t,i);case"Subscribe":return this.handleSubscribe(o,t,i);case"Unsubscribe":return this.handleUnsubscribe(o,t,i);case"ListSubscriptions":return this.handleListSubscriptions(o,t,i);case"ListSubscriptionsByTopic":return this.handleListSubscriptionsByTopic(o,t,i);case"GetSubscriptionAttributes":return this.handleGetSubscriptionAttributes(o,t,i);case"ConfirmSubscription":return this.handleConfirmSubscription(o,t,i);default:break}}}catch(n){n instanceof a?(t.statusCode=n.statusCode,t.end(n.toXml(i))):(t.statusCode=500,t.end(a.genericErrorResponse({Code:"InternalError",RequestId:i,Message:n?.toString?.()??"Unknown error"})));return}t.statusCode=500,t.end(new a({Code:"UnsupportedOperation",Message:`This Action ${r?`(${r})`:""} is currently not supported`}).toXml(i))}createTopic(e){let t=new P(e,`http://localhost:${this.port}`,this.region,this.accountId),i=this.topics.find(r=>r.config.Name==e.Name);if(!i)return this.topics.push(t),t;if(!ve(t.config,i.config))throw new u("Attributes Reason: Topic already exists with different attributes");return i}subscribe(e,t){let i=e.subscribers.find(n=>n.config.Endpoint==t.Endpoint&&!n.deleted);if(i)return i;let r=new N(t,e.TopicArn,this.accountId,this.getLambdas,this.getSqsClient);return e.subscribe(r),r}getTopicByName(e){let t=this.topics.find(i=>i.config.Name==e);if(!t)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});return t}requestSubscriptionsConfirmation(){let e=`http://localhost:${this.port}`;for(let t of this.topics)for(let i of t.subscribers)i.requestConfirmation(e)}handlePublishRequest(e,t,i){let r=L(e),n=this.topics.find(f=>f.config.Name==r.topicName);if(!n)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});let{messageId:o,sequenceNumber:l}=n.publish(r),p=W(o,i,l);t.statusCode=200,t.end(p)}handlePublishBatchRequest(e,t,i){let r=U(e),n=this.topics.find(p=>p.config.Name==r.topicName);if(!n)throw new a({Code:"NotFound",Message:"Topic does not exist",statusCode:404});let o=n.publishBatch(r),l=Q(i,o.successful,o.failed);t.statusCode=200,t.end(l)}handleCreateTopicRequest(e,t,i){let r=O(e),n=this.createTopic(r);t.statusCode=200,t.end(`<CreateTopicResponse xmlns="https://sns.amazonaws.com/doc/2010-03-31/">
32
32
  <CreateTopicResult>
33
33
  <TopicArn>arn:aws:sns:${this.region}:${this.accountId}:${n.config.Name}</TopicArn>
34
34
  </CreateTopicResult>
@@ -13,14 +13,14 @@ export declare class SnsServer {
13
13
  private topics;
14
14
  constructor(port: number, region: string, accountId: string, getLambdas: () => ILambda[], getSqsClient: () => SQS);
15
15
  start(): Promise<void>;
16
- createTopic(config: ISnsTopic): SnsTopic;
17
- subscribe(topic: SnsTopic, config: ISnsTopicSubscriber): SnsSubscriber;
18
16
  stop(): void;
19
- getTopicByName(topicName: string): SnsTopic;
20
- requestSubscriptionsConfirmation(): void;
21
17
  private static collectBody;
22
18
  private static getRequestBody;
23
19
  private requestHandler;
20
+ createTopic(config: ISnsTopic): SnsTopic;
21
+ subscribe(topic: SnsTopic, config: ISnsTopicSubscriber): SnsSubscriber;
22
+ getTopicByName(topicName: string): SnsTopic;
23
+ requestSubscriptionsConfirmation(): void;
24
24
  private handlePublishRequest;
25
25
  private handlePublishBatchRequest;
26
26
  private handleCreateTopicRequest;
@@ -3,4 +3,4 @@ import type { Vitest } from "vitest/node";
3
3
  export declare function initMonocart(): Promise<void>;
4
4
  export declare function generateLambdaCoverage(vitest: Vitest, coverageMap: any, rawCoverageDir: string): Promise<void>;
5
5
  export declare function enhanceCoverageProvider(vitest: Vitest, coverageMaps: any[]): Promise<void>;
6
- export declare function getBaseCoverageProvider(): Promise<BaseCoverageProvider<any>>;
6
+ export declare function getBaseCoverageProvider(): Promise<BaseCoverageProvider>;
@@ -1,13 +1,13 @@
1
- "use strict";var Mt=Object.create;var W=Object.defineProperty;var qt=Object.getOwnPropertyDescriptor;var jt=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,Ht=Object.prototype.hasOwnProperty;var _t=(t,e)=>{for(var n in e)W(t,n,{get:e[n],enumerable:!0})},Ee=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of jt(e))!Ht.call(t,s)&&s!==n&&W(t,s,{get:()=>e[s],enumerable:!(r=qt(e,s))||r.enumerable});return t};var P=(t,e,n)=>(n=t!=null?Mt(Ft(t)):{},Ee(e||!t||!t.__esModule?W(n,"default",{value:t,enumerable:!0}):n,t)),$t=t=>Ee(W({},"__esModule",{value:!0}),t);var $n={};_t($n,{createAppRunner:()=>Dt,exloVersion:()=>ut,run:()=>_n});module.exports=$t($n);var L=P(require("node:path")),xe=P(require("esbuild")),Nt=require("exlo/internal/esm");var me=P(require("node:path")),Ie=require("node:module"),Ut={},_=require,C={};function q(t){if(C[t])return C[t];if(typeof _=="function"&&typeof _.resolve=="function"){let n=me.default.resolve(_.resolve(t),"../../");return C[t]=n,n}_=(0,Ie.createRequire)(new URL(".",Ut.url));let e=me.default.resolve(_.resolve(t),"../../");return C[t]=e,e}var Ae=["aws-sdk","@aws-sdk/*","@angular/core","@angular/platform-browser","@aws-sdk/*","@elastic/elasticsearch","@hapi/joi","@opensearch-project/opensearch","@smithy/*","axios","axios-retry","axios-cache-interceptor","aws-serverless-express","aws-sdk","body-parser","classnames","clsx","cookie-parser","cors","core-js","date-fns","dayjs","express","helmet","joi","koa","leaflet","lodash","mysql","mysql2","mongodb","mongoose","moment","http-proxy","http-proxy-middleware","react","react/*","react-dom","react-dom/*","react-hook-form","react-infinite-scroll-component","react-modal","react-rangeslider","react-responsive","react-select","react-scroll","react-slick","react-lazy-load","react-lazyload","react-redux","react-router","react-router-dom","redux","redux-persist","regenerator-runtime","serve-static","express-session","exlo/*","serverless-http","sequelize","svelte","svelte/*","typeorm","pg","pg-hstore","prop-types","underscore","uuid","vue","xmlbuilder","yup","zod","sharp"];var Wt=t=>`import { createRequire as __crE_ } from "${t}module";import { fileURLToPath as __futP_ } from "${t}url";import { dirname as __dN_ } from "${t}path";global.__filename = __futP_(import.meta.url);global.__dirname = __dN_(__filename);global.require = __crE_(__filename);
2
- `,ke=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let l of s())l.writable&&l.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(l){console.log(l)}o=!0}),n&&(i.initialOptions.external.push(...Ae),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=Wt(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var Pe=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),typeof e.logLevel=="string"&&(t.logLevel=e.logLevel),typeof e.logLimit=="number"&&(t.logLimit=e.logLimit),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var Le=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),typeof t.logLevel=="string"&&(e.logLevel=t.logLevel),typeof t.logLimit=="number"&&(e.logLimit=t.logLimit),e};var Oe=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var Ct=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},Ne=t=>{let e={},n=Ct(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var De=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let l=n.split(":");l.length&&(e.name=l[l.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var z=["lambda","sns","sqs"],Te=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=De(o);a&&r.push(a)}continue;case"dynamodb":{let a=Ne(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},V=t=>{if(!(!t||t.type&&!z.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if(z.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,z.includes(n)&&(e.kind=n)}else if(z.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};var dt=require("node:crypto"),pt=P(require("node:http")),mt=P(require("node:inspector")),ye=require("node:os");var Fe=require("node:crypto");var B=!1,zt=t=>{B=t},Vt=()=>B,j=(t,e)=>{B&&console.log(`\x1B[${t}m${e}\x1B[0m`)},Bt=t=>console.log(`\x1B[31m${t}\x1B[0m`),Jt=t=>j("32",t),Qt=t=>j("33",t),Kt=t=>j("36",t),Gt=t=>j("90",t),Yt=t=>j("94",t),Xt=t=>j("95",t),Zt=t=>B?console.log(t):void 0,b={GREEN:Jt,YELLOW:Qt,CYAN:Kt,BR_BLUE:Yt,RED:Bt,GREY:Gt,PINK:Xt,setDebug:zt,getDebug:Vt,info:Zt};var Me="application/vnd.awslambda.http-integration-response",A=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(l=>l===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==Me&&(!this._ct||this._ct==Me),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return b.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var qe="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",je="<html><head><title>400 Request Header Or Cookie Too Large</title></head><body><center><h1>400 Bad Request</h1></center><center>Request Header Or Cookie Too Large</center></body></html>";var en=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],tn=JSON.stringify({Message:null}),J=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},He=(t,e)=>{if(!en.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(tn),!0},D=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},Q=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},K=t=>t instanceof A,_e=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},F=t=>{let e=(0,Fe.randomUUID)();return t.setHeader("x-amzn-RequestId",e),e},G=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Y=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),X=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),Z=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},$e=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var dr=new Error(je);var Ue=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(Ue).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];i[d]=h,m=="x-api-key"&&(s=h),c=c+2}let o={};for(let c of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[c]=i[c];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let c=0;c<r.length;){let d=r[c],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){c=c+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[c+1];a[d]?a[d].push(h):a[d]=[h],c=c+2}let l={};for(let c of Object.keys(a).sort((d,m)=>d.localeCompare(m)))l[c]=a[c];return{headers:o,multiValueHeaders:l,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(c=>c.toLowerCase()),l=o.toLowerCase();a?r[l]?r[l].push(...a):r[l]=a:r[l]||(r[l]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};var Qe=require("exlo/internal/esm");var Ce=require("exlo/internal/esm");var ee=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,n=this.handlers.find(r=>r.name==this.lambdaName);try{let r=await n.invoke({Records:this.#e});await this.onInvokeFinished(e,r)}catch{}}};var ze=10,Ve=0,nn=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),rn=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),We=async(t,e,n)=>{for(let r of Je(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},sn=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},on=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:l}=t,c={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:sn(a)};return l&&(c.md5OfMessageAttributes=l),c.md5OfBody=s,c.eventSource="aws:sqs",c.eventSourceARN=e,c.awsRegion=e.split(":")[3],c},an=(t,e)=>t.map(n=>on(n,e)),te=class extends Ce.EventSourceMapping{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Be(n,r)),await We(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new ee(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#c(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await rn(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await nn(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=an(s,this.config.EventSourceArn),o=await this.#l(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#c(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#l(n){let r=n.map(a=>{let l={...a};try{l.body=JSON.parse(l.body)}catch{}return l}),[s,i]=this.filterRecords(r);await We(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(l=>l.messageId==a.messageId));return o}};var Ke=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let l;if(Array.isArray(o.filterPatterns)){l=[];for(let d of o.filterPatterns)l.push({Pattern:JSON.stringify(d)});l.length||(l=void 0)}let c=new te({BatchSize:typeof o.batchSize=="number"?o.batchSize:ze,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:l?{Filters:l}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Ve},t,s.sqs);if(Qe.EventSourceMapping.SOURCES.push(c),c.config.Enabled)try{await c.init()}catch(d){b.RED(`Failed to start EventSourceMapping ${c.config.EventSourceArn}
3
- Please verify provided SQS Client validity.`),console.error(d)}}},cn=/(-|\w+)/g,ln=t=>t.length<81&&t.replace(cn,"")=="",Be=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!ln(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},Je=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};var nt=require("node:crypto");var Ge=P(require("node:http")),dn=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},Ye=(t,e)=>{let n=dn(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return Ge.default.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},Xe=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},pn=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=Xe({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(l){console.log(l)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},mn=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},Ze=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return pn({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return Xe({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return mn({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},ue=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},et=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=Ye(e,t);if(!o)return;o.end(Ze({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var un=1080*1e3,fn=new Set(["async","ddb","kinesis","s3","sns","sqs"]),tt=t=>typeof t?.kind=="string"?fn.has(t.kind)||t.async:!1,$=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:l,esOutputPath:c,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:S,onSuccess:u,onFailure:v,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=l,this.esOutputPath=c,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=S,this.onSuccess=u,this.onFailure=v,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),tt(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&ue({...i,destination:this.onError}),this.onFailure&&ue({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&tt(n)&&et({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=(0,nt.randomUUID)();this.runner.isMounted||(b.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let l=await a(e,n);typeof l!="function"&&(e=l)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(l,c)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),b.RED(`'${this.name}' | ${i}: Request failed`),c({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),l(m)}catch(m){clearTimeout(d),c(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},un)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;b.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),b.GREY(this.entryPoint);let l="";return typeof r?.kind=="string"&&(l=` (${r.kind.toUpperCase()})`),b.YELLOW(`\u03BB payload${l}:`),b.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{b.YELLOW(i)},400)}};var ne=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by exlo.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};var rt=require("node:events"),st=P(require("node:path")),it=require("node:worker_threads");var hn=st.default.resolve(q("exlo"),"./dist/lib/runtime/runners/node/index.js"),re=class extends rt.EventEmitter{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((l,c)=>{this.once("loaded",d=>{d?l(void 0):c()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",l=>{let{channel:c,data:d,awsRequestId:m,type:h,encoding:p}=l;c=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,b.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(b.BR_BLUE("Solution:"),console.log(d.solution))):c=="fail"?(this.emit(m,c,d,h,p),this.unmount()):this.emit(m,c,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:l,info:c,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:l,clientContext:d},awsRequestId:h});let y=m??new A(c);function f(S,u,v,w){switch(S){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":v=="write"?y.write(u,w):v=="ct"?y.setHeader("Content-Type",u):v=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof A?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={name:this.name,env:this.environment,execArgv:["--enable-source-maps"],workerData:{name:this.name,timeout:this.timeout,memorySize:this.memorySize,esOutputPath:this.esOutputPath,handlerPath:this.handlerPath,handlerName:this.handlerName,debug:b.getDebug()}};this._worker=new it.Worker(hn,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};var ie=require("node:child_process"),at=require("node:fs"),fe=require("node:fs/promises"),H=P(require("node:path"));var yn=process.cwd();function ot(t){let e="";try{e=(0,ie.execSync)(t,{encoding:"utf-8"})}catch{}return e}var se=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=H.default.resolve(q("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=H.default.resolve(i);this.handlerDir=H.default.dirname(c),this.handlerPath=H.default.basename(c,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(yn,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=c.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await(0,fe.access)(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),S="",u=w=>{let R=null,E=w.toString();try{let O=E.includes(t.WATCH);if(O&&this.setWatchFiles(E),E.startsWith(t.DELIMITER)&&E.includes(t.DELIMITEREND)){let I=E.split(t.DELIMITER),T=I[I.length-1].split(t.DELIMITEREND)[0];if(I.length>1){let M;O?M=I[0].split(t.WATCHEND)[1]:M=I.slice(0,-1).join(`
4
- `),M.trim()&&console.log(M)}T&&(R=JSON.parse(T)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),g(R)}else if(E.startsWith(t.DELIMITER))S=E.slice(t.DELIMITER.length);else if(E.includes(t.DELIMITEREND)){let I=E.slice(0,E.indexOf(t.DELIMITEREND)),T=JSON.parse(`${S}${I}`);this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),g(T)}else if(S)S+=E;else if(!S&&E.trim()){let I;if(O){let T=E.split(`
5
- `),M=T.findIndex(Tt=>Tt.startsWith(t.WATCH));I=T.slice(0,M).join(`
6
- `)}else I=E;I.trim()&&console.log(I)}}catch(O){console.log("err",O),y(O)}};this.python.stdout.on("data",u);let v=w=>{let R=w.toString();if(R.includes(t.ERR_RESPONSE))try{R=JSON.parse(R.split(t.ERR_RESPONSE)[1]),R.requestId=p}catch{}finally{this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),y(R)}else console.log(R)};this.python.stderr.on("data",v),this.python.stdin.write(`${f}
7
- `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,H.default.sep)}.py`);for(let o of i)try{await(0,fe.access)(o),this.watchers.push((0,at.watch)(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(ot(`${e} --version`))return e;let r=ot("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&b.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=(0,ie.spawn)(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,this.pyModulePath,this.handlerName,String(this.timeout)],{env:this.environment}),this.python.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}};var ct=require("node:child_process"),lt=require("node:fs"),he=require("node:fs/promises"),U=P(require("node:path"));var oe=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=U.default.resolve(q("exlo"),"./src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},l){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=l;let c=U.default.resolve(i);this.handlerDir=U.default.dirname(c),this.handlerPath=U.default.basename(c,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await(0,he.access)(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),S=v=>{let w=null,R=v.toString();try{if(R.includes(t.WATCH))this.setWatchFiles(R);else if(R.includes(t.DELIMITER)){let E=R.split(t.DELIMITER),O=E[E.length-1];if(E.length>1){let I=E.slice(0,-1).join(`
8
- `);I.trim()&&console.log(I)}O&&(w=JSON.parse(O)),this.ruby.stdout.removeListener("data",S),this.ruby.stderr.removeListener("data",u),g(w)}else R.trim()&&console.log(R)}catch(E){y(E)}};this.ruby.stdout.on("data",S);let u=v=>{let w=v.toString();if(w.includes(t.ERR_RESPONSE))try{w=JSON.parse(w.split(t.ERR_RESPONSE)[1]),w.requestId=p}catch{}finally{this.ruby.stdout.removeListener("data",S),this.ruby.stderr.removeListener("data",u),y(w)}else console.log(w)};this.ruby.stderr.on("data",u),this.ruby.stdin.write(`${f}
9
- `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await(0,he.access)(i),this.watchers.push((0,lt.watch)(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=(0,ct.spawn)(this.bin,[t.wrapper,this.modulePath,this.handlerName,this.name,String(this.timeout)],{env:this.environment,shell:!0}),this.ruby.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}};var gn=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=gn.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var ae;ye.networkInterfaces&&(ae=Object.values((0,ye.networkInterfaces)()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var bn=mt.default?.url()!=null;bn&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),$.ENABLE_TIMEOUT=!1);var vn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},ce=class extends k{#e;runtimeConfig={};#t;sco=[];aws;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),b.setDebug(n.debug),this.aws=e.aws,this.sco=[],this.#e=pt.default.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=(0,dt.randomUUID)();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(b.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),ae&&(k.ip=ae),typeof n=="function"&&await n(r,ae);try{await this.onReady?.(r,k.ip),await Ke(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(l=>l.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(l=>l.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",l=>{console.error(l.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end(qe)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(vn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){let r=n.runtime.charAt(0);n.runner=r=="n"?new re(n):r=="p"?new se(n,this.fakeRebuildEmitter):r=="r"?new oe(n,this.fakeRebuildEmitter):new ne(n.runtime);let s=new $(n);this.addHandler(s)}}};var ht=require("node:fs/promises"),N=P(require("node:path")),yt=require("node:url"),gt=P(require("esbuild"));var ut="0.0.22";function ft(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[]};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[S,u]of Object.entries(t.functions))c(S,u);t.services&&(t.services.sqs&&l("sqs",t.services.sqs),t.services.sns&&l("sns",t.services.sns),t.services.dynamodb&&l("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:l,addLambda:c,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,v)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,v)}catch(R){d.RED(w.name),console.error(R)}},y.buildCallback=async(u,v)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,v)}catch(R){d.RED(w.name),console.error(R),v||process.exit(1)}};let S=t.plugins.reduce((u,v)=>(v.server?.request?.length&&u.push(...v.server.request),u),[]);S?.length&&(y.server.request=S.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(v){throw d.RED(u.name),v}}return y}return n.plugins=t.plugins??[],n}var xn=["js","mjs","cjs","ts","cts","mts"],wn=async t=>{let e=N.default.dirname(N.default.toNamespacedPath(t)),n=N.default.basename(t,N.default.extname(t)),r=N.default.join(e,`__${n}.mjs`);await gt.default.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import((0,yt.pathToFileURL)(r).href)}catch(s){throw s}finally{await(0,ht.rm)(r)}},bt=async t=>{if(t){if(typeof t=="string"){let e=N.default.posix.parse(t),n=N.default.posix.join(e.dir,e.name),r=e.ext.slice(1),s=N.default.posix.resolve(n);xn.includes(r)&&(s+=`.${r}`);let i;try{i=await wn(s)}catch(o){b.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:ft(t)}}};var Rn=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},ge=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(Rn),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};var be=require("node:crypto");var le=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:l,requestId:c}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:l,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:c,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:l,requestId:c,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:l}=e,c=t.getPathParameters(n,r),d,m=n.methods.find(v=>v==a)??"ANY",h={},p="";for(let v of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(v);p+=`&${w.map(R=>encodeURI(`${v}=${R}`)).join("&")}`,h[v]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",S=l.host?.startsWith("localhost")?f:l.host?l.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:S,userAgent:l["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(c).length&&(u.pathParameters=c),l.cookie&&(u.cookies=l.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:l}=e,c={};n.proxy=="httpApi"&&(c.version="1.0");let d=n.paths[0];c.resource=d,c.path=r.pathname,c.httpMethod=l;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);c.headers=m,c.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);c.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);c.multiValueQueryStringParameters=Object.keys(f).length?f:null;let S=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:l,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:S.toISOString(),requestTimeEpoch:S.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),c.requestContext=u;let v=t.getPathParameters(n,r);return c.pathParameters=Object.keys(v).length?v:null,c.stageVariables=null,c.body=a??null,c.isBase64Encoded=a?i:!1,c};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from((0,be.randomUUID)()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw b.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
10
- Received:`),console.log(e),new Error;r=e.statusCode,e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.entries(e.headers).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c),h=this.#e(d);n.push([m,h])}),e.multiValueHeaders&&typeof e.multiValueHeaders=="object"&&!Array.isArray(e.multiValueHeaders)&&Object.entries(e.multiValueHeaders).forEach(([c,d])=>{let m=t.normalizeHeaderKey(c);if(!Array.isArray(d))throw new Error;d.map(p=>this.#e(p)).forEach(p=>{n.push([m,p])})});let s=e.body;if(e.isBase64Encoded&&s){if(typeof s!="string")throw new Error;let c=Buffer.from(s,"base64").toString();if(Buffer.from(c).toString("base64")!=s)throw b.RED("response body is not properly base64 encoded"),new Error;s=c}n.findIndex(c=>c[0].toLowerCase()=="content-type")==-1&&n.push(["Content-Type",t.contentType.json]);let o=n.findIndex(c=>c[0].toLowerCase()=="content-length");o!=-1&&n.splice(o,1);let a=typeof s;a=="number"||a=="boolean"?s=String(s):s&&a!="string"&&b.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let l=r==204?"0":s?String(Buffer.from(s).byteLength):"0";n.push(["Content-Length",l]),this.res.shouldKeepAlive=!1,this.res.writeHead(r,n),this.res.end(s)};sendV2Response=e=>{this.res.setHeader("Apigw-Requestid",Buffer.from((0,be.randomUUID)()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),e?(typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.keys(e.headers).filter(s=>s!=="Apigw-Requestid"&&s!=="Date").forEach(s=>{this.res.setHeader(s,e.headers[s])}),e.statusCode?(this.res.statusCode=e.statusCode,e.cookies?.length&&this.res.setHeader("Set-Cookie",e.cookies)):this.res.statusCode=200):this.res.statusCode=200;let n="";if(!e)return this.res.end();if(typeof e=="object"&&typeof e.body=="string"&&(n=e.body,e.isBase64Encoded)){let r=Buffer.from(n,"base64").toString();if(Buffer.from(r).toString("base64")!=n)throw b.RED("response body is not properly base64 encoded"),new Error;n=r}typeof e=="string"?(this.res.setHeader("Content-Type",t.contentType.json),n=e):typeof e=="object"&&!e.statusCode&&(this.res.setHeader("Content-Type",t.contentType.json),n=JSON.stringify(e)),this.res.end(n)};sendResponse=e=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(e):this.sendV2Response(e)}};var En=(t,e)=>{let n=e.url.stream?t:void 0;if(n){let r=!1,s=t.write.bind(t),i=t.setHeader.bind(t),o,a,l=m=>{a=a?Buffer.concat([a,m]):m},c=()=>{if(a){let m=_e(a),h=m.statusCode??200;try{let p=ge(m.headers,m.cookies);t.writeHead(h,p)}catch(p){t.writeHead(500,p.headers),t.end?.(x.amzMsgNull),delete p.headers}}else t.writeHead(200)};n.setHeader=(m,h)=>{if(m.toLowerCase()=="content-type"){if(h=="application/vnd.awslambda.http-integration-response")return r=!0,i("Content-Type",x.contentType.json);o=h}return i(m,h)};let d=!1;return n.write=(m,h,p)=>{if(n.headersSent)return s(m,h,p);if(d)try{let g=A.codec.decode(m),y=JSON.parse(g);if(Array.isArray(y))throw new Error("Invalid stream response");return y&&typeof y=="object"?(c(),s(m,h,p)):(t.writeHead(200,{"Content-Type":x.contentType.octet}),t.end())}catch(g){let y=new Error(`When using HttpResponseStream first chunk of .write() must be valid JSON and not be Array. Number and null will respones with 200.
11
- '${e.name}'`);return y.cause=g.message,console.error(y),Z(t)}else if(r)$e(m)?d=!0:l(m);else{if(o==x.contentType.json)try{let y=A.codec.decode(m),f=JSON.parse(y);if(f===null||typeof f=="number")throw new Error(y)}catch(y){let f=new Error(`When 'Content-Type' is 'application/json' first chunk of .write() must be parsable JSON and not be null or number.
12
- '${e.name}'`);return f.cause=y.message,console.error(f),Z(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},In=(t,e,n,r)=>{let s=K(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let l=isNaN(i.statusCode),c=l?500:i.statusCode;if(a=!l&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=ge(i.headers,i.cookies,r);e.writeHead(c,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(c,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function An(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function vt(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function kn(t,e){if(!t.allowMethods?.length)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function Pn(t,e){if(!kn(t,e)||!vt(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var St=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(He(n,s))return;let o=new URL(r,x.dummyHost),a=F(n),l=k.parseNameFromUrl(o.pathname),c=t.handlers.find(f=>f.name==l);if(!c?.url)return n.statusCode=404,n.end("Not Found");let d;if(c.url.cors){if(An(i,s)){let S=Pn(c.url.cors,i),u={"Content-Type":x.contentType.json};return S&&(u["access-control-allow-origin"]=i.origin,c.url.cors.allowMethods.find(v=>v=="*")?u["access-control-allow-methods"]=i["access-control-request-method"]:u["access-control-allow-methods"]=c.url.cors.allowMethods.join(","),c.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=c.url.cors.allowHeaders.join(",")),typeof c.url.cors.maxAge=="number"&&c.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${c.url.cors.maxAge}`),c.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}vt(c.url.cors,i)&&(d={"access-control-allow-origin":i.origin},c.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=c.url.cors.exposeHeaders.join(",")),c.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await D(e,m),p=le.createApgV2Event({req:e,mockEvent:c.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${c.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=En(n,c),S=await c.invoke(p,c.url,void 0,f);if(!S)return n.end();In(S,n,f,d)}catch(f){console.error(f),Z(n,d)}}});var xt=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),l=F(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:S}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(X(o,f,S))}let c=s["x-amz-invocation-type"],d=J(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let m=c=="DryRun"?204:c=="Event"?202:200,h=await D(e),p=Q(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let S=K(f),u=S?f.buffer:f;S?u=A.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){n.writableFinished||(n.setHeader("X-Amz-Function-Error",f.errorType??f.message??""),n.statusCode=200,n.end(JSON.stringify(f)))}}});var ve=require("node:crypto"),wt=require("node:timers/promises");var Rt=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await D(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:l,Timeout:c,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:l,timeout:c,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await(0,wt.setTimeout)(100),n.statusCode=201,n.end(r)}}),Et=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,ve.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),On=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function It(t){let e={};for(let[n,r]of Object.entries(t))On.includes(n)||(e[n]=String(r));return e}var At=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:It(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,ve.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),kt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});var Pt=require("@smithy/eventstream-codec");var Nn=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Dn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),Se=new Pt.EventStreamCodec(Dn,Nn),de=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(Se.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(Se.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(Se.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var Lt=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=F(n),a=k.parseNameFromUrl(i.pathname),l=t.handlers.find(p=>p.name==a),c=await D(e),d=Q(c);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(G(d.message));let m=J(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Y);let h=new de(n);if(l){let p=l.url?.stream??{};try{let g=await l.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(X(a,p,g))}}});var Ot=t=>[Rt(t),At(t),kt(t),xt(t),Lt(t),St(t),Et(t)];var we=process.cwd(),Tn=3,Mn=1024,qn={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},jn=we.split(L.default.sep)[0],Fn=new RegExp(`^.*:${jn}`),Hn=t=>Fn.test(t);process.title="node (exlo)";var pe=class extends ce{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",b.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")).map(r=>r.esEntryPoint),outdir:L.default.join(we,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&b.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(ke({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=Pe(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await xe.default.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,l)=>{let c=`http://localhost:${a}`;b.PINK(`Lambda endpoint: ${c}`),this.endpoints.lambda=c,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=c,this.aws.environment.AWS_ENDPOINT_URL_LAMBDA=c),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",c);o({url:c,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)b.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,l=L.default.extname(a),c=l.slice(1),d=L.default.resolve(a.replace(l,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:c,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??Mn,timeout:o.timeout??this.runtimeConfig.timeout??Tn,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:L.default.basename(a),...this.runtimeConfig.environment,...o.environment,...qn},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);b.RED(`'${e}' is not mounted yet.
13
- Please invoke it after the initial build is completed.`)},invokeSub:[],invokeSuccessSub:[],invokeErrorSub:[],setEnv:(g,y)=>{this.setEnv(e,g,y)},shutdown:async()=>{let g=this.getHandlerByName(`/@invoke/${e}`);g&&await g.shutdown()}};if(p.onError=V(o.onError),p.onError?.kind=="lambda"&&(b.YELLOW("Dead-Letter queue could only be a SNS or SQS service"),delete p.onError),o.destinations&&typeof o.destinations=="object"&&(p.onFailure=V(o.destinations.onFailure),p.onSuccess=V(o.destinations.onSuccess)),p.onInvoke=g=>{p.invokeSub.push(g)},p.onInvokeSuccess=g=>{p.invokeSuccessSub.push(g)},p.onInvokeError=g=>{p.invokeErrorSub.push(g)},process.env.NODE_ENV&&(p.environment.NODE_ENV=process.env.NODE_ENV),s&&(p.environment.AWS_REGION=s,p.environment.AWS_DEFAULT_REGION=s),p.environment.AWS_LAMBDA_FUNCTION_MEMORY_SIZE=p.memorySize,p.url=Oe(o),o.triggers?.length){let{sqs:g,ddb:y}=Te({triggers:o.triggers});p.sqs=g,p.ddb=y}return p}#r(){let e=this.aws.functions;return Object.keys(e).reduce((s,i)=>{let o=this.#n(i);return s.push(o),s},[])}#i(e){let n=Object.keys(e).filter(r=>!r.endsWith(".map")&&e[r].entryPoint).map(r=>{let i=e[r].entryPoint,o="";Hn(i)&&(i=i.split(":").slice(1).join(":")),L.default.isAbsolute(i)||(i=L.default.resolve(i));let a=i.lastIndexOf(".");return a!=-1&&(o=L.default.extname(i),i=i.slice(0,a)),{esOutputPath:L.default.join(we,r),entryPoint:i,ext:o}});for(let r of this.#e){let s=n.find(i=>i?.entryPoint==r.esEntryPoint);s&&(r.esOutputPath=s.esOutputPath,r.entryPoint=`${s.entryPoint}${s.ext}`)}}#s(){let{environment:e,memorySize:n,timeout:r}=this.aws;this.runtimeConfig.memorySize=n,this.runtimeConfig.timeout=r,this.runtimeConfig.environment=e?{...e}:{};let s=Object.keys(process.env).filter(i=>i.startsWith("AWS_"));for(let i of s)this.runtimeConfig.environment[i]=process.env[i];"FORCE_COLOR"in this.runtimeConfig.environment||process.env.FORCE_COLOR?.toLowerCase()==="false"||process.env.FORCE_COLOR?.toLowerCase()==="no"||process.env.FORCE_COLOR==="0"||("COLORTERM"in process.env||process.env.TERM?.includes("256"))&&(this.runtimeConfig.environment.FORCE_COLOR="true")}setEnv(e,n,r){let s=this.#e.findIndex(i=>i.name==e);if(s>-1){this.#e[s].environment[n]=r;let i=this.aws.getFunction(e);i&&(i.environment||(i.environment={}),i.environment[n]=r)}else b.RED(`Can not set env variable '${n}' on '${e}'`)}addLambda(e,n){if(!n.triggers)n.triggers=[];else if(!Array.isArray(n.triggers))throw new Error("Lambda 'triggers' must be an array when defined.");this.#s(),this.aws.functions[e]=n;let r=this.#n(e);this.#e.push(r)}getLambdaByName(e){return this.#e.find(n=>n.name==e)}buildDefineConfigParam(){let e=this;return{stop:async r=>{await this.kill(r)},lambdas:this.#e,addLambda:(r,s)=>{this.addLambda(r,s)},esbuild:xe.default,getServices(){return{s3:e.aws.services.s3,sqs:e.aws.services.sqs,sns:e.aws.services.sns,dynamodb:e.aws.services.dynamodb}},setService(r,s){switch(r){case"s3":e.aws.services.s3=s;break;case"sns":e.aws.services.sns=s;break;case"sqs":e.aws.services.sqs=s;break;case"dynamodb":e.aws.services.dynamodb=s;break;default:break}},setEndpoint:(r,s,i)=>{if(this.endpoints[r]=s,typeof i=="string"){this.aws.environment[i]=s;for(let o of this.#e)this.setEnv(o.name,i,s)}},getEndpoint:r=>this.endpoints[r],getAwsProviderDefaults:()=>({accountId:e.aws.accountId,region:e.aws.region,runtime:e.aws.runtime,memorySize:e.aws.memorySize,timeout:e.aws.timeout,environment:{...e.aws.environment}}),setAwsProviderDefaults:({accountId:r,environment:s,memorySize:i,region:o,runtime:a,timeout:l})=>{r&&(e.aws.accountId=r),s&&(e.aws.environment=s),i&&(e.aws.memorySize=i),o&&(e.aws.region=o),a&&(e.aws.runtime=a),l&&(e.aws.timeout=l)},log:b}}async resolveConfig(){let e=await bt(this.config);if(e?.exportedFunc){let n,{exportedFunc:r,configObjectName:s,configPath:i}=e;if(typeof r[s]=="function")n=r[s];else if(typeof r=="function")n=r;else if(typeof r.default=="function")n=r.default;else throw new Error(`Can not read exlo config at: ${i}`);return n}}onBeforeApplyConfigCallbacks=[];onBeforeApplyConfig(e){this.onBeforeApplyConfigCallbacks.push(e)}async#c(e){for(let n of this.onBeforeApplyConfigCallbacks)await n(e)}async#o(){let e=this.buildDefineConfigParam(),n=Ot(this).map(a=>(a.callback=a.callback.bind(e),a)),r=await this.resolveConfig(),s={};r&&(await this.#c(r),s=await r(e),Array.isArray(s.onKill)&&this.onKill.push(...s.onKill),s.build&&(typeof s.build.shimRequire=="boolean"&&(this.shimRequire=s.build.shimRequire),typeof s.build.optimizeBuild=="boolean"&&(this.optimizeBuild=s.build.optimizeBuild)),typeof s.buildCallback=="function"&&(this.customBuildCallback=s.buildCallback),s.server&&typeof s.server=="object"&&(Array.isArray(s.server.request)&&n.unshift(...s.server.request),typeof s.server.port=="number"&&!this.port&&(this.port=s.server.port),typeof s.server.onReady=="function"&&(this.onReady=s.server.onReady),typeof s.server.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=s.server.setEndpointEnvVar))),this.customOfflineRequests=n;let i=s?.build?.esbuild;if(!i)return;let o=Le(i);Object.keys(o).length&&(this.customEsBuildConfig?this.customEsBuildConfig={...this.customEsBuildConfig,...o}:this.customEsBuildConfig=o)}#a=()=>{let e=this.options.port;isNaN(e)||(this.port=e)};async kill(e){this.buildContext.dispose&&await this.buildContext.dispose();for(let n of Nt.EventSourceMapping.SOURCES)try{await n.disable()}catch(r){console.error(r)}for(let n of this.handlers)n.clear?.();this.stop(e);for(let n of this.onKill)try{await n()}catch(r){console.error(r)}}};async function _n(t){let e=Dt(t);return await e.exlo.start(),await e.waitServer,{port:e.listeningPort,url:e.listeningUrl,endpoints:e.exlo.endpoints,async kill(){await e.exlo.kill()},[Symbol.asyncDispose]:async()=>{await e.exlo.kill()}}}var Re=class{accountId="123456789012";region="us-east-1";timeout=3;memorySize=1024;environment={};services={};functions={};runtime=`node${process.versions.node.split(".")[0]}.x`;getFunction(e){return this.functions[e]}};function Dt(t){let e=new Re,n={};t&&(t.port&&(n.port=t.port),typeof t.debug=="boolean"&&(n.debug=t.debug),t.build&&(typeof t.build.shimRequire=="boolean"&&(n.shimRequire=t.build.shimRequire),typeof t.build.optimizeBuild=="boolean"&&(n.optimizeBuild=t.build.optimizeBuild),t.build.esbuild&&(n.customEsBuildConfig=t.build.esbuild)),t.config&&(n.config=t.config),t.functions&&(e.functions=t.functions),t.defaults&&(t.defaults.environment&&(e.environment=t.defaults.environment),t.defaults.timeout&&(e.timeout=t.defaults.timeout),t.defaults.memorySize&&(e.memorySize=t.defaults.memorySize),t.defaults.runtime&&(e.runtime=t.defaults.runtime),t.defaults.accountId&&(e.accountId=t.defaults.accountId),t.defaults.region&&(e.region=t.defaults.region)));let r=new pe({aws:e},n);typeof t?.onKill=="function"&&r.onKill.push(t.onKill);let s;r.onceServerReady.push(o=>{i.listeningPort=o.port,i.listeningUrl=o.url,s()});let i={listeningPort:0,listeningUrl:"",exlo:r,waitServer:new Promise(o=>{s=o})};return i}0&&(module.exports={createAppRunner,exloVersion,run});
1
+ "use strict";var Wt=Object.create;var z=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var Bt=(t,e)=>{for(var n in e)z(t,n,{get:e[n],enumerable:!0})},Pe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ut(e))!Vt.call(t,s)&&s!==n&&z(t,s,{get:()=>e[s],enumerable:!(r=$t(e,s))||r.enumerable});return t};var A=(t,e,n)=>(n=t!=null?Wt(zt(t)):{},Pe(e||!t||!t.__esModule?z(n,"default",{value:t,enumerable:!0}):n,t)),Jt=t=>Pe(z({},"__esModule",{value:!0}),t);var Qn={};Bt(Qn,{createAppRunner:()=>_t,exloVersion:()=>St,run:()=>Jn});module.exports=Jt(Qn);var L=A(require("node:path")),Ie=A(require("esbuild")),Ht=require("exlo/internal/esm");var fe=A(require("node:path")),ke=require("node:module"),Qt={},W=require,V={};function j(t){if(V[t])return V[t];if(typeof W=="function"&&typeof W.resolve=="function"){let n=fe.default.resolve(W.resolve(t),"../../");return V[t]=n,n}W=(0,ke.createRequire)(new URL(".",Qt.url));let e=fe.default.resolve(W.resolve(t),"../../");return V[t]=e,e}var Le=["aws-sdk","@aws-sdk/*","@angular/core","@angular/platform-browser","@aws-sdk/*","@elastic/elasticsearch","@hapi/joi","@opensearch-project/opensearch","@smithy/*","axios","axios-retry","axios-cache-interceptor","aws-serverless-express","aws-sdk","body-parser","classnames","clsx","cookie-parser","cors","core-js","date-fns","dayjs","express","helmet","joi","koa","leaflet","lodash","mysql","mysql2","mongodb","mongoose","moment","http-proxy","http-proxy-middleware","react","react/*","react-dom","react-dom/*","react-hook-form","react-infinite-scroll-component","react-modal","react-rangeslider","react-responsive","react-select","react-scroll","react-slick","react-lazy-load","react-lazyload","react-redux","react-router","react-router-dom","redux","redux-persist","regenerator-runtime","serve-static","express-session","exlo/*","serverless-http","sequelize","svelte","svelte/*","typeorm","pg","pg-hstore","prop-types","underscore","uuid","vue","xmlbuilder","yup","zod","sharp"];var Kt=t=>`import { createRequire as __crE_ } from "${t}module";import { fileURLToPath as __futP_ } from "${t}url";import { dirname as __dN_ } from "${t}path";global.__filename = __futP_(import.meta.url);global.__dirname = __dN_(__filename);global.require = __crE_(__filename);
2
+ `,Oe=({nodeVersion:t,shimRequire:e,optimizeBuild:n,buildCallback:r,getSockets:s})=>({name:"build-optimizer-plugin",setup(i){let o=!1;if(i.onEnd(async a=>{if(!o&&a?.errors?.length&&process.exit(1),o)for(let c of s())c.writable&&c.destroy();try{await r(a,o,i.initialOptions.format,i.initialOptions.outdir)}catch(c){console.log(c)}o=!0}),n&&(i.initialOptions.external.push(...Le),i.initialOptions.format=="esm"&&(i.initialOptions.mainFields?i.initialOptions.mainFields.includes("module")||(i.initialOptions.mainFields.includes("main")?i.initialOptions.mainFields.unshift("module"):i.initialOptions.mainFields.unshift("module","main")):i.initialOptions.mainFields=["module","main"])),i.initialOptions.format=="esm"&&e){let a=Kt(t<18?"":"node:");i.initialOptions.banner?i.initialOptions.banner.js?i.initialOptions.banner.js=`${a}${i.initialOptions.banner.js}`:i.initialOptions.banner.js=a:i.initialOptions.banner={js:a}}}});var Ne=(t,e)=>(Array.isArray(e.plugins)&&t.plugins.unshift(...e.plugins),Array.isArray(e.external)&&t.external.push(...e.external),Array.isArray(e.entryPoints)&&t.entryPoints.push(...e.entryPoints),"sourcemap"in e&&(t.sourcemap=e.sourcemap),typeof e.sourceRoot=="string"&&(t.sourceRoot=e.sourceRoot),typeof e.format=="string"&&(t.format=e.format),e.outExtension&&typeof e.outExtension=="object"&&!Array.isArray(e.outExtension)&&(t.outExtension=e.outExtension),"sourcesContent"in e&&(t.sourcesContent=e.sourcesContent),typeof e.minify=="boolean"&&(t.minify=e.minify),typeof e.minifyWhitespace=="boolean"&&(t.minifyWhitespace=e.minifyWhitespace),typeof e.minifyIdentifiers=="boolean"&&(t.minifyIdentifiers=e.minifyIdentifiers),typeof e.minifySyntax=="boolean"&&(t.minifySyntax=e.minifySyntax),typeof e.jsx=="string"&&(t.jsx=e.jsx),typeof e.jsxFactory=="string"&&(t.jsxFactory=e.jsxFactory),typeof e.jsxFragment=="string"&&(t.jsxFragment=e.jsxFragment),typeof e.jsxImportSource=="string"&&(t.jsxImportSource=e.jsxImportSource),"jsxDev"in e&&(t.jsxDev=e.jsxDev),"jsxSideEffects"in e&&(t.jsxSideEffects=e.jsxSideEffects),typeof e.outdir=="string"&&(t.outdir=e.outdir),typeof e.outbase=="string"&&(t.outbase=e.outbase),(typeof e.target=="string"||Array.isArray(e.target))&&(t.target=e.target),typeof e.tsconfig=="string"&&(t.tsconfig=e.tsconfig),e.tsconfigRaw&&["string","object"].includes(typeof e.tsconfigRaw)&&(t.tsconfigRaw=e.tsconfigRaw),typeof e.legalComments=="string"&&(t.legalComments=e.legalComments),Array.isArray(e.pure)&&(t.pure=e.pure),Array.isArray(e.drop)&&(t.drop=e.drop),Array.isArray(e.dropLabels)&&t.dropLabels.push(...e.dropLabels),Array.isArray(e.resolveExtensions)&&(t.resolveExtensions=e.resolveExtensions),Array.isArray(e.mainFields)&&(t.mainFields=e.mainFields),Array.isArray(e.nodePaths)&&(t.nodePaths=e.nodePaths),typeof e.ignoreAnnotations=="boolean"&&(t.ignoreAnnotations=e.ignoreAnnotations),typeof e.treeShaking=="boolean"&&(t.treeShaking=e.treeShaking),e.define&&typeof e.define=="object"&&(t.define?t.define={...t.define,...e.define}:t.define=e.define),e.banner&&typeof e.banner=="object"&&(t.banner=e.banner),e.footer&&typeof e.footer=="object"&&(t.footer=e.footer),e.loader&&typeof e.loader=="object"&&(t.loader=e.loader),e.alias&&typeof e.alias=="object"&&(t.alias=e.alias),typeof e.assetNames=="string"&&(t.assetNames=e.assetNames),typeof e.entryNames=="string"&&(t.entryNames=e.entryNames),typeof e.publicPath=="string"&&(t.publicPath=e.publicPath),Array.isArray(e.inject)&&(t.inject=e.inject),typeof e.splitting=="boolean"&&(t.splitting=e.splitting),typeof e.preserveSymlinks=="boolean"&&(t.preserveSymlinks=e.preserveSymlinks),typeof e.keepNames=="boolean"&&(t.keepNames=e.keepNames),e.supported&&typeof e.supported=="object"&&(t.supported=e.supported),Array.isArray(e.conditions)&&(t.conditions=e.conditions),typeof e.absWorkingDir=="string"&&(t.absWorkingDir=e.absWorkingDir),e.mangleProps instanceof RegExp&&(t.mangleProps=e.mangleProps),e.reserveProps instanceof RegExp&&(t.reserveProps=e.reserveProps),typeof e.mangleQuoted=="boolean"&&(t.mangleQuoted=e.mangleQuoted),e.mangleCache&&typeof e.mangleCache=="object"&&(t.mangleCache=e.mangleCache),typeof e.packages=="string"&&(t.packages=e.packages),typeof e.logLevel=="string"&&(t.logLevel=e.logLevel),typeof e.logLimit=="number"&&(t.logLimit=e.logLimit),e.logOverride&&typeof e.logOverride=="object"&&(t.logOverride?t.logOverride={...t.logOverride,...e.logOverride}:t.logOverride=e.logOverride),t);var De=t=>{let e={};return Array.isArray(t.plugins)&&(e.plugins=t.plugins),Array.isArray(t.external)&&(e.external=t.external),"sourcemap"in t&&(e.sourcemap=t.sourcemap),typeof t.sourceRoot=="string"&&(e.sourceRoot=t.sourceRoot),typeof t.format=="string"&&(e.format=t.format),t.outExtension&&typeof t.outExtension=="object"&&!Array.isArray(t.outExtension)&&(e.outExtension=t.outExtension),"sourcesContent"in t&&(e.sourcesContent=t.sourcesContent),typeof t.minify=="boolean"&&(e.minify=t.minify),typeof t.minifyWhitespace=="boolean"&&(e.minifyWhitespace=t.minifyWhitespace),typeof t.minifyIdentifiers=="boolean"&&(e.minifyIdentifiers=t.minifyIdentifiers),typeof t.minifySyntax=="boolean"&&(e.minifySyntax=t.minifySyntax),typeof t.jsx=="string"&&(e.jsx=t.jsx),typeof t.jsxFactory=="string"&&(e.jsxFactory=t.jsxFactory),typeof t.jsxFragment=="string"&&(e.jsxFragment=t.jsxFragment),typeof t.jsxImportSource=="string"&&(e.jsxImportSource=t.jsxImportSource),"jsxDev"in t&&(e.jsxDev=t.jsxDev),"jsxSideEffects"in t&&(e.jsxSideEffects=t.jsxSideEffects),typeof t.outdir=="string"&&(e.outdir=t.outdir),typeof t.outbase=="string"&&(e.outbase=t.outbase),(typeof t.target=="string"||Array.isArray(t.target))&&(e.target=t.target),typeof t.tsconfig=="string"&&(e.tsconfig=t.tsconfig),t.tsconfigRaw&&["string","object"].includes(typeof t.tsconfigRaw)&&(e.tsconfigRaw=t.tsconfigRaw),typeof t.legalComments=="string"&&(e.legalComments=t.legalComments),Array.isArray(t.pure)&&(e.pure=t.pure),Array.isArray(t.drop)&&(e.drop=t.drop),Array.isArray(t.dropLabels)&&(e.dropLabels=t.dropLabels),Array.isArray(t.resolveExtensions)&&(e.resolveExtensions=t.resolveExtensions),Array.isArray(t.mainFields)&&(e.mainFields=t.mainFields),Array.isArray(t.nodePaths)&&(e.nodePaths=t.nodePaths),typeof t.ignoreAnnotations=="boolean"&&(e.ignoreAnnotations=t.ignoreAnnotations),typeof t.treeShaking=="boolean"&&(e.treeShaking=t.treeShaking),t.define&&typeof t.define=="object"&&(e.define=t.define),t.banner&&typeof t.banner=="object"&&(e.banner=t.banner),t.footer&&typeof t.footer=="object"&&(e.footer=t.footer),t.loader&&typeof t.loader=="object"&&(e.loader=t.loader),t.alias&&typeof t.alias=="object"&&(e.alias=t.alias),typeof t.assetNames=="string"&&(e.assetNames=t.assetNames),typeof t.entryNames=="string"&&(e.entryNames=t.entryNames),typeof t.publicPath=="string"&&(e.publicPath=t.publicPath),typeof t.splitting=="boolean"&&(e.splitting=t.splitting),typeof t.preserveSymlinks=="boolean"&&(e.preserveSymlinks=t.preserveSymlinks),Array.isArray(t.inject)&&(e.inject=t.inject),typeof t.keepNames=="boolean"&&(e.keepNames=t.keepNames),t.supported&&typeof t.supported=="object"&&(e.supported=t.supported),Array.isArray(t.entryPoints)&&(e.entryPoints=t.entryPoints),Array.isArray(t.conditions)&&(e.conditions=t.conditions),typeof t.absWorkingDir=="string"&&(e.absWorkingDir=t.absWorkingDir),t.mangleProps instanceof RegExp&&(e.mangleProps=t.mangleProps),t.reserveProps instanceof RegExp&&(e.reserveProps=t.reserveProps),typeof t.mangleQuoted=="boolean"&&(e.mangleQuoted=t.mangleQuoted),t.mangleCache&&typeof t.mangleCache=="object"&&(e.mangleCache=t.mangleCache),typeof t.packages=="string"&&(e.packages=t.packages),t.logOverride&&typeof t.logOverride=="object"&&(e.logOverride=t.logOverride),typeof t.logLevel=="string"&&(e.logLevel=t.logLevel),typeof t.logLimit=="number"&&(e.logLimit=t.logLimit),e};var Te=t=>{if(!t.url)return;let e=t.url.cors;return{kind:"url",proxy:"url",version:2,methods:["ANY"],paths:["/*"],pathsRegex:[],stream:typeof t.url=="object"&&t.url.invokeMode=="RESPONSE_STREAM",cors:e}};var Gt=t=>{if(typeof t=="string"){let e=t.split(":")?.[2],n=t.split("/")?.[1];if(e==="dynamodb"&&n)return n}},Me=t=>{let e={},n=Gt(t.arn);if(n&&(e.TableName=n),!!e.TableName){if(typeof t.batchSize=="number"&&t.batchSize>0&&t.batchSize<=1e4?e.batchSize=t.batchSize:e.batchSize=100,typeof t.enabled=="boolean"?e.enabled=t.enabled:e.enabled=!0,t.startingPosition&&(e.startingPosition=t.startingPosition),typeof t.maximumBatchingWindow=="number"&&t.maximumBatchingWindow>0&&t.maximumBatchingWindow<=300&&(e.maximumBatchingWindow=t.maximumBatchingWindow),typeof t.maximumRecordAgeInSeconds=="number"&&t.maximumRecordAgeInSeconds>=60&&t.maximumRecordAgeInSeconds<=604800&&(e.maximumRecordAgeInSeconds=t.maximumRecordAgeInSeconds),t.maximumRetryAttempts&&t.maximumRetryAttempts>0&&t.maximumRetryAttempts<=1e4&&(e.maximumRetryAttempts=t.maximumRetryAttempts),"bisectBatchOnFunctionError"in t&&(e.bisectBatchOnFunctionError=t.bisectBatchOnFunctionError),t.functionResponseType&&(e.functionResponseType=t.functionResponseType),t.filterPatterns&&(e.filterPatterns=t.filterPatterns),typeof t.tumblingWindowInSeconds=="number"&&(e.tumblingWindowInSeconds=t.tumblingWindowInSeconds),t.onFailureDestination){let r=t.onFailureDestination;if(!r.startsWith("arn:aws"))throw new Error(`Invalid onFailureDestination ARN: ${r}`);e.onFailureDestination=r}return e}};var qe=t=>{let e={},{arn:n,filterPatterns:r,batchSize:s,maximumBatchingWindow:i,functionResponseType:o,enabled:a}=t;if(typeof n=="string"){let c=n.split(":");c.length&&(e.name=c[c.length-1],e.arn=n)}if(r&&(e.filterPatterns=r),s&&(e.batchSize=s),i&&(e.maximumBatchingWindow=i),(o=="ReportBatchItemFailures"||Array.isArray(o)&&o[0]=="ReportBatchItemFailures")&&(e.functionResponseType=["ReportBatchItemFailures"]),typeof a=="boolean"?e.enabled=a:e.enabled=!0,e.name)return e};var B=["lambda","sns","sqs"],je=({triggers:t})=>{let e=[],n=[],r=[],s=[],i=[];for(let o of t)switch(o.source){case"sqs":{let a=qe(o);a&&r.push(a)}continue;case"dynamodb":{let a=Me(o);a&&s.push(a)}continue;default:break}return{ddb:s,endpoints:e,s3:i,sns:n,sqs:r}},J=t=>{if(!(!t||t.type&&!B.includes(t.type)))if(typeof t=="string")if(t.startsWith("arn:")){let[,,e,n,r,s,i]=t.split(":");if(B.includes(e))return{kind:e,name:s=="function"?i:s}}else return{kind:"lambda",name:t};else{let e={};if(typeof t.arn=="string"){let[,,n,r,s,i,o]=t.arn.split(":");e.name=i,B.includes(n)&&(e.kind=n)}else if(B.includes(t.type)&&t.arn){e.kind=t.type;let[n,r]=Object.entries(t.arn)?.[0];if(!n||!r)return}if(e.kind&&e.name)return e}};var he=A(require("node:path"));var Fe=require("node:child_process"),He=require("node:fs"),_e=require("node:http"),Ce=A(require("node:path")),Yt=new URLPattern({pathname:"/2018-06-01/runtime/invocation/:awsRequestId/:returnType"}),F=class t{constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},c,l){this.cwd=l;this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=c,this.bin=Ce.default.resolve(i),this.mount=async()=>{await this.createOwnedServer(),await this.load()},this.unmount=d=>{this.runner?.kill(),this.runner=void 0,this.isMounted=!1,this.server?.close(),this.server?.closeAllConnections(),this.watcher?.close()},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>{this.isMounted||await this.load();let g,y,f=new Promise((u,v)=>{g=u,y=v}),b={id:p,event:d,resolve:g,inFlight:!1,reject:y};return this.invocations.push(b),this.handleInvoke(),f}}static async collectBody(e){let n=Buffer.alloc(0);return e.on("data",r=>{n=Buffer.concat([n,r])}),new Promise(r=>{e.on("end",async()=>{r(n?n.toString("utf-8"):void 0)})})}invoke;mount;unmount;name;timeout;memorySize;environment;handlerName;runtime;bin;runner;isMounted=!1;watchers=[];filesTime=new Map;port;watcher;emitRebuild;invocations=[];queue=[];getWaitingInvocation(){return this.invocations.find(e=>!e.inFlight)}server=void 0;async createOwnedServer(){let e=(0,_e.createServer)(async(n,r)=>{let{method:s,url:i,headers:o}=n;if(s=="POST"){let a=Yt.exec(i,"http://localhost:3000"),c=a?.pathname.groups.awsRequestId,l=a?.pathname.groups.returnType;if(!(c&&(l=="response"||l=="error"))){r.statusCode=400,r.end();return}let d=this.invocations.findIndex(p=>p.id==c);if(d==-1){r.statusCode=400,r.end();return}let m=await t.collectBody(n),h=this.invocations[d];this.invocations.splice(d,1),await new Promise(p=>{r.statusCode=202,r.end(()=>{l=="response"?h.resolve(m):h.reject(m),p(void 0)})});return}if(s=="GET"&&i=="/2018-06-01/runtime/invocation/next"){let a=this.getWaitingInvocation();if(!a){this.queue.push(r);return}a.inFlight=!0,r.setHeader("Lambda-Runtime-Aws-Request-Id",a.id),r.end(JSON.stringify(a.event));return}r.statusCode=400,r.end()});e.keepAliveTimeout=0,await new Promise(n=>{e.listen(n)}),e.unref(),this.port=e.address().port,this.server=e}load=()=>(this.watcher||(this.watcher=(0,He.watch)(this.bin,(e,n)=>{this.emitRebuild()}),this.watcher.unref()),this.runner=(0,Fe.spawn)(this.bin,{env:{...this.environment,AWS_LAMBDA_RUNTIME_API:`127.0.0.1:${this.port}`},stdio:"inherit",cwd:this.cwd}),this.runner.on("error",e=>{console.error("Failed to run custome runtime.",e)}),this.runner.pid||(console.error(`Can not find custome runtime ${this.bin}`),process.exit(1)),new Promise(e=>{this.runner.once("spawn",()=>{this.isMounted=!0,e(void 0)})}));onComplete=e=>{let n=this.invocations.findIndex(r=>r.id==e);n!=-1&&this.invocations.splice(n,1)};handleInvoke(){try{let e=this.getWaitingInvocation();if(!e||!this.queue.length)return;let n=this.queue[0];n||console.error("This is a bug in exlo, please report!"),n.setHeader("Lambda-Runtime-Aws-Request-Id",e.id),this.queue.splice(this.queue.findIndex(r=>r==n),1),n.end(JSON.stringify(e.event))}catch(e){console.error(e)}}};var N=class t extends F{static llrtEnvs={};static llrtBoostrapPath="bootstrap";constructor(e,n){let r=he.default.basename(e.handlerPath);e.handlerPath=t.llrtBoostrapPath;let s=he.default.dirname(e.esOutputPath);super({...e,environment:{...t.llrtEnvs,...e.environment,LAMBDA_HANDLER:r}},n,s)}};var gt=require("node:crypto"),bt=A(require("node:http")),vt=A(require("node:inspector")),ve=require("node:os");var ze=require("node:crypto");var Q=!1,Xt=t=>{Q=t},Zt=()=>Q,H=(t,e)=>{Q&&console.log(`\x1B[${t}m${e}\x1B[0m`)},en=t=>console.log(`\x1B[31m${t}\x1B[0m`),tn=t=>H("32",t),nn=t=>H("33",t),rn=t=>H("36",t),sn=t=>H("90",t),on=t=>H("94",t),an=t=>H("95",t),ln=t=>Q?console.log(t):void 0,S={GREEN:tn,YELLOW:nn,CYAN:rn,BR_BLUE:on,RED:en,GREY:sn,PINK:an,setDebug:Xt,getDebug:Zt,info:ln};var We="application/vnd.awslambda.http-integration-response",P=class t{buffer;_isHttpIntegrationResponse;_metaDelimiter;_endDelimiter;_ct;_isStreamResponse=!0;#e;static codec=new TextDecoder;static splitMessage=(e,n)=>{if(!e)return;let r=Array.from(e.values()),s=null;if(n)s=n;else for(let i=0;i<r.length;i++)if(r[i]===0&&[r[i+1],r[i+2],r[i+3],r[i+4],r[i+5],r[i+6],r[i+7]].every(c=>c===0)){s=i;break}if(s)return new Uint8Array(r.slice(0,s))};constructor(e){this._isHttpIntegrationResponse=!1,this._metaDelimiter=0,this._endDelimiter=0,this.#e=e}setHeader(e,n){this._isHttpIntegrationResponse=!this.buffer&&n==We&&(!this._ct||this._ct==We),this._ct=n}write(e,n){!this._isHttpIntegrationResponse&&!this._metaDelimiter&&(this._metaDelimiter=e.byteLength),this.#t(e)}end(e){this.buffer&&(this._endDelimiter=this.buffer.byteLength),e&&this.#t(e)}destroy(){}#t(e){this.buffer=typeof this.buffer>"u"?e:Buffer.concat([this.buffer,e])}getParsedResponse(){if(!this.#e)return;let e=this.#e.kind;if(e=="alb")return this.#n();if(e=="url")return this.#i();if(e=="apg")return this.#r()}#n(){let e=this._isHttpIntegrationResponse?t.splitMessage(this.buffer):this.buffer,n;return e&&(n=this.#s(e)),n}#r(){if(this._isHttpIntegrationResponse)return S.RED("awslambda.HttpResponseStream.from() is not supported with API Gateway"),{statusCode:500,headers:{"Content-Type":x.contentType.json},body:x.httpErrMsg};if(this.buffer)return this.#s(this.buffer)}#i(){let e=t.splitMessage(this.buffer,this._isHttpIntegrationResponse?void 0:this._metaDelimiter),n;return e&&(n=this.#s(e)),n}#s(e){let n=t.codec.decode(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return n}};var $e="<html><head><title>404 Not Found</title></head><body><center><h1>404 Not Found</h1></center></body></html>",Ue="<html><head><title>400 Request Header Or Cookie Too Large</title></head><body><center><h1>400 Bad Request</h1></center><center>Request Header Or Cookie Too Large</center></body></html>";var cn=["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"],dn=JSON.stringify({Message:null}),K=t=>{if(t)try{let e=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(e)}catch{return new Error("InvalidRequestContentException")}},Ve=(t,e)=>{if(!cn.includes(e))return t.statusCode=403,t.setHeader("Content-Type","application/json"),t.end(dn),!0},T=async(t,e)=>{let n=Buffer.alloc(0);return t.on("data",s=>{n=Buffer.concat([n,s])}),await new Promise(s=>{t.on("end",async()=>{s(n?n.toString(e?"base64":"utf-8"):void 0)})})},G=t=>{let e;try{e=JSON.parse(t)}catch(n){e?.length?e=n:e={}}return e},Y=t=>t instanceof P,Be=t=>{let e,n=Buffer.from(t).toString();try{e=JSON.parse(n)}catch{e=n}return e},_=t=>{let e=(0,ze.randomUUID)();return t.setHeader("x-amzn-RequestId",e),e},X=t=>JSON.stringify({Type:"User",message:`Could not parse request body into json: Could not parse payload into json: ${t}: was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')`}),Z=JSON.stringify({Type:null,message:"Client context must be a valid Base64-encoded JSON object."}),ee=(t,e,n)=>JSON.stringify({Type:"User",message:`Function not found: arn:aws:lambda:${e}:${n}:function:${t}`}),te=(t,e)=>{if(!t.writableFinished){if(t.statusCode=502,!t.headersSent&&(t.setHeader("Content-Type","application/json"),e))for(let[n,r]of Object.entries(e))t.setHeader(n,r);t.end("Internal Server Error")}},Je=t=>t.byteLength==8&&Array.from(t.values()).every(e=>e===0);var xr=new Error(Ue);var Qe=t=>t.charAt(0).toUpperCase()+t.slice(1);var x=class t{static apiId="";static accountId="";static port=3e3;static serve;static contentType={json:"application/json",text:"text/plain; charset=utf-8",octet:"application/octet-stream"};static keepAlive=["Connection","keep-alive"];static dummyHost="http://localhost:3003";static httpErrMsg='{"message":"Internal Server Error"}';static apigJsonParseErrMsg='{"message":"[Unknown error parsing request body]"}';static apigForbiddenErrMsg='{"message":"Forbidden"}';static amzMsgNull='{"message":null}';static apgTimeoutMsg='{"message": "Endpoint request timed out"}';static unavailable='{"message":"Service Unavailable"}';static timeoutRegex=/after.\d+.*seconds/;static apgRequestTimeout=30;static normalizeHeaderKey=e=>e.toLowerCase().split("-").map(Qe).join("-");static getMultiValueHeaders=e=>{let n={},r=e.filter((i,o)=>o%2==0).map(i=>i.toLowerCase()),s=e.filter((i,o)=>o%2!==0);return r.forEach((i,o)=>{i!="x-mock-type"&&(n[i]?n[i].push(s[o]):n[i]=[s[o]])}),n};static getIsBase64Encoded=e=>{let n=e["content-type"];return e["content-encoding"]||!n?!0:!(n.startsWith("application/json")||n.startsWith("application/xml")||n.startsWith("application/javascript")||n.startsWith("text/"))};static knownHeaders=["accept","accept-encoding","user-agent","host","via","content-length"];static getApiGV1Headers(e,n){let{rawHeaders:r}=e,s,i={"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port)};for(let l=0;l<r.length;){let d=r[l],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){l=l+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[l+1];i[d]=h,m=="x-api-key"&&(s=h),l=l+2}let o={};for(let l of Object.keys(i).sort((d,m)=>d.localeCompare(m)))o[l]=i[l];let a={"X-Forwarded-For":[e.socket.remoteAddress],"X-Forwarded-Proto":["http"],"X-Forwarded-Port":[String(t.port)]};for(let l=0;l<r.length;){let d=r[l],m=d.toLowerCase();if(["connection","x-mock-type"].includes(m)){l=l+2;continue}this.knownHeaders.includes(m)&&(d=this.normalizeHeaderKey(m));let h=r[l+1];a[d]?a[d].push(h):a[d]=[h],l=l+2}let c={};for(let l of Object.keys(a).sort((d,m)=>d.localeCompare(m)))c[l]=a[l];return{headers:o,multiValueHeaders:c,apiKey:s}}static getCustomHeaders(e,n){let{headers:r}=e;return delete r["x-mock-type"],delete r.connection,{"X-Forwarded-For":e.socket.remoteAddress,"X-Forwarded-Proto":"http","X-Forwarded-Port":String(t.port),...r}}static getPathParameters(e,n){let r=e.paths[0].split("/"),s=n.pathname.split("/"),i={};return r.forEach((o,a)=>{o.startsWith("{")&&o.endsWith("}")&&!o.endsWith("+}")&&(i[o.slice(1,-1)]=s[a])}),i}static normalizeSearchParams=(e,n)=>{let r={};Array.from(e.keys()).forEach(o=>{let a=e.getAll(o).map(l=>l.toLowerCase()),c=o.toLowerCase();a?r[c]?r[c].push(...a):r[c]=a:r[c]||(r[c]=void 0)});let s="",i=n.indexOf("?");return i!=-1&&(s=n.slice(i+1)),r.toString=()=>s,r};static getMultiValueQueryStringParameters=e=>{let n={};e.delete("x_mock_type");for(let r of Array.from(new Set(e.keys())))n[r]=e.getAll(r).map(encodeURI);return n};static isEndpointTimeoutError=e=>{if(!e)return;let n=e.match(this.timeoutRegex)?.[0];if(n){let r=n.split(" ")[1];if(!isNaN(r))return Number(r)>=t.apgRequestTimeout}}};var tt=require("exlo/internal/esm");var Ge=require("exlo/internal/esm");var ne=class{constructor(e,n,r,s,i){this.MaximumBatchingWindowInSeconds=e;this.BatchSize=n;this.lambdaName=r;this.handlers=s;this.onInvokeFinished=i}available=!0;#e=[];#t=!1;get messages(){return this.#e}#n(){setTimeout(async()=>{this.available=!1,this.#t||await this.#r()},this.MaximumBatchingWindowInSeconds*1e3)}async setRecord(e){this.#e.length||this.#n(),this.#e.push(e),(this.#e.length==this.BatchSize||!this.available)&&(this.available=!1,await this.#r())}async#r(){this.#t=!0;let e=this.#e,n=this.handlers.find(r=>r.name==this.lambdaName);try{let r=await n.invoke({Records:this.#e});await this.onInvokeFinished(e,r)}catch{}}};var Ye=10,Xe=0,pn=(t,e,n)=>t.receiveMessage({QueueUrl:e,AttributeNames:["All"],MessageAttributeNames:["All"],MaxNumberOfMessages:n}),mn=(t,e)=>t.getQueueAttributes({QueueUrl:e,AttributeNames:["All"]}),Ke=async(t,e,n)=>{for(let r of et(n,10)){if(!r.length)continue;let s=r.map((i,o)=>({Id:`id-${o+1}`,ReceiptHandle:i}));try{await t.deleteMessageBatch({QueueUrl:e,Entries:s})}catch{}}},un=t=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){e[n]={};let{StringValue:s,BinaryValue:i,DataType:o}=r;o.startsWith("B")?e[n].binaryValue=i:e[n].stringValue=s,e[n].stringListValues=[],e[n].binaryListValues=[],e[n].dataType=o}return e},fn=(t,e)=>{let{MessageId:n,Body:r,MD5OfBody:s,ReceiptHandle:i,Attributes:o,MessageAttributes:a,MD5OfMessageAttributes:c}=t,l={messageId:n,receiptHandle:i,body:r,attributes:o,messageAttributes:un(a)};return c&&(l.md5OfMessageAttributes=c),l.md5OfBody=s,l.eventSource="aws:sqs",l.eventSourceARN=e,l.awsRegion=e.split(":")[3],l},hn=(t,e)=>t.map(n=>fn(n,e)),re=class extends Ge.EventSourceMapping{constructor(n,r,s){super(n);this.config=n;this.handlers=r;this.sqsClient=s;let i=this.config.EventSourceArn.split(":");this.QueueName=i[i.length-1],this.#n=this.config.FunctionResponseTypes?.[0]=="ReportBatchItemFailures"}#e=[];QueueName="";QueueUrl="";#t;#n;async onInvokeFinished(n,r){let s=n.map(i=>i.receiptHandle);this.#n&&(s=Ze(n,r)),await Ke(this.sqsClient,this.QueueUrl,s)}#r(){let n=this.#e.find(s=>s.available);if(n)return n;let r=new ne(this.config.MaximumBatchingWindowInSeconds,this.config.BatchSize,this.config.FunctionName,this.handlers,this.onInvokeFinished.bind(this));return this.#e.push(r),r}async#i(n){for(let r of n)await this.#r().setRecord(r)}async init(){if(!this.sqsClient)return;let{QueueUrl:n}=await this.sqsClient.getQueueUrl({QueueName:this.QueueName});this.QueueUrl=n,await this.enable()}#s=1500;cleanBatchs(){for(let n=0;n<this.#e.length;n++)this.#e[n].available||this.#e.splice(n,1)}async#l(){let n=0,r=2e3,s=async()=>{try{let{Attributes:i}=await mn(this.sqsClient,this.QueueUrl);if(!Number(i.ApproximateNumberOfMessages))n++,this.#s<=2e4&&(this.#s+=200),n==5&&(r=2e3);else{n=0,r=400;let a=this.#s;this.#s=350,a>=1600&&await this.#a(!0)}}catch{r=2e3}this.cleanBatchs(),this.#t=setTimeout(s,r)};await s()}#o;async#a(n){n&&clearTimeout(this.#o);let r=async()=>{if(!this.config.Enabled){this.State=="Disabling"&&(this.State="Disabled");return}try{let{Messages:s}=await pn(this.sqsClient,this.QueueUrl,this.config.BatchSize<=10?this.config.BatchSize:10);if(s){let i=hn(s,this.config.EventSourceArn),o=await this.#c(i);await this.#i(o)}}catch{}this.#o=setTimeout(r,this.#s)};await r()}async enable(){this.State="Enabling";try{await this.#l(),this.config.Enabled=!0,this.State="Enabled",await this.#a()}catch(n){console.error(n)}}disable(){this.config.Enabled=!1,clearTimeout(this.#t),this.State="Disabling"}async#c(n){let r=n.map(a=>{let c={...a};try{c.body=JSON.parse(c.body)}catch{}return c}),[s,i]=this.filterRecords(r);await Ke(this.sqsClient,this.QueueUrl,i.map(a=>a.receiptHandle));let o=[];for(let a of s)o.push(...n.filter(c=>c.messageId==a.messageId));return o}};var nt=async(t,e)=>{let{accountId:n,region:r,services:s}=e;for(let i of t)for(let o of i.sqs){if(typeof o.arn!="string")throw new Error("SQS Event Source Mapping must have arn string");let a=o.arn;a.startsWith("arn:aws:sqs:")||(a=`arn:aws:sqs:${r}:${n}:${o.name}`);let c;if(Array.isArray(o.filterPatterns)){c=[];for(let d of o.filterPatterns)c.push({Pattern:JSON.stringify(d)});c.length||(c=void 0)}let l=new re({BatchSize:typeof o.batchSize=="number"?o.batchSize:Ye,Enabled:o.enabled,EventSourceArn:a,FunctionName:i.name,FunctionResponseTypes:o.functionResponseType,FilterCriteria:c?{Filters:c}:void 0,MaximumBatchingWindowInSeconds:typeof o.maximumBatchingWindow=="number"?o.maximumBatchingWindow:Xe},t,s.sqs);if(tt.EventSourceMapping.SOURCES.push(l),l.config.Enabled)try{await l.init()}catch(d){S.RED(`Failed to start EventSourceMapping ${l.config.EventSourceArn}
3
+ Please verify provided SQS Client validity.`),console.error(d)}}},yn=/(-|\w+)/g,gn=t=>t.length<81&&t.replace(yn,"")=="",Ze=(t,e)=>{if(typeof e>"u"||e===null||typeof e=="object"&&(e.batchItemFailures===null||Array.isArray(e.batchItemFailures)&&!e.batchItemFailures.length))return t.map(r=>r.receiptHandle);let n=[];if(typeof e=="object"&&Array.isArray(e.batchItemFailures)){if(e.batchItemFailures.some(r=>!r.itemIdentifier||!gn(r.itemIdentifier)||!t.find(s=>s.messageId==r.itemIdentifier)))throw new Error("ReportBatchItemFailures: complete failure.");return t.forEach(r=>{e.batchItemFailures.find(i=>i.itemIdentifier==r.messageId)||n.push(r.receiptHandle)}),n}},et=(t,e)=>{let n=[];for(let r=0;r<t.length;r+=e){let s=t.slice(r,r+e);n.push(s)}return n};var ct=require("node:crypto");var rt=A(require("node:http")),bn=t=>{switch(t.kind){case"sns":return"@sns/parsed/";case"sqs":return"@sqs";case"lambda":return`@invoke/${t.name}/`;default:break}},st=(t,e)=>{let n=bn(e);if(!n)return;let r={"Content-Type":e.kind=="sqs"?"application/x-www-form-urlencoded":"application/json"};return rt.default.request(`http://localhost:${t}/${n}`,{method:"POST",headers:r})},it=({event:t,payload:e,requestId:n,lambdaName:r,success:s})=>{let i={version:"1.0",timestamp:"2023-02-25T13:25:04.688Z",requestContext:{requestId:n,functionArn:`arn:aws:lambda:eu-west-3:000000000000:function:${r}:$LATEST`,condition:s?"Success":"RetriesExhausted",approximateInvokeCount:1},requestPayload:t,responseContext:{statusCode:200,executedVersion:"$LATEST"},responsePayload:e};return s||(i.responseContext.functionError="Unhandled"),JSON.stringify(i)},vn=({topicName:t,event:e,payload:n,requestId:r,success:s,lambdaName:i})=>{let o="";if(s)o=it({event:e,payload:n,requestId:r,success:s,lambdaName:i});else if(typeof e=="string")o=e;else try{o=JSON.stringify(e)}catch(c){console.log(c)}let a={TopicArn:`arn:aws:sns:eu-west-3:000000000000:${t}`,Message:o,Action:"Publish",Version:"2010-03-31",MessageAttributes:{}};return s||(a.MessageAttributes={RequestID:{Type:"String",Value:r},ErrorCode:{Type:"String",Value:"200"},ErrorMessage:{Type:"String",Value:n.errorMessage}}),JSON.stringify(a)},Sn=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{let o=new URLSearchParams;o.append("QueueUrl",t.name),o.append("Action","SendMessage");let a=e;try{a=JSON.stringify(a)}catch{}return o.append("MessageBody",a),i||(o.append("MessageAttribute.1.Name","RequestID"),o.append("MessageAttribute.1.Value.StringValue",r),o.append("MessageAttribute.1.Value.DataType","String"),o.append("MessageAttribute.1.Name","ErrorCode"),o.append("MessageAttribute.1.Value.StringValue","200"),o.append("MessageAttribute.1.Value.DataType","Number"),o.append("MessageAttribute.1.Name","ErrorMessage"),o.append("MessageAttribute.1.Value.StringValue",n.errorMessage),o.append("MessageAttribute.1.Value.DataType","String")),o.toString()},ot=({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i})=>{switch(t.kind){case"sns":return vn({topicName:t.name,event:e,payload:n,requestId:r,success:i,lambdaName:s});case"lambda":return it({event:e,payload:n,requestId:r,lambdaName:s,success:i});case"sqs":return Sn({destination:t,event:e,payload:n,requestId:r,lambdaName:s,success:i});default:return""}},ye=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=st(e,t);if(!o)return;o.end(ot({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!1}))}catch{}},at=({destination:t,LOCAL_PORT:e,event:n,payload:r,requestId:s,lambdaName:i})=>{try{let o=st(e,t);if(!o)return;o.end(ot({destination:t,event:n,payload:r,requestId:s,lambdaName:i,success:!0}))}catch{}};var xn=1080*1e3,wn=new Set(["async","ddb","kinesis","s3","sns","sqs"]),lt=t=>typeof t?.kind=="string"?wn.has(t.kind)||t.async:!1,$=class t{name;runtime;sqs;ddb;url;timeout;memorySize;environment;handlerPath;handlerName;esEntryPoint;esOutputPath;entryPoint;onError;onSuccess;onFailure;invokeSub;invokeSuccessSub;invokeErrorSub;#e;runner;static ENABLE_TIMEOUT=!0;constructor({name:e,runtime:n,timeout:r,memorySize:s,environment:i,handlerPath:o,handlerName:a,esEntryPoint:c,esOutputPath:l,entryPoint:d,sqs:m,ddb:h,url:p,invokeSub:g,invokeSuccessSub:y,invokeErrorSub:f,onError:b,onSuccess:u,onFailure:v,runner:w}){this.name=e,this.runtime=n,this.sqs=m,this.ddb=h,this.url=p,this.timeout=r,this.memorySize=s,this.environment=i,this.handlerPath=o,this.handlerName=a,this.esEntryPoint=c,this.esOutputPath=l,this.entryPoint=d,this.invokeSub=g,this.invokeSuccessSub=y,this.invokeErrorSub=f,this.onError=b,this.onSuccess=u,this.onFailure=v,this.runner=w}handleErrorDestination(e,n,r,s){if(this.runner.onComplete(s),this.invokeErrorSub.forEach(async i=>{try{await i(e,r,n)}catch{}}),lt(n)){let i={LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name};this.onError&&ye({...i,destination:this.onError}),this.onFailure&&ye({...i,destination:this.onFailure})}}handleSuccessDestination(e,n,r,s){this.runner.onComplete(s),this.onSuccess&&lt(n)&&at({destination:this.onSuccess,LOCAL_PORT:this.environment.LOCAL_PORT,event:e,payload:r,requestId:s,lambdaName:this.name}),this.invokeSuccessSub.forEach(async i=>{try{await i(e,r,n)}catch{}})}async invoke(e,n,r,s){let i=(0,ct.randomUUID)();this.runner.isMounted||(S.BR_BLUE(`\u2744\uFE0F Cold start \u03BB '${this.name}'`),await this.runner.mount());for(let a of this.invokeSub)try{let c=await a(e,n);typeof c!="function"&&(e=c)}catch{}let o=this.#n(i,e,n);try{let a=await new Promise(async(c,l)=>{let d;t.ENABLE_TIMEOUT&&(d=setTimeout(()=>{s?.destroy(),this.runner.onComplete(i,!0),S.RED(`'${this.name}' | ${i}: Request failed`),l({errorType:"Unhandled",errorMessage:`${new Date().toISOString()} ${i} Task timed out after ${this.timeout} seconds`})},this.timeout*1e3));try{let m=await this.runner.invoke({event:e,awsRequestId:i,info:n,clientContext:r,response:s});clearTimeout(d),c(m)}catch(m){clearTimeout(d),l(m)}});return this.#t(),t.#r(o,this.name),this.handleSuccessDestination(e,n,a,i),a}catch(a){throw this.handleErrorDestination(e,n,a,i),this.runner.unmount(!0),this.#t(),a}}clear=()=>{clearTimeout(this.#e),this.runner.unmount()};async shutdown(){clearTimeout(this.#e),await this.runner.unmount(!0)}#t=()=>{clearTimeout(this.#e),this.#e=setTimeout(()=>{this.runner.unmount(!0)},xn)};#n=(e,n,r)=>{let s=n?.httpMethod??n?.method??"",i=n?.path??n?.rawPath??"";i&&(i=decodeURI(i));let o=`${s} ${i}`,a=new Date;S.CYAN(`${a.toLocaleDateString()} ${a.toLocaleTimeString()} requestId: ${e} | '${this.name}' ${o}`),S.GREY(this.entryPoint);let c="";return typeof r?.kind=="string"&&(c=` (${r.kind.toUpperCase()})`),S.YELLOW(`\u03BB payload${c}:`),S.info(n),process.hrtime()};static#r=(e,n)=>{let r=process.hrtime(e),s=`${r[0]},${r[1]}s`,i=`\u231B\uFE0F \u03BB '${n}' execution time: ${s}`;setTimeout(()=>{S.YELLOW(i)},400)}};var se=class{err;constructor(e){this.err=new Error(`Local invoke of ${e} runtime is currently not supported by exlo.`)}isMounted=!0;mount=()=>{};unmount=()=>{};invoke=async()=>{throw this.err};onComplete=()=>{}};var dt=require("node:events"),pt=A(require("node:path")),mt=require("node:worker_threads");var Rn=pt.default.resolve(j("exlo"),"./dist/lib/runtime/runners/node/index.js"),ie=class extends dt.EventEmitter{_worker;isMounted=!1;_isLoading=!1;invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;handlerName;esOutputPath;hasFatalError;constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,esOutputPath:a}){super(),this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerPath=i,this.handlerName=o,this.esOutputPath=a,this.mount=async()=>{this._isLoading?(this.setMaxListeners(0),await new Promise((c,l)=>{this.once("loaded",d=>{d?c(void 0):l()})})):this.isMounted||(this._isLoading=!0,await this.importHandler(),this._worker.on("message",c=>{let{channel:l,data:d,awsRequestId:m,type:h,encoding:p}=c;l=="uncaught"?(this._worker.terminate(),this.isMounted=!1,this._isLoading=!1,S.RED(`${h} Uncaught exceptions`),console.error(d.error),d.solution&&(S.BR_BLUE("Solution:"),console.log(d.solution))):l=="fail"?(this.emit(m,l,d,h,p),this.unmount()):this.emit(m,l,d,h,p)}))},this.unmount=()=>{this._worker?.terminate(),this.isMounted=!1,this._isLoading=!1},this.invoke=async({event:c,info:l,clientContext:d,response:m,awsRequestId:h})=>new Promise((p,g)=>{this._worker.postMessage({channel:"exec",data:{event:c,clientContext:d},awsRequestId:h});let y=m??new P(l);function f(b,u,v,w){switch(b){case"return":case"succeed":case"done":this.removeListener(h,f),p(u);break;case"fail":this.removeListener(h,f),g(u);break;case"stream":v=="write"?y.write(u,w):v=="ct"?y.setHeader("Content-Type",u):v=="timeout"?(this.removeListener(h,f),y.destroy(),g(u)):(this.removeListener(h,f),y.end(u),p(y instanceof P?y:void 0));break;default:this.removeListener(h,f),g(new Error("Unknown error"));break}}this.on(h,f)})}async importHandler(){await new Promise((e,n)=>{let r={name:this.name,env:this.environment,execArgv:["--enable-source-maps"],workerData:{name:this.name,timeout:this.timeout,memorySize:this.memorySize,esOutputPath:this.esOutputPath,handlerPath:this.handlerPath,handlerName:this.handlerName,debug:S.getDebug()}};this._worker=new mt.Worker(Rn,r),this._worker.setMaxListeners(0),this._worker.once("message",s=>{let{channel:i,data:o}=s;i=="import"?(this._worker.setMaxListeners(55),this.setMaxListeners(10),this.isMounted=!0,this._isLoading=!1,this.emit("loaded",!0),e(void 0)):i=="fatal"&&n(o)}),this._worker.postMessage({channel:"import"})})}onComplete=(e,n)=>{this._worker?.postMessage({channel:"complete",awsRequestId:e,timeout:n})}};var ae=require("node:child_process"),ft=require("node:fs"),ge=require("node:fs/promises"),C=A(require("node:path"));var In=process.cwd();function ut(t){let e="";try{e=(0,ae.execSync)(t,{encoding:"utf-8"})}catch{}return e}var oe=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;pyModulePath;handlerDir;handlerName;handlerFileAbsolutePath;runtime;bin;python;isMounted=!1;watchers=[];filesTime=new Map;watcherListener;emitRebuild;static wrapper=C.default.resolve(j("exlo"),"./src/lib/runtime/runners/python/index.py");static DELIMITER="__|response|__";static DELIMITEREND="__|responseEnd|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";static WATCHEND="__|watchEnd|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},c){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=c;let l=C.default.resolve(i);this.handlerDir=C.default.dirname(l),this.handlerPath=C.default.basename(l,`.${this.handlerName}`),this.pyModulePath=`${this.handlerDir}/${this.handlerPath}`.replace(In,"").replace(/\/|\\/g,".").slice(1),this.handlerFileAbsolutePath=l.replace(`.${this.handlerName}`,".py"),this.mount=async()=>{if(this.python)return;let d=`${this.handlerDir}/${this.handlerPath}.py`;try{await(0,ge.access)(d),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${d}"`),process.exit(1)}},this.unmount=d=>{d&&(this.python?.kill(),this.python=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),b="",u=w=>{let R=null,I=w.toString();try{let O=I.includes(t.WATCH);if(O&&this.setWatchFiles(I),I.startsWith(t.DELIMITER)&&I.includes(t.DELIMITEREND)){let E=I.split(t.DELIMITER),M=E[E.length-1].split(t.DELIMITEREND)[0];if(E.length>1){let q;O?q=E[0].split(t.WATCHEND)[1]:q=E.slice(0,-1).join(`
4
+ `),q.trim()&&console.log(q)}M&&(R=JSON.parse(M)),this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),g(R)}else if(I.startsWith(t.DELIMITER))b=I.slice(t.DELIMITER.length);else if(I.includes(t.DELIMITEREND)){let E=I.slice(0,I.indexOf(t.DELIMITEREND)),M=JSON.parse(`${b}${E}`);this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),g(M)}else if(b)b+=I;else if(!b&&I.trim()){let E;if(O){let M=I.split(`
5
+ `),q=M.findIndex(Ct=>Ct.startsWith(t.WATCH));E=M.slice(0,q).join(`
6
+ `)}else E=I;E.trim()&&console.log(E)}}catch(O){console.log("err",O),y(O)}};this.python.stdout.on("data",u);let v=w=>{let R=w.toString();if(R.includes(t.ERR_RESPONSE))try{R=JSON.parse(R.split(t.ERR_RESPONSE)[1]),R.requestId=p}catch{}finally{this.python.stdout.removeListener("data",u),this.python.stderr.removeListener("data",v),y(R)}else console.log(R)};this.python.stderr.on("data",v),this.python.stdin.write(`${f}
7
+ `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),s=n[n.length-1].split(t.WATCHEND)[0],i=JSON.parse(s).map(o=>`${o.replace(/\./g,C.default.sep)}.py`);for(let o of i)try{await(0,ge.access)(o),this.watchers.push((0,ft.watch)(o,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};findPython(){let[e]=this.runtime.split("."),n=e.split("python")[1];if(ut(`${e} --version`))return e;let r=ut("python --version");if(!r)throw new Error("Can not find python on your OS. Make sure it is installed.");if(n){let s=r.split(" ")[1]?.split(".")[0];s&&s!=n&&S.YELLOW("found python binary but with different version")}return"python"}load=()=>{this.bin||(this.bin=this.findPython()),this.python=(0,ae.spawn)(this.bin,["-u",t.wrapper,this.handlerFileAbsolutePath,this.pyModulePath,this.handlerName,String(this.timeout)],{env:this.environment}),this.python.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}};var ht=require("node:child_process"),yt=require("node:fs"),be=require("node:fs/promises"),U=A(require("node:path"));var le=class t{invoke;mount;unmount;name;timeout;memorySize;environment;handlerPath;modulePath;handlerDir;handlerName;runtime;bin;ruby;isMounted=!1;emitRebuild;watcherListener;watchers=[];static wrapper=U.default.resolve(j("exlo"),"./src/lib/runtime/runners/ruby/index.rb");static DELIMITER="__|response|__";static ERR_RESPONSE="__|error|__";static WATCH="__|watch|__";constructor({name:e,timeout:n,memorySize:r,environment:s,handlerPath:i,handlerName:o,runtime:a},c){this.name=e,this.timeout=n,this.memorySize=r,this.environment=s,this.handlerName=o,this.runtime=a,this.emitRebuild=c;let l=U.default.resolve(i);this.handlerDir=U.default.dirname(l),this.handlerPath=U.default.basename(l,`.${this.handlerName}`),this.modulePath=`${this.handlerDir}/${this.handlerPath}.rb`,this.mount=async()=>{if(!this.ruby)try{await(0,be.access)(this.modulePath),this.load()}catch{console.error(`Can not find ${this.name}'s handler at: "${this.modulePath}"`),process.exit(1)}},this.unmount=d=>{d&&(this.ruby?.kill(),this.ruby=void 0,this.isMounted=!1)},this.invoke=async({event:d,info:m,clientContext:h,awsRequestId:p})=>new Promise((g,y)=>{let f=JSON.stringify({event:d,awsRequestId:p,context:h??""}),b=v=>{let w=null,R=v.toString();try{if(R.includes(t.WATCH))this.setWatchFiles(R);else if(R.includes(t.DELIMITER)){let I=R.split(t.DELIMITER),O=I[I.length-1];if(I.length>1){let E=I.slice(0,-1).join(`
8
+ `);E.trim()&&console.log(E)}O&&(w=JSON.parse(O)),this.ruby.stdout.removeListener("data",b),this.ruby.stderr.removeListener("data",u),g(w)}else R.trim()&&console.log(R)}catch(I){y(I)}};this.ruby.stdout.on("data",b);let u=v=>{let w=v.toString();if(w.includes(t.ERR_RESPONSE))try{w=JSON.parse(w.split(t.ERR_RESPONSE)[1]),w.requestId=p}catch{}finally{this.ruby.stdout.removeListener("data",b),this.ruby.stderr.removeListener("data",u),y(w)}else console.log(w)};this.ruby.stderr.on("data",u),this.ruby.stdin.write(`${f}
9
+ `)}),this.watcherListener=()=>{this.isMounted&&(this.unmount(!0),this.watchers.forEach(d=>d.close()),this.watchers=[],this.emitRebuild())}}setWatchFiles=async e=>{try{let n=e.split(t.WATCH),r=n[n.length-1],s=JSON.parse(r);s.push(this.modulePath);for(let i of s)try{await(0,be.access)(i),this.watchers.push((0,yt.watch)(i,{persistent:!1},this.watcherListener))}catch{}}catch(n){console.log(n)}};load=()=>{this.bin||(this.bin=process.platform==="win32"?"ruby.exe":"ruby"),this.ruby=(0,ht.spawn)(this.bin,[t.wrapper,this.modulePath,this.handlerName,this.name,String(this.timeout)],{env:this.environment,shell:!0}),this.ruby.pid||(console.error(`Can not find ${this.bin} in your PATH`),process.exit(1)),this.isMounted=!0};onComplete=e=>{}};var En=["@invoke","@url"],k=class t{handlers=[];static ip="127.0.0.1";debug=!1;port=0;constructor(e){this.debug=e.debug}static parseNameFromUrl(e){let n=e.split("/"),r=En.includes(n[1])?n[2]:n[3];if(r=decodeURIComponent(r),r.includes(":function:")){let s=r.split(":function:");r=s[s.length-1]}if(r.includes(":")){let s=r.split(":");s.length==2&&(r=s[0])}return r}getHandlerByName(e){if(!e)return;let n=t.parseNameFromUrl(e);return this.handlers.find(r=>r.name==n)}addHandler(e){let n=this.handlers.findIndex(r=>r.name==e.name&&r.esOutputPath==e.esOutputPath);n==-1?(this.handlers.push(e),this.#e("POST",`/2015-03-31/functions/${e.name}/invocations`),e.url&&this.#e("ANY",`/@url/${e.name}`,"34")):this.handlers[n].runtime.startsWith("n")&&(this.handlers[n].clear(),this.handlers[n]=e)}#e(e,n,r="90"){let s=`${e} http://localhost:${this.port}${n}`;console.log(`\x1B[${r}m${s}\x1B[0m`)}};var ce;ve.networkInterfaces&&(ce=Object.values((0,ve.networkInterfaces)()).reduce((t,e)=>(t.push(...e),t),[])?.filter(t=>!t.internal&&t.family==="IPv4").find(Boolean)?.address);var An=vt.default?.url()!=null;An&&(console.warn("Lambdas timeout are disabled when a Debugger is attached"),$.ENABLE_TIMEOUT=!1);var Pn={errors:[],warnings:[],outputFiles:[],metafile:{inputs:{},outputs:{}},mangleCache:{}},de=class extends k{#e;runtimeConfig={};#t;sco=[];aws;llrt;customOfflineRequests=[];customBuildCallback;onReady;stop(e){this.#e.close(e)}constructor(e,n={debug:!1}){super(n),S.setDebug(n.debug),this.aws=e.aws,this.llrt=e.llrt,e.llrt&&(N.llrtBoostrapPath=e.llrt.boostrapPath,e.llrt.environment&&(N.llrtEnvs=e.llrt.environment)),this.sco=[],this.#e=bt.default.createServer({maxHeaderSize:105536},this.#r.bind(this)),this.#e.on("connection",s=>{s.on("close",()=>{let i=this.sco.findIndex(o=>o==s);i!=-1&&this.sco.splice(i,1)}),this.sco.push(s)});let r=(0,gt.randomUUID)();x.accountId=Buffer.from(r).toString("hex").slice(0,16),x.apiId=Buffer.from(r).toString("ascii").slice(0,10),x.port=this.port}setPort(e){this.port=e,x.port=e}listen(e=0,n){if(isNaN(e))throw Error("port should be a number");this.#e.once("error",async r=>{r.code==="EADDRINUSE"?(S.RED(r.message),process.exit(1)):console.log(r)}),this.#e.listen(e,async()=>{let{port:r,address:s}=this.#e.address();this.setPort(r),ce&&(k.ip=ce),typeof n=="function"&&await n(r,ce);try{await this.onReady?.(r,k.ip),await nt(this.handlers,this.aws)}catch(i){console.error(i)}})}#n(e,n){n=n.endsWith("/")?n:`${n}/`;let r=this.customOfflineRequests.find(s=>{let i=!1,o=!0;return typeof s.filter=="string"?(s.filter.endsWith("/")||(s.filter+="/"),i=s.filter==n):s.filter instanceof RegExp&&(i=s.filter.test(n)),typeof s.method=="string"&&s.method.toUpperCase()!="ANY"?o=s.method.toUpperCase()==e:Array.isArray(s.method)&&(s.method.findIndex(c=>c.toUpperCase()=="ANY")!==-1||(o=s.method.findIndex(c=>c.toUpperCase()==e)!==-1)),i&&o});if(r)return r.callback}async#r(e,n){let{url:r,method:s}=e,i=new URL(r,x.dummyHost),o=this.#n(s,i.pathname);if(o)try{await o(e,n)}catch{n.writableFinished||n.end("Internal Server Error")}else{e.on("error",c=>{console.error(c.stack)});let a=()=>{n.setHeader("Content-Type","text/html"),n.statusCode=404,n.end($e)};this.#t?this.#t(e,n,a):a()}}fakeRebuildEmitter=async()=>{if(this.customBuildCallback)try{await this.customBuildCallback(Pn,!0)}catch(e){console.log(e)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)};async load(e){for(let n of e){switch(n.runtime.charAt(0)){case"n":n.runner=new ie(n);break;case"p":n.runner=new oe(n,this.fakeRebuildEmitter);break;case"r":n.runner=new le(n,this.fakeRebuildEmitter);break;case"l":n.runner=new N(n,this.fakeRebuildEmitter);break;case"c":n.runner=new F(n,this.fakeRebuildEmitter);break;default:n.runner=new se(n.runtime);break}let s=new $(n);this.addHandler(s)}}};var wt=require("node:fs/promises"),D=A(require("node:path")),Rt=require("node:url"),It=A(require("esbuild"));var St="0.0.24";function xt(t){let e=new Set;t.plugins&&(t.plugins=t.plugins.filter((r,s)=>typeof r!="object"||!r||!("name"in r)?!1:((!r.name||!r.name.length||typeof r.name!="string")&&(r.name=`plugin-${s}`,console.warn(`No Plugin name provided at index ${s}`)),e.has(r.name)?r.name=r.name+s:e.add(r.name),!0)));async function n({stop:r,lambdas:s,region:i,esbuild:o,getServices:a,setService:c,addLambda:l,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p,setAwsProviderDefaults:g}){let y={build:{esbuild:t?.build?.esbuild??{},shimRequire:t?.build?.shimRequire,optimizeBuild:t?.build?.optimizeBuild},server:{port:t.server?.port,setEndpointEnvVar:t.server?.setEndpointEnvVar},onKill:[],llrt:t.llrt};if(t.defaults&&typeof t.defaults=="object"&&!Array.isArray(t.defaults)&&g(t.defaults),t.functions&&typeof t.functions=="object"&&!Array.isArray(t.functions))for(let[b,u]of Object.entries(t.functions))l(b,u);t.services&&(t.services.sqs&&c("sqs",t.services.sqs),t.services.sns&&c("sns",t.services.sns),t.services.dynamodb&&c("dynamodb",t.services.dynamodb));let f={stop:r,lambdas:s,region:i,esbuild:o,options:t,config:y,getServices:a,setService:c,addLambda:l,log:d,setEndpoint:m,getEndpoint:h,getAwsProviderDefaults:p};if(t.plugins){y.server.onReady=async(u,v)=>{for(let w of t.plugins)if(w.server?.onReady)try{await w.server.onReady.call(f,u,v)}catch(R){d.RED(w.name),console.error(R)}},y.buildCallback=async(u,v)=>{for(let w of t.plugins)if(w.buildCallback)try{await w.buildCallback.call(f,u,v)}catch(R){d.RED(w.name),console.error(R),v||process.exit(1)}};let b=t.plugins.reduce((u,v)=>(v.server?.request?.length&&u.push(...v.server.request),u),[]);b?.length&&(y.server.request=b.map(u=>(u.callback=u.callback.bind(f),u)));for(let u of t.plugins)if(u.onKill&&y.onKill.push(u.onKill.bind(f)),u.onInit)try{await u.onInit.call(f)}catch(v){throw d.RED(u.name),v}}return y}return n.plugins=t.plugins??[],n}var Ln=["js","mjs","cjs","ts","cts","mts"],On=async t=>{let e=D.default.dirname(D.default.toNamespacedPath(t)),n=D.default.basename(t,D.default.extname(t)),r=D.default.join(e,`__${n}.mjs`);await It.default.build({outfile:r,entryPoints:[t],bundle:!0,packages:"external",platform:"node",format:"esm",target:`node${process.versions.node.split(".")[0]}`,minify:!0,sourcemap:"inline",sourcesContent:!0});try{return await import((0,Rt.pathToFileURL)(r).href)}catch(s){throw s}finally{await(0,wt.rm)(r)}},Et=async t=>{if(t){if(typeof t=="string"){let e=D.default.posix.parse(t),n=D.default.posix.join(e.dir,e.name),r=e.ext.slice(1),s=D.default.posix.resolve(n);Ln.includes(r)&&(s+=`.${r}`);let i;try{i=await On(s)}catch(o){S.YELLOW(`Can not read 'defineConfig' from ${t}`),console.error(o),process.exit(1)}return{exportedFunc:i,configObjectName:r,configPath:s}}if(typeof t=="object"&&!Array.isArray(t))return{configObjectName:"__inline_config__",configPath:"inline define config",exportedFunc:xt(t)}}};var Nn=t=>{let e=t.split(";");return e.findIndex(r=>r.trim().toLowerCase().startsWith("path="))==-1&&e.push("Path=/"),e.join(";")},Se=(t,e,n)=>{let r={};if(t&&Object.entries(t).forEach(([s,i])=>{r[s.toLowerCase()]=Array.isArray(i)?`[${i.join(", ")}]`:i}),n)for(let[s,i]of Object.entries(n))r[s]=i;if(!Array.isArray(e))return r;if(!e.every(s=>typeof s=="string")){let s=new Error("Wrong 'cookies'. must be string[]",{cause:e}),i={"Content-Type":r["content-type"]??"application/json","x-amzn-ErrorType":"InternalFailure",...n};throw r["set-cookie"]&&(i["set-cookie"]=r["set-cookie"]),s.headers=i,s}return e=e.map(Nn),r["set-cookie"]=r["set-cookie"]?[r["set-cookie"],...e]:e,r};var xe=require("node:crypto");var pe=class t extends x{res;mockEvent;payload;constructor({res:e,req:n,body:r,mockEvent:s,multiValueHeaders:i,isBase64Encoded:o,lambdaName:a,parsedURL:c,requestId:l}){super(),this.res=e,this.mockEvent=s,this.payload=s.version==1?t.createApgV1Event({req:n,mockEvent:s,parsedURL:c,lambdaName:a,multiValueHeaders:i,isBase64Encoded:o,requestId:l,body:r}):t.createApgV2Event({req:n,mockEvent:s,parsedURL:c,requestId:l,isBase64Encoded:o,body:r})}static skipHeaders=["connection","content"];static createApgV2Event=({req:e,mockEvent:n,parsedURL:r,requestId:s,isBase64Encoded:i,body:o})=>{let{method:a,headers:c}=e,l=t.getPathParameters(n,r),d,m=n.methods.find(v=>v==a)??"ANY",h={},p="";for(let v of Array.from(new Set(r.searchParams.keys()))){let w=r.searchParams.getAll(v);p+=`&${w.map(R=>encodeURI(`${v}=${R}`)).join("&")}`,h[v]=w.join(",")}p&&(p=p.slice(1));let g=n.paths[0]=="/*"?"$default":`${m} ${r.pathname}`,y=new Date,f="127.0.0.1",b=c.host?.startsWith("localhost")?f:c.host?c.host.split(":")[0]:f,u={version:"2.0",routeKey:g,rawPath:r.pathname,rawQueryString:p,headers:t.getCustomHeaders(e,n),requestContext:{accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",http:{method:a,path:r.pathname,protocol:"HTTP/1.1",sourceIp:b,userAgent:c["user-agent"]??""},requestId:s,routeKey:g,stage:"$default",time:y.toISOString(),timeEpoch:y.getTime()}};return o?(u.body=o,u.isBase64Encoded=i):u.isBase64Encoded=!1,Object.keys(h).length&&(u.queryStringParameters=h),Object.keys(l).length&&(u.pathParameters=l),c.cookie&&(u.cookies=c.cookie.split("; ")),d=u,d.headers["x-mock-type"]&&delete d.headers["x-mock-type"],d};static createApgV1Event=({req:e,mockEvent:n,parsedURL:r,lambdaName:s,isBase64Encoded:i,requestId:o,body:a})=>{let{method:c}=e,l={};n.proxy=="httpApi"&&(l.version="1.0");let d=n.paths[0];l.resource=d,l.path=r.pathname,l.httpMethod=c;let{headers:m,multiValueHeaders:h,apiKey:p}=t.getApiGV1Headers(e,n);l.headers=m,l.multiValueHeaders=h;let g=String(e.socket.remoteAddress),y=Object.fromEntries(r.searchParams);l.queryStringParameters=Object.keys(y).length?y:null;let f=t.getMultiValueQueryStringParameters(r.searchParams);l.multiValueQueryStringParameters=Object.keys(f).length?f:null;let b=new Date,u={accountId:String(t.accountId),apiId:t.apiId,domainName:`localhost:${t.port}`,domainPrefix:"localhost",extendedRequestId:"fake-id",httpMethod:c,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:g,user:null,userAgent:e.headers["user-agent"],userArn:null},path:r.pathname,protocol:"HTTP/1.1",requestId:o,requestTime:b.toISOString(),requestTimeEpoch:b.getTime(),resourceId:"exhmtv",resourcePath:d};n.proxy=="httpApi"?(u.identity.cognitoAmr=null,u.stage="$default"):(u.stage="dev",n.private&&(u.identity.apiKey=p,u.identity.apiKeyId="abcdefghjk")),l.requestContext=u;let v=t.getPathParameters(n,r);return l.pathParameters=Object.keys(v).length?v:null,l.stageVariables=null,l.body=a??null,l.isBase64Encoded=a?i:!1,l};returnError=e=>{if(this.res.writableFinished)return!0;let n=500,r=t.httpErrMsg;e&&t.isEndpointTimeoutError(e.errorMessage)&&(this.mockEvent.proxy=="httpApi"?(n=503,r=t.unavailable):(n=504,r=t.apgTimeoutMsg));let s=[["Date",new Date().toUTCString()],["Content-Type",t.contentType.json],["Content-Length",String(r.length)],t.keepAlive,["Apigw-Requestid","ETuSEj-PiGYEJdQ="]];return this.res.shouldKeepAlive=!1,this.res.writeHead(n,s),this.res.end(r)};#e=e=>{let n="",r=typeof e;if(r=="string"||r=="number"||r=="boolean")n=String(e);else if(e===null)n="";else throw new Error("");return n};sendV1Response=e=>{let n=[["Date",new Date().toUTCString()],["Apigw-Requestid",Buffer.from((0,xe.randomUUID)()).toString("base64").slice(0,16)],t.keepAlive],r=200;if(!e||isNaN(e.statusCode))throw S.RED(`Valid 'http' response payload must be an object which includes a valid 'statusCode'.
10
+ Received:`),console.log(e),new Error;r=e.statusCode,e.headers&&typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.entries(e.headers).forEach(([l,d])=>{let m=t.normalizeHeaderKey(l),h=this.#e(d);n.push([m,h])}),e.multiValueHeaders&&typeof e.multiValueHeaders=="object"&&!Array.isArray(e.multiValueHeaders)&&Object.entries(e.multiValueHeaders).forEach(([l,d])=>{let m=t.normalizeHeaderKey(l);if(!Array.isArray(d))throw new Error;d.map(p=>this.#e(p)).forEach(p=>{n.push([m,p])})});let s=e.body;if(e.isBase64Encoded&&s){if(typeof s!="string")throw new Error;let l=Buffer.from(s,"base64").toString();if(Buffer.from(l).toString("base64")!=s)throw S.RED("response body is not properly base64 encoded"),new Error;s=l}n.findIndex(l=>l[0].toLowerCase()=="content-type")==-1&&n.push(["Content-Type",t.contentType.json]);let o=n.findIndex(l=>l[0].toLowerCase()=="content-length");o!=-1&&n.splice(o,1);let a=typeof s;a=="number"||a=="boolean"?s=String(s):s&&a!="string"&&S.YELLOW("API Gateway payload v1 return body must be typeof string, number or boolean ");let c=r==204?"0":s?String(Buffer.from(s).byteLength):"0";n.push(["Content-Length",c]),this.res.shouldKeepAlive=!1,this.res.writeHead(r,n),this.res.end(s)};sendV2Response=e=>{this.res.setHeader("Apigw-Requestid",Buffer.from((0,xe.randomUUID)()).toString("base64").slice(0,16)),this.res.setHeader("Date",new Date().toUTCString()),e?(typeof e.headers=="object"&&!Array.isArray(e.headers)&&Object.keys(e.headers).filter(s=>s!=="Apigw-Requestid"&&s!=="Date").forEach(s=>{this.res.setHeader(s,e.headers[s])}),e.statusCode?(this.res.statusCode=e.statusCode,e.cookies?.length&&this.res.setHeader("Set-Cookie",e.cookies)):this.res.statusCode=200):this.res.statusCode=200;let n="";if(!e)return this.res.end();if(typeof e=="object"&&typeof e.body=="string"&&(n=e.body,e.isBase64Encoded)){let r=Buffer.from(n,"base64").toString();if(Buffer.from(r).toString("base64")!=n)throw S.RED("response body is not properly base64 encoded"),new Error;n=r}typeof e=="string"?(this.res.setHeader("Content-Type",t.contentType.json),n=e):typeof e=="object"&&!e.statusCode&&(this.res.setHeader("Content-Type",t.contentType.json),n=JSON.stringify(e)),this.res.end(n)};sendResponse=e=>{if(!this.res.writableFinished)return this.mockEvent.version==1?this.sendV1Response(e):this.sendV2Response(e)}};var Dn=(t,e)=>{let n=e.url.stream?t:void 0;if(n){let r=!1,s=t.write.bind(t),i=t.setHeader.bind(t),o,a,c=m=>{a=a?Buffer.concat([a,m]):m},l=()=>{if(a){let m=Be(a),h=m.statusCode??200;try{let p=Se(m.headers,m.cookies);t.writeHead(h,p)}catch(p){t.writeHead(500,p.headers),t.end?.(x.amzMsgNull),delete p.headers}}else t.writeHead(200)};n.setHeader=(m,h)=>{if(m.toLowerCase()=="content-type"){if(h=="application/vnd.awslambda.http-integration-response")return r=!0,i("Content-Type",x.contentType.json);o=h}return i(m,h)};let d=!1;return n.write=(m,h,p)=>{if(n.headersSent)return s(m,h,p);if(d)try{let g=P.codec.decode(m),y=JSON.parse(g);if(Array.isArray(y))throw new Error("Invalid stream response");return y&&typeof y=="object"?(l(),s(m,h,p)):(t.writeHead(200,{"Content-Type":x.contentType.octet}),t.end())}catch(g){let y=new Error(`When using HttpResponseStream first chunk of .write() must be valid JSON and not be Array. Number and null will respones with 200.
11
+ '${e.name}'`);return y.cause=g.message,console.error(y),te(t)}else if(r)Je(m)?d=!0:c(m);else{if(o==x.contentType.json)try{let y=P.codec.decode(m),f=JSON.parse(y);if(f===null||typeof f=="number")throw new Error(y)}catch(y){let f=new Error(`When 'Content-Type' is 'application/json' first chunk of .write() must be parsable JSON and not be null or number.
12
+ '${e.name}'`);return f.cause=y.message,console.error(f),te(t)}let g={"Content-Type":o??x.contentType.octet};return n.writeHead(200,g),s(m,h,p)}},n}},Tn=(t,e,n,r)=>{let s=Y(t),i=s?t.getParsedResponse():t,o,a=!1;if(i&&typeof i=="object"&&i.statusCode){let c=isNaN(i.statusCode),l=c?500:i.statusCode;if(a=!c&&(i.isBase64Encoded==!0||i.isBase64Encoded=="true"),i.headers||i.cookies)try{let d=Se(i.headers,i.cookies,r);e.writeHead(l,d)}catch(d){return e.writeHead(500,d.headers),delete d.headers,console.error(d),e.end(x.amzMsgNull)}else e.writeHead(l,{"Content-Type":x.contentType.json,...r});n?o=i:(typeof i.body<"u"&&(o=i.body),e.headersSent||e.setHeader("Content-Type",s?x.contentType.octet:x.contentType.json))}else e.writeHead(200,{"Content-Type":x.contentType.json,...r}),o=i;!e.headersSent&&!n&&s&&e.setHeader("Content-Type",x.contentType.octet),n?o instanceof Uint8Array?e.end(o):e.end(JSON.stringify(o)):((typeof o=="number"||typeof o=="boolean"||o==null||o instanceof Object)&&(o=JSON.stringify(o)),o&&a&&(o=Buffer.from(o,"base64")),e.end(o))};function Mn(t,e){let n=t["access-control-request-method"];return e=="OPTIONS"&&t.origin&&n&&["GET","HEAD","POST","PUT","DELETE","PATCH"].includes(n)}function At(t,e){let n=e.origin;return n&&t.allowOrigins.find(s=>s=="*"||s=="http://*"||s=="https://*")?!0:!!t.allowOrigins.find(s=>s==n)}function qn(t,e){if(!t.allowMethods?.length)return!1;if(t.allowMethods.find(s=>s=="*"))return!0;let r=e["access-control-request-method"];return!!t.allowMethods.find(s=>s==r)}function jn(t,e){if(!qn(t,e)||!At(t,e))return!1;let n=e["access-control-request-headers"]?e["access-control-request-headers"].split(",").filter(Boolean):[];return n.length?t.allowHeaders?.length?n.every(r=>t.allowHeaders.find(s=>s.toLowerCase()==r.toLowerCase())):!1:!0}var Pt=t=>({filter:/^\/@url\//,callback:async(e,n)=>{let{url:r,method:s,headers:i}=e;if(Ve(n,s))return;let o=new URL(r,x.dummyHost),a=_(n),c=k.parseNameFromUrl(o.pathname),l=t.handlers.find(f=>f.name==c);if(!l?.url)return n.statusCode=404,n.end("Not Found");let d;if(l.url.cors){if(Mn(i,s)){let b=jn(l.url.cors,i),u={"Content-Type":x.contentType.json};return b&&(u["access-control-allow-origin"]=i.origin,l.url.cors.allowMethods.find(v=>v=="*")?u["access-control-allow-methods"]=i["access-control-request-method"]:u["access-control-allow-methods"]=l.url.cors.allowMethods.join(","),l.url.cors.allowHeaders?.length&&(u["access-control-allow-headers"]=l.url.cors.allowHeaders.join(",")),typeof l.url.cors.maxAge=="number"&&l.url.cors.maxAge>-1&&(u["access-control-max-age"]=`${l.url.cors.maxAge}`),l.url.cors.allowCredentials&&(u["access-control-allow-credentials"]="true")),n.writeHead(200,u),n.end()}At(l.url.cors,i)&&(d={"access-control-allow-origin":i.origin},l.url.cors.exposeHeaders?.length&&(d["access-control-expose-headers"]=l.url.cors.exposeHeaders.join(",")),l.url.cors.allowCredentials&&(d["access-control-allow-credentials"]="true"))}let m=x.getIsBase64Encoded(i),h=await T(e,m),p=pe.createApgV2Event({req:e,mockEvent:l.url,parsedURL:o,requestId:a,body:h,isBase64Encoded:m}),g=`/@url/${l.name}`,y=o.pathname.slice(g.length);y||(y="/"),p.requestContext.accountId="anonymous",p.rawPath=y,p.requestContext.http.path=y;try{let f=Dn(n,l),b=await l.invoke(p,l.url,void 0,f);if(!b)return n.end();Tn(b,n,f,d)}catch(f){console.error(f),te(n,d)}}});var kt=t=>({filter:/(^\/2015-03-31\/functions\/.*\/invocations)|(^\/@invoke\/)/,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=k.parseNameFromUrl(i.pathname),a=t.handlers.find(f=>f.name==o),c=_(n);if(n.setHeader("Content-Type","application/json"),e.on("error",f=>{n.statusCode=502,n.end(JSON.stringify(f))}),!a){let{region:f,accountId:b}=t.aws;return n.statusCode=404,n.setHeader("x-amzn-errortype","ResourceNotFoundException"),n.end(ee(o,f,b))}let l=s["x-amz-invocation-type"],d=K(s["x-amz-client-context"]);if(d instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Z);let m=l=="DryRun"?204:l=="Event"?202:200,h=await T(e),p=G(h);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),p instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(X(p.message));n.setHeader("X-Amz-Executed-Version","$LATEST");let g=new Date,y={};n.statusCode=m,m!==200&&n.end(),m==202&&(y.kind="async");try{let f=await a.invoke(p,y,d);if(m==200){if(typeof f>"u"){n.end();return}let b=Y(f),u=b?f.buffer:f;b?u=P.codec.decode(u):typeof u!="string"&&(u=JSON.stringify(u)),n.end(u)}}catch(f){let b,u=!1;if(typeof f=="string")try{b=JSON.parse(f),u=!0}catch{}else b=f;n.writableFinished||(n.setHeader("X-Amz-Function-Error",b.errorType??b.message??""),n.statusCode=200,n.end(u?f:JSON.stringify(b)))}}});var we=require("node:crypto"),Lt=require("node:timers/promises");var Ot=t=>({filter:"/2015-03-31/functions",method:"POST",async callback(e,n){let r=await T(e),s=JSON.parse(r),{FunctionName:i,Handler:o,Environment:a,Runtime:c,Timeout:l,MemorySize:d}=s;t.addLambda(i,{handler:o,environment:a?.Variables,runtime:c,timeout:l,memorySize:d}),t.isDynamicBuild=!0,t.setEsBuildConfig(),await t.buildContext.dispose(),await t.buildAndWatch(),await(0,Lt.setTimeout)(100),n.statusCode=201,n.end(r)}}),Nt=t=>({filter:/\/2015-03-31\/functions\/*/,method:"GET",async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22),o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Code:{RepositoryType:"S3",Location:"https://s3.com/snapshots/1234543"},Tags:{},Configuration:{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:Dt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,we.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}};n.end(JSON.stringify(a))}}),Hn=["AWS_EXECUTION_ENV","AWS_LAMBDA_FUNCTION_VERSION","AWS_LAMBDA_FUNCTION_NAME","_HANDLER","IS_OFFLINE","IS_LOCAL","AWS_SAM_LOCAL","AWS_LAMBDA_FUNCTION_MEMORY_SIZE"];function Dt(t){let e={};for(let[n,r]of Object.entries(t))Hn.includes(n)||(e[n]=String(r));return e}var Tt=t=>({method:"GET",filter:/\/2015-03-31\/functions\/.*\/versions/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);i=i.slice(0,i.indexOf("/"));let o=t.getLambdaByName(i);if(!o){n.statusCode=404,n.end();return}let a={Versions:[{Architectures:["arm64"],CodeSha256:"WrLckXVmmfsSPvP/15FqPi9Nt9qQBaspP6RV3T137K4=",SigningJobArn:"",FunctionArn:`arn:aws:lambda:${t.aws.region}:${t.aws.accountId}:function:${i}`,FunctionName:i,Handler:o.handlerPath,Timeout:o.timeout,Runtime:o.runtime,MemorySize:o.memorySize,Environment:{Variables:Dt(o.environment)},State:"Active",LastUpdateStatus:"Successful",LastModified:new Date().toISOString(),Version:"$LATEST",Role:`arn:aws:iam::${t.aws.accountId}:role/fake-role-name`,RevisionId:(0,we.randomUUID)(),PackageType:"Zip",Description:"",EphemeralStorage:{Size:512},TracingConfig:{Mode:"PassThrough"},VpcConfig:{Ipv6AllowedForDualStack:!1,VpcId:"",SecurityGroupIds:[],SubnetIds:[]},CodeSize:5867,SnapStart:{OptimizationStatus:"Off",ApplyOn:"None"},LoggingConfig:{LogFormat:"Text",LogGroup:`/aws/lambda/${i}`}}]};n.end(JSON.stringify(a))}}),Mt=t=>({method:"GET",filter:/\/2020-06-30\/functions\/.*\/code-signing-config/,async callback(e,n){let{url:r}=e,i=new URL(r,"http://localhost:3003").pathname.slice(22);if(i=i.slice(0,i.indexOf("/")),!t.getLambdaByName(i)){n.statusCode=404,n.end();return}let a={CodeSigningConfigArn:"",FunctionName:i};n.end(JSON.stringify(a))}});var qt=require("@smithy/eventstream-codec");var _n=(t,e)=>{let n=Buffer.from(t,e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Cn=t=>Buffer.from(t,t.byteOffset,t.byteLength).toString("utf8"),Re=new qt.EventStreamCodec(Cn,_n),me=class t{res;static complete=Buffer.from([0,0,0,102,0,0,0,84,31,86,200,105,11,58,101,118,101,110,116,45,116,121,112,101,7,0,14,73,110,118,111,107,101,67,111,109,112,108,101,116,101,13,58,99,111,110,116,101,110,116,45,116,121,112,101,7,0,16,97,112,112,108,105,99,97,116,105,111,110,47,106,115,111,110,13,58,109,101,115,115,97,103,101,45,116,121,112,101,7,0,5,101,118,101,110,116,123,125,112,6,212,103]);constructor(e){this.res=e}write(e,n,r){this.res.write(Re.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:e}),n,r)}end(e){e?this.write(e,"utf8",()=>{this.res.end(t.complete)}):this.res.end(t.complete)}setHeader(e,n){e=="Content-Type"&&this.res.setHeader("Content-Type",n)}destroy(){this.res.destroy()}endWithError(e){let n={ErrorCode:e.errorType,ErrorDetails:JSON.stringify(e)},r=Array.from(Buffer.from(JSON.stringify(n)).values());this.res.end(Re.encode({headers:this.#e("InvokeComplete",x.contentType.json),body:new Uint8Array(r)}))}endWithJson(e){let n=Array.from(Buffer.from(JSON.stringify(e)).values());this.res.write(Re.encode({headers:this.#e("PayloadChunk",x.contentType.octet),body:new Uint8Array(n)}),()=>{this.res.end(t.complete)})}#e(e,n,r="event"){return{":event-type":{type:"string",value:e},":content-type":{type:"string",value:n},":message-type":{type:"string",value:r}}}};var jt=t=>({filter:/^\/2021-11-15\/functions\//,callback:async(e,n)=>{let{url:r,headers:s}=e,i=new URL(r,"http://localhost:3003"),o=_(n),a=k.parseNameFromUrl(i.pathname),c=t.handlers.find(p=>p.name==a),l=await T(e),d=G(l);if(n.setHeader("X-Amzn-Trace-Id","root=1-xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx;sampled=0"),d instanceof Error)return n.statusCode=400,n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.end(X(d.message));let m=K(s["x-amz-client-context"]);if(m instanceof Error)return n.setHeader("x-amzn-errortype","InvalidRequestContentException"),n.statusCode=400,n.end(Z);let h=new me(n);if(c){let p=c.url?.stream??{};try{let g=await c.invoke(d,p,m,h);g&&h.endWithJson(g)}catch(g){n.writableFinished||h.endWithError(g)}}else{let{region:p,accountId:g}=t.aws;n.statusCode=404,n.end(ee(a,p,g))}}});var Ft=t=>[Ot(t),Tt(t),Mt(t),kt(t),jt(t),Pt(t),Nt(t)];var Ee=process.cwd(),Wn=3,$n=1024,Un={IS_OFFLINE:!0,IS_LOCAL:!0,AWS_SAM_LOCAL:!0},zn=Ee.split(L.default.sep)[0],Vn=new RegExp(`^.*:${zn}`),Bn=t=>Vn.test(t);process.title="node (exlo)";var ue=class extends de{#e;options;config;esBuildConfig;buildContext={};customEsBuildConfig;optimizeBuild=!1;nodeVersion=!1;onKill=[];shimRequire=!1;port=0;onceServerReady=[];isDynamicBuild=!1;endpoints={};setLambdaEndpointEnvVar=!0;constructor(e,n){super(e,{debug:typeof n.debug=="boolean"?n.debug:!1}),this.#e=[],this.options=n,this.options.customEsBuildConfig&&(this.customEsBuildConfig=this.options.customEsBuildConfig),typeof this.options.config?.server?.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=this.options.config.server.setEndpointEnvVar),this.options.config&&(typeof this.options.config=="string"||typeof this.options.config=="object"&&!Array.isArray(this.options.config))&&(this.config=this.options.config),typeof this.options.optimizeBuild=="boolean"&&(this.optimizeBuild=this.options.optimizeBuild),typeof this.options.shimRequire=="boolean"&&(this.shimRequire=this.options.shimRequire),this.aws.runtime?.startsWith("node")?this.nodeVersion=this.aws.runtime?.replace(/[^0-9]/g,""):this.nodeVersion="20",S.BR_BLUE("Starting exlo...")}async start(){this.#s(),this.#e=this.#r(),await this.#o(),this.setEsBuildConfig(),await this.buildAndWatch()}setEsBuildConfig(){let n={sourcemap:!0,minify:!1,entryPoints:this.#e.filter(r=>r.runtime.startsWith("n")||r.runtime=="llrt").map(r=>r.esEntryPoint),outdir:L.default.join(Ee,".exlo","build"),metafile:!0,bundle:!0,platform:"node",target:"node20",format:"cjs",outbase:"src",plugins:[],external:["esbuild","llrt","llrt:*"],dropLabels:[]};if(typeof process.env.NODE_ENV=="string"&&(n.define={"process.env.NODE_ENV":`"${process.env.NODE_ENV}"`}),typeof this.nodeVersion=="string"&&!isNaN(Number(this.nodeVersion))){Number(process.versions.node.slice(0,2))<Number(this.nodeVersion)&&S.RED(`You are running on NodeJS ${process.version} which is lower than defined '${this.nodeVersion}'.`),n.target=`node${this.nodeVersion}`;let r=()=>this.sco;n.plugins?.push(Oe({nodeVersion:Number(this.nodeVersion),shimRequire:this.shimRequire,optimizeBuild:this.optimizeBuild,buildCallback:this.buildCallback,getSockets:r}))}this.customEsBuildConfig&&(n=Ne(n,this.customEsBuildConfig)),this.esBuildConfig=n}async buildAndWatch(){this.buildContext=await Ie.default.context(this.esBuildConfig),await this.buildContext.watch()}buildCallback=async(e,n)=>{if(n||this.isDynamicBuild)await this.#t(e);else{let{outputs:r}=e.metafile;if(this.#i(r),this.customBuildCallback)try{await this.customBuildCallback(e,!1)}catch(o){console.log(o)}this.#a();let s=this,i=await new Promise(o=>{this.listen(this.port,async(a,c)=>{let l=`http://localhost:${a}`;S.PINK(`Lambda endpoint: ${l}`),this.endpoints.lambda=l,this.setLambdaEndpointEnvVar&&(this.runtimeConfig.environment.AWS_ENDPOINT_URL_LAMBDA=l,this.aws.environment.AWS_ENDPOINT_URL_LAMBDA=l),await s.load(s.#e);for(let d of s.#e)d.setEnv("LOCAL_PORT",a),d.setEnv("AWS_LAMBDA_RUNTIME_API",`127.0.0.1:${a}`),this.setLambdaEndpointEnvVar&&d.setEnv("AWS_ENDPOINT_URL_LAMBDA",l);o({url:l,port:a})})});this.onceServerReady.forEach(o=>{o(i)})}};async#t(e){if(e?.errors?.length)S.RED("Build failed:"),console.error(e.errors);else{this.#i(e.metafile.outputs);try{await this.load(this.#e),this.customBuildCallback&&await this.customBuildCallback(e,!0)}catch(n){console.error(n)}console.log(`\x1B[32m${new Date().toLocaleString()} \u{1F504}\u2705 Rebuild\x1B[0m`)}}#n(e){let n=this.aws,r=n.runtime,s=this.runtimeConfig.environment.AWS_REGION??this.runtimeConfig.environment.REGION,o=n.functions[e],a=o.handler,c=L.default.extname(a),l=c.slice(1),d=L.default.resolve(a.replace(c,"")),m=n.getFunction(e),h=m.runtime??r,p={name:e,runtime:m.runtime??r,handlerPath:a,handlerName:l,esEntryPoint:d,memorySize:o.memorySize??this.runtimeConfig.memorySize??$n,timeout:o.timeout??this.runtimeConfig.timeout??Wn,sqs:[],ddb:[],environment:{AWS_EXECUTION_ENV:`AWS_Lambda_${h}`,AWS_LAMBDA_FUNCTION_VERSION:"$LATEST",AWS_LAMBDA_FUNCTION_NAME:e,_HANDLER:L.default.basename(a),...this.runtimeConfig.environment,...o.environment,...Un},invoke:async(g,y)=>{let f=this.getHandlerByName(`/@invoke/${e}`);if(f)return await f.invoke(g,y);S.RED(`'${e}' is not mounted yet.
13
+ Please invoke it after the initial build is completed.`)},invokeSub:[],invokeSuccessSub:[],invokeErrorSub:[],setEnv:(g,y)=>{this.setEnv(e,g,y)},shutdown:async()=>{let g=this.getHandlerByName(`/@invoke/${e}`);g&&await g.shutdown()}};if(p.onError=J(o.onError),p.onError?.kind=="lambda"&&(S.YELLOW("Dead-Letter queue could only be a SNS or SQS service"),delete p.onError),o.destinations&&typeof o.destinations=="object"&&(p.onFailure=J(o.destinations.onFailure),p.onSuccess=J(o.destinations.onSuccess)),p.onInvoke=g=>{p.invokeSub.push(g)},p.onInvokeSuccess=g=>{p.invokeSuccessSub.push(g)},p.onInvokeError=g=>{p.invokeErrorSub.push(g)},process.env.NODE_ENV&&(p.environment.NODE_ENV=process.env.NODE_ENV),s&&(p.environment.AWS_REGION=s,p.environment.AWS_DEFAULT_REGION=s),p.environment.AWS_LAMBDA_FUNCTION_MEMORY_SIZE=p.memorySize,p.url=Te(o),o.triggers?.length){let{sqs:g,ddb:y}=je({triggers:o.triggers});p.sqs=g,p.ddb=y}return p}#r(){let e=this.aws.functions;return Object.keys(e).reduce((s,i)=>{let o=this.#n(i);return s.push(o),s},[])}#i(e){let n=Object.keys(e).filter(r=>!r.endsWith(".map")&&e[r].entryPoint).map(r=>{let i=e[r].entryPoint,o="";Bn(i)&&(i=i.split(":").slice(1).join(":")),L.default.isAbsolute(i)||(i=L.default.resolve(i));let a=i.lastIndexOf(".");return a!=-1&&(o=L.default.extname(i),i=i.slice(0,a)),{esOutputPath:L.default.join(Ee,r),entryPoint:i,ext:o}});for(let r of this.#e){let s=n.find(i=>i?.entryPoint==r.esEntryPoint);s&&(r.esOutputPath=s.esOutputPath,r.entryPoint=`${s.entryPoint}${s.ext}`)}}#s(){let{environment:e,memorySize:n,timeout:r}=this.aws;this.runtimeConfig.memorySize=n,this.runtimeConfig.timeout=r,this.runtimeConfig.environment=e?{...e}:{};let s=Object.keys(process.env).filter(i=>i.startsWith("AWS_"));for(let i of s)this.runtimeConfig.environment[i]=process.env[i];"FORCE_COLOR"in this.runtimeConfig.environment||process.env.FORCE_COLOR?.toLowerCase()==="false"||process.env.FORCE_COLOR?.toLowerCase()==="no"||process.env.FORCE_COLOR==="0"||("COLORTERM"in process.env||process.env.TERM?.includes("256"))&&(this.runtimeConfig.environment.FORCE_COLOR="true")}setEnv(e,n,r){let s=this.#e.findIndex(i=>i.name==e);if(s>-1){this.#e[s].environment[n]=r;let i=this.aws.getFunction(e);i&&(i.environment||(i.environment={}),i.environment[n]=r)}else S.RED(`Can not set env variable '${n}' on '${e}'`)}addLambda(e,n){if(!n.triggers)n.triggers=[];else if(!Array.isArray(n.triggers))throw new Error("Lambda 'triggers' must be an array when defined.");this.#s(),this.aws.functions[e]=n;let r=this.#n(e);this.#e.push(r)}getLambdaByName(e){return this.#e.find(n=>n.name==e)}buildDefineConfigParam(){let e=this;return{stop:async r=>{await this.kill(r)},lambdas:this.#e,addLambda:(r,s)=>{this.addLambda(r,s)},esbuild:Ie.default,getServices(){return{s3:e.aws.services.s3,sqs:e.aws.services.sqs,sns:e.aws.services.sns,dynamodb:e.aws.services.dynamodb}},setService(r,s){switch(r){case"s3":e.aws.services.s3=s;break;case"sns":e.aws.services.sns=s;break;case"sqs":e.aws.services.sqs=s;break;case"dynamodb":e.aws.services.dynamodb=s;break;default:break}},setEndpoint:(r,s,i)=>{if(this.endpoints[r]=s,typeof i=="string"){this.aws.environment[i]=s;for(let o of this.#e)this.setEnv(o.name,i,s)}},getEndpoint:r=>this.endpoints[r],getAwsProviderDefaults:()=>({accountId:e.aws.accountId,region:e.aws.region,runtime:e.aws.runtime,memorySize:e.aws.memorySize,timeout:e.aws.timeout,environment:{...e.aws.environment}}),setAwsProviderDefaults:({accountId:r,environment:s,memorySize:i,region:o,runtime:a,timeout:c})=>{r&&(e.aws.accountId=r),s&&(e.aws.environment=s),i&&(e.aws.memorySize=i),o&&(e.aws.region=o),a&&(e.aws.runtime=a),c&&(e.aws.timeout=c)},log:S}}async resolveConfig(){let e=await Et(this.config);if(e?.exportedFunc){let n,{exportedFunc:r,configObjectName:s,configPath:i}=e;if(typeof r[s]=="function")n=r[s];else if(typeof r=="function")n=r;else if(typeof r.default=="function")n=r.default;else throw new Error(`Can not read exlo config at: ${i}`);return n}}onBeforeApplyConfigCallbacks=[];onBeforeApplyConfig(e){this.onBeforeApplyConfigCallbacks.push(e)}async#l(e){for(let n of this.onBeforeApplyConfigCallbacks)await n(e)}async#o(){let e=this.buildDefineConfigParam(),n=Ft(this).map(a=>(a.callback=a.callback.bind(e),a)),r=await this.resolveConfig(),s={};r&&(await this.#l(r),s=await r(e),Array.isArray(s.onKill)&&this.onKill.push(...s.onKill),s.build&&(typeof s.build.shimRequire=="boolean"&&(this.shimRequire=s.build.shimRequire),typeof s.build.optimizeBuild=="boolean"&&(this.optimizeBuild=s.build.optimizeBuild)),!this.llrt&&s.llrt&&(this.llrt=s.llrt,N.llrtBoostrapPath=this.llrt.boostrapPath,this.llrt.environment&&(N.llrtEnvs=this.llrt.environment)),typeof s.buildCallback=="function"&&(this.customBuildCallback=s.buildCallback),s.server&&typeof s.server=="object"&&(Array.isArray(s.server.request)&&n.unshift(...s.server.request),typeof s.server.port=="number"&&!this.port&&(this.port=s.server.port),typeof s.server.onReady=="function"&&(this.onReady=s.server.onReady),typeof s.server.setEndpointEnvVar=="boolean"&&(this.setLambdaEndpointEnvVar=s.server.setEndpointEnvVar))),this.customOfflineRequests=n;let i=s?.build?.esbuild;if(!i)return;let o=De(i);Object.keys(o).length&&(this.customEsBuildConfig?this.customEsBuildConfig={...this.customEsBuildConfig,...o}:this.customEsBuildConfig=o)}#a=()=>{let e=this.options.port;isNaN(e)||(this.port=e)};async kill(e){this.buildContext.dispose&&await this.buildContext.dispose();for(let n of Ht.EventSourceMapping.SOURCES)try{await n.disable()}catch(r){console.error(r)}for(let n of this.handlers)n.clear?.();this.stop(e);for(let n of this.onKill)try{await n()}catch(r){console.error(r)}}};async function Jn(t){let e=_t(t);return await e.exlo.start(),await e.waitServer,{port:e.listeningPort,url:e.listeningUrl,endpoints:e.exlo.endpoints,async kill(){await e.exlo.kill()},[Symbol.asyncDispose]:async()=>{await e.exlo.kill()}}}var Ae=class{accountId="123456789012";region="us-east-1";timeout=3;memorySize=1024;environment={};services={};functions={};runtime=`node${process.versions.node.split(".")[0]}.x`;getFunction(e){return this.functions[e]}};function _t(t){let e=new Ae,n={};t&&(t.port&&(n.port=t.port),typeof t.debug=="boolean"&&(n.debug=t.debug),t.build&&(typeof t.build.shimRequire=="boolean"&&(n.shimRequire=t.build.shimRequire),typeof t.build.optimizeBuild=="boolean"&&(n.optimizeBuild=t.build.optimizeBuild),t.build.esbuild&&(n.customEsBuildConfig=t.build.esbuild)),t.config&&(n.config=t.config),t.functions&&(e.functions=t.functions),t.defaults&&(t.defaults.environment&&(e.environment=t.defaults.environment),t.defaults.timeout&&(e.timeout=t.defaults.timeout),t.defaults.memorySize&&(e.memorySize=t.defaults.memorySize),t.defaults.runtime&&(e.runtime=t.defaults.runtime),t.defaults.accountId&&(e.accountId=t.defaults.accountId),t.defaults.region&&(e.region=t.defaults.region)));let r;t?.llrt?r=t.llrt:typeof t?.config=="object"&&t.config.llrt&&(r=t.config.llrt);let s=new ue({aws:e,llrt:r},n);typeof t?.onKill=="function"&&s.onKill.push(t.onKill);let i;s.onceServerReady.push(a=>{o.listeningPort=a.port,o.listeningUrl=a.url,i()});let o={listeningPort:0,listeningUrl:"",exlo:s,waitServer:new Promise(a=>{i=a})};return o}0&&(module.exports={createAppRunner,exloVersion,run});