@nightx.co/pulsar 1.0.15 → 1.0.16
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.
- package/LICENSE +207 -0
- package/dist/chunk-cpn1qh4e.js.map +2 -2
- package/dist/helpers/computeConfigDelta.d.ts.map +1 -1
- package/dist/helpers/generateShaHash.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +8 -8
- package/dist/network/abstract/BaseNetworkDriver.d.ts +1 -1
- package/dist/network/abstract/BaseNetworkDriver.d.ts.map +1 -1
- package/dist/network/drivers/HttpNetworkDriver.d.ts +1 -1
- package/dist/network/drivers/HttpNetworkDriver.d.ts.map +1 -1
- package/dist/network/drivers/WebSocketNetworkDriver.d.ts +1 -1
- package/dist/network/drivers/WebSocketNetworkDriver.d.ts.map +1 -1
- package/dist/storage/index.js +1 -1
- package/dist/storage/index.js.map +4 -4
- package/dist/subsys/LoggerService.d.ts.map +1 -1
- package/dist/types/consumer.types.d.ts +36 -0
- package/dist/types/consumer.types.d.ts.map +1 -1
- package/package.json +1 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
10
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the
|
|
13
|
+
copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other
|
|
16
|
+
entities that control, are controlled by, or are under common control with
|
|
17
|
+
that entity. For the purposes of this definition, "control" means (i) the
|
|
18
|
+
power, direct or indirect, to cause the direction or management of such
|
|
19
|
+
entity, whether by contract or otherwise, or (ii) ownership of
|
|
20
|
+
fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
|
|
21
|
+
ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
24
|
+
permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation source,
|
|
28
|
+
and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical transformation
|
|
31
|
+
or translation of a Source form, including but not limited to compiled
|
|
32
|
+
object code, generated documentation, and conversions to
|
|
33
|
+
other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or Object
|
|
36
|
+
form, made available under the License, as indicated by a copyright notice
|
|
37
|
+
that is included in or attached to the work (an example is provided in the
|
|
38
|
+
Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object form,
|
|
41
|
+
that is based on (or derived from) the Work and for which the editorial
|
|
42
|
+
revisions, annotations, elaborations, or other modifications represent,
|
|
43
|
+
as a whole, an original work of authorship. For the purposes of this
|
|
44
|
+
License, Derivative Works shall not include works that remain separable
|
|
45
|
+
from, or merely link (or bind by name) to the interfaces of, the Work and
|
|
46
|
+
Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including the original
|
|
49
|
+
version of the Work and any modifications or additions to that Work or
|
|
50
|
+
Derivative Works thereof, that is intentionally submitted to Licensor for
|
|
51
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
52
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
53
|
+
For the purposes of this definition, "submitted" means any form of
|
|
54
|
+
electronic, verbal, or written communication sent to the Licensor or its
|
|
55
|
+
representatives, including but not limited to communication on electronic
|
|
56
|
+
mailing lists, source code control systems, and issue tracking systems
|
|
57
|
+
that are managed by, or on behalf of, the Licensor for the purpose of
|
|
58
|
+
discussing and improving the Work, but excluding communication that is
|
|
59
|
+
conspicuously marked or otherwise designated in writing by the copyright
|
|
60
|
+
owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on
|
|
63
|
+
behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License.
|
|
67
|
+
|
|
68
|
+
Subject to the terms and conditions of this License, each Contributor
|
|
69
|
+
hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
|
|
70
|
+
royalty-free, irrevocable copyright license to reproduce, prepare
|
|
71
|
+
Derivative Works of, publicly display, publicly perform, sublicense,
|
|
72
|
+
and distribute the Work and such Derivative Works in
|
|
73
|
+
Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License.
|
|
76
|
+
|
|
77
|
+
Subject to the terms and conditions of this License, each Contributor
|
|
78
|
+
hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
|
|
79
|
+
royalty-free, irrevocable (except as stated in this section) patent
|
|
80
|
+
license to make, have made, use, offer to sell, sell, import, and
|
|
81
|
+
otherwise transfer the Work, where such license applies only to those
|
|
82
|
+
patent claims licensable by such Contributor that are necessarily
|
|
83
|
+
infringed by their Contribution(s) alone or by combination of their
|
|
84
|
+
Contribution(s) with the Work to which such Contribution(s) was submitted.
|
|
85
|
+
If You institute patent litigation against any entity (including a
|
|
86
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
87
|
+
Contribution incorporated within the Work constitutes direct or
|
|
88
|
+
contributory patent infringement, then any patent licenses granted to
|
|
89
|
+
You under this License for that Work shall terminate as of the date such
|
|
90
|
+
litigation is filed.
|
|
91
|
+
|
|
92
|
+
4. Redistribution.
|
|
93
|
+
|
|
94
|
+
You may reproduce and distribute copies of the Work or Derivative Works
|
|
95
|
+
thereof in any medium, with or without modifications, and in Source or
|
|
96
|
+
Object form, provided that You meet the following conditions:
|
|
97
|
+
|
|
98
|
+
1. You must give any other recipients of the Work or Derivative Works a
|
|
99
|
+
copy of this License; and
|
|
100
|
+
|
|
101
|
+
2. You must cause any modified files to carry prominent notices stating
|
|
102
|
+
that You changed the files; and
|
|
103
|
+
|
|
104
|
+
3. You must retain, in the Source form of any Derivative Works that You
|
|
105
|
+
distribute, all copyright, patent, trademark, and attribution notices from
|
|
106
|
+
the Source form of the Work, excluding those notices that do not pertain
|
|
107
|
+
to any part of the Derivative Works; and
|
|
108
|
+
|
|
109
|
+
4. If the Work includes a "NOTICE" text file as part of its distribution,
|
|
110
|
+
then any Derivative Works that You distribute must include a readable copy
|
|
111
|
+
of the attribution notices contained within such NOTICE file, excluding
|
|
112
|
+
those notices that do not pertain to any part of the Derivative Works,
|
|
113
|
+
in at least one of the following places: within a NOTICE text file
|
|
114
|
+
distributed as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or, within a
|
|
116
|
+
display generated by the Derivative Works, if and wherever such
|
|
117
|
+
third-party notices normally appear. The contents of the NOTICE file are
|
|
118
|
+
for informational purposes only and do not modify the License.
|
|
119
|
+
You may add Your own attribution notices within Derivative Works that You
|
|
120
|
+
distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
121
|
+
provided that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and may
|
|
125
|
+
provide additional or different license terms and conditions for use,
|
|
126
|
+
reproduction, or distribution of Your modifications, or for any such
|
|
127
|
+
Derivative Works as a whole, provided Your use, reproduction, and
|
|
128
|
+
distribution of the Work otherwise complies with the conditions
|
|
129
|
+
stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions.
|
|
132
|
+
|
|
133
|
+
Unless You explicitly state otherwise, any Contribution intentionally
|
|
134
|
+
submitted for inclusion in the Work by You to the Licensor shall be under
|
|
135
|
+
the terms and conditions of this License, without any additional
|
|
136
|
+
terms or conditions. Notwithstanding the above, nothing herein shall
|
|
137
|
+
supersede or modify the terms of any separate license agreement you may
|
|
138
|
+
have executed with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks.
|
|
141
|
+
|
|
142
|
+
This License does not grant permission to use the trade names, trademarks,
|
|
143
|
+
service marks, or product names of the Licensor, except as required for
|
|
144
|
+
reasonable and customary use in describing the origin of the Work and
|
|
145
|
+
reproducing the content of the NOTICE file.
|
|
146
|
+
|
|
147
|
+
7. Disclaimer of Warranty.
|
|
148
|
+
|
|
149
|
+
Unless required by applicable law or agreed to in writing, Licensor
|
|
150
|
+
provides the Work (and each Contributor provides its Contributions)
|
|
151
|
+
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
|
152
|
+
either express or implied, including, without limitation, any warranties
|
|
153
|
+
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS
|
|
154
|
+
FOR A PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
155
|
+
appropriateness of using or redistributing the Work and assume any risks
|
|
156
|
+
associated with Your exercise of permissions under this License.
|
|
157
|
+
|
|
158
|
+
8. Limitation of Liability.
|
|
159
|
+
|
|
160
|
+
In no event and under no legal theory, whether in tort
|
|
161
|
+
(including negligence), contract, or otherwise, unless required by
|
|
162
|
+
applicable law (such as deliberate and grossly negligent acts) or agreed
|
|
163
|
+
to in writing, shall any Contributor be liable to You for damages,
|
|
164
|
+
including any direct, indirect, special, incidental, or consequential
|
|
165
|
+
damages of any character arising as a result of this License or out of
|
|
166
|
+
the use or inability to use the Work (including but not limited to damages
|
|
167
|
+
for loss of goodwill, work stoppage, computer failure or malfunction,
|
|
168
|
+
or any and all other commercial damages or losses), even if such
|
|
169
|
+
Contributor has been advised of the possibility of such damages.
|
|
170
|
+
|
|
171
|
+
9. Accepting Warranty or Additional Liability.
|
|
172
|
+
|
|
173
|
+
While redistributing the Work or Derivative Works thereof, You may choose
|
|
174
|
+
to offer, and charge a fee for, acceptance of support, warranty,
|
|
175
|
+
indemnity, or other liability obligations and/or rights consistent with
|
|
176
|
+
this License. However, in accepting such obligations, You may act only
|
|
177
|
+
on Your own behalf and on Your sole responsibility, not on behalf of any
|
|
178
|
+
other Contributor, and only if You agree to indemnify, defend, and hold
|
|
179
|
+
each Contributor harmless for any liability incurred by, or claims
|
|
180
|
+
asserted against, such Contributor by reason of your accepting any such
|
|
181
|
+
warranty or additional liability.
|
|
182
|
+
|
|
183
|
+
END OF TERMS AND CONDITIONS
|
|
184
|
+
|
|
185
|
+
APPENDIX: How to apply the Apache License to your work
|
|
186
|
+
|
|
187
|
+
To apply the Apache License to your work, attach the following boilerplate
|
|
188
|
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
|
189
|
+
identifying information. (Don't include the brackets!) The text should be
|
|
190
|
+
enclosed in the appropriate comment syntax for the file format. We also
|
|
191
|
+
recommend that a file or class name and description of purpose be included
|
|
192
|
+
on the same "printed page" as the copyright notice for easier
|
|
193
|
+
identification within third-party archives.
|
|
194
|
+
|
|
195
|
+
Copyright {{ year }} {{ organization }}
|
|
196
|
+
|
|
197
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
198
|
+
you may not use this file except in compliance with the License.
|
|
199
|
+
You may obtain a copy of the License at
|
|
200
|
+
|
|
201
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
202
|
+
|
|
203
|
+
Unless required by applicable law or agreed to in writing, software
|
|
204
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
205
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
|
206
|
+
or implied. See the License for the specific language governing
|
|
207
|
+
permissions and limitations under the License.
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"export enum EventTriggerStrategy {\r\n /**\r\n * Uses PostgreSQL LISTEN/NOTIFY (PG Notify) for real-time event-driven queue triggering.\r\n * \r\n * **How it works:** The engine establishes a persistent subscription to a database channel. \r\n * When an event occurs, Postgres broadcasts an instant notification, triggering the queues \r\n * immediately with minimal latency and zero polling overhead.\r\n * \r\n * **Crucial Infrastructure Requirement:** This strategy **requires a direct, persistent TCP \r\n * connection URL** provided to the Postgres driver. If your database infrastructure uses serverless \r\n * proxies, restricted connection pools, or environments that do not support long-lived TCP socket \r\n * listeners (LISTEN/NOTIFY state), this strategy will fail to receive events.\r\n */\r\n POSTGRES_NOTIFY = \"POSTGRES_NOTIFY\",\r\n\r\n /**\r\n * Uses an external HTTP webhook driven directly by the database (`pg_net`).\r\n * \r\n * **How it works:** This strategy requires an accessible HTTP endpoint to be exposed on the \r\n * running container or machine. When an event occurs, Postgres utilizes the built-in `pg_net` \r\n * extension to fire an outbound HTTP request directly to this endpoint, which in turn invokes \r\n * and executes the event-driven queues.\r\n */\r\n WEBHOOK = \"WEBHOOK\",\r\n\r\n /**\r\n * Uses a database-backed table polling mechanism.\r\n * \r\n * **How it works:** Completely independent of persistent TCP notification sockets or HTTP \r\n * endpoints. Instead, event producers insert new task rows directly into a designated \r\n * subscription table. The engine periodically polls this table at a configured interval \r\n * (e.g., every 500ms) to scan for new rows, process them, and trigger the respective queues.\r\n */\r\n POLLING = \"POLLING\"\r\n}",
|
|
6
6
|
"import { IsolateInstance } from \"../service/Isolate.service.ts\";\r\nimport type { NetworkConfig } from \"../network/interfaces/network.types.ts\";\r\nimport type { BaseEngineConfig } from \"./base.types.ts\";\r\nimport type { PersistentEngine, SelfInvokingEngine } from \"./engine.types.ts\";\r\nimport type { EventTriggerStrategy } from \"./eventTriggerStrategry.types.ts\";\r\n\r\n/**\r\n * Supported runtime execution environments for Pulsar.\r\n */\r\nexport enum PulsarRuntime {\r\n /**\r\n * Configuration for ephemeral V8 isolate environments (Cloudflare Workers, Supabase Edge, Deno Deploy).\r\n * \r\n * In V8 isolate platforms, incoming requests share the same warm memory space until the isolate shuts down.\r\n * The engine relies on the required `isolate` instance to monitor remaining isolate lifespan, handle dynamic global \r\n * state, and sync tick schedules before the V8 isolate gets terminated by the cloud provider.\r\n */\r\n V8_ISOLATE = \"v8-isolate\",\r\n \r\n /**\r\n * Configuration for containerized or persistent runtime environments (AWS Lambda, GCP Cloud Run, Docker, Node.js VMs).\r\n * \r\n * Unlike V8 isolates, these environments operate in dedicated process/container sandboxes with predictable execution limits\r\n * or persistent process lifetimes. Tracking V8 isolate memory and remaining uptime across HTTP invocations is not strictly required.\r\n */\r\n SERVERLESS_VM = \"serverless-vm\",\r\n\r\n /**\r\n * Configuration for traditional, long-running persistent environments (AWS EC2, VPS, Dedicated Servers, local Node.js processes).\r\n * \r\n * Unlike ephemeral isolates or serverless containers that spin down between invocations, persistent runtimes maintain an uninterrupted \r\n * execution context and continuous process lifespan. The engine can rely on background event loops, stateful in-memory caching, \r\n * and non-ephemeral scheduling without relying on cloud provider lifecycle hooks.\r\n */\r\n PERSISTENT = \"persistent\"\r\n}\r\n\r\nexport type PulsarRuntimeType = typeof PulsarRuntime[keyof typeof PulsarRuntime];\r\n\r\nexport type ConfigForRuntime<T extends PulsarRuntimeType> = \r\n T extends typeof PulsarRuntime.V8_ISOLATE ? V8IsolateConfig :\r\n T extends typeof PulsarRuntime.SERVERLESS_VM ? ServerlessVMConfig :\r\n PersistentConfig;\r\n\r\nexport type V8IsolateConfig = BaseEngineConfig & {\r\n runtime : typeof PulsarRuntime.V8_ISOLATE;\r\n engine: SelfInvokingEngine;\r\n /**\r\n * Active isolate tracking instance.\r\n */\r\n isolate : IsolateInstance;\r\n}\r\n\r\nexport type ServerlessVMConfig = BaseEngineConfig & {\r\n runtime : typeof PulsarRuntime.SERVERLESS_VM;\r\n engine: SelfInvokingEngine;\r\n /**\r\n * Optional isolate tracking instance if custom lifecycle tracking is desired inside Lambda or containerized workers.\r\n */\r\n isolate? : IsolateInstance;\r\n}\r\n\r\nexport type PersistentConfig = BaseEngineConfig & {\r\n runtime : typeof PulsarRuntime.PERSISTENT;\r\n \r\n /**\r\n * Optional isolate tracking instance if custom lifecycle tracking is desired inside Lambda or containerized workers.\r\n */\r\n isolate? : IsolateInstance;\r\n\r\n networkInterface : {\r\n /**\r\n * Determines the operational network mode of the server.\r\n * \r\n * - `http`: Opens an HTTP server. Crucial for consumers running dependent workers \r\n * (e.g., when a consumer cannot initialize local storage configuration directly). \r\n * Dependent workers use this HTTP server for acks, retries, etc. \r\n * *(Note: This mode introduces latency and throughput limitations).*\r\n * \r\n * - `socket`: Opens a WebSocket server. Both the pulsar and consumers connect to \r\n * this socket to transport and dispatch jobs. Provides near-realtime job dispatch \r\n * performance for workers.\r\n * \r\n * - `hybrid`: Opens both HTTP and WebSocket servers simultaneously. Ideal for \r\n * multi-runtime deployed consumers where some instances operate in serverless \r\n * functions and others on a VPS, allowing each consumer to select its optimal \r\n * server option based on its specific configuration.\r\n */\r\n mode : Exclude<NetworkConfig[\"mode\"], \"client\">;\r\n /**\r\n * The port number on which the server instance will listen for incoming traffic.\r\n */\r\n port : NetworkConfig[\"port\"];\r\n /**\r\n * Optional hostname or IP address to bind the server to.\r\n */\r\n host? : NetworkConfig[\"host\"];\r\n }\r\n \r\n eventTriggerStrategy : typeof EventTriggerStrategy[keyof typeof EventTriggerStrategy];\r\n engine : PersistentEngine;\r\n}",
|
|
7
|
-
"export interface ILogger {\r\n log(message : string, ...args : any[]) : void;\r\n warn(message : string, ...args : any[]) : void;\r\n error(message : string, ...args : any[]) : void;\r\n debug?(message : string, ...args : any[]) : void;\r\n}\r\n\r\nclass ConsoleLogger implements ILogger {\r\n log(message : string, ...args : any[]) { console.log(message, ...args); }\r\n warn(message : string, ...args : any[]) { console.warn(message, ...args); }\r\n error(message : string, ...args : any[]) { console.error(message, ...args); }\r\n debug(message : string, ...args : any[]) { console.debug(message, ...args); }\r\n}\r\n\r\nexport class LoggerService implements ILogger {\r\n private static provider : ILogger = new ConsoleLogger();\r\n\r\n public setProvider(customLogger: ILogger) {\r\n LoggerService.provider = customLogger;\r\n }\r\n\r\n public log(message : string, ...args : any[]) {\r\n LoggerService.provider.log(message, ...args);\r\n }\r\n\r\n public warn(message : string, ...args : any[]) {\r\n LoggerService.provider.warn(message, ...args);\r\n }\r\n\r\n public error(message : string, ...args : any[]) {\r\n LoggerService.provider.error(message, ...args);\r\n }\r\n\r\n public debug(message : string, ...args : any[]) {\r\n if (LoggerService.provider.debug) {\r\n LoggerService.provider.debug(message, ...args);\r\n }\r\n }\r\n}"
|
|
7
|
+
"export interface ILogger {\r\n log(message : string, ...args : any[]) : void;\r\n warn(message : string, ...args : any[]) : void;\r\n error(message : string, ...args : any[]) : void;\r\n debug?(message : string, ...args : any[]) : void;\r\n}\r\n\r\nclass ConsoleLogger implements ILogger {\r\n log(message : string, ...args : any[]) { console.log(message, ...args); }\r\n warn(message : string, ...args : any[]) { console.warn(message, ...args); }\r\n error(message : string, ...args : any[]) { console.error(message, ...args); }\r\n debug(message : string, ...args : any[]) { console.debug(message, ...args); }\r\n}\r\n\r\nexport class LoggerService implements ILogger {\r\n private static provider : ILogger = new ConsoleLogger();\r\n\r\n public setProvider(customLogger : ILogger) {\r\n LoggerService.provider = customLogger;\r\n }\r\n\r\n public log(message : string, ...args : any[]) {\r\n LoggerService.provider.log(message, ...args);\r\n }\r\n\r\n public warn(message : string, ...args : any[]) {\r\n LoggerService.provider.warn(message, ...args);\r\n }\r\n\r\n public error(message : string, ...args : any[]) {\r\n LoggerService.provider.error(message, ...args);\r\n }\r\n\r\n public debug(message : string, ...args : any[]) {\r\n if (LoggerService.provider.debug) {\r\n LoggerService.provider.debug(message, ...args);\r\n }\r\n }\r\n}"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";;;;AAAO,IAAK,GAAL,CAAK,IAAL,CAaH,kBAAkB,kBAUlB,UAAU,UAUV,UAAU,YAjCF,QCSL,IAAK,GAAL,CAAK,IAAL,CAQH,aAAa,aAQb,gBAAgB,gBAShB,aAAa,eAzBL,QCFZ,MAAM,CAAiC,CACnC,GAAG,CAAC,KAAqB,EAAc,CAAE,QAAQ,IAAI,EAAS,GAAG,CAAI,EACrE,IAAI,CAAC,KAAqB,EAAc,CAAE,QAAQ,KAAK,EAAS,GAAG,CAAI,EACvE,KAAK,CAAC,KAAqB,EAAc,CAAE,QAAQ,MAAM,EAAS,GAAG,CAAI,EACzE,KAAK,CAAC,KAAqB,EAAc,CAAE,QAAQ,MAAM,EAAS,GAAG,CAAI,EAC7E,CAEO,MAAM,CAAiC,OAC3B,UAAqB,IAAI,EAEjC,WAAW,CAAC,
|
|
9
|
+
"mappings": ";;;;AAAO,IAAK,GAAL,CAAK,IAAL,CAaH,kBAAkB,kBAUlB,UAAU,UAUV,UAAU,YAjCF,QCSL,IAAK,GAAL,CAAK,IAAL,CAQH,aAAa,aAQb,gBAAgB,gBAShB,aAAa,eAzBL,QCFZ,MAAM,CAAiC,CACnC,GAAG,CAAC,KAAqB,EAAc,CAAE,QAAQ,IAAI,EAAS,GAAG,CAAI,EACrE,IAAI,CAAC,KAAqB,EAAc,CAAE,QAAQ,KAAK,EAAS,GAAG,CAAI,EACvE,KAAK,CAAC,KAAqB,EAAc,CAAE,QAAQ,MAAM,EAAS,GAAG,CAAI,EACzE,KAAK,CAAC,KAAqB,EAAc,CAAE,QAAQ,MAAM,EAAS,GAAG,CAAI,EAC7E,CAEO,MAAM,CAAiC,OAC3B,UAAqB,IAAI,EAEjC,WAAW,CAAC,EAAwB,CACvC,EAAc,SAAW,EAGtB,GAAG,CAAC,KAAqB,EAAc,CAC1C,EAAc,SAAS,IAAI,EAAS,GAAG,CAAI,EAGxC,IAAI,CAAC,KAAqB,EAAc,CAC3C,EAAc,SAAS,KAAK,EAAS,GAAG,CAAI,EAGzC,KAAK,CAAC,KAAqB,EAAc,CAC5C,EAAc,SAAS,MAAM,EAAS,GAAG,CAAI,EAG1C,KAAK,CAAC,KAAqB,EAAc,CAC5C,GAAI,EAAc,SAAS,MACvB,EAAc,SAAS,MAAM,EAAS,GAAG,CAAI,EAGzD",
|
|
10
10
|
"debugId": "90BBA63A042C7D4764756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"computeConfigDelta.d.ts","sourceRoot":"","sources":["../../src/helpers/computeConfigDelta.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAElE,wBAAgB,kBAAkB,CAAC,MAAM,EAAG,oBAAoB,EAAE,MAAM,EAAG,oBAAoB;;;
|
|
1
|
+
{"version":3,"file":"computeConfigDelta.d.ts","sourceRoot":"","sources":["../../src/helpers/computeConfigDelta.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAElE,wBAAgB,kBAAkB,CAAC,MAAM,EAAG,oBAAoB,EAAE,MAAM,EAAG,oBAAoB;;;eAMvD,MAAM;gBAAW,MAAM;;;eACrB,MAAM;gBAAW,MAAM;;;eACtB,MAAM;mBAAc,MAAM;mBAAc,MAAM;;EA4BxF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateShaHash.d.ts","sourceRoot":"","sources":["../../src/helpers/generateShaHash.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"generateShaHash.d.ts","sourceRoot":"","sources":["../../src/helpers/generateShaHash.ts"],"names":[],"mappings":"AAAA,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAI,OAAO,CAAC,MAAM,CAAC,CAOhE"}
|
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Pulsar by NightX
|
|
3
3
|
* Copyright (c) 2026 NightX. All rights reserved.
|
|
4
4
|
*/
|
|
5
|
-
import{a as q$,b as v$,c as x$}from"./chunk-a9kye38b.js";import{d as z,e as F}from"./chunk-rrj8rm04.js";import{f as m0,g as l,h as I}from"./chunk-cpn1qh4e.js";import{i as F0,j as U}from"./chunk-3sg08kqp.js";var g0=U((sW,J0)=>{var f$=Object.prototype.hasOwnProperty,k="~";function q(){}if(Object.create){if(q.prototype=Object.create(null),!new q().__proto__)k=!1}function d$($,W,P){this.fn=$,this.context=W,this.once=P||!1}function L0($,W,P,Z,X){if(typeof P!=="function")throw TypeError("The listener must be a function");var Q=new d$(P,Z||$,X),G=k?k+W:W;if(!$._events[G])$._events[G]=Q,$._eventsCount++;else if(!$._events[G].fn)$._events[G].push(Q);else $._events[G]=[$._events[G],Q];return $}function f($,W){if(--$._eventsCount===0)$._events=new q;else delete $._events[W]}function R(){this._events=new q,this._eventsCount=0}R.prototype.eventNames=function(){var W=[],P,Z;if(this._eventsCount===0)return W;for(Z in P=this._events)if(f$.call(P,Z))W.push(k?Z.slice(1):Z);if(Object.getOwnPropertySymbols)return W.concat(Object.getOwnPropertySymbols(P));return W};R.prototype.listeners=function(W){var P=k?k+W:W,Z=this._events[P];if(!Z)return[];if(Z.fn)return[Z.fn];for(var X=0,Q=Z.length,G=Array(Q);X<Q;X++)G[X]=Z[X].fn;return G};R.prototype.listenerCount=function(W){var P=k?k+W:W,Z=this._events[P];if(!Z)return 0;if(Z.fn)return 1;return Z.length};R.prototype.emit=function(W,P,Z,X,Q,G){var J=k?k+W:W;if(!this._events[J])return!1;var N=this._events[J],H=arguments.length,K,V;if(N.fn){if(N.once)this.removeListener(W,N.fn,void 0,!0);switch(H){case 1:return N.fn.call(N.context),!0;case 2:return N.fn.call(N.context,P),!0;case 3:return N.fn.call(N.context,P,Z),!0;case 4:return N.fn.call(N.context,P,Z,X),!0;case 5:return N.fn.call(N.context,P,Z,X,Q),!0;case 6:return N.fn.call(N.context,P,Z,X,Q,G),!0}for(V=1,K=Array(H-1);V<H;V++)K[V-1]=arguments[V];N.fn.apply(N.context,K)}else{var M=N.length,w;for(V=0;V<M;V++){if(N[V].once)this.removeListener(W,N[V].fn,void 0,!0);switch(H){case 1:N[V].fn.call(N[V].context);break;case 2:N[V].fn.call(N[V].context,P);break;case 3:N[V].fn.call(N[V].context,P,Z);break;case 4:N[V].fn.call(N[V].context,P,Z,X);break;default:if(!K)for(w=1,K=Array(H-1);w<H;w++)K[w-1]=arguments[w];N[V].fn.apply(N[V].context,K)}}}return!0};R.prototype.on=function(W,P,Z){return L0(this,W,P,Z,!1)};R.prototype.once=function(W,P,Z){return L0(this,W,P,Z,!0)};R.prototype.removeListener=function(W,P,Z,X){var Q=k?k+W:W;if(!this._events[Q])return this;if(!P)return f(this,Q),this;var G=this._events[Q];if(G.fn){if(G.fn===P&&(!X||G.once)&&(!Z||G.context===Z))f(this,Q)}else{for(var J=0,N=[],H=G.length;J<H;J++)if(G[J].fn!==P||X&&!G[J].once||Z&&G[J].context!==Z)N.push(G[J]);if(N.length)this._events[Q]=N.length===1?N[0]:N;else f(this,Q)}return this};R.prototype.removeAllListeners=function(W){var P;if(W){if(P=k?k+W:W,this._events[P])f(this,P)}else this._events=new q,this._eventsCount=0;return this};R.prototype.off=R.prototype.removeListener;R.prototype.addListener=R.prototype.on;R.prefixed=k;R.EventEmitter=R;if(typeof J0<"u")J0.exports=R});var d=U((j0)=>{Object.defineProperty(j0,"__esModule",{value:!0});j0.utf8Count=i$;j0.utf8EncodeJs=v0;j0.utf8EncodeTE=x0;j0.utf8Encode=c$;j0.utf8DecodeJs=l0;j0.utf8DecodeTD=q0;j0.utf8Decode=s$;function i$($){let W=$.length,P=0,Z=0;while(Z<W){let X=$.charCodeAt(Z++);if((X&4294967168)===0){P++;continue}else if((X&4294965248)===0)P+=2;else{if(X>=55296&&X<=56319){if(Z<W){let Q=$.charCodeAt(Z);if((Q&64512)===56320)++Z,X=((X&1023)<<10)+(Q&1023)+65536}}if((X&4294901760)===0)P+=3;else P+=4}}return P}function v0($,W,P){let Z=$.length,X=P,Q=0;while(Q<Z){let G=$.charCodeAt(Q++);if((G&4294967168)===0){W[X++]=G;continue}else if((G&4294965248)===0)W[X++]=G>>6&31|192;else{if(G>=55296&&G<=56319){if(Q<Z){let J=$.charCodeAt(Q);if((J&64512)===56320)++Q,G=((G&1023)<<10)+(J&1023)+65536}}if((G&4294901760)===0)W[X++]=G>>12&15|224,W[X++]=G>>6&63|128;else W[X++]=G>>18&7|240,W[X++]=G>>12&63|128,W[X++]=G>>6&63|128}W[X++]=G&63|128}}var r$=new TextEncoder,n$=50;function x0($,W,P){r$.encodeInto($,W.subarray(P))}function c$($,W,P){if($.length>n$)x0($,W,P);else v0($,W,P)}var a$=4096;function l0($,W,P){let Z=W,X=Z+P,Q=[],G="";while(Z<X){let J=$[Z++];if((J&128)===0)Q.push(J);else if((J&224)===192){let N=$[Z++]&63;Q.push((J&31)<<6|N)}else if((J&240)===224){let N=$[Z++]&63,H=$[Z++]&63;Q.push((J&31)<<12|N<<6|H)}else if((J&248)===240){let N=$[Z++]&63,H=$[Z++]&63,K=$[Z++]&63,V=(J&7)<<18|N<<12|H<<6|K;if(V>65535)V-=65536,Q.push(V>>>10&1023|55296),V=56320|V&1023;Q.push(V)}else Q.push(J);if(Q.length>=a$)G+=String.fromCharCode(...Q),Q.length=0}if(Q.length>0)G+=String.fromCharCode(...Q);return G}var u$=new TextDecoder,o$=200;function q0($,W,P){let Z=$.subarray(W,W+P);return u$.decode(Z)}function s$($,W,P){if(P>o$)return q0($,W,P);else return l0($,W,P)}});var V0=U((y0)=>{Object.defineProperty(y0,"__esModule",{value:!0});y0.ExtData=void 0;class p0{type;data;constructor($,W){this.type=$,this.data=W}}y0.ExtData=p0});var i=U((d0)=>{Object.defineProperty(d0,"__esModule",{value:!0});d0.DecodeError=void 0;class b extends Error{constructor($){super($);let W=Object.create(b.prototype);Object.setPrototypeOf(this,W),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:b.name})}}d0.DecodeError=b});var r=U((i0)=>{Object.defineProperty(i0,"__esModule",{value:!0});i0.UINT32_MAX=void 0;i0.setUint64=Q1;i0.setInt64=G1;i0.getInt64=N1;i0.getUint64=J1;i0.UINT32_MAX=4294967295;function Q1($,W,P){let Z=P/4294967296,X=P;$.setUint32(W,Z),$.setUint32(W+4,X)}function G1($,W,P){let Z=Math.floor(P/4294967296),X=P;$.setUint32(W,Z),$.setUint32(W+4,X)}function N1($,W){let P=$.getInt32(W),Z=$.getUint32(W+4);return P*4294967296+Z}function J1($,W){let P=$.getUint32(W),Z=$.getUint32(W+4);return P*4294967296+Z}});var H0=U((t0)=>{Object.defineProperty(t0,"__esModule",{value:!0});t0.timestampExtension=t0.EXT_TIMESTAMP=void 0;t0.encodeTimeSpecToTimestamp=c0;t0.encodeDateToTimeSpec=a0;t0.encodeTimestampExtension=u0;t0.decodeTimestampToTimeSpec=o0;t0.decodeTimestampExtension=s0;var Y1=i(),n0=r();t0.EXT_TIMESTAMP=-1;var M1=4294967295,U1=17179869183;function c0({sec:$,nsec:W}){if($>=0&&W>=0&&$<=U1)if(W===0&&$<=M1){let P=new Uint8Array(4);return new DataView(P.buffer).setUint32(0,$),P}else{let P=$/4294967296,Z=$&4294967295,X=new Uint8Array(8),Q=new DataView(X.buffer);return Q.setUint32(0,W<<2|P&3),Q.setUint32(4,Z),X}else{let P=new Uint8Array(12),Z=new DataView(P.buffer);return Z.setUint32(0,W),(0,n0.setInt64)(Z,4,$),P}}function a0($){let W=$.getTime(),P=Math.floor(W/1000),Z=(W-P*1000)*1e6,X=Math.floor(Z/1e9);return{sec:P+X,nsec:Z-X*1e9}}function u0($){if($ instanceof Date){let W=a0($);return c0(W)}else return null}function o0($){let W=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let P=W.getUint32(0),Z=0;return{sec:P,nsec:0}}case 8:{let P=W.getUint32(0),Z=W.getUint32(4),X=(P&3)*4294967296+Z,Q=P>>>2;return{sec:X,nsec:Q}}case 12:{let P=(0,n0.getInt64)(W,4),Z=W.getUint32(0);return{sec:P,nsec:Z}}default:throw new Y1.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function s0($){let W=o0($);return new Date(W.sec*1000+W.nsec/1e6)}t0.timestampExtension={type:t0.EXT_TIMESTAMP,encode:u0,decode:s0}});var c=U((W$)=>{Object.defineProperty(W$,"__esModule",{value:!0});W$.ExtensionCodec=void 0;var n=V0(),O1=H0();class Y0{static defaultCodec=new Y0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(O1.timestampExtension)}register({type:$,encode:W,decode:P}){if($>=0)this.encoders[$]=W,this.decoders[$]=P;else{let Z=-1-$;this.builtInEncoders[Z]=W,this.builtInDecoders[Z]=P}}tryToEncode($,W){for(let P=0;P<this.builtInEncoders.length;P++){let Z=this.builtInEncoders[P];if(Z!=null){let X=Z($,W);if(X!=null){let Q=-1-P;return new n.ExtData(Q,X)}}}for(let P=0;P<this.encoders.length;P++){let Z=this.encoders[P];if(Z!=null){let X=Z($,W);if(X!=null){let Q=P;return new n.ExtData(Q,X)}}}if($ instanceof n.ExtData)return $;return null}decode($,W,P){let Z=W<0?this.builtInDecoders[-1-W]:this.decoders[W];if(Z)return Z($,W,P);else return new n.ExtData(W,$)}}W$.ExtensionCodec=Y0});var M0=U((Z$)=>{Object.defineProperty(Z$,"__esModule",{value:!0});Z$.ensureUint8Array=S1;function A1($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function S1($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(A1($))return new Uint8Array($);else return Uint8Array.from($)}});var w0=U((G$)=>{Object.defineProperty(G$,"__esModule",{value:!0});G$.Encoder=G$.DEFAULT_INITIAL_BUFFER_SIZE=G$.DEFAULT_MAX_DEPTH=void 0;var X$=d(),B1=c(),Q$=r(),D1=M0();G$.DEFAULT_MAX_DEPTH=100;G$.DEFAULT_INITIAL_BUFFER_SIZE=2048;class U0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??B1.ExtensionCodec.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??G$.DEFAULT_MAX_DEPTH,this.initialBufferSize=$?.initialBufferSize??G$.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new U0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,W){if(W>this.maxDepth)throw Error(`Too deep objects in depth ${W}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,W)}ensureBufferSizeToWrite($){let W=this.pos+$;if(this.view.byteLength<W)this.resizeBuffer(W*2)}resizeBuffer($){let W=new ArrayBuffer($),P=new Uint8Array(W),Z=new DataView(W);P.set(this.bytes),this.view=Z,this.bytes=P}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let P=(0,X$.utf8Count)($);this.ensureBufferSizeToWrite(5+P),this.writeStringHeader(P),(0,X$.utf8Encode)($,this.bytes,this.pos),this.pos+=P}encodeObject($,W){let P=this.extensionCodec.tryToEncode($,this.context);if(P!=null)this.encodeExtension(P);else if(Array.isArray($))this.encodeArray($,W);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,W);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let W=$.byteLength;if(W<256)this.writeU8(196),this.writeU8(W);else if(W<65536)this.writeU8(197),this.writeU16(W);else if(W<4294967296)this.writeU8(198),this.writeU32(W);else throw Error(`Too large binary: ${W}`);let P=(0,D1.ensureUint8Array)($);this.writeU8a(P)}encodeArray($,W){let P=$.length;if(P<16)this.writeU8(144+P);else if(P<65536)this.writeU8(220),this.writeU16(P);else if(P<4294967296)this.writeU8(221),this.writeU32(P);else throw Error(`Too large array: ${P}`);for(let Z of $)this.doEncode(Z,W+1)}countWithoutUndefined($,W){let P=0;for(let Z of W)if($[Z]!==void 0)P++;return P}encodeMap($,W){let P=Object.keys($);if(this.sortKeys)P.sort();let Z=this.ignoreUndefined?this.countWithoutUndefined($,P):P.length;if(Z<16)this.writeU8(128+Z);else if(Z<65536)this.writeU8(222),this.writeU16(Z);else if(Z<4294967296)this.writeU8(223),this.writeU32(Z);else throw Error(`Too large map object: ${Z}`);for(let X of P){let Q=$[X];if(!(this.ignoreUndefined&&Q===void 0))this.encodeString(X),this.doEncode(Q,W+1)}}encodeExtension($){if(typeof $.data==="function"){let P=$.data(this.pos+6),Z=P.length;if(Z>=4294967296)throw Error(`Too large extension object: ${Z}`);this.writeU8(201),this.writeU32(Z),this.writeI8($.type),this.writeU8a(P);return}let W=$.data.length;if(W===1)this.writeU8(212);else if(W===2)this.writeU8(213);else if(W===4)this.writeU8(214);else if(W===8)this.writeU8(215);else if(W===16)this.writeU8(216);else if(W<256)this.writeU8(199),this.writeU8(W);else if(W<65536)this.writeU8(200),this.writeU16(W);else if(W<4294967296)this.writeU8(201),this.writeU32(W);else throw Error(`Too large extension object: ${W}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let W=$.length;this.ensureBufferSizeToWrite(W),this.bytes.set($,this.pos),this.pos+=W}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),(0,Q$.setUint64)(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),(0,Q$.setInt64)(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}G$.Encoder=U0});var V$=U((K$)=>{Object.defineProperty(K$,"__esModule",{value:!0});K$.encode=h1;var C1=w0();function h1($,W){return new C1.Encoder(W).encodeSharedRef($)}});var Y$=U((H$)=>{Object.defineProperty(H$,"__esModule",{value:!0});H$.prettyByte=L1;function L1($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}});var R$=U((U$)=>{Object.defineProperty(U$,"__esModule",{value:!0});U$.CachedKeyDecoder=void 0;var _1=d(),E1=16,v1=16;class M${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=E1,W=v1){this.maxKeyLength=$,this.maxLengthPerKey=W,this.caches=[];for(let P=0;P<this.maxKeyLength;P++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,W,P){let Z=this.caches[P-1];$:for(let X of Z){let Q=X.bytes;for(let G=0;G<P;G++)if(Q[G]!==$[W+G])continue $;return X.str}return null}store($,W){let P=this.caches[$.length-1],Z={bytes:$,str:W};if(P.length>=this.maxLengthPerKey)P[Math.random()*P.length|0]=Z;else P.push(Z)}decode($,W,P){let Z=this.find($,W,P);if(Z!=null)return this.hit++,Z;this.miss++;let X=(0,_1.utf8DecodeJs)($,W,P),Q=Uint8Array.prototype.slice.call($,W,W+P);return this.store(Q,X),X}}U$.CachedKeyDecoder=M$});var a=U((A$)=>{Object.defineProperty(A$,"__esModule",{value:!0});A$.Decoder=void 0;var R0=Y$(),x1=c(),D=r(),l1=d(),k$=M0(),q1=R$(),O=i(),k0="array",p="map_key",T$="map_value",j1=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new O.DecodeError("The type of key must be string or number but "+typeof $)};class O${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let W=this.getUninitializedStateFromPool();W.type=k0,W.position=0,W.size=$,W.array=Array($)}pushMapState($){let W=this.getUninitializedStateFromPool();W.type=p,W.readCount=0,W.size=$,W.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===k0){let P=$;P.size=0,P.array=void 0,P.position=0,P.type=void 0}if($.type===p||$.type===T$){let P=$;P.size=0,P.map=void 0,P.readCount=0,P.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var j=-1,I0=new DataView(new ArrayBuffer(0)),p1=new Uint8Array(I0.buffer);try{I0.getInt8(0)}catch($){if(!($ instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var I$=RangeError("Insufficient data"),y1=new q1.CachedKeyDecoder;class T0{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=I0;bytes=p1;headByte=j;stack=new O$;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??x1.ExtensionCodec.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??D.UINT32_MAX,this.maxBinLength=$?.maxBinLength??D.UINT32_MAX,this.maxArrayLength=$?.maxArrayLength??D.UINT32_MAX,this.maxMapLength=$?.maxMapLength??D.UINT32_MAX,this.maxExtLength=$?.maxExtLength??D.UINT32_MAX,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:y1,this.mapKeyConverter=$?.mapKeyConverter??j1}clone(){return new T0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=j,this.stack.reset()}setBuffer($){let W=(0,k$.ensureUint8Array)($);this.bytes=W,this.view=new DataView(W.buffer,W.byteOffset,W.byteLength),this.pos=0}appendBuffer($){if(this.headByte===j&&!this.hasRemaining(1))this.setBuffer($);else{let W=this.bytes.subarray(this.pos),P=(0,k$.ensureUint8Array)($),Z=new Uint8Array(W.length+P.length);Z.set(W),Z.set(P,W.length),this.setBuffer(Z)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:W,pos:P}=this;return RangeError(`Extra ${W.byteLength-P} of ${W.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let W=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return W}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let W=!1,P;for await(let G of $){if(W)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(G);try{P=this.doDecodeSync(),W=!0}catch(J){if(!(J instanceof RangeError))throw J}this.totalPos+=this.pos}if(W){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return P}let{headByte:Z,pos:X,totalPos:Q}=this;throw RangeError(`Insufficient data in parsing ${(0,R0.prettyByte)(Z)} at ${Q} (${X} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,W){if(this.entered){yield*this.clone().decodeMultiAsync($,W);return}try{this.entered=!0;let P=W,Z=-1;for await(let X of $){if(W&&Z===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(X),P)Z=this.readArraySize(),P=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--Z===0)break}catch(Q){if(!(Q instanceof RangeError))throw Q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),W;if($>=224)W=$-256;else if($<192)if($<128)W=$;else if($<144){let Z=$-128;if(Z!==0){this.pushMapState(Z),this.complete();continue $}else W={}}else if($<160){let Z=$-144;if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else W=[]}else{let Z=$-160;W=this.decodeString(Z,0)}else if($===192)W=null;else if($===194)W=!1;else if($===195)W=!0;else if($===202)W=this.readF32();else if($===203)W=this.readF64();else if($===204)W=this.readU8();else if($===205)W=this.readU16();else if($===206)W=this.readU32();else if($===207)if(this.useBigInt64)W=this.readU64AsBigInt();else W=this.readU64();else if($===208)W=this.readI8();else if($===209)W=this.readI16();else if($===210)W=this.readI32();else if($===211)if(this.useBigInt64)W=this.readI64AsBigInt();else W=this.readI64();else if($===217){let Z=this.lookU8();W=this.decodeString(Z,1)}else if($===218){let Z=this.lookU16();W=this.decodeString(Z,2)}else if($===219){let Z=this.lookU32();W=this.decodeString(Z,4)}else if($===220){let Z=this.readU16();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else W=[]}else if($===221){let Z=this.readU32();if(Z!==0){this.pushArrayState(Z),this.complete();continue $}else W=[]}else if($===222){let Z=this.readU16();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else W={}}else if($===223){let Z=this.readU32();if(Z!==0){this.pushMapState(Z),this.complete();continue $}else W={}}else if($===196){let Z=this.lookU8();W=this.decodeBinary(Z,1)}else if($===197){let Z=this.lookU16();W=this.decodeBinary(Z,2)}else if($===198){let Z=this.lookU32();W=this.decodeBinary(Z,4)}else if($===212)W=this.decodeExtension(1,0);else if($===213)W=this.decodeExtension(2,0);else if($===214)W=this.decodeExtension(4,0);else if($===215)W=this.decodeExtension(8,0);else if($===216)W=this.decodeExtension(16,0);else if($===199){let Z=this.lookU8();W=this.decodeExtension(Z,1)}else if($===200){let Z=this.lookU16();W=this.decodeExtension(Z,2)}else if($===201){let Z=this.lookU32();W=this.decodeExtension(Z,4)}else throw new O.DecodeError(`Unrecognized type byte: ${(0,R0.prettyByte)($)}`);this.complete();let P=this.stack;while(P.length>0){let Z=P.top();if(Z.type===k0)if(Z.array[Z.position]=W,Z.position++,Z.position===Z.size)W=Z.array,P.release(Z);else continue $;else if(Z.type===p){if(W==="__proto__")throw new O.DecodeError("The key __proto__ is not allowed");Z.key=this.mapKeyConverter(W),Z.type=T$;continue $}else if(Z.map[Z.key]=W,Z.readCount++,Z.readCount===Z.size)W=Z.map,P.release(Z);else{Z.key=null,Z.type=p;continue $}}return W}}readHeadByte(){if(this.headByte===j)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=j}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new O.DecodeError(`Unrecognized array type byte: ${(0,R0.prettyByte)($)}`)}}pushMapState($){if($>this.maxMapLength)throw new O.DecodeError(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new O.DecodeError(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,W){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,W);return this.decodeBinary($,W)}decodeUtf8String($,W){if($>this.maxStrLength)throw new O.DecodeError(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+W+$)throw I$;let P=this.pos+W,Z;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))Z=this.keyDecoder.decode(this.bytes,P,$);else Z=(0,l1.utf8Decode)(this.bytes,P,$);return this.pos+=W+$,Z}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===p;return!1}decodeBinary($,W){if($>this.maxBinLength)throw new O.DecodeError(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+W))throw I$;let P=this.pos+W,Z=this.bytes.subarray(P,P+$);return this.pos+=W+$,Z}decodeExtension($,W){if($>this.maxExtLength)throw new O.DecodeError(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let P=this.view.getInt8(this.pos+W),Z=this.decodeBinary($,W+1);return this.extensionCodec.decode(Z,P,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=(0,D.getUint64)(this.view,this.pos);return this.pos+=8,$}readI64(){let $=(0,D.getInt64)(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}A$.Decoder=T0});var D$=U((B$)=>{Object.defineProperty(B$,"__esModule",{value:!0});B$.decode=f1;B$.decodeMulti=d1;var z$=a();function f1($,W){return new z$.Decoder(W).decode($)}function d1($,W){return new z$.Decoder(W).decodeMulti($)}});var L$=U((m$)=>{Object.defineProperty(m$,"__esModule",{value:!0});m$.isAsyncIterable=C$;m$.asyncIterableFromStream=h$;m$.ensureAsyncIterable=r1;function C$($){return $[Symbol.asyncIterator]!=null}async function*h$($){let W=$.getReader();try{while(!0){let{done:P,value:Z}=await W.read();if(P)return;yield Z}}finally{W.releaseLock()}}function r1($){if(C$($))return $;else return h$($)}});var _$=U((g$)=>{Object.defineProperty(g$,"__esModule",{value:!0});g$.decodeAsync=u1;g$.decodeArrayStream=o1;g$.decodeMultiStream=s1;var O0=a(),A0=L$();async function u1($,W){let P=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeAsync(P)}function o1($,W){let P=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeArrayStream(P)}function s1($,W){let P=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeStream(P)}});var z0=U((Y)=>{Object.defineProperty(Y,"__esModule",{value:!0});Y.decodeTimestampExtension=Y.encodeTimestampExtension=Y.decodeTimestampToTimeSpec=Y.encodeTimeSpecToTimestamp=Y.encodeDateToTimeSpec=Y.EXT_TIMESTAMP=Y.ExtData=Y.ExtensionCodec=Y.Encoder=Y.DecodeError=Y.Decoder=Y.decodeMultiStream=Y.decodeArrayStream=Y.decodeAsync=Y.decodeMulti=Y.decode=Y.encode=void 0;var WW=V$();Object.defineProperty(Y,"encode",{enumerable:!0,get:function(){return WW.encode}});var E$=D$();Object.defineProperty(Y,"decode",{enumerable:!0,get:function(){return E$.decode}});Object.defineProperty(Y,"decodeMulti",{enumerable:!0,get:function(){return E$.decodeMulti}});var S0=_$();Object.defineProperty(Y,"decodeAsync",{enumerable:!0,get:function(){return S0.decodeAsync}});Object.defineProperty(Y,"decodeArrayStream",{enumerable:!0,get:function(){return S0.decodeArrayStream}});Object.defineProperty(Y,"decodeMultiStream",{enumerable:!0,get:function(){return S0.decodeMultiStream}});var PW=a();Object.defineProperty(Y,"Decoder",{enumerable:!0,get:function(){return PW.Decoder}});var ZW=i();Object.defineProperty(Y,"DecodeError",{enumerable:!0,get:function(){return ZW.DecodeError}});var XW=w0();Object.defineProperty(Y,"Encoder",{enumerable:!0,get:function(){return XW.Encoder}});var QW=c();Object.defineProperty(Y,"ExtensionCodec",{enumerable:!0,get:function(){return QW.ExtensionCodec}});var GW=V0();Object.defineProperty(Y,"ExtData",{enumerable:!0,get:function(){return GW.ExtData}});var L=H0();Object.defineProperty(Y,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return L.EXT_TIMESTAMP}});Object.defineProperty(Y,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return L.encodeDateToTimeSpec}});Object.defineProperty(Y,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return L.encodeTimeSpecToTimestamp}});Object.defineProperty(Y,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return L.decodeTimestampToTimeSpec}});Object.defineProperty(Y,"encodeTimestampExtension",{enumerable:!0,get:function(){return L.encodeTimestampExtension}});Object.defineProperty(Y,"decodeTimestampExtension",{enumerable:!0,get:function(){return L.decodeTimestampExtension}})});function p$($){return{...$,consumer:{...$.consumer,queue:$.queue}}}class h0{MAX_ISOLATE_LIFESPAN_MS;constructor($){this.MAX_ISOLATE_LIFESPAN_MS=$;this.set("isolate_id",crypto.randomUUID()),this.set("isolate_start_time",Date.now()),this.set("isolate_max_life_span_ms",this.MAX_ISOLATE_LIFESPAN_MS)}isSameIsolate($){return $===this.get("isolate_id")}get id(){return this.get("isolate_id")??crypto.randomUUID()}get remainingTime(){let $=this.get("isolate_start_time"),W=this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS;if(typeof $!=="number")return W;let P=Date.now()-$;return Math.max(0,W-P)}get uptime(){let $=this.get("isolate_start_time");return typeof $==="number"?Date.now()-$:0}get maxTime(){return this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS}set($,W){globalThis[$]=W}get($){return globalThis[$]}}import JW from"js-sha256";class E{target=new EventTarget;pending=new Set;track($){let W=$.catch((P)=>console.error("[EventBus] : handler failed - ",P)).finally(()=>this.pending.delete(W));this.pending.add(W)}emit($,W){this.target.dispatchEvent(new CustomEvent($,{detail:W}))}on($,W){let P=(Z)=>{let X=W(Z.detail);if(X instanceof Promise)this.track(X)};return this.target.addEventListener($,P),()=>this.target.removeEventListener($,P)}once($,W){let P=(Z)=>W(Z.detail);this.target.addEventListener($,P,{once:!0})}async drain(){while(this.pending.size>0)await Promise.allSettled([...this.pending])}}class e{tracks=[];startTime;maxExecutionBudgetMs;safetyBufferMs;maxTrackHistory;enabled;cpuExecutionMicroseconds=0;constructor($={}){this.startTime=performance.now(),this.maxExecutionBudgetMs=$.maxExecutionBudgetMs??25000,this.safetyBufferMs=$.safetyBufferMs??2000,this.maxTrackHistory=$.maxTrackHistory??100,this.enabled=$.enabled??!1}async trackExecutionTime({contextId:$},W){let P=performance.now();try{return await W()}finally{if(this.enabled==!0){let X=performance.now()-P;if(this.tracks.push({id:crypto.randomUUID(),duration:X,contextId:$}),this.tracks.length>this.maxTrackHistory)this.tracks.shift()}}}getElapsedTotalTime(){return performance.now()-this.startTime}getTimeRemaining(){let $=this.getElapsedTotalTime(),W=this.maxExecutionBudgetMs-$-this.safetyBufferMs;return Math.max(0,W)}getAverageTickDuration($=5){if(this.tracks.length===0)return 0;let W=this.tracks.slice(-$);return W.reduce((Z,X)=>Z+X.duration,0)/W.length}isSafeToContinue(){if(!this.enabled)return!0;let $=this.getTimeRemaining();if($<=0)return!1;let W=this.getAverageTickDuration(5);if(W>0&&$<W)return!1;return!0}clear($){this.tracks=this.tracks.filter((W)=>W.contextId!==$)}}class $0{maxGlobalJobsPerTick;maxGlobalConcurrency;constructor($,W){this.maxGlobalJobsPerTick=$;this.maxGlobalConcurrency=W}getMaxGlobalConcurrency(){return this.maxGlobalConcurrency}getMaxGlobalJobsPerTick(){return this.maxGlobalJobsPerTick}}var S={REALTIME:{activePollMs:1000,backoffPollMs:1000,idlePollMs:1000,maxTimerMs:5000},STANDARD:{activePollMs:100,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},BALANCED:{activePollMs:1e4,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},RELAXED:{activePollMs:1000,backoffPollMs:20000,idlePollMs:30000,maxTimerMs:60000},ULTRA_EFFICIENT:{activePollMs:5000,backoffPollMs:1e5,idlePollMs:120000,maxTimerMs:240000}};var y$=2147483647;class W0{timers=new Map;profiles=new Map;constructor(){}registerQueueProfile($,W){if(typeof W==="string"){let P=W!=="CUSTOM"?S[W]:void 0;this.profiles.set($,P??S.STANDARD)}else this.profiles.set($,W)}getProfile($){let P=F.get("queues")?.find((Z)=>Z.queue===$)?.profile;if(P){if(typeof P==="string")return P!=="CUSTOM"?S[P]:S.STANDARD;if(typeof P==="object")return P}return this.profiles.get($)??S.STANDARD}cancel($){let W=this.timers.get($);if(W)clearTimeout(W);this.timers.delete($)}scheduleNext($){let{metrics:W,onNext:P,onUpcomingDelayedNext:Z,onFutureSchedule:X}=$,{queue:Q,readyJobs:G,delayedJobs:J,availableSlots:N,nextVisibleAt:H}=W;this.cancel(Q);let K=this.getProfile(Q);if(G>0&&N>0){this.setTimer(Q,P,K.activePollMs);return}if(G>0&&N===0){this.setTimer(Q,P,K.backoffPollMs);return}if(J>0&&H){let V=Math.max(0,H-Date.now());if(V<=K.maxTimerMs){if(Z)Z(V);this.setTimer(Q,P,V);return}if(X)X(H).catch((M)=>console.error(`Scheduler error setting long delay for ${Q}:`,M));return}if(K.idlePollMs)this.setTimer(Q,P,K.idlePollMs)}setTimer($,W,P){let Z=Math.min(Math.max(0,P),y$),X=()=>{this.timers.delete($),W()};if(Z===0){let G=setTimeout(X);this.timers.set($,G);return}let Q=setTimeout(X,Z);this.timers.set($,Q)}}class P0{logger;transitionItems=new Set;constructor($){this.logger=$}transitionToIdleMode({queue:$,stateTransitionPolicy:W}){if(this.transitionItems.has($))return;if(this.transitionItems.add($),this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to IDLE. Queue config: (${$})`),W?.enabled){let P=W.idleTimingProfile;if(P){let Z=typeof P==="object"?{activePollMs:P.activePollMs,backoffPollMs:P.backoffPollMs,idlePollMs:P.idlePollMs}:S[P];F.modifyQueue($,"profile",Z)}}}transitionToActiveMode({queue:$,profile:W,stateTransitionPolicy:P}){if(this.transitionItems.delete($),P?.enabled)F.modifyQueue($,"profile",W);this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to ACTIVE. Queue config: (${$})`)}}class Z0{storage;queue;executionProfileSwitcher;unifiedTransportManager;swarmManager;PROCESS_ID;globalSequence=0;consecutiveEmptyTicks=0;logger;events;constructor({queue:$,storage:W,swarmManager:P,unifiedTransportManager:Z,events:X}){this.storage=W,this.queue=$,this.swarmManager=P,this.unifiedTransportManager=Z,this.logger=new I,this.executionProfileSwitcher=new P0(this.logger),this.PROCESS_ID=crypto.randomUUID().slice(0,12),this.globalSequence=0,this.events=X}async run($,W){let{concurrency:P,queue:Z}=$,X=this.swarmManager.getMaxGlobalConcurrency(),{batches:Q,window:G}=await this.getCandidatesBatch({queueConfig:$,maxGlobalSlotsAllowed:W}),J=$.stateTransitionPolicy?.enabled==!0;if(!Q||Q.length===0){if(J){if(this.consecutiveEmptyTicks++,this.consecutiveEmptyTicks>=($.stateTransitionPolicy?.idleThresholdTicks??10))this.executionProfileSwitcher.transitionToIdleMode($)}this.logger.warn(`[Tick] : [${Z}] - Empty Tick Executred)`);return}if(J&&this.consecutiveEmptyTicks>0)this.consecutiveEmptyTicks=0,this.executionProfileSwitcher.transitionToActiveMode($);let N=await this.storage.repository.registerWorker(Z,Q,P,X),H=new Set(N),K=Q.filter((V)=>!H.has(V.workerId));if(K.length>0){let V=K.reduce((M,w)=>M+w.batch.length,0);await this.storage.repository.refundGlobalJobBudget(V,G)}if(N.length===0)return;this.logger.log(`[Tick] : [${Z}] - Tick Executred. Total Jobs (${Q.reduce((V,M)=>V+M.batch.length,0)})`),await this.spwanWorkers({candidateBatches:Q,grantedWorkerIds:N,queueConfig:$})}async spwanWorkers({grantedWorkerIds:$,candidateBatches:W,queueConfig:{queue:P}}){if(!$?.length)return;let Z=new Set($),X=W.filter((Q)=>Z.has(Q.workerId));await Promise.allSettled(X.map(({batch:Q,workerId:G})=>{return this.unifiedTransportManager.dispatchToNetwork(P,{batch:Q,worker_id:G})}))}async getCandidatesBatch({queueConfig:$,maxGlobalSlotsAllowed:W}){let{concurrency:P,maxJobsPerTick:Z,queue:X,sleep:Q,n:G}=$,J=await this.storage.repository.getActiveWorkersCount(X),N=Math.max(0,P-J);if(N===0)return{batches:[],window:""};let H=Math.min(N,W);if(H===0)return{batches:[],window:""};let K=H*G,V=Z!==void 0&&Z>0?Z:1/0,M=Math.min(K,V);if(M<=0)return{batches:[],window:""};let w=this.swarmManager.getMaxGlobalJobsPerTick(),{granted:T,window:A}=await this.storage.repository.claimGlobalJobBudget(M,w);if(T<=0)return{batches:[],window:A};let C=await this.queue.read(X,Q??1,T),g=C.length;if(g===0)return await this.storage.repository.refundGlobalJobBudget(T,A),{batches:[],window:A};if(g<T){let m=T-C.length;await this.storage.repository.refundGlobalJobBudget(m,A)}let _=Math.ceil(g/G),h=Array(_),s=Date.now(),t=0;for(let m=0;m<g;m+=G)h[t++]={workerId:`w_${this.PROCESS_ID}_${s}_${this.globalSequence++}`,batch:C.slice(m,m+G)};return{batches:h,window:A}}}class X0{clock;tickService;scheduler;storage;events;runtimeStrategy;tickState=new Map;activeTicks=new Set;lastHealthCheckAt=0;logger;constructor({scheduler:$,storage:W,tickService:P,clock:Z,events:X,runtimeStrategy:Q}){this.logger=new I,this.clock=Z,this.tickService=P,this.scheduler=$,this.storage=W,this.events=X,this.runtimeStrategy=Q,this.initializeState()}initializeState(){this.tickState.clear(),this.activeTicks.clear()}async runTick($){await this.runtimeStrategy.executeTick($,async()=>{let{queue:W}=$;if(this.initializeTickState($),this.activeTicks.has(W)||this.tickState.get(W)?.stopped)return;this.activeTicks.add(W),this.scheduler.cancel(W);try{let P=1/0,Z=F.get("swarmConfig")?.maxGlobalConcurrency;if(Z!==void 0){let X=await this.storage.repository.getGlobalActiveWorkersCount();P=Math.max(0,Z-X)}if(P>0&&!this.tickState.get(W)?.stopped)await this.tickService.run($,P)}catch(P){this.logger.error(`Orchestrator error on ${W}:`,P)}finally{this.activeTicks.delete(W),this.updateTickCounter(W)}if(this.tickState.get(W)?.stopped==!0)return;await this.runtimeStrategy.scheduleTick($,()=>this.runTick($))})}endTick($){let W=this.tickState.get($);if(W){if(W.stopped==!0)return;if(this.tickState.set($,{...W,stopped:!0}),this.scheduler.cancel($),this.clock.clear($),F.raw.queues.every((Z)=>{let X=this.tickState.get(Z.queue);return X?X.stopped:!0}))this.events.emit("tick:cycle-completed",{queue:$,cycles:this.tickState.get($)?.count??1})}}initializeTickState($){if(!this.tickState.get($.queue))this.tickState.set($.queue,{count:0,max:$.cycleTickLimit??10,registred:!0,stopped:!1})}updateTickCounter($){let W=this.tickState.get($)??{count:0,stopped:!1,max:10,registred:!1},P=W.count+1,Z=W.max,X=P>=Z;if((W.stopped||X)&&!W.stopped)this.tickState.set($,{count:P,stopped:W.stopped,max:Z,registred:W.registred}),this.endTick($);else this.tickState.set($,{count:P,stopped:W.stopped,max:Z,registred:W.registred});this.triggerPeriodicHealthCheck()}triggerPeriodicHealthCheck(){let $=Date.now(),W=this.runtimeStrategy.shouldShutdownOnCycleComplete,P=(F.get("engine.healthCheckIntervalSec")??15)*1000;if($-this.lastHealthCheckAt>=P&&!W)this.lastHealthCheckAt=$,this.events.emit("engine:health-check-requested",{timestamp:$})}}class B{queueService;clock;queues;storage;isolate;events;scheduler;logger;constructor($){this.queueService=$.queueService,this.clock=$.clock,this.queues=$.queues,this.isolate=$.isolate,this.storage=$.storage,this.events=$.events,this.scheduler=$.scheduler,this.logger=new I}async executeQueuesTick($){let W=F.get("engine.tickConcurrency");if(this.logger.log(`[Tick Controller] : Execution tick mode has been selected with concurrency ${W}`),W=="sequential"){for(let P of this.queues)if(P.pooler=="interval-driven-pooler")await $(P)}else{let P=await Promise.allSettled(this.queues.filter((Z)=>Z.pooler==="interval-driven-pooler").map((Z)=>$(Z)));for(let Z of P)if(Z.status==="rejected")this.logger.error("[Tick] : Error >>",Z.reason)}}async triggerSelfInvocation($){let{queue:W,pooler:P,delaySec:Z,continuationOwnerId:X,isIdpLock:Q,isEdpLock:G,targetEdpQueue:J}=$,N=F.get("engine.selfURL"),K=F.raw.engine.selfInvocationMethod,V={idpInvoked:!1,continuationScheduledForCurrentLock:!1};if(P==="interval-driven-pooler"){if(V.idpInvoked=!0,Q)V.continuationScheduledForCurrentLock=!0;this.logger.log(`(IDP) : Invoking Self in ${Z} seconds...`)}else if(P==="event-driven-pooler"){if(G&&W===J)V.continuationScheduledForCurrentLock=!0;this.logger.log(`(EDP) : Invoking Self in ${Z} seconds...`)}let M={"content-type":"application/json","x-last-execution-id":X,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"false","x-pooler":P,"x-target-queue":W};if(K=="auto_using_pgnet")await this.queueService.triggerUrl({url:N,headers:M,delaySeconds:Z});else if(typeof K==="object"&&K!==null&&K.method==="manual")await K.handler(N);return V}}class v{storage;logger;runtimeExecutionId;pgNotifyChannel="channel_pulsar_event_driven_queue";events;constructor($,W,P){this.storage=$;this.logger=W;this.runtimeExecutionId=P;this.events=new E}async registerPgNotifyHandler($){await this.storage.ops.subscribeToDatabaseEvents(this.pgNotifyChannel,async(W)=>{this.logger.log(`[Persistent Runtime] : Recived PgNotification Event - ${new Date().toISOString()}`);let P=F.get("queues").find((X)=>X.queue===W.queue_name);if(!P){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue: '${W.queue_name}' on channel: ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity(P.queue,W.fencing_token))await $.runTick(P)},()=>{this.logger.log(`[Persistent Runtime] : Successfully established PostgreSQL notification listener on channel : ${this.pgNotifyChannel}`)})}async registerPollingHandler($){setInterval(async()=>{let W=await this.storage.ops.getPollingQueueEntries("q_3");for(let P of W){let Z=P.payload.queue_name,X=P.payload.fencing_token,Q=await this.handleTriggerValidity(Z,X);if(Q)await $.runTick(Q),await this.storage.ops.deletePollingQueueEntry(P.id)}},F.get("engine.poolingIntervalMS"))}async httpEventDrivenQueueTrigger($,W,P){let Z=F.get("queues").find((Q)=>Q.queue===$);if(!Z){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue : '${$}' on channel : ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity($,W))await P.runTick(Z)}async handleTriggerValidity($,W){let P=F.get("queues").find((J)=>J.queue===$);if(!P)return this.logger.error(`[Persistent Runtime] : pool entry for unregistered or unmanaged queue: '${$}'`),null;if(!await this.storage.ops.checkFencingTokenValidity($,W)){let J=`[EventDrivenPoller]-[ExecutionTrigger]-[${$}] : Engine execution rejected : Invalid fencing token.`;return this.logger.error(J),null}let X=`lock:edp:${$}`,Q=120000;if(await this.storage.repository.acquireQueueLock(X,this.runtimeExecutionId,Q))await this.storage.repository.clearDispatchPending(X);else return this.logger.log(`[Persistent Runtime] : Engine busy for queue ${$}, skipping trigger.`),null;return P}}class x{minBootRequirementSec;scheduler;events;clock;logger;constructor($,W,P,Z,X){this.minBootRequirementSec=$;this.scheduler=W;this.events=P;this.clock=Z;this.logger=X}timers=new Map;watchdogTimer=null;isShutdownTriggered=!1;evaluateUpcomingDelayedNext($,W){let P=F.raw.isolate;if(!P)throw Error("Isolate is not configured for V8_Isolate_Runtime!");let Z=F.get("engine.selfInvocationIntervalSec")??1,X=this.minBootRequirementSec,Q=(Z+X)*1000;if(P.remainingTime-$<Q){this.logger.log(`[Isolate Runtime] Sleep duration of ${$}ms exceeds safe isolate budget. Canceling timer sleep and initiating shutdown.`),this.scheduler.cancel(W),this.triggerGracefulShutdown(W);return}this.startDelayedSleepWatchdog(W,Q)}startDelayedSleepWatchdog($,W){this.stopRuntimeWatchdog(),this.isShutdownTriggered=!1,this.watchdogTimer=setInterval(()=>{let P=F.raw.isolate;if(!P||this.isShutdownTriggered)return;if(P.remainingTime<=W)this.logger.log(`[Isolate Watchdog] Remaining isolate budget (${P.remainingTime}ms) expired during delayed sleep. Canceling wakeup and executing graceful shutdown.`),this.scheduler.cancel($),this.triggerGracefulShutdown($)},1000)}triggerGracefulShutdown($){if(this.isShutdownTriggered)return;this.isShutdownTriggered=!0,this.stopRuntimeWatchdog(),this.events.emit("tick:time-exceeded",{queue:$,elapsedMs:this.clock.getElapsedTotalTime()}),this.events.emit("tick:cycle-completed",{queue:$,cycles:1})}stopRuntimeWatchdog(){if(this.watchdogTimer)clearInterval(this.watchdogTimer),this.watchdogTimer=null}clearTimer($){let W=this.timers.get($);if(W)clearTimeout(W);this.timers.delete($)}forceExecuteTickLater($,W){let Z=`Extended time limit reached ${W}ms elapsed, overriding standard caps !`,X=()=>this.events.emit("tick:force-run",{queue:$,reason:Z}),Q=W-Date.now();if(Q>2147483647)this.timers.set($.queue,setTimeout(()=>{this.forceExecuteTickLater($,W)},2147483647));this.timers.set($.queue,setTimeout(()=>{X()},Math.max(0,Q)))}}class Q0 extends B{type="PERSISTENT";shouldShutdownOnCycleComplete=!1;minBootRequirementSec=1;runtimeExecutionId;deferredTickEvaluator;runtimeEventBridge;rs;constructor($){super($);this.deferredTickEvaluator=new x(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger),this.runtimeExecutionId=crypto.randomUUID(),this.runtimeEventBridge=new v(this.storage,this.logger,this.runtimeExecutionId),this.rs=z(),this.rs.kv.set("runtime_execution_id",this.runtimeExecutionId)}async onStart($){this.logger.log("Initialized Persistent Runtime.");let W=this.runtimeEventBridge;if(F.raw.runtime=="persistent")switch(F.raw.eventTriggerStrategy){case"POSTGRES_NOTIFY":await W.registerPgNotifyHandler($);break;case"POLLING":await W.registerPollingHandler($);break;case"WEBHOOK":this.logger.log("[Persistent Runtime] : Event Driven Queue triggers will heppen via webhook endpoint.");break}this.rs.kv.set("active_runtime_ctx",$),await this.executeQueuesTick($.runTick)}async executeTick($,W){this.deferredTickEvaluator.clearTimer($.queue);let{isValid:P,reason:Z}=this.validateTickRun($);if(!P)this.logger.warn(`[Tick] : [${$.queue}] - Rejected, invalid tick run: ${Z}. Please Reconnect Worker ASAP.`);if($.interventionPolicy=="tick"){if(await this.storage.repository.getStopSignal($.queue)){this.events.emit("tick:cycle-completed",{queue:$.queue,cycles:1});return}}await W()}validateTickRun({queue:$}){let W=F.raw.queues.find((P)=>P.queue===$);if(!W)return{isValid:!1,reason:`Queue configuration could not be found for '${$}'.`};if(W.consumer.type==="socket"){let P=this.rs.lists.get($);if(!P)return this.events.emit("tick:end",{queue:$,reason:"Socket consumer connection list does not exist"}),{isValid:!1,reason:`Socket consumer connection list does not exist for queue '${$}'.`};let Z=Array.from(P.values());if(Z.length==0)return this.events.emit("tick:end",{queue:$,reason:`Socket consumer has (${Z.length}) active connections.`}),{isValid:!1,reason:`Socket consumer for queue '${$}' has (${Z.length}) active connections.`}}return{isValid:!0,reason:"Tick run validation passed successfully."}}async scheduleTick($,W){let{queue:P,concurrency:Z,pooler:X}=$,Q=await this.queueService.getSingleQueueMetrics(P);if(!Q)return;if(Q?.total==0){if(X=="event-driven-pooler"){this.logger.log(`[Tick] : [${P}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:P,cycles:1});return}}let G=await this.storage.repository.getActiveWorkersCount(P),J=Math.max(0,Z-G);this.deferredTickEvaluator.clearTimer(P),this.scheduler.scheduleNext({metrics:{queue:P,availableSlots:J,...Q},onNext:W,onUpcomingDelayedNext:(N)=>{this.logger.log(`[Scheduler] : Next tick scheduled in ${(N/1000).toFixed(2)}s`)},onFutureSchedule:async(N)=>{let H=N-Date.now();this.logger.log(`[Scheduler] : Deffered tick execution in ${(Math.max(0,H)/1000).toFixed(2)}s`),this.deferredTickEvaluator.forceExecuteTickLater($,N)}})}async handleCycleCompletion(){return!1}async handleRestart(){this.logger.log("[Persistent Runtime] : Restart triggered. Handled by process manager (PM2/systemd).")}}class G0 extends B{type="SERVERLESS_VM";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=1;constructor($){super($);this.logger.log("Initialized Serverless VM Runtime.")}async onStart($){await this.executeQueuesTick($.runTick)}async executeTick($,W){await W()}async scheduleTick($,W){await W()}async handleCycleCompletion($){let W=!1,P=!1,Z=$.currentExecutionId,X=$.lockKey,Q=X?.startsWith("pulsar:lock:edp:"),G=X==="pulsar:lock:idp",J=Q?X?.replace("pulsar:lock:edp:",""):null;for(let{queue:N,pooler:H}of $.getActiveQueues())try{if(H=="interval-driven-pooler"&&W)continue;if(Q&&N!==J)continue;let K=await this.queueService.getSingleQueueMetrics(N);if(!K||K.total===0){console.log(`[Pulsar] Failed to fetch metrics for ${N}. Halting queue.`),$.endTick(N);continue}let V=K.total;if(!await this.storage.repository.evaluateDeadRun(N,H,V,Z,15000)){console.log(`[Pulsar] Should not invoke for ${N}. Skipping.`);continue}let w=F.get("engine.selfInvocationIntervalSec")??1,T=await this.triggerSelfInvocation({queue:N,pooler:H,delaySec:w,continuationOwnerId:Z,isIdpLock:G,isEdpLock:Q,targetEdpQueue:J});if(T.idpInvoked)W=!0;if(T.continuationScheduledForCurrentLock)P=!0}catch(K){console.log(`[deadRun] Error checking queue ${N}:`,K)}return P}async handleRestart($){}}class N0 extends B{deps;type="V8_ISOLATE";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=5;deferredTickEvaluator;constructor($){super($);this.deps=$;this.logger.log("[EngineRuntime] : Initialized V8 Isolate Runtime."),this.deferredTickEvaluator=new x(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger)}async onStart($){await this.executeQueuesTick($.runTick)}async executeTick($,W){let{queue:P}=$;this.deferredTickEvaluator.stopRuntimeWatchdog();let Z=this.deps.clock.isSafeToContinue(),X=this.deps.events;if(!Z){this.logger.log("[EngineRuntime] : Ending All Ticks due to time limit."),X.emit("tick:time-exceeded",{queue:P,elapsedMs:this.deps.clock.getElapsedTotalTime()}),X.emit("tick:cycle-completed",{queue:P,cycles:1});return}if($.interventionPolicy=="tick"||$.interventionPolicy=="inherit"&&F.get("engine.interventionPolicy")=="tick"){if(await this.storage.repository.getStopSignal($.queue)){X.emit("tick:cycle-completed",{queue:P,cycles:1});return}}await this.deps.clock.trackExecutionTime({contextId:P},W)}async scheduleTick($,W){let{queue:P,concurrency:Z,pooler:X}=$,Q=await this.queueService.getSingleQueueMetrics(P);if(!Q)return;if(Q?.total==0){if(X=="event-driven-pooler"){this.logger.log(`[Tick] : [${P}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:P,cycles:1});return}}let G=await this.storage.repository.getActiveWorkersCount(P),J=Math.max(0,Z-G),N=async()=>{this.deferredTickEvaluator.stopRuntimeWatchdog(),await W()};this.scheduler.scheduleNext({metrics:{queue:P,availableSlots:J,...Q},onNext:N,onUpcomingDelayedNext:(H)=>{return this.logger.log(`[Scheduler] : Next tick scheduled in ${(H/1000).toFixed(2)}s`),this.deferredTickEvaluator.evaluateUpcomingDelayedNext(H,P)},onFutureSchedule:async(H)=>{this.logger.log("[Scheduler] : scheduled tick execution request",H)}});return}async handleCycleCompletion($){let W=!1,P=!1,Z=$.currentExecutionId,X=$.lockKey,Q=X?.startsWith("pulsar:lock:edp:"),G=X==="pulsar:lock:idp",J=Q?X?.replace("pulsar:lock:edp:",""):null;for(let{queue:N,pooler:H}of $.getActiveQueues())try{if(H=="interval-driven-pooler"&&W)continue;if(Q&&N!==J)continue;let K=await this.queueService.getSingleQueueMetrics(N);if(!K)continue;if(K.total===0)if(this.logger.log(`[Engine] : Queue ${N} is empty (total: 0) using ${H} pooler. Halting tick.`),H=="event-driven-pooler"){$.endTick(N);continue}else $.endTick(N);let V=K.total;if(!await this.storage.repository.evaluateDeadRun(N,H,V,Z,15000)){this.logger.log(`[Engine] : Should not invoke for ${N}. Skipping.`);continue}let w=F.get("engine.selfInvocationIntervalSec")??1,T=F.get("runtime")=="v8-isolate",A=w;if(T&&F.raw.isolate){let _=F.raw.isolate.remainingTime/1000,h=this.minBootRequirementSec,s=w+h;if(_<s)return this.logger.log(`[EngineRuntime] : Isolate remaining time (${_.toFixed(3)}s) is insufficient for self-invocation (${w}s delay + ${h}s min work). Triggering restart.`),await this.handleRestart($),!0;let t=Math.max(1,_-h);A=Math.min(w,t)}let C=await this.triggerSelfInvocation({queue:N,pooler:H,delaySec:A,continuationOwnerId:Z,isIdpLock:G,isEdpLock:Q,targetEdpQueue:J});if(C.idpInvoked)W=!0;if(C.continuationScheduledForCurrentLock)P=!0}catch(K){this.logger.log(`[deadRun] : Error checking queue ${N}:`,K)}return P}async handleRestart($){let W=!1,P=$.currentExecutionId,Z=F.get("engine.selfRestartIntervalSec"),X=$.getActiveQueues();for(let{queue:Q,pooler:G}of X){if(G=="interval-driven-pooler"&&W)continue;let J={"content-type":"application/json","x-last-execution-id":P,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"true","x-pooler":G,"x-target-queue":Q};if(this.logger.log(`(${G}) : invoking engine via restartTick (${Z})`),G=="interval-driven-pooler")W=!0;let N=$.lockKey;await this.storage.repository.releaseQueueLock(N,$.isolateId),await this.storage.ops.addRestart(X),await this.queueService.triggerUrl({url:F.get("engine.selfURL"),headers:J,delaySeconds:Z}),await this.storage.ops.updateRestartOwnership(Q,"handled_by_engine")}}}import{serve as b$}from"crossws/server";var _0=F0(g0(),1);var E0=_0.default;class K0 extends E0{config;serverInstance=null;logger;store;onFetch;constructor($){super();this.config=$;this.logger=new I,this.store=z()}async start(){let $=this;this.logger.log(`[Network] : Initializing server on port ${this.config.port} in [${this.config.mode}] mode`);let W=this.config.mode==="hybrid"||this.config.mode==="websocket";if(W)this.logger.log(`[Network] : WebSocket server handlers attached on port ${this.config.port}`);this.serverInstance=b$({port:this.config.port,...W?{websocket:{open(P){$.emit("open",P)},message(P,Z){$.emit("message",P,Z)},close(P,Z){$.emit("close",P,Z)}}}:{},fetch(P){if($.onFetch)return $.onFetch(P);return $.logger.warn(`[Network] : Unhandled route accessed: ${P.method} ${P.url}`),new Response(null,{status:404})},gracefulShutdown:!1,maxRequestBodySize:void 0}),this.store.kv.set("self_url",this.serverInstance.url),await this.serverInstance.ready(),this.logger.log(`[Server] Successfully started and listening on port ${this.config.port}`)}async close(){try{await this.serverInstance?.close(!0)}catch($){this.logger.error("[Network] : Error closing server:",$)}}}var B0=F0(z0(),1);class y{config;isRunning=!1;logger;rs;constructor($){this.config=$;this.logger=new I,this.rs=z()}}class u extends y{networkConfig;networkInterface;storage;queueService;interface="HTTP";consumersMap;triggerHandler;runtimeEventBridge;store;constructor($,W,P,Z){super($);this.networkConfig=$;this.networkInterface=W;this.storage=P;this.queueService=Z;this.store=z();let X=this.rs.kv.get("runtime_execution_id");this.runtimeEventBridge=new v(this.storage,this.logger,X);let Q=F.get("queues"),G=new Map;if(Q.forEach(({consumer:J,queue:N})=>G.set(N,J)),this.consumersMap=G,this.networkInterface)this.networkInterface.onFetch=(J)=>this.handleFetch(J)}async start(){}async broadcast($,W){let P=this.consumersMap.get($);if(!P)throw Error(`No consumer registered for queue: "${$}"`);if(P.type!=="http")return;let{worker_id:Z,batch:X}=W,Q=B0.default.encode(W),G=F.get("runtime")=="persistent"?this.store.kv.get("self_url"):F.get("engine.selfURL");try{await fetch(`${P.url}/dispatch`,{method:"POST",headers:{"content-type":"application/x-msgpack",...P.headers,"x-worker-id":Z,"x-batch-size":X.length.toString(),"x-pulsar-callback-url":G,"x-queue":$,"x-execution-signature":crypto.randomUUID(),"x-instance-id":F.get("instanceId"),"x-api-key":F.get("apiKey"),"x-dispatched-at":new Date().toISOString()},body:Q})}catch(J){this.logger.error("Error dispatching jobs to http consumer,",J)}}onTrigger($){this.triggerHandler=$}async stop(){}async handleFetch($){let{url:W,method:P,body:Z,headers:X}=await v$($),Q=x$(X),G=new URL(W),J={headers:Q,body:Z};if(G.pathname.endsWith("/ack")&&P==="POST"){let K=await this.handleAck(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/nack")&&P==="POST"){let K=await this.handleNack(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/retry")&&P==="POST"){let K=await this.handleRetry(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/deregister")&&P==="POST"){let K=await this.handleDeregister(J);return new Response(K.message,{status:K.status})}let{executionOwner:N,poolerMode:H}=Q;if(N=="trigger"){if(H=="event-driven-pooler"){let K=Q.targetQueue,V=Q.fencingToken??"0",M=this.store.kv.get("active_runtime_ctx");if(!M)return this.logger.warn("active runtime context was not found"),new Response("UNKNOWN ROUTE",{status:200});else await this.runtimeEventBridge.httpEventDrivenQueueTrigger(K,V,M)}}return new Response("UNKNOWN ROUTE",{status:200})}async performBatchAction($,W,P,Z){try{switch(Z){case"ACK":await this.queueService.ackBatch($,P);break;case"NACK":await this.queueService.ackBatch($,P);break;case"RETRY":await this.queueService.retryBatch($,P);break;case"DEREGISTER":await this.storage.repository.deregisterWorker(W,$);break}}catch(X){throw this.logger.error(`Error performing batch action [${Z}] for queue [${$}]:`,X),X}}parseBody($){try{if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return B0.default.decode($);return $}catch(W){throw Error(`Failed to parse request body : ${W?.message}`)}}extractContext($){let W=$.headers,P=this.parseBody($.body),Z=W.targetQueue,X=W.workerId??"";if(!Z)throw Error("[HttpNetworkDriver] Queue not found in headers");return{headers:W,body:P,queue:Z,workerId:X}}async getMessageIds($){let{queue:W,body:P,workerId:Z}=this.extractContext($),Q=(Array.isArray(P?.msg_ids)?P.msg_ids:[]).map((G)=>Number.parseInt(String(G),10)).filter((G)=>Number.isInteger(G)&&G>=0);return{queue:W,messageIds:Q,workerId:Z}}async handleAck($){let{messageIds:W,queue:P,workerId:Z}=await this.getMessageIds($);return await this.performBatchAction(P,Z,W,"ACK"),{message:"Jobs Acknowledged",status:200}}async handleNack($){let{messageIds:W,queue:P,workerId:Z}=await this.getMessageIds($);return await this.performBatchAction(P,Z,W,"NACK"),{message:"Jobs Not Acknowledged",status:200}}async handleRetry($){let{queue:W,workerId:P,messageIds:Z}=await this.getMessageIds($);return await this.performBatchAction(W,P,Z,"RETRY"),{message:"Jobs Retry Applied",status:200}}async handleDeregister($){let{queue:W,workerId:P}=this.extractContext($);if(!P)throw Error("[HttpNetworkDriver] Worker ID not found in headers");return await this.performBatchAction(W,P,[],"DEREGISTER"),{message:"Worker Deregistered",status:200}}}var l$=F0(z0(),1);class D0 extends y{networkInterface;interface="WEBSOCKET";queuePeers=new Map;triggerHandler;boundOpen=($)=>this.onConnectionOpen($);boundMessage=($,W)=>this.onMessage($,W);boundClose=($)=>this.onConnectionClose($);constructor($,W){super($);this.networkInterface=W;this.networkInterface.on("open",this.boundOpen),this.networkInterface.on("message",this.boundMessage),this.networkInterface.on("close",this.boundClose)}async start(){}async broadcast($,W){let P=this.queuePeers.get($);if(!P||P.size===0){this.logger.warn(`[Network] : No active workers listening on queue: ${$}`);return}let Z=l$.default.encode(W);for(let X of P)try{X.send(Z)}catch(Q){this.logger.error(`[Network] : Failed to send message to peer ${X.id}:`,Q)}}onTrigger($){this.triggerHandler=$}async stop(){this.networkInterface.off("open",this.boundOpen),this.networkInterface.off("message",this.boundMessage),this.networkInterface.off("close",this.boundClose);for(let $ of this.queuePeers.values())for(let W of $)try{W.close(1001,"server shutting down")}catch{}this.queuePeers.clear()}onConnectionOpen($){this.logger.log("[Network] : Worker connected:",$.id)}onMessage($,W){let P=JSON.parse(W.toString());P.type==="REGISTER"?this.handleWorkerRegistration($,P):this.handleWorkerMessage(P)}handleWorkerRegistration($,W){let P=this.queuePeers.get(W.queue);if(!P)P=new Set,this.queuePeers.set(W.queue,P);if(P.has($)){this.logger.log(`[Network] : Worker ${$.id} is already registered to queue: ${W.queue}`);return}$.subscribe(W.queue),P.add($),this.rs.lists.add(W.queue,$.id),this.logger.log(`[Network] : Worker ${$.id} registered to queue: ${W.queue}`)}handleWorkerMessage($){if(this.triggerHandler){let W=$.queue,P=$.data!==void 0?$?.data:$;if(W)this.triggerHandler(W,P)}}onConnectionClose($){this.logger.log("[Network] : [WebSocketNetworkDriver] - Worker disconnected:",$.id);for(let[W,P]of this.queuePeers.entries())if(P.has($)){if(P.delete($),this.rs.lists.remove(W,$.id),P.size===0)this.queuePeers.delete(W)}}}class o{config;storage;queueServuce;drivers=[];topology;networkInterface;isServerMode;logger;constructor($,W,P){this.config=$;this.storage=W;this.queueServuce=P;if(this.topology=$.mode,this.isServerMode=$.isServer,this.logger=new I,this.isServerMode)this.initializeTopology();else this.initializeClientTopology()}initializeTopology(){if(this.networkInterface=new K0(this.config),this.config.mode==="websocket"||this.config.mode==="hybrid")this.drivers.push(new D0(this.config,this.networkInterface));if(this.config.mode==="http"||this.config.mode==="hybrid")this.drivers.push(new u(this.config,this.networkInterface,this.storage,this.queueServuce))}initializeClientTopology(){this.drivers.push(new u(this.config,void 0,this.storage,this.queueServuce))}async bootAll(){if(!this.isServerMode||!this.networkInterface)return;await this.networkInterface.start();for(let $ of this.drivers)await $.start()}async shutdownAll(){if(!this.isServerMode)return;for(let $ of this.drivers)await $.stop();await this.networkInterface?.close()}onTrigger($){for(let W of this.drivers)W.onTrigger($)}async dispatchToNetwork($,W){let P=F.get("queues").find((J)=>J.queue===$),Z={http:"HTTP",socket:"WEBSOCKET"},X=P.consumer.type,Q=Z[X];if(!Q)throw Error(`[DispatchToNetwork] : Unsupported consumer type "${X}" for queue: "${$}"`);for(let J of this.drivers)if(J.interface===Q)await J.broadcast($,W);if(this.drivers.filter((J)=>J.interface===Q).length===0)throw this.logger.error(`[DispatchToNetwork] : No "${Q}" driver available for queue "${$}" (mode: ${this.topology}, server: ${this.isServerMode})`),Error(`[DispatchToNetwork] : No "${Q}" driver available for queue "${$}" (mode: ${this.topology}, server: ${this.isServerMode})`)}}class C0{storage;tickService;tickController;unifiedTransportManager;swarmManager;scheduler;queueService;clock;events;queues=[];consumers=[];runtimeStrategy;logger;integrations=new Map;constructor($){if(F.initialize($),this.logger=new I,$.integrations?.length)this.runIntegrations($.integrations);for(let{consumer:G,...J}of F.raw.queues)this.queues.push(J),this.consumers.push(G);let W=F.get("instanceId");if(!W)throw Error("[Pulsar] : instanceId is required.");if(typeof W!=="string"||!/^[a-zA-Z0-9_-]+$/.test(W))throw Error('[Pulsar] : Invalid instanceId format. It must contain only alphanumeric characters, hyphens, and underscores (e.g., "string-like-this" or "or_this").');this.events=new E;let Z=1/0,X=F.raw.runtime==="v8-isolate",Q=F.get("isolate");if(X)Z=Math.max(0,Q.remainingTime-5000);if(this.storage=F.raw.storage,this.storage.connect(),this.storage.bindInstanceId(W),this.clock=new e({maxExecutionBudgetMs:Z,safetyBufferMs:0,maxTrackHistory:50,enabled:!0}),this.queueService=new q$(this.storage),this.scheduler=new W0,this.runtimeStrategy=this.resolveRuntimeStrategy(),!this.runtimeStrategy)throw this.logger.error("[Pulsar] Failed to resolve a valid runtime strategy."),Error("[Pulsar] Failed to resolve a valid runtime strategy.");if(F.raw.runtime=="persistent")this.unifiedTransportManager=new o({...F.raw.networkInterface,isServer:!0},this.storage,this.queueService);else this.unifiedTransportManager=new o({mode:"client",isServer:!1,port:0},this.storage,this.queueService);if(this.swarmManager=new $0(F.raw.swarmConfig?.globalMaxJobsPerTick??1/0,F.raw.swarmConfig?.maxGlobalConcurrency??1/0),this.tickService=new Z0({queue:this.queueService,storage:this.storage,swarmManager:this.swarmManager,unifiedTransportManager:this.unifiedTransportManager,events:this.events}),this.tickController=new X0({scheduler:this.scheduler,storage:this.storage,tickService:this.tickService,clock:this.clock,events:this.events,runtimeStrategy:this.runtimeStrategy}),Number.isFinite(Z))this.logger.log(`[EngineRuntime] : isolate registred with id : [${Q.id}]`),this.logger.log(`[Clock] : Synced execution timeout (${Z/1000}s) with isolate [${Q.id}]`);else this.logger.log(`[EngineRuntime] : Engine Started With No V8 Isolate (${new Date().toISOString()})`)}resolveRuntimeStrategy(){let $={queueService:this.queueService,clock:this.clock,queues:this.queues,storage:this.storage,isolate:this.V8Isolate,events:this.events,scheduler:this.scheduler};switch(F.get("runtime")){case"persistent":return new Q0($);case"serverless-vm":return new G0($);case"v8-isolate":return new N0($);default:throw Error("Unsupported Runtime")}}async runIntegrations($){for(let W of $){let P;if(typeof W==="function")P=new W("ALL");else P=W;await P.main(this),this.integrations.set(P.module,P)}}getIntegration($){if(typeof $==="string")return this.integrations.get($);for(let P of this.integrations.values())if(P instanceof $)return P;let W=typeof $==="string"?$:$.name;throw Error(`Integration "${W}" is not registered.`)}get runtime(){return this.runtimeStrategy.type}get isV8Isolate(){return F.get("runtime")==="v8-isolate"}get V8Isolate(){return F.raw.isolate}async exit(){await this.storage.disconnect()}}class j$ extends C0{baseConfig;isolateId;currentExecutionId;lockKey;shutdownPromise=null;eventCleanUps=[];activeQueues=new Set;constructor($){super($);this.baseConfig=$;if(this.registerEvents(),!this.isV8Isolate)this.isolateId=crypto.randomUUID();else this.isolateId=this.V8Isolate.id;if(this.isV8Isolate)this.currentExecutionId=this.V8Isolate.get("current_execution_id"),this.lockKey=this.V8Isolate.get("lock_key");else this.currentExecutionId=this.generateCurrentExecutionIdFromConfig(),this.lockKey="lock-template-static-defination-for-non-v8";this.tickController.initializeState()}async start(){await this.unifiedTransportManager.bootAll(),await F.reconcileConfiguration(this.storage.ops),this.tickController.initializeState(),this.configureQueueProfiles(),await this.runtimeStrategy.onStart(this.executionContext)}async triggerQueue($){let W=this.queues.find((P)=>P.queue===$);if(!W)throw Error("[Pulsar] Target queue is missing.");this.logger.log(`[Pulsar] : Event-driven trigger for (${$})`),await this.validateConfiguration(),await this.runTick(W)}async validateConfiguration(){return{status:200,message:await F.reconcileConfiguration(this.storage.ops)}}configureQueueProfiles(){for(let $ of this.queues){let W=$.profile||"REALTIME";this.scheduler.registerQueueProfile($.queue,W)}}async runTick($){return this.activeQueues.add($),await this.tickController.runTick($)}async shutdown(){return this.shutdownPromise??=this.doShutdown(),this.shutdownPromise}async doShutdown(){if(this.logger.log("Engine Shutdown ⚠️."),this.removeRegisteredEvents(),this.unifiedTransportManager)await this.unifiedTransportManager.shutdownAll();if(!await this.runtimeStrategy.handleCycleCompletion(this.executionContext))await this.releaseExecutionLock(this.lockKey,this.currentExecutionId);await this.storage.ops.pingHealthCheck(),await this.storage.disconnect()}async scheduleRestart($){if($){let P=this.queues.find((Z)=>Z.queue==$);if(P)this.activeQueues.add(P)}let W=Array.from(this.activeQueues.values());await this.releaseExecutionLock(this.lockKey,this.isolateId),await this.storage.ops.addRestart(W),await this.runtimeStrategy.handleRestart(this.executionContext),await this.storage.ops.updateRestartOwnership($,"handled_by_engine")}async restartForSameIsolate($){let W=30;if(this.isV8Isolate)W=this.V8Isolate.remainingTime+5;this.logger.log(`Estimated Restart in (${W})S`),await this.queueService.triggerUrl({url:F.get("engine.selfURL"),headers:$,delaySeconds:W})}get executionContext(){return{lockKey:this.lockKey,currentExecutionId:this.currentExecutionId,isolateId:this.isolateId,getActiveQueues:()=>Array.from(this.activeQueues.values()),runTick:($)=>this.runTick($),endTick:($)=>this.tickController.endTick($)}}setCurrentExecutionId($){this.currentExecutionId=$}generateCurrentExecutionIdFromConfig(){let $=this.baseConfig.queues.map((W)=>`${W.queue}:${W.pooler}`).join(",");return JW($)}registerEvents(){let $=this.runtimeStrategy.shouldShutdownOnCycleComplete;this.eventCleanUps.push(this.events.on("tick:cycle-completed",async()=>{if($)await this.shutdown();else this.logger.log("[Pulsar Persistent] : Cycle completed. Resetting state for next execution round."),this.tickController.initializeState()})),this.eventCleanUps.push(this.events.on("tick:force-run",async({queue:W,reason:P})=>{this.logger.log(`[Tick] : Force executing tick for queue [${W.queue}] Trigger Reason : ${P}`),await this.runTick(W)})),this.eventCleanUps.push(this.events.on("tick:end",({queue:W,reason:P})=>{this.logger.log(`[Tick] : Force stoping tick for queue [${W}] (Trigger Reason : ${P})`),this.tickController.endTick(W)})),this.eventCleanUps.push(this.events.on("tick:time-exceeded",async()=>{if($)await this.shutdown()})),this.eventCleanUps.push(this.events.on("engine:health-check-requested",async()=>{this.logger.log(`Pulsar : Health checking ping at (${new Date().toISOString()})`),await this.storage.ops.pingHealthCheck()}))}removeRegisteredEvents(){this.eventCleanUps.forEach(($)=>$()),this.eventCleanUps=[]}async awaitPendingShutdown(){if(await this.events.drain(),this.shutdownPromise)await this.shutdownPromise}async deleteScheduledRestart($){await this.storage.ops.deleteRestart($)}async acquireExecutionLock($,W,P){return await this.storage.repository.acquireQueueLock($,W,P)}async releaseExecutionLock($,W){return await this.storage.repository.releaseQueueLock($,W)}}export{p$ as createQueue,l as PulsarRuntime,j$ as Pulsar,h0 as IsolateInstance,m0 as EventTriggerStrategy};
|
|
5
|
+
import{a as q$,b as v$,c as x$}from"./chunk-a9kye38b.js";import{d as B,e as F}from"./chunk-rrj8rm04.js";import{f as L0,g as l,h as I}from"./chunk-cpn1qh4e.js";import{i as F0,j as U}from"./chunk-3sg08kqp.js";var g0=U((sW,J0)=>{var f$=Object.prototype.hasOwnProperty,k="~";function q(){}if(Object.create){if(q.prototype=Object.create(null),!new q().__proto__)k=!1}function d$($,W,Z){this.fn=$,this.context=W,this.once=Z||!1}function m0($,W,Z,P,X){if(typeof Z!=="function")throw TypeError("The listener must be a function");var Q=new d$(Z,P||$,X),G=k?k+W:W;if(!$._events[G])$._events[G]=Q,$._eventsCount++;else if(!$._events[G].fn)$._events[G].push(Q);else $._events[G]=[$._events[G],Q];return $}function f($,W){if(--$._eventsCount===0)$._events=new q;else delete $._events[W]}function R(){this._events=new q,this._eventsCount=0}R.prototype.eventNames=function(){var W=[],Z,P;if(this._eventsCount===0)return W;for(P in Z=this._events)if(f$.call(Z,P))W.push(k?P.slice(1):P);if(Object.getOwnPropertySymbols)return W.concat(Object.getOwnPropertySymbols(Z));return W};R.prototype.listeners=function(W){var Z=k?k+W:W,P=this._events[Z];if(!P)return[];if(P.fn)return[P.fn];for(var X=0,Q=P.length,G=Array(Q);X<Q;X++)G[X]=P[X].fn;return G};R.prototype.listenerCount=function(W){var Z=k?k+W:W,P=this._events[Z];if(!P)return 0;if(P.fn)return 1;return P.length};R.prototype.emit=function(W,Z,P,X,Q,G){var J=k?k+W:W;if(!this._events[J])return!1;var N=this._events[J],H=arguments.length,K,V;if(N.fn){if(N.once)this.removeListener(W,N.fn,void 0,!0);switch(H){case 1:return N.fn.call(N.context),!0;case 2:return N.fn.call(N.context,Z),!0;case 3:return N.fn.call(N.context,Z,P),!0;case 4:return N.fn.call(N.context,Z,P,X),!0;case 5:return N.fn.call(N.context,Z,P,X,Q),!0;case 6:return N.fn.call(N.context,Z,P,X,Q,G),!0}for(V=1,K=Array(H-1);V<H;V++)K[V-1]=arguments[V];N.fn.apply(N.context,K)}else{var M=N.length,w;for(V=0;V<M;V++){if(N[V].once)this.removeListener(W,N[V].fn,void 0,!0);switch(H){case 1:N[V].fn.call(N[V].context);break;case 2:N[V].fn.call(N[V].context,Z);break;case 3:N[V].fn.call(N[V].context,Z,P);break;case 4:N[V].fn.call(N[V].context,Z,P,X);break;default:if(!K)for(w=1,K=Array(H-1);w<H;w++)K[w-1]=arguments[w];N[V].fn.apply(N[V].context,K)}}}return!0};R.prototype.on=function(W,Z,P){return m0(this,W,Z,P,!1)};R.prototype.once=function(W,Z,P){return m0(this,W,Z,P,!0)};R.prototype.removeListener=function(W,Z,P,X){var Q=k?k+W:W;if(!this._events[Q])return this;if(!Z)return f(this,Q),this;var G=this._events[Q];if(G.fn){if(G.fn===Z&&(!X||G.once)&&(!P||G.context===P))f(this,Q)}else{for(var J=0,N=[],H=G.length;J<H;J++)if(G[J].fn!==Z||X&&!G[J].once||P&&G[J].context!==P)N.push(G[J]);if(N.length)this._events[Q]=N.length===1?N[0]:N;else f(this,Q)}return this};R.prototype.removeAllListeners=function(W){var Z;if(W){if(Z=k?k+W:W,this._events[Z])f(this,Z)}else this._events=new q,this._eventsCount=0;return this};R.prototype.off=R.prototype.removeListener;R.prototype.addListener=R.prototype.on;R.prefixed=k;R.EventEmitter=R;if(typeof J0<"u")J0.exports=R});var d=U((j0)=>{Object.defineProperty(j0,"__esModule",{value:!0});j0.utf8Count=i$;j0.utf8EncodeJs=v0;j0.utf8EncodeTE=x0;j0.utf8Encode=c$;j0.utf8DecodeJs=l0;j0.utf8DecodeTD=q0;j0.utf8Decode=s$;function i$($){let W=$.length,Z=0,P=0;while(P<W){let X=$.charCodeAt(P++);if((X&4294967168)===0){Z++;continue}else if((X&4294965248)===0)Z+=2;else{if(X>=55296&&X<=56319){if(P<W){let Q=$.charCodeAt(P);if((Q&64512)===56320)++P,X=((X&1023)<<10)+(Q&1023)+65536}}if((X&4294901760)===0)Z+=3;else Z+=4}}return Z}function v0($,W,Z){let P=$.length,X=Z,Q=0;while(Q<P){let G=$.charCodeAt(Q++);if((G&4294967168)===0){W[X++]=G;continue}else if((G&4294965248)===0)W[X++]=G>>6&31|192;else{if(G>=55296&&G<=56319){if(Q<P){let J=$.charCodeAt(Q);if((J&64512)===56320)++Q,G=((G&1023)<<10)+(J&1023)+65536}}if((G&4294901760)===0)W[X++]=G>>12&15|224,W[X++]=G>>6&63|128;else W[X++]=G>>18&7|240,W[X++]=G>>12&63|128,W[X++]=G>>6&63|128}W[X++]=G&63|128}}var r$=new TextEncoder,n$=50;function x0($,W,Z){r$.encodeInto($,W.subarray(Z))}function c$($,W,Z){if($.length>n$)x0($,W,Z);else v0($,W,Z)}var a$=4096;function l0($,W,Z){let P=W,X=P+Z,Q=[],G="";while(P<X){let J=$[P++];if((J&128)===0)Q.push(J);else if((J&224)===192){let N=$[P++]&63;Q.push((J&31)<<6|N)}else if((J&240)===224){let N=$[P++]&63,H=$[P++]&63;Q.push((J&31)<<12|N<<6|H)}else if((J&248)===240){let N=$[P++]&63,H=$[P++]&63,K=$[P++]&63,V=(J&7)<<18|N<<12|H<<6|K;if(V>65535)V-=65536,Q.push(V>>>10&1023|55296),V=56320|V&1023;Q.push(V)}else Q.push(J);if(Q.length>=a$)G+=String.fromCharCode(...Q),Q.length=0}if(Q.length>0)G+=String.fromCharCode(...Q);return G}var u$=new TextDecoder,o$=200;function q0($,W,Z){let P=$.subarray(W,W+Z);return u$.decode(P)}function s$($,W,Z){if(Z>o$)return q0($,W,Z);else return l0($,W,Z)}});var V0=U((y0)=>{Object.defineProperty(y0,"__esModule",{value:!0});y0.ExtData=void 0;class p0{type;data;constructor($,W){this.type=$,this.data=W}}y0.ExtData=p0});var i=U((d0)=>{Object.defineProperty(d0,"__esModule",{value:!0});d0.DecodeError=void 0;class b extends Error{constructor($){super($);let W=Object.create(b.prototype);Object.setPrototypeOf(this,W),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:b.name})}}d0.DecodeError=b});var r=U((i0)=>{Object.defineProperty(i0,"__esModule",{value:!0});i0.UINT32_MAX=void 0;i0.setUint64=Q1;i0.setInt64=G1;i0.getInt64=N1;i0.getUint64=J1;i0.UINT32_MAX=4294967295;function Q1($,W,Z){let P=Z/4294967296,X=Z;$.setUint32(W,P),$.setUint32(W+4,X)}function G1($,W,Z){let P=Math.floor(Z/4294967296),X=Z;$.setUint32(W,P),$.setUint32(W+4,X)}function N1($,W){let Z=$.getInt32(W),P=$.getUint32(W+4);return Z*4294967296+P}function J1($,W){let Z=$.getUint32(W),P=$.getUint32(W+4);return Z*4294967296+P}});var H0=U((t0)=>{Object.defineProperty(t0,"__esModule",{value:!0});t0.timestampExtension=t0.EXT_TIMESTAMP=void 0;t0.encodeTimeSpecToTimestamp=c0;t0.encodeDateToTimeSpec=a0;t0.encodeTimestampExtension=u0;t0.decodeTimestampToTimeSpec=o0;t0.decodeTimestampExtension=s0;var Y1=i(),n0=r();t0.EXT_TIMESTAMP=-1;var M1=4294967295,U1=17179869183;function c0({sec:$,nsec:W}){if($>=0&&W>=0&&$<=U1)if(W===0&&$<=M1){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,$),Z}else{let Z=$/4294967296,P=$&4294967295,X=new Uint8Array(8),Q=new DataView(X.buffer);return Q.setUint32(0,W<<2|Z&3),Q.setUint32(4,P),X}else{let Z=new Uint8Array(12),P=new DataView(Z.buffer);return P.setUint32(0,W),(0,n0.setInt64)(P,4,$),Z}}function a0($){let W=$.getTime(),Z=Math.floor(W/1000),P=(W-Z*1000)*1e6,X=Math.floor(P/1e9);return{sec:Z+X,nsec:P-X*1e9}}function u0($){if($ instanceof Date){let W=a0($);return c0(W)}else return null}function o0($){let W=new DataView($.buffer,$.byteOffset,$.byteLength);switch($.byteLength){case 4:{let Z=W.getUint32(0),P=0;return{sec:Z,nsec:0}}case 8:{let Z=W.getUint32(0),P=W.getUint32(4),X=(Z&3)*4294967296+P,Q=Z>>>2;return{sec:X,nsec:Q}}case 12:{let Z=(0,n0.getInt64)(W,4),P=W.getUint32(0);return{sec:Z,nsec:P}}default:throw new Y1.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${$.length}`)}}function s0($){let W=o0($);return new Date(W.sec*1000+W.nsec/1e6)}t0.timestampExtension={type:t0.EXT_TIMESTAMP,encode:u0,decode:s0}});var c=U((W$)=>{Object.defineProperty(W$,"__esModule",{value:!0});W$.ExtensionCodec=void 0;var n=V0(),O1=H0();class Y0{static defaultCodec=new Y0;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(O1.timestampExtension)}register({type:$,encode:W,decode:Z}){if($>=0)this.encoders[$]=W,this.decoders[$]=Z;else{let P=-1-$;this.builtInEncoders[P]=W,this.builtInDecoders[P]=Z}}tryToEncode($,W){for(let Z=0;Z<this.builtInEncoders.length;Z++){let P=this.builtInEncoders[Z];if(P!=null){let X=P($,W);if(X!=null){let Q=-1-Z;return new n.ExtData(Q,X)}}}for(let Z=0;Z<this.encoders.length;Z++){let P=this.encoders[Z];if(P!=null){let X=P($,W);if(X!=null){let Q=Z;return new n.ExtData(Q,X)}}}if($ instanceof n.ExtData)return $;return null}decode($,W,Z){let P=W<0?this.builtInDecoders[-1-W]:this.decoders[W];if(P)return P($,W,Z);else return new n.ExtData(W,$)}}W$.ExtensionCodec=Y0});var M0=U((P$)=>{Object.defineProperty(P$,"__esModule",{value:!0});P$.ensureUint8Array=S1;function A1($){return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer}function S1($){if($ instanceof Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else if(A1($))return new Uint8Array($);else return Uint8Array.from($)}});var w0=U((G$)=>{Object.defineProperty(G$,"__esModule",{value:!0});G$.Encoder=G$.DEFAULT_INITIAL_BUFFER_SIZE=G$.DEFAULT_MAX_DEPTH=void 0;var X$=d(),z1=c(),Q$=r(),D1=M0();G$.DEFAULT_MAX_DEPTH=100;G$.DEFAULT_INITIAL_BUFFER_SIZE=2048;class U0{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??z1.ExtensionCodec.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.maxDepth=$?.maxDepth??G$.DEFAULT_MAX_DEPTH,this.initialBufferSize=$?.initialBufferSize??G$.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=$?.sortKeys??!1,this.forceFloat32=$?.forceFloat32??!1,this.ignoreUndefined=$?.ignoreUndefined??!1,this.forceIntegerToFloat=$?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new U0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef($){if(this.entered)return this.clone().encodeSharedRef($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode($){if(this.entered)return this.clone().encode($);try{return this.entered=!0,this.reinitializeState(),this.doEncode($,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode($,W){if(W>this.maxDepth)throw Error(`Too deep objects in depth ${W}`);if($==null)this.encodeNil();else if(typeof $==="boolean")this.encodeBoolean($);else if(typeof $==="number")if(!this.forceIntegerToFloat)this.encodeNumber($);else this.encodeNumberAsFloat($);else if(typeof $==="string")this.encodeString($);else if(this.useBigInt64&&typeof $==="bigint")this.encodeBigInt64($);else this.encodeObject($,W)}ensureBufferSizeToWrite($){let W=this.pos+$;if(this.view.byteLength<W)this.resizeBuffer(W*2)}resizeBuffer($){let W=new ArrayBuffer($),Z=new Uint8Array(W),P=new DataView(W);Z.set(this.bytes),this.view=P,this.bytes=Z}encodeNil(){this.writeU8(192)}encodeBoolean($){if($===!1)this.writeU8(194);else this.writeU8(195)}encodeNumber($){if(!this.forceIntegerToFloat&&Number.isSafeInteger($))if($>=0)if($<128)this.writeU8($);else if($<256)this.writeU8(204),this.writeU8($);else if($<65536)this.writeU8(205),this.writeU16($);else if($<4294967296)this.writeU8(206),this.writeU32($);else if(!this.useBigInt64)this.writeU8(207),this.writeU64($);else this.encodeNumberAsFloat($);else if($>=-32)this.writeU8(224|$+32);else if($>=-128)this.writeU8(208),this.writeI8($);else if($>=-32768)this.writeU8(209),this.writeI16($);else if($>=-2147483648)this.writeU8(210),this.writeI32($);else if(!this.useBigInt64)this.writeU8(211),this.writeI64($);else this.encodeNumberAsFloat($);else this.encodeNumberAsFloat($)}encodeNumberAsFloat($){if(this.forceFloat32)this.writeU8(202),this.writeF32($);else this.writeU8(203),this.writeF64($)}encodeBigInt64($){if($>=BigInt(0))this.writeU8(207),this.writeBigUint64($);else this.writeU8(211),this.writeBigInt64($)}writeStringHeader($){if($<32)this.writeU8(160+$);else if($<256)this.writeU8(217),this.writeU8($);else if($<65536)this.writeU8(218),this.writeU16($);else if($<4294967296)this.writeU8(219),this.writeU32($);else throw Error(`Too long string: ${$} bytes in UTF-8`)}encodeString($){let Z=(0,X$.utf8Count)($);this.ensureBufferSizeToWrite(5+Z),this.writeStringHeader(Z),(0,X$.utf8Encode)($,this.bytes,this.pos),this.pos+=Z}encodeObject($,W){let Z=this.extensionCodec.tryToEncode($,this.context);if(Z!=null)this.encodeExtension(Z);else if(Array.isArray($))this.encodeArray($,W);else if(ArrayBuffer.isView($))this.encodeBinary($);else if(typeof $==="object")this.encodeMap($,W);else throw Error(`Unrecognized object: ${Object.prototype.toString.apply($)}`)}encodeBinary($){let W=$.byteLength;if(W<256)this.writeU8(196),this.writeU8(W);else if(W<65536)this.writeU8(197),this.writeU16(W);else if(W<4294967296)this.writeU8(198),this.writeU32(W);else throw Error(`Too large binary: ${W}`);let Z=(0,D1.ensureUint8Array)($);this.writeU8a(Z)}encodeArray($,W){let Z=$.length;if(Z<16)this.writeU8(144+Z);else if(Z<65536)this.writeU8(220),this.writeU16(Z);else if(Z<4294967296)this.writeU8(221),this.writeU32(Z);else throw Error(`Too large array: ${Z}`);for(let P of $)this.doEncode(P,W+1)}countWithoutUndefined($,W){let Z=0;for(let P of W)if($[P]!==void 0)Z++;return Z}encodeMap($,W){let Z=Object.keys($);if(this.sortKeys)Z.sort();let P=this.ignoreUndefined?this.countWithoutUndefined($,Z):Z.length;if(P<16)this.writeU8(128+P);else if(P<65536)this.writeU8(222),this.writeU16(P);else if(P<4294967296)this.writeU8(223),this.writeU32(P);else throw Error(`Too large map object: ${P}`);for(let X of Z){let Q=$[X];if(!(this.ignoreUndefined&&Q===void 0))this.encodeString(X),this.doEncode(Q,W+1)}}encodeExtension($){if(typeof $.data==="function"){let Z=$.data(this.pos+6),P=Z.length;if(P>=4294967296)throw Error(`Too large extension object: ${P}`);this.writeU8(201),this.writeU32(P),this.writeI8($.type),this.writeU8a(Z);return}let W=$.data.length;if(W===1)this.writeU8(212);else if(W===2)this.writeU8(213);else if(W===4)this.writeU8(214);else if(W===8)this.writeU8(215);else if(W===16)this.writeU8(216);else if(W<256)this.writeU8(199),this.writeU8(W);else if(W<65536)this.writeU8(200),this.writeU16(W);else if(W<4294967296)this.writeU8(201),this.writeU32(W);else throw Error(`Too large extension object: ${W}`);this.writeI8($.type),this.writeU8a($.data)}writeU8($){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,$),this.pos++}writeU8a($){let W=$.length;this.ensureBufferSizeToWrite(W),this.bytes.set($,this.pos),this.pos+=W}writeI8($){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,$),this.pos++}writeU16($){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,$),this.pos+=2}writeI16($){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,$),this.pos+=2}writeU32($){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,$),this.pos+=4}writeI32($){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,$),this.pos+=4}writeF32($){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,$),this.pos+=4}writeF64($){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,$),this.pos+=8}writeU64($){this.ensureBufferSizeToWrite(8),(0,Q$.setUint64)(this.view,this.pos,$),this.pos+=8}writeI64($){this.ensureBufferSizeToWrite(8),(0,Q$.setInt64)(this.view,this.pos,$),this.pos+=8}writeBigUint64($){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,$),this.pos+=8}writeBigInt64($){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,$),this.pos+=8}}G$.Encoder=U0});var V$=U((K$)=>{Object.defineProperty(K$,"__esModule",{value:!0});K$.encode=h1;var C1=w0();function h1($,W){return new C1.Encoder(W).encodeSharedRef($)}});var Y$=U((H$)=>{Object.defineProperty(H$,"__esModule",{value:!0});H$.prettyByte=m1;function m1($){return`${$<0?"-":""}0x${Math.abs($).toString(16).padStart(2,"0")}`}});var R$=U((U$)=>{Object.defineProperty(U$,"__esModule",{value:!0});U$.CachedKeyDecoder=void 0;var _1=d(),E1=16,v1=16;class M${hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor($=E1,W=v1){this.maxKeyLength=$,this.maxLengthPerKey=W,this.caches=[];for(let Z=0;Z<this.maxKeyLength;Z++)this.caches.push([])}canBeCached($){return $>0&&$<=this.maxKeyLength}find($,W,Z){let P=this.caches[Z-1];$:for(let X of P){let Q=X.bytes;for(let G=0;G<Z;G++)if(Q[G]!==$[W+G])continue $;return X.str}return null}store($,W){let Z=this.caches[$.length-1],P={bytes:$,str:W};if(Z.length>=this.maxLengthPerKey)Z[Math.random()*Z.length|0]=P;else Z.push(P)}decode($,W,Z){let P=this.find($,W,Z);if(P!=null)return this.hit++,P;this.miss++;let X=(0,_1.utf8DecodeJs)($,W,Z),Q=Uint8Array.prototype.slice.call($,W,W+Z);return this.store(Q,X),X}}U$.CachedKeyDecoder=M$});var a=U((A$)=>{Object.defineProperty(A$,"__esModule",{value:!0});A$.Decoder=void 0;var R0=Y$(),x1=c(),D=r(),l1=d(),k$=M0(),q1=R$(),O=i(),k0="array",p="map_key",T$="map_value",j1=($)=>{if(typeof $==="string"||typeof $==="number")return $;throw new O.DecodeError("The type of key must be string or number but "+typeof $)};class O${stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState($){let W=this.getUninitializedStateFromPool();W.type=k0,W.position=0,W.size=$,W.array=Array($)}pushMapState($){let W=this.getUninitializedStateFromPool();W.type=p,W.readCount=0,W.size=$,W.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let $={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push($)}return this.stack[this.stackHeadPosition]}release($){if(this.stack[this.stackHeadPosition]!==$)throw Error("Invalid stack state. Released state is not on top of the stack.");if($.type===k0){let Z=$;Z.size=0,Z.array=void 0,Z.position=0,Z.type=void 0}if($.type===p||$.type===T$){let Z=$;Z.size=0,Z.map=void 0,Z.readCount=0,Z.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}var j=-1,I0=new DataView(new ArrayBuffer(0)),p1=new Uint8Array(I0.buffer);try{I0.getInt8(0)}catch($){if(!($ instanceof RangeError))throw Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var I$=RangeError("Insufficient data"),y1=new q1.CachedKeyDecoder;class T0{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=I0;bytes=p1;headByte=j;stack=new O$;entered=!1;constructor($){this.extensionCodec=$?.extensionCodec??x1.ExtensionCodec.defaultCodec,this.context=$?.context,this.useBigInt64=$?.useBigInt64??!1,this.rawStrings=$?.rawStrings??!1,this.maxStrLength=$?.maxStrLength??D.UINT32_MAX,this.maxBinLength=$?.maxBinLength??D.UINT32_MAX,this.maxArrayLength=$?.maxArrayLength??D.UINT32_MAX,this.maxMapLength=$?.maxMapLength??D.UINT32_MAX,this.maxExtLength=$?.maxExtLength??D.UINT32_MAX,this.keyDecoder=$?.keyDecoder!==void 0?$.keyDecoder:y1,this.mapKeyConverter=$?.mapKeyConverter??j1}clone(){return new T0({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=j,this.stack.reset()}setBuffer($){let W=(0,k$.ensureUint8Array)($);this.bytes=W,this.view=new DataView(W.buffer,W.byteOffset,W.byteLength),this.pos=0}appendBuffer($){if(this.headByte===j&&!this.hasRemaining(1))this.setBuffer($);else{let W=this.bytes.subarray(this.pos),Z=(0,k$.ensureUint8Array)($),P=new Uint8Array(W.length+Z.length);P.set(W),P.set(Z,W.length),this.setBuffer(P)}}hasRemaining($){return this.view.byteLength-this.pos>=$}createExtraByteError($){let{view:W,pos:Z}=this;return RangeError(`Extra ${W.byteLength-Z} of ${W.byteLength} byte(s) found at buffer[${$}]`)}decode($){if(this.entered)return this.clone().decode($);try{this.entered=!0,this.reinitializeState(),this.setBuffer($);let W=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return W}finally{this.entered=!1}}*decodeMulti($){if(this.entered){yield*this.clone().decodeMulti($);return}try{this.entered=!0,this.reinitializeState(),this.setBuffer($);while(this.hasRemaining(1))yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync($){if(this.entered)return this.clone().decodeAsync($);try{this.entered=!0;let W=!1,Z;for await(let G of $){if(W)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(G);try{Z=this.doDecodeSync(),W=!0}catch(J){if(!(J instanceof RangeError))throw J}this.totalPos+=this.pos}if(W){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return Z}let{headByte:P,pos:X,totalPos:Q}=this;throw RangeError(`Insufficient data in parsing ${(0,R0.prettyByte)(P)} at ${Q} (${X} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream($){return this.decodeMultiAsync($,!0)}decodeStream($){return this.decodeMultiAsync($,!1)}async*decodeMultiAsync($,W){if(this.entered){yield*this.clone().decodeMultiAsync($,W);return}try{this.entered=!0;let Z=W,P=-1;for await(let X of $){if(W&&P===0)throw this.createExtraByteError(this.totalPos);if(this.appendBuffer(X),Z)P=this.readArraySize(),Z=!1,this.complete();try{while(!0)if(yield this.doDecodeSync(),--P===0)break}catch(Q){if(!(Q instanceof RangeError))throw Q}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){$:while(!0){let $=this.readHeadByte(),W;if($>=224)W=$-256;else if($<192)if($<128)W=$;else if($<144){let P=$-128;if(P!==0){this.pushMapState(P),this.complete();continue $}else W={}}else if($<160){let P=$-144;if(P!==0){this.pushArrayState(P),this.complete();continue $}else W=[]}else{let P=$-160;W=this.decodeString(P,0)}else if($===192)W=null;else if($===194)W=!1;else if($===195)W=!0;else if($===202)W=this.readF32();else if($===203)W=this.readF64();else if($===204)W=this.readU8();else if($===205)W=this.readU16();else if($===206)W=this.readU32();else if($===207)if(this.useBigInt64)W=this.readU64AsBigInt();else W=this.readU64();else if($===208)W=this.readI8();else if($===209)W=this.readI16();else if($===210)W=this.readI32();else if($===211)if(this.useBigInt64)W=this.readI64AsBigInt();else W=this.readI64();else if($===217){let P=this.lookU8();W=this.decodeString(P,1)}else if($===218){let P=this.lookU16();W=this.decodeString(P,2)}else if($===219){let P=this.lookU32();W=this.decodeString(P,4)}else if($===220){let P=this.readU16();if(P!==0){this.pushArrayState(P),this.complete();continue $}else W=[]}else if($===221){let P=this.readU32();if(P!==0){this.pushArrayState(P),this.complete();continue $}else W=[]}else if($===222){let P=this.readU16();if(P!==0){this.pushMapState(P),this.complete();continue $}else W={}}else if($===223){let P=this.readU32();if(P!==0){this.pushMapState(P),this.complete();continue $}else W={}}else if($===196){let P=this.lookU8();W=this.decodeBinary(P,1)}else if($===197){let P=this.lookU16();W=this.decodeBinary(P,2)}else if($===198){let P=this.lookU32();W=this.decodeBinary(P,4)}else if($===212)W=this.decodeExtension(1,0);else if($===213)W=this.decodeExtension(2,0);else if($===214)W=this.decodeExtension(4,0);else if($===215)W=this.decodeExtension(8,0);else if($===216)W=this.decodeExtension(16,0);else if($===199){let P=this.lookU8();W=this.decodeExtension(P,1)}else if($===200){let P=this.lookU16();W=this.decodeExtension(P,2)}else if($===201){let P=this.lookU32();W=this.decodeExtension(P,4)}else throw new O.DecodeError(`Unrecognized type byte: ${(0,R0.prettyByte)($)}`);this.complete();let Z=this.stack;while(Z.length>0){let P=Z.top();if(P.type===k0)if(P.array[P.position]=W,P.position++,P.position===P.size)W=P.array,Z.release(P);else continue $;else if(P.type===p){if(W==="__proto__")throw new O.DecodeError("The key __proto__ is not allowed");P.key=this.mapKeyConverter(W),P.type=T$;continue $}else if(P.map[P.key]=W,P.readCount++,P.readCount===P.size)W=P.map,Z.release(P);else{P.key=null,P.type=p;continue $}}return W}}readHeadByte(){if(this.headByte===j)this.headByte=this.readU8();return this.headByte}complete(){this.headByte=j}readArraySize(){let $=this.readHeadByte();switch($){case 220:return this.readU16();case 221:return this.readU32();default:if($<160)return $-144;else throw new O.DecodeError(`Unrecognized array type byte: ${(0,R0.prettyByte)($)}`)}}pushMapState($){if($>this.maxMapLength)throw new O.DecodeError(`Max length exceeded: map length (${$}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState($)}pushArrayState($){if($>this.maxArrayLength)throw new O.DecodeError(`Max length exceeded: array length (${$}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState($)}decodeString($,W){if(!this.rawStrings||this.stateIsMapKey())return this.decodeUtf8String($,W);return this.decodeBinary($,W)}decodeUtf8String($,W){if($>this.maxStrLength)throw new O.DecodeError(`Max length exceeded: UTF-8 byte length (${$}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+W+$)throw I$;let Z=this.pos+W,P;if(this.stateIsMapKey()&&this.keyDecoder?.canBeCached($))P=this.keyDecoder.decode(this.bytes,Z,$);else P=(0,l1.utf8Decode)(this.bytes,Z,$);return this.pos+=W+$,P}stateIsMapKey(){if(this.stack.length>0)return this.stack.top().type===p;return!1}decodeBinary($,W){if($>this.maxBinLength)throw new O.DecodeError(`Max length exceeded: bin length (${$}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining($+W))throw I$;let Z=this.pos+W,P=this.bytes.subarray(Z,Z+$);return this.pos+=W+$,P}decodeExtension($,W){if($>this.maxExtLength)throw new O.DecodeError(`Max length exceeded: ext length (${$}) > maxExtLength (${this.maxExtLength})`);let Z=this.view.getInt8(this.pos+W),P=this.decodeBinary($,W+1);return this.extensionCodec.decode(P,Z,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let $=this.view.getUint8(this.pos);return this.pos++,$}readI8(){let $=this.view.getInt8(this.pos);return this.pos++,$}readU16(){let $=this.view.getUint16(this.pos);return this.pos+=2,$}readI16(){let $=this.view.getInt16(this.pos);return this.pos+=2,$}readU32(){let $=this.view.getUint32(this.pos);return this.pos+=4,$}readI32(){let $=this.view.getInt32(this.pos);return this.pos+=4,$}readU64(){let $=(0,D.getUint64)(this.view,this.pos);return this.pos+=8,$}readI64(){let $=(0,D.getInt64)(this.view,this.pos);return this.pos+=8,$}readU64AsBigInt(){let $=this.view.getBigUint64(this.pos);return this.pos+=8,$}readI64AsBigInt(){let $=this.view.getBigInt64(this.pos);return this.pos+=8,$}readF32(){let $=this.view.getFloat32(this.pos);return this.pos+=4,$}readF64(){let $=this.view.getFloat64(this.pos);return this.pos+=8,$}}A$.Decoder=T0});var D$=U((z$)=>{Object.defineProperty(z$,"__esModule",{value:!0});z$.decode=f1;z$.decodeMulti=d1;var B$=a();function f1($,W){return new B$.Decoder(W).decode($)}function d1($,W){return new B$.Decoder(W).decodeMulti($)}});var m$=U((L$)=>{Object.defineProperty(L$,"__esModule",{value:!0});L$.isAsyncIterable=C$;L$.asyncIterableFromStream=h$;L$.ensureAsyncIterable=r1;function C$($){return $[Symbol.asyncIterator]!=null}async function*h$($){let W=$.getReader();try{while(!0){let{done:Z,value:P}=await W.read();if(Z)return;yield P}}finally{W.releaseLock()}}function r1($){if(C$($))return $;else return h$($)}});var _$=U((g$)=>{Object.defineProperty(g$,"__esModule",{value:!0});g$.decodeAsync=u1;g$.decodeArrayStream=o1;g$.decodeMultiStream=s1;var O0=a(),A0=m$();async function u1($,W){let Z=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeAsync(Z)}function o1($,W){let Z=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeArrayStream(Z)}function s1($,W){let Z=(0,A0.ensureAsyncIterable)($);return new O0.Decoder(W).decodeStream(Z)}});var B0=U((Y)=>{Object.defineProperty(Y,"__esModule",{value:!0});Y.decodeTimestampExtension=Y.encodeTimestampExtension=Y.decodeTimestampToTimeSpec=Y.encodeTimeSpecToTimestamp=Y.encodeDateToTimeSpec=Y.EXT_TIMESTAMP=Y.ExtData=Y.ExtensionCodec=Y.Encoder=Y.DecodeError=Y.Decoder=Y.decodeMultiStream=Y.decodeArrayStream=Y.decodeAsync=Y.decodeMulti=Y.decode=Y.encode=void 0;var WW=V$();Object.defineProperty(Y,"encode",{enumerable:!0,get:function(){return WW.encode}});var E$=D$();Object.defineProperty(Y,"decode",{enumerable:!0,get:function(){return E$.decode}});Object.defineProperty(Y,"decodeMulti",{enumerable:!0,get:function(){return E$.decodeMulti}});var S0=_$();Object.defineProperty(Y,"decodeAsync",{enumerable:!0,get:function(){return S0.decodeAsync}});Object.defineProperty(Y,"decodeArrayStream",{enumerable:!0,get:function(){return S0.decodeArrayStream}});Object.defineProperty(Y,"decodeMultiStream",{enumerable:!0,get:function(){return S0.decodeMultiStream}});var ZW=a();Object.defineProperty(Y,"Decoder",{enumerable:!0,get:function(){return ZW.Decoder}});var PW=i();Object.defineProperty(Y,"DecodeError",{enumerable:!0,get:function(){return PW.DecodeError}});var XW=w0();Object.defineProperty(Y,"Encoder",{enumerable:!0,get:function(){return XW.Encoder}});var QW=c();Object.defineProperty(Y,"ExtensionCodec",{enumerable:!0,get:function(){return QW.ExtensionCodec}});var GW=V0();Object.defineProperty(Y,"ExtData",{enumerable:!0,get:function(){return GW.ExtData}});var m=H0();Object.defineProperty(Y,"EXT_TIMESTAMP",{enumerable:!0,get:function(){return m.EXT_TIMESTAMP}});Object.defineProperty(Y,"encodeDateToTimeSpec",{enumerable:!0,get:function(){return m.encodeDateToTimeSpec}});Object.defineProperty(Y,"encodeTimeSpecToTimestamp",{enumerable:!0,get:function(){return m.encodeTimeSpecToTimestamp}});Object.defineProperty(Y,"decodeTimestampToTimeSpec",{enumerable:!0,get:function(){return m.decodeTimestampToTimeSpec}});Object.defineProperty(Y,"encodeTimestampExtension",{enumerable:!0,get:function(){return m.encodeTimestampExtension}});Object.defineProperty(Y,"decodeTimestampExtension",{enumerable:!0,get:function(){return m.decodeTimestampExtension}})});function p$($){return{...$,consumer:{...$.consumer,queue:$.queue}}}class h0{MAX_ISOLATE_LIFESPAN_MS;constructor($){this.MAX_ISOLATE_LIFESPAN_MS=$;this.set("isolate_id",crypto.randomUUID()),this.set("isolate_start_time",Date.now()),this.set("isolate_max_life_span_ms",this.MAX_ISOLATE_LIFESPAN_MS)}isSameIsolate($){return $===this.get("isolate_id")}get id(){return this.get("isolate_id")??crypto.randomUUID()}get remainingTime(){let $=this.get("isolate_start_time"),W=this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS;if(typeof $!=="number")return W;let Z=Date.now()-$;return Math.max(0,W-Z)}get uptime(){let $=this.get("isolate_start_time");return typeof $==="number"?Date.now()-$:0}get maxTime(){return this.get("isolate_max_life_span_ms")??this.MAX_ISOLATE_LIFESPAN_MS}set($,W){globalThis[$]=W}get($){return globalThis[$]}}import JW from"js-sha256";class E{target=new EventTarget;pending=new Set;track($){let W=$.catch((Z)=>console.error("[EventBus] : handler failed - ",Z)).finally(()=>this.pending.delete(W));this.pending.add(W)}emit($,W){this.target.dispatchEvent(new CustomEvent($,{detail:W}))}on($,W){let Z=(P)=>{let X=W(P.detail);if(X instanceof Promise)this.track(X)};return this.target.addEventListener($,Z),()=>this.target.removeEventListener($,Z)}once($,W){let Z=(P)=>W(P.detail);this.target.addEventListener($,Z,{once:!0})}async drain(){while(this.pending.size>0)await Promise.allSettled([...this.pending])}}class e{tracks=[];startTime;maxExecutionBudgetMs;safetyBufferMs;maxTrackHistory;enabled;cpuExecutionMicroseconds=0;constructor($={}){this.startTime=performance.now(),this.maxExecutionBudgetMs=$.maxExecutionBudgetMs??25000,this.safetyBufferMs=$.safetyBufferMs??2000,this.maxTrackHistory=$.maxTrackHistory??100,this.enabled=$.enabled??!1}async trackExecutionTime({contextId:$},W){let Z=performance.now();try{return await W()}finally{if(this.enabled==!0){let X=performance.now()-Z;if(this.tracks.push({id:crypto.randomUUID(),duration:X,contextId:$}),this.tracks.length>this.maxTrackHistory)this.tracks.shift()}}}getElapsedTotalTime(){return performance.now()-this.startTime}getTimeRemaining(){let $=this.getElapsedTotalTime(),W=this.maxExecutionBudgetMs-$-this.safetyBufferMs;return Math.max(0,W)}getAverageTickDuration($=5){if(this.tracks.length===0)return 0;let W=this.tracks.slice(-$);return W.reduce((P,X)=>P+X.duration,0)/W.length}isSafeToContinue(){if(!this.enabled)return!0;let $=this.getTimeRemaining();if($<=0)return!1;let W=this.getAverageTickDuration(5);if(W>0&&$<W)return!1;return!0}clear($){this.tracks=this.tracks.filter((W)=>W.contextId!==$)}}class $0{maxGlobalJobsPerTick;maxGlobalConcurrency;constructor($,W){this.maxGlobalJobsPerTick=$;this.maxGlobalConcurrency=W}getMaxGlobalConcurrency(){return this.maxGlobalConcurrency}getMaxGlobalJobsPerTick(){return this.maxGlobalJobsPerTick}}var S={REALTIME:{activePollMs:1000,backoffPollMs:1000,idlePollMs:1000,maxTimerMs:5000},STANDARD:{activePollMs:100,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},BALANCED:{activePollMs:1e4,backoffPollMs:500,idlePollMs:1e4,maxTimerMs:60000},RELAXED:{activePollMs:1000,backoffPollMs:20000,idlePollMs:30000,maxTimerMs:60000},ULTRA_EFFICIENT:{activePollMs:5000,backoffPollMs:1e5,idlePollMs:120000,maxTimerMs:240000}};var y$=2147483647;class W0{timers=new Map;profiles=new Map;constructor(){}registerQueueProfile($,W){if(typeof W==="string"){let Z=W!=="CUSTOM"?S[W]:void 0;this.profiles.set($,Z??S.STANDARD)}else this.profiles.set($,W)}getProfile($){let Z=F.get("queues")?.find((P)=>P.queue===$)?.profile;if(Z){if(typeof Z==="string")return Z!=="CUSTOM"?S[Z]:S.STANDARD;if(typeof Z==="object")return Z}return this.profiles.get($)??S.STANDARD}cancel($){let W=this.timers.get($);if(W)clearTimeout(W);this.timers.delete($)}scheduleNext($){let{metrics:W,onNext:Z,onUpcomingDelayedNext:P,onFutureSchedule:X}=$,{queue:Q,readyJobs:G,delayedJobs:J,availableSlots:N,nextVisibleAt:H}=W;this.cancel(Q);let K=this.getProfile(Q);if(G>0&&N>0){this.setTimer(Q,Z,K.activePollMs);return}if(G>0&&N===0){this.setTimer(Q,Z,K.backoffPollMs);return}if(J>0&&H){let V=Math.max(0,H-Date.now());if(V<=K.maxTimerMs){if(P)P(V);this.setTimer(Q,Z,V);return}if(X)X(H).catch((M)=>console.error(`Scheduler error setting long delay for ${Q}:`,M));return}if(K.idlePollMs)this.setTimer(Q,Z,K.idlePollMs)}setTimer($,W,Z){let P=Math.min(Math.max(0,Z),y$),X=()=>{this.timers.delete($),W()};if(P===0){let G=setTimeout(X);this.timers.set($,G);return}let Q=setTimeout(X,P);this.timers.set($,Q)}}class Z0{logger;transitionItems=new Set;constructor($){this.logger=$}transitionToIdleMode({queue:$,stateTransitionPolicy:W}){if(this.transitionItems.has($))return;if(this.transitionItems.add($),this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to IDLE. Queue config: (${$})`),W?.enabled){let Z=W.idleTimingProfile;if(Z){let P=typeof Z==="object"?{activePollMs:Z.activePollMs,backoffPollMs:Z.backoffPollMs,idlePollMs:Z.idlePollMs}:S[Z];F.modifyQueue($,"profile",P)}}}transitionToActiveMode({queue:$,profile:W,stateTransitionPolicy:Z}){if(this.transitionItems.delete($),Z?.enabled)F.modifyQueue($,"profile",W);this.logger.log(`[ENGINE_STATE] Transitioning engine execution profile to ACTIVE. Queue config: (${$})`)}}class P0{storage;queue;executionProfileSwitcher;unifiedTransportManager;swarmManager;PROCESS_ID;globalSequence=0;consecutiveEmptyTicks=0;logger;events;constructor({queue:$,storage:W,swarmManager:Z,unifiedTransportManager:P,events:X}){this.storage=W,this.queue=$,this.swarmManager=Z,this.unifiedTransportManager=P,this.logger=new I,this.executionProfileSwitcher=new Z0(this.logger),this.PROCESS_ID=crypto.randomUUID().slice(0,12),this.globalSequence=0,this.events=X}async run($,W){let{concurrency:Z,queue:P}=$,X=this.swarmManager.getMaxGlobalConcurrency(),{batches:Q,window:G}=await this.getCandidatesBatch({queueConfig:$,maxGlobalSlotsAllowed:W}),J=$.stateTransitionPolicy?.enabled==!0;if(!Q||Q.length===0){if(J){if(this.consecutiveEmptyTicks++,this.consecutiveEmptyTicks>=($.stateTransitionPolicy?.idleThresholdTicks??10))this.executionProfileSwitcher.transitionToIdleMode($)}this.logger.warn(`[Tick] : [${P}] - Empty Tick Executred)`);return}if(J&&this.consecutiveEmptyTicks>0)this.consecutiveEmptyTicks=0,this.executionProfileSwitcher.transitionToActiveMode($);let N=await this.storage.repository.registerWorker(P,Q,Z,X),H=new Set(N),K=Q.filter((V)=>!H.has(V.workerId));if(K.length>0){let V=K.reduce((M,w)=>M+w.batch.length,0);await this.storage.repository.refundGlobalJobBudget(V,G)}if(N.length===0)return;this.logger.log(`[Tick] : [${P}] - Tick Executred. Total Jobs (${Q.reduce((V,M)=>V+M.batch.length,0)})`),await this.spwanWorkers({candidateBatches:Q,grantedWorkerIds:N,queueConfig:$})}async spwanWorkers({grantedWorkerIds:$,candidateBatches:W,queueConfig:{queue:Z}}){if(!$?.length)return;let P=new Set($),X=W.filter((Q)=>P.has(Q.workerId));await Promise.allSettled(X.map(({batch:Q,workerId:G})=>{return this.unifiedTransportManager.dispatchToNetwork(Z,{batch:Q,worker_id:G})}))}async getCandidatesBatch({queueConfig:$,maxGlobalSlotsAllowed:W}){let{concurrency:Z,maxJobsPerTick:P,queue:X,sleep:Q,n:G}=$,J=await this.storage.repository.getActiveWorkersCount(X),N=Math.max(0,Z-J);if(N===0)return{batches:[],window:""};let H=Math.min(N,W);if(H===0)return{batches:[],window:""};let K=H*G,V=P!==void 0&&P>0?P:1/0,M=Math.min(K,V);if(M<=0)return{batches:[],window:""};let w=this.swarmManager.getMaxGlobalJobsPerTick(),{granted:T,window:A}=await this.storage.repository.claimGlobalJobBudget(M,w);if(T<=0)return{batches:[],window:A};let C=await this.queue.read(X,Q??1,T),g=C.length;if(g===0)return await this.storage.repository.refundGlobalJobBudget(T,A),{batches:[],window:A};if(g<T){let L=T-C.length;await this.storage.repository.refundGlobalJobBudget(L,A)}let _=Math.ceil(g/G),h=Array(_),s=Date.now(),t=0;for(let L=0;L<g;L+=G)h[t++]={workerId:`w_${this.PROCESS_ID}_${s}_${this.globalSequence++}`,batch:C.slice(L,L+G)};return{batches:h,window:A}}}class X0{clock;tickService;scheduler;storage;events;runtimeStrategy;tickState=new Map;activeTicks=new Set;lastHealthCheckAt=0;logger;constructor({scheduler:$,storage:W,tickService:Z,clock:P,events:X,runtimeStrategy:Q}){this.logger=new I,this.clock=P,this.tickService=Z,this.scheduler=$,this.storage=W,this.events=X,this.runtimeStrategy=Q,this.initializeState()}initializeState(){this.tickState.clear(),this.activeTicks.clear()}async runTick($){await this.runtimeStrategy.executeTick($,async()=>{let{queue:W}=$;if(this.initializeTickState($),this.activeTicks.has(W)||this.tickState.get(W)?.stopped)return;this.activeTicks.add(W),this.scheduler.cancel(W);try{let Z=1/0,P=F.get("swarmConfig")?.maxGlobalConcurrency;if(P!==void 0){let X=await this.storage.repository.getGlobalActiveWorkersCount();Z=Math.max(0,P-X)}if(Z>0&&!this.tickState.get(W)?.stopped)await this.tickService.run($,Z)}catch(Z){this.logger.error(`Orchestrator error on ${W}:`,Z)}finally{this.activeTicks.delete(W),this.updateTickCounter(W)}if(this.tickState.get(W)?.stopped==!0)return;await this.runtimeStrategy.scheduleTick($,()=>this.runTick($))})}endTick($){let W=this.tickState.get($);if(W){if(W.stopped==!0)return;if(this.tickState.set($,{...W,stopped:!0}),this.scheduler.cancel($),this.clock.clear($),F.raw.queues.every((P)=>{let X=this.tickState.get(P.queue);return X?X.stopped:!0}))this.events.emit("tick:cycle-completed",{queue:$,cycles:this.tickState.get($)?.count??1})}}initializeTickState($){if(!this.tickState.get($.queue))this.tickState.set($.queue,{count:0,max:$.cycleTickLimit??10,registred:!0,stopped:!1})}updateTickCounter($){let W=this.tickState.get($)??{count:0,stopped:!1,max:10,registred:!1},Z=W.count+1,P=W.max,X=Z>=P;if((W.stopped||X)&&!W.stopped)this.tickState.set($,{count:Z,stopped:W.stopped,max:P,registred:W.registred}),this.endTick($);else this.tickState.set($,{count:Z,stopped:W.stopped,max:P,registred:W.registred});this.triggerPeriodicHealthCheck()}triggerPeriodicHealthCheck(){let $=Date.now(),W=this.runtimeStrategy.shouldShutdownOnCycleComplete,Z=(F.get("engine.healthCheckIntervalSec")??15)*1000;if($-this.lastHealthCheckAt>=Z&&!W)this.lastHealthCheckAt=$,this.events.emit("engine:health-check-requested",{timestamp:$})}}class z{queueService;clock;queues;storage;isolate;events;scheduler;logger;constructor($){this.queueService=$.queueService,this.clock=$.clock,this.queues=$.queues,this.isolate=$.isolate,this.storage=$.storage,this.events=$.events,this.scheduler=$.scheduler,this.logger=new I}async executeQueuesTick($){let W=F.get("engine.tickConcurrency");if(this.logger.log(`[Tick Controller] : Execution tick mode has been selected with concurrency ${W}`),W=="sequential"){for(let Z of this.queues)if(Z.pooler=="interval-driven-pooler")await $(Z)}else{let Z=await Promise.allSettled(this.queues.filter((P)=>P.pooler==="interval-driven-pooler").map((P)=>$(P)));for(let P of Z)if(P.status==="rejected")this.logger.error("[Tick] : Error >>",P.reason)}}async triggerSelfInvocation($){let{queue:W,pooler:Z,delaySec:P,continuationOwnerId:X,isIdpLock:Q,isEdpLock:G,targetEdpQueue:J}=$,N=F.get("engine.selfURL"),K=F.raw.engine.selfInvocationMethod,V={idpInvoked:!1,continuationScheduledForCurrentLock:!1};if(Z==="interval-driven-pooler"){if(V.idpInvoked=!0,Q)V.continuationScheduledForCurrentLock=!0;this.logger.log(`(IDP) : Invoking Self in ${P} seconds...`)}else if(Z==="event-driven-pooler"){if(G&&W===J)V.continuationScheduledForCurrentLock=!0;this.logger.log(`(EDP) : Invoking Self in ${P} seconds...`)}let M={"content-type":"application/json","x-last-execution-id":X,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"false","x-pooler":Z,"x-target-queue":W};if(K=="auto_using_pgnet")await this.queueService.triggerUrl({url:N,headers:M,delaySeconds:P});else if(typeof K==="object"&&K!==null&&K.method==="manual")await K.handler(N);return V}}class v{storage;logger;runtimeExecutionId;pgNotifyChannel="channel_pulsar_event_driven_queue";events;constructor($,W,Z){this.storage=$;this.logger=W;this.runtimeExecutionId=Z;this.events=new E}async registerPgNotifyHandler($){await this.storage.ops.subscribeToDatabaseEvents(this.pgNotifyChannel,async(W)=>{this.logger.log(`[Persistent Runtime] : Recived PgNotification Event - ${new Date().toISOString()}`);let Z=F.get("queues").find((X)=>X.queue===W.queue_name);if(!Z){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue: '${W.queue_name}' on channel: ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity(Z.queue,W.fencing_token))await $.runTick(Z)},()=>{this.logger.log(`[Persistent Runtime] : Successfully established PostgreSQL notification listener on channel : ${this.pgNotifyChannel}`)})}async registerPollingHandler($){setInterval(async()=>{let W=await this.storage.ops.getPollingQueueEntries("q_3");for(let Z of W){let P=Z.payload.queue_name,X=Z.payload.fencing_token,Q=await this.handleTriggerValidity(P,X);if(Q)await $.runTick(Q),await this.storage.ops.deletePollingQueueEntry(Z.id)}},F.get("engine.poolingIntervalMS"))}async httpEventDrivenQueueTrigger($,W,Z){let P=F.get("queues").find((Q)=>Q.queue===$);if(!P){this.logger.error(`[Persistent Runtime] : Received notification for unregistered or unmanaged queue : '${$}' on channel : ${this.pgNotifyChannel}`);return}if(await this.handleTriggerValidity($,W))await Z.runTick(P)}async handleTriggerValidity($,W){let Z=F.get("queues").find((J)=>J.queue===$);if(!Z)return this.logger.error(`[Persistent Runtime] : pool entry for unregistered or unmanaged queue: '${$}'`),null;if(!await this.storage.ops.checkFencingTokenValidity($,W)){let J=`[EventDrivenPoller]-[ExecutionTrigger]-[${$}] : Engine execution rejected : Invalid fencing token.`;return this.logger.error(J),null}let X=`lock:edp:${$}`,Q=120000;if(await this.storage.repository.acquireQueueLock(X,this.runtimeExecutionId,Q))await this.storage.repository.clearDispatchPending(X);else return this.logger.log(`[Persistent Runtime] : Engine busy for queue ${$}, skipping trigger.`),null;return Z}}class x{minBootRequirementSec;scheduler;events;clock;logger;constructor($,W,Z,P,X){this.minBootRequirementSec=$;this.scheduler=W;this.events=Z;this.clock=P;this.logger=X}timers=new Map;watchdogTimer=null;isShutdownTriggered=!1;evaluateUpcomingDelayedNext($,W){let Z=F.raw.isolate;if(!Z)throw Error("Isolate is not configured for V8_Isolate_Runtime!");let P=F.get("engine.selfInvocationIntervalSec")??1,X=this.minBootRequirementSec,Q=(P+X)*1000;if(Z.remainingTime-$<Q){this.logger.log(`[Isolate Runtime] Sleep duration of ${$}ms exceeds safe isolate budget. Canceling timer sleep and initiating shutdown.`),this.scheduler.cancel(W),this.triggerGracefulShutdown(W);return}this.startDelayedSleepWatchdog(W,Q)}startDelayedSleepWatchdog($,W){this.stopRuntimeWatchdog(),this.isShutdownTriggered=!1,this.watchdogTimer=setInterval(()=>{let Z=F.raw.isolate;if(!Z||this.isShutdownTriggered)return;if(Z.remainingTime<=W)this.logger.log(`[Isolate Watchdog] Remaining isolate budget (${Z.remainingTime}ms) expired during delayed sleep. Canceling wakeup and executing graceful shutdown.`),this.scheduler.cancel($),this.triggerGracefulShutdown($)},1000)}triggerGracefulShutdown($){if(this.isShutdownTriggered)return;this.isShutdownTriggered=!0,this.stopRuntimeWatchdog(),this.events.emit("tick:time-exceeded",{queue:$,elapsedMs:this.clock.getElapsedTotalTime()}),this.events.emit("tick:cycle-completed",{queue:$,cycles:1})}stopRuntimeWatchdog(){if(this.watchdogTimer)clearInterval(this.watchdogTimer),this.watchdogTimer=null}clearTimer($){let W=this.timers.get($);if(W)clearTimeout(W);this.timers.delete($)}forceExecuteTickLater($,W){let P=`Extended time limit reached ${W}ms elapsed, overriding standard caps !`,X=()=>this.events.emit("tick:force-run",{queue:$,reason:P}),Q=W-Date.now();if(Q>2147483647)this.timers.set($.queue,setTimeout(()=>{this.forceExecuteTickLater($,W)},2147483647));this.timers.set($.queue,setTimeout(()=>{X()},Math.max(0,Q)))}}class Q0 extends z{type="PERSISTENT";shouldShutdownOnCycleComplete=!1;minBootRequirementSec=1;runtimeExecutionId;deferredTickEvaluator;runtimeEventBridge;rs;constructor($){super($);this.deferredTickEvaluator=new x(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger),this.runtimeExecutionId=crypto.randomUUID(),this.runtimeEventBridge=new v(this.storage,this.logger,this.runtimeExecutionId),this.rs=B(),this.rs.kv.set("runtime_execution_id",this.runtimeExecutionId)}async onStart($){this.logger.log("Initialized Persistent Runtime.");let W=this.runtimeEventBridge;if(F.raw.runtime=="persistent")switch(F.raw.eventTriggerStrategy){case"POSTGRES_NOTIFY":await W.registerPgNotifyHandler($);break;case"POLLING":await W.registerPollingHandler($);break;case"WEBHOOK":this.logger.log("[Persistent Runtime] : Event Driven Queue triggers will heppen via webhook endpoint.");break}this.rs.kv.set("active_runtime_ctx",$),await this.executeQueuesTick($.runTick)}async executeTick($,W){this.deferredTickEvaluator.clearTimer($.queue);let{isValid:Z,reason:P}=this.validateTickRun($);if(!Z)this.logger.warn(`[Tick] : [${$.queue}] - Rejected, invalid tick run: ${P}. Please Reconnect Worker ASAP.`);if($.interventionPolicy=="tick"){if(await this.storage.repository.getStopSignal($.queue)){this.events.emit("tick:cycle-completed",{queue:$.queue,cycles:1});return}}await W()}validateTickRun({queue:$}){let W=F.raw.queues.find((Z)=>Z.queue===$);if(!W)return{isValid:!1,reason:`Queue configuration could not be found for '${$}'.`};if(W.consumer.type==="socket"){let Z=this.rs.lists.get($);if(!Z)return this.events.emit("tick:end",{queue:$,reason:"Socket consumer connection list does not exist"}),{isValid:!1,reason:`Socket consumer connection list does not exist for queue '${$}'.`};let P=Array.from(Z.values());if(P.length==0)return this.events.emit("tick:end",{queue:$,reason:`Socket consumer has (${P.length}) active connections.`}),{isValid:!1,reason:`Socket consumer for queue '${$}' has (${P.length}) active connections.`}}return{isValid:!0,reason:"Tick run validation passed successfully."}}async scheduleTick($,W){let{queue:Z,concurrency:P,pooler:X}=$,Q=await this.queueService.getSingleQueueMetrics(Z);if(!Q)return;if(Q?.total==0){if(X=="event-driven-pooler"){this.logger.log(`[Tick] : [${Z}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:Z,cycles:1});return}}let G=await this.storage.repository.getActiveWorkersCount(Z),J=Math.max(0,P-G);this.deferredTickEvaluator.clearTimer(Z),this.scheduler.scheduleNext({metrics:{queue:Z,availableSlots:J,...Q},onNext:W,onUpcomingDelayedNext:(N)=>{this.logger.log(`[Scheduler] : Next tick scheduled in ${(N/1000).toFixed(2)}s`)},onFutureSchedule:async(N)=>{let H=N-Date.now();this.logger.log(`[Scheduler] : Deffered tick execution in ${(Math.max(0,H)/1000).toFixed(2)}s`),this.deferredTickEvaluator.forceExecuteTickLater($,N)}})}async handleCycleCompletion(){return!1}async handleRestart(){this.logger.log("[Persistent Runtime] : Restart triggered. Handled by process manager (PM2/systemd).")}}class G0 extends z{type="SERVERLESS_VM";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=1;constructor($){super($);this.logger.log("Initialized Serverless VM Runtime.")}async onStart($){await this.executeQueuesTick($.runTick)}async executeTick($,W){await W()}async scheduleTick($,W){await W()}async handleCycleCompletion($){let W=!1,Z=!1,P=$.currentExecutionId,X=$.lockKey,Q=X?.startsWith("pulsar:lock:edp:"),G=X==="pulsar:lock:idp",J=Q?X?.replace("pulsar:lock:edp:",""):null;for(let{queue:N,pooler:H}of $.getActiveQueues())try{if(H=="interval-driven-pooler"&&W)continue;if(Q&&N!==J)continue;let K=await this.queueService.getSingleQueueMetrics(N);if(!K||K.total===0){console.log(`[Pulsar] Failed to fetch metrics for ${N}. Halting queue.`),$.endTick(N);continue}let V=K.total;if(!await this.storage.repository.evaluateDeadRun(N,H,V,P,15000)){console.log(`[Pulsar] Should not invoke for ${N}. Skipping.`);continue}let w=F.get("engine.selfInvocationIntervalSec")??1,T=await this.triggerSelfInvocation({queue:N,pooler:H,delaySec:w,continuationOwnerId:P,isIdpLock:G,isEdpLock:Q,targetEdpQueue:J});if(T.idpInvoked)W=!0;if(T.continuationScheduledForCurrentLock)Z=!0}catch(K){console.log(`[deadRun] Error checking queue ${N}:`,K)}return Z}async handleRestart($){}}class N0 extends z{deps;type="V8_ISOLATE";shouldShutdownOnCycleComplete=!0;minBootRequirementSec=5;deferredTickEvaluator;constructor($){super($);this.deps=$;this.logger.log("[EngineRuntime] : Initialized V8 Isolate Runtime."),this.deferredTickEvaluator=new x(this.minBootRequirementSec,this.scheduler,this.events,this.clock,this.logger)}async onStart($){await this.executeQueuesTick($.runTick)}async executeTick($,W){let{queue:Z}=$;this.deferredTickEvaluator.stopRuntimeWatchdog();let P=this.deps.clock.isSafeToContinue(),X=this.deps.events;if(!P){this.logger.log("[EngineRuntime] : Ending All Ticks due to time limit."),X.emit("tick:time-exceeded",{queue:Z,elapsedMs:this.deps.clock.getElapsedTotalTime()}),X.emit("tick:cycle-completed",{queue:Z,cycles:1});return}if($.interventionPolicy=="tick"||$.interventionPolicy=="inherit"&&F.get("engine.interventionPolicy")=="tick"){if(await this.storage.repository.getStopSignal($.queue)){X.emit("tick:cycle-completed",{queue:Z,cycles:1});return}}await this.deps.clock.trackExecutionTime({contextId:Z},W)}async scheduleTick($,W){let{queue:Z,concurrency:P,pooler:X}=$,Q=await this.queueService.getSingleQueueMetrics(Z);if(!Q)return;if(Q?.total==0){if(X=="event-driven-pooler"){this.logger.log(`[Tick] : [${Z}] - Tick Process Ended. Cycle Limit Reached`),this.events.emit("tick:cycle-completed",{queue:Z,cycles:1});return}}let G=await this.storage.repository.getActiveWorkersCount(Z),J=Math.max(0,P-G),N=async()=>{this.deferredTickEvaluator.stopRuntimeWatchdog(),await W()};this.scheduler.scheduleNext({metrics:{queue:Z,availableSlots:J,...Q},onNext:N,onUpcomingDelayedNext:(H)=>{return this.logger.log(`[Scheduler] : Next tick scheduled in ${(H/1000).toFixed(2)}s`),this.deferredTickEvaluator.evaluateUpcomingDelayedNext(H,Z)},onFutureSchedule:async(H)=>{this.logger.log("[Scheduler] : scheduled tick execution request",H)}});return}async handleCycleCompletion($){let W=!1,Z=!1,P=$.currentExecutionId,X=$.lockKey,Q=X?.startsWith("pulsar:lock:edp:"),G=X==="pulsar:lock:idp",J=Q?X?.replace("pulsar:lock:edp:",""):null;for(let{queue:N,pooler:H}of $.getActiveQueues())try{if(H=="interval-driven-pooler"&&W)continue;if(Q&&N!==J)continue;let K=await this.queueService.getSingleQueueMetrics(N);if(!K)continue;if(K.total===0)if(this.logger.log(`[Engine] : Queue ${N} is empty (total: 0) using ${H} pooler. Halting tick.`),H=="event-driven-pooler"){$.endTick(N);continue}else $.endTick(N);let V=K.total;if(!await this.storage.repository.evaluateDeadRun(N,H,V,P,15000)){this.logger.log(`[Engine] : Should not invoke for ${N}. Skipping.`);continue}let w=F.get("engine.selfInvocationIntervalSec")??1,T=F.get("runtime")=="v8-isolate",A=w;if(T&&F.raw.isolate){let _=F.raw.isolate.remainingTime/1000,h=this.minBootRequirementSec,s=w+h;if(_<s)return this.logger.log(`[EngineRuntime] : Isolate remaining time (${_.toFixed(3)}s) is insufficient for self-invocation (${w}s delay + ${h}s min work). Triggering restart.`),await this.handleRestart($),!0;let t=Math.max(1,_-h);A=Math.min(w,t)}let C=await this.triggerSelfInvocation({queue:N,pooler:H,delaySec:A,continuationOwnerId:P,isIdpLock:G,isEdpLock:Q,targetEdpQueue:J});if(C.idpInvoked)W=!0;if(C.continuationScheduledForCurrentLock)Z=!0}catch(K){this.logger.log(`[deadRun] : Error checking queue ${N}:`,K)}return Z}async handleRestart($){let W=!1,Z=$.currentExecutionId,P=F.get("engine.selfRestartIntervalSec"),X=$.getActiveQueues();for(let{queue:Q,pooler:G}of X){if(G=="interval-driven-pooler"&&W)continue;let J={"content-type":"application/json","x-last-execution-id":Z,"x-last-execution-at":new Date().toISOString(),"x-execution-owner":"engine","x-restart":"true","x-pooler":G,"x-target-queue":Q};if(this.logger.log(`(${G}) : invoking engine via restartTick (${P})`),G=="interval-driven-pooler")W=!0;let N=$.lockKey;await this.storage.repository.releaseQueueLock(N,$.isolateId),await this.storage.ops.addRestart(X),await this.queueService.triggerUrl({url:F.get("engine.selfURL"),headers:J,delaySeconds:P}),await this.storage.ops.updateRestartOwnership(Q,"handled_by_engine")}}}import{serve as b$}from"crossws/server";var _0=F0(g0(),1);var E0=_0.default;class K0 extends E0{config;serverInstance=null;logger;store;onFetch;constructor($){super();this.config=$;this.logger=new I,this.store=B()}async start(){let $=this;this.logger.log(`[Network] : Initializing server on port ${this.config.port} in [${this.config.mode}] mode`);let W=this.config.mode==="hybrid"||this.config.mode==="websocket";if(W)this.logger.log(`[Network] : WebSocket server handlers attached on port ${this.config.port}`);this.serverInstance=b$({port:this.config.port,...W?{websocket:{open(Z){$.emit("open",Z)},message(Z,P){$.emit("message",Z,P)},close(Z,P){$.emit("close",Z,P)}}}:{},fetch(Z){if($.onFetch)return $.onFetch(Z);return $.logger.warn(`[Network] : Unhandled route accessed: ${Z.method} ${Z.url}`),new Response(null,{status:404})},gracefulShutdown:!1,maxRequestBodySize:void 0}),this.store.kv.set("self_url",this.serverInstance.url),await this.serverInstance.ready(),this.logger.log(`[Server] Successfully started and listening on port ${this.config.port}`)}async close(){try{await this.serverInstance?.close(!0)}catch($){this.logger.error("[Network] : Error closing server:",$)}}}var z0=F0(B0(),1);class y{config;isRunning=!1;logger;rs;constructor($){this.config=$;this.logger=new I,this.rs=B()}}class u extends y{networkConfig;networkInterface;storage;queueService;interface="HTTP";consumersMap;triggerHandler;runtimeEventBridge;store;constructor($,W,Z,P){super($);this.networkConfig=$;this.networkInterface=W;this.storage=Z;this.queueService=P;this.store=B();let X=this.rs.kv.get("runtime_execution_id");this.runtimeEventBridge=new v(this.storage,this.logger,X);let Q=F.get("queues"),G=new Map;if(Q.forEach(({consumer:J,queue:N})=>G.set(N,J)),this.consumersMap=G,this.networkInterface)this.networkInterface.onFetch=(J)=>this.handleFetch(J)}async start(){}async broadcast($,W,Z){let P=this.consumersMap.get($);if(!P)throw Error(`No consumer registered for queue: "${$}"`);if(P.type!=="http")return;let{worker_id:X,batch:Q}=W,G=Z?z0.default.encode(W):W,J=F.get("runtime")=="persistent"?this.store.kv.get("self_url"):F.get("engine.selfURL");try{await fetch(`${P.url}/dispatch`,{method:"POST",headers:{"content-type":Z?"application/x-msgpack":"application/json",...P.headers,"x-worker-id":X,"x-batch-size":Q.length.toString(),"x-pulsar-callback-url":J,"x-queue":$,"x-execution-signature":crypto.randomUUID(),"x-instance-id":F.get("instanceId"),"x-api-key":F.get("apiKey"),"x-dispatched-at":new Date().toISOString()},body:G})}catch(N){this.logger.error("Error dispatching jobs to http consumer,",N)}}onTrigger($){this.triggerHandler=$}async stop(){}async handleFetch($){let{url:W,method:Z,body:P,headers:X}=await v$($),Q=x$(X),G=new URL(W),J={headers:Q,body:P};if(G.pathname.endsWith("/ack")&&Z==="POST"){let K=await this.handleAck(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/nack")&&Z==="POST"){let K=await this.handleNack(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/retry")&&Z==="POST"){let K=await this.handleRetry(J);return new Response(K.message,{status:K.status})}if(G.pathname.endsWith("/deregister")&&Z==="POST"){let K=await this.handleDeregister(J);return new Response(K.message,{status:K.status})}let{executionOwner:N,poolerMode:H}=Q;if(N=="trigger"){if(H=="event-driven-pooler"){let K=Q.targetQueue,V=Q.fencingToken??"0",M=this.store.kv.get("active_runtime_ctx");if(!M)return this.logger.warn("active runtime context was not found"),new Response("UNKNOWN ROUTE",{status:200});else await this.runtimeEventBridge.httpEventDrivenQueueTrigger(K,V,M)}}return new Response("UNKNOWN ROUTE",{status:200})}async performBatchAction($,W,Z,P){try{switch(P){case"ACK":await this.queueService.ackBatch($,Z);break;case"NACK":await this.queueService.ackBatch($,Z);break;case"RETRY":await this.queueService.retryBatch($,Z);break;case"DEREGISTER":await this.storage.repository.deregisterWorker(W,$);break}}catch(X){throw this.logger.error(`Error performing batch action [${P}] for queue [${$}]:`,X),X}}parseBody($){try{if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return z0.default.decode($);return $}catch(W){throw Error(`Failed to parse request body : ${W?.message}`)}}extractContext($){let W=$.headers,Z=this.parseBody($.body),P=W.targetQueue,X=W.workerId??"";if(!P)throw Error("[HttpNetworkDriver] Queue not found in headers");return{headers:W,body:Z,queue:P,workerId:X}}async getMessageIds($){let{queue:W,body:Z,workerId:P}=this.extractContext($),Q=(Array.isArray(Z?.msg_ids)?Z.msg_ids:[]).map((G)=>Number.parseInt(String(G),10)).filter((G)=>Number.isInteger(G)&&G>=0);return{queue:W,messageIds:Q,workerId:P}}async handleAck($){let{messageIds:W,queue:Z,workerId:P}=await this.getMessageIds($);return await this.performBatchAction(Z,P,W,"ACK"),{message:"Jobs Acknowledged",status:200}}async handleNack($){let{messageIds:W,queue:Z,workerId:P}=await this.getMessageIds($);return await this.performBatchAction(Z,P,W,"NACK"),{message:"Jobs Not Acknowledged",status:200}}async handleRetry($){let{queue:W,workerId:Z,messageIds:P}=await this.getMessageIds($);return await this.performBatchAction(W,Z,P,"RETRY"),{message:"Jobs Retry Applied",status:200}}async handleDeregister($){let{queue:W,workerId:Z}=this.extractContext($);if(!Z)throw Error("[HttpNetworkDriver] Worker ID not found in headers");return await this.performBatchAction(W,Z,[],"DEREGISTER"),{message:"Worker Deregistered",status:200}}}var l$=F0(B0(),1);class D0 extends y{networkInterface;interface="WEBSOCKET";queuePeers=new Map;triggerHandler;boundOpen=($)=>this.onConnectionOpen($);boundMessage=($,W)=>this.onMessage($,W);boundClose=($)=>this.onConnectionClose($);constructor($,W){super($);this.networkInterface=W;this.networkInterface.on("open",this.boundOpen),this.networkInterface.on("message",this.boundMessage),this.networkInterface.on("close",this.boundClose)}async start(){}async broadcast($,W,Z){let P=this.queuePeers.get($);if(!P||P.size===0){this.logger.warn(`[Network] : No active workers listening on queue: ${$}`);return}let X=Z?l$.default.encode(W):W;for(let Q of P)try{Q.send(X)}catch(G){this.logger.error(`[Network] : Failed to send message to peer ${Q.id}:`,G)}}onTrigger($){this.triggerHandler=$}async stop(){this.networkInterface.off("open",this.boundOpen),this.networkInterface.off("message",this.boundMessage),this.networkInterface.off("close",this.boundClose);for(let $ of this.queuePeers.values())for(let W of $)try{W.close(1001,"server shutting down")}catch{}this.queuePeers.clear()}onConnectionOpen($){this.logger.log("[Network] : Worker connected:",$.id)}onMessage($,W){let Z=JSON.parse(W.toString());Z.type==="REGISTER"?this.handleWorkerRegistration($,Z):this.handleWorkerMessage(Z)}handleWorkerRegistration($,W){let Z=this.queuePeers.get(W.queue);if(!Z)Z=new Set,this.queuePeers.set(W.queue,Z);if(Z.has($)){this.logger.log(`[Network] : Worker ${$.id} is already registered to queue: ${W.queue}`);return}$.subscribe(W.queue),Z.add($),this.rs.lists.add(W.queue,$.id),this.logger.log(`[Network] : Worker ${$.id} registered to queue: ${W.queue}`)}handleWorkerMessage($){if(this.triggerHandler){let W=$.queue,Z=$.data!==void 0?$?.data:$;if(W)this.triggerHandler(W,Z)}}onConnectionClose($){this.logger.log("[Network] : [WebSocketNetworkDriver] - Worker disconnected:",$.id);for(let[W,Z]of this.queuePeers.entries())if(Z.has($)){if(Z.delete($),this.rs.lists.remove(W,$.id),Z.size===0)this.queuePeers.delete(W)}}}class o{config;storage;queueServuce;drivers=[];topology;networkInterface;isServerMode;logger;constructor($,W,Z){this.config=$;this.storage=W;this.queueServuce=Z;if(this.topology=$.mode,this.isServerMode=$.isServer,this.logger=new I,this.isServerMode)this.initializeTopology();else this.initializeClientTopology()}initializeTopology(){if(this.networkInterface=new K0(this.config),this.config.mode==="websocket"||this.config.mode==="hybrid")this.drivers.push(new D0(this.config,this.networkInterface));if(this.config.mode==="http"||this.config.mode==="hybrid")this.drivers.push(new u(this.config,this.networkInterface,this.storage,this.queueServuce))}initializeClientTopology(){this.drivers.push(new u(this.config,void 0,this.storage,this.queueServuce))}async bootAll(){if(!this.isServerMode||!this.networkInterface)return;await this.networkInterface.start();for(let $ of this.drivers)await $.start()}async shutdownAll(){if(!this.isServerMode)return;for(let $ of this.drivers)await $.stop();await this.networkInterface?.close()}onTrigger($){for(let W of this.drivers)W.onTrigger($)}async dispatchToNetwork($,W){let Z=F.get("queues").find((J)=>J.queue===$),P={http:"HTTP",socket:"WEBSOCKET"},X=Z.consumer.type,Q=P[X];if(!Q)throw Error(`[DispatchToNetwork] : Unsupported consumer type "${X}" for queue: "${$}"`);for(let J of this.drivers)if(J.interface===Q)await J.broadcast($,W,Z.consumer.optimizePayload??!0);if(this.drivers.filter((J)=>J.interface===Q).length===0)throw this.logger.error(`[DispatchToNetwork] : No "${Q}" driver available for queue "${$}" (mode: ${this.topology}, server: ${this.isServerMode})`),Error(`[DispatchToNetwork] : No "${Q}" driver available for queue "${$}" (mode: ${this.topology}, server: ${this.isServerMode})`)}}class C0{storage;tickService;tickController;unifiedTransportManager;swarmManager;scheduler;queueService;clock;events;queues=[];consumers=[];runtimeStrategy;logger;integrations=new Map;constructor($){if(F.initialize($),this.logger=new I,$.integrations?.length)this.runIntegrations($.integrations);for(let{consumer:G,...J}of F.raw.queues)this.queues.push(J),this.consumers.push(G);let W=F.get("instanceId");if(!W)throw Error("[Pulsar] : instanceId is required.");if(typeof W!=="string"||!/^[a-zA-Z0-9_-]+$/.test(W))throw Error('[Pulsar] : Invalid instanceId format. It must contain only alphanumeric characters, hyphens, and underscores (e.g., "string-like-this" or "or_this").');this.events=new E;let P=1/0,X=F.raw.runtime==="v8-isolate",Q=F.get("isolate");if(X)P=Math.max(0,Q.remainingTime-5000);if(this.storage=F.raw.storage,this.storage.connect(),this.storage.bindInstanceId(W),this.clock=new e({maxExecutionBudgetMs:P,safetyBufferMs:0,maxTrackHistory:50,enabled:!0}),this.queueService=new q$(this.storage),this.scheduler=new W0,this.runtimeStrategy=this.resolveRuntimeStrategy(),!this.runtimeStrategy)throw this.logger.error("[Pulsar] Failed to resolve a valid runtime strategy."),Error("[Pulsar] Failed to resolve a valid runtime strategy.");if(F.raw.runtime=="persistent")this.unifiedTransportManager=new o({...F.raw.networkInterface,isServer:!0},this.storage,this.queueService);else this.unifiedTransportManager=new o({mode:"client",isServer:!1,port:0},this.storage,this.queueService);if(this.swarmManager=new $0(F.raw.swarmConfig?.globalMaxJobsPerTick??1/0,F.raw.swarmConfig?.maxGlobalConcurrency??1/0),this.tickService=new P0({queue:this.queueService,storage:this.storage,swarmManager:this.swarmManager,unifiedTransportManager:this.unifiedTransportManager,events:this.events}),this.tickController=new X0({scheduler:this.scheduler,storage:this.storage,tickService:this.tickService,clock:this.clock,events:this.events,runtimeStrategy:this.runtimeStrategy}),Number.isFinite(P))this.logger.log(`[EngineRuntime] : isolate registred with id : [${Q.id}]`),this.logger.log(`[Clock] : Synced execution timeout (${P/1000}s) with isolate [${Q.id}]`);else this.logger.log(`[EngineRuntime] : Engine Started With No V8 Isolate (${new Date().toISOString()})`)}resolveRuntimeStrategy(){let $={queueService:this.queueService,clock:this.clock,queues:this.queues,storage:this.storage,isolate:this.V8Isolate,events:this.events,scheduler:this.scheduler};switch(F.get("runtime")){case"persistent":return new Q0($);case"serverless-vm":return new G0($);case"v8-isolate":return new N0($);default:throw Error("Unsupported Runtime")}}async runIntegrations($){for(let W of $){let Z;if(typeof W==="function")Z=new W("ALL");else Z=W;await Z.main(this),this.integrations.set(Z.module,Z)}}getIntegration($){if(typeof $==="string")return this.integrations.get($);for(let Z of this.integrations.values())if(Z instanceof $)return Z;let W=typeof $==="string"?$:$.name;throw Error(`Integration "${W}" is not registered.`)}get runtime(){return this.runtimeStrategy.type}get isV8Isolate(){return F.get("runtime")==="v8-isolate"}get V8Isolate(){return F.raw.isolate}async exit(){await this.storage.disconnect()}}class j$ extends C0{baseConfig;isolateId;currentExecutionId;lockKey;shutdownPromise=null;eventCleanUps=[];activeQueues=new Set;constructor($){super($);this.baseConfig=$;if(this.registerEvents(),!this.isV8Isolate)this.isolateId=crypto.randomUUID();else this.isolateId=this.V8Isolate.id;if(this.isV8Isolate)this.currentExecutionId=this.V8Isolate.get("current_execution_id"),this.lockKey=this.V8Isolate.get("lock_key");else this.currentExecutionId=this.generateCurrentExecutionIdFromConfig(),this.lockKey="lock-template-static-defination-for-non-v8";this.tickController.initializeState()}async start(){await this.unifiedTransportManager.bootAll(),await F.reconcileConfiguration(this.storage.ops),this.tickController.initializeState(),this.configureQueueProfiles(),await this.runtimeStrategy.onStart(this.executionContext)}async triggerQueue($){let W=this.queues.find((Z)=>Z.queue===$);if(!W)throw Error("[Pulsar] Target queue is missing.");this.logger.log(`[Pulsar] : Event-driven trigger for (${$})`),await this.validateConfiguration(),await this.runTick(W)}async validateConfiguration(){return{status:200,message:await F.reconcileConfiguration(this.storage.ops)}}configureQueueProfiles(){for(let $ of this.queues){let W=$.profile||"REALTIME";this.scheduler.registerQueueProfile($.queue,W)}}async runTick($){return this.activeQueues.add($),await this.tickController.runTick($)}async shutdown(){return this.shutdownPromise??=this.doShutdown(),this.shutdownPromise}async doShutdown(){if(this.logger.log("Engine Shutdown ⚠️."),this.removeRegisteredEvents(),this.unifiedTransportManager)await this.unifiedTransportManager.shutdownAll();if(!await this.runtimeStrategy.handleCycleCompletion(this.executionContext))await this.releaseExecutionLock(this.lockKey,this.currentExecutionId);await this.storage.ops.pingHealthCheck(),await this.storage.disconnect()}async scheduleRestart($){if($){let Z=this.queues.find((P)=>P.queue==$);if(Z)this.activeQueues.add(Z)}let W=Array.from(this.activeQueues.values());await this.releaseExecutionLock(this.lockKey,this.isolateId),await this.storage.ops.addRestart(W),await this.runtimeStrategy.handleRestart(this.executionContext),await this.storage.ops.updateRestartOwnership($,"handled_by_engine")}async restartForSameIsolate($){let W=30;if(this.isV8Isolate)W=this.V8Isolate.remainingTime+5;this.logger.log(`Estimated Restart in (${W})S`),await this.queueService.triggerUrl({url:F.get("engine.selfURL"),headers:$,delaySeconds:W})}get executionContext(){return{lockKey:this.lockKey,currentExecutionId:this.currentExecutionId,isolateId:this.isolateId,getActiveQueues:()=>Array.from(this.activeQueues.values()),runTick:($)=>this.runTick($),endTick:($)=>this.tickController.endTick($)}}setCurrentExecutionId($){this.currentExecutionId=$}generateCurrentExecutionIdFromConfig(){let $=this.baseConfig.queues.map((W)=>`${W.queue}:${W.pooler}`).join(",");return JW($)}registerEvents(){let $=this.runtimeStrategy.shouldShutdownOnCycleComplete;this.eventCleanUps.push(this.events.on("tick:cycle-completed",async()=>{if($)await this.shutdown();else this.logger.log("[Pulsar Persistent] : Cycle completed. Resetting state for next execution round."),this.tickController.initializeState()})),this.eventCleanUps.push(this.events.on("tick:force-run",async({queue:W,reason:Z})=>{this.logger.log(`[Tick] : Force executing tick for queue [${W.queue}] Trigger Reason : ${Z}`),await this.runTick(W)})),this.eventCleanUps.push(this.events.on("tick:end",({queue:W,reason:Z})=>{this.logger.log(`[Tick] : Force stoping tick for queue [${W}] (Trigger Reason : ${Z})`),this.tickController.endTick(W)})),this.eventCleanUps.push(this.events.on("tick:time-exceeded",async()=>{if($)await this.shutdown()})),this.eventCleanUps.push(this.events.on("engine:health-check-requested",async()=>{this.logger.log(`Pulsar : Health checking ping at (${new Date().toISOString()})`),await this.storage.ops.pingHealthCheck()}))}removeRegisteredEvents(){this.eventCleanUps.forEach(($)=>$()),this.eventCleanUps=[]}async awaitPendingShutdown(){if(await this.events.drain(),this.shutdownPromise)await this.shutdownPromise}async deleteScheduledRestart($){await this.storage.ops.deleteRestart($)}async acquireExecutionLock($,W,Z){return await this.storage.repository.acquireQueueLock($,W,Z)}async releaseExecutionLock($,W){return await this.storage.repository.releaseQueueLock($,W)}}export{p$ as createQueue,l as PulsarRuntime,j$ as Pulsar,h0 as IsolateInstance,L0 as EventTriggerStrategy};
|
|
6
6
|
/* Powered by NightX - Pulsar Engine */
|
|
7
7
|
|
|
8
|
-
//# debugId=
|
|
8
|
+
//# debugId=3A67A9504B3A0F0764756E2164756E21
|