Author SHA1 Message Date
Renovate 064a0f6dd1 chore(deps): update dependency @actions/core to v2.0.2
Lint / pre-commit Linting (push) Failing after 17m9s
Test / Run Tests (push) Failing after 20m58s
2026-01-15 23:43:13 +00:00
22 changed files with 2448 additions and 2945 deletions

No files matched your search

-6
View File
@@ -1,6 +0,0 @@
# .gitea/CODEOWNERS
# Gitea's CODEOWNERS uses Go-style Regular Expressions.
# Patterns are evaluated from top to bottom; the last matching rule takes precedence.
# Global owner: Assign @AutoReview to all files
.* @AutoReview
+18
View File
@@ -0,0 +1,18 @@
name: Lint
on:
push:
workflow_dispatch:
jobs:
pre-commit-lint:
name: pre-commit Linting
runs-on: pi
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
- run: pip install pre-commit
shell: bash
- name: Pre Commit
run: SKIP=no-commit-to-branch pre-commit run -a
shell: bash
-55
View File
@@ -1,55 +0,0 @@
name: Recompile dist/ on Renovate PR
on:
pull_request:
types: [opened, synchronize]
paths:
- package.json
- pnpm-lock.yaml
- index.js
- monitor.js
permissions:
contents: write
jobs:
recompile:
runs-on: pi
if: |
(github.actor == 'renovate[bot]' || contains(github.head_ref, 'renovate/')) &&
!contains(github.event.head_commit.message, '[skip compile]')
steps:
- name: Checkout PR Branch
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
ref: ${{ github.head_ref }}
fetch-depth: 0
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: '22'
cache: pnpm
- name: Clean Install
run: pnpm install --frozen-lockfile --ignore-scripts
shell: bash
- name: Build
run: pnpm run build
shell: bash
- name: Commit dist/
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add dist/
if git diff --staged --quiet; then
echo "No changes to dist/"
else
git commit -m "chore: compile action bundle [skip compile]"
git push origin HEAD:${{ github.head_ref }}
fi
shell: bash
+5 -8
View File
@@ -2,7 +2,6 @@ name: Test
on: on:
push: push:
pull_request:
workflow_dispatch: workflow_dispatch:
jobs: jobs:
@@ -10,13 +9,11 @@ jobs:
name: Run Tests name: Run Tests
runs-on: pi runs-on: pi
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@v6
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 - uses: actions/setup-node@v6
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with: with:
node-version: '22' node-version: '24'
cache: pnpm - run: npm install
- run: pnpm install --frozen-lockfile
shell: bash shell: bash
- run: pnpm test - run: npm test
shell: bash shell: bash
-3
View File
@@ -1078,6 +1078,3 @@ FodyWeavers.xsd
/node_modules/.cache/ /node_modules/.cache/
/coverage/ /coverage/
!/dist/ !/dist/
# Local test credentials — never commit
.env.test
+2 -4
View File
@@ -17,11 +17,10 @@ repos:
- id: no-commit-to-branch - id: no-commit-to-branch
- repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks
rev: v2.16.0 rev: v2.15.0
hooks: hooks:
- id: pretty-format-yaml - id: pretty-format-yaml
args: [--autofix] args: [--autofix]
exclude: ^pnpm-lock\.yaml$
- repo: https://github.com/pre-commit/mirrors-prettier - repo: https://github.com/pre-commit/mirrors-prettier
rev: v4.0.0-alpha.8 rev: v4.0.0-alpha.8
@@ -30,11 +29,10 @@ repos:
types_or: [css, javascript] types_or: [css, javascript]
- repo: https://github.com/python-jsonschema/check-jsonschema - repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.38.0 rev: 0.36.0
hooks: hooks:
- id: check-renovate - id: check-renovate
- id: check-github-actions - id: check-github-actions
exclude: ^action\.yaml$
- id: check-github-workflows - id: check-github-workflows
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
+4 -11
View File
@@ -6,8 +6,6 @@ This repository is maintained by Gemini.
* **Test-Driven Development (TDD):** Wherever possible, Test-Driven Development principles should be followed. Write tests before writing the code they are intended to validate. * **Test-Driven Development (TDD):** Wherever possible, Test-Driven Development principles should be followed. Write tests before writing the code they are intended to validate.
* **Pre-commit Hooks:** Ensure that `pre-commit` hooks are installed and active before making any commits. This can be done by running `pre-commit install` in your local repository. * **Pre-commit Hooks:** Ensure that `pre-commit` hooks are installed and active before making any commits. This can be done by running `pre-commit install` in your local repository.
* **Note for Gemini:** Git commits trigger pre-commit hooks, which can take several seconds (or minutes) to complete. Checking the command status for git commit is only appropriate every 120s.
* **Package Manager Preferences:** Always use `pnpm` and `pnpx`. Never use `npm` or `npx` under any circumstances. All package management operations, script runs, and tool invocations must use `pnpm` / `pnpx`.
## Repository Comparison ## Repository Comparison
@@ -20,7 +18,7 @@ This project uses [Vitest](https://vitest.dev/) for testing. The tests are locat
To run the tests locally, use the following command: To run the tests locally, use the following command:
```bash ```bash
pnpm test npm test
``` ```
### Testing Pipeline ### Testing Pipeline
@@ -30,11 +28,6 @@ The tests are automatically run on every push and workflow dispatch using a Gite
The Gitea workflow does the following: The Gitea workflow does the following:
1. Checks out the code. 1. Checks out the code.
2. Sets up Node.js and pnpm. 2. Sets up Node.js.
3. Installs the dependencies using `pnpm install`. 3. Installs the dependencies using `npm install`.
4. Runs the tests using `pnpm test`. 4. Runs the tests using `npm test`.
### Automated Recompilation & Permissions
* The automated recompilation workflow (`.gitea/workflows/recompile-dist.yaml`) recompiles `dist/index.js` on Renovate PRs and requires `contents: write` permissions to push back to the branch.
* Ensure that the Gitea repository workflow settings have write permissions enabled (**Settings** ➔ **Actions** ➔ **General** ➔ **Workflow permissions** ➔ **Read and write permissions**).
+3 -16
View File
@@ -26,19 +26,6 @@ To use this action, you need to set it up in your workflow .yml file located in
- `pattern`: Glob pattern to match files (default: *.js). - `pattern`: Glob pattern to match files (default: *.js).
- `branch`: Branch in Screeps to which the code will be uploaded (default: default). - `branch`: Branch in Screeps to which the code will be uploaded (default: default).
- `git-replace`: Overwrite "{{gitRef}}", "{{gitHash}}" and "{{deployTime}}" values in files matching the pattern. - `git-replace`: Overwrite "{{gitRef}}", "{{gitHash}}" and "{{deployTime}}" values in files matching the pattern.
- `shard`: The Screeps shard to monitor (e.g. `shard0`, `shard1`). Defaults to `shard0` on the official server.
- `monitor`: Number of game ticks to monitor the Screeps console after deploying (0 = disabled, default: 0).
- `log_to_file`: If `true`, buffers stdout to an artifact file instead of streaming live (default: false). Note: Errors and warnings always stream live.
- `on_traceback`: Action on JS traceback detection: `ignore`, `warn`, or `fail` (default: `fail`).
- `on_error_log`: Action on Screeps error-console output: `ignore`, `warn`, or `fail` (default: `warn`).
- `on_warning_log`: Action on `console.warn` output: `ignore`, `warn`, or `fail` (default: `ignore`).
- `monitor_interval`: Print a progress update every N ticks (default: 10).
## Outputs
- `saw_traceback`: `true` if a JS traceback was detected during monitoring.
- `saw_error_log`: `true` if the Screeps error console had output during monitoring.
- `saw_warning_log`: `true` if `console.warn` output was detected during monitoring.
Example Workflow Example Workflow
@@ -84,7 +71,7 @@ This project includes a build step to prepare the action for use.
### Why a Build Step? ### Why a Build Step?
We use a build step to compile the JavaScript code and its dependencies into a single, self-contained file (`dist/index.js`). This approach is chosen for the following reasons: We use a build step to compile the JavaScript code and its dependencies into a single, self-contained file (`dist/index.js`). This approach is chosen for the following reasons:
1. **Zero-configuration at Runtime:** By bundling everything, the action runner doesn't need to run `pnpm install` or `npm install`, which speeds up the action execution. 1. **Zero-configuration at Runtime:** By bundling everything, the action runner doesn't need to run `npm install`, which speeds up the action execution.
2. **Reliability:** It guarantees that the exact versions of dependencies tested during development are used in the action, avoiding potential issues with version updates or missing packages. 2. **Reliability:** It guarantees that the exact versions of dependencies tested during development are used in the action, avoiding potential issues with version updates or missing packages.
3. **Standard Practice:** This is a recommended practice for JavaScript-based GitHub/Gitea Actions. 3. **Standard Practice:** This is a recommended practice for JavaScript-based GitHub/Gitea Actions.
@@ -100,8 +87,8 @@ We chose [`@vercel/ncc`](https://github.com/vercel/ncc) as the compiler because:
If you modify `index.js` or change dependencies, you must rebuild the project before committing: If you modify `index.js` or change dependencies, you must rebuild the project before committing:
```bash ```bash
pnpm install npm install
pnpm run build npm run build
``` ```
This will update the `dist/index.js` file, which should be committed to the repository. This will update the `dist/index.js` file, which should be committed to the repository.
+6 -165
View File
@@ -1,65 +1,13 @@
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"; const {
// Mock @actions/core for all tests in this file
vi.mock("@actions/core", () => ({
getInput: vi.fn(),
getBooleanInput: vi.fn(),
info: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
setFailed: vi.fn(),
setOutput: vi.fn(),
}));
// Mock monitor.js so postCode() integration tests don't open a real socket
vi.mock("../monitor.js", () => ({
monitorConsole: vi.fn().mockResolvedValue({
sawTraceback: false,
sawErrorLog: false,
sawWarningLog: false,
}),
}));
// Mock screeps-api
vi.mock("screeps-api", () => {
const mockApi = {
auth: vi.fn().mockResolvedValue(),
authSignin: vi.fn().mockResolvedValue({ ok: 1, token: "test_token" }),
userCodeGet: vi
.fn()
.mockResolvedValue({ ok: 1, modules: { main: "old_code" } }),
userCodeSet: vi.fn().mockResolvedValue({ ok: 1 }),
code: {
get: vi.fn().mockResolvedValue({ ok: 1, modules: { main: "old_code" } }),
set: vi.fn().mockResolvedValue({ ok: 1 }),
},
};
// Use a regular function so it can be called with `new`
const MockClient = vi.fn(function () {
return mockApi;
});
return {
ScreepsHttpClient: MockClient,
ScreepsAPI: MockClient,
};
});
import * as core from "@actions/core";
import { monitorConsole } from "../monitor.js";
import {
validateAuthentication, validateAuthentication,
replacePlaceholders, replacePlaceholders,
readReplaceAndWriteFiles, readReplaceAndWriteFiles,
readFilesIntoDict, readFilesIntoDict,
applyOnAction, } = require("../index");
postCode, const fs = require("fs");
} from "../index.js"; const path = require("path");
import { ScreepsHttpClient } from "screeps-api"; const os = require("os");
import fs from "fs"; const { glob } = require("glob");
import path from "path";
import os from "os";
import { glob } from "glob";
describe("validateAuthentication", () => { describe("validateAuthentication", () => {
it("should return null when only token is provided", () => { it("should return null when only token is provided", () => {
@@ -249,110 +197,3 @@ describe("glob functionality", () => {
expect(normalizedFiles.sort()).toEqual(expectedFiles); expect(normalizedFiles.sort()).toEqual(expectedFiles);
}); });
}); });
// ────────────────────────────────────────────────────────────────────────────
// applyOnAction
// ────────────────────────────────────────────────────────────────────────────
describe("applyOnAction", () => {
beforeEach(() => vi.clearAllMocks());
it("'ignore' + true → no core call, returns false", () => {
expect(applyOnAction("ignore", true, "msg")).toBe(false);
expect(core.warning).not.toHaveBeenCalled();
expect(core.setFailed).not.toHaveBeenCalled();
});
it("'warn' + true → core.warning() called with message, returns false", () => {
expect(applyOnAction("warn", true, "boom")).toBe(false);
expect(core.warning).toHaveBeenCalledWith("boom");
expect(core.setFailed).not.toHaveBeenCalled();
});
it("'fail' + true → core.setFailed() called with message, returns true", () => {
expect(applyOnAction("fail", true, "boom")).toBe(true);
expect(core.setFailed).toHaveBeenCalledWith("boom");
expect(core.warning).not.toHaveBeenCalled();
});
it("'fail' + false → no core call, returns false", () => {
expect(applyOnAction("fail", false, "boom")).toBe(false);
expect(core.setFailed).not.toHaveBeenCalled();
});
it("'warn' + false → no core call, returns false", () => {
expect(applyOnAction("warn", false, "msg")).toBe(false);
expect(core.warning).not.toHaveBeenCalled();
});
});
// ────────────────────────────────────────────────────────────────────────────
// postCode — monitor wiring
// ────────────────────────────────────────────────────────────────────────────
describe("postCode — monitor wiring", () => {
beforeEach(() => {
vi.clearAllMocks();
// Default core mocks
core.getInput.mockImplementation((name) => {
if (name === "monitor") return "0";
if (name === "token") return "test-token";
if (name === "branch") return "default";
if (name === "on_traceback") return "fail";
return "";
});
core.getBooleanInput.mockImplementation((name) => {
if (name === "rollback_on_failure") return false;
return false;
});
});
it("does not call monitorConsole when monitor=0 (default)", async () => {
// We just run postCode with monitor=0 and verify monitorConsole is not called.
await postCode();
expect(monitorConsole).not.toHaveBeenCalled();
});
it("rolls back to previous code when monitor detects a failure and rollback_on_failure is true", async () => {
// Setup inputs for monitor and rollback
core.getInput.mockImplementation((name) => {
if (name === "monitor") return "10";
if (name === "token") return "test-token";
if (name === "branch") return "default";
if (name === "on_traceback") return "fail";
return "";
});
core.getBooleanInput.mockImplementation((name) => {
if (name === "rollback_on_failure") return true;
return false;
});
// Simulate a failure in monitorConsole
monitorConsole.mockResolvedValueOnce({
sawTraceback: true, // Should trigger "fail" due to on_traceback=fail
sawErrorLog: false,
sawWarningLog: false,
});
await postCode();
// Verify rollback was performed
const mockApiInstance = new ScreepsHttpClient();
// `userCodeSet` should be called twice:
// 1st time: uploading the new files
// 2nd time: rolling back to oldCode
expect(mockApiInstance.userCodeSet).toHaveBeenCalledTimes(2);
expect(mockApiInstance.userCodeSet).toHaveBeenNthCalledWith(2, {
branch: "default",
modules: {
main: "old_code",
},
});
// Verify it called core.setFailed due to traceback
expect(core.setFailed).toHaveBeenCalledWith(
"Screeps console: traceback detected",
);
});
});
-641
View File
@@ -1,641 +0,0 @@
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
// ── mock @actions/core so tests never touch real CI outputs ─────────────────
vi.mock("@actions/core", () => ({
info: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
setFailed: vi.fn(),
setOutput: vi.fn(),
startGroup: vi.fn(),
endGroup: vi.fn(),
}));
import * as artifact from "@actions/artifact";
vi.mock("@actions/artifact", () => {
const mockClient = {
uploadArtifact: vi.fn().mockResolvedValue({}),
};
return {
create: vi.fn(() => mockClient),
};
});
import * as core from "@actions/core";
import fs from "fs";
import os from "os";
import path from "path";
import {
isOfficialServer,
buildSubscribePath,
detectTraceback,
detectWarning,
outputMultiline,
buildProgressMessage,
writeLogFile,
uploadLogArtifacts,
handleConsoleEvent,
monitorConsole,
} from "../monitor.js";
// ────────────────────────────────────────────────────────────────────────────
// Pure helpers
// ────────────────────────────────────────────────────────────────────────────
describe("isOfficialServer", () => {
it("returns true for screeps.com", () => {
expect(isOfficialServer("screeps.com")).toBe(true);
});
it("returns false for a private hostname", () => {
expect(isOfficialServer("builder64")).toBe(false);
});
it("returns false for an IP address", () => {
expect(isOfficialServer("192.168.1.10")).toBe(false);
});
});
describe("buildSubscribePath", () => {
it("returns console for official server (no shard provided)", () => {
expect(buildSubscribePath("screeps.com")).toBe("console");
});
it("returns console for private server (no shard provided)", () => {
expect(buildSubscribePath("builder64")).toBe("console");
});
it("returns console when shard is provided (official)", () => {
expect(buildSubscribePath("screeps.com", "shard3")).toBe("console");
});
it("returns console when shard is provided (private)", () => {
expect(buildSubscribePath("builder64", "myshard")).toBe("console");
});
});
describe("detectTraceback", () => {
it("returns true when error contains a stack frame line", () => {
const error =
"TypeError: Cannot read properties of undefined\n at Object.<anonymous> (main:1:42)";
expect(detectTraceback(error)).toBe(true);
});
it("returns false for a plain error message without stack frames", () => {
expect(detectTraceback("Something went wrong")).toBe(false);
});
it("returns false for null", () => {
expect(detectTraceback(null)).toBe(false);
});
it("returns false for undefined", () => {
expect(detectTraceback(undefined)).toBe(false);
});
it("returns false for an empty string", () => {
expect(detectTraceback("")).toBe(false);
});
});
describe("detectWarning", () => {
it("returns true for a line with orange font tag", () => {
const lines = ["<font color='orange'>WARN: low energy</font>"];
expect(detectWarning(lines)).toBe(true);
});
it("returns true for a line with yellow font tag", () => {
const lines = ['<font color="yellow">WARN: something</font>'];
expect(detectWarning(lines)).toBe(true);
});
it("returns false for a plain log line", () => {
expect(detectWarning(["Tick 123: harvesting"])).toBe(false);
});
it("returns false for an empty array", () => {
expect(detectWarning([])).toBe(false);
});
it("returns false for null", () => {
expect(detectWarning(null)).toBe(false);
});
it("returns true when only one line in a mixed array is a warning", () => {
const lines = ["normal line", "<font color='orange'>warn</font>"];
expect(detectWarning(lines)).toBe(true);
});
});
describe("outputMultiline", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("prefixes lines with shard when provided", () => {
outputMultiline("line1\nline2", "info", "shard0");
expect(core.info).toHaveBeenCalledWith("[shard0] line1");
expect(core.info).toHaveBeenCalledWith("[shard0] line2");
});
it("does not prefix when shard is missing", () => {
outputMultiline("line1", "info");
expect(core.info).toHaveBeenCalledWith("line1");
});
it("uses core.warning for level=warning", () => {
outputMultiline("warn", "warning", "s0");
expect(core.warning).toHaveBeenCalledWith("[s0] warn");
});
it("uses core.error for level=error", () => {
outputMultiline("err", "error", "s0");
expect(core.error).toHaveBeenCalledWith("[s0] err");
});
});
describe("buildProgressMessage", () => {
it("formats correctly at 0 elapsed", () => {
expect(buildProgressMessage(0, 50)).toBe("[Monitor] 0/50 ticks elapsed...");
});
it("formats correctly midway", () => {
expect(buildProgressMessage(25, 50)).toBe(
"[Monitor] 25/50 ticks elapsed...",
);
});
it("formats correctly at 100%", () => {
expect(buildProgressMessage(50, 50)).toBe(
"[Monitor] 50/50 ticks elapsed...",
);
});
});
describe("uploadLogArtifacts", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("instantiates client and calls uploadArtifact", async () => {
await uploadLogArtifacts(
["/path/to/shard0_console_log.txt"],
"custom-name",
);
expect(artifact.create().uploadArtifact).toHaveBeenCalledWith(
"custom-name",
["/path/to/shard0_console_log.txt"],
"/path/to",
{ continueOnError: true },
);
});
it("does nothing if filePaths is empty", async () => {
await uploadLogArtifacts([]);
expect(artifact.create().uploadArtifact).not.toHaveBeenCalled();
});
});
// ────────────────────────────────────────────────────────────────────────────
// handleConsoleEvent
// ────────────────────────────────────────────────────────────────────────────
describe("handleConsoleEvent", () => {
let state;
let shardBuffers;
beforeEach(() => {
vi.clearAllMocks();
state = { sawTraceback: false, sawErrorLog: false, sawWarningLog: false };
shardBuffers = {};
});
const makeEvent = (log = [], results = [], error = null) => ({
data: { messages: { log, results }, error },
});
it("calls core.info for each stdout line with shard prefix when logToFile=false", () => {
const event = {
data: {
shard: "shard0",
messages: { log: ["line1"], results: ["line2"] },
},
};
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(core.info).toHaveBeenCalledWith("[shard0] line1");
expect(core.info).toHaveBeenCalledWith("[shard0] line2");
expect(Object.keys(shardBuffers)).toHaveLength(0);
});
it("buffers stdout when logToFile=true; does not call core.info", () => {
const event = {
data: { shard: "shard0", messages: { log: ["line1", "line2"] } },
};
handleConsoleEvent(event, { logToFile: true }, shardBuffers, state);
expect(core.info).not.toHaveBeenCalled();
expect(shardBuffers["shard0"]).toEqual(["line1", "line2"]);
});
it("includes results lines in output", () => {
const event = makeEvent([], ["result1"]);
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(core.info).toHaveBeenCalledWith("result1");
});
it("calls core.error when error field is non-empty", () => {
const event = makeEvent([], [], "Script crashed");
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(core.error).toHaveBeenCalledWith("Script crashed");
expect(state.sawErrorLog).toBe(true);
});
it("sets state.sawTraceback when error contains stack frames", () => {
const error = "TypeError: boom\n at Object.<anonymous> (main:1:1)";
const event = makeEvent([], [], error);
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(state.sawTraceback).toBe(true);
expect(state.sawErrorLog).toBe(true);
});
it("does not set sawTraceback for plain error without stack frames", () => {
const event = makeEvent([], [], "Script error: low CPU");
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(state.sawTraceback).toBe(false);
expect(state.sawErrorLog).toBe(true);
});
it("sets state.sawWarningLog and calls core.warning for warn lines", () => {
const event = makeEvent(["<font color='orange'>low energy</font>"]);
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state);
expect(state.sawWarningLog).toBe(true);
expect(core.warning).toHaveBeenCalled();
});
it("calls core.warning regardless of logToFile setting", () => {
const event = makeEvent(["<font color='orange'>warn line</font>"]);
handleConsoleEvent(event, { logToFile: true }, shardBuffers, state);
expect(core.warning).toHaveBeenCalled();
});
it("handles missing messages gracefully (no crash on empty event)", () => {
const event = { data: {} };
expect(() =>
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state),
).not.toThrow();
});
it("handles completely empty event gracefully", () => {
const event = {};
expect(() =>
handleConsoleEvent(event, { logToFile: false }, shardBuffers, state),
).not.toThrow();
});
it("filters messages by shard when targetShard is provided", () => {
const event = { data: { shard: "shard0", messages: { log: ["msg0"] } } };
handleConsoleEvent(event, { shard: "shard1" }, shardBuffers, state);
expect(core.info).not.toHaveBeenCalled();
handleConsoleEvent(event, { shard: "shard0" }, shardBuffers, state);
expect(core.info).toHaveBeenCalledWith("[shard0] msg0");
});
it("does not filter when targetShard is undefined", () => {
const event = { data: { shard: "shard0", messages: { log: ["msg0"] } } };
handleConsoleEvent(event, {}, shardBuffers, state);
expect(core.info).toHaveBeenCalledWith("[shard0] msg0");
});
it("buffers messages separately for different shards", () => {
const event0 = { data: { shard: "shard0", messages: { log: ["msg0"] } } };
const event1 = { data: { shard: "shard1", messages: { log: ["msg1"] } } };
handleConsoleEvent(event0, { logToFile: true }, shardBuffers, state);
handleConsoleEvent(event1, { logToFile: true }, shardBuffers, state);
expect(shardBuffers["shard0"]).toEqual(["msg0"]);
expect(shardBuffers["shard1"]).toEqual(["msg1"]);
});
it("uses 'default' key when shard is missing in event", () => {
const event = { data: { messages: { log: ["msg"] } } };
handleConsoleEvent(event, { logToFile: true }, shardBuffers, state);
expect(shardBuffers["default"]).toEqual(["msg"]);
});
});
// ────────────────────────────────────────────────────────────────────────────
// writeLogFile
// ────────────────────────────────────────────────────────────────────────────
describe("writeLogFile", () => {
let tempDir;
let tempFile;
beforeEach(async () => {
tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), "monitor-test-"),
);
tempFile = path.join(tempDir, "log.txt");
});
afterEach(async () => {
await fs.promises.rm(tempDir, { recursive: true, force: true });
});
it("writes all lines to file joined by newlines", async () => {
await writeLogFile(["line1", "line2", "line3"], tempFile);
const content = await fs.promises.readFile(tempFile, "utf8");
expect(content).toBe("line1\nline2\nline3");
});
it("writes an empty file when given an empty array", async () => {
await writeLogFile([], tempFile);
const content = await fs.promises.readFile(tempFile, "utf8");
expect(content).toBe("");
});
});
// ────────────────────────────────────────────────────────────────────────────
// monitorConsole — integration with mocked API
// ────────────────────────────────────────────────────────────────────────────
/**
* Builds a mock ScreepsAPI that:
* - api.time(shard) returns ticks from a list on each call
* - api.socket.connect() → resolves immediately
* - api.socket.subscribe() → resolves immediately (stores the callback)
* - api.socket.disconnect()→ no-op
*/
function buildMockApi({
ticks = [100, 101, 102, 103, 104, 105],
hostname = "builder64",
} = {}) {
let tickIndex = 0;
let consoleCallback = null;
const socket = {
connect: vi.fn().mockResolvedValue(undefined),
subscribe: vi.fn().mockImplementation((_path, cb) => {
consoleCallback = cb;
return Promise.resolve();
}),
disconnect: vi.fn(),
};
const getTime = vi.fn().mockImplementation(() => {
const t = ticks[Math.min(tickIndex, ticks.length - 1)];
tickIndex++;
return Promise.resolve({ time: t });
});
const api = {
opts: { hostname },
time: getTime,
get gameTime() {
return this.time;
},
set gameTime(fn) {
this.time = fn;
},
socket,
// Expose so tests can fire console events
_fireConsole: (eventData) => {
if (consoleCallback) {
consoleCallback({ data: eventData });
}
},
};
return api;
}
const BASE_OPTS = {
monitor: 3,
logToFile: false,
onTraceback: "fail",
onErrorLog: "warn",
onWarningLog: "ignore",
monitorInterval: 2,
hostname: "builder64",
};
describe("monitorConsole", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns all three flags false on a clean run", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
const result = await monitorConsole(api, BASE_OPTS);
expect(result).toEqual({
sawTraceback: false,
sawErrorLog: false,
sawWarningLog: false,
});
});
it("calls api.socket.connect() exactly once", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
await monitorConsole(api, BASE_OPTS);
expect(api.socket.connect).toHaveBeenCalledTimes(1);
});
it("calls api.socket.disconnect() after completion", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
await monitorConsole(api, BASE_OPTS);
expect(api.socket.disconnect).toHaveBeenCalledTimes(1);
});
it("subscribes to 'console' for a private server", async () => {
const api = buildMockApi({
hostname: "builder64",
ticks: [100, 101, 102, 103],
});
await monitorConsole(api, { ...BASE_OPTS, hostname: "builder64" });
expect(api.socket.subscribe).toHaveBeenCalledWith(
"console",
expect.any(Function),
);
});
it("subscribes to 'console' for the official server (default)", async () => {
const api = buildMockApi({
hostname: "screeps.com",
ticks: [100, 101, 102, 103],
});
await monitorConsole(api, { ...BASE_OPTS, hostname: "screeps.com" });
expect(api.socket.subscribe).toHaveBeenCalledWith(
"console",
expect.any(Function),
);
});
it("subscribes to 'console' even when custom shard is provided", async () => {
const api = buildMockApi({
hostname: "screeps.com",
ticks: [100, 101, 102, 103],
});
await monitorConsole(api, {
...BASE_OPTS,
hostname: "screeps.com",
shard: "shard3",
});
expect(api.socket.subscribe).toHaveBeenCalledWith(
"console",
expect.any(Function),
);
// Verify polling still uses shard3 for timing
expect(api.time).toHaveBeenCalledWith("shard3");
});
it("returns sawTraceback=true when a traceback event arrives", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
// Schedule console event before poll advances
setTimeout(() => {
api._fireConsole({
messages: { log: [], results: [] },
error: "TypeError: boom\n at Object.<anonymous> (main:1:1)",
});
}, 0);
const result = await monitorConsole(api, BASE_OPTS);
expect(result.sawTraceback).toBe(true);
});
it("returns sawErrorLog=true when an error (no traceback) event arrives", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
setTimeout(() => {
api._fireConsole({
messages: { log: [], results: [] },
error: "Script error: CPU limit exceeded",
});
}, 0);
const result = await monitorConsole(api, BASE_OPTS);
expect(result.sawErrorLog).toBe(true);
expect(result.sawTraceback).toBe(false);
});
it("returns sawWarningLog=true when a warn log line arrives", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
setTimeout(() => {
api._fireConsole({
messages: {
log: ["<font color='orange'>low energy</font>"],
results: [],
},
error: null,
});
}, 0);
const result = await monitorConsole(api, BASE_OPTS);
expect(result.sawWarningLog).toBe(true);
});
it("logs progress via core.info at monitorInterval boundaries when logToFile=true", async () => {
// ticks: start=100, then 101,102(interval),103(done at delta=3)
const api = buildMockApi({ ticks: [100, 100, 101, 102, 103] });
await monitorConsole(api, {
...BASE_OPTS,
logToFile: true,
monitorInterval: 2,
});
// Progress should be logged when elapsed reaches 2
const infoCalls = core.info.mock.calls.map((c) => c[0]);
expect(infoCalls.some((m) => m.includes("2/3"))).toBe(true);
});
it("calls api.socket.disconnect() even if an error occurs during polling", async () => {
const api = buildMockApi({ ticks: [100] });
// Make time() reject after first call
let calls = 0;
api.time = vi.fn().mockImplementation(() => {
calls++;
if (calls > 1) return Promise.reject(new Error("network error"));
return Promise.resolve({ time: 100 });
});
await expect(monitorConsole(api, BASE_OPTS)).rejects.toThrow(
"network error",
);
expect(api.socket.disconnect).toHaveBeenCalledTimes(1);
});
it("exits early if a traceback occurs and onTraceback='fail'", async () => {
// startTick=100, monitor=10 ticks.
// If it didn't exit early, it would call api.time() many times.
const api = buildMockApi({
ticks: [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
});
// Fire a traceback event after the first poll
setTimeout(() => {
api._fireConsole({
messages: { log: [], results: [] },
error:
"TypeError: fail-fast test\n at Object.<anonymous> (main:1:1)",
});
}, 100);
const result = await monitorConsole(api, {
...BASE_OPTS,
monitor: 10,
onTraceback: "fail",
});
expect(result.sawTraceback).toBe(true);
// We expect it to have called api.time fewer than 10 times (excluding the startTick call)
expect(api.time.mock.calls.length).toBeLessThan(10);
});
it("detects encoded tracebacks in log lines", async () => {
const api = buildMockApi({ ticks: [100, 101, 102] });
setTimeout(() => {
api._fireConsole({
messages: {
log: [
"Error: ReferenceError: a is not defined%0A at eval (eval at <anonymous> (_console1778948572008_0:1:46), <anonymous>:1:1)%0A at _console1778948572008_0:1:46",
],
results: [],
},
error: null,
});
}, 50);
const result = await monitorConsole(api, {
...BASE_OPTS,
onTraceback: "fail",
});
expect(result.sawTraceback).toBe(true);
expect(result.sawErrorLog).toBe(true);
});
it("creates separate log files for different shards when logToFile=true", async () => {
const api = buildMockApi({ ticks: [100, 101, 102, 103] });
setTimeout(() => {
api._fireConsole({
shard: "shard0",
messages: { log: ["msg0"], results: [] },
error: null,
});
api._fireConsole({
shard: "shard1",
messages: { log: ["msg1"], results: [] },
error: null,
});
}, 50);
// Verify uploadArtifact was called with two files
await monitorConsole(api, {
...BASE_OPTS,
logToFile: true,
});
expect(artifact.create().uploadArtifact).toHaveBeenCalledWith(
"screeps-console-log",
expect.arrayContaining([
expect.stringContaining("shard0_console_log.txt"),
expect.stringContaining("shard1_console_log.txt"),
]),
expect.any(String),
{ continueOnError: true },
);
});
});
+1 -39
View File
@@ -40,44 +40,6 @@ inputs:
git-replace: git-replace:
description: Allows for the overwrite of the "{{gitRef}}", "{{gitHash}}" and "{{deployTime}}" values in the file matching the file pattern. The file pattern will be combined with the prefix. description: Allows for the overwrite of the "{{gitRef}}", "{{gitHash}}" and "{{deployTime}}" values in the file matching the file pattern. The file pattern will be combined with the prefix.
required: false required: false
shard:
description: The Screeps shard to monitor (e.g. shard0, shard1). Defaults to shard0 on the official server.
required: false
monitor:
description: Number of game ticks to monitor the Screeps console after deploying (0 = disabled).
required: false
default: '0'
log_to_file:
description: 'Buffer stdout to an artifact file instead of streaming live (default: false). Errors/warnings always stream live.'
required: false
default: 'false'
on_traceback:
description: 'Action on JS traceback detection: ignore, warn, or fail (default: fail).'
required: false
default: fail
on_error_log:
description: 'Action on Screeps error-console output: ignore, warn, or fail (default: warn).'
required: false
default: warn
on_warning_log:
description: 'Action on console.warn output: ignore, warn, or fail (default: ignore).'
required: false
default: ignore
monitor_interval:
description: 'Print a progress update every N ticks when log_to_file=true (default: 10).'
required: false
default: '10'
rollback_on_failure:
description: 'Automatically rollback to previous code if the monitor detects failures. Requires monitor > 0. (default: false)'
required: false
default: 'false'
outputs:
saw_traceback:
description: true if a JS traceback was detected during monitoring.
saw_error_log:
description: true if the Screeps error console had output during monitoring.
saw_warning_log:
description: true if console.warn output was detected during monitoring.
runs: runs:
using: node22 using: node20
main: dist/index.js main: dist/index.js
+5 -16
View File
@@ -1,27 +1,16 @@
import{createRequire as A}from"module";var i={7038:(A,i,g)=>{var f;f={value:true};i.v=void 0;const p=g(918);function create(){return p.DefaultArtifactClient.create()}i.v=create},918:function(A,i,g){var f=this&&this.__createBinding||(Object.create?function(A,i,g,f){if(f===undefined)f=g;var p=Object.getOwnPropertyDescriptor(i,g);if(!p||("get"in p?!i.__esModule:p.writable||p.configurable)){p={enumerable:true,get:function(){return i[g]}}}Object.defineProperty(A,f,p)}:function(A,i,g,f){if(f===undefined)f=g;A[f]=i[g]});var p=this&&this.__setModuleDefault||(Object.create?function(A,i){Object.defineProperty(A,"default",{enumerable:true,value:i})}:function(A,i){A["default"]=i});var E=this&&this.__importStar||function(A){if(A&&A.__esModule)return A;var i={};if(A!=null)for(var g in A)if(g!=="default"&&Object.prototype.hasOwnProperty.call(A,g))f(i,A,g);p(i,A);return i};var C=this&&this.__awaiter||function(A,i,g,f){function adopt(A){return A instanceof g?A:new g(function(i){i(A)})}return new(g||(g=Promise))(function(g,p){function fulfilled(A){try{step(f.next(A))}catch(A){p(A)}}function rejected(A){try{step(f["throw"](A))}catch(A){p(A)}}function step(A){A.done?g(A.value):adopt(A.value).then(fulfilled,rejected)}step((f=f.apply(A,i||[])).next())})};Object.defineProperty(i,"__esModule",{value:true});i.DefaultArtifactClient=void 0;const B=E(g(9910));const Q=g(9367);const I=g(8950);const y=g(2669);const b=g(9400);const k=g(3439);const D=g(3886);const R=g(1124);const S=g(6928);class DefaultArtifactClient{static create(){return new DefaultArtifactClient}uploadArtifact(A,i,g,f){return C(this,void 0,void 0,function*(){B.info(`Starting artifact upload\nFor more detailed logs during the artifact upload process, enable step-debugging: https://docs.github.com/actions/monitoring-and-troubleshooting-workflows/enabling-debug-logging#enabling-step-debug-logging`);(0,b.checkArtifactName)(A);const p=(0,Q.getUploadSpecification)(A,g,i);const E={artifactName:A,artifactItems:[],size:0,failedItems:[]};const C=new I.UploadHttpClient;if(p.length===0){B.warning(`No files found that can be uploaded`)}else{const i=yield C.createArtifactInFileContainer(A,f);if(!i.fileContainerResourceUrl){B.debug(i.toString());throw new Error("No URL provided by the Artifact Service to upload an artifact to")}B.debug(`Upload Resource URL: ${i.fileContainerResourceUrl}`);B.info(`Container for artifact "${A}" successfully created. Starting upload of file(s)`);const g=yield C.uploadArtifactToFileContainer(i.fileContainerResourceUrl,p,f);B.info(`File upload process has finished. Finalizing the artifact upload`);yield C.patchArtifactSize(g.totalSize,A);if(g.failedItems.length>0){B.info(`Upload finished. There were ${g.failedItems.length} items that failed to upload`)}else{B.info(`Artifact has been finalized. All files have been successfully uploaded!`)}B.info(`\nThe raw size of all the files that were specified for upload is ${g.totalSize} bytes\nThe size of all the files that were uploaded is ${g.uploadSize} bytes. This takes into account any gzip compression used to reduce the upload size, time and storage\n\nNote: The size of downloaded zips can differ significantly from the reported size. For more information see: https://github.com/actions/upload-artifact#zipped-artifact-downloads \r\n`);E.artifactItems=p.map(A=>A.absoluteFilePath);E.size=g.uploadSize;E.failedItems=g.failedItems}return E})}downloadArtifact(A,i,g){return C(this,void 0,void 0,function*(){const f=new k.DownloadHttpClient;const p=yield f.listArtifacts();if(p.count===0){throw new Error(`Unable to find any artifacts for the associated workflow`)}const E=p.value.find(i=>i.name===A);if(!E){throw new Error(`Unable to find an artifact with the name: ${A}`)}const C=yield f.getContainerItems(E.name,E.fileContainerResourceUrl);if(!i){i=(0,R.getWorkSpaceDirectory)()}i=(0,S.normalize)(i);i=(0,S.resolve)(i);const Q=(0,D.getDownloadSpecification)(A,C.value,i,(g===null||g===void 0?void 0:g.createArtifactFolder)||false);if(Q.filesToDownload.length===0){B.info(`No downloadable files were found for the artifact: ${E.name}`)}else{yield(0,y.createDirectoriesForArtifact)(Q.directoryStructure);B.info("Directory structure has been set up for the artifact");yield(0,y.createEmptyFilesForArtifact)(Q.emptyFilesToCreate);yield f.downloadSingleArtifact(Q.filesToDownload)}return{artifactName:A,downloadPath:Q.rootDownloadLocation}})}downloadAllArtifacts(A){return C(this,void 0,void 0,function*(){const i=new k.DownloadHttpClient;const g=[];const f=yield i.listArtifacts();if(f.count===0){B.info("Unable to find any artifacts for the associated workflow");return g}if(!A){A=(0,R.getWorkSpaceDirectory)()}A=(0,S.normalize)(A);A=(0,S.resolve)(A);let p=0;while(p<f.count){const E=f.value[p];p+=1;B.info(`starting download of artifact ${E.name} : ${p}/${f.count}`);const C=yield i.getContainerItems(E.name,E.fileContainerResourceUrl);const Q=(0,D.getDownloadSpecification)(E.name,C.value,A,true);if(Q.filesToDownload.length===0){B.info(`No downloa Line truncated (()=>{var __webpack_modules__={6136:(module,__unused_webpack_exports,__nccwpck_require__)=>{const{ScreepsAPI:ScreepsAPI}=__nccwpck_require__(9546);const core=__nccwpck_require__(7484);const fs=__nccwpck_require__(9896);const{glob:glob}=__nccwpck_require__(1363);const path=__nccwpck_require__(6928);function replacePlaceholders(e,t){const s=(new Date).toISOString();return e.replace(/{{gitHash}}/g,process.env.GITHUB_SHA).replace(/{{gitRef}}/g,process.env.GITHUB_REF).replace(/{{deployTime}}/g,s).replace(/{{hostname}}/g,t)}async function readReplaceAndWriteFiles(e,t,s){const i=t?path.join(t,e):e;const n=await glob(i);let r=n.map((e=>fs.promises.readFile(e,"utf8").then((t=>{t=replacePlaceholders(t,s);return fs.promises.writeFile(e,t)}))));await Promise.all(r);return n}async function readFilesIntoDict(e,t){const s=t?path.join(t,e):e;const i=await glob(s);let n={};let r=i.map((e=>fs.promises.readFile(e,"utf8").then((s=>{let i=e;if(t&&e.startsWith(t)){i=i.slice(t.length)}i=path.basename(i,path.extname(i));n[i]=s}))));await Promise.all(r);return n}function validateAuthentication(e,t,s){if(e){if(t||s){return"Token is defined along with username and/or password."}}else{if(!t&&!s){return"Neither token nor password and username are defined."}if(t&&!s){return"Username is defined but no password is provided."}if(!t&&s){return"Password is defined but no username is provided."}}return null}async function postCode(){const e=core.getInput("protocol")||"https";const t=core.getInput("hostname")||"screeps.com";const s=core.getInput("port")||"443";const i=core.getInput("path")||"/";const n=core.getInput("token")||undefined;const r=core.getInput("username")||undefined;const A=core.getInput("password")||undefined;const o=core.getInput("source-prefix");const a=core.getInput("pattern")||"*.js";const c=core.getInput("branch")||"default";const l=core.getInput("git-replace")||null;if(l){await readReplaceAndWriteFiles(l,o,t)}const u=await readFilesIntoDict(a,o);core.info(`Trying to upload the following files to ${c}:`);Object.keys(u).forEach((e=>{core.info(`Key: ${e}`)}));const h={token:n,username:r,password:A,protocol:e,hostname:t,port:s,path:i};core.info("login_arguments:");core.info(JSON.stringify(h,null,2));const p=validateAuthentication(n,r,A);if(p){core.error(p);return}let d=new ScreepsAPI(h);if(n){const e=await d.code.set(c,u);core.info(JSON.stringify(e,null,2));console.log(`Code set successfully to ${c}`)}else{core.info(`Logging in as user ${r}`);await Promise.resolve().then((()=>d.auth(r,A,h))).then((()=>{d.code.set(c,u)})).then((()=>{console.log(`Code set successfully to ${c}`)})).catch((e=>{console.error("Error:",e)}))}}if(require.main===require.cache[eval("__filename")]){postCode()}module.exports={validateAuthentication:validateAuthentication,replacePlaceholders:replacePlaceholders,postCode:postCode,readReplaceAndWriteFiles:readReplaceAndWriteFiles,readFilesIntoDict:readFilesIntoDict}},4914:function(e,t,s){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,s,i){if(i===undefined)i=s;var n=Object.getOwnPropertyDescriptor(t,s);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable)){n={enumerable:true,get:function(){return t[s]}}}Object.defineProperty(e,i,n)}:function(e,t,s,i){if(i===undefined)i=s;e[i]=t[s]});var n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:true,value:t})}:function(e,t){e["default"]=t});var r=this&&this.__importStar||function(){var ownKeys=function(e){ownKeys=Object.getOwnPropertyNames||function(e){var t=[];for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s))t[t.length]=s;return t};return ownKeys(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var s=ownKeys(e),r=0;r<s.length;r++)if(s[r]!=="default")i(t,e,s[r]);n(t,e);return t}}();Object.defineProperty(t,"__esModule",{value:true});t.issueCommand=issueCommand;t.issue=issue;const A=r(s(857));const o=s(302);function issueCommand(e,t,s){const i=new Command(e,t,s);process.stdout.write(i.toString()+A.EOL)}function issue(e,t=""){issueCommand(e,{},t)}const a="::";class Command{constructor(e,t,s){if(!e){e="missing.command"}this.command=e;this.properties=t;this.message=s}toString(){let e=a+this.command;if(this.properties&&Object.keys(this.properties).length>0){e+=" ";let t=true;for(const s in this.properties){if(this.properties.hasOwnProperty(s)){const i=this.properties[s];if(i){if(t){t=false}else{e+=","}e+=`${s}=${escapeProperty(i)}`}}}}e+=`${a}${escapeData(this.message)}`;return e}}function escapeData(e){return(0,o.toCommandValue)(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A")}function escapeProperty(e){return(0,o.toCommandValue)(e).replace(/%/g,"%25").replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/:/g,"%3A").replace(/,/g,"%2C")}},7484:function(e,t,s){"use strict";var i=this&&this.__createBinding||(Object.create?function(e,t,s,i){if(i===undefined)i=s;var n=Object.getOwnPropertyDescriptor(t,s);if(!n||("get"in n?!t.__esModule:nLine truncated
/*! /*!
* mime-db * mime-db
* Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2022 Douglas Christopher Wilson * Copyright(c) 2015-2022 Douglas Christopher Wilson
* MIT Licensed * MIT Licensed
*/ */
A.exports=g(7080)},3674:(A,i,g)=>{ e.exports=s(1813)},4096:(e,t,s)=>{"use strict";
/*! /*!
* mime-types * mime-types
* Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson * Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed * MIT Licensed
*/ */var i=s(9829);var n=s(6928).extname;var r=/^\s*([^;\s]*)(?:;|\s|$)/;var A=/^text\//i;t.charset=charset;t.charsets={lookup:charset};t.contentType=contentType;t.extension=extension;t.extensions=Object.create(null);t.lookup=lookup;t.types=Object.create(null);populateMaps(t.extensions,t.types);function charset(e){if(!e||typeof e!=="string"){return false}var t=r.exec(e);var s=t&&i[t[1].toLowerCase()];if(s&&s.charset){return s.charset}if(t&&A.test(t[1])){return"UTF-8"}return false}function contentType(e){if(!e||typeof e!=="string"){return false}var s=e.indexOf("/")===-1?t.lookup(e):e;if(!s){return false}if(s.indexOf("charset")===-1){var i=t.charset(s);if(i)s+="; charset="+i.toLowerCase()}return s}function extension(e){if(!e||typeof e!=="string"){return false}var s=r.exec(e);var i=s&&t.extensions[s[1].toLowerCase()];if(!i||!i.length){return false}return i[0]}function lookup(e){if(!e||typeof e!=="string"){return false}var s=n("x."+e).toLowerCase().substr(1);if(!s){return false}return t.types[s]||false}function populateMaps(e,t){var s=["nginx","apache",undefined,"iana"];Object.keys(i).forEach((function forEachMimeType(n){var r=i[n];var A=r.extensions;if(!A||!A.length){return}e[n]=A;for(var o=0;o<A.length;o++){var a=A[o];if(t[a]){var c=s.indexOf(i[t[a]].source);var l=s.indexOf(r.source);if(t[a]!=="application/octet-stream"&&(c>l||c===l&&t[a].substr(0,12)==="application/")){continue}}t[a]=n}}))}},744:e=>{var t=1e3;var s=t*60;var i=s*60;var n=i*24;var r=n*7;var A=n*365.25;e.exports=function(e,t){t=t||{};var s=typeof e;if(s==="string"&&e.length>0){return parse(e)}else if(s==="number"&&isFinite(e)){return t.long?fmtLong(e):fmtShort(e)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse(e){e=String(e);if(e.length>100){return}var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!o){return}var a=parseFloat(o[1]);var c=(o[2]||"ms").toLowerCase();switch(c){case"years":case"year":case"yrs":case"yr":case"y":return a*A;case"weeks":case"week":case"w":return a*r;case"days":case"day":case"d":return a*n;case"hours":case"hour":case"hrs":case"hr":case"h":return a*i;case"minutes":case"minute":case"mins":case"min":case"m":return a*s;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return undefined}}function fmtShort(e){var r=Math.abs(e);if(r>=n){return Math.round(e/n)+"d"}if(r>=i){return Math.round(e/i)+"h"}if(r>=s){return Math.round(e/s)+"m"}if(r>=t){return Math.round(e/t)+"s"}return e+"ms"}function fmtLong(e){var r=Math.abs(e);if(r>=n){return plural(e,r,n,"day")}if(r>=i){return plural(e,r,i,"hour")}if(r>=s){return plural(e,r,s,"minute")}if(r>=t){return plural(e,r,t,"second")}return e+" ms"}function plural(e,t,s,i){var n=t>=s*1.5;return Math.round(e/s)+" "+i+(n?"s":"")}},7777:(e,t,s)=>{"use strict";var i=s(7016).parse;var n={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};var r=String.prototype.endsWith||function(e){return e.length<=this.length&&this.indexOf(e,this.length-e.length)!==-1};function getProxyForUrl(e){var t=typeof e==="string"?i(e):e||{};var s=t.protocol;var r=t.host;var A=t.port;if(typeof r!=="string"||!r||typeof s!=="string"){return""}s=s.split(":",1)[0];r=r.replace(/:\d*$/,"");A=parseInt(A)||n[s]||0;if(!shouldProxy(r,A)){return""}var o=getEnv("npm_config_"+s+"_proxy")||getEnv(s+"_proxy")||getEnv("npm_config_proxy")||getEnv("all_proxy");if(o&&o.indexOf("://")===-1){o=s+"://"+o}return o}function shouldProxy(e,t){var s=(getEnv("npm_config_no_proxy")||getEnv("no_proxy")).toLowerCase();if(!s){return true}if(s==="*"){return false}return s.split(/[,\s]/).every((function(s){if(!s){return true}var i=s.match(/^(.+):(\d+)$/);var n=i?i[1]:s;var A=i?parseInt(i[2]):0;if(A&&A!==t){return true}if(!/^[.*]/.test(n)){return e!==n}if(n.charAt(0)==="*"){n=n.slice(1)}return!r.call(e,n)}))}function getEnv(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||""}t.T=getProxyForUrl},9546:(e,t,s)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const i=s(1354);const n=s(7016);const r=s(4434);const A=s(2830);const o=s(3106);const a=s(4922);const c=s(9023);const l=s(9896);const u=s(9557);const h=s(6928);function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}const p=_interopDefaultLegacy(i);const d=_interopDefaultLegacy(n);const g=_interopDefaultLegacy(A);const f=_interopDefaultLegacy(o);const E=_interopDefaultLegacy(a);const C=_interopDefaultLegacy(c);const Q=_interopDefaultLegacy(l);const B=_interopDefaultLegacy(u);const I=_interopDefaultLegacy(h);const y=g["default"]("screepsapi:socket");const b={reconnect:true,resubscribe:true,keepAlive:true,maxRetries:10,maxRetryDelay:60*1e3};class Socket extends r.EventEmitter{constructor(e){super();this.api=e;this.opts=Object.assign({},b);this.on("error",(()=>{}));this.reset();this.oLine truncated
var f=g(8975);var p=g(6928).extname;var E=/^\s*([^;\s]*)(?:;|\s|$)/;var C=/^text\//i;i.charset=charset;i.charsets={lookup:charset};i.contentType=contentType;i.extension=extension;i.extensions=Object.create(null);i.lookup=lookup;i.types=Object.create(null);populateMaps(i.extensions,i.types);function charset(A){if(!A||typeof A!=="string"){return false}var i=E.exec(A);var g=i&&f[i[1].toLowerCase()];if(g&&g.charset){return g.charset}if(i&&C.test(i[1])){return"UTF-8"}return false}function contentType(A){if(!A||typeof A!=="string"){return false}var g=A.indexOf("/")===-1?i.lookup(A):A;if(!g){return false}if(g.indexOf("charset")===-1){var f=i.charset(g);if(f)g+="; charset="+f.toLowerCase()}return g}function extension(A){if(!A||typeof A!=="string"){return false}var g=E.exec(A);var f=g&&i.extensions[g[1].toLowerCase()];if(!f||!f.length){return false}return f[0]}function lookup(A){if(!A||typeof A!=="string"){return false}var g=p("x."+A).toLowerCase().substr(1);if(!g){return false}return i.types[g]||false}function populateMaps(A,i){var g=["nginx","apache",undefined,"iana"];Object.keys(f).forEach(function forEachMimeType(p){var E=f[p];var C=E.extensions;if(!C||!C.length){return}A[p]=C;for(var B=0;B<C.length;B++){var Q=C[B];if(i[Q]){var I=g.indexOf(f[i[Q]].source);var y=g.indexOf(E.source);if(i[Q]!=="application/octet-stream"&&(I>y||I===y&&i[Q].substr(0,12)==="application/")){continue}}i[Q]=p}})}},4023:A=>{var i=1e3;var g=i*60;var f=g*60;var p=f*24;var E=p*7;var C=p*365.25;A.exports=function(A,i){i=i||{};var g=typeof A;if(g==="string"&&A.length>0){return parse(A)}else if(g==="number"&&isFinite(A)){return i.long?fmtLong(A):fmtShort(A)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(A))};function parse(A){A=String(A);if(A.length>100){return}var B=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(A);if(!B){return}var Q=parseFloat(B[1]);var I=(B[2]||"ms").toLowerCase();switch(I){case"years":case"year":case"yrs":case"yr":case"y":return Q*C;case"weeks":case"week":case"w":return Q*E;case"days":case"day":case"d":return Q*p;case"hours":case"hour":case"hrs":case"hr":case"h":return Q*f;case"minutes":case"minute":case"mins":case"min":case"m":return Q*g;case"seconds":case"second":case"secs":case"sec":case"s":return Q*i;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return Q;default:return undefined}}function fmtShort(A){var E=Math.abs(A);if(E>=p){return Math.round(A/p)+"d"}if(E>=f){return Math.round(A/f)+"h"}if(E>=g){return Math.round(A/g)+"m"}if(E>=i){return Math.round(A/i)+"s"}return A+"ms"}function fmtLong(A){var E=Math.abs(A);if(E>=p){return plural(A,E,p,"day")}if(E>=f){return plural(A,E,f,"hour")}if(E>=g){return plural(A,E,g,"minute")}if(E>=i){return plural(A,E,i,"second")}return A+" ms"}function plural(A,i,g,f){var p=i>=g*1.5;return Math.round(A/g)+" "+f+(p?"s":"")}},6916:(A,i,g)=>{const f=g(857);const p=g(2018);const E=g(2219);const{env:C}=process;let B;if(E("no-color")||E("no-colors")||E("color=false")||E("color=never")){B=0}else if(E("color")||E("colors")||E("color=true")||E("color=always")){B=1}if("FORCE_COLOR"in C){if(C.FORCE_COLOR==="true"){B=1}else if(C.FORCE_COLOR==="false"){B=0}else{B=C.FORCE_COLOR.length===0?1:Math.min(parseInt(C.FORCE_COLOR,10),3)}}function translateLevel(A){if(A===0){return false}return{level:A,hasBasic:true,has256:A>=2,has16m:A>=3}}function supportsColor(A,i){if(B===0){return 0}if(E("color=16m")||E("color=full")||E("color=truecolor")){return 3}if(E("color=256")){return 2}if(A&&!i&&B===undefined){return 0}const g=B||0;if(C.TERM==="dumb"){return g}if(process.platform==="win32"){const A=f.release().split(".");if(Number(A[0])>=10&&Number(A[2])>=10586){return Number(A[2])>=14931?3:2}return 1}if("CI"in C){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(A=>A in C)||C.CI_NAME==="codeship"){return 1}return g}if("TEAMCITY_VERSION"in C){return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(C.TEAMCITY_VERSION)?1:0}if(C.COLORTERM==="truecolor"){return 3}if("TERM_PROGRAM"in C){const A=parseInt((C.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(C.TERM_PROGRAM){case"iTerm.app":return A>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(C.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(C.TERM)){return 1}if("COLORTERM"in C){return 1}return g}function getSupportLevel(A){const i=supportsColor(A,A&&A.isTTY);return translateLevel(i)}A.exports={supportsColor:getSupportLevel,stdout:translateLevel(supportsColor(true,p.isatty(1))),stderr:translateLevel(supportsColor(true,p.isatty(2)))}},9229:(A,i,g)=>{const{promisify:f}=g(9023);const p=g(3125);A.exports.fileSync=p.fileSync;const E=f((A,i)=>p.file(A,(A,g,p,E)=>A?i(A):i(undefined,{path:g,fd:p,cleanup:f(E)})));A.exports.file=async A=>E(A);A.exports.withFile=async function withFile(i,g){const{path:f,fd:p,cleanup:E}=await A.exports.file(g);try{return await i(Line truncated /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=e=>e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=e=>e.replace(/\r?\n|\r/g,"\r\n");const i=[];const n=new Uint8Array([13,10]);u=0;let r=false;for(const[t,A]of e){if(typeof A==="string"){const e=D.encode(s+`; name="${escape(normalizeLinefeeds(t))}"`+`\r\n\r\n${normalizeLinefeeds(A)}\r\n`);i.push(e);u+=e.byteLength}else{const e=D.encode(`${s}; name="${escape(normalizeLinefeeds(t))}"`+(A.name?`; filename="${escape(A.name)}"`:"")+"\r\n"+`Content-Type: ${A.type||"application/octet-stream"}\r\n\r\n`);i.push(e,A,n);if(typeof A.size==="number"){u+=e.byteLength+A.size+n.byteLength}else{r=true}}}const A=D.encode(`--${t}--`);i.push(A);u+=A.byteLength;if(r){u=null}l=e;c=async function*(){for(const e of i){if(e.stream){yield*e.stream()}else{yield e}}};h="multipart/form-data; boundary="+t}else if(A(e)){l=e;u=e.size;if(e.type){h=e.type}}else if(typeof e[Symbol.asyncIterator]==="function"){if(t){throw new TypeError("keepalive")}if(n.isDisturbed(e)||e.locked){throw new TypeError("Response body object should not be disturbed or locked")}i=e instanceof R?e:r(e)}if(typeof l==="string"||n.isBuffer(l)){u=Buffer.byteLength(l)}if(c!=null){let t;i=new R({async start(){t=c(e)[Symbol.asyncIterator]()},async pull(e){const{value:s,done:n}=await t.next();if(n){queueMicrotask((()=>{e.close()}))}else{if(!B(i)){e.enqueue(new Uint8Array(s))}}return e.desiredSize>0},async cancel(e){await t.return()},type:undefined})}const p={stream:i,source:l,length:u};return[p,h]}function safelyExtractBody(e,t=false){if(!R){R=s(3774).ReadableStream}if(e instanceof R){Q(!n.isDisturbed(e),"The body has already been consumed.");Q(!e.locked,"The stream is locked.")}return extractBody(e,t)}function cloneBody(e){const[t,s]=e.stream.tee();const i=g(s,{transfer:[s]});const[,n]=i.tee();e.stream=t;return{stream:n,length:e.length,source:e.source}}async function*consumeBody(e){if(e){if(I(e)){yield e}else{const t=e.stream;if(n.isDisturbed(t)){throw new TypeError("The body has already been consumed.")}if(t.locked){throw new TypeError("The stream is locked.")}t[C]=true;yield*t}}}function throwIfAborted(e){if(e.aborted){throw new d("The operation was aborted.","AbortError")}}function bodyMixinMethods(e){const t={blob(){return specConsumeBody(this,(e=>{let t=bodyMimeType(this);if(t==="failure"){t=""}else if(t){t=v(t)}return new f([e],{type:t})}),e)},arrayBuffer(){return specConsumeBody(this,(e=>new Uint8Array(e).buffer),e)},text(){return specConsumeBody(this,utf8DecodeBytes,e)},json(){return specConsumeBody(this,parseJSONFromBytes,e)},async formData(){p.brandCheck(this,e);throwIfAborted(this[h]);const t=this.headers.get("Content-Type");if(/multipart\/form-data/.test(t)){const e={};for(const[t,s]of this.headers)e[t.toLowerCase()]=s;const t=new u;let s;try{s=new i({headers:e,preservePath:true})}catch(e){throw new d(`${e}`,"AbortError")}s.on("field",((e,s)=>{t.append(e,s)}));s.on("file",((e,s,i,n,r)=>{const A=[];if(n==="base64"||n.toLowerCase()==="base64"){let n="";s.on("data",(e=>{n+=e.toString().replace(/[\r\n]/gm,"");const t=n.length-n.length%4;A.push(Buffer.from(n.slice(0,t),"base64"));n=n.slice(t)}));s.on("end",(()=>{A.push(Buffer.from(n,"base64"));t.append(e,new k(A,i,{type:r}))}))}else{s.on("data",(e=>{A.push(e)}));s.on("end",(()=>{t.append(e,new k(A,i,{type:r}))}))}}));const n=new Promise(((e,t)=>{s.on("finish",e);s.on("error",(e=>t(new TypeError(e))))}));if(this.body!==null)for await(const e of consumeBody(this[h].body))s.write(e);s.end();await n;return t}else if(/application\/x-www-form-urlencoded/.test(t)){let e;try{let t="";const s=new TextDecoder("utf-8",{ignoreBOM:true});for await(const e of consumeBody(this[h].body)){if(!I(e)){throw new TypeError("Expected Uint8Array chunk")}t+=s.decode(e,{stream:true})}t+=s.decode();e=new URLSearchParams(t)}catch(e){throw Object.assign(new TypeError,{cause:e})}const t=new u;for(const[s,i]of e){t.append(s,i)}return t}else{await Promise.resolve();throwIfAborted(this[h]);throw p.errors.exception({header:`${e.name}.formData`,message:"Could not parse content as FormData."})}}};return t}function mixinBody(e){Object.assign(e.prototype,bodyMixinMethods(e))}async function specConsumeBody(e,t,s){p.brandCheck(e,s);throwIfAborted(e[h]);if(bodyUnusable(e[h].body)){throw new TypeError("Body is unusable")}const i=c();const errorSteps=e=>i.reject(e);const successSteps=e=>{try{i.resolve(t(e))}catch(e){errorSteps(e)}};if(e[h].body==null){successSteps(new Uint8Array);return i.promise}await l(e[h].body,successSteps,errorSteps);return i.promise}function bodyUnusable(e){return e!=null&&(e.stream.locked||n.isDisturbed(e.stream))}function utf8DecodeBytes(e){if(e.length===0){return""}if(e[0]===239&&e[1]===187&&e[2]===191){e=e.subarray(3)}const t=S.decode(e);return t}function parseJSONFromBytes(e){return JSON.parse(utf8DecodeBytes(e))}function bodyMimeType(e){const{headersList:t}=e[h];const s=t.get("content-Line truncated
/*! /*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */r[n-4]=this.maskKey[0];r[n-3]=this.maskKey[1];r[n-2]=this.maskKey[2];r[n-1]=this.maskKey[3];r[1]=s;if(s===126){r.writeUInt16BE(t,2)}else if(s===127){r[2]=r[3]=0;r.writeUIntBE(t,4,6)}r[1]|=128;for(let e=0;e<t;e++){r[n+e]=this.frameData[e]^this.maskKey[e%4]}return r}}e.exports={WebsocketFrameSend:WebsocketFrameSend}},3171:(e,t,s)=>{"use strict";const{Writable:i}=s(2203);const n=s(1637);const{parserStates:r,opcodes:A,states:o,emptyBuffer:a}=s(5913);const{kReadyState:c,kSentClose:l,kResponse:u,kReceivedClose:h}=s(2933);const{isValidStatusCode:p,failWebsocketConnection:d,websocketMessageReceived:g}=s(3574);const{WebsocketFrameSend:f}=s(1237);const E={};E.ping=n.channel("undici:websocket:ping");E.pong=n.channel("undici:websocket:pong");class ByteParser extends i{#A=[];#o=0;#a=r.INFO;#c={};#l=[];constructor(e){super();this.ws=e}_write(e,t,s){this.#A.push(e);this.#o+=e.length;this.run(s)}run(e){while(true){if(this.#a===r.INFO){if(this.#o<2){return e()}const t=this.consume(2);this.#c.fin=(t[0]&128)!==0;this.#c.opcode=t[0]&15;this.#c.originalOpcode??=this.#c.opcode;this.#c.fragmented=!this.#c.fin&&this.#c.opcode!==A.CONTINUATION;if(this.#c.fragmented&&this.#c.opcode!==A.BINARY&&this.#c.opcode!==A.TEXT){d(this.ws,"Invalid frame type was fragmented.");return}const s=t[1]&127;if(s<=125){this.#c.payloadLength=s;this.#a=r.READ_DATA}else if(s===126){this.#a=r.PAYLOADLENGTH_16}else if(s===127){this.#a=r.PAYLOADLENGTH_64}if(this.#c.fragmented&&s>125){d(this.ws,"Fragmented frame exceeded 125 bytes.");return}else if((this.#c.opcode===A.PING||this.#c.opcode===A.PONG||this.#c.opcode===A.CLOSE)&&s>125){d(this.ws,"Payload length for control frame exceeded 125 bytes.");return}else if(this.#c.opcode===A.CLOSE){if(s===1){d(this.ws,"Received close frame with a 1-byte body.");return}const e=this.consume(s);this.#c.closeInfo=this.parseCloseBody(false,e);if(!this.ws[l]){const e=Buffer.allocUnsafe(2);e.writeUInt16BE(this.#c.closeInfo.code,0);const t=new f(e);this.ws[u].socket.write(t.createFrame(A.CLOSE),(e=>{if(!e){this.ws[l]=true}}))}this.ws[c]=o.CLOSING;this.ws[h]=true;this.end();return}else if(this.#c.opcode===A.PING){const t=this.consume(s);if(!this.ws[h]){const e=new f(t);this.ws[u].socket.write(e.createFrame(A.PONG));if(E.ping.hasSubscribers){E.ping.publish({payload:t})}}this.#a=r.INFO;if(this.#o>0){continue}else{e();return}}else if(this.#c.opcode===A.PONG){const t=this.consume(s);if(E.pong.hasSubscribers){E.pong.publish({payload:t})}if(this.#o>0){continue}else{e();return}}}else if(this.#a===r.PAYLOADLENGTH_16){if(this.#o<2){return e()}const t=this.consume(2);this.#c.payloadLength=t.readUInt16BE(0);this.#a=r.READ_DATA}else if(this.#a===r.PAYLOADLENGTH_64){if(this.#o<8){return e()}const t=this.consume(8);const s=t.readUInt32BE(0);if(s>2**31-1){d(this.ws,"Received payload length > 2^31 bytes.");return}const i=t.readUInt32BE(4);this.#c.payloadLength=(s<<8)+i;this.#a=r.READ_DATA}else if(this.#a===r.READ_DATA){if(this.#o<this.#c.payloadLength){return e()}else if(this.#o>=this.#c.payloadLength){const e=this.consume(this.#c.payloadLength);this.#l.push(e);if(!this.#c.fragmented||this.#c.fin&&this.#c.opcode===A.CONTINUATION){const e=Buffer.concat(this.#l);g(this.ws,this.#c.originalOpcode,e);this.#c={};this.#l.length=0}this.#a=r.INFO}}if(this.#o>0){continue}else{e();break}}}consume(e){if(e>this.#o){return null}else if(e===0){return a}if(this.#A[0].length===e){this.#o-=this.#A[0].length;return this.#A.shift()}const t=Buffer.allocUnsafe(e);let s=0;while(s!==e){const i=this.#A[0];const{length:n}=i;if(n+s===e){t.set(this.#A.shift(),s);break}else if(n+s>e){t.set(i.subarray(0,e-s),s);this.#A[0]=i.subarray(e-s);break}else{t.set(this.#A.shift(),s);s+=i.length}}this.#o-=e;return t}parseCloseBody(e,t){let s;if(t.length>=2){s=t.readUInt16BE(0)}if(e){if(!p(s)){return null}return{code:s}}let i=t.subarray(2);if(i[0]===239&&i[1]===187&&i[2]===191){i=i.subarray(3)}if(s!==undefined&&!p(s)){return null}try{i=new TextDecoder("utf-8",{fatal:true}).decode(i)}catch{return null}return{code:s,reason:i}}get closingInfo(){return this.#c.closeInfo}}e.exports={ByteParser:ByteParser}},2933:e=>{"use strict";e.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}},3574:(e,t,s)=>{"use strict";const{kReadyState:i,kController:n,kResponse:r,kBinaryType:A,kWebSocketURL:o}=s(2933);const{states:a,opcodes:c}=s(5913);const{MessageEvent:l,ErrorEvent:u}=s(6255);function isEstablished(e){return e[i]===a.OPEN}function isClosing(e){return e[i]===a.CLOSING}function isClosed(e){return e[i]===a.CLOSED}function fireEvent(e,t,s=Event,i){const n=new s(e,i);t.dispatchEvent(n)}function websocketMessageReceived(e,t,s){if(e[i]!==a.OPEN){return}let n;if(t===c.TEXT){try{n=new TextDecoder("utf-8",{fatal:true}).decode(s)Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/
const f=g(9896);const p=g(857);const E=g(6928);const C=g(6982);const B={fs:f.constants,os:p.constants};const Q="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",I=/XXXXXX/,y=3,b=(B.O_CREAT||B.fs.O_CREAT)|(B.O_EXCL||B.fs.O_EXCL)|(B.O_RDWR||B.fs.O_RDWR),k=p.platform()==="win32",D=B.EBADF||B.os.errno.EBADF,R=B.ENOENT||B.os.errno.ENOENT,S=448,v=384,F="exit",x=[],U=f.rmdirSync.bind(f);let L=false;function rimraf(A,i){return f.rm(A,{recursive:true},i)}function FN_RIMRAF_SYNC(A){return f.rmSync(A,{recursive:true})}function tmpName(A,i){const g=_parseArguments(A,i),p=g[0],E=g[1];_assertAndSanitizeOptions(p,function(A,i){if(A)return E(A);let g=i.tries;(function _getUniqueName(){try{const A=_generateTmpName(i);f.stat(A,function(i){if(!i){if(g-- >0)return _getUniqueName();return E(new Error("Could not get a unique tmp filename, max tries reached "+A))}E(null,A)})}catch(A){E(A)}})()})}function tmpNameSync(A){const i=_parseArguments(A),g=i[0];const p=_assertAndSanitizeOptionsSync(g);let E=p.tries;do{const A=_generateTmpName(p);try{f.statSync(A)}catch(i){return A}}while(E-- >0);throw new Error("Could not get a unique tmp filename, max tries reached")}function file(A,i){const g=_parseArguments(A,i),p=g[0],E=g[1];tmpName(p,function _tmpNameCreated(A,i){if(A)return E(A);f.open(i,b,p.mode||v,function _fileCreated(A,g){if(A)return E(A);if(p.discardDescriptor){return f.close(g,function _discardCallback(A){return E(A,i,undefined,_prepareTmpFileRemoveCallback(i,-1,p,false))})}else{const A=p.discardDescriptor||p.detachDescriptor;E(null,i,g,_prepareTmpFileRemoveCallback(i,A?-1:g,p,false))}})})}function fileSync(A){const i=_parseArguments(A),g=i[0];const p=g.discardDescriptor||g.detachDescriptor;const E=tmpNameSync(g);let C=f.openSync(E,b,g.mode||v);if(g.discardDescriptor){f.closeSync(C);C=undefined}return{name:E,fd:C,removeCallback:_prepareTmpFileRemoveCallback(E,p?-1:C,g,true)}}function dir(A,i){const g=_parseArguments(A,i),p=g[0],E=g[1];tmpName(p,function _tmpNameCreated(A,i){if(A)return E(A);f.mkdir(i,p.mode||S,function _dirCreated(A){if(A)return E(A);E(null,i,_prepareTmpDirRemoveCallback(i,p,false))})})}function dirSync(A){const i=_parseArguments(A),g=i[0];const p=tmpNameSync(g);f.mkdirSync(p,g.mode||S);return{name:p,removeCallback:_prepareTmpDirRemoveCallback(p,g,true)}}function _removeFileAsync(A,i){const _handler=function(A){if(A&&!_isENOENT(A)){return i(A)}i()};if(0<=A[0])f.close(A[0],function(){f.unlink(A[1],_handler)});else f.unlink(A[1],_handler)}function _removeFileSync(A){let i=null;try{if(0<=A[0])f.closeSync(A[0])}catch(A){if(!_isEBADF(A)&&!_isENOENT(A))throw A}finally{try{f.unlinkSync(A[1])}catch(A){if(!_isENOENT(A))i=A}}if(i!==null){throw i}}function _prepareTmpFileRemoveCallback(A,i,g,f){const p=_prepareRemoveCallback(_removeFileSync,[i,A],f);const E=_prepareRemoveCallback(_removeFileAsync,[i,A],f,p);if(!g.keep)x.unshift(p);return f?p:E}function _prepareTmpDirRemoveCallback(A,i,g){const p=i.unsafeCleanup?rimraf:f.rmdir.bind(f);const E=i.unsafeCleanup?FN_RIMRAF_SYNC:U;const C=_prepareRemoveCallback(E,A,g);const B=_prepareRemoveCallback(p,A,g,C);if(!i.keep)x.unshift(C);return g?C:B}function _prepareRemoveCallback(A,i,g,f){let p=false;return function _cleanupCallback(E){if(!p){const C=f||_cleanupCallback;const B=x.indexOf(C);if(B>=0)x.splice(B,1);p=true;if(g||A===U||A===FN_RIMRAF_SYNC){return A(i)}else{return A(i,E||function(){})}}}}function _garbageCollector(){if(!L)return;while(x.length){try{x[0]()}catch(A){}}}function _randomChars(A){let i=[],g=null;try{g=C.randomBytes(A)}catch(i){g=C.pseudoRandomBytes(A)}for(let f=0;f<A;f++){i.push(Q[g[f]%Q.length])}return i.join("")}function _isUndefined(A){return typeof A==="undefined"}function _parseArguments(A,i){if(typeof A==="function"){return[{},A]}if(_isUndefined(A)){return[{},i]}const g={};for(const i of Object.getOwnPropertyNames(A)){g[i]=A[i]}return[g,i]}function _resolvePath(A,i,g){const p=E.isAbsolute(A)?A:E.join(i,A);f.stat(p,function(A){if(A){f.realpath(E.dirname(p),function(A,i){if(A)return g(A);g(null,E.join(i,E.basename(p)))})}else{f.realpath(p,g)}})}function _resolvePathSync(A,i){const g=E.isAbsolute(A)?A:E.join(i,A);try{f.statSync(g);return f.realpathSync(g)}catch(A){const i=f.realpathSync(E.dirname(g));return E.join(i,E.basename(g))}}function _generateTmpName(A){const i=A.tmpdir;if(!_isUndefined(A.name)){return E.join(i,A.dir,A.name)}if(!_isUndefined(A.template)){return E.join(i,A.dir,A.template).replace(I,_randomChars(6))}const g=[A.prefix?A.prefix:"tmp","-",process.pid,"-",_randomChars(12),A.postfix?"-"+A.postfix:""].join("");return E.join(i,A.dir,g)}function _assertPath(A,i){if(typeof i!=="string"){throw new Error(`${A} option must be a string, got "${typeof i}".`)}if(i.includes("..")){throw new Error("Relative value not allowed")}return i}function _assertOptionsBase(A){if(!_isUndefined(A.name)){const i=A.name;if(E.isAbsolute(i))throw new Error(`name option must not contain an absolute path, found "${i}".`);const g=E.basename(i);if(g===".."Line truncated
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=A=>A.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=A=>A.replace(/\r?\n|\r/g,"\r\n");const f=[];const p=new Uint8Array([13,10]);b=0;let E=false;for(const[i,C]of A){if(typeof C==="string"){const A=V.encode(g+`; name="${escape(normalizeLinefeeds(i))}"`+`\r\n\r\n${normalizeLinefeeds(C)}\r\n`);f.push(A);b+=A.byteLength}else{const A=V.encode(`${g}; name="${escape(normalizeLinefeeds(i))}"`+(C.name?`; filename="${escape(C.name)}"`:"")+"\r\n"+`Content-Type: ${C.type||"application/octet-stream"}\r\n\r\n`);f.push(A,C,p);if(typeof C.size==="number"){b+=A.byteLength+C.size+p.byteLength}else{E=true}}}const C=V.encode(`--${i}--`);f.push(C);b+=C.byteLength;if(E){b=null}y=A;I=async function*(){for(const A of f){if(A.stream){yield*A.stream()}else{yield A}}};k="multipart/form-data; boundary="+i}else if(C(A)){y=A;b=A.size;if(A.type){k=A.type}}else if(typeof A[Symbol.asyncIterator]==="function"){if(i){throw new TypeError("keepalive")}if(p.isDisturbed(A)||A.locked){throw new TypeError("Response body object should not be disturbed or locked")}f=A instanceof J?A:E(A)}if(typeof y==="string"||p.isBuffer(y)){b=Buffer.byteLength(y)}if(I!=null){let i;f=new J({async start(){i=I(A)[Symbol.asyncIterator]()},async pull(A){const{value:g,done:p}=await i.next();if(p){queueMicrotask(()=>{A.close()})}else{if(!L(f)){A.enqueue(new Uint8Array(g))}}return A.desiredSize>0},async cancel(A){await i.return()},type:undefined})}const D={stream:f,source:y,length:b};return[D,k]}function safelyExtractBody(A,i=false){if(!J){J=g(3774).ReadableStream}if(A instanceof J){U(!p.isDisturbed(A),"The body has already been consumed.");U(!A.locked,"The stream is locked.")}return extractBody(A,i)}function cloneBody(A){const[i,g]=A.stream.tee();const f=S(g,{transfer:[g]});const[,p]=f.tee();A.stream=i;return{stream:p,length:A.length,source:A.source}}async function*consumeBody(A){if(A){if(M(A)){yield A}else{const i=A.stream;if(p.isDisturbed(i)){throw new TypeError("The body has already been consumed.")}if(i.locked){throw new TypeError("The stream is locked.")}i[x]=true;yield*i}}}function throwIfAborted(A){if(A.aborted){throw new R("The operation was aborted.","AbortError")}}function bodyMixinMethods(A){const i={blob(){return specConsumeBody(this,A=>{let i=bodyMimeType(this);if(i==="failure"){i=""}else if(i){i=G(i)}return new v([A],{type:i})},A)},arrayBuffer(){return specConsumeBody(this,A=>new Uint8Array(A).buffer,A)},text(){return specConsumeBody(this,utf8DecodeBytes,A)},json(){return specConsumeBody(this,parseJSONFromBytes,A)},async formData(){D.brandCheck(this,A);throwIfAborted(this[k]);const i=this.headers.get("Content-Type");if(/multipart\/form-data/.test(i)){const A={};for(const[i,g]of this.headers)A[i.toLowerCase()]=g;const i=new b;let g;try{g=new f({headers:A,preservePath:true})}catch(A){throw new R(`${A}`,"AbortError")}g.on("field",(A,g)=>{i.append(A,g)});g.on("file",(A,g,f,p,E)=>{const C=[];if(p==="base64"||p.toLowerCase()==="base64"){let p="";g.on("data",A=>{p+=A.toString().replace(/[\r\n]/gm,"");const i=p.length-p.length%4;C.push(Buffer.from(p.slice(0,i),"base64"));p=p.slice(i)});g.on("end",()=>{C.push(Buffer.from(p,"base64"));i.append(A,new P(C,f,{type:E}))})}else{g.on("data",A=>{C.push(A)});g.on("end",()=>{i.append(A,new P(C,f,{type:E}))})}});const p=new Promise((A,i)=>{g.on("finish",A);g.on("error",A=>i(new TypeError(A)))});if(this.body!==null)for await(const A of consumeBody(this[k].body))g.write(A);g.end();await p;return i}else if(/application\/x-www-form-urlencoded/.test(i)){let A;try{let i="";const g=new TextDecoder("utf-8",{ignoreBOM:true});for await(const A of consumeBody(this[k].body)){if(!M(A)){throw new TypeError("Expected Uint8Array chunk")}i+=g.decode(A,{stream:true})}i+=g.decode();A=new URLSearchParams(i)}catch(A){throw Object.assign(new TypeError,{cause:A})}const i=new b;for(const[g,f]of A){i.append(g,f)}return i}else{await Promise.resolve();throwIfAborted(this[k]);throw D.errors.exception({header:`${A.name}.formData`,message:"Could not parse content as FormData."})}}};return i}function mixinBody(A){Object.assign(A.prototype,bodyMixinMethods(A))}async function specConsumeBody(A,i,g){D.brandCheck(A,g);throwIfAborted(A[k]);if(bodyUnusable(A[k].body)){throw new TypeError("Body is unusable")}const f=I();const errorSteps=A=>f.reject(A);const successSteps=A=>{try{f.resolve(i(A))}catch(A){errorSteps(A)}};if(A[k].body==null){successSteps(new Uint8Array);return f.promise}await y(A[k].body,successSteps,errorSteps);return f.promise}function bodyUnusable(A){return A!=null&&(A.stream.locked||p.isDisturbed(A.stream))}function utf8DecodeBytes(A){if(A.length===0){return""}if(A[0]===239&&A[1]===187&&A[2]===191){A=A.subarray(3)}const i=j.decode(A);return i}function parseJSONFromBytes(A){return JSON.parse(utf8DecodeBytes(A))}function bodyMimeType(A){const{headersList:i}=A[k];const g=i.get("content-type");if(g===null){reLine truncated
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */E[p-4]=this.maskKey[0];E[p-3]=this.maskKey[1];E[p-2]=this.maskKey[2];E[p-1]=this.maskKey[3];E[1]=g;if(g===126){E.writeUInt16BE(i,2)}else if(g===127){E[2]=E[3]=0;E.writeUIntBE(i,4,6)}E[1]|=128;for(let A=0;A<i;A++){E[p+A]=this.frameData[A]^this.maskKey[A%4]}return E}}A.exports={WebsocketFrameSend:WebsocketFrameSend}},5080:(A,i,g)=>{const{Writable:f}=g(2203);const p=g(1637);const{parserStates:E,opcodes:C,states:B,emptyBuffer:Q}=g(8551);const{kReadyState:I,kSentClose:y,kResponse:b,kReceivedClose:k}=g(327);const{isValidStatusCode:D,failWebsocketConnection:R,websocketMessageReceived:S}=g(1501);const{WebsocketFrameSend:v}=g(9140);const F={};F.ping=p.channel("undici:websocket:ping");F.pong=p.channel("undici:websocket:pong");class ByteParser extends f{#i=[];#o=0;#a=E.INFO;#c={};#l=[];constructor(A){super();this.ws=A}_write(A,i,g){this.#i.push(A);this.#o+=A.length;this.run(g)}run(A){while(true){if(this.#a===E.INFO){if(this.#o<2){return A()}const i=this.consume(2);this.#c.fin=(i[0]&128)!==0;this.#c.opcode=i[0]&15;this.#c.originalOpcode??=this.#c.opcode;this.#c.fragmented=!this.#c.fin&&this.#c.opcode!==C.CONTINUATION;if(this.#c.fragmented&&this.#c.opcode!==C.BINARY&&this.#c.opcode!==C.TEXT){R(this.ws,"Invalid frame type was fragmented.");return}const g=i[1]&127;if(g<=125){this.#c.payloadLength=g;this.#a=E.READ_DATA}else if(g===126){this.#a=E.PAYLOADLENGTH_16}else if(g===127){this.#a=E.PAYLOADLENGTH_64}if(this.#c.fragmented&&g>125){R(this.ws,"Fragmented frame exceeded 125 bytes.");return}else if((this.#c.opcode===C.PING||this.#c.opcode===C.PONG||this.#c.opcode===C.CLOSE)&&g>125){R(this.ws,"Payload length for control frame exceeded 125 bytes.");return}else if(this.#c.opcode===C.CLOSE){if(g===1){R(this.ws,"Received close frame with a 1-byte body.");return}const A=this.consume(g);this.#c.closeInfo=this.parseCloseBody(false,A);if(!this.ws[y]){const A=Buffer.allocUnsafe(2);A.writeUInt16BE(this.#c.closeInfo.code,0);const i=new v(A);this.ws[b].socket.write(i.createFrame(C.CLOSE),A=>{if(!A){this.ws[y]=true}})}this.ws[I]=B.CLOSING;this.ws[k]=true;this.end();return}else if(this.#c.opcode===C.PING){const i=this.consume(g);if(!this.ws[k]){const A=new v(i);this.ws[b].socket.write(A.createFrame(C.PONG));if(F.ping.hasSubscribers){F.ping.publish({payload:i})}}this.#a=E.INFO;if(this.#o>0){continue}else{A();return}}else if(this.#c.opcode===C.PONG){const i=this.consume(g);if(F.pong.hasSubscribers){F.pong.publish({payload:i})}if(this.#o>0){continue}else{A();return}}}else if(this.#a===E.PAYLOADLENGTH_16){if(this.#o<2){return A()}const i=this.consume(2);this.#c.payloadLength=i.readUInt16BE(0);this.#a=E.READ_DATA}else if(this.#a===E.PAYLOADLENGTH_64){if(this.#o<8){return A()}const i=this.consume(8);const g=i.readUInt32BE(0);if(g>2**31-1){R(this.ws,"Received payload length > 2^31 bytes.");return}const f=i.readUInt32BE(4);this.#c.payloadLength=(g<<8)+f;this.#a=E.READ_DATA}else if(this.#a===E.READ_DATA){if(this.#o<this.#c.payloadLength){return A()}else if(this.#o>=this.#c.payloadLength){const A=this.consume(this.#c.payloadLength);this.#l.push(A);if(!this.#c.fragmented||this.#c.fin&&this.#c.opcode===C.CONTINUATION){const A=Buffer.concat(this.#l);S(this.ws,this.#c.originalOpcode,A);this.#c={};this.#l.length=0}this.#a=E.INFO}}if(this.#o>0){continue}else{A();break}}}consume(A){if(A>this.#o){return null}else if(A===0){return Q}if(this.#i[0].length===A){this.#o-=this.#i[0].length;return this.#i.shift()}const i=Buffer.allocUnsafe(A);let g=0;while(g!==A){const f=this.#i[0];const{length:p}=f;if(p+g===A){i.set(this.#i.shift(),g);break}else if(p+g>A){i.set(f.subarray(0,A-g),g);this.#i[0]=f.subarray(A-g);break}else{i.set(this.#i.shift(),g);g+=f.length}}this.#o-=A;return i}parseCloseBody(A,i){let g;if(i.length>=2){g=i.readUInt16BE(0)}if(A){if(!D(g)){return null}return{code:g}}let f=i.subarray(2);if(f[0]===239&&f[1]===187&&f[2]===191){f=f.subarray(3)}if(g!==undefined&&!D(g)){return null}try{f=new TextDecoder("utf-8",{fatal:true}).decode(f)}catch{return null}return{code:g,reason:f}}get closingInfo(){return this.#c.closeInfo}}A.exports={ByteParser:ByteParser}},327:A=>{A.exports={kWebSocketURL:Symbol("url"),kReadyState:Symbol("ready state"),kController:Symbol("controller"),kResponse:Symbol("response"),kBinaryType:Symbol("binary type"),kSentClose:Symbol("sent close"),kReceivedClose:Symbol("received close"),kByteParser:Symbol("byte parser")}},1501:(A,i,g)=>{const{kReadyState:f,kController:p,kResponse:E,kBinaryType:C,kWebSocketURL:B}=g(327);const{states:Q,opcodes:I}=g(8551);const{MessageEvent:y,ErrorEvent:b}=g(7952);function isEstablished(A){return A[f]===Q.OPEN}function isClosing(A){return A[f]===Q.CLOSING}function isClosed(A){return A[f]===Q.CLOSED}function fireEvent(A,i,g=Event,f){const p=new g(A,f);i.dispatchEvent(p)}function websocketMessageReceived(A,i,g){if(A[f]!==Q.OPEN){return}let p;if(i===I.TEXT){try{p=new TextDecoder("utf-8",{fatal:true}).decode(g)}catch{failWebsocketConnection(A,"Received iLine truncated
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */;const escape=A=>A.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22");const normalizeLinefeeds=A=>A.replace(/\r?\n|\r/g,"\r\n");const f=[];const p=new Uint8Array([13,10]);y=0;let E=false;for(const[i,C]of A){if(typeof C==="string"){const A=H.encode(g+`; name="${escape(normalizeLinefeeds(i))}"`+`\r\n\r\n${normalizeLinefeeds(C)}\r\n`);f.push(A);y+=A.byteLength}else{const A=H.encode(`${g}; name="${escape(normalizeLinefeeds(i))}"`+(C.name?`; filename="${escape(C.name)}"`:"")+"\r\n"+`Content-Type: ${C.type||"application/octet-stream"}\r\n\r\n`);f.push(A,C,p);if(typeof C.size==="number"){y+=A.byteLength+C.size+p.byteLength}else{E=true}}}const C=H.encode(`--${i}--\r\n`);f.push(C);y+=C.byteLength;if(E){y=null}I=A;Q=async function*(){for(const A of f){if(A.stream){yield*A.stream()}else{yield A}}};b=`multipart/form-data; boundary=${i}`}else if(E(A)){I=A;y=A.size;if(A.type){b=A.type}}else if(typeof A[Symbol.asyncIterator]==="function"){if(i){throw new TypeError("keepalive")}if(f.isDisturbed(A)||A.locked){throw new TypeError("Response body object should not be disturbed or locked")}g=A instanceof ReadableStream?A:p(A)}if(typeof I==="string"||f.isBuffer(I)){y=Buffer.byteLength(I)}if(Q!=null){let i;g=new ReadableStream({async start(){i=Q(A)[Symbol.asyncIterator]()},async pull(A){const{value:f,done:p}=await i.next();if(p){queueMicrotask(()=>{A.close();A.byobRequest?.respond(0)})}else{if(!F(g)){const i=new Uint8Array(f);if(i.byteLength){A.enqueue(i)}}}return A.desiredSize>0},async cancel(A){await i.return()},type:"bytes"})}const k={stream:g,source:I,length:y};return[k,b]}function safelyExtractBody(A,i=false){if(A instanceof ReadableStream){v(!f.isDisturbed(A),"The body has already been consumed.");v(!A.locked,"The stream is locked.")}return extractBody(A,i)}function cloneBody(A,i){const[g,f]=i.stream.tee();i.stream=g;return{stream:f,length:i.length,source:i.source}}function throwIfAborted(A){if(A.aborted){throw new DOMException("The operation was aborted.","AbortError")}}function bodyMixinMethods(A){const i={blob(){return consumeBody(this,A=>{let i=bodyMimeType(this);if(i===null){i=""}else if(i){i=L(i)}return new S([A],{type:i})},A)},arrayBuffer(){return consumeBody(this,A=>new Uint8Array(A).buffer,A)},text(){return consumeBody(this,b,A)},json(){return consumeBody(this,parseJSONFromBytes,A)},formData(){return consumeBody(this,A=>{const i=bodyMimeType(this);if(i!==null){switch(i.essence){case"multipart/form-data":{const g=M(A,i);if(g==="failure"){throw new TypeError("Failed to parse body as FormData.")}const f=new k;f[D]=g;return f}case"application/x-www-form-urlencoded":{const i=new URLSearchParams(A.toString());const g=new k;for(const[A,f]of i){g.append(A,f)}return g}}}throw new TypeError('Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".')},A)},bytes(){return consumeBody(this,A=>new Uint8Array(A),A)}};return i}function mixinBody(A){Object.assign(A.prototype,bodyMixinMethods(A))}async function consumeBody(A,i,g){R.brandCheck(A,g);if(bodyUnusable(A)){throw new TypeError("Body is unusable: Body has already been read")}throwIfAborted(A[D]);const f=Q();const errorSteps=A=>f.reject(A);const successSteps=A=>{try{f.resolve(i(A))}catch(A){errorSteps(A)}};if(A[D].body==null){successSteps(Buffer.allocUnsafe(0));return f.promise}await I(A[D].body,successSteps,errorSteps);return f.promise}function bodyUnusable(A){const i=A[D].body;return i!=null&&(i.stream.locked||f.isDisturbed(i.stream))}function parseJSONFromBytes(A){return JSON.parse(b(A))}function bodyMimeType(A){const i=A[D].headersList;const g=y(i);if(g==="failure"){return null}return g}A.exports={extractBody:extractBody,safelyExtractBody:safelyExtractBody,cloneBody:cloneBody,mixinBody:mixinBody,streamRegistry:G,hasFinalizationRegistry:_,bodyUnusable:bodyUnusable}},4578:A=>{const i=["GET","HEAD","POST"];const g=new Set(i);const f=[101,204,205,304];const p=[301,302,303,307,308];const E=new Set(p);const C=["1","7","9","11","13","15","17","19","20","21","22","23","25","37","42","43","53","69","77","79","87","95","101","102","103","104","109","110","111","113","115","117","119","123","135","137","139","143","161","179","389","427","465","512","513","514","515","526","530","531","532","540","548","554","556","563","587","601","636","989","990","993","995","1719","1720","1723","2049","3659","4045","4190","5060","5061","6000","6566","6665","6666","6667","6668","6669","6679","6697","10080"];const B=new Set(C);const Q=["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"];const I=new Set(Q);const y=["follow","manual","error"];const b=["GET","HEAD","OPTIONS","TRACE"];const k=new Set(b);const D=["navigate","same-origin","no-cors","cors"];const R=["omit","same-origin","include"];const S=["default","no-store","reload","no-cache","force-cache","onlLine truncated
/*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> */B[C-4]=g[0];B[C-3]=g[1];B[C-2]=g[2];B[C-1]=g[3];B[1]=E;if(E===126){B.writeUInt16BE(p,2)}else if(E===127){B[2]=B[3]=0;B.writeUIntBE(p,4,6)}B[1]|=128;for(let A=0;A<p;++A){B[C+A]=i[A]^g[A&3]}return B}}A.exports={WebsocketFrameSend:WebsocketFrameSend}},6286:(A,i,g)=>{const{createInflateRaw:f,Z_DEFAULT_WINDOWBITS:p}=g(8522);const{isValidClientWindowBits:E}=g(8098);const{MessageSizeExceededError:C}=g(6246);const B=Buffer.from([0,0,255,255]);const Q=Symbol("kBuffer");const I=Symbol("kLength");class PerMessageDeflate{#ne;#S={};#re=0;constructor(A,i){this.#S.serverNoContextTakeover=A.has("server_no_context_takeover");this.#S.serverMaxWindowBits=A.get("server_max_window_bits");this.#re=i.maxPayloadSize}decompress(A,i,g){if(!this.#ne){let A=p;if(this.#S.serverMaxWindowBits){if(!E(this.#S.serverMaxWindowBits)){g(new Error("Invalid server_max_window_bits"));return}A=Number.parseInt(this.#S.serverMaxWindowBits)}try{this.#ne=f({windowBits:A})}catch(A){g(A);return}this.#ne[Q]=[];this.#ne[I]=0;this.#ne.on("data",A=>{this.#ne[I]+=A.length;if(this.#re>0&&this.#ne[I]>this.#re){g(new C);this.#ne.removeAllListeners();this.#ne=null;return}this.#ne[Q].push(A)});this.#ne.on("error",A=>{this.#ne=null;g(A)})}this.#ne.write(A);if(i){this.#ne.write(B)}this.#ne.flush(()=>{if(!this.#ne){return}const A=Buffer.concat(this.#ne[Q],this.#ne[I]);this.#ne[Q].length=0;this.#ne[I]=0;g(null,A)})}}A.exports={PerMessageDeflate:PerMessageDeflate}},5975:(A,i,g)=>{const{Writable:f}=g(7075);const p=g(4589);const{parserStates:E,opcodes:C,states:B,emptyBuffer:Q,sentCloseFrameState:I}=g(8397);const{kReadyState:y,kSentClose:b,kResponse:k,kReceivedClose:D}=g(7609);const{channels:R}=g(9978);const{isValidStatusCode:S,isValidOpcode:v,failWebsocketConnection:F,websocketMessageReceived:x,utf8Decode:U,isControlFrame:L,isTextBinaryFrame:M,isContinuationFrame:T}=g(8098);const{WebsocketFrameSend:H}=g(9321);const{closeWebSocketConnection:_}=g(1874);const{PerMessageDeflate:G}=g(6286);const{MessageSizeExceededError:Y}=g(6246);function failWebsocketConnectionWithCode(A,i,g){_(A,i,g,Buffer.byteLength(g));F(A,g)}class ByteParser extends f{#i=[];#ie=0;#o=0;#oe=false;#a=E.INFO;#c={};#l=[];#d;#ae;#re;constructor(A,i,g={}){super();this.ws=A;this.#d=i==null?new Map:i;this.#ae=g.maxFragments??0;this.#re=g.maxPayloadSize??0;if(this.#d.has("permessage-deflate")){this.#d.set("permessage-deflate",new G(i,g))}}_write(A,i,g){this.#i.push(A);this.#o+=A.length;this.#oe=true;this.run(g)}#ce(){if(this.#re>0&&!L(this.#c.opcode)&&this.#c.payloadLength+this.#ie>this.#re){failWebsocketConnectionWithCode(this.ws,1009,"Payload size exceeds maximum allowed size");return false}return true}run(A){while(this.#oe){if(this.#a===E.INFO){if(this.#o<2){return A()}const i=this.consume(2);const g=(i[0]&128)!==0;const f=i[0]&15;const p=(i[1]&128)===128;const B=!g&&f!==C.CONTINUATION;const Q=i[1]&127;const I=i[0]&64;const y=i[0]&32;const b=i[0]&16;if(!v(f)){F(this.ws,"Invalid opcode received");return A()}if(p){F(this.ws,"Frame cannot be masked");return A()}if(I!==0&&!this.#d.has("permessage-deflate")){F(this.ws,"Expected RSV1 to be clear.");return}if(y!==0||b!==0){F(this.ws,"RSV1, RSV2, RSV3 must be clear");return}if(B&&!M(f)){F(this.ws,"Invalid frame type was fragmented.");return}if(M(f)&&this.#l.length>0){F(this.ws,"Expected continuation frame");return}if(this.#c.fragmented&&B){F(this.ws,"Fragmented frame exceeded 125 bytes.");return}if((Q>125||B)&&L(f)){F(this.ws,"Control frame either too large or fragmented");return}if(T(f)&&this.#l.length===0&&!this.#c.compressed){F(this.ws,"Unexpected continuation frame");return}if(Q<=125){this.#c.payloadLength=Q;this.#a=E.READ_DATA;if(!this.#ce()){return}}else if(Q===126){this.#a=E.PAYLOADLENGTH_16}else if(Q===127){this.#a=E.PAYLOADLENGTH_64}if(M(f)){this.#c.binaryType=f;this.#c.compressed=I!==0}this.#c.opcode=f;this.#c.masked=p;this.#c.fin=g;this.#c.fragmented=B}else if(this.#a===E.PAYLOADLENGTH_16){if(this.#o<2){return A()}const i=this.consume(2);this.#c.payloadLength=i.readUInt16BE(0);this.#a=E.READ_DATA;if(!this.#ce()){return}}else if(this.#a===E.PAYLOADLENGTH_64){if(this.#o<8){return A()}const i=this.consume(8);const g=i.readUInt32BE(0);const f=i.readUInt32BE(4);if(g!==0||f>2**31-1){F(this.ws,"Received payload length > 2^31 bytes.");return}this.#c.payloadLength=f;this.#a=E.READ_DATA;if(!this.#ce()){return}}else if(this.#a===E.READ_DATA){if(this.#o<this.#c.payloadLength){return A()}const i=this.consume(this.#c.payloadLength);if(L(this.#c.opcode)){this.#oe=this.parseControlFrame(i);this.#a=E.INFO}else{if(!this.#c.compressed){if(!this.writeFragments(i)){return}if(this.#re>0&&this.#ie>this.#re){failWebsocketConnectionWithCode(this.ws,1009,(new Y).message);return}if(!this.#c.fragmented&&this.#c.fin){x(this.ws,this.#c.binaryType,this.consumeFragments())}this.#a=E.INFO}else{this.#d.get("permessage-deflate").decompress(i,this.#c.fin,(i,g)=>{if(i){const A=i instanceof Y?1009:1007;failWebsocketConnectionWithCLine truncated
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
+38 -158
View File
@@ -1,10 +1,8 @@
import { ScreepsHttpClient } from "screeps-api"; const { ScreepsAPI } = require("screeps-api");
import * as core from "@actions/core"; const core = require("@actions/core");
import fs from "fs"; const fs = require("fs");
import { glob } from "glob"; const { glob } = require("glob");
import path from "path"; const path = require("path");
import { fileURLToPath } from "url";
import { monitorConsole } from "./monitor.js";
/** /**
* Replaces specific placeholder strings within the provided content with corresponding dynamic values. * Replaces specific placeholder strings within the provided content with corresponding dynamic values.
@@ -19,7 +17,7 @@ import { monitorConsole } from "./monitor.js";
* @param {string} content - The string content in which placeholders are to be replaced. * @param {string} content - The string content in which placeholders are to be replaced.
* @returns {string} The content with placeholders replaced by their respective dynamic values. * @returns {string} The content with placeholders replaced by their respective dynamic values.
*/ */
export function replacePlaceholders(content, hostname) { function replacePlaceholders(content, hostname) {
const deployTime = new Date().toISOString(); const deployTime = new Date().toISOString();
return content return content
.replace(/{{gitHash}}/g, process.env.GITHUB_SHA) .replace(/{{gitHash}}/g, process.env.GITHUB_SHA)
@@ -39,9 +37,8 @@ export function replacePlaceholders(content, hostname) {
* @param {string} [prefix] - An optional directory prefix to prepend to the glob pattern. This allows searching within a specific directory. * @param {string} [prefix] - An optional directory prefix to prepend to the glob pattern. This allows searching within a specific directory.
* @returns {Promise<string[]>} A promise that resolves with an array of file paths that were processed, or rejects with an error if the process fails. * @returns {Promise<string[]>} A promise that resolves with an array of file paths that were processed, or rejects with an error if the process fails.
*/ */
export async function readReplaceAndWriteFiles(pattern, prefix, hostname) { async function readReplaceAndWriteFiles(pattern, prefix, hostname) {
let globPattern = prefix ? path.join(prefix, pattern) : pattern; const globPattern = prefix ? path.join(prefix, pattern) : pattern;
globPattern = globPattern.replace(/\\/g, "/");
const files = await glob(globPattern); const files = await glob(globPattern);
let processPromises = files.map((file) => { let processPromises = files.map((file) => {
@@ -61,10 +58,9 @@ export async function readReplaceAndWriteFiles(pattern, prefix, hostname) {
* @param {string} prefix - Directory prefix for file paths. * @param {string} prefix - Directory prefix for file paths.
* @returns {Promise<Object>} - Promise resolving to a dictionary of file contents keyed by filenames. * @returns {Promise<Object>} - Promise resolving to a dictionary of file contents keyed by filenames.
*/ */
export async function readFilesIntoDict(pattern, prefix) { async function readFilesIntoDict(pattern, prefix) {
// Prepend the prefix to the glob pattern // Prepend the prefix to the glob pattern
let globPattern = prefix ? path.join(prefix, pattern) : pattern; const globPattern = prefix ? path.join(prefix, pattern) : pattern;
globPattern = globPattern.replace(/\\/g, "/");
const files = await glob(globPattern); const files = await glob(globPattern);
let fileDict = {}; let fileDict = {};
@@ -92,7 +88,7 @@ export async function readFilesIntoDict(pattern, prefix) {
* @param {string} password - The password. * @param {string} password - The password.
* @returns {string|null} - Returns an error message if validation fails, otherwise null. * @returns {string|null} - Returns an error message if validation fails, otherwise null.
*/ */
export function validateAuthentication(token, username, password) { function validateAuthentication(token, username, password) {
if (token) { if (token) {
if (username || password) { if (username || password) {
return "Token is defined along with username and/or password."; return "Token is defined along with username and/or password.";
@@ -111,32 +107,10 @@ export function validateAuthentication(token, username, password) {
return null; // No errors found return null; // No errors found
} }
/**
* Applies the 'ignore' | 'warn' | 'fail' enum action when the given flag is true.
* Exported so it can be unit-tested independently.
*
* @param {'ignore'|'warn'|'fail'} action
* @param {boolean} flag - Only acts when true
* @param {string} message - Passed to core.warning / core.setFailed
* @returns {boolean} - Returns true if the action was 'fail' and the flag was true.
*/
export function applyOnAction(action, flag, message) {
if (!flag) return false;
if (action === "warn") {
core.warning(message);
return false;
}
if (action === "fail") {
core.setFailed(message);
return true;
}
return false;
}
/** /**
* Posts code to Screeps server. * Posts code to Screeps server.
*/ */
export async function postCode() { async function postCode() {
const protocol = core.getInput("protocol") || "https"; const protocol = core.getInput("protocol") || "https";
const hostname = core.getInput("hostname") || "screeps.com"; const hostname = core.getInput("hostname") || "screeps.com";
const port = core.getInput("port") || "443"; const port = core.getInput("port") || "443";
@@ -180,129 +154,35 @@ export async function postCode() {
core.error(errorMessage); core.error(errorMessage);
return; return;
} }
let api = new ScreepsHttpClient(login_arguments); let api = new ScreepsAPI(login_arguments);
if (token) {
if (!token) { const response = await api.code.set(branch, files_to_push);
core.info(`Logging in as user ${username}`);
try {
if (typeof api.authSignin === "function") {
await api.authSignin(username, password);
} else {
await api.auth(username, password, login_arguments);
}
} catch (err) {
core.error(`Authentication error: ${err}`);
throw err;
}
}
let oldCode = null;
let rollbackOnFailure = false;
try {
rollbackOnFailure = core.getBooleanInput("rollback_on_failure");
} catch (e) {
// getBooleanInput throws if not 'true' or 'false', ignore
}
if (rollbackOnFailure) {
core.info(
`Downloading existing code from branch ${branch} for potential rollback...`,
);
try {
const getResponse = await (api.userCodeGet
? api.userCodeGet(branch)
: api.code.get(branch));
if (getResponse && getResponse.ok && getResponse.modules) {
oldCode = getResponse.modules;
core.info(
`Successfully downloaded existing code (modules: ${Object.keys(oldCode).join(", ")})`,
);
} else {
core.setFailed(
`Failed to download existing code, but rollback_on_failure is enabled. Aborting deployment.`,
);
return;
}
} catch (err) {
core.setFailed(
`Error downloading existing code: ${err.message}. Aborting deployment.`,
);
return;
}
}
try {
const response = await (api.userCodeSet
? api.userCodeSet({ branch, modules: files_to_push })
: api.code.set(branch, files_to_push));
core.info(JSON.stringify(response, null, 2)); core.info(JSON.stringify(response, null, 2));
core.info(`Code set successfully to ${branch}`); console.log(`Code set successfully to ${branch}`);
} catch (err) { } else {
core.error(`Upload error: ${err}`); core.info(`Logging in as user ${username}`);
throw err; await Promise.resolve()
} .then(() => api.auth(username, password, login_arguments))
.then(() => {
// Console monitoring (optional) api.code.set(branch, files_to_push);
const monitorTicks = parseInt(core.getInput("monitor") || "0", 10); })
if (monitorTicks > 0) { .then(() => {
const onTraceback = core.getInput("on_traceback") || "fail"; console.log(`Code set successfully to ${branch}`);
const onErrorLog = core.getInput("on_error_log") || "warn"; })
const onWarningLog = core.getInput("on_warning_log") || "ignore"; .catch((err) => {
console.error("Error:", err);
const result = await monitorConsole(api, { });
monitor: monitorTicks,
logToFile: core.getBooleanInput("log_to_file"),
onTraceback,
onErrorLog,
onWarningLog,
monitorInterval: parseInt(core.getInput("monitor_interval") || "10", 10),
hostname,
shard: core.getInput("shard") || undefined,
});
core.setOutput("saw_traceback", String(result.sawTraceback));
core.setOutput("saw_error_log", String(result.sawErrorLog));
core.setOutput("saw_warning_log", String(result.sawWarningLog));
const fail1 = applyOnAction(
onTraceback,
result.sawTraceback,
"Screeps console: traceback detected",
);
const fail2 = applyOnAction(
onErrorLog,
result.sawErrorLog,
"Screeps console: error log output detected",
);
const fail3 = applyOnAction(
onWarningLog,
result.sawWarningLog,
"Screeps console: warning log output detected",
);
const shouldFail = fail1 || fail2 || fail3;
if (shouldFail && rollbackOnFailure && oldCode) {
core.info(
"Action failed based on monitor configuration. Rolling back to previous code...",
);
try {
if (typeof api.userCodeSet === "function") {
await api.userCodeSet({ branch, modules: oldCode });
} else {
await api.code.set(branch, oldCode);
}
core.info(
`Successfully rolled back to previous code on branch ${branch}.`,
);
} catch (err) {
core.error(`Rollback failed: ${err}`);
}
}
} }
} }
const __filename = fileURLToPath(import.meta.url); if (require.main === module) {
if (process.argv[1] === __filename) {
postCode(); postCode();
} }
module.exports = {
validateAuthentication,
replacePlaceholders,
postCode,
readReplaceAndWriteFiles,
readFilesIntoDict,
};
-424
View File
@@ -1,424 +0,0 @@
import * as core from "@actions/core";
import { create } from "@actions/artifact";
import fs from "fs";
import path from "path";
import os from "os";
/**
* Returns true if the hostname is the official Screeps server.
* Used to decide whether to prefix the subscribe path with a shard name.
*
* @param {string} hostname - e.g. "screeps.com" or "builder64"
* @returns {boolean}
*/
export function isOfficialServer(hostname) {
return hostname === "screeps.com";
}
/**
* Builds the channel path argument passed to socket.subscribe().
*
* The screeps-api socket automatically prefixes `user:<id>/` when the path
* does not match the `type:id` pattern, so we only supply the channel part:
* If shard is provided → "<shard>/console"
* Official server → "shard0/console" (if no shard provided)
* Private server → "console" (if no shard provided)
*
* @param {string} hostname
* @param {string} [shard]
* @returns {string}
*/
export function buildSubscribePath(hostname, shard) {
// The console channel on Screeps official and most private servers is 'console'.
// We subscribe to the aggregate feed and filter by shard in handleConsoleEvent.
return "console";
}
/**
* Returns true when errorText contains JavaScript stack-frame lines.
* Screeps places runtime errors (including stack traces) in event.data.error.
* A traceback is identified by lines beginning with four spaces followed by "at ".
*
* @param {string|null|undefined} errorText - Contents of event.data.error
* @returns {boolean}
*/
export function detectTraceback(errorText) {
if (!errorText) return false;
const text = safeDecode(errorText);
return /^\s{4}at /m.test(text);
}
/**
* Returns true when any log line contains Screeps console.warn markup.
* Screeps wraps console.warn() output in orange or yellow <font> HTML tags.
*
* @param {string[]|null|undefined} logLines - Contents of event.data.messages.log
* @returns {boolean}
*/
export function detectWarning(logLines) {
if (!logLines || logLines.length === 0) return false;
const warnPattern = /<font\s+color=['"](?:orange|yellow)['"]/i;
return logLines.some((line) => warnPattern.test(line));
}
/**
* Safely decodes a URI-encoded string from the Screeps console.
* Returns the original string if decoding fails or if no '%' is present.
*
* @param {string} text
* @returns {string}
*/
export function safeDecode(text) {
if (typeof text !== "string") return text;
let result = text;
if (result.includes("%")) {
try {
result = decodeURIComponent(result);
} catch (err) {
// Ignore decoding errors
}
}
// Screeps console often contains HTML entities
return result
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&");
}
/**
* Outputs text to the action log, splitting by newline to ensure proper display.
* Optionally prepends a [shard] prefix.
*
* @param {string} text
* @param {"info"|"warning"|"error"} level
* @param {string} [shard]
*/
export function outputMultiline(text, level = "info", shard = null) {
if (!text) return;
const prefix = shard ? `[${shard}] ` : "";
const lines = text.split(/\r?\n/);
lines.forEach((line) => {
const formattedLine = `${prefix}${line}`;
if (level === "error") core.error(formattedLine);
else if (level === "warning") core.warning(formattedLine);
else core.info(formattedLine);
});
}
/**
* Builds a CI-friendly progress string for core.info().
*
* @param {number} elapsed - Ticks elapsed since monitoring started
* @param {number} total - Total ticks to monitor
* @returns {string} - e.g. "[Monitor] 10/50 ticks elapsed..."
*/
export function buildProgressMessage(elapsed, total) {
return `[Monitor] ${elapsed}/${total} ticks elapsed...`;
}
/**
* Writes an array of log lines to a UTF-8 text file, one line per entry.
*
* @param {string[]} lines - Lines to write
* @param {string} filePath - Absolute path to write to
* @returns {Promise<void>}
*/
export async function writeLogFile(lines, filePath) {
await fs.promises.writeFile(filePath, lines.join("\n"), "utf8");
}
/**
* Uploads one or more files as a named workflow artifact using @actions/artifact.
* Degrades gracefully to core.warning() if the runner does not support the
* artifact service.
*
* @param {string[]} filePaths - Absolute paths of the files to upload
* @param {string} [artifactName="screeps-console-log"] - Artifact display name
* @returns {Promise<void>}
*/
export async function uploadLogArtifacts(
filePaths,
artifactName = "screeps-console-log",
) {
if (!filePaths || filePaths.length === 0) return;
try {
const client = create();
const rootDir = path.dirname(filePaths[0]);
await client.uploadArtifact(artifactName, filePaths, rootDir, {
continueOnError: true,
});
core.info(`[Monitor] Console logs uploaded as artifact '${artifactName}'.`);
} catch (err) {
core.warning(
`[Monitor] Could not upload console logs as artifact: ${err.message}`,
);
}
}
/**
* Processes a single 'console' WebSocket event from the Screeps socket.
* Mutates `state` and `stdoutBuffer` in place; never throws.
*
* WebSocket event.data shape:
* {
* messages: {
* log: string[], // stdout (console.warn included with HTML markup)
* results: string[], // return values of console-evaluated expressions
* },
* error: string | null, // stderr, runtime errors, tracebacks
* }
*
* Behaviour:
* - Warn lines (orange/yellow <font> tags) → always core.warning() (live),
* sets state.sawWarningLog, still included in stdoutBuffer / core.info().
* - Error field → always core.error() (live), sets state.sawErrorLog.
* If a stack frame is detected → also sets state.sawTraceback.
* - All stdout lines → core.info() when logToFile=false,
* pushed to stdoutBuffer when logToFile=true.
*
* @param {{ data?: { messages?: { log?: string[], results?: string[] }, error?: string, shard?: string } }} event
* @param {{ logToFile: boolean, shard?: string }} opts
* @param {Record<string, string[]>} shardBuffers - Mutable buffer Map used in logToFile mode
* @param {{ sawTraceback: boolean, sawErrorLog: boolean, sawWarningLog: boolean }} state
*/
export function handleConsoleEvent(event, opts, shardBuffers, state) {
const { logToFile, shard: targetShard } = opts;
const data = event?.data ?? {};
// Shard filtering: If a shard is specified in opts, only process messages from that shard.
// Official server events include a 'shard' property in event.data.
if (targetShard && data.shard && data.shard !== targetShard) {
return;
}
const logLines = data?.messages?.log ?? [];
const results = data?.messages?.results ?? [];
const errorText = data?.error ?? null;
// Warn detection (always live regardless of logToFile)
if (detectWarning(logLines)) {
state.sawWarningLog = true;
const warnPattern = /<font\s+color=['"](?:orange|yellow)['"]/i;
logLines
.filter((l) => warnPattern.test(l))
.forEach((l) => outputMultiline(safeDecode(l), "warning", data.shard));
}
// Traceback detection in log lines (Screeps sometimes sends errors here)
if (logLines.some((l) => detectTraceback(l))) {
state.sawTraceback = true;
state.sawErrorLog = true;
}
// Stdout lines
const allStdout = [...logLines, ...results].map(safeDecode);
if (allStdout.length > 0) {
if (logToFile) {
const shard = data.shard || "default";
if (!shardBuffers[shard]) shardBuffers[shard] = [];
shardBuffers[shard].push(...allStdout);
} else {
allStdout.forEach((l) => outputMultiline(l, "info", data.shard));
}
}
// Error field (always live)
if (errorText) {
state.sawErrorLog = true;
const decodedError = safeDecode(errorText);
outputMultiline(decodedError, "error", data.shard);
if (detectTraceback(decodedError)) {
state.sawTraceback = true;
}
}
}
/**
* Sleeps for the given number of milliseconds.
*
* @param {number} ms
* @returns {Promise<void>}
*/
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Polls GET /api/game/time every `intervalMs` milliseconds until the tick
* delta (currentTick - startTick) reaches or exceeds `targetTicks`.
* Calls `onProgress(elapsed, targetTicks)` on every poll so the caller can
* log progress at whatever cadence it chooses.
*
* @param {import('screeps-api').ScreepsHttpClient} api
* @param {number} startTick - Tick number recorded before monitoring started
* @param {number} targetTicks - Stop when (currentTick - startTick) >= this
* @param {string|undefined} shard - "shard0" for official, undefined for private
* @param {number} intervalMs - Poll interval in milliseconds
* @param {(elapsed: number, total: number) => void} onProgress
* @returns {Promise<number>} Final elapsed tick count
*/
export async function pollUntilDone(
api,
startTick,
targetTicks,
shard,
intervalMs,
onProgress,
shouldStop = () => false,
) {
let elapsed = 0;
while (elapsed < targetTicks && !shouldStop()) {
await sleep(intervalMs);
const { time } = await (typeof api.gameTime === "function"
? api.gameTime(shard)
: api.time(shard));
elapsed = time - startTick;
onProgress(elapsed, targetTicks);
}
return elapsed;
}
/**
* @typedef {Object} MonitorOptions
* @property {number} monitor - Number of game ticks to collect.
* @property {boolean} logToFile - Buffer stdout to artifact instead of streaming.
* @property {'ignore'|'warn'|'fail'} onTraceback - Action on traceback detection.
* @property {'ignore'|'warn'|'fail'} onErrorLog - Action on any error-console output.
* @property {'ignore'|'warn'|'fail'} onWarningLog - Action on console.warn output.
* @property {number} monitorInterval - Print a progress update every N ticks.
* @property {string} hostname - Screeps hostname (for shard derivation).
* @property {string} [shard] - Optional shard to monitor.
*/
/**
* @typedef {Object} MonitorResult
* @property {boolean} sawTraceback - True if a JS stack trace was detected.
* @property {boolean} sawErrorLog - True if the error console had any output.
* @property {boolean} sawWarningLog - True if console.warn output was detected.
*/
/**
* Monitors the Screeps console for a given number of game ticks after a deploy.
*
* Flow:
* 1. Fetch startTick via GET /api/game/time (REST poll).
* 2. Connect WebSocket and subscribe to the console channel.
* 3. Run the tick-poll loop (500 ms interval) concurrently with the socket
* event listener; the poll loop drives the stop condition.
* 4. On each 'console' WebSocket event, delegate to handleConsoleEvent().
* 5. When poll finishes, disconnect socket cleanly (in a finally block).
* 6. If logToFile=true: write buffered stdout to a temp file and upload artifact.
* 7. Return MonitorResult.
*
* @param {import('screeps-api').ScreepsHttpClient} api
* @param {MonitorOptions} opts
* @returns {Promise<MonitorResult>}
*/
export async function monitorConsole(api, opts) {
const {
monitor,
logToFile,
monitorInterval,
hostname,
shard: providedShard,
} = opts;
// Use provided shard, or fall back to shard0 for official, or undefined for private
const shard =
providedShard || (isOfficialServer(hostname) ? "shard0" : undefined);
const subscribePath = buildSubscribePath(hostname, providedShard);
// Shared mutable state — updated by handleConsoleEvent via event listener
const shardBuffers = {}; // { [shardName]: string[] }
const state = {
sawTraceback: false,
sawErrorLog: false,
sawWarningLog: false,
};
let lastProgressTick = 0;
// Step 1: record starting tick
const { time: startTick } = await (typeof api.gameTime === "function"
? api.gameTime(shard)
: api.time(shard));
// Step 2: connect socket + subscribe
await api.socket.connect();
await api.socket.subscribe(subscribePath, (event) => {
handleConsoleEvent(event, opts, shardBuffers, state);
});
core.info(
`[Monitor] Watching Screeps console for ${monitor} ticks` +
(shard ? ` on ${shard}` : "") +
"...",
);
// Step 3 & 4: tick-poll loop
try {
await pollUntilDone(
api,
startTick,
monitor,
shard,
500,
(elapsed, total) => {
// Print progress at configured interval boundaries
if (
elapsed > 0 &&
elapsed >= lastProgressTick + monitorInterval &&
elapsed <= total
) {
core.info(buildProgressMessage(elapsed, total));
lastProgressTick = elapsed;
}
},
() => {
// Fail-fast logic: stop monitoring if any 'fail' action is triggered
if (opts.onTraceback === "fail" && state.sawTraceback) return true;
if (opts.onErrorLog === "fail" && state.sawErrorLog) return true;
if (opts.onWarningLog === "fail" && state.sawWarningLog) return true;
return false;
},
);
} finally {
// Step 5: always disconnect cleanly
api.socket.disconnect();
}
// Step 6: artifact upload
const shardKeys = Object.keys(shardBuffers);
if (logToFile && shardKeys.length > 0) {
const tmpDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), "screeps-monitor-"),
);
const filePaths = [];
for (const sName of shardKeys) {
const fileName =
sName === "default"
? "screeps_console_log.txt"
: `${sName}_console_log.txt`;
const tmpFile = path.join(tmpDir, fileName);
await writeLogFile(shardBuffers[sName], tmpFile);
filePaths.push(tmpFile);
}
await uploadLogArtifacts(filePaths);
} else if (logToFile) {
core.info(
"[Monitor] No stdout lines were collected; skipping artifact upload.",
);
}
core.info(
`[Monitor] Done. sawTraceback=${state.sawTraceback} sawErrorLog=${state.sawErrorLog} sawWarningLog=${state.sawWarningLog}`,
);
return {
sawTraceback: state.sawTraceback,
sawErrorLog: state.sawErrorLog,
sawWarningLog: state.sawWarningLog,
};
}
+2344
View File
File diff suppressed because it is too large. Load diff
+7 -10
View File
@@ -1,9 +1,7 @@
{ {
"name": "screeps-deploy-action", "name": "screeps-deploy-action",
"version": "0.2.1", "version": "0.1.1",
"description": "Deploys screeps code to the official game or a private server.", "description": "Deploys screeps code to the official game or an pirvate server.",
"type": "module",
"packageManager": "pnpm@11.25.0",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node index.js", "start": "node index.js",
@@ -11,14 +9,13 @@
"build": "ncc build index.js -o dist -m --external utf-8-validate --external bufferutil" "build": "ncc build index.js -o dist -m --external utf-8-validate --external bufferutil"
}, },
"dependencies": { "dependencies": {
"@actions/artifact": "^1.1.2", "@actions/core": "^2.0.0",
"@actions/core": "^3.0.0",
"glob": "^13.0.0", "glob": "^13.0.0",
"screeps-api": "^2.0.0" "screeps-api": "^1.7.2"
}, },
"devDependencies": { "devDependencies": {
"@vercel/ncc": "^0.44.1", "@vercel/ncc": "^0.38.4",
"@vitest/coverage-v8": "^4.1.11", "@vitest/coverage-v8": "^4.0.16",
"vitest": "^4.1.11" "vitest": "^4.0.16"
} }
} }
-1336
View File
File diff suppressed because it is too large. Load diff
-3
View File
@@ -1,3 +0,0 @@
allowBuilds:
bufferutil: true
utf-8-validate: true
+15 -6
View File
@@ -5,11 +5,20 @@
"config:recommended", "config:recommended",
":automergeLinters" ":automergeLinters"
], ],
"rebaseWhen": "behind-base-branch", "packageRules": [
"branchConcurrentLimit": 2, {
"prConcurrentLimit": 2, "matchManagers": [
"gitIgnoredAuthors": [ "npm"
"github-actions[bot]@users.noreply.github.com", ],
"bot@horstenkamp.eu" "postUpgradeTasks": {
"commands": [
"npm ci",
"npm run build"
],
"fileFilters": [
"dist/index.js"
]
}
}
] ]
} }
-29
View File
@@ -1,29 +0,0 @@
import { glob } from "glob";
import path from "path";
import os from "os";
import fs from "fs";
async function test() {
const tempDir = await fs.promises.mkdtemp(
path.join(os.tmpdir(), "glob-test-"),
);
const file = path.join(tempDir, "test.js");
await fs.promises.writeFile(file, "test");
const pattern = "*.js";
const globPattern = path.join(tempDir, pattern);
console.log("globPattern:", globPattern);
const files = await glob(globPattern);
console.log("found files:", files);
// Fix for windows
const fixedPattern = globPattern.replace(/\\/g, "/");
console.log("fixedPattern:", fixedPattern);
const fixedFiles = await glob(fixedPattern);
console.log("found fixed files:", fixedFiles);
await fs.promises.rm(tempDir, { recursive: true, force: true });
}
test();
-12
View File
@@ -1,12 +0,0 @@
function detectTraceback(errorText) {
if (!errorText) return false;
return /^\s{4}at /m.test(errorText);
}
const encodedTraceback =
"Error: ReferenceError: a is not defined%0A at eval (eval at <anonymous> (_console1778948572008_0:1:46), <anonymous>:1:1)%0A at _console1778948572008_0:1:46%0A at _console1778948572008_0:1:60%0A at exports.evalCode (<runtime>:15347:63)%0A at exports.run (<runtime>:20876:41)%0A";
console.log("Encoded match:", detectTraceback(encodedTraceback));
const decodedTraceback = decodeURIComponent(encodedTraceback);
console.log("Decoded match:", detectTraceback(decodedTraceback));