@vpxa/aikit 0.1.45 → 0.1.47

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.
Files changed (58) hide show
  1. package/package.json +1 -1
  2. package/packages/cli/dist/commands/init/index.js +4 -4
  3. package/packages/cli/dist/commands/init/scaffold.d.ts +6 -1
  4. package/packages/cli/dist/commands/init/scaffold.js +1 -1
  5. package/packages/cli/dist/commands/upgrade.js +1 -1
  6. package/packages/dashboard/dist/assets/{index-CO2S9BKY.js → index-L06q8M9R.js} +4 -4
  7. package/packages/dashboard/dist/assets/{index-CO2S9BKY.js.map → index-L06q8M9R.js.map} +1 -1
  8. package/packages/dashboard/dist/index.html +1 -1
  9. package/packages/present/dist/index.html +306 -306
  10. package/packages/server/dist/tools/flow.tools.js +1 -1
  11. package/packages/server/dist/tools/present-charts.js +1 -1
  12. package/packages/server/dist/tools/search.tool.js +1 -1
  13. package/packages/store/dist/sqlite-graph-store.js +1 -1
  14. package/packages/tui/dist/{App-DuldJWwG.js → App-CoMyn2kt.js} +1 -1
  15. package/packages/tui/dist/App.js +1 -1
  16. package/packages/tui/dist/{CuratedPanel-BIamXLNy.js → CuratedPanel-DGFKz-fJ.js} +1 -1
  17. package/packages/tui/dist/LogPanel-CDItCD0E.js +17 -0
  18. package/packages/tui/dist/{SearchPanel-CpJGczAc.js → SearchPanel-CDSGcT7M.js} +1 -1
  19. package/packages/tui/dist/{StatusPanel-BAbUxyqQ.js → StatusPanel-yRieSRc3.js} +1 -1
  20. package/packages/tui/dist/chunk-DqSKhezp.js +2 -0
  21. package/packages/tui/dist/devtools-6rm8h8Q1.js +7 -0
  22. package/packages/tui/dist/hooks/useKBClient.js +1 -1
  23. package/packages/tui/dist/hooks/usePolling.js +1 -1
  24. package/packages/tui/dist/index.js +1 -1
  25. package/packages/tui/dist/jsx-runtime-CI8Ofr1S.js +294 -0
  26. package/packages/tui/dist/panels/CuratedPanel.js +1 -1
  27. package/packages/tui/dist/panels/LogPanel.js +1 -1
  28. package/packages/tui/dist/panels/SearchPanel.js +1 -1
  29. package/packages/tui/dist/panels/StatusPanel.js +1 -1
  30. package/packages/tui/dist/{react-D__J1GQe.js → react-CKRDn6y3.js} +3 -3
  31. package/packages/tui/dist/{useKBClient-C35iA4uG.js → useKBClient-BACLDL_U.js} +1 -1
  32. package/packages/tui/dist/{usePolling-BbjnRWgx.js → usePolling-D-4v1sTA.js} +1 -1
  33. package/scaffold/adapters/claude-code.mjs +34 -8
  34. package/scaffold/adapters/copilot.mjs +1 -1
  35. package/scaffold/claude-code/commands/aikit-ask.md +12 -0
  36. package/scaffold/claude-code/commands/aikit-debug.md +14 -0
  37. package/scaffold/claude-code/commands/aikit-design.md +14 -0
  38. package/scaffold/claude-code/commands/aikit-flow-add.md +83 -0
  39. package/scaffold/claude-code/commands/aikit-flow-create.md +79 -0
  40. package/scaffold/claude-code/commands/aikit-flow-manage.md +23 -0
  41. package/scaffold/claude-code/commands/aikit-implement.md +16 -0
  42. package/scaffold/claude-code/commands/aikit-plan.md +14 -0
  43. package/scaffold/claude-code/commands/aikit-review.md +23 -0
  44. package/scaffold/definitions/prompts.mjs +201 -0
  45. package/scaffold/general/prompts/aikit-flow-add.prompt.md +92 -0
  46. package/scaffold/general/prompts/aikit-flow-create.prompt.md +88 -0
  47. package/scaffold/general/prompts/aikit-flow-manage.prompt.md +33 -0
  48. package/scaffold/generate.mjs +1 -1
  49. package/packages/tui/dist/LogPanel-B8EJGqBN.js +0 -17
  50. package/packages/tui/dist/chunk-D6axbAb-.js +0 -2
  51. package/packages/tui/dist/devtools-DMOZMn70.js +0 -7
  52. package/packages/tui/dist/jsx-runtime-y6Gdq5PZ.js +0 -294
  53. /package/scaffold/general/prompts/{ask.prompt.md → aikit-ask.prompt.md} +0 -0
  54. /package/scaffold/general/prompts/{debug.prompt.md → aikit-debug.prompt.md} +0 -0
  55. /package/scaffold/general/prompts/{design.prompt.md → aikit-design.prompt.md} +0 -0
  56. /package/scaffold/general/prompts/{implement.prompt.md → aikit-implement.prompt.md} +0 -0
  57. /package/scaffold/general/prompts/{plan.prompt.md → aikit-plan.prompt.md} +0 -0
  58. /package/scaffold/general/prompts/{review.prompt.md → aikit-review.prompt.md} +0 -0
@@ -161,4 +161,205 @@ Merge findings from both reviewers:
161
161
  ### Step 5: Report
162
162
  Present unified review with: verdict, findings by severity, recommended actions.`,
163
163
  },
164
+
165
+ 'flow-add': {
166
+ description:
167
+ 'Install a new flow from a git URL or local path — with interactive error recovery',
168
+ agent: 'Orchestrator',
169
+ tools: ['flow_add', 'flow_list', 'flow_info', 'search', 'compact', 'file_summary', 'present'],
170
+ content: `## Flow Installation Assistant
171
+
172
+ Install a development flow from a git repository or local directory.
173
+
174
+ ### Usage
175
+ Provide a git URL or local path:
176
+ - \`https://github.com/org/my-flow.git\`
177
+ - \`git@github.com:org/my-flow.git\`
178
+ - \`./path/to/local/flow\`
179
+ - \`C:\\Users\\name\\flows\\my-flow\`
180
+
181
+ ### Workflow
182
+
183
+ 1. **Attempt Install** — Call \`flow_add\` with the provided source
184
+ 2. **On Success** — Show installed flow info with \`flow_info\`, present summary to user
185
+ 3. **On Failure** — Classify the error and enter the appropriate recovery path:
186
+
187
+ ### Error Recovery Paths
188
+
189
+ #### Git Authentication Failure
190
+ If the error mentions authentication, credentials, 401, 403, permission denied, or SAML:
191
+
192
+ 1. Present the error clearly to the user
193
+ 2. Ask which auth method they prefer:
194
+ - **SSH key**: Walk through \`ssh-keygen -t ed25519\`, adding the public key to their git host, and retrying with the SSH URL
195
+ - **Personal Access Token (PAT)**: Guide them to create a PAT in their git host settings, configure \`git credential.helper store\`, and retry
196
+ - **Git Credential Manager**: Check if GCM is installed, help install if needed, then retry (GCM opens a browser for auth)
197
+ 3. After credentials are configured, retry \`flow_add\`
198
+
199
+ #### Network / Connectivity Failure
200
+ If the error mentions timeout, host not found, SSL, or proxy:
201
+
202
+ 1. Present diagnostics: Is VPN needed? Is the URL correct? Is there a proxy?
203
+ 2. Guide the user through resolution
204
+ 3. Retry after the issue is resolved
205
+
206
+ #### Format Not Recognized
207
+ If \`flow_add\` succeeds cloning but returns a format/structure error:
208
+
209
+ 1. Explain that the source was fetched but doesn't match any supported format
210
+ 2. List the 3 supported formats:
211
+ - **Native**: Has a \`flow.json\` manifest in the root
212
+ - **Claude Plugin**: Has \`.claude-plugin/plugin.json\` with skills as steps
213
+ - **Copilot Agents**: Has \`.github/agents/\` with agent .md files as steps
214
+ 3. Analyze the source structure to understand what's there
215
+ 4. Offer to help migrate:
216
+ - If it has README files or markdown docs → propose creating a \`flow.json\` that maps them as steps
217
+ - If it has a different workflow format → propose conversion
218
+ - If it's missing key parts → guide user to fill them in
219
+ 5. Create the missing \`flow.json\` manifest and step structure
220
+ 6. Retry \`flow_add\` with the fixed source
221
+
222
+ ### Native flow.json Format Reference
223
+ \`\`\`json
224
+ {
225
+ "name": "my-flow",
226
+ "version": "1.0.0",
227
+ "description": "Description of the flow",
228
+ "steps": [
229
+ {
230
+ "id": "step-id",
231
+ "name": "Step Name",
232
+ "instruction": "steps/step-id/README.md",
233
+ "produces": ["output.md"],
234
+ "requires": [],
235
+ "agents": [],
236
+ "description": "What this step does"
237
+ }
238
+ ],
239
+ "agents": [],
240
+ "artifacts_dir": ".spec",
241
+ "install": []
242
+ }
243
+ \`\`\`
244
+
245
+ ### Post-Install
246
+ After successful installation:
247
+ - Show the flow name, steps, and description via \`present\`
248
+ - Remind user they can start it with \`flow_start\``,
249
+ },
250
+
251
+ 'flow-manage': {
252
+ description: 'List, inspect, update, and remove installed flows',
253
+ agent: 'Orchestrator',
254
+ tools: [
255
+ 'flow_list',
256
+ 'flow_info',
257
+ 'flow_status',
258
+ 'flow_update',
259
+ 'flow_remove',
260
+ 'flow_start',
261
+ 'flow_reset',
262
+ 'present',
263
+ ],
264
+ content: `## Flow Management
265
+
266
+ Manage your installed development flows.
267
+
268
+ ### Available Actions
269
+
270
+ 1. **List flows** — \`flow_list\` to see all installed flows with status
271
+ 2. **Inspect a flow** — \`flow_info\` to see detailed steps, agents, and artifacts
272
+ 3. **Check status** — \`flow_status\` to see the active flow and current step
273
+ 4. **Update a flow** — \`flow_update\` to pull latest changes for git-installed flows
274
+ 5. **Remove a flow** — \`flow_remove\` to uninstall (builtin flows cannot be removed)
275
+ 6. **Start a flow** — \`flow_start\` to begin executing a flow
276
+ 7. **Reset active flow** — \`flow_reset\` to clear active flow state
277
+
278
+ ### Workflow
279
+ 1. If no specific action requested, start with \`flow_list\` and present overview
280
+ 2. Use \`present\` to display flow information in a clear table/card format
281
+ 3. For updates, warn if there's an active flow that might be affected
282
+ 4. For removals, confirm with user before proceeding`,
283
+ },
284
+
285
+ 'flow-create': {
286
+ description: 'Create a new flow from scratch or migrate an existing workflow to aikit format',
287
+ agent: 'Orchestrator',
288
+ tools: ['flow_add', 'flow_list', 'flow_info', 'search', 'compact', 'file_summary', 'present'],
289
+ content: `## Flow Creation Assistant
290
+
291
+ Create a new development flow or migrate an existing workflow to the aikit flow format.
292
+
293
+ ### Mode 1: Create from Scratch
294
+
295
+ Guide the user through building a complete flow:
296
+
297
+ 1. **Define the workflow** — Ask what the flow should accomplish (e.g., "TDD workflow", "documentation pipeline", "migration process")
298
+ 2. **Design steps** — Break the workflow into sequential steps (3-8 is ideal)
299
+ 3. **For each step**:
300
+ - Define the step id, name, and description
301
+ - Write the instruction (README.md content — what the agent should do)
302
+ - Identify what it produces (output artifacts)
303
+ - Identify what it requires (which previous steps must complete first)
304
+ - Optionally assign preferred agents
305
+ 4. **Generate flow.json** — Create the manifest with all steps
306
+ 5. **Write step READMEs** — Create instruction files for each step
307
+ 6. **Install** — Use \`flow_add\` to install from the local directory
308
+
309
+ ### Mode 2: Migrate Existing Workflow
310
+
311
+ If the user has an existing workflow (scripts, docs, runbooks) that they want to convert:
312
+
313
+ 1. **Analyze the source** — Read the existing workflow files to understand the process
314
+ 2. **Map to steps** — Identify discrete steps with clear inputs/outputs
315
+ 3. **Identify gaps** — What's missing for a complete flow? (instructions? ordering? agents?)
316
+ 4. **Fill gaps with user** — Ask user to clarify any ambiguous parts
317
+ 5. **Generate the flow** — Create flow.json + step READMEs
318
+ 6. **Install and validate** — Use \`flow_add\` and \`flow_info\` to verify
319
+
320
+ ### Flow Structure
321
+
322
+ \`\`\`
323
+ my-flow/
324
+ flow.json — Flow manifest (name, version, steps, agents)
325
+ steps/
326
+ step-1/
327
+ README.md — Step instructions (what the agent should do)
328
+ step-2/
329
+ README.md
330
+ references/ — Optional reference files for the step
331
+ ...
332
+ \`\`\`
333
+
334
+ ### flow.json Format
335
+ \`\`\`json
336
+ {
337
+ "name": "my-flow",
338
+ "version": "1.0.0",
339
+ "description": "What this flow does",
340
+ "steps": [
341
+ {
342
+ "id": "step-id",
343
+ "name": "Human-readable Step Name",
344
+ "instruction": "steps/step-id/README.md",
345
+ "produces": ["artifact-name.md"],
346
+ "requires": [],
347
+ "agents": ["Preferred-Agent"],
348
+ "description": "Brief description of this step"
349
+ }
350
+ ],
351
+ "agents": [],
352
+ "artifacts_dir": ".spec",
353
+ "install": []
354
+ }
355
+ \`\`\`
356
+
357
+ ### Step README Format
358
+ Each step README should include:
359
+ - **Goal** — What this step accomplishes
360
+ - **Inputs** — What context/artifacts from prior steps are needed
361
+ - **Instructions** — Detailed steps for the agent to follow
362
+ - **Output** — What artifact(s) to produce and where to save them
363
+ - **Acceptance criteria** — How to know the step is complete`,
364
+ },
164
365
  };
@@ -0,0 +1,92 @@
1
+ ---
2
+ description: "Install a new flow from a git URL or local path — with interactive error recovery"
3
+ agent: "Orchestrator"
4
+ tools:
5
+ - aikit/flow_add
6
+ - aikit/flow_list
7
+ - aikit/flow_info
8
+ - aikit/search
9
+ - aikit/compact
10
+ - aikit/file_summary
11
+ - aikit/present
12
+ ---
13
+
14
+ ## Flow Installation Assistant
15
+
16
+ Install a development flow from a git repository or local directory.
17
+
18
+ ### Usage
19
+ Provide a git URL or local path:
20
+ - `https://github.com/org/my-flow.git`
21
+ - `git@github.com:org/my-flow.git`
22
+ - `./path/to/local/flow`
23
+ - `C:\Users\name\flows\my-flow`
24
+
25
+ ### Workflow
26
+
27
+ 1. **Attempt Install** — Call `flow_add` with the provided source
28
+ 2. **On Success** — Show installed flow info with `flow_info`, present summary to user
29
+ 3. **On Failure** — Classify the error and enter the appropriate recovery path:
30
+
31
+ ### Error Recovery Paths
32
+
33
+ #### Git Authentication Failure
34
+ If the error mentions authentication, credentials, 401, 403, permission denied, or SAML:
35
+
36
+ 1. Present the error clearly to the user
37
+ 2. Ask which auth method they prefer:
38
+ - **SSH key**: Walk through `ssh-keygen -t ed25519`, adding the public key to their git host, and retrying with the SSH URL
39
+ - **Personal Access Token (PAT)**: Guide them to create a PAT in their git host settings, configure `git credential.helper store`, and retry
40
+ - **Git Credential Manager**: Check if GCM is installed, help install if needed, then retry (GCM opens a browser for auth)
41
+ 3. After credentials are configured, retry `flow_add`
42
+
43
+ #### Network / Connectivity Failure
44
+ If the error mentions timeout, host not found, SSL, or proxy:
45
+
46
+ 1. Present diagnostics: Is VPN needed? Is the URL correct? Is there a proxy?
47
+ 2. Guide the user through resolution
48
+ 3. Retry after the issue is resolved
49
+
50
+ #### Format Not Recognized
51
+ If `flow_add` succeeds cloning but returns a format/structure error:
52
+
53
+ 1. Explain that the source was fetched but doesn't match any supported format
54
+ 2. List the 3 supported formats:
55
+ - **Native**: Has a `flow.json` manifest in the root
56
+ - **Claude Plugin**: Has `.claude-plugin/plugin.json` with skills as steps
57
+ - **Copilot Agents**: Has `.github/agents/` with agent .md files as steps
58
+ 3. Analyze the source structure to understand what's there
59
+ 4. Offer to help migrate:
60
+ - If it has README files or markdown docs → propose creating a `flow.json` that maps them as steps
61
+ - If it has a different workflow format → propose conversion
62
+ - If it's missing key parts → guide user to fill them in
63
+ 5. Create the missing `flow.json` manifest and step structure
64
+ 6. Retry `flow_add` with the fixed source
65
+
66
+ ### Native flow.json Format Reference
67
+ ```json
68
+ {
69
+ "name": "my-flow",
70
+ "version": "1.0.0",
71
+ "description": "Description of the flow",
72
+ "steps": [
73
+ {
74
+ "id": "step-id",
75
+ "name": "Step Name",
76
+ "instruction": "steps/step-id/README.md",
77
+ "produces": ["output.md"],
78
+ "requires": [],
79
+ "agents": [],
80
+ "description": "What this step does"
81
+ }
82
+ ],
83
+ "agents": [],
84
+ "artifacts_dir": ".spec",
85
+ "install": []
86
+ }
87
+ ```
88
+
89
+ ### Post-Install
90
+ After successful installation:
91
+ - Show the flow name, steps, and description via `present`
92
+ - Remind user they can start it with `flow_start`
@@ -0,0 +1,88 @@
1
+ ---
2
+ description: "Create a new flow from scratch or migrate an existing workflow to aikit format"
3
+ agent: "Orchestrator"
4
+ tools:
5
+ - aikit/flow_add
6
+ - aikit/flow_list
7
+ - aikit/flow_info
8
+ - aikit/search
9
+ - aikit/compact
10
+ - aikit/file_summary
11
+ - aikit/present
12
+ ---
13
+
14
+ ## Flow Creation Assistant
15
+
16
+ Create a new development flow or migrate an existing workflow to the aikit flow format.
17
+
18
+ ### Mode 1: Create from Scratch
19
+
20
+ Guide the user through building a complete flow:
21
+
22
+ 1. **Define the workflow** — Ask what the flow should accomplish (e.g., "TDD workflow", "documentation pipeline", "migration process")
23
+ 2. **Design steps** — Break the workflow into sequential steps (3-8 is ideal)
24
+ 3. **For each step**:
25
+ - Define the step id, name, and description
26
+ - Write the instruction (README.md content — what the agent should do)
27
+ - Identify what it produces (output artifacts)
28
+ - Identify what it requires (which previous steps must complete first)
29
+ - Optionally assign preferred agents
30
+ 4. **Generate flow.json** — Create the manifest with all steps
31
+ 5. **Write step READMEs** — Create instruction files for each step
32
+ 6. **Install** — Use `flow_add` to install from the local directory
33
+
34
+ ### Mode 2: Migrate Existing Workflow
35
+
36
+ If the user has an existing workflow (scripts, docs, runbooks) that they want to convert:
37
+
38
+ 1. **Analyze the source** — Read the existing workflow files to understand the process
39
+ 2. **Map to steps** — Identify discrete steps with clear inputs/outputs
40
+ 3. **Identify gaps** — What's missing for a complete flow? (instructions? ordering? agents?)
41
+ 4. **Fill gaps with user** — Ask user to clarify any ambiguous parts
42
+ 5. **Generate the flow** — Create flow.json + step READMEs
43
+ 6. **Install and validate** — Use `flow_add` and `flow_info` to verify
44
+
45
+ ### Flow Structure
46
+
47
+ ```
48
+ my-flow/
49
+ flow.json — Flow manifest (name, version, steps, agents)
50
+ steps/
51
+ step-1/
52
+ README.md — Step instructions (what the agent should do)
53
+ step-2/
54
+ README.md
55
+ references/ — Optional reference files for the step
56
+ ...
57
+ ```
58
+
59
+ ### flow.json Format
60
+ ```json
61
+ {
62
+ "name": "my-flow",
63
+ "version": "1.0.0",
64
+ "description": "What this flow does",
65
+ "steps": [
66
+ {
67
+ "id": "step-id",
68
+ "name": "Human-readable Step Name",
69
+ "instruction": "steps/step-id/README.md",
70
+ "produces": ["artifact-name.md"],
71
+ "requires": [],
72
+ "agents": ["Preferred-Agent"],
73
+ "description": "Brief description of this step"
74
+ }
75
+ ],
76
+ "agents": [],
77
+ "artifacts_dir": ".spec",
78
+ "install": []
79
+ }
80
+ ```
81
+
82
+ ### Step README Format
83
+ Each step README should include:
84
+ - **Goal** — What this step accomplishes
85
+ - **Inputs** — What context/artifacts from prior steps are needed
86
+ - **Instructions** — Detailed steps for the agent to follow
87
+ - **Output** — What artifact(s) to produce and where to save them
88
+ - **Acceptance criteria** — How to know the step is complete
@@ -0,0 +1,33 @@
1
+ ---
2
+ description: "List, inspect, update, and remove installed flows"
3
+ agent: "Orchestrator"
4
+ tools:
5
+ - aikit/flow_list
6
+ - aikit/flow_info
7
+ - aikit/flow_status
8
+ - aikit/flow_update
9
+ - aikit/flow_remove
10
+ - aikit/flow_start
11
+ - aikit/flow_reset
12
+ - aikit/present
13
+ ---
14
+
15
+ ## Flow Management
16
+
17
+ Manage your installed development flows.
18
+
19
+ ### Available Actions
20
+
21
+ 1. **List flows** — `flow_list` to see all installed flows with status
22
+ 2. **Inspect a flow** — `flow_info` to see detailed steps, agents, and artifacts
23
+ 3. **Check status** — `flow_status` to see the active flow and current step
24
+ 4. **Update a flow** — `flow_update` to pull latest changes for git-installed flows
25
+ 5. **Remove a flow** — `flow_remove` to uninstall (builtin flows cannot be removed)
26
+ 6. **Start a flow** — `flow_start` to begin executing a flow
27
+ 7. **Reset active flow** — `flow_reset` to clear active flow state
28
+
29
+ ### Workflow
30
+ 1. If no specific action requested, start with `flow_list` and present overview
31
+ 2. Use `present` to display flow information in a clear table/card format
32
+ 3. For updates, warn if there's an active flow that might be affected
33
+ 4. For removals, confirm with user before proceeding
@@ -51,7 +51,7 @@ for (const ide of idesToRun) {
51
51
 
52
52
  // Clean only the subdirectories the generator manages (agents/, prompts/).
53
53
  // This avoids wiping hand-maintained files if they coexist in general/.
54
- for (const subdir of ['agents', 'prompts']) {
54
+ for (const subdir of ['agents', 'prompts', 'commands']) {
55
55
  const sub = resolve(outDir, subdir);
56
56
  if (existsSync(sub)) {
57
57
  rmSync(sub, { recursive: true });
@@ -1,17 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{r as e}from"./chunk-D6axbAb-.js";import{t}from"./react-D__J1GQe.js";import{a as n,i as r,t as i}from"./jsx-runtime-y6Gdq5PZ.js";import{homedir as a}from"node:os";import{exec as o,execFile as s}from"node:child_process";import{appendFileSync as c,closeSync as ee,constants as l,existsSync as u,mkdirSync as d,openSync as f,readFileSync as p,readdirSync as te,renameSync as m,statSync as h,unlinkSync as g,writeFileSync as _}from"node:fs";import{basename as v,dirname as y,join as b,resolve as x}from"node:path";import{promisify as S}from"node:util";import{fileURLToPath as C}from"node:url";import{createHash as w}from"node:crypto";import"gpt-tokenizer/model/gpt-4o";import"diff";import{LRUCache as T}from"lru-cache";import"turndown";S(o),b(y(C(import.meta.url)),`..`,`..`,`wasm`),new Set(Object.keys({".ts":`tree-sitter-typescript.wasm`,".tsx":`tree-sitter-typescript.wasm`,".mts":`tree-sitter-typescript.wasm`,".cts":`tree-sitter-typescript.wasm`,".js":`tree-sitter-javascript.wasm`,".jsx":`tree-sitter-javascript.wasm`,".mjs":`tree-sitter-javascript.wasm`,".cjs":`tree-sitter-javascript.wasm`,".py":`tree-sitter-python.wasm`,".go":`tree-sitter-go.wasm`,".rs":`tree-sitter-rust.wasm`,".java":`tree-sitter-java.wasm`,".kt":`tree-sitter-kotlin.wasm`,".kts":`tree-sitter-kotlin.wasm`,".scala":`tree-sitter-scala.wasm`,".sc":`tree-sitter-scala.wasm`,".c":`tree-sitter-c.wasm`,".h":`tree-sitter-c.wasm`,".cpp":`tree-sitter-cpp.wasm`,".cc":`tree-sitter-cpp.wasm`,".cxx":`tree-sitter-cpp.wasm`,".hpp":`tree-sitter-cpp.wasm`,".hxx":`tree-sitter-cpp.wasm`,".cs":`tree-sitter-c_sharp.wasm`,".swift":`tree-sitter-swift.wasm`,".rb":`tree-sitter-ruby.wasm`,".php":`tree-sitter-php.wasm`}));const E={ai:`.ai`,aiContext:`.ai/context`,aiCurated:`.ai/curated`,restorePoints:`.ai/restore-points`,data:`.aikit-data`,state:`.aikit-state`,logs:`.aikit-state/logs`,brainstorm:`.brainstorm`,handoffs:`.handoffs`},D={root:`.aikit-data`,registry:`registry.json`};E.data;function O(){return process.env.AIKIT_GLOBAL_DATA_DIR??x(a(),D.root)}function ne(e){let t=x(e);return`${v(t).toLowerCase().replace(/[^a-z0-9-]/g,`-`)||`workspace`}-${w(`sha256`).update(t).digest(`hex`).slice(0,8)}`}function re(){let e=x(O(),D.registry);if(!u(e))return{version:1,workspaces:{}};let t=p(e,`utf-8`);try{return JSON.parse(t)}catch{return{version:1,workspaces:{}}}}function ie(e,t=5e3){let n=`${e}.lock`,r=Date.now()+t,i=10;for(;Date.now()<r;)try{let e=f(n,l.O_CREAT|l.O_EXCL|l.O_WRONLY);return _(e,`${process.pid}\n`),ee(e),n}catch(e){if(e.code!==`EEXIST`)throw e;try{let{mtimeMs:e}=h(n);if(Date.now()-e>3e4){g(n);continue}}catch{}let t=new SharedArrayBuffer(4);Atomics.wait(new Int32Array(t),0,0,i),i=Math.min(i*2,200)}throw Error(`Failed to acquire registry lock after ${t}ms`)}function ae(e){try{g(e)}catch{}}function oe(e){let t=O();d(t,{recursive:!0});let n=x(t,D.registry),r=ie(n);try{let t=`${n}.tmp`;_(t,JSON.stringify(e,null,2),`utf-8`),m(t,n)}finally{ae(r)}}function se(e){let t=re(),n=ne(e),r=new Date().toISOString();return t.workspaces[n]?t.workspaces[n].lastAccessedAt=r:t.workspaces[n]={partition:n,workspacePath:x(e),registeredAt:r,lastAccessedAt:r},d(k(n),{recursive:!0}),oe(t),t.workspaces[n]}function k(e){return x(O(),e)}function A(){return u(x(O(),D.registry))}function j(e){return A()?x(k(se(e).partition),`state`):x(e,E.state)}const M={debug:0,info:1,warn:2,error:3},N=[];let P=process.env.AIKIT_LOG_LEVEL??`info`,F=process.env.AIKIT_LOG_FILE_SINK===`true`||process.env.AIKIT_LOG_FILE_SINK!==`false`&&!process.env.VITEST&&process.env.NODE_ENV!==`test`;function I(){return F?process.env.VITEST||process.env.NODE_ENV===`test`?process.env.AIKIT_LOG_FILE_SINK===`true`:!0:!1}let L;function R(){return L||=b(j(process.cwd()),`logs`),L}function z(e){let t=e.toISOString().slice(0,10);return b(R(),`${t}.jsonl`)}let B=0;function V(){let e=Date.now();if(!(e-B<36e5)){B=e;try{let t=R(),n=new Date(e-30*864e5).toISOString().slice(0,10);for(let e of te(t))if(e.endsWith(`.jsonl`)&&e.slice(0,10)<n)try{g(b(t,e))}catch{}}catch{}}}function H(e,t){try{d(R(),{recursive:!0}),c(z(t),`${e}\n`),V()}catch{}}function U(e){function t(t,n,r){if(M[t]<M[P])return;let i=new Date,a={ts:i.toISOString(),level:t,component:e,msg:n,...r},o=JSON.stringify(a);console.error(o);for(let i of N)try{i({level:t,component:e,message:n,data:r})}catch{}I()&&(t===`warn`||t===`error`)&&H(o,i)}return{debug:(e,n)=>t(`debug`,e,n),info:(e,n)=>t(`info`,e,n),warn:(e,n)=>t(`warn`,e,n),error:(e,n)=>t(`error`,e,n)}}const W=U(`query-executor`),G=y(C(import.meta.url));function ce(){let e=b(G,`..`,`queries`);if(u(e))return e;let t=b(G,`..`,`..`,`src`,`queries`);return u(t)?t:e}const K=ce(),le={".ts":`typescript`,".tsx":`typescript`,".mts":`typescript`,".cts":`typescript`,".js":`javascript`,".jsx":`javascript`,".mjs":`javascript`,".cjs":`javascript`,".py":`python`,".go":`go`,".rs":`rust`,".java":`java`};var q=class{queryCache=new Map;scmCache=new Map;execute(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.matches(e).map(e=>J(e)):[]}executeCaptures(e,t,n,r){let i=this.getOrCompile(t,n,r);return i?i.captures(e).map(e=>Y(e)):[]}executeRaw(e,t,n){return t.query(n).matches(e).map(e=>J(e))}getOrCompile(e,t,n){let r=le[t];if(!r)return null;let i=`${r}:${n}`,a=this.queryCache.get(i);if(a)return a;let o=this.loadScm(r,n);if(!o)return null;try{let t=e.query(o);return this.queryCache.set(i,t),t}catch(e){throw W.warn(`Failed to compile query`,{langDir:r,queryType:n,error:String(e)}),Error(`Failed to compile ${r}/${n}.scm: ${String(e)}`)}}loadScm(e,t){let n=`${e}:${t}`,r=this.scmCache.get(n);if(r!==void 0)return r;let i=b(K,e,`${t}.scm`);try{let e=p(i,`utf-8`);return this.scmCache.set(n,e),e}catch{return W.info(`Query file not found (graceful skip)`,{langDir:e,queryType:t}),null}}dispose(){this.queryCache.clear(),this.scmCache.clear()}static resolveQueryDir(e){return b(K,e)}};function J(e){let t=new Map;for(let n of e.captures)t.set(n.name,Y(n));return{pattern:e.pattern,captures:t}}function Y(e){let{node:t}=e;return{name:e.name,text:t.text,nodeType:t.type,startLine:t.startPosition.row,endLine:t.endPosition.row,startColumn:t.startPosition.column,endColumn:t.endPosition.column,node:t}}new q,new q,new q,new q,new q,new Set(`.ts,.tsx,.js,.jsx,.mjs,.cjs,.java,.kt,.kts,.scala,.py,.go,.rs,.rb,.php,.swift,.cs,.c,.cpp,.h,.hpp,.sh,.bash,.ps1,.sql,.graphql,.gql,.proto,.json,.yaml,.yml,.toml,.env,.ini,.cfg,.xml,.pom,.gradle,.tf,.hcl,.lock,.mjs`.split(`,`)),E.restorePoints,new Set([`node_modules`,`.git`,`dist`,`build`,`coverage`,`.turbo`,`.cache`,`cdk.out`,E.state]),new T({max:200,ttl:1e3*60*30});const X=[];function ue(e){X.push(e),X.sort((e,t)=>t.priority-e.priority)}function de(e){for(let t of e)ue(t)}de([{name:`git`,toolPatterns:[`git`,`git-status`],priority:10,match(e){return e.tool===`git`||e.tool===`git-status`},compress(e){let t=e.text.split(`
3
- `),n=[],r=!1,i=0,a=0,o=``;for(let s of t){if(s.startsWith(`diff --git`)||s.startsWith(`---`)||s.startsWith(`+++`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),r=!1,i=0,a=0,n.push(s),s.startsWith(`diff --git`)&&(o=s.replace(/^diff --git a\/\S+ b\//,``));continue}if(s.startsWith(`@@`)){r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines]`),r=!0,i=0,a=0,n.push(s);continue}if(e.tool===`git-status`){n.push(s);continue}if(r){s.startsWith(`+`)?i++:s.startsWith(`-`)&&a++;continue}if(s.startsWith(`commit `)||s.startsWith(`Author:`)||s.startsWith(`Date:`)||s.startsWith(`On branch`)||s.match(/^\s*\d+ file/)||s.match(/insertion|deletion/)){n.push(s);continue}if(s.startsWith(`error:`)||s.startsWith(`fatal:`)||s.startsWith(`warning:`)){n.push(s);continue}/^\s{4}\S/.test(s)&&n.push(s)}return r&&(i>0||a>0)&&n.push(` [${i}+ ${a}- lines in ${o}]`),n.join(`
4
- `)}},{name:`npm`,toolPatterns:[`npm`,`pnpm`,`yarn`],priority:10,match(e){return e.tool===`npm`||e.tool===`pnpm`},compress(e){let t=e.text.split(`
5
- `),n=[],r=0,i=0,a=[];for(let e of t){if(e.includes(`ERR!`)||e.startsWith(`npm error`)||e.includes(`ERESOLVE`)){a.push(e);continue}if(e.includes(`npm warn`)||e.includes(`WARN`)){r++,r<=3&&n.push(e);continue}if(e.includes(`notice`)){i++;continue}if(!(e.includes(`timing`)||e.includes(`http fetch`)||/^\s*$/.test(e))){if(e.match(/^(added|removed|changed|up to date|audited|found \d+)/)){n.push(e);continue}if(e.match(/^(Packages:|Progress:|Done in|dependencies:)/)){n.push(e);continue}e.match(/^(>|\$)\s/)&&n.push(e)}}return r>3&&n.push(`[${r-3} more warnings]`),i>0&&n.push(`[${i} notices]`),a.length>0&&(n.unshift(`=== ERRORS ===`),n.splice(1,0,...a)),n.join(`
6
- `)}},{name:`test-runner`,toolPatterns:[`test-runner`,`vitest`,`jest`,`mocha`],priority:10,match(e){return e.tool===`test-runner`},compress(e){let t=e.text.split(`
7
- `),n=[],r=0,i=!1,a=[];for(let e of t){if(e.match(/Tests?\s+\d+\s+(passed|failed)|Test Suites:|test.*files?|Duration/i)){n.push(e);continue}if(e.match(/^(FAIL|✗|×|✖)\s/)||e.match(/^\s*(FAIL|Error|AssertionError)/)){i&&a.length>0&&n.push(...a),i=!0,a=[e];continue}if(i){if(e.match(/^\s+(at\s|Expected|Received|>\s|\d+\s*\||⎯|─)/)||e.trim().length===0){a.length<12&&a.push(e);continue}n.push(...a),i=!1,a=[]}if(e.match(/^(PASS|✓|✔|√)\s/)||e.match(/^\s*✓\s/)){r++;continue}if(e.match(/^\s*(PASS|FAIL|RUN)\s+\S+\.(test|spec)\./)){n.push(e);continue}e.match(/^(Rerun|Watch|press|Waiting|stdout)/)||e.trim()}return i&&a.length>0&&n.push(...a),r>0&&n.unshift(`[${r} tests passed]`),n.join(`
8
- `)}},{name:`lint`,toolPatterns:[`lint`,`tsc`,`eslint`,`biome`],priority:10,match(e){return e.tool===`lint`||e.tool===`tsc`},compress(e){let t=e.text.split(`
9
- `),n=[],r=[],i=0;for(let e of t){if(e.match(/:\d+:\d+\s+error\b/i)||e.match(/^error\s+TS\d+/)){n.push(e);continue}if(e.match(/:\d+:\d+\s+warning\b/i)||e.match(/^warning\s+TS\d+/)){r.push(e);continue}if(e.match(/:\d+:\d+\s+(info|hint)\b/i)){i++;continue}if(e.match(/Found \d+|✖\s+\d+|errors?\s+and\s+\d+\s+warning|problems?.*error/i)){n.push(e);continue}e.match(/^\s*\d+ error/)&&n.push(e)}let a=[];return n.length>0&&(a.push(`=== ERRORS (${n.length}) ===`),a.push(...n.slice(0,30)),n.length>30&&a.push(`[${n.length-30} more errors]`)),r.length>0&&(a.push(`=== WARNINGS (${r.length}) ===`),a.push(...r.slice(0,10)),r.length>10&&a.push(`[${r.length-10} more warnings]`)),i>0&&a.push(`[${i} info/hint messages]`),a.length===0&&a.push(`[No errors or warnings found]`),a.join(`
10
- `)}},{name:`docker`,toolPatterns:[`docker`],priority:8,match(e){return e.tool===`docker`},compress(e){let t=e.text.split(`
11
- `),n=[],r=0,i=0;for(let e of t){if(e.match(/^(ERROR|error|Error|WARNING|SECURITY)/i)||e.includes(`failed`)){n.push(e);continue}if(e.match(/^Step \d+\/\d+\s*:/)){n.push(e);continue}if(e.match(/^\s*(FROM|RUN|COPY|ADD|WORKDIR|ENV|EXPOSE|CMD|ENTRYPOINT)\s/i)){n.push(e);continue}if(e.includes(`CACHED`)||e.includes(`Using cache`)){r++;continue}if(e.match(/^[a-f0-9]+:\s*(Pull|Download|Extract|Waiting|Verifying)/)){i++;continue}if(e.match(/^(Successfully|sha256:|REPOSITORY|IMAGE ID|CONTAINER ID)/)){n.push(e);continue}if(e.match(/^\S{12}\s+\S+/)&&!e.match(/^[a-f0-9]+:/)){n.push(e);continue}e.match(/^#\d+\s/)&&n.push(e)}return r>0&&n.push(`[${r} cached layers]`),i>0&&n.push(`[${i} download/extract operations]`),n.join(`
12
- `)}},{name:`kubectl`,toolPatterns:[`kubectl`,`k8s`],priority:8,match(e){return e.tool===`kubectl`},compress(e){let t=e.text.split(`
13
- `),n=[],r=0;for(let e of t){if(e.match(/^(NAME|NAMESPACE|LAST SEEN|TYPE)\s+/)){n.push(e);continue}if(e.match(/\b(Warning|Error|Failed|CrashLoopBackOff|OOMKilled|Evicted|Pending)\b/i)){n.push(e);continue}if(e.match(/^\S+\s+\d+\/\d+\s+(Running|Error|CrashLoop|Pending|Completed|Terminating)/)){n.push(e);continue}if(e.match(/^\d+[smhd]\s+.*Normal\s/)){r++;continue}e.match(/^\S+\s+/)&&e.trim().length>0&&n.push(e)}return r>0&&n.push(`[${r} normal events]`),n.join(`
14
- `)}},{name:`generic`,toolPatterns:[/.*/],priority:0,match(e){return e.tool===`unknown`||!e.tool},compress(e){let t=e.text.split(`
15
- `),n=[],r=``,i=0,a=0;for(let e of t){let t=e.trim();if(t===``){a++,a<=1&&n.push(``);continue}if(a=0,t===r.trim()){i++;continue}i>0&&(n.push(` [repeated ${i} more times]`),i=0),r=e,n.push(e)}return i>0&&n.push(` [repeated ${i} more times]`),n.join(`
16
- `)}}]),new Set([`.git`,E.data,E.state,`.turbo`,`.yarn`,`build`,`coverage`,`dist`,`node_modules`]),S(s),new Set(`if_statement.for_statement.for_in_statement.while_statement.do_statement.switch_case.catch_clause.ternary_expression.if_statement.for_statement.while_statement.except_clause.list_comprehension.if_statement.for_statement.enhanced_for_statement.while_statement.catch_clause.ternary_expression.if_statement.for_statement.select_statement.if_expression.for_expression.while_expression.match_arm`.split(`.`));function Z(){return x(j(process.cwd()),`replay.jsonl`)}function fe(e={}){let t=Z(),n;try{n=p(t,`utf-8`)}catch{return[]}let r=n.trim().split(`
17
- `).filter(Boolean),i=[];for(let e of r)try{i.push(JSON.parse(e))}catch{}if(e.tool&&(i=i.filter(t=>t.tool===e.tool)),e.source&&(i=i.filter(t=>t.source===e.source)),e.since){let t=e.since;i=i.filter(e=>e.ts>=t)}let a=e.last??20;return i.slice(-a)}S(o),E.data,`script,style,noscript,iframe,svg,nav,footer,header,aside,form,button,input,select,textarea,[role="navigation"],[role="banner"],[role="contentinfo"],[aria-hidden="true"],.sidebar,.nav,.menu,.footer,.header,.ad,.advertisement,.cookie-banner,.popup,.modal`.split(`,`);var Q=e(t()),$=i();function pe(){let[e,t]=(0,Q.useState)([]);return(0,Q.useEffect)(()=>{let e=()=>{t(fe({last:30}))};e();let n=setInterval(e,2e3);return()=>clearInterval(n)},[]),(0,$.jsxs)(n,{flexDirection:`column`,borderStyle:`round`,paddingX:1,children:[(0,$.jsx)(r,{bold:!0,color:`cyan`,children:`Activity Log`}),(0,$.jsx)(r,{children:` `}),e.length===0&&(0,$.jsx)(r,{color:`gray`,children:`No activity recorded yet`}),e.slice().reverse().map((e,t)=>{let n=e.ts.split(`T`)[1]?.split(`.`)[0]??e.ts,i=e.status===`ok`?`green`:`red`;return(0,$.jsxs)(r,{children:[(0,$.jsx)(r,{color:`gray`,children:n}),` `,(0,$.jsx)(r,{color:i,children:e.status===`ok`?`✓`:`✗`}),` `,(0,$.jsx)(r,{bold:!0,children:e.tool}),` `,(0,$.jsxs)(r,{color:`gray`,children:[`(`,e.durationMs,`ms)`]})]},`${e.ts}-${t}`)}),(0,$.jsx)(r,{children:` `}),(0,$.jsx)(r,{color:`gray`,children:`Refreshes every 2s │ Showing last 30`})]})}export{pe as t};
@@ -1,2 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{createRequire as e}from"node:module";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=e(import.meta.url);export{u as n,l as r,s as t};
@@ -1,7 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import{n as e,r as t,t as n}from"./chunk-D6axbAb-.js";import r from"react-devtools-core";var i=n(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),a=n(((t,n)=>{let{EMPTY_BUFFER:r}=i(),a=Buffer[Symbol.species];function o(e,t){if(e.length===0)return r;if(e.length===1)return e[0];let n=Buffer.allocUnsafe(t),i=0;for(let t=0;t<e.length;t++){let r=e[t];n.set(r,i),i+=r.length}return i<t?new a(n.buffer,n.byteOffset,i):n}function s(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function c(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function l(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function u(e){if(u.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new a(e):ArrayBuffer.isView(e)?t=new a(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),u.readOnly=!1),t}if(n.exports={concat:o,mask:s,toArrayBuffer:l,toBuffer:u,unmask:c},!process.env.WS_NO_BUFFER_UTIL)try{let t=e(`bufferutil`);n.exports.mask=function(e,n,r,i,a){a<48?s(e,n,r,i,a):t.mask(e,n,r,i,a)},n.exports.unmask=function(e,n){e.length<32?c(e,n):t.unmask(e,n)}}catch{}})),o=n(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),s=n(((t,n)=>{let r=e(`zlib`),s=a(),c=o(),{kStatusCode:l}=i(),u=Buffer[Symbol.species],d=Buffer.from([0,0,255,255]),f=Symbol(`permessage-deflate`),p=Symbol(`total-length`),m=Symbol(`callback`),h=Symbol(`buffers`),g=Symbol(`error`),_;n.exports=class{constructor(e){this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,_||=new c(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[m];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){_.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){_.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,n){let i=this._isServer?`client`:`server`;if(!this._inflate){let e=`${i}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._inflate=r.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[f]=this,this._inflate[p]=0,this._inflate[h]=[],this._inflate.on(`error`,b),this._inflate.on(`data`,y)}this._inflate[m]=n,this._inflate.write(e),t&&this._inflate.write(d),this._inflate.flush(()=>{let e=this._inflate[g];if(e){this._inflate.close(),this._inflate=null,n(e);return}let r=s.concat(this._inflate[h],this._inflate[p]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[p]=0,this._inflate[h]=[],t&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,r)})}_compress(e,t,n){let i=this._isServer?`server`:`client`;if(!this._deflate){let e=`${i}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:r.Z_DEFAULT_WINDOWBITS;this._deflate=r.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[p]=0,this._deflate[h]=[],this._deflate.on(`data`,v)}this._deflate[m]=n,this._deflate.write(e),this._deflate.flush(r.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=s.concat(this._deflate[h],this._deflate[p]);t&&(e=new u(e.buffer,e.byteOffset,e.length-4)),this._deflate[m]=null,this._deflate[p]=0,this._deflate[h]=[],t&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,e)})}};function v(e){this[h].push(e),this[p]+=e.length}function y(e){if(this[p]+=e.length,this[f]._maxPayload<1||this[p]<=this[f]._maxPayload){this[h].push(e);return}this[g]=RangeError(`Max payload size exceeded`),this[g].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[g][l]=1009,this.removeListener(`data`,y),this.reset()}function b(e){if(this[f]._inflate=null,this[g]){this[m](this[g]);return}e[l]=1007,this[m](e)}})),c=n(((t,n)=>{let{isUtf8:r}=e(`buffer`),{hasBlob:a}=i(),o=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function s(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function c(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function l(e){return a&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(n.exports={isBlob:l,isValidStatusCode:s,isValidUTF8:c,tokenChars:o},r)n.exports.isValidUTF8=function(e){return e.length<24?c(e):r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=e(`utf-8-validate`);n.exports.isValidUTF8=function(e){return e.length<32?c(e):t(e)}}catch{}})),l=n(((t,n)=>{let{Writable:r}=e(`stream`),o=s(),{BINARY_TYPES:l,EMPTY_BUFFER:u,kStatusCode:d,kWebSocket:f}=i(),{concat:p,toArrayBuffer:m,unmask:h}=a(),{isValidStatusCode:g,isValidUTF8:_}=c(),v=Buffer[Symbol.species];n.exports=class extends r{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||l[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[f]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new v(t.buffer,t.byteOffset+e,t.length-e),new v(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new v(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[o.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=u;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&h(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[o.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?p(n,t):this._binaryType===`arraybuffer`?m(p(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=p(n,t);if(!this._skipUTF8Validation&&!_(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,u),this.end();else{let n=e.readUInt16BE(0);if(!g(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new v(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!_(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[d]=r,a}}})),u=n(((t,n)=>{let{Duplex:r}=e(`stream`),{randomFillSync:o}=e(`crypto`),l=s(),{EMPTY_BUFFER:u,kWebSocket:d,NOOP:f}=i(),{isBlob:p,isValidStatusCode:m}=c(),{mask:h,toBuffer:g}=a(),_=Symbol(`kByteLength`),v=Buffer.alloc(4),y=8*1024,b,x=y;n.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=f,this[d]=void 0}static frame(e,t){let n,r=!1,i=2,a=!1;t.mask&&(n=t.maskBuffer||v,t.generateMask?t.generateMask(n):(x===y&&(b===void 0&&(b=Buffer.alloc(y)),o(b,0,y),x=0),n[0]=b[x++],n[1]=b[x++],n[2]=b[x++],n[3]=b[x++]),a=(n[0]|n[1]|n[2]|n[3])===0,i=6);let s;typeof e==`string`?(!t.mask||a)&&t[_]!==void 0?s=t[_]:(e=Buffer.from(e),s=e.length):(s=e.length,r=t.mask&&t.readOnly&&!a);let c=s;s>=65536?(i+=8,c=127):s>125&&(i+=2,c=126);let l=Buffer.allocUnsafe(r?s+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[i-4]=n[0],l[i-3]=n[1],l[i-2]=n[2],l[i-1]=n[3],a)?[l,e]:r?(h(e,n,l,i,s),[l]):(h(e,n,e,0,s),[l,e])}close(t,n,r,i){let a;if(t===void 0)a=u;else if(typeof t!=`number`||!m(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)a=Buffer.allocUnsafe(2),a.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);a=Buffer.allocUnsafe(2+e),a.writeUInt16BE(t,0),typeof n==`string`?a.write(n,2):a.set(n,2)}let o={[_]:a.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(a,o),i):this.enqueue([this.dispatch,a,!1,o,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):p(t)?(i=t.size,a=!1):(t=g(t),i=t.length,a=g.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[_]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};p(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):p(t)?(i=t.size,a=!1):(t=g(t),i=t.length,a=g.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[_]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};p(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[l.extensionName],i=t.binary?2:1,a=t.compress,o,s;typeof e==`string`?(o=Buffer.byteLength(e),s=!1):p(e)?(o=e.size,s=!1):(e=g(e),o=e.length,s=g.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(a=o>=r._threshold),this._compress=a):(a=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[_]:o,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:s,rsv1:a};p(e)?this._state===0?this.getBlobData(e,this._compress,c,n):this.enqueue([this.getBlobData,e,this._compress,c,n]):this._state===0?this.dispatch(e,this._compress,c,n):this.enqueue([this.dispatch,e,this._compress,c,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[_],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(S,this,e,i);return}this._bufferedBytes-=r[_];let a=g(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(C,this,e,i)})}dispatch(t,n,r,i){if(!n){this.sendFrame(e.frame(t,r),i);return}let a=this._extensions[l.extensionName];this._bufferedBytes+=r[_],this._state=1,a.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){S(this,Error(`The socket was closed while data was being compressed`),i);return}this._bufferedBytes-=r[_],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function S(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function C(e,t,n){S(e,t,n),e.onerror(t)}})),d=n(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=i(),a=Symbol(`kCode`),o=Symbol(`kData`),s=Symbol(`kError`),c=Symbol(`kMessage`),l=Symbol(`kReason`),u=Symbol(`kTarget`),d=Symbol(`kType`),f=Symbol(`kWasClean`);var p=class{constructor(e){this[u]=null,this[d]=e}get target(){return this[u]}get type(){return this[d]}};Object.defineProperty(p.prototype,`target`,{enumerable:!0}),Object.defineProperty(p.prototype,`type`,{enumerable:!0});var m=class extends p{constructor(e,t={}){super(e),this[a]=t.code===void 0?0:t.code,this[l]=t.reason===void 0?``:t.reason,this[f]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[a]}get reason(){return this[l]}get wasClean(){return this[f]}};Object.defineProperty(m.prototype,`code`,{enumerable:!0}),Object.defineProperty(m.prototype,`reason`,{enumerable:!0}),Object.defineProperty(m.prototype,`wasClean`,{enumerable:!0});var h=class extends p{constructor(e,t={}){super(e),this[s]=t.error===void 0?null:t.error,this[c]=t.message===void 0?``:t.message}get error(){return this[s]}get message(){return this[c]}};Object.defineProperty(h.prototype,`error`,{enumerable:!0}),Object.defineProperty(h.prototype,`message`,{enumerable:!0});var g=class extends p{constructor(e,t={}){super(e),this[o]=t.data===void 0?null:t.data}get data(){return this[o]}};Object.defineProperty(g.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:m,ErrorEvent:h,Event:p,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new g(`message`,{data:n?e:e.toString()});r[u]=this,_(t,this,r)};else if(e===`close`)a=function(e,n){let r=new m(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[u]=this,_(t,this,r)};else if(e===`error`)a=function(e){let n=new h(`error`,{error:e,message:e.message});n[u]=this,_(t,this,n)};else if(e===`open`)a=function(){let e=new p(`open`);e[u]=this,_(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:g};function _(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),f=n(((e,t)=>{let{tokenChars:n}=c();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),p=n(((t,n)=>{let r=e(`events`),o=e(`https`),p=e(`http`),m=e(`net`),h=e(`tls`),{randomBytes:g,createHash:_}=e(`crypto`),{Duplex:v,Readable:y}=e(`stream`),{URL:b}=e(`url`),x=s(),S=l(),C=u(),{isBlob:w}=c(),{BINARY_TYPES:T,CLOSE_TIMEOUT:E,EMPTY_BUFFER:D,GUID:O,kForOnEventAttribute:k,kListener:A,kStatusCode:j,kWebSocket:M,NOOP:N}=i(),{EventTarget:{addEventListener:ee,removeEventListener:te}}=d(),{format:P,parse:F}=f(),{toBuffer:I}=a(),L=Symbol(`kAborted`),R=[8,13],z=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],B=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var V=class e extends r{constructor(t,n,r){super(),this._binaryType=T[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=D,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),H(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){T.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new S({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new C(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[M]=this,a[M]=this,t[M]=this,i.on(`conclude`,re),i.on(`drain`,ie),i.on(`error`,ae),i.on(`message`,oe),i.on(`ping`,se),i.on(`pong`,ce),a.onerror=le,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,X),t.on(`data`,Z),t.on(`end`,Q),t.on(`error`,$),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[x.extensionName]&&this._extensions[x.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){G(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){K(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||D,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){K(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||D,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){K(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[x.extensionName]||(i.compress=!1),this._sender.send(t||D,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){G(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(V,`CONNECTING`,{enumerable:!0,value:z.indexOf(`CONNECTING`)}),Object.defineProperty(V.prototype,`CONNECTING`,{enumerable:!0,value:z.indexOf(`CONNECTING`)}),Object.defineProperty(V,`OPEN`,{enumerable:!0,value:z.indexOf(`OPEN`)}),Object.defineProperty(V.prototype,`OPEN`,{enumerable:!0,value:z.indexOf(`OPEN`)}),Object.defineProperty(V,`CLOSING`,{enumerable:!0,value:z.indexOf(`CLOSING`)}),Object.defineProperty(V.prototype,`CLOSING`,{enumerable:!0,value:z.indexOf(`CLOSING`)}),Object.defineProperty(V,`CLOSED`,{enumerable:!0,value:z.indexOf(`CLOSED`)}),Object.defineProperty(V.prototype,`CLOSED`,{enumerable:!0,value:z.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(V.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(V.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[k])return t[A];return null},set(t){for(let t of this.listeners(e))if(t[k]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[k]:!0})}})}),V.prototype.addEventListener=ee,V.prototype.removeEventListener=te,n.exports=V;function H(e,t,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:E,protocolVersion:R[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,e._closeTimeout=i.closeTimeout,!R.includes(i.protocolVersion))throw RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${R.join(`, `)})`);let a;if(t instanceof b)a=t;else try{a=new b(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}a.protocol===`http:`?a.protocol=`ws:`:a.protocol===`https:`&&(a.protocol=`wss:`),e._url=a.href;let s=a.protocol===`wss:`,c=a.protocol===`ws+unix:`,l;if(a.protocol!==`ws:`&&!s&&!c?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!a.pathname?l=`The URL's pathname is empty`:a.hash&&(l=`The URL contains a fragment identifier`),l){let t=SyntaxError(l);if(e._redirects===0)throw t;U(e,t);return}let u=s?443:80,d=g(16).toString(`base64`),f=s?o.request:p.request,m=new Set,h;if(i.createConnection=i.createConnection||(s?ne:W),i.defaultPort=i.defaultPort||u,i.port=a.port||u,i.host=a.hostname.startsWith(`[`)?a.hostname.slice(1,-1):a.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:`Upgrade`,Upgrade:`websocket`},i.path=a.pathname+a.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new x({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers[`Sec-WebSocket-Extensions`]=P({[x.extensionName]:h.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!B.test(e)||m.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);m.add(e)}i.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(i.origin&&(i.protocolVersion<13?i.headers[`Sec-WebSocket-Origin`]=i.origin:i.headers.Origin=i.origin),(a.username||a.password)&&(i.auth=`${a.username}:${a.password}`),c){let e=i.path.split(`:`);i.socketPath=e[0],i.path=e[1]}let v;if(i.followRedirects){if(e._redirects===0){e._originalIpc=c,e._originalSecure=s,e._originalHostOrSocketPath=c?i.socketPath:a.host;let t=r&&r.headers;if(r={...r,headers:{}},t)for(let[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=c?e._originalIpc?i.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:a.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization=`Basic `+Buffer.from(i.auth).toString(`base64`)),v=e._req=f(i),e._redirects&&e.emit(`redirect`,e.url,v)}else v=e._req=f(i);i.timeout&&v.on(`timeout`,()=>{G(e,v,`Opening handshake has timed out`)}),v.on(`error`,t=>{v===null||v[L]||(v=e._req=null,U(e,t))}),v.on(`response`,a=>{let o=a.headers.location,s=a.statusCode;if(o&&i.followRedirects&&s>=300&&s<400){if(++e._redirects>i.maxRedirects){G(e,v,`Maximum redirects exceeded`);return}v.abort();let a;try{a=new b(o,t)}catch{U(e,SyntaxError(`Invalid URL: ${o}`));return}H(e,a,n,r)}else e.emit(`unexpected-response`,v,a)||G(e,v,`Unexpected server response: ${a.statusCode}`)}),v.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==V.CONNECTING)return;v=e._req=null;let a=t.headers.upgrade;if(a===void 0||a.toLowerCase()!==`websocket`){G(e,n,`Invalid Upgrade header`);return}let o=_(`sha1`).update(d+O).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==o){G(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],c;if(s===void 0?m.size&&(c=`Server sent no subprotocol`):m.size?m.has(s)||(c=`Server sent an invalid subprotocol`):c=`Server sent a subprotocol but none was requested`,c){G(e,n,c);return}s&&(e._protocol=s);let l=t.headers[`sec-websocket-extensions`];if(l!==void 0){if(!h){G(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=F(l)}catch{G(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==x.extensionName){G(e,n,`Server indicated an extension that was not requested`);return}try{h.accept(t[x.extensionName])}catch{G(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[x.extensionName]=h}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(v,e):v.end()}function U(e,t){e._readyState=V.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function W(e){return e.path=e.socketPath,m.connect(e)}function ne(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=m.isIP(e.host)?``:e.host),h.connect(e)}function G(e,t,n){e._readyState=V.CLOSING;let r=Error(n);Error.captureStackTrace(r,G),t.setHeader?(t[L]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(U,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function K(e,t,n){if(t){let n=w(t)?t.size:I(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${z[e.readyState]})`);process.nextTick(n,t)}}function re(e,t){let n=this[M];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[M]!==void 0&&(n._socket.removeListener(`data`,Z),process.nextTick(J,n._socket),e===1005?n.close():n.close(e,t))}function ie(){let e=this[M];e.isPaused||e._socket.resume()}function ae(e){let t=this[M];t._socket[M]!==void 0&&(t._socket.removeListener(`data`,Z),process.nextTick(J,t._socket),t.close(e[j])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function q(){this[M].emitClose()}function oe(e,t){this[M].emit(`message`,e,t)}function se(e){let t=this[M];t._autoPong&&t.pong(e,!this._isServer,N),t.emit(`ping`,e)}function ce(e){this[M].emit(`pong`,e)}function J(e){e.resume()}function le(e){let t=this[M];t.readyState!==V.CLOSED&&(t.readyState===V.OPEN&&(t._readyState=V.CLOSING,Y(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function Y(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function X(){let e=this[M];if(this.removeListener(`close`,X),this.removeListener(`data`,Z),this.removeListener(`end`,Q),e._readyState=V.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[M]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,q),e._receiver.on(`finish`,q))}function Z(e){this[M]._receiver.write(e)||this.pause()}function Q(){let e=this[M];e._readyState=V.CLOSING,e._receiver.end(),this.end()}function $(){let e=this[M];this.removeListener(`error`,$),this.on(`error`,N),e&&(e._readyState=V.CLOSING,this.destroy())}})),m=n(((t,n)=>{p();let{Duplex:r}=e(`stream`);function i(e){e.emit(`close`)}function a(){!this.destroyed&&this._writableState.finished&&this.destroy()}function o(e){this.removeListener(`error`,o),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function s(e,t){let n=!0,s=new r({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(n=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,r){if(e.readyState===e.CLOSED){r(t),process.nextTick(i,s);return}let a=!1;e.once(`error`,function(e){a=!0,r(e)}),e.once(`close`,function(){a||r(t),process.nextTick(i,s)}),n&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,a),s.on(`error`,o),s}n.exports=s})),h=n(((e,t)=>{let{tokenChars:n}=c();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),g=n(((t,n)=>{let r=e(`events`),a=e(`http`),{Duplex:o}=e(`stream`),{createHash:c}=e(`crypto`),l=f(),u=s(),d=h(),m=p(),{CLOSE_TIMEOUT:g,GUID:_,kWebSocket:v}=i(),y=/^[+/0-9A-Za-z]{22}==$/;n.exports=class extends r{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:g,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:m,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=a.createServer((e,t)=>{let n=a.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=b(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(x,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(x,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{x(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,S);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,o=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){w(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){w(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!y.test(i)){w(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(o!==13&&o!==8){w(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){C(t,400);return}let s=e.headers[`sec-websocket-protocol`],c=new Set;if(s!==void 0)try{c=d.parse(s)}catch{w(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],p={};if(this.options.perMessageDeflate&&f!==void 0){let n=new u({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let e=l.parse(f);e[u.extensionName]&&(n.accept(e[u.extensionName]),p[u.extensionName]=n)}catch{w(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${o===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,l)=>{if(!a)return C(t,o||401,s,l);this.completeUpgrade(p,i,c,e,t,n,r)});return}if(!this.options.verifyClient(a))return C(t,401)}this.completeUpgrade(p,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,a,o){if(!i.readable||!i.writable)return i.destroy();if(i[v])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return C(i,503);let s=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${c(`sha1`).update(t+_).digest(`base64`)}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(s.push(`Sec-WebSocket-Protocol: ${e}`),d._protocol=e)}if(e[u.extensionName]){let t=e[u.extensionName].params,n=l.format({[u.extensionName]:[t]});s.push(`Sec-WebSocket-Extensions: ${n}`),d._extensions=e}this.emit(`headers`,s,r),i.write(s.concat(`\r
3
- `).join(`\r
4
- `)),i.removeListener(`error`,S),d.setSocket(i,a,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on(`close`,()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(x,this)})),o(d,r)}};function b(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function x(e){e._state=2,e.emit(`close`)}function S(){this.destroy()}function C(e,t,n,r){n||=a.STATUS_CODES[t],r={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...r},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${a.STATUS_CODES[t]}\r\n`+Object.keys(r).map(e=>`${e}: ${r[e]}`).join(`\r
5
- `)+`\r
6
- \r
7
- `+n)}function w(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,w),e.emit(`wsClientError`,r,n,t)}else C(n,r,i,a)}}));m(),f(),s(),l(),u(),h();var _=t(p(),1);g();var v=_.default;const y=global;y.WebSocket||=v,y.window||=global,y.self||=global,y.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:`InternalApp`,isEnabled:!0,isValid:!0},{type:2,value:`InternalAppContext`,isEnabled:!0,isValid:!0},{type:2,value:`InternalStdoutContext`,isEnabled:!0,isValid:!0},{type:2,value:`InternalStderrContext`,isEnabled:!0,isValid:!0},{type:2,value:`InternalStdinContext`,isEnabled:!0,isValid:!0},{type:2,value:`InternalFocusContext`,isEnabled:!0,isValid:!0}],r.initialize(),r.connectToDevTools();export{};