Compare commits
43 Commits
worktree-a
...
v3.3.4.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9cc7d29cf | ||
|
|
b8bc432175 | ||
|
|
d3b468575b | ||
|
|
921a6ad984 | ||
|
|
c307027dd0 | ||
|
|
21fe53eaf7 | ||
|
|
34ce7d1d32 | ||
|
|
796de876b7 | ||
|
|
a35e789eb9 | ||
|
|
9d1d4f899b | ||
|
|
d1688aae0b | ||
|
|
a6a276b509 | ||
|
|
6df81e6f8d | ||
|
|
2c20b6c7b5 | ||
|
|
722934bdf2 | ||
|
|
2a86b3cc54 | ||
|
|
3bc0270eb9 | ||
|
|
066e482f06 | ||
|
|
02642840da | ||
|
|
1565046ab7 | ||
|
|
5478a4299e | ||
|
|
835a79cc0f | ||
|
|
983518e93d | ||
|
|
917ef2a239 | ||
|
|
b5a25b4ae5 | ||
|
|
0891e6c979 | ||
|
|
1f20ac9535 | ||
|
|
8e23adee14 | ||
|
|
3817566ed5 | ||
|
|
d16367582c | ||
|
|
e8051b256b | ||
|
|
cf916d7bc3 | ||
|
|
97036be319 | ||
|
|
52d7118c33 | ||
|
|
d7631ec671 | ||
|
|
f6eeaed97d | ||
|
|
ef54ac201a | ||
|
|
0c0588f920 | ||
|
|
420928f11e | ||
|
|
bc9445f06e | ||
|
|
ea34ddf8e4 | ||
|
|
5408867921 | ||
|
|
a8b521f7f7 |
@@ -75,6 +75,9 @@ SECRET_KEY=
|
||||
# Enable invite-only mode (requires invitation to register)
|
||||
INVITE_ONLY=true
|
||||
|
||||
# Allow visitors to request an invite from the login page (only relevant when INVITE_ONLY=true)
|
||||
INVITE_REQUEST_ENABLED=false
|
||||
|
||||
# Metered open signups (public beta)
|
||||
# 0 = disabled (invite-only enforced), -1 = unlimited, N = max open signups per day
|
||||
# When set > 0, users can register without an invite code up to the daily limit.
|
||||
|
||||
50
.gitea/workflows/deploy-prod.yml
Normal file
50
.gitea/workflows/deploy-prod.yml
Normal file
@@ -0,0 +1,50 @@
|
||||
name: Deploy Production
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to deploy (e.g. v3.3.0)'
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy to production
|
||||
uses: appleboy/ssh-action@v1
|
||||
with:
|
||||
host: ${{ secrets.PROD_HOST }}
|
||||
username: root
|
||||
key: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
script: |
|
||||
set -e
|
||||
TAG="${{ github.event.inputs.tag }}"
|
||||
IMAGE="git.adlee.work/alee/golfgame"
|
||||
|
||||
cd /opt/golfgame
|
||||
|
||||
# Pull the image that passed staging
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.adlee.work -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
docker pull "$IMAGE:$TAG"
|
||||
docker tag "$IMAGE:$TAG" golfgame-app:latest
|
||||
|
||||
# Update code for compose/env changes
|
||||
git fetch origin
|
||||
git checkout "$TAG"
|
||||
|
||||
# Restart app
|
||||
docker compose -f docker-compose.prod.yml up -d app
|
||||
|
||||
# Wait for healthy
|
||||
echo "Waiting for health check..."
|
||||
for i in $(seq 1 30); do
|
||||
if docker compose -f docker-compose.prod.yml ps app | grep -q "healthy"; then
|
||||
echo "Production deploy successful — $TAG"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "CRITICAL: app not healthy after 60s"
|
||||
docker compose -f docker-compose.prod.yml logs --tail=30 app
|
||||
exit 1
|
||||
50
.gitea/workflows/deploy-staging.yml
Normal file
50
.gitea/workflows/deploy-staging.yml
Normal file
@@ -0,0 +1,50 @@
|
||||
name: Build & Deploy Staging
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Build, push, and deploy to staging
|
||||
uses: appleboy/ssh-action@v1
|
||||
with:
|
||||
host: ${{ secrets.STAGING_HOST }}
|
||||
username: root
|
||||
key: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
script: |
|
||||
set -e
|
||||
TAG="${{ github.ref_name }}"
|
||||
IMAGE="git.adlee.work/alee/golfgame"
|
||||
|
||||
cd /opt/golfgame
|
||||
|
||||
# Pull latest code and checkout the release tag
|
||||
git fetch origin
|
||||
git checkout "$TAG"
|
||||
|
||||
# Build the image
|
||||
docker build -t "$IMAGE:$TAG" -t "$IMAGE:latest" -t golfgame-app:latest .
|
||||
|
||||
# Push to Gitea container registry
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.adlee.work -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
docker push "$IMAGE:$TAG"
|
||||
docker push "$IMAGE:latest"
|
||||
|
||||
# Restart app (no --build, image already tagged)
|
||||
docker compose -f docker-compose.staging.yml up -d app
|
||||
|
||||
# Wait for healthy
|
||||
echo "Waiting for health check..."
|
||||
for i in $(seq 1 30); do
|
||||
if docker compose -f docker-compose.staging.yml ps app | grep -q "healthy"; then
|
||||
echo "Staging deploy successful — $TAG"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "WARNING: app not healthy after 60s"
|
||||
docker compose -f docker-compose.staging.yml logs --tail=20 app
|
||||
exit 1
|
||||
25
.gitignore
vendored
25
.gitignore
vendored
@@ -136,7 +136,31 @@ celerybeat.pid
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.envrc
|
||||
|
||||
# Private keys and certificates
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.pfx
|
||||
*.jks
|
||||
*.keystore
|
||||
|
||||
# Service credentials
|
||||
credentials.json
|
||||
service-account.json
|
||||
*-credentials.json
|
||||
|
||||
# SSH keys
|
||||
id_rsa
|
||||
id_ecdsa
|
||||
id_ed25519
|
||||
|
||||
# Other sensitive files
|
||||
*.secrets
|
||||
.htpasswd
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
@@ -190,6 +214,7 @@ cython_debug/
|
||||
|
||||
# Claude Code
|
||||
.claude/
|
||||
.superpowers/
|
||||
|
||||
# Virtualenv in project root
|
||||
bin/
|
||||
|
||||
304
.secrets.baseline
Normal file
304
.secrets.baseline
Normal file
@@ -0,0 +1,304 @@
|
||||
{
|
||||
"version": "1.5.0",
|
||||
"plugins_used": [
|
||||
{
|
||||
"name": "ArtifactoryDetector"
|
||||
},
|
||||
{
|
||||
"name": "AWSKeyDetector"
|
||||
},
|
||||
{
|
||||
"name": "AzureStorageKeyDetector"
|
||||
},
|
||||
{
|
||||
"name": "Base64HighEntropyString",
|
||||
"limit": 4.5
|
||||
},
|
||||
{
|
||||
"name": "BasicAuthDetector"
|
||||
},
|
||||
{
|
||||
"name": "CloudantDetector"
|
||||
},
|
||||
{
|
||||
"name": "DiscordBotTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "GitHubTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "GitLabTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "HexHighEntropyString",
|
||||
"limit": 3.0
|
||||
},
|
||||
{
|
||||
"name": "IbmCloudIamDetector"
|
||||
},
|
||||
{
|
||||
"name": "IbmCosHmacDetector"
|
||||
},
|
||||
{
|
||||
"name": "IPPublicDetector"
|
||||
},
|
||||
{
|
||||
"name": "JwtTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "KeywordDetector",
|
||||
"keyword_exclude": ""
|
||||
},
|
||||
{
|
||||
"name": "MailchimpDetector"
|
||||
},
|
||||
{
|
||||
"name": "NpmDetector"
|
||||
},
|
||||
{
|
||||
"name": "OpenAIDetector"
|
||||
},
|
||||
{
|
||||
"name": "PrivateKeyDetector"
|
||||
},
|
||||
{
|
||||
"name": "PypiTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "SendGridDetector"
|
||||
},
|
||||
{
|
||||
"name": "SlackDetector"
|
||||
},
|
||||
{
|
||||
"name": "SoftlayerDetector"
|
||||
},
|
||||
{
|
||||
"name": "SquareOAuthDetector"
|
||||
},
|
||||
{
|
||||
"name": "StripeDetector"
|
||||
},
|
||||
{
|
||||
"name": "TelegramBotTokenDetector"
|
||||
},
|
||||
{
|
||||
"name": "TwilioKeyDetector"
|
||||
}
|
||||
],
|
||||
"filters_used": [
|
||||
{
|
||||
"path": "detect_secrets.filters.allowlist.is_line_allowlisted"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.common.is_baseline_file",
|
||||
"filename": ".secrets.baseline"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies",
|
||||
"min_level": 2
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_indirect_reference"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_likely_id_string"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_lock_file"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_potential_uuid"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_sequential_string"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_swagger_file"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.heuristic.is_templated_secret"
|
||||
},
|
||||
{
|
||||
"path": "detect_secrets.filters.regex.should_exclude_file",
|
||||
"pattern": [
|
||||
"\\.env\\.example$",
|
||||
"server/\\.env\\.example$"
|
||||
]
|
||||
}
|
||||
],
|
||||
"results": {
|
||||
"INSTALL.md": [
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "365e24291fd19bba10a0d8504c0ed90d5c8bef7f",
|
||||
"is_verified": false,
|
||||
"line_number": 75
|
||||
},
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "4f4944a7117fd2e95169da2b40af33b68a65a161",
|
||||
"is_verified": false,
|
||||
"line_number": 114
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "c35bdb821a941808a150db95d0f934f449bbff17",
|
||||
"is_verified": false,
|
||||
"line_number": 182
|
||||
},
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "c35bdb821a941808a150db95d0f934f449bbff17",
|
||||
"is_verified": false,
|
||||
"line_number": 225
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "001c1654cb8dff7c4ddb1ae6d2203d0dd15a6096",
|
||||
"is_verified": false,
|
||||
"line_number": 391
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "INSTALL.md",
|
||||
"hashed_secret": "53fe8c55272f9c3ceebb5e6058788e8981a359cb",
|
||||
"is_verified": false,
|
||||
"line_number": 397
|
||||
}
|
||||
],
|
||||
"docker-compose.dev.yml": [
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "docker-compose.dev.yml",
|
||||
"hashed_secret": "4f4944a7117fd2e95169da2b40af33b68a65a161",
|
||||
"is_verified": false,
|
||||
"line_number": 44
|
||||
}
|
||||
],
|
||||
"docs/v2/V2_BUILD_PLAN.md": [
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "docs/v2/V2_BUILD_PLAN.md",
|
||||
"hashed_secret": "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4",
|
||||
"is_verified": false,
|
||||
"line_number": 301
|
||||
}
|
||||
],
|
||||
"scripts/docker-build.sh": [
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "scripts/docker-build.sh",
|
||||
"hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684",
|
||||
"is_verified": false,
|
||||
"line_number": 40
|
||||
}
|
||||
],
|
||||
"scripts/install.sh": [
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "scripts/install.sh",
|
||||
"hashed_secret": "4f4944a7117fd2e95169da2b40af33b68a65a161",
|
||||
"is_verified": false,
|
||||
"line_number": 156
|
||||
},
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "scripts/install.sh",
|
||||
"hashed_secret": "7205a0abf00d1daec13c63ece029057c974795a9",
|
||||
"is_verified": false,
|
||||
"line_number": 267
|
||||
}
|
||||
],
|
||||
"server/RULES.md": [
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/RULES.md",
|
||||
"hashed_secret": "a6778f1880744bd1a342a8e3789135412d8f9da2",
|
||||
"is_verified": false,
|
||||
"line_number": 904
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/RULES.md",
|
||||
"hashed_secret": "aafdc23870ecbcd3d557b6423a8982134e17927e",
|
||||
"is_verified": false,
|
||||
"line_number": 949
|
||||
}
|
||||
],
|
||||
"server/config.py": [
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "server/config.py",
|
||||
"hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8",
|
||||
"is_verified": false,
|
||||
"line_number": 124
|
||||
}
|
||||
],
|
||||
"server/game_analyzer.py": [
|
||||
{
|
||||
"type": "Basic Auth Credentials",
|
||||
"filename": "server/game_analyzer.py",
|
||||
"hashed_secret": "4f4944a7117fd2e95169da2b40af33b68a65a161",
|
||||
"is_verified": false,
|
||||
"line_number": 617
|
||||
}
|
||||
],
|
||||
"server/test_auth.py": [
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "cbfdac6008f9cab4083784cbd1874f76618d2a97",
|
||||
"is_verified": false,
|
||||
"line_number": 39
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "f0578f1e7174b1a41c4ea8c6e17f7a8a3b88c92a",
|
||||
"is_verified": false,
|
||||
"line_number": 51
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "8be52126a6fde450a7162a3651d589bb51e9579d",
|
||||
"is_verified": false,
|
||||
"line_number": 65
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "74913f5cd5f61ec0bcfdb775414c2fb3d161b620",
|
||||
"is_verified": false,
|
||||
"line_number": 75
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "9d4e1e23bd5b727046a9e3b4b7db57bd8d6ee684",
|
||||
"is_verified": false,
|
||||
"line_number": 92
|
||||
},
|
||||
{
|
||||
"type": "Secret Keyword",
|
||||
"filename": "server/test_auth.py",
|
||||
"hashed_secret": "1e99b09f6eb835305555cc43c3e0768b1a39226b",
|
||||
"is_verified": false,
|
||||
"line_number": 104
|
||||
}
|
||||
]
|
||||
},
|
||||
"generated_at": "2026-04-05T13:26:03Z"
|
||||
}
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -203,4 +203,4 @@ From testing (1000+ games):
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
GPL-3.0-or-later — see [LICENSE](LICENSE) for the full text.
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
<a href="#" data-panel="users" class="nav-link">Users</a>
|
||||
<a href="#" data-panel="games" class="nav-link">Games</a>
|
||||
<a href="#" data-panel="invites" class="nav-link">Invites</a>
|
||||
<a href="#" data-panel="invite-requests" class="nav-link">Requests</a>
|
||||
<a href="#" data-panel="audit" class="nav-link">Audit Log</a>
|
||||
</div>
|
||||
<div class="nav-user">
|
||||
@@ -113,6 +114,10 @@
|
||||
<input type="checkbox" id="include-banned" checked>
|
||||
Include banned
|
||||
</label>
|
||||
<label class="checkbox-label">
|
||||
<input type="checkbox" id="include-test" checked>
|
||||
Include test accounts
|
||||
</label>
|
||||
</div>
|
||||
<table id="users-table" class="data-table">
|
||||
<thead>
|
||||
@@ -191,6 +196,35 @@
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- Invite Requests Panel -->
|
||||
<section id="invite-requests-panel" class="panel hidden">
|
||||
<h2>Invite Requests</h2>
|
||||
<div class="panel-toolbar">
|
||||
<div class="filter-bar">
|
||||
<select id="request-status-filter">
|
||||
<option value="pending">Pending</option>
|
||||
<option value="">All</option>
|
||||
<option value="approved">Approved</option>
|
||||
<option value="denied">Denied</option>
|
||||
</select>
|
||||
<button id="request-filter-btn" class="btn">Filter</button>
|
||||
</div>
|
||||
</div>
|
||||
<table id="invite-requests-table" class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Email</th>
|
||||
<th>Message</th>
|
||||
<th>Submitted</th>
|
||||
<th>Status</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- Audit Log Panel -->
|
||||
<section id="audit-panel" class="panel hidden">
|
||||
<h2>Audit Log</h2>
|
||||
@@ -207,12 +241,15 @@
|
||||
<option value="end_game">End Game</option>
|
||||
<option value="create_invite">Create Invite</option>
|
||||
<option value="revoke_invite">Revoke Invite</option>
|
||||
<option value="approve_invite_request">Approve Request</option>
|
||||
<option value="deny_invite_request">Deny Request</option>
|
||||
</select>
|
||||
<select id="audit-target-filter">
|
||||
<option value="">All Targets</option>
|
||||
<option value="user">Users</option>
|
||||
<option value="game">Games</option>
|
||||
<option value="invite_code">Invites</option>
|
||||
<option value="invite_request">Invite Requests</option>
|
||||
</select>
|
||||
<button id="audit-filter-btn" class="btn">Filter</button>
|
||||
</div>
|
||||
@@ -363,6 +400,8 @@
|
||||
<!-- Toast Container -->
|
||||
<div id="toast-container"></div>
|
||||
|
||||
<footer class="app-footer" style="text-align: center; padding: 16px; color: #888; font-size: 12px;">v3.3.4 © Aaron D. Lee</footer>
|
||||
|
||||
<script src="admin.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
103
client/admin.js
103
client/admin.js
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/**
|
||||
* Golf Admin Dashboard
|
||||
* JavaScript for admin interface functionality
|
||||
@@ -66,12 +67,13 @@ async function getStats() {
|
||||
return apiRequest('/api/admin/stats');
|
||||
}
|
||||
|
||||
async function getUsers(query = '', offset = 0, includeBanned = true) {
|
||||
async function getUsers(query = '', offset = 0, includeBanned = true, includeTest = true) {
|
||||
const params = new URLSearchParams({
|
||||
query,
|
||||
offset,
|
||||
limit: PAGE_SIZE,
|
||||
include_banned: includeBanned,
|
||||
include_test: includeTest,
|
||||
});
|
||||
return apiRequest(`/api/admin/users?${params}`);
|
||||
}
|
||||
@@ -197,6 +199,9 @@ function showPanel(panelId) {
|
||||
case 'invites':
|
||||
loadInvites();
|
||||
break;
|
||||
case 'invite-requests':
|
||||
loadInviteRequests();
|
||||
break;
|
||||
case 'audit':
|
||||
loadAuditLog();
|
||||
break;
|
||||
@@ -302,15 +307,19 @@ async function loadUsers() {
|
||||
try {
|
||||
const query = document.getElementById('user-search').value;
|
||||
const includeBanned = document.getElementById('include-banned').checked;
|
||||
const data = await getUsers(query, usersPage * PAGE_SIZE, includeBanned);
|
||||
const includeTest = document.getElementById('include-test').checked;
|
||||
const data = await getUsers(query, usersPage * PAGE_SIZE, includeBanned, includeTest);
|
||||
|
||||
const tbody = document.querySelector('#users-table tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
data.users.forEach(user => {
|
||||
const testBadge = user.is_test_account
|
||||
? ' <span class="badge badge-info" title="Soak harness test account">Test</span>'
|
||||
: '';
|
||||
tbody.innerHTML += `
|
||||
<tr>
|
||||
<td>${escapeHtml(user.username)}</td>
|
||||
<td>${escapeHtml(user.username)}${testBadge}</td>
|
||||
<td>${escapeHtml(user.email || '-')}</td>
|
||||
<td><span class="badge badge-${user.role === 'admin' ? 'info' : 'muted'}">${user.role}</span></td>
|
||||
<td>${getStatusBadge(user)}</td>
|
||||
@@ -443,10 +452,13 @@ async function loadInvites() {
|
||||
: invite.remaining_uses <= 0
|
||||
? '<span class="badge badge-warning">Used Up</span>'
|
||||
: '<span class="badge badge-success">Active</span>';
|
||||
const testSeedBadge = invite.marks_as_test
|
||||
? ' <span class="badge badge-info" title="Creates test accounts">Test-seed</span>'
|
||||
: '';
|
||||
|
||||
tbody.innerHTML += `
|
||||
<tr>
|
||||
<td><code>${escapeHtml(invite.code)}</code></td>
|
||||
<td><code>${escapeHtml(invite.code)}</code>${testSeedBadge}</td>
|
||||
<td>${invite.use_count} / ${invite.max_uses}</td>
|
||||
<td>${invite.remaining_uses}</td>
|
||||
<td>${escapeHtml(invite.created_by_username)}</td>
|
||||
@@ -642,6 +654,80 @@ async function promptRevokeInvite(code) {
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Invite Requests
|
||||
// =============================================================================
|
||||
|
||||
async function loadInviteRequests() {
|
||||
const status = document.getElementById('request-status-filter').value;
|
||||
const params = new URLSearchParams();
|
||||
if (status) params.set('status', status);
|
||||
|
||||
try {
|
||||
const data = await apiRequest(`/api/admin/invite-requests?${params}`);
|
||||
const tbody = document.querySelector('#invite-requests-table tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
if (data.requests.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="6" class="text-muted">No invite requests</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
data.requests.forEach(req => {
|
||||
const statusBadge = req.status === 'approved'
|
||||
? '<span class="badge badge-success">Approved</span>'
|
||||
: req.status === 'denied'
|
||||
? '<span class="badge badge-danger">Denied</span>'
|
||||
: '<span class="badge badge-warning">Pending</span>';
|
||||
|
||||
const actions = req.status === 'pending'
|
||||
? `<button class="btn btn-small btn-primary" data-action="approve-request" data-id="${req.id}">Approve</button>
|
||||
<button class="btn btn-small btn-danger" data-action="deny-request" data-id="${req.id}">Deny</button>`
|
||||
: `<span class="text-muted">${req.reviewed_by_username || '-'}</span>`;
|
||||
|
||||
tbody.innerHTML += `
|
||||
<tr>
|
||||
<td>${escapeHtml(req.name)}</td>
|
||||
<td>${escapeHtml(req.email)}</td>
|
||||
<td>${req.message ? escapeHtml(req.message).substring(0, 80) : '<span class="text-muted">-</span>'}</td>
|
||||
<td>${formatDate(req.created_at)}</td>
|
||||
<td>${statusBadge}</td>
|
||||
<td>${actions}</td>
|
||||
</tr>`;
|
||||
});
|
||||
} catch (error) {
|
||||
showToast('Failed to load invite requests: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleApproveRequest(requestId) {
|
||||
if (!confirm('Approve this invite request? An invite code will be created and emailed to the requester.')) return;
|
||||
|
||||
try {
|
||||
const data = await apiRequest(`/api/admin/invite-requests/${requestId}/approve`, {
|
||||
method: 'POST',
|
||||
});
|
||||
showToast(`Request approved! Invite code: ${data.code}`, 'success');
|
||||
loadInviteRequests();
|
||||
} catch (error) {
|
||||
showToast('Failed to approve request: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDenyRequest(requestId) {
|
||||
if (!confirm('Deny this invite request? The requester will be notified.')) return;
|
||||
|
||||
try {
|
||||
await apiRequest(`/api/admin/invite-requests/${requestId}/deny`, {
|
||||
method: 'POST',
|
||||
});
|
||||
showToast('Request denied', 'success');
|
||||
loadInviteRequests();
|
||||
} catch (error) {
|
||||
showToast('Failed to deny request: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Auth
|
||||
// =============================================================================
|
||||
@@ -749,6 +835,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
usersPage = 0;
|
||||
loadUsers();
|
||||
});
|
||||
document.getElementById('include-test').addEventListener('change', () => {
|
||||
usersPage = 0;
|
||||
loadUsers();
|
||||
});
|
||||
document.getElementById('users-prev').addEventListener('click', () => {
|
||||
if (usersPage > 0) {
|
||||
usersPage--;
|
||||
@@ -785,6 +875,9 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
document.getElementById('create-invite-btn').addEventListener('click', handleCreateInvite);
|
||||
document.getElementById('include-expired').addEventListener('change', loadInvites);
|
||||
|
||||
// Invite requests panel
|
||||
document.getElementById('request-filter-btn').addEventListener('click', loadInviteRequests);
|
||||
|
||||
// Audit panel
|
||||
document.getElementById('audit-filter-btn').addEventListener('click', () => {
|
||||
auditPage = 0;
|
||||
@@ -825,6 +918,8 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
else if (action === 'end-game') promptEndGame(btn.dataset.id);
|
||||
else if (action === 'copy-invite') copyInviteLink(btn.dataset.code);
|
||||
else if (action === 'revoke-invite') promptRevokeInvite(btn.dataset.code);
|
||||
else if (action === 'approve-request') handleApproveRequest(parseInt(btn.dataset.id));
|
||||
else if (action === 'deny-request') handleDenyRequest(parseInt(btn.dataset.id));
|
||||
});
|
||||
|
||||
// Check auth on load
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// AnimationQueue - Sequences card animations properly
|
||||
// Ensures animations play in order without overlap
|
||||
|
||||
|
||||
142
client/app.js
142
client/app.js
@@ -81,6 +81,7 @@ class GolfGame {
|
||||
this.initCardTooltips();
|
||||
this.bindEvents();
|
||||
this.initMobileDetection();
|
||||
this.initDesktopScorecard();
|
||||
this.checkUrlParams();
|
||||
}
|
||||
|
||||
@@ -111,9 +112,11 @@ class GolfGame {
|
||||
this.isMobile = e.matches;
|
||||
document.body.classList.toggle('mobile-portrait', e.matches);
|
||||
setAppHeight();
|
||||
// Close any open drawers on layout change
|
||||
// Close any open drawers/overlays on layout change
|
||||
if (!e.matches) {
|
||||
this.closeDrawers();
|
||||
} else {
|
||||
this.closeDesktopScorecard();
|
||||
}
|
||||
};
|
||||
mql.addEventListener('change', update);
|
||||
@@ -154,6 +157,31 @@ class GolfGame {
|
||||
if (bottomBar) bottomBar.classList.remove('hidden');
|
||||
}
|
||||
|
||||
initDesktopScorecard() {
|
||||
if (!this.desktopScorecardBtn) return;
|
||||
|
||||
this.desktopScorecardBtn.addEventListener('click', () => {
|
||||
const isOpen = this.desktopScorecardOverlay.classList.contains('open');
|
||||
if (isOpen) {
|
||||
this.closeDesktopScorecard();
|
||||
} else {
|
||||
this.desktopScorecardOverlay.classList.add('open');
|
||||
this.desktopScorecardBtn.classList.add('active');
|
||||
this.desktopScorecardBackdrop.classList.add('visible');
|
||||
}
|
||||
});
|
||||
|
||||
this.desktopScorecardBackdrop.addEventListener('click', () => {
|
||||
this.closeDesktopScorecard();
|
||||
});
|
||||
}
|
||||
|
||||
closeDesktopScorecard() {
|
||||
if (this.desktopScorecardOverlay) this.desktopScorecardOverlay.classList.remove('open');
|
||||
if (this.desktopScorecardBtn) this.desktopScorecardBtn.classList.remove('active');
|
||||
if (this.desktopScorecardBackdrop) this.desktopScorecardBackdrop.classList.remove('visible');
|
||||
}
|
||||
|
||||
initAudio() {
|
||||
// Initialize audio context on first user interaction
|
||||
const initCtx = () => {
|
||||
@@ -544,6 +572,13 @@ class GolfGame {
|
||||
this.gameUsername = document.getElementById('game-username');
|
||||
this.gameLogoutBtn = document.getElementById('game-logout-btn');
|
||||
this.authBar = document.getElementById('auth-bar');
|
||||
|
||||
// Desktop scorecard overlay elements
|
||||
this.desktopScorecardBtn = document.getElementById('desktop-scorecard-btn');
|
||||
this.desktopScorecardOverlay = document.getElementById('desktop-scorecard-overlay');
|
||||
this.desktopScorecardBackdrop = document.getElementById('desktop-scorecard-backdrop');
|
||||
this.desktopStandingsList = document.getElementById('desktop-standings-list');
|
||||
this.desktopScoreTable = document.getElementById('desktop-score-table')?.querySelector('tbody');
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
@@ -1464,12 +1499,8 @@ class GolfGame {
|
||||
this.swapAnimationCardEl = handCardEl;
|
||||
this.swapAnimationHandCardEl = handCardEl;
|
||||
|
||||
// Hide originals and UI during animation
|
||||
handCardEl.classList.add('swap-out');
|
||||
// Hide discard button during animation (held card hidden later by onStart)
|
||||
this.discardBtn.classList.add('hidden');
|
||||
if (this.heldCardFloating) {
|
||||
this.heldCardFloating.style.visibility = 'hidden';
|
||||
}
|
||||
|
||||
// Store drawn card data before clearing
|
||||
const drawnCardData = this.drawnCard;
|
||||
@@ -1492,6 +1523,12 @@ class GolfGame {
|
||||
{
|
||||
rotation: 0,
|
||||
wasHandFaceDown: false,
|
||||
onStart: () => {
|
||||
handCardEl.classList.add('swap-out');
|
||||
if (this.heldCardFloating) {
|
||||
this.heldCardFloating.style.visibility = 'hidden';
|
||||
}
|
||||
},
|
||||
onComplete: () => {
|
||||
handCardEl.classList.remove('swap-out');
|
||||
if (this.heldCardFloating) {
|
||||
@@ -1555,6 +1592,12 @@ class GolfGame {
|
||||
{
|
||||
rotation: 0,
|
||||
wasHandFaceDown: true,
|
||||
onStart: () => {
|
||||
if (handCardEl) handCardEl.classList.add('swap-out');
|
||||
if (this.heldCardFloating) {
|
||||
this.heldCardFloating.style.visibility = 'hidden';
|
||||
}
|
||||
},
|
||||
onComplete: () => {
|
||||
if (handCardEl) handCardEl.classList.remove('swap-out');
|
||||
if (this.heldCardFloating) {
|
||||
@@ -2887,9 +2930,6 @@ class GolfGame {
|
||||
return;
|
||||
}
|
||||
|
||||
// Hide the source card during animation
|
||||
sourceCardEl.classList.add('swap-out');
|
||||
|
||||
// Use unified swap animation
|
||||
if (window.cardAnimations) {
|
||||
const heldRect = window.cardAnimations.getHoldingRect();
|
||||
@@ -2902,6 +2942,9 @@ class GolfGame {
|
||||
{
|
||||
rotation: sourceRotation,
|
||||
wasHandFaceDown: !wasFaceUp,
|
||||
onStart: () => {
|
||||
sourceCardEl.classList.add('swap-out');
|
||||
},
|
||||
onComplete: () => {
|
||||
if (sourceCardEl) sourceCardEl.classList.remove('swap-out');
|
||||
this.opponentSwapAnimation = null;
|
||||
@@ -4347,6 +4390,11 @@ class GolfGame {
|
||||
`;
|
||||
this.scoreTable.appendChild(tr);
|
||||
});
|
||||
|
||||
// Mirror to desktop overlay
|
||||
if (this.desktopScoreTable) {
|
||||
this.desktopScoreTable.innerHTML = this.scoreTable.innerHTML;
|
||||
}
|
||||
}
|
||||
|
||||
updateStandings() {
|
||||
@@ -4384,7 +4432,7 @@ class GolfGame {
|
||||
return `<div class="rank-row ${holesRank === 0 && p.rounds_won > 0 ? 'leader' : ''}"><span class="rank-pos">${medal}</span><span class="rank-name">${name}</span><span class="rank-val">${p.rounds_won} wins</span></div>`;
|
||||
}).join('');
|
||||
|
||||
this.standingsList.innerHTML = `
|
||||
const standingsContent = `
|
||||
<div class="standings-section">
|
||||
<div class="standings-title">By Score</div>
|
||||
${pointsHtml}
|
||||
@@ -4394,6 +4442,10 @@ class GolfGame {
|
||||
${holesHtml}
|
||||
</div>
|
||||
`;
|
||||
this.standingsList.innerHTML = standingsContent;
|
||||
if (this.desktopStandingsList) {
|
||||
this.desktopStandingsList.innerHTML = standingsContent;
|
||||
}
|
||||
}
|
||||
|
||||
renderCard(card, clickable, selected) {
|
||||
@@ -4473,6 +4525,11 @@ class GolfGame {
|
||||
this.scoreTable.appendChild(tr);
|
||||
});
|
||||
|
||||
// Mirror to desktop overlay
|
||||
if (this.desktopScoreTable) {
|
||||
this.desktopScoreTable.innerHTML = this.scoreTable.innerHTML;
|
||||
}
|
||||
|
||||
// Show rankings announcement only for final results
|
||||
const existingAnnouncement = document.getElementById('rankings-announcement');
|
||||
if (existingAnnouncement) existingAnnouncement.remove();
|
||||
@@ -4810,6 +4867,15 @@ class AuthManager {
|
||||
this.resetPasswordConfirm = document.getElementById('reset-password-confirm');
|
||||
this.resetError = document.getElementById('reset-error');
|
||||
this.resetSuccess = document.getElementById('reset-success');
|
||||
this.requestInviteContainer = document.getElementById('request-invite-container');
|
||||
this.requestInviteForm = document.getElementById('request-invite-form');
|
||||
this.requestInviteName = document.getElementById('request-invite-name');
|
||||
this.requestInviteEmail = document.getElementById('request-invite-email');
|
||||
this.requestInviteMessage = document.getElementById('request-invite-message');
|
||||
this.requestInviteError = document.getElementById('request-invite-error');
|
||||
this.requestInviteSuccess = document.getElementById('request-invite-success');
|
||||
this.requestBackSignup = document.getElementById('request-back-signup');
|
||||
this.requestBackLogin = document.getElementById('request-back-login');
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
@@ -4840,6 +4906,15 @@ class AuthManager {
|
||||
});
|
||||
this.forgotForm?.addEventListener('submit', (e) => this.handleForgotPassword(e));
|
||||
this.resetForm?.addEventListener('submit', (e) => this.handleResetPassword(e));
|
||||
this.requestInviteForm?.addEventListener('submit', (e) => this.handleRequestInvite(e));
|
||||
this.requestBackSignup?.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
this.showForm('signup');
|
||||
});
|
||||
this.requestBackLogin?.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
this.showForm('login');
|
||||
});
|
||||
|
||||
// Check URL for reset token or invite code on page load
|
||||
this.checkResetToken();
|
||||
@@ -4865,6 +4940,7 @@ class AuthManager {
|
||||
this.signupFormContainer.classList.add('hidden');
|
||||
this.forgotFormContainer?.classList.add('hidden');
|
||||
this.resetFormContainer?.classList.add('hidden');
|
||||
this.requestInviteContainer?.classList.add('hidden');
|
||||
this.clearErrors();
|
||||
|
||||
if (form === 'login') {
|
||||
@@ -4879,6 +4955,9 @@ class AuthManager {
|
||||
} else if (form === 'reset') {
|
||||
this.resetFormContainer?.classList.remove('hidden');
|
||||
this.resetPassword?.focus();
|
||||
} else if (form === 'request-invite') {
|
||||
this.requestInviteContainer?.classList.remove('hidden');
|
||||
this.requestInviteName?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4895,6 +4974,8 @@ class AuthManager {
|
||||
if (this.forgotSuccess) this.forgotSuccess.textContent = '';
|
||||
if (this.resetError) this.resetError.textContent = '';
|
||||
if (this.resetSuccess) this.resetSuccess.textContent = '';
|
||||
if (this.requestInviteError) this.requestInviteError.textContent = '';
|
||||
if (this.requestInviteSuccess) this.requestInviteSuccess.textContent = '';
|
||||
}
|
||||
|
||||
async handleLogin(e) {
|
||||
@@ -5031,7 +5112,17 @@ class AuthManager {
|
||||
if (invite_required) {
|
||||
this.signupInviteCode.required = true;
|
||||
this.signupInviteCode.placeholder = 'Invite Code (required)';
|
||||
if (this.inviteCodeHint) this.inviteCodeHint.textContent = '';
|
||||
if (this.inviteCodeHint) {
|
||||
if (this.signupInfo.invite_request_enabled) {
|
||||
this.inviteCodeHint.innerHTML = 'Don\'t have one? <a href="#" id="show-request-invite">Request an invite</a>';
|
||||
document.getElementById('show-request-invite')?.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
this.showForm('request-invite');
|
||||
});
|
||||
} else {
|
||||
this.inviteCodeHint.textContent = '';
|
||||
}
|
||||
}
|
||||
} else if (open_signups_enabled) {
|
||||
this.signupInviteCode.required = false;
|
||||
this.signupInviteCode.placeholder = 'Invite Code (optional)';
|
||||
@@ -5108,4 +5199,33 @@ class AuthManager {
|
||||
this.resetError.textContent = 'Connection error';
|
||||
}
|
||||
}
|
||||
|
||||
async handleRequestInvite(e) {
|
||||
e.preventDefault();
|
||||
this.clearErrors();
|
||||
|
||||
const name = this.requestInviteName.value.trim();
|
||||
const email = this.requestInviteEmail.value.trim();
|
||||
const message = this.requestInviteMessage.value.trim() || null;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/request-invite', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, email, message }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
this.requestInviteError.textContent = data.detail || 'Request failed';
|
||||
return;
|
||||
}
|
||||
|
||||
this.requestInviteSuccess.textContent = data.message;
|
||||
this.requestInviteForm.reset();
|
||||
} catch (err) {
|
||||
this.requestInviteError.textContent = 'Connection error';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// CardAnimations - Unified anime.js-based animation system
|
||||
// Replaces draw-animations.js and handles ALL card animations
|
||||
|
||||
@@ -1105,7 +1106,7 @@ class CardAnimations {
|
||||
// heldRect: position of the held card (or null to use default holding position)
|
||||
// options: { rotation, wasHandFaceDown, onComplete }
|
||||
animateUnifiedSwap(handCardData, heldCardData, handRect, heldRect, options = {}) {
|
||||
const { rotation = 0, wasHandFaceDown = false, onComplete } = options;
|
||||
const { rotation = 0, wasHandFaceDown = false, onComplete, onStart } = options;
|
||||
const T = window.TIMING?.swap || { lift: 100, arc: 320, settle: 100 };
|
||||
const discardRect = this.getDiscardRect();
|
||||
|
||||
@@ -1137,15 +1138,15 @@ class CardAnimations {
|
||||
delete el.dataset.animating;
|
||||
el.remove();
|
||||
});
|
||||
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete);
|
||||
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete, onStart);
|
||||
}, 350);
|
||||
return;
|
||||
}
|
||||
|
||||
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete);
|
||||
this._runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete, onStart);
|
||||
}
|
||||
|
||||
_runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete) {
|
||||
_runUnifiedSwap(handCardData, heldCardData, handRect, heldRect, discardRect, T, rotation, wasHandFaceDown, onComplete, onStart) {
|
||||
// Create the two traveling cards
|
||||
const travelingHand = this.createCardFromData(handCardData, handRect, rotation);
|
||||
const travelingHeld = this.createCardFromData(heldCardData, heldRect, 0);
|
||||
@@ -1154,6 +1155,9 @@ class CardAnimations {
|
||||
document.body.appendChild(travelingHand);
|
||||
document.body.appendChild(travelingHeld);
|
||||
|
||||
// Now that overlays cover the originals, hide them
|
||||
if (onStart) onStart();
|
||||
|
||||
this.playSound('card');
|
||||
|
||||
// If hand card was face-down, flip it first
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// CardManager - Manages persistent card DOM elements
|
||||
// Cards are REAL elements that exist in ONE place and move between locations
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
|
||||
<title>Golf Card Game</title>
|
||||
<link rel="icon" type="image/svg+xml" href="golfball-logo.svg">
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
@@ -54,7 +55,7 @@
|
||||
|
||||
<p id="lobby-error" class="error"></p>
|
||||
|
||||
<footer class="app-footer">v3.1.6 © Aaron D. Lee</footer>
|
||||
<footer class="app-footer">v3.3.4 © Aaron D. Lee</footer>
|
||||
</div>
|
||||
|
||||
<!-- Matchmaking Screen -->
|
||||
@@ -287,7 +288,7 @@
|
||||
<p id="waiting-message" class="info">Waiting for host to start the game...</p>
|
||||
</div>
|
||||
|
||||
<footer class="app-footer">v3.1.6 © Aaron D. Lee</footer>
|
||||
<footer class="app-footer">v3.3.4 © Aaron D. Lee</footer>
|
||||
</div>
|
||||
|
||||
<!-- Game Screen -->
|
||||
@@ -322,38 +323,38 @@
|
||||
<div class="game-table">
|
||||
<div id="opponents-row" class="opponents-row"></div>
|
||||
|
||||
<div class="player-row">
|
||||
<div class="table-center">
|
||||
<div class="deck-area">
|
||||
<!-- Held card slot (left of deck) -->
|
||||
<div id="held-card-slot" class="held-card-slot hidden">
|
||||
<div id="held-card-display" class="card card-front">
|
||||
<span id="held-card-content"></span>
|
||||
</div>
|
||||
<span class="held-label">Holding</span>
|
||||
<div class="table-center">
|
||||
<div class="deck-area">
|
||||
<!-- Held card slot (left of deck) -->
|
||||
<div id="held-card-slot" class="held-card-slot hidden">
|
||||
<div id="held-card-display" class="card card-front">
|
||||
<span id="held-card-content"></span>
|
||||
</div>
|
||||
<div class="pile-wrapper">
|
||||
<span class="pile-label">DRAW</span>
|
||||
<div id="deck" class="card card-back"></div>
|
||||
</div>
|
||||
<div class="pile-wrapper">
|
||||
<span class="pile-label">DISCARD</span>
|
||||
<div class="discard-stack">
|
||||
<div id="discard" class="card">
|
||||
<span id="discard-content"></span>
|
||||
</div>
|
||||
<!-- Floating held card (appears larger over discard when holding) -->
|
||||
<div id="held-card-floating" class="card card-front held-card-floating hidden">
|
||||
<span id="held-card-floating-content"></span>
|
||||
</div>
|
||||
<button id="discard-btn" class="btn btn-small hidden">Discard</button>
|
||||
<button id="skip-flip-btn" class="btn btn-small btn-secondary hidden">Skip Flip</button>
|
||||
<button id="knock-early-btn" class="btn btn-small btn-danger hidden">Knock!</button>
|
||||
<span class="held-label">Holding</span>
|
||||
</div>
|
||||
<div class="pile-wrapper">
|
||||
<span class="pile-label">DRAW</span>
|
||||
<div id="deck" class="card card-back"></div>
|
||||
</div>
|
||||
<div class="pile-wrapper">
|
||||
<span class="pile-label">DISCARD</span>
|
||||
<div class="discard-stack">
|
||||
<div id="discard" class="card">
|
||||
<span id="discard-content"></span>
|
||||
</div>
|
||||
<!-- Floating held card (appears larger over discard when holding) -->
|
||||
<div id="held-card-floating" class="card card-front held-card-floating hidden">
|
||||
<span id="held-card-floating-content"></span>
|
||||
</div>
|
||||
<button id="discard-btn" class="btn btn-small hidden">Discard</button>
|
||||
<button id="skip-flip-btn" class="btn btn-small btn-secondary hidden">Skip Flip</button>
|
||||
<button id="knock-early-btn" class="btn btn-small btn-danger hidden">Knock!</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="player-row">
|
||||
<div class="player-section">
|
||||
<div class="player-area">
|
||||
<h4 id="player-header"><span class="player-name">You</span><span id="your-score" class="player-showing">0</span></h4>
|
||||
@@ -427,6 +428,26 @@
|
||||
|
||||
<!-- Drawer backdrop for mobile -->
|
||||
<div id="drawer-backdrop" class="drawer-backdrop"></div>
|
||||
|
||||
<!-- Desktop scorecard button + overlay -->
|
||||
<button id="desktop-scorecard-btn">Scorecard</button>
|
||||
<div id="desktop-scorecard-overlay" class="side-panel desktop-scorecard-overlay">
|
||||
<h4>Current Standings</h4>
|
||||
<div id="desktop-standings-list" class="standings-list"></div>
|
||||
<h4>Scores</h4>
|
||||
<table id="desktop-score-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Player</th>
|
||||
<th>Hole</th>
|
||||
<th>Tot</th>
|
||||
<th>W</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div id="desktop-scorecard-backdrop" class="desktop-scorecard-backdrop"></div>
|
||||
</div>
|
||||
|
||||
<!-- Rules Screen -->
|
||||
@@ -911,6 +932,28 @@ TOTAL: 0 + 8 + 16 = 24 points</pre>
|
||||
</form>
|
||||
<p class="auth-switch">Already have an account? <a href="#" id="show-login">Login</a></p>
|
||||
</div>
|
||||
|
||||
<!-- Request Invite Form -->
|
||||
<div id="request-invite-container" class="hidden">
|
||||
<h3>Request an Invite</h3>
|
||||
<p class="auth-hint">Registration is invite-only. Request access and we'll get back to you.</p>
|
||||
<form id="request-invite-form">
|
||||
<div class="form-group">
|
||||
<input type="text" id="request-invite-name" placeholder="Your name" required maxlength="100">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<input type="email" id="request-invite-email" placeholder="Email" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<textarea id="request-invite-message" placeholder="Why do you want to join? (optional)" rows="3" maxlength="500"></textarea>
|
||||
</div>
|
||||
<p id="request-invite-error" class="error"></p>
|
||||
<p id="request-invite-success" class="success"></p>
|
||||
<button type="submit" class="btn btn-primary btn-full">Request Invite</button>
|
||||
</form>
|
||||
<p class="auth-switch">Already have an invite? <a href="#" id="request-back-signup">Sign up</a></p>
|
||||
<p class="auth-switch">Already have an account? <a href="#" id="request-back-login">Login</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
/**
|
||||
* Leaderboard component for Golf game.
|
||||
* Handles leaderboard display, metric switching, and player stats modal.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Golf Card Game - Replay Viewer
|
||||
|
||||
class ReplayViewer {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// StateDiffer - Detects what changed between game states
|
||||
// Generates movement instructions for the animation queue
|
||||
|
||||
|
||||
228
client/style.css
228
client/style.css
@@ -1024,13 +1024,13 @@ input::placeholder {
|
||||
|
||||
/* Card Styles */
|
||||
.card {
|
||||
width: clamp(65px, 5.5vw, 100px);
|
||||
height: clamp(91px, 7.7vw, 140px);
|
||||
width: clamp(65px, 7vw, 135px);
|
||||
height: clamp(91px, 9.8vw, 189px);
|
||||
border-radius: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: clamp(2rem, 2.5vw, 3.2rem);
|
||||
font-size: clamp(2rem, 3vw, 3.8rem);
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
/* No CSS transition - hover effects handled by anime.js */
|
||||
@@ -1151,7 +1151,7 @@ input::placeholder {
|
||||
/* Card Grid */
|
||||
.card-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, clamp(65px, 5.5vw, 100px));
|
||||
grid-template-columns: repeat(3, clamp(65px, 7vw, 135px));
|
||||
gap: clamp(8px, 0.8vw, 14px);
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -1161,18 +1161,22 @@ input::placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 25px;
|
||||
justify-content: space-between;
|
||||
gap: 15px;
|
||||
width: 100%;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Player row - deck/discard and player cards side by side */
|
||||
/* Player row - local player cards */
|
||||
.player-row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 25px;
|
||||
gap: clamp(15px, 2vh, 35px);
|
||||
width: 100%;
|
||||
flex-wrap: wrap;
|
||||
padding-bottom: clamp(10px, 2vh, 30px);
|
||||
}
|
||||
|
||||
.opponents-row {
|
||||
@@ -1180,9 +1184,9 @@ input::placeholder {
|
||||
flex-wrap: nowrap;
|
||||
justify-content: center;
|
||||
align-items: flex-end;
|
||||
gap: clamp(12px, 1.8vw, 35px);
|
||||
min-height: clamp(120px, 14vw, 200px);
|
||||
padding: 8px 20px 0;
|
||||
gap: clamp(12px, 6vw, 120px);
|
||||
min-height: clamp(120px, 18vw, 280px);
|
||||
padding: 15px 20px 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -1234,7 +1238,62 @@ input::placeholder {
|
||||
transform: rotate(8deg);
|
||||
}
|
||||
|
||||
/* 5 opponents: deeper arch with graduated rotation toward center */
|
||||
/* 5 opponents: tighter spacing to fit single row on wide screens */
|
||||
.opponents-row:has(.opponent-area:first-child:nth-last-child(5)) {
|
||||
gap: clamp(6px, 2vw, 50px);
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5),
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area {
|
||||
flex-shrink: 1;
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) .card-grid,
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area .card-grid {
|
||||
grid-template-columns: repeat(3, clamp(38px, 4vw, 85px));
|
||||
gap: clamp(2px, 0.4vw, 6px);
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) .card,
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area .card {
|
||||
width: clamp(38px, 4vw, 85px);
|
||||
height: clamp(53px, 5.6vw, 119px);
|
||||
font-size: clamp(0.9rem, 1.3vw, 2.2rem);
|
||||
}
|
||||
|
||||
/* 5 opponents mid-width: wrap into 2 arch rows (3 + 2) */
|
||||
@media (min-width: 750px) and (max-width: 1220px) {
|
||||
.opponents-row:has(.opponent-area:first-child:nth-last-child(5)) {
|
||||
flex-wrap: wrap;
|
||||
gap: clamp(6px, 1.5vw, 20px);
|
||||
row-gap: clamp(4px, 1vw, 16px);
|
||||
}
|
||||
/* Force 3+2 split: each item ~30% so 3 fit per row */
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5),
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
/* Row 1 arch: 3 opponents */
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) {
|
||||
margin-bottom: 0;
|
||||
transform: rotate(-5deg);
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area:nth-child(2) {
|
||||
margin-bottom: 20px;
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area:nth-child(3) {
|
||||
margin-bottom: 0;
|
||||
transform: rotate(5deg);
|
||||
}
|
||||
/* Row 2 arch: 2 opponents */
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area:nth-child(4) {
|
||||
margin-bottom: 8px;
|
||||
transform: rotate(-3deg);
|
||||
}
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) ~ .opponent-area:nth-child(5) {
|
||||
margin-bottom: 8px;
|
||||
transform: rotate(3deg);
|
||||
}
|
||||
}
|
||||
|
||||
.opponents-row .opponent-area:first-child:nth-last-child(5) {
|
||||
margin-bottom: 0;
|
||||
transform: rotate(-10deg);
|
||||
@@ -1367,9 +1426,9 @@ input::placeholder {
|
||||
}
|
||||
|
||||
.deck-area .card {
|
||||
width: clamp(80px, 7vw, 120px);
|
||||
height: clamp(112px, 9.8vw, 168px);
|
||||
font-size: clamp(2.4rem, 3.2vw, 4rem);
|
||||
width: clamp(80px, 8.5vw, 150px);
|
||||
height: clamp(112px, 11.9vw, 210px);
|
||||
font-size: clamp(2.4rem, 3.5vw, 4.5rem);
|
||||
}
|
||||
|
||||
#discard {
|
||||
@@ -1771,14 +1830,14 @@ input::placeholder {
|
||||
|
||||
.opponent-area .card-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, clamp(45px, 4vw, 75px));
|
||||
gap: clamp(4px, 0.4vw, 8px);
|
||||
grid-template-columns: repeat(3, clamp(45px, 5vw, 100px));
|
||||
gap: clamp(4px, 0.5vw, 8px);
|
||||
}
|
||||
|
||||
.opponent-area .card {
|
||||
width: clamp(45px, 4vw, 75px);
|
||||
height: clamp(63px, 5.6vw, 105px);
|
||||
font-size: clamp(1.3rem, 1.5vw, 2.2rem);
|
||||
width: clamp(45px, 5vw, 100px);
|
||||
height: clamp(63px, 7vw, 140px);
|
||||
font-size: clamp(1.3rem, 1.8vw, 2.6rem);
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
@@ -1929,6 +1988,7 @@ input::placeholder {
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: calc(100vh - 50px);
|
||||
}
|
||||
|
||||
/* Side Panels - positioned in bottom corners */
|
||||
@@ -1953,6 +2013,88 @@ input::placeholder {
|
||||
right: 15px;
|
||||
}
|
||||
|
||||
/* Desktop: hide side panels by default, show via scorecard button */
|
||||
.side-panel.left-panel,
|
||||
.side-panel.right-panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Desktop scorecard button - bottom right corner */
|
||||
#desktop-scorecard-btn {
|
||||
position: fixed;
|
||||
bottom: 15px;
|
||||
right: 15px;
|
||||
z-index: 99;
|
||||
background: linear-gradient(145deg, rgba(15, 50, 35, 0.92) 0%, rgba(8, 30, 20, 0.95) 100%);
|
||||
border: 1px solid rgba(244, 164, 96, 0.35);
|
||||
color: #f4a460;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.15em;
|
||||
text-transform: uppercase;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
backdrop-filter: blur(10px);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
#desktop-scorecard-btn:hover {
|
||||
background: linear-gradient(145deg, rgba(20, 60, 40, 0.95) 0%, rgba(12, 40, 28, 0.97) 100%);
|
||||
border-color: rgba(244, 164, 96, 0.6);
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5), 0 0 10px rgba(244, 164, 96, 0.15);
|
||||
}
|
||||
|
||||
#desktop-scorecard-btn:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
#desktop-scorecard-btn.active {
|
||||
background: linear-gradient(135deg, #f4a460, #e8935a);
|
||||
color: #1a472a;
|
||||
border-color: transparent;
|
||||
box-shadow: 0 2px 12px rgba(244, 164, 96, 0.4);
|
||||
}
|
||||
|
||||
/* Desktop scorecard overlay — combines standings + scores */
|
||||
.side-panel.desktop-scorecard-overlay {
|
||||
display: none;
|
||||
position: fixed;
|
||||
bottom: 55px;
|
||||
right: 15px;
|
||||
left: auto;
|
||||
width: 280px;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
z-index: 100;
|
||||
border-radius: 10px;
|
||||
padding: 10px 12px;
|
||||
background: linear-gradient(145deg, rgba(15, 50, 35, 0.95) 0%, rgba(8, 30, 20, 0.97) 100%);
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid rgba(244, 164, 96, 0.25);
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
|
||||
.side-panel.desktop-scorecard-overlay.open {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Desktop scorecard backdrop */
|
||||
.desktop-scorecard-backdrop {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
z-index: 98;
|
||||
}
|
||||
|
||||
.desktop-scorecard-backdrop.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.side-panel > h4 {
|
||||
font-size: 0.7rem;
|
||||
text-align: center;
|
||||
@@ -3596,7 +3738,24 @@ input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.modal-auth input:focus {
|
||||
.modal-auth textarea {
|
||||
width: 100%;
|
||||
padding: 12px 15px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 8px;
|
||||
color: white;
|
||||
font-size: 1rem;
|
||||
font-family: inherit;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.modal-auth textarea::placeholder {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.modal-auth input:focus,
|
||||
.modal-auth textarea:focus {
|
||||
outline: none;
|
||||
border-color: #f4a460;
|
||||
}
|
||||
@@ -3612,6 +3771,15 @@ input::placeholder {
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
.form-hint a {
|
||||
color: #f4a460;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.form-hint a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.auth-switch {
|
||||
text-align: center;
|
||||
margin-top: 15px;
|
||||
@@ -5336,12 +5504,16 @@ body.mobile-portrait .opponents-row {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* --- Mobile: Player row gets remaining space, centered vertically --- */
|
||||
/* --- Mobile: Table center and player row share remaining space --- */
|
||||
body.mobile-portrait .table-center {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
body.mobile-portrait .player-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: space-evenly;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
flex: 1 1 0%;
|
||||
@@ -5503,6 +5675,18 @@ body.mobile-portrait .real-card .card-face-back {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* Hide desktop scorecard button and backdrop on mobile */
|
||||
body.mobile-portrait #desktop-scorecard-btn,
|
||||
body.mobile-portrait .desktop-scorecard-backdrop {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Re-enable side panels on mobile (overrides desktop hide) */
|
||||
body.mobile-portrait .side-panel.left-panel,
|
||||
body.mobile-portrait .side-panel.right-panel {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* --- Mobile: Side panels become bottom drawers --- */
|
||||
body.mobile-portrait .side-panel {
|
||||
position: fixed;
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
services:
|
||||
app:
|
||||
restart: unless-stopped
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
@@ -39,6 +40,7 @@ services:
|
||||
- BASE_URL=${BASE_URL:-https://golf.example.com}
|
||||
- RATE_LIMIT_ENABLED=true
|
||||
- INVITE_ONLY=true
|
||||
- INVITE_REQUEST_ENABLED=true
|
||||
- DAILY_OPEN_SIGNUPS=${DAILY_OPEN_SIGNUPS:-0}
|
||||
- DAILY_SIGNUPS_PER_IP=${DAILY_SIGNUPS_PER_IP:-3}
|
||||
- BOOTSTRAP_ADMIN_USERNAME=${BOOTSTRAP_ADMIN_USERNAME:-}
|
||||
@@ -50,10 +52,6 @@ services:
|
||||
redis:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
replicas: 1
|
||||
restart_policy:
|
||||
condition: on-failure
|
||||
max_attempts: 3
|
||||
resources:
|
||||
limits:
|
||||
memory: 256M
|
||||
@@ -64,7 +62,7 @@ services:
|
||||
- web
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.docker.network=golfgame_web"
|
||||
- "traefik.docker.network=traefik_web"
|
||||
- "traefik.http.routers.golf.rule=Host(`${DOMAIN:-golf.example.com}`)"
|
||||
- "traefik.http.routers.golf.entrypoints=websecure"
|
||||
- "traefik.http.routers.golf.tls=true"
|
||||
@@ -84,6 +82,7 @@ services:
|
||||
- "traefik.http.services.golf.loadbalancer.sticky.cookie.name=golf_server"
|
||||
|
||||
postgres:
|
||||
restart: unless-stopped
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: golf
|
||||
@@ -106,6 +105,7 @@ services:
|
||||
memory: 64M
|
||||
|
||||
redis:
|
||||
restart: unless-stopped
|
||||
image: redis:7-alpine
|
||||
command: redis-server --appendonly yes --maxmemory 32mb --maxmemory-policy allkeys-lru
|
||||
volumes:
|
||||
@@ -124,45 +124,14 @@ services:
|
||||
reservations:
|
||||
memory: 16M
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.6
|
||||
environment:
|
||||
- DOCKER_API_VERSION=1.44
|
||||
command:
|
||||
- "--api.dashboard=true"
|
||||
- "--api.insecure=true"
|
||||
- "--accesslog=true"
|
||||
- "--log.level=WARN"
|
||||
- "--providers.docker=true"
|
||||
- "--providers.docker.exposedbydefault=false"
|
||||
- "--entrypoints.web.address=:80"
|
||||
- "--entrypoints.web.http.redirections.entryPoint.to=websecure"
|
||||
- "--entrypoints.web.http.redirections.entryPoint.scheme=https"
|
||||
- "--entrypoints.websecure.address=:443"
|
||||
- "--certificatesresolvers.letsencrypt.acme.httpchallenge=true"
|
||||
- "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web"
|
||||
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
||||
- letsencrypt:/letsencrypt
|
||||
networks:
|
||||
- web
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 64M
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
letsencrypt:
|
||||
|
||||
networks:
|
||||
internal:
|
||||
driver: bridge
|
||||
web:
|
||||
driver: bridge
|
||||
name: traefik_web
|
||||
external: true
|
||||
|
||||
@@ -29,6 +29,7 @@ services:
|
||||
- BASE_URL=${BASE_URL:-https://staging.golfcards.club}
|
||||
- RATE_LIMIT_ENABLED=false
|
||||
- INVITE_ONLY=true
|
||||
- INVITE_REQUEST_ENABLED=false
|
||||
- DAILY_OPEN_SIGNUPS=${DAILY_OPEN_SIGNUPS:-0}
|
||||
- DAILY_SIGNUPS_PER_IP=${DAILY_SIGNUPS_PER_IP:-3}
|
||||
- BOOTSTRAP_ADMIN_USERNAME=${BOOTSTRAP_ADMIN_USERNAME:-}
|
||||
|
||||
125
docs/soak-harness-bringup.md
Normal file
125
docs/soak-harness-bringup.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# Soak Harness Bring-Up
|
||||
|
||||
One-time setup steps before running `tests/soak` against an environment.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- An invite code exists with 16+ available uses
|
||||
- You have psql access to the target DB (or admin SQL access via some other means)
|
||||
|
||||
## 1. Flag the invite code as test-seed
|
||||
|
||||
Any account registered with a `marks_as_test=TRUE` invite code gets
|
||||
`users_v2.is_test_account=TRUE`, which keeps it out of real-user stats.
|
||||
|
||||
### Staging
|
||||
|
||||
Invite code: `5VC2MCCN` (16 uses, provisioned 2026-04-10).
|
||||
|
||||
```sql
|
||||
UPDATE invite_codes SET marks_as_test = TRUE WHERE code = '5VC2MCCN';
|
||||
SELECT code, max_uses, use_count, marks_as_test FROM invite_codes WHERE code = '5VC2MCCN';
|
||||
```
|
||||
|
||||
Expected: `marks_as_test | t`.
|
||||
|
||||
From your workstation:
|
||||
|
||||
```bash
|
||||
ssh root@129.212.150.189 \
|
||||
'docker compose -f /opt/golfgame/docker-compose.staging.yml exec -T postgres psql -U postgres -d golfgame' <<'SQL'
|
||||
UPDATE invite_codes SET marks_as_test = TRUE WHERE code = '5VC2MCCN';
|
||||
SELECT code, max_uses, use_count, marks_as_test FROM invite_codes WHERE code = '5VC2MCCN';
|
||||
SQL
|
||||
```
|
||||
|
||||
### Production
|
||||
|
||||
Invite code — to be provisioned when production seeding is needed. Same pattern:
|
||||
|
||||
```bash
|
||||
ssh root@165.245.152.51 \
|
||||
'docker compose -f /opt/golfgame/docker-compose.prod.yml exec -T postgres psql -U postgres -d golfgame' <<'SQL'
|
||||
UPDATE invite_codes SET marks_as_test = TRUE WHERE code = '<PROD_INVITE_CODE>';
|
||||
SQL
|
||||
```
|
||||
|
||||
### Local dev
|
||||
|
||||
The local dev environment uses the `SOAKTEST` invite code. Create it once
|
||||
(if you wiped the DB since the last run):
|
||||
|
||||
```sql
|
||||
INSERT INTO invite_codes (code, created_by, expires_at, max_uses, is_active, marks_as_test)
|
||||
SELECT 'SOAKTEST', id, NOW() + INTERVAL '10 years', 100, TRUE, TRUE
|
||||
FROM users_v2 LIMIT 1
|
||||
ON CONFLICT (code) DO UPDATE SET marks_as_test = TRUE;
|
||||
```
|
||||
|
||||
Note: `created_by` references any existing user (the FK doesn't require admin role).
|
||||
If your dev DB has zero users, register one first via the UI or `curl`.
|
||||
|
||||
Connection string for local dev:
|
||||
|
||||
```bash
|
||||
PGPASSWORD=devpassword psql -h localhost -U golf -d golf
|
||||
```
|
||||
|
||||
## 2. Verify the schema migrations applied
|
||||
|
||||
The server-side changes (columns, matview rebuild, stats filter) run automatically
|
||||
on server startup via `SCHEMA_SQL` in `server/stores/user_store.py`. After the
|
||||
server-side changes deploy, verify against each target environment:
|
||||
|
||||
```sql
|
||||
-- All four should return matching rows
|
||||
\d users_v2 -- look for is_test_account column
|
||||
\d invite_codes -- look for marks_as_test column
|
||||
\d leaderboard_overall -- look for is_test_account column
|
||||
\di idx_users_test_account
|
||||
```
|
||||
|
||||
If `leaderboard_overall` doesn't show the new column, the matview rebuild
|
||||
didn't run. Check server startup logs for errors around `initialize_schema`.
|
||||
|
||||
## 3. Run the harness
|
||||
|
||||
Once the harness is built (Tasks 9+ of the implementation plan):
|
||||
|
||||
```bash
|
||||
cd tests/soak
|
||||
npm install
|
||||
|
||||
# First run only: seed 16 accounts via the invite code
|
||||
TEST_URL=https://staging.adlee.work SOAK_INVITE_CODE=5VC2MCCN npm run seed
|
||||
|
||||
# Smoke test against local dev
|
||||
TEST_URL=http://localhost:8000 SOAK_INVITE_CODE=SOAKTEST npm run smoke
|
||||
|
||||
# Populate staging scoreboard
|
||||
TEST_URL=https://staging.adlee.work SOAK_INVITE_CODE=5VC2MCCN npm run soak:populate
|
||||
|
||||
# Stress test
|
||||
TEST_URL=https://staging.adlee.work SOAK_INVITE_CODE=5VC2MCCN npm run soak:stress
|
||||
```
|
||||
|
||||
See `tests/soak/README.md` for the full flag reference.
|
||||
|
||||
## 4. Verify test account filtering works end-to-end
|
||||
|
||||
After a soak run, the soak-seeded accounts should be visible to admins but
|
||||
hidden from public stats:
|
||||
|
||||
```bash
|
||||
# Should return no soak_* usernames (test accounts hidden by default)
|
||||
curl -s "https://staging.adlee.work/api/stats/leaderboard?metric=wins" | jq '.entries[] | select(.username | startswith("soak_"))'
|
||||
|
||||
# Should return the soak_* accounts when explicitly requested
|
||||
curl -s "https://staging.adlee.work/api/stats/leaderboard?metric=wins&include_test=true" | jq '.entries[] | select(.username | startswith("soak_"))'
|
||||
```
|
||||
|
||||
In the admin panel:
|
||||
|
||||
- Users tab shows a `[Test]` badge next to soak accounts
|
||||
- Invite codes tab shows `[Test-seed]` next to the flagged code
|
||||
- "Include test accounts" checkbox (default checked) toggles visibility
|
||||
5582
docs/superpowers/plans/2026-04-10-multiplayer-soak-test.md
Normal file
5582
docs/superpowers/plans/2026-04-10-multiplayer-soak-test.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,638 @@
|
||||
# Multiplayer Soak & UX Test Harness — Design
|
||||
|
||||
**Date:** 2026-04-10
|
||||
**Status:** Design approved, pending implementation plan
|
||||
|
||||
## Context
|
||||
|
||||
Golf Card Game is a real-time multiplayer WebSocket application with event-sourced game state, a leaderboard system, and an aggressive animation pipeline. Current test coverage is:
|
||||
|
||||
- `server/` — pytest unit/integration tests
|
||||
- `tests/e2e/specs/` — Playwright tests exercising single-context flows (full game, stress with rapid clicks, visual regression, v3 features)
|
||||
|
||||
What's missing: a way to exercise the system with **many concurrent authenticated users playing real multiplayer games** for long durations. We can't currently:
|
||||
|
||||
1. Populate staging scoreboards with realistic game history for demos and visual verification
|
||||
2. Hunt race conditions, WebSocket leaks, and room cleanup bugs under sustained concurrent load
|
||||
3. Validate multiplayer UX end-to-end across rooms without manual coordination
|
||||
4. Exercise authentication, room lifecycle, and stats aggregation as a cohesive system
|
||||
|
||||
This spec defines a **multi-scenario soak and UX test harness**: a standalone Playwright-based runner that drives 16 authenticated browser sessions across 4 concurrent rooms playing many games against each other (plus optional CPU opponents). It starts as a soak tool with two scenarios (`populate`, `stress`) and grows into the project's general-purpose multi-user UX test platform.
|
||||
|
||||
## Goals
|
||||
|
||||
1. **Scoreboard population** — run long multi-round games against staging with varied CPU personalities to produce realistic scoreboard data
|
||||
2. **Stability stress** — run rapid short games with chaos injection to surface race conditions and cleanup bugs
|
||||
3. **Extensibility** — new scenarios (reconnect, invite flow, admin workflow, mobile) slot in without runner changes
|
||||
4. **Watchability** — a dashboard mode with click-to-watch live video of any player, usable for demos and debugging
|
||||
5. **Per-run isolation** — test account traffic must be cleanly separable from real user traffic in stats queries
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Replacing the existing `tests/e2e/specs/` Playwright tests (they serve a different purpose — single-context edge cases)
|
||||
- Distributed runner across multiple machines
|
||||
- Concurrent scenario execution (one scenario per run for MVP)
|
||||
- Grafana/OTEL integration
|
||||
- Auto-promoting findings to regression tests
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Staging auth gate** — staging runs `INVITE_ONLY=true`; seeding must go through the register endpoint with an invite code
|
||||
- **Invite code `5VC2MCCN`** — provisioned with 16 uses, used once per test account on first-ever run, cached afterward
|
||||
- **Per-IP rate limiting** — `DAILY_SIGNUPS_PER_IP=20` on prod, lower default elsewhere; seeding must stay within budget
|
||||
- **Room idle cleanup** — `ROOM_IDLE_TIMEOUT_SECONDS=300` means the scenario must keep rooms active or tolerate cleanup cascades
|
||||
- **Existing bot code** — `tests/e2e/bot/golf-bot.ts` already provides `createGame`, `joinGame`, `addCPU`, `playTurn`, `playGame`; the harness reuses it verbatim
|
||||
|
||||
## Architecture
|
||||
|
||||
### Module layout
|
||||
|
||||
```
|
||||
runner.ts (entry)
|
||||
├─ SessionPool owns 16 BrowserContexts, seeds/logs in, allocates
|
||||
├─ Scenario pluggable interface, per-scenario file
|
||||
├─ RoomCoordinator host→joiners room-code handoff via Deferred<string>
|
||||
├─ Dashboard (optional) HTTP + WS server, status grid + click-to-watch video
|
||||
└─ GolfBot (reused) tests/e2e/bot/golf-bot.ts, unchanged
|
||||
```
|
||||
|
||||
Default: one browser, 16 contexts (lowest RAM, fastest startup). `WATCH=tiled` is the exception — it launches two browsers, one headed (hosts) and one headless (joiners), because Chromium's headed/headless flag is browser-scoped, not context-scoped. See the `tiled` implementation detail below.
|
||||
|
||||
### Location
|
||||
|
||||
New sibling directory `tests/soak/` — does not modify `tests/e2e/`. Shares `GolfBot` via direct import from `../e2e/bot/`.
|
||||
|
||||
Rationale: Playwright Test is designed for short isolated tests. A single `test()` running 16 contexts for hours fights the test model (worker limits, all-or-nothing failure, single giant trace file). A standalone node script gives first-class CLI flags, full control over the event loop, clean home for the dashboard server, and reuses the `GolfBot` class unchanged. Existing `tests/e2e/specs/stress.spec.ts` stays as-is for single-context edge cases.
|
||||
|
||||
## Components
|
||||
|
||||
### SessionPool
|
||||
|
||||
Owns the lifecycle of 16 authenticated `BrowserContext`s.
|
||||
|
||||
**Responsibilities:**
|
||||
- On first run: register 16 accounts via `POST /api/auth/register` with invite code `5VC2MCCN`, cache credentials to `.env.stresstest`
|
||||
- On subsequent runs: read cached credentials, create contexts, inject auth into each (localStorage token, or re-login via cached password if token rejected)
|
||||
- Expose `acquire({ count }): Promise<Session[]>` — scenarios request N authenticated sessions without caring how they got there
|
||||
- On scenario completion: close all contexts cleanly
|
||||
|
||||
**`Session` shape:**
|
||||
```typescript
|
||||
interface Session {
|
||||
context: BrowserContext;
|
||||
page: Page;
|
||||
bot: GolfBot;
|
||||
account: Account; // { username, password, token }
|
||||
key: string; // stable identifier, e.g., "soak_07"
|
||||
}
|
||||
```
|
||||
|
||||
**`.env.stresstest` format** (gitignored, local-only, plaintext — this is a test tool):
|
||||
```
|
||||
SOAK_ACCOUNT_00=soak_00_a7bx:Hunter2!xK9mQ:eyJhbGc...
|
||||
SOAK_ACCOUNT_01=soak_01_c3pz:Kc82!wQm4Rt:eyJhbGc...
|
||||
...
|
||||
SOAK_ACCOUNT_15=soak_15_m9fy:Px7!eR4sTn2:eyJhbGc...
|
||||
```
|
||||
|
||||
Line format: `username:password:token`. Password kept so the pool can recover from token expiry automatically.
|
||||
|
||||
### Scenario interface
|
||||
|
||||
```typescript
|
||||
export interface ScenarioNeeds {
|
||||
accounts: number;
|
||||
rooms?: number;
|
||||
cpusPerRoom?: number;
|
||||
}
|
||||
|
||||
export interface ScenarioContext {
|
||||
config: ScenarioConfig; // CLI flags merged with scenario defaults
|
||||
sessions: Session[]; // pre-authenticated, pre-navigated
|
||||
coordinator: RoomCoordinator;
|
||||
dashboard: DashboardReporter; // no-op when watch mode doesn't use it
|
||||
logger: Logger;
|
||||
signal: AbortSignal; // graceful shutdown
|
||||
heartbeat(roomId: string): void; // resets the per-room watchdog
|
||||
}
|
||||
|
||||
export interface ScenarioResult {
|
||||
gamesCompleted: number;
|
||||
errors: ScenarioError[];
|
||||
durationMs: number;
|
||||
customMetrics?: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface Scenario {
|
||||
name: string;
|
||||
description: string;
|
||||
defaultConfig: ScenarioConfig;
|
||||
needs: ScenarioNeeds;
|
||||
run(ctx: ScenarioContext): Promise<ScenarioResult>;
|
||||
}
|
||||
```
|
||||
|
||||
Scenarios are plain objects exported as default from files in `tests/soak/scenarios/`. The runner discovers them via a registry (`scenarios/index.ts`) that maps name → module. No filesystem scanning, no magic.
|
||||
|
||||
### RoomCoordinator
|
||||
|
||||
~30 lines. Solves host→joiners room-code handoff:
|
||||
|
||||
```typescript
|
||||
class RoomCoordinator {
|
||||
private rooms = new Map<string, Deferred<string>>();
|
||||
|
||||
announce(roomId: string, code: string) { this.get(roomId).resolve(code); }
|
||||
async await(roomId: string): Promise<string> { return this.get(roomId).promise; }
|
||||
private get(roomId: string) {
|
||||
if (!this.rooms.has(roomId)) this.rooms.set(roomId, deferred());
|
||||
return this.rooms.get(roomId)!;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Usage:
|
||||
```typescript
|
||||
// Host
|
||||
const code = await host.bot.createGame(host.account.username);
|
||||
coordinator.announce('room-1', code);
|
||||
|
||||
// Joiners (concurrent)
|
||||
const code = await coordinator.await('room-1');
|
||||
await joiner.bot.joinGame(code, joiner.account.username);
|
||||
```
|
||||
|
||||
No polling, no sleeps, no cross-page scraping.
|
||||
|
||||
### Dashboard
|
||||
|
||||
Optional — only instantiated when `WATCH=dashboard`.
|
||||
|
||||
**Server side** (`dashboard/server.ts`): vanilla `http` + `ws` module. Serves a single static HTML page, accepts WebSocket connections, relays messages between scenarios and the browser.
|
||||
|
||||
**Client side** (`dashboard/index.html` + `dashboard.js`): 2×2 room grid, per-player tiles with live status (current player, score, held card, phase, moves), progress bars per hole, activity log at the bottom. No framework, ~300 lines total.
|
||||
|
||||
**Click-to-watch**: clicking a player tile sends `start_stream(sessionKey)` over WS. The runner attaches a CDP session to that player's page via `context.newCDPSession(page)`, calls `Page.startScreencast` with `{format: 'jpeg', quality: 60, maxWidth: 640, maxHeight: 360, everyNthFrame: 2}`, and forwards each `Page.screencastFrame` event to the dashboard as `{ sessionKey, jpeg_b64 }`. The dashboard renders it into an `<img>` that swaps `src` on each frame.
|
||||
|
||||
Returning to the grid sends `stop_stream(sessionKey)` and the runner detaches the CDP session. On WS disconnect, all active screencasts stop. This keeps CPU cost zero except while someone is actively watching.
|
||||
|
||||
**`DashboardReporter` interface exposed to scenarios:**
|
||||
```typescript
|
||||
interface DashboardReporter {
|
||||
update(roomId: string, state: Partial<RoomState>): void;
|
||||
log(level: 'info'|'warn'|'error', msg: string, meta?: object): void;
|
||||
incrementMetric(name: string, by?: number): void;
|
||||
}
|
||||
```
|
||||
|
||||
When `WATCH` is not `dashboard`, all three methods are no-ops; structured logs still go to stdout.
|
||||
|
||||
### Runner
|
||||
|
||||
`runner.ts` is the CLI entry point. Parses flags, resolves config precedence, launches browser(s), instantiates `SessionPool` + `RoomCoordinator` + (optional) `Dashboard`, loads the requested scenario by name, executes it, reports results, cleans up.
|
||||
|
||||
## Scenarios
|
||||
|
||||
### Scenario 1: `populate`
|
||||
|
||||
**Goal:** produce realistic scoreboard data for staging demos.
|
||||
|
||||
**Config:**
|
||||
```typescript
|
||||
{
|
||||
name: 'populate',
|
||||
description: 'Long multi-round games to populate scoreboards',
|
||||
needs: { accounts: 16, rooms: 4, cpusPerRoom: 1 },
|
||||
defaultConfig: {
|
||||
gamesPerRoom: 10,
|
||||
holes: 9,
|
||||
decks: 2,
|
||||
cpuPersonalities: ['Sofia', 'Marcus', 'Kenji', 'Priya'],
|
||||
thinkTimeMs: [800, 2200],
|
||||
interGamePauseMs: 3000,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Shape:** 4 rooms × 4 accounts + 1 CPU each. Each room runs `gamesPerRoom` sequential games. Inside a room: host creates game → joiners join → host adds CPU → host starts game → all sessions loop on `isMyTurn()` + `playTurn()` with randomized human-like think time between turns. Between games, rooms pause briefly to mimic natural pacing.
|
||||
|
||||
### Scenario 2: `stress`
|
||||
|
||||
**Goal:** hunt race conditions and stability bugs.
|
||||
|
||||
**Config:**
|
||||
```typescript
|
||||
{
|
||||
name: 'stress',
|
||||
description: 'Rapid short games for stability & race condition hunting',
|
||||
needs: { accounts: 16, rooms: 4, cpusPerRoom: 2 },
|
||||
defaultConfig: {
|
||||
gamesPerRoom: 50,
|
||||
holes: 1,
|
||||
decks: 1,
|
||||
thinkTimeMs: [50, 150],
|
||||
interGamePauseMs: 200,
|
||||
chaosChance: 0.05,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Shape:** same as `populate` but tight loops, 1-hole games, and a chaos injector that fires with 5% probability per turn. Chaos events:
|
||||
- Rapid concurrent clicks on multiple cards
|
||||
- Random tab-navigation away and back
|
||||
- Simultaneous click on card + discard button
|
||||
- Brief WebSocket drop via Playwright's `context.setOffline()` followed by reconnect
|
||||
|
||||
Each chaos event is logged with enough context to reproduce (room, player, turn, event type).
|
||||
|
||||
### Future scenarios (not MVP, design anticipates them)
|
||||
|
||||
- `reconnect` — 2 accounts, deliberate mid-game disconnect, verify recovery
|
||||
- `invite-flow` — 0 accounts (fresh signups), exercise invite request → approval → first-game pipeline
|
||||
- `admin-workflow` — 1 admin account, drive the admin panel
|
||||
- `mobile-populate` — reuses `populate` with `devices['iPhone 13']` context options
|
||||
- `replay-viewer` — watches completed games via the replay UI
|
||||
|
||||
Each is a new file in `tests/soak/scenarios/`, zero runner changes.
|
||||
|
||||
## Data flow
|
||||
|
||||
### Cold start (first-ever run)
|
||||
|
||||
1. Runner reads `.env.stresstest` → file missing
|
||||
2. `SessionPool.seedAccounts()`:
|
||||
- For `i` in `0..15`: `POST /api/auth/register` with `{ username, password, email, invite_code: '5VC2MCCN' }`
|
||||
- Receive `{ user, token, expires_at }`, write to `.env.stresstest`
|
||||
3. Server sets `is_test_account=true` automatically because the invite code has `marks_as_test=true` (see Server changes)
|
||||
4. Runner proceeds to normal startup
|
||||
|
||||
### Warm start (subsequent runs)
|
||||
|
||||
1. Runner reads `.env.stresstest` → 16 entries
|
||||
2. `SessionPool` creates 16 `BrowserContext`s
|
||||
3. For each context: inject token into localStorage using the key the client app reads on load (resolved during implementation by inspecting `client/app.js`; see Open Questions)
|
||||
4. Each session navigates to `/` and lands post-auth
|
||||
5. If any token is rejected (401), pool silently re-logs in via cached password and refreshes the token in `.env.stresstest`
|
||||
|
||||
### Seeding: explicit script vs automatic fallback
|
||||
|
||||
Two paths to the same result, for flexibility:
|
||||
|
||||
- **Preferred: explicit `npm run seed`** — runs `scripts/seed-accounts.ts` once during bring-up. Gives clear feedback, fails loudly on rate limits or network issues, lets you verify the accounts exist before a real run.
|
||||
- **Fallback: auto-seed on cold start** — if `runner.ts` starts and `.env.stresstest` is missing, `SessionPool` invokes the same seeding logic transparently. Useful for CI or fresh clones where nobody ran the explicit step.
|
||||
|
||||
Both paths share the same code in `core/session-pool.ts`; the script is a thin CLI wrapper around `SessionPool.seedAccounts()`. Documented in `tests/soak/README.md` with "run `npm run seed` first" as the happy path.
|
||||
|
||||
### Room code handoff
|
||||
|
||||
Host session calls `createGame` → receives room code → `coordinator.announce(roomId, code)`. Joiner sessions `await coordinator.await(roomId)` → receive code → call `joinGame`. All in-process, no polling.
|
||||
|
||||
## Watch modes
|
||||
|
||||
| Mode | Flag | Rendering | When to use |
|
||||
|---|---|---|---|
|
||||
| `none` | `WATCH=none` | Pure headless, JSONL stdout | CI, overnight unattended |
|
||||
| `dashboard` | `WATCH=dashboard` *(default)* | HTML status grid + click-to-watch live video | Interactive runs, demos, debugging |
|
||||
| `tiled` | `WATCH=tiled` | 4 native Chromium windows positioned 2×2 | Hands-on power-user debugging |
|
||||
|
||||
### `tiled` implementation detail
|
||||
|
||||
Two browsers launched: one headed (`headless: false, slowMo: 50`) for the 4 host contexts, one headless for the 12 joiner contexts. Host windows positioned via `page.evaluate(() => window.moveTo(x, y))` after load. Grid computed from screen size with a default of 1920×1080.
|
||||
|
||||
## Server-side changes
|
||||
|
||||
All changes are additive and fit the existing inline migration pattern in `server/stores/user_store.py`.
|
||||
|
||||
### 1. Schema
|
||||
|
||||
Two new columns + one partial index:
|
||||
|
||||
```sql
|
||||
ALTER TABLE users_v2 ADD COLUMN IF NOT EXISTS is_test_account BOOLEAN DEFAULT FALSE;
|
||||
CREATE INDEX IF NOT EXISTS idx_users_test_account ON users_v2(is_test_account)
|
||||
WHERE is_test_account = TRUE;
|
||||
ALTER TABLE invite_codes ADD COLUMN IF NOT EXISTS marks_as_test BOOLEAN DEFAULT FALSE;
|
||||
```
|
||||
|
||||
Partial index because ~99% of rows will be `FALSE`; we only want to accelerate the "show test accounts" admin queries, not pay index-maintenance cost on every normal write.
|
||||
|
||||
### 2. Register flow propagates the flag
|
||||
|
||||
In `services/auth_service.py`, after resolving the invite code, read `marks_as_test` and pass through to `user_store.create_user`:
|
||||
|
||||
```python
|
||||
invite = await admin_service.get_invite_code(invite_code)
|
||||
is_test = bool(invite and invite.marks_as_test)
|
||||
user = await user_store.create_user(
|
||||
username=..., password_hash=..., email=...,
|
||||
is_test_account=is_test,
|
||||
)
|
||||
```
|
||||
|
||||
Users signing up without an invite or with a non-test invite are unaffected.
|
||||
|
||||
### 3. One-time: flag `5VC2MCCN` as test-seed
|
||||
|
||||
Executed once against staging (and any other environment the harness runs against):
|
||||
|
||||
```sql
|
||||
UPDATE invite_codes SET marks_as_test = TRUE WHERE code = '5VC2MCCN';
|
||||
```
|
||||
|
||||
Documented in the seeder script as a comment, and in `tests/soak/README.md` as a bring-up step. No admin UI for flagging invites as test-seed in MVP — add later if needed.
|
||||
|
||||
### 4. Stats filtering
|
||||
|
||||
Add `include_test: bool = False` parameter to stats queries in `services/stats_service.py`:
|
||||
|
||||
```python
|
||||
async def get_leaderboard(self, limit=50, include_test=False):
|
||||
query = """
|
||||
SELECT ... FROM player_stats ps
|
||||
JOIN users_v2 u ON u.id = ps.user_id
|
||||
WHERE ($1 OR NOT u.is_test_account)
|
||||
ORDER BY ps.total_points DESC
|
||||
LIMIT $2
|
||||
"""
|
||||
return await conn.fetch(query, include_test, limit)
|
||||
```
|
||||
|
||||
Router in `routers/stats.py` exposes `include_test` as an optional query parameter. Default `False` — real users visiting the site never see soak traffic. Admin panel and debugging views pass `?include_test=true`.
|
||||
|
||||
Same treatment for:
|
||||
- `get_player_stats(user_id, include_test)` — gates individual profile lookups
|
||||
- `get_recent_games(include_test)` — hides games where any participant is a test account by default
|
||||
|
||||
### 5. Admin panel surfacing
|
||||
|
||||
Small additions to `client/admin.html` + `client/admin.js`:
|
||||
- User list: "Test" badge column for `is_test_account=true` rows
|
||||
- Invite codes: "Test-seed" indicator next to `marks_as_test=true` codes
|
||||
- Leaderboard + user list: "Include test accounts" toggle → passes `?include_test=true`
|
||||
|
||||
### Out of scope (server-side)
|
||||
|
||||
- New admin endpoint for marking existing accounts as test
|
||||
- Admin UI for flagging invites as test-seed at creation time
|
||||
- Separate "test stats only" aggregation (admins invert their mental filter)
|
||||
- `test_only=true` query mode
|
||||
|
||||
## Error handling
|
||||
|
||||
### Failure taxonomy
|
||||
|
||||
| Category | Example | Strategy |
|
||||
|---|---|---|
|
||||
| Recoverable game error | Animation flag stuck, click missed target | Log, continue, bot retries via existing `GolfBot` fallbacks |
|
||||
| Recoverable session error | WS disconnect for one player, token expires | Reconnect session, rejoin game if possible, abort that room only if unrecoverable |
|
||||
| Unrecoverable room error | Room stuck >60s, impossible state | Kill the room, capture artifacts, let other rooms continue |
|
||||
| Fatal runner error | Staging unreachable, invite code exhausted, OOM | Stop everything cleanly, dump summary, exit non-zero |
|
||||
|
||||
**Core principle: per-room isolation.** A failure in room 3 never unwinds rooms 1, 2, 4. Each room runs in its own `Promise.allSettled` branch.
|
||||
|
||||
### Per-room watchdog
|
||||
|
||||
Each room gets a watchdog that resets on every `ctx.heartbeat(roomId)` call. If a room hasn't heartbeat'd in 60s, the watchdog captures artifacts, aborts that room only, and the runner continues with the remaining rooms.
|
||||
|
||||
Scenarios call `heartbeat` at each significant progress point (turn played, game started, game finished). The helper `DashboardReporter.update()` internally calls `heartbeat` as a convenience, so scenarios that use the dashboard reporter get watchdog resets for free. Scenarios that run with `WATCH=none` still need to call `heartbeat` explicitly at least once per 60s — a single call at the top of the per-turn loop is sufficient.
|
||||
|
||||
### Artifact capture on failure
|
||||
|
||||
Captured per-room into `tests/soak/artifacts/<run-id>/<room-id>/`:
|
||||
- Screenshot of every context in the affected room
|
||||
- `page.content()` HTML snapshot per context
|
||||
- Last 200 console log messages per context (already captured by `GolfBot`)
|
||||
- Game state JSON from the state parser
|
||||
- Error stack trace
|
||||
- Scenario config snapshot
|
||||
|
||||
Directory structure:
|
||||
```
|
||||
tests/soak/artifacts/
|
||||
2026-04-10-populate-14.23.05/
|
||||
run.log # structured JSONL, full run
|
||||
summary.json # final stats
|
||||
room-0/
|
||||
screenshot-host.png
|
||||
screenshot-joiner-1.png
|
||||
page-host.html
|
||||
console.txt
|
||||
state.json
|
||||
error.txt
|
||||
```
|
||||
|
||||
Artifacts directory is gitignored. Runs older than 7 days auto-pruned on startup.
|
||||
|
||||
### Structured logging
|
||||
|
||||
Single logger, JSON Lines to stdout, pretty mirror to the dashboard. Every log line carries `run_id`, `scenario`, `room` (when applicable), and `timestamp`. Grep-friendly and `jq`-friendly.
|
||||
|
||||
### Graceful shutdown
|
||||
|
||||
`SIGINT` / `SIGTERM` trigger shutdown via `AbortController`:
|
||||
1. Global `AbortSignal` flips to aborted
|
||||
2. Scenarios check `ctx.signal.aborted` in loops, finish current turn, exit cleanly
|
||||
3. Runner waits up to 10s for scenarios to unwind
|
||||
4. After 10s, force-closes all contexts + browser
|
||||
5. Writes final `summary.json` and prints results
|
||||
6. Exit codes: `0` = all rooms completed target games, `1` = any room failed, `2` = interrupted before completion
|
||||
|
||||
Double Ctrl-C = immediate force exit.
|
||||
|
||||
### Periodic health probes
|
||||
|
||||
Every 30s during a run:
|
||||
- `GET /api/health` against the target server
|
||||
- Count of open browser contexts vs expected
|
||||
- Runner memory usage
|
||||
|
||||
If `/api/health` fails 3 consecutive times, declare fatal error, capture artifacts, stop. This prevents staging outages from being misattributed to bot bugs.
|
||||
|
||||
### Retry policy
|
||||
|
||||
Retry only at the session level, never at the scenario level.
|
||||
- WS drop → reconnect session, rejoin game if possible, 3 attempts max
|
||||
- Token rejected → re-login via cached password, 1 attempt
|
||||
- Click missed → existing `GolfBot` retry (already built in)
|
||||
|
||||
Never retry: whole games, whole scenarios, fatal errors.
|
||||
|
||||
### Cleanup guarantees
|
||||
|
||||
Three cleanup points, all going through the same `cleanup()` function wrapped in top-level `try/finally`:
|
||||
1. **Success** — close contexts, close browsers, flush logs, write summary
|
||||
2. **Exception** — capture artifacts first, then close contexts, flush logs, write partial summary
|
||||
3. **Signal interrupt** — graceful shutdown as above, best-effort artifact capture
|
||||
|
||||
## File layout
|
||||
|
||||
```
|
||||
tests/soak/
|
||||
├── package.json # standalone (separate from tests/e2e/)
|
||||
├── tsconfig.json
|
||||
├── README.md # quickstart + flag reference + bring-up steps
|
||||
├── .env.stresstest.example # template (real file gitignored)
|
||||
│
|
||||
├── runner.ts # CLI entry — `npm run soak`
|
||||
├── config.ts # CLI parsing + defaults merging
|
||||
│
|
||||
├── core/
|
||||
│ ├── session-pool.ts
|
||||
│ ├── room-coordinator.ts
|
||||
│ ├── screencaster.ts # CDP attach/detach on demand
|
||||
│ ├── watchdog.ts
|
||||
│ ├── artifacts.ts
|
||||
│ ├── logger.ts
|
||||
│ └── types.ts # Scenario, Session, ScenarioContext interfaces
|
||||
│
|
||||
├── scenarios/
|
||||
│ ├── populate.ts
|
||||
│ ├── stress.ts
|
||||
│ └── index.ts # name → module registry
|
||||
│
|
||||
├── dashboard/
|
||||
│ ├── server.ts # http + ws
|
||||
│ ├── index.html
|
||||
│ ├── dashboard.css
|
||||
│ └── dashboard.js
|
||||
│
|
||||
├── scripts/
|
||||
│ ├── seed-accounts.ts # one-shot seeding
|
||||
│ ├── reset-accounts.ts # future: wipe test account stats
|
||||
│ └── smoke.sh # bring-up validation
|
||||
│
|
||||
└── artifacts/ # gitignored, auto-pruned 7d
|
||||
└── <run-id>/...
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
New `tests/soak/package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "golf-soak",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"soak": "tsx runner.ts",
|
||||
"soak:populate": "tsx runner.ts --scenario=populate",
|
||||
"soak:stress": "tsx runner.ts --scenario=stress",
|
||||
"seed": "tsx scripts/seed-accounts.ts",
|
||||
"smoke": "scripts/smoke.sh"
|
||||
},
|
||||
"dependencies": {
|
||||
"playwright-core": "^1.40.0",
|
||||
"ws": "^8.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "^4.7.0",
|
||||
"@types/ws": "^8.5.0",
|
||||
"@types/node": "^20.10.0",
|
||||
"typescript": "^5.3.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Three runtime deps: `playwright-core` (already in `tests/e2e/`), `ws` (WebSocket for dashboard), `tsx` (dev-only, runs TypeScript directly). No HTTP framework, no bundler, no build step.
|
||||
|
||||
## CLI flags
|
||||
|
||||
```
|
||||
--scenario=populate|stress required
|
||||
--accounts=<n> total sessions (default: scenario.needs.accounts)
|
||||
--rooms=<n> default from scenario.needs
|
||||
--cpus-per-room=<n> default from scenario.needs
|
||||
--games-per-room=<n> default from scenario.defaultConfig
|
||||
--holes=<n> default from scenario.defaultConfig
|
||||
--watch=none|dashboard|tiled default: dashboard
|
||||
--dashboard-port=<n> default: 7777
|
||||
--target=<url> default: TEST_URL env or http://localhost:8000
|
||||
--run-id=<string> default: ISO timestamp
|
||||
--list print available scenarios and exit
|
||||
--dry-run validate config without running
|
||||
```
|
||||
|
||||
Derived: `accounts-per-room = accounts / rooms`. Must divide evenly; runner errors out with a clear message if not.
|
||||
|
||||
Config precedence: CLI flags → environment variables → scenario `defaultConfig` → runner defaults.
|
||||
|
||||
## Meta-testing
|
||||
|
||||
### Unit tests (Vitest, minimal)
|
||||
|
||||
- `room-coordinator.ts` — announce/await correctness, timeout behavior
|
||||
- `watchdog.ts` — fires on timeout, resets on heartbeat, cancels cleanly
|
||||
- `config.ts` — CLI precedence, required field validation
|
||||
|
||||
### Bring-up smoke test (`tests/soak/scripts/smoke.sh`)
|
||||
|
||||
Runs against local dev server with minimum viable config:
|
||||
```bash
|
||||
TEST_URL=http://localhost:8000 \
|
||||
npm run soak -- \
|
||||
--scenario=populate \
|
||||
--accounts=2 \
|
||||
--rooms=1 \
|
||||
--cpus-per-room=0 \
|
||||
--games-per-room=1 \
|
||||
--holes=1 \
|
||||
--watch=none
|
||||
```
|
||||
|
||||
Exit 0 = full harness works end-to-end. ~30 seconds. Run after any change.
|
||||
|
||||
### Manual validation checklist
|
||||
|
||||
Documented in `tests/soak/CHECKLIST.md`:
|
||||
- [ ] Seed 16 accounts against staging using the invite code
|
||||
- [ ] `--scenario=populate --rooms=1 --games-per-room=1` completes cleanly
|
||||
- [ ] `--scenario=populate --rooms=4 --games-per-room=1` — 4 rooms in parallel, no cross-contamination
|
||||
- [ ] `--watch=dashboard` opens browser, grid renders, progress updates
|
||||
- [ ] Click a player tile → live video appears, Esc → stops
|
||||
- [ ] `--watch=tiled` opens 4 browser windows in 2×2 grid
|
||||
- [ ] Ctrl-C during a run → graceful shutdown, summary printed, exit 2
|
||||
- [ ] Kill the target server mid-run → runner detects, captures artifacts, exits 1
|
||||
- [ ] Stats query `?include_test=false` hides soak accounts, `?include_test=true` shows them
|
||||
- [ ] Full stress run (`--scenario=stress --games-per-room=10`) — no console errors, all rooms complete
|
||||
|
||||
## Implementation order
|
||||
|
||||
Sequenced so each step produces something demonstrable before moving on. The writing-plans skill will break this into concrete tasks.
|
||||
|
||||
1. **Server-side changes** — schema alters, register flow, stats filter, admin badge. Independent, ships first, unblocks local testing.
|
||||
2. **Scaffold `tests/soak/`** — package.json, tsconfig, core/types, logger. No behavior yet.
|
||||
3. **`SessionPool` + `scripts/seed-accounts.ts`** — end-to-end auth: seed, cache, load, validate login.
|
||||
4. **`RoomCoordinator` + minimal `populate` scenario body** — proves multi-room orchestration.
|
||||
5. **`runner.ts`** — CLI, config merging, scenario loading, top-level error handling.
|
||||
6. **`--watch=none` works** — runs against local dev, produces clean logs, exits 0. First end-to-end milestone.
|
||||
7. **`--watch=dashboard` status grid** — HTML + WS + tile updates (no video yet).
|
||||
8. **CDP screencast / click-to-watch** — the live video feature.
|
||||
9. **`--watch=tiled` mode** — native windows via `page.evaluate(window.moveTo)`.
|
||||
10. **`stress` scenario** — chaos injection, rapid games.
|
||||
11. **Failure handling** — watchdog, artifact capture, graceful shutdown.
|
||||
12. **Smoke test script + CHECKLIST.md** — validation.
|
||||
13. **Run against staging for real** — populate scoreboard, hunt bugs, report findings.
|
||||
|
||||
If step 6 takes longer than planned, steps 1–5 are still useful standalone.
|
||||
|
||||
## Out of scope for MVP
|
||||
|
||||
- Mobile viewport scenarios (future `mobile-populate`)
|
||||
- Reconnect-storm scenarios
|
||||
- Admin workflow scenarios
|
||||
- Concurrent scenario execution
|
||||
- Distributed runner
|
||||
- Grafana / OTEL / custom metrics push
|
||||
- Test account stat reset tooling
|
||||
- Auto-promoting stress findings into Playwright regression tests
|
||||
- New admin endpoints for account marking
|
||||
- Admin UI for flagging invites as test-seed
|
||||
|
||||
All of these are cheap to add later because the scenario interface and session pool don't presuppose them.
|
||||
|
||||
## Open questions (to resolve during implementation)
|
||||
|
||||
1. **localStorage auth key** — exact keys used by `client/app.js` to persist the JWT and user blob; verified by reading the file during step 3.
|
||||
2. **Chaos event set for `stress` scenario** — finalize which chaos events are in scope for MVP vs added incrementally (start with rapid clicks + tab nav + `setOffline`, add more as the server proves robust).
|
||||
3. **CDP screencast frame rate tuning** — start at `everyNthFrame: 2` (~15fps), adjust down if bandwidth/CPU is excessive on long runs.
|
||||
4. **Screen bounds detection for `tiled` mode** — default to 1920×1080, expose override via `--tiled-bounds=WxH`; auto-detect later if useful.
|
||||
@@ -1,10 +1,10 @@
|
||||
[project]
|
||||
name = "golfgame"
|
||||
version = "3.1.6"
|
||||
version = "3.3.4"
|
||||
description = "6-Card Golf card game with AI opponents"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
license = {text = "MIT"}
|
||||
license = {text = "GPL-3.0-or-later"}
|
||||
authors = [
|
||||
{name = "alee"}
|
||||
]
|
||||
@@ -13,7 +13,7 @@ classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Framework :: FastAPI",
|
||||
"Intended Audience :: End Users/Desktop",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
|
||||
42
scripts/deploy-prod.sh
Executable file
42
scripts/deploy-prod.sh
Executable file
@@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
TAG="${1:?Usage: deploy-prod.sh <tag> (e.g. v3.3.2)}"
|
||||
DROPLET="root@165.245.152.51"
|
||||
IMAGE="git.adlee.work/alee/golfgame"
|
||||
|
||||
echo "Deploying $TAG to production ($DROPLET)..."
|
||||
|
||||
ssh $DROPLET bash -s "$TAG" "$IMAGE" <<'REMOTE'
|
||||
set -e
|
||||
TAG="$1"
|
||||
IMAGE="$2"
|
||||
|
||||
cd /opt/golfgame
|
||||
|
||||
# Pull the image that passed staging
|
||||
docker pull "$IMAGE:$TAG"
|
||||
docker tag "$IMAGE:$TAG" golfgame-app:latest
|
||||
|
||||
# Update code for compose/env changes
|
||||
git fetch origin
|
||||
git checkout "$TAG"
|
||||
|
||||
# Restart app
|
||||
docker compose -f docker-compose.prod.yml up -d app
|
||||
|
||||
# Wait for healthy
|
||||
echo "Waiting for health check..."
|
||||
for i in $(seq 1 30); do
|
||||
if docker compose -f docker-compose.prod.yml ps app | grep -q "healthy"; then
|
||||
echo "Production deploy successful — $TAG"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "CRITICAL: app not healthy after 60s"
|
||||
docker compose -f docker-compose.prod.yml logs --tail=30 app
|
||||
exit 1
|
||||
REMOTE
|
||||
|
||||
echo "Done."
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""AI personalities for CPU players in Golf."""
|
||||
|
||||
import logging
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Authentication and user management for Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Centralized configuration for Golf game server.
|
||||
|
||||
@@ -148,6 +149,9 @@ class ServerConfig:
|
||||
SECRET_KEY: str = ""
|
||||
INVITE_ONLY: bool = True
|
||||
|
||||
# Allow visitors to request an invite (shown on login page when invite-only)
|
||||
INVITE_REQUEST_ENABLED: bool = False
|
||||
|
||||
# Metered open signups (public beta)
|
||||
# 0 = disabled (invite-only), -1 = unlimited, N = max per day
|
||||
DAILY_OPEN_SIGNUPS: int = 0
|
||||
@@ -202,6 +206,7 @@ class ServerConfig:
|
||||
ROOM_IDLE_TIMEOUT_SECONDS=get_env_int("ROOM_IDLE_TIMEOUT_SECONDS", 300),
|
||||
SECRET_KEY=get_env("SECRET_KEY", ""),
|
||||
INVITE_ONLY=get_env_bool("INVITE_ONLY", True),
|
||||
INVITE_REQUEST_ENABLED=get_env_bool("INVITE_REQUEST_ENABLED", False),
|
||||
DAILY_OPEN_SIGNUPS=get_env_int("DAILY_OPEN_SIGNUPS", 0),
|
||||
DAILY_SIGNUPS_PER_IP=get_env_int("DAILY_SIGNUPS_PER_IP", 3),
|
||||
BOOTSTRAP_ADMIN_USERNAME=get_env("BOOTSTRAP_ADMIN_USERNAME", ""),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Card value constants for 6-Card Golf.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Game logic for 6-Card Golf.
|
||||
|
||||
@@ -782,9 +783,17 @@ class Game:
|
||||
for i, player in enumerate(self.players):
|
||||
if player.id == player_id:
|
||||
removed = self.players.pop(i)
|
||||
# Adjust dealer_idx if needed after removal
|
||||
if self.players and self.dealer_idx >= len(self.players):
|
||||
self.dealer_idx = 0
|
||||
if self.players:
|
||||
# Adjust dealer_idx if needed after removal
|
||||
if self.dealer_idx >= len(self.players):
|
||||
self.dealer_idx = 0
|
||||
# Adjust current_player_index after removal
|
||||
if i < self.current_player_index:
|
||||
# Removed player was before current: shift back
|
||||
self.current_player_index -= 1
|
||||
elif self.current_player_index >= len(self.players):
|
||||
# Removed player was at/after current and index is now OOB
|
||||
self.current_player_index = 0
|
||||
self._emit("player_left", player_id=player_id, reason=reason)
|
||||
return removed
|
||||
return None
|
||||
@@ -807,6 +816,8 @@ class Game:
|
||||
def current_player(self) -> Optional[Player]:
|
||||
"""Get the player whose turn it currently is."""
|
||||
if self.players:
|
||||
if self.current_player_index >= len(self.players):
|
||||
self.current_player_index = self.current_player_index % len(self.players)
|
||||
return self.players[self.current_player_index]
|
||||
return None
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Game Analyzer for 6-Card Golf AI decisions.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""WebSocket message handlers for the Golf card game.
|
||||
|
||||
Each handler corresponds to a single message type from the client.
|
||||
@@ -313,22 +314,6 @@ async def handle_swap(data: dict, ctx: ConnectionContext, *, broadcast_game_stat
|
||||
reason=f"swapped {drawn_card.rank.value} into position {position}, replaced {old_rank}",
|
||||
)
|
||||
|
||||
# Broadcast reveal of old face-down card before state update
|
||||
if old_card_data:
|
||||
reveal_msg = {
|
||||
"type": "card_revealed",
|
||||
"player_id": ctx.player_id,
|
||||
"position": position,
|
||||
"card": old_card_data,
|
||||
}
|
||||
for pid, p in ctx.current_room.players.items():
|
||||
if not p.is_cpu and p.websocket:
|
||||
try:
|
||||
await p.websocket.send_json(reveal_msg)
|
||||
except Exception:
|
||||
pass
|
||||
await asyncio.sleep(1.0)
|
||||
|
||||
await broadcast_game_state(ctx.current_room)
|
||||
await asyncio.sleep(1.0)
|
||||
check_and_run_cpu_turn(ctx.current_room)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Structured logging configuration for Golf game server.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""FastAPI WebSocket server for Golf card game."""
|
||||
|
||||
import asyncio
|
||||
@@ -431,7 +432,7 @@ async def _close_all_websockets():
|
||||
app = FastAPI(
|
||||
title="Golf Card Game",
|
||||
debug=config.DEBUG,
|
||||
version="3.1.6",
|
||||
version="3.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
@@ -943,7 +944,18 @@ if os.path.exists(client_path):
|
||||
return FileResponse(os.path.join(client_path, "index.html"))
|
||||
|
||||
# Mount static files for everything else (JS, CSS, SVG, etc.)
|
||||
app.mount("/", StaticFiles(directory=client_path), name="static")
|
||||
# Wrap StaticFiles to reject WebSocket requests gracefully instead of
|
||||
# crashing with AssertionError (starlette asserts scope["type"] == "http").
|
||||
static_files = StaticFiles(directory=client_path)
|
||||
|
||||
async def safe_static_files(scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
if scope["type"] == "websocket":
|
||||
await send({"type": "websocket.close", "code": 1000})
|
||||
return
|
||||
await static_files(scope, receive, send)
|
||||
|
||||
app.mount("/", safe_static_files, name="static")
|
||||
|
||||
|
||||
def run():
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Middleware components for Golf game server.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Rate limiting middleware for FastAPI.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Request ID middleware for request tracing.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Security headers middleware for FastAPI.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Models package for Golf game V2."""
|
||||
|
||||
from .events import EventType, GameEvent
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Event definitions for Golf game event sourcing.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Game state rebuilder for event sourcing.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
User-related models for Golf game authentication.
|
||||
|
||||
@@ -44,6 +45,7 @@ class User:
|
||||
is_banned: Whether user is banned.
|
||||
ban_reason: Reason for ban (if banned).
|
||||
force_password_reset: Whether user must reset password on next login.
|
||||
is_test_account: True for accounts created by the soak test harness.
|
||||
"""
|
||||
id: str
|
||||
username: str
|
||||
@@ -65,6 +67,7 @@ class User:
|
||||
is_banned: bool = False
|
||||
ban_reason: Optional[str] = None
|
||||
force_password_reset: bool = False
|
||||
is_test_account: bool = False
|
||||
|
||||
def is_admin(self) -> bool:
|
||||
"""Check if user has admin role."""
|
||||
@@ -99,6 +102,7 @@ class User:
|
||||
"is_banned": self.is_banned,
|
||||
"ban_reason": self.ban_reason,
|
||||
"force_password_reset": self.force_password_reset,
|
||||
"is_test_account": self.is_test_account,
|
||||
}
|
||||
if include_sensitive:
|
||||
d["password_hash"] = self.password_hash
|
||||
@@ -145,6 +149,7 @@ class User:
|
||||
is_banned=d.get("is_banned", False),
|
||||
ban_reason=d.get("ban_reason"),
|
||||
force_password_reset=d.get("force_password_reset", False),
|
||||
is_test_account=d.get("is_test_account", False),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Room management for multiplayer Golf games.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Routers package for Golf game API."""
|
||||
|
||||
from .auth import router as auth_router
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Admin API router for Golf game V2.
|
||||
|
||||
@@ -83,6 +84,7 @@ async def list_users(
|
||||
offset: int = 0,
|
||||
include_banned: bool = True,
|
||||
include_deleted: bool = False,
|
||||
include_test: bool = True,
|
||||
admin: User = Depends(require_admin_v2),
|
||||
service: AdminService = Depends(get_admin_service_dep),
|
||||
):
|
||||
@@ -95,6 +97,10 @@ async def list_users(
|
||||
offset: Results to skip.
|
||||
include_banned: Include banned users.
|
||||
include_deleted: Include soft-deleted users.
|
||||
include_test: Include soak-harness test accounts (default true).
|
||||
Admins see all accounts by default; pass ?include_test=false
|
||||
to hide test accounts. Public stats endpoints default to
|
||||
hiding them.
|
||||
"""
|
||||
users = await service.search_users(
|
||||
query=query,
|
||||
@@ -102,6 +108,7 @@ async def list_users(
|
||||
offset=offset,
|
||||
include_banned=include_banned,
|
||||
include_deleted=include_deleted,
|
||||
include_test=include_test,
|
||||
)
|
||||
return {"users": [u.to_dict() for u in users]}
|
||||
|
||||
@@ -417,3 +424,76 @@ async def revoke_invite_code(
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Invite code not found")
|
||||
return {"message": "Invite code revoked successfully"}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Invite Request Endpoints
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@router.get("/invite-requests")
|
||||
async def list_invite_requests(
|
||||
status: Optional[str] = None,
|
||||
admin: User = Depends(require_admin_v2),
|
||||
service: AdminService = Depends(get_admin_service_dep),
|
||||
):
|
||||
"""List invite requests, optionally filtered by status (pending, approved, denied)."""
|
||||
requests = await service.get_invite_requests(status=status)
|
||||
return {"requests": [r.to_dict() for r in requests]}
|
||||
|
||||
|
||||
@router.post("/invite-requests/{request_id}/approve")
|
||||
async def approve_invite_request(
|
||||
request_id: int,
|
||||
request: Request,
|
||||
admin: User = Depends(require_admin_v2),
|
||||
service: AdminService = Depends(get_admin_service_dep),
|
||||
):
|
||||
"""Approve an invite request — creates a code and emails the requester."""
|
||||
code = await service.approve_invite_request(
|
||||
request_id=request_id,
|
||||
admin_id=admin.id,
|
||||
ip_address=get_client_ip(request),
|
||||
)
|
||||
if not code:
|
||||
raise HTTPException(status_code=404, detail="Request not found or already handled")
|
||||
|
||||
# Get the request details to send the approval email
|
||||
requests = await service.get_invite_requests()
|
||||
req = next((r for r in requests if r.id == request_id), None)
|
||||
if req:
|
||||
from services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
await email_service.send_invite_approved_email(
|
||||
to=req.email,
|
||||
name=req.name,
|
||||
invite_code=code,
|
||||
)
|
||||
|
||||
return {"code": code, "message": "Request approved and invite sent"}
|
||||
|
||||
|
||||
@router.post("/invite-requests/{request_id}/deny")
|
||||
async def deny_invite_request(
|
||||
request_id: int,
|
||||
request: Request,
|
||||
admin: User = Depends(require_admin_v2),
|
||||
service: AdminService = Depends(get_admin_service_dep),
|
||||
):
|
||||
"""Deny an invite request — optionally emails the requester."""
|
||||
result = await service.deny_invite_request(
|
||||
request_id=request_id,
|
||||
admin_id=admin.id,
|
||||
ip_address=get_client_ip(request),
|
||||
)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Request not found or already handled")
|
||||
|
||||
from services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
await email_service.send_invite_denied_email(
|
||||
to=result["email"],
|
||||
name=result["name"],
|
||||
)
|
||||
|
||||
return {"message": "Request denied"}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Authentication API router for Golf game V2.
|
||||
|
||||
@@ -74,6 +75,13 @@ class UpdatePreferencesRequest(BaseModel):
|
||||
preferences: dict
|
||||
|
||||
|
||||
class InviteRequestBody(BaseModel):
|
||||
"""Invite request body."""
|
||||
name: str
|
||||
email: str
|
||||
message: Optional[str] = None
|
||||
|
||||
|
||||
class ConvertGuestRequest(BaseModel):
|
||||
"""Convert guest to user request."""
|
||||
guest_id: str
|
||||
@@ -237,11 +245,23 @@ async def register(
|
||||
)
|
||||
|
||||
# --- Invite code validation ---
|
||||
is_test_account = False
|
||||
if has_invite:
|
||||
if not _admin_service:
|
||||
raise HTTPException(status_code=503, detail="Admin service not initialized")
|
||||
if not await _admin_service.validate_invite_code(request_body.invite_code):
|
||||
raise HTTPException(status_code=400, detail="Invalid or expired invite code")
|
||||
# Check if this invite flags new accounts as test accounts
|
||||
invite_details = await _admin_service.get_invite_code_details(request_body.invite_code)
|
||||
if invite_details and invite_details.get("marks_as_test"):
|
||||
is_test_account = True
|
||||
logger.info(
|
||||
"test_seed_account_registering",
|
||||
extra={
|
||||
"username": request_body.username,
|
||||
"invite_code": request_body.invite_code,
|
||||
},
|
||||
)
|
||||
else:
|
||||
# No invite code — check if open signups are allowed
|
||||
if config.INVITE_ONLY and config.DAILY_OPEN_SIGNUPS == 0:
|
||||
@@ -269,6 +289,7 @@ async def register(
|
||||
username=request_body.username,
|
||||
password=request_body.password,
|
||||
email=request_body.email,
|
||||
is_test_account=is_test_account,
|
||||
)
|
||||
|
||||
if not result.success:
|
||||
@@ -331,6 +352,7 @@ async def signup_info():
|
||||
|
||||
return {
|
||||
"invite_required": invite_required,
|
||||
"invite_request_enabled": config.INVITE_REQUEST_ENABLED,
|
||||
"open_signups_enabled": open_signups_enabled,
|
||||
"daily_limit": config.DAILY_OPEN_SIGNUPS if not unlimited else None,
|
||||
"remaining_today": remaining,
|
||||
@@ -338,6 +360,55 @@ async def signup_info():
|
||||
}
|
||||
|
||||
|
||||
@router.post("/request-invite")
|
||||
async def request_invite(
|
||||
request_body: InviteRequestBody,
|
||||
request: Request,
|
||||
):
|
||||
"""
|
||||
Public endpoint: submit a request for an invite code.
|
||||
|
||||
Stores the request in the database and notifies admins via email.
|
||||
"""
|
||||
if not config.INVITE_REQUEST_ENABLED:
|
||||
raise HTTPException(status_code=404, detail="Invite requests are not enabled")
|
||||
|
||||
if not _admin_service:
|
||||
raise HTTPException(status_code=503, detail="Service not initialized")
|
||||
|
||||
name = request_body.name.strip()
|
||||
email = request_body.email.strip().lower()
|
||||
message = request_body.message.strip() if request_body.message else None
|
||||
|
||||
if not name or len(name) > 100:
|
||||
raise HTTPException(status_code=400, detail="Name is required (max 100 characters)")
|
||||
if not email or "@" not in email:
|
||||
raise HTTPException(status_code=400, detail="Valid email is required")
|
||||
|
||||
client_ip = get_client_ip(request)
|
||||
|
||||
request_id = await _admin_service.create_invite_request(
|
||||
name=name,
|
||||
email=email,
|
||||
message=message,
|
||||
ip_address=client_ip,
|
||||
)
|
||||
|
||||
# Notify admin emails
|
||||
if config.ADMIN_EMAILS:
|
||||
from services.email_service import get_email_service
|
||||
email_service = get_email_service()
|
||||
for admin_email in config.ADMIN_EMAILS:
|
||||
await email_service.send_invite_request_admin_notification(
|
||||
to=admin_email,
|
||||
requester_name=name,
|
||||
requester_email=email,
|
||||
message=message or "",
|
||||
)
|
||||
|
||||
return {"status": "ok", "message": "Your request has been submitted. We'll be in touch!"}
|
||||
|
||||
|
||||
@router.post("/verify-email")
|
||||
async def verify_email(
|
||||
request_body: VerifyEmailRequest,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Health check endpoints for production deployment.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Replay API router for Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Stats and Leaderboards API router for Golf game.
|
||||
|
||||
@@ -158,6 +159,7 @@ async def get_leaderboard(
|
||||
metric: str = Query("wins", pattern="^(wins|win_rate|avg_score|knockouts|streak|rating)$"),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
include_test: bool = Query(False, description="Include soak-harness test accounts"),
|
||||
service: StatsService = Depends(get_stats_service_dep),
|
||||
):
|
||||
"""
|
||||
@@ -171,8 +173,9 @@ async def get_leaderboard(
|
||||
- streak: Best win streak
|
||||
|
||||
Players must have 5+ games to appear on leaderboards.
|
||||
By default, soak-harness test accounts are hidden.
|
||||
"""
|
||||
entries = await service.get_leaderboard(metric, limit, offset)
|
||||
entries = await service.get_leaderboard(metric, limit, offset, include_test)
|
||||
|
||||
return {
|
||||
"metric": metric,
|
||||
@@ -227,10 +230,11 @@ async def get_player_stats(
|
||||
async def get_player_rank(
|
||||
user_id: str,
|
||||
metric: str = Query("wins", pattern="^(wins|win_rate|avg_score|knockouts|streak|rating)$"),
|
||||
include_test: bool = Query(False, description="Include soak-harness test accounts"),
|
||||
service: StatsService = Depends(get_stats_service_dep),
|
||||
):
|
||||
"""Get player's rank on a leaderboard."""
|
||||
rank = await service.get_player_rank(user_id, metric)
|
||||
rank = await service.get_player_rank(user_id, metric, include_test)
|
||||
|
||||
return {
|
||||
"user_id": user_id,
|
||||
@@ -347,11 +351,12 @@ async def get_my_stats(
|
||||
@router.get("/me/rank", response_model=PlayerRankResponse)
|
||||
async def get_my_rank(
|
||||
metric: str = Query("wins", pattern="^(wins|win_rate|avg_score|knockouts|streak|rating)$"),
|
||||
include_test: bool = Query(False, description="Include soak-harness test accounts"),
|
||||
user: User = Depends(require_user),
|
||||
service: StatsService = Depends(get_stats_service_dep),
|
||||
):
|
||||
"""Get current user's rank on a leaderboard."""
|
||||
rank = await service.get_player_rank(user.id, metric)
|
||||
rank = await service.get_player_rank(user.id, metric, include_test)
|
||||
|
||||
return {
|
||||
"user_id": user.id,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Score distribution analysis for Golf AI.
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Create an admin user for the Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Services package for Golf game V2 business logic."""
|
||||
|
||||
from .recovery_service import RecoveryService, RecoveryResult
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Admin service for Golf game.
|
||||
|
||||
@@ -37,6 +38,7 @@ class UserDetails:
|
||||
is_active: bool
|
||||
games_played: int
|
||||
games_won: int
|
||||
is_test_account: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
@@ -54,6 +56,7 @@ class UserDetails:
|
||||
"is_active": self.is_active,
|
||||
"games_played": self.games_played,
|
||||
"games_won": self.games_won,
|
||||
"is_test_account": self.is_test_account,
|
||||
}
|
||||
|
||||
|
||||
@@ -122,6 +125,7 @@ class InviteCode:
|
||||
max_uses: int
|
||||
use_count: int
|
||||
is_active: bool
|
||||
marks_as_test: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
@@ -134,6 +138,36 @@ class InviteCode:
|
||||
"use_count": self.use_count,
|
||||
"is_active": self.is_active,
|
||||
"remaining_uses": max(0, self.max_uses - self.use_count),
|
||||
"marks_as_test": self.marks_as_test,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class InviteRequest:
|
||||
"""Invite request details."""
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
message: Optional[str]
|
||||
status: str
|
||||
ip_address: Optional[str]
|
||||
created_at: datetime
|
||||
reviewed_at: Optional[datetime]
|
||||
reviewed_by: Optional[str]
|
||||
reviewed_by_username: Optional[str] = None
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"email": self.email,
|
||||
"message": self.message,
|
||||
"status": self.status,
|
||||
"ip_address": self.ip_address,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
"reviewed_at": self.reviewed_at.isoformat() if self.reviewed_at else None,
|
||||
"reviewed_by": self.reviewed_by,
|
||||
"reviewed_by_username": self.reviewed_by_username,
|
||||
}
|
||||
|
||||
|
||||
@@ -286,6 +320,7 @@ class AdminService:
|
||||
offset: int = 0,
|
||||
include_banned: bool = True,
|
||||
include_deleted: bool = False,
|
||||
include_test: bool = True,
|
||||
) -> List[UserDetails]:
|
||||
"""
|
||||
Search users by username or email.
|
||||
@@ -296,6 +331,10 @@ class AdminService:
|
||||
offset: Number of results to skip.
|
||||
include_banned: Include banned users.
|
||||
include_deleted: Include soft-deleted users.
|
||||
include_test: Include soak-harness test accounts (default True).
|
||||
Admins see all accounts by default; the admin UI provides a
|
||||
toggle to hide test accounts. Public stats endpoints use the
|
||||
opposite default (False) so real users never see soak traffic.
|
||||
|
||||
Returns:
|
||||
List of user details.
|
||||
@@ -306,6 +345,7 @@ class AdminService:
|
||||
u.email_verified, u.is_banned, u.ban_reason,
|
||||
u.force_password_reset, u.created_at, u.last_login,
|
||||
u.last_seen_at, u.is_active,
|
||||
COALESCE(u.is_test_account, FALSE) as is_test_account,
|
||||
COALESCE(s.games_played, 0) as games_played,
|
||||
COALESCE(s.games_won, 0) as games_won
|
||||
FROM users_v2 u
|
||||
@@ -326,6 +366,9 @@ class AdminService:
|
||||
if not include_deleted:
|
||||
sql += " AND u.deleted_at IS NULL"
|
||||
|
||||
if not include_test:
|
||||
sql += " AND (u.is_test_account = FALSE OR u.is_test_account IS NULL)"
|
||||
|
||||
sql += f" ORDER BY u.created_at DESC LIMIT ${param_num} OFFSET ${param_num + 1}"
|
||||
params.extend([limit, offset])
|
||||
|
||||
@@ -347,6 +390,7 @@ class AdminService:
|
||||
is_active=row["is_active"],
|
||||
games_played=row["games_played"] or 0,
|
||||
games_won=row["games_won"] or 0,
|
||||
is_test_account=row["is_test_account"],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
@@ -355,6 +399,10 @@ class AdminService:
|
||||
"""
|
||||
Get detailed user info by ID.
|
||||
|
||||
Note: Returns the user regardless of is_test_account status.
|
||||
Filtering by test-account only applies to list views
|
||||
(search_users). If you know the ID, you get the row.
|
||||
|
||||
Args:
|
||||
user_id: User UUID.
|
||||
|
||||
@@ -368,6 +416,7 @@ class AdminService:
|
||||
u.email_verified, u.is_banned, u.ban_reason,
|
||||
u.force_password_reset, u.created_at, u.last_login,
|
||||
u.last_seen_at, u.is_active,
|
||||
COALESCE(u.is_test_account, FALSE) as is_test_account,
|
||||
COALESCE(s.games_played, 0) as games_played,
|
||||
COALESCE(s.games_won, 0) as games_won
|
||||
FROM users_v2 u
|
||||
@@ -395,6 +444,7 @@ class AdminService:
|
||||
is_active=row["is_active"],
|
||||
games_played=row["games_played"] or 0,
|
||||
games_won=row["games_won"] or 0,
|
||||
is_test_account=row["is_test_account"],
|
||||
)
|
||||
|
||||
async def ban_user(
|
||||
@@ -1087,6 +1137,7 @@ class AdminService:
|
||||
query = """
|
||||
SELECT c.code, c.created_by, c.created_at, c.expires_at,
|
||||
c.max_uses, c.use_count, c.is_active,
|
||||
COALESCE(c.marks_as_test, FALSE) as marks_as_test,
|
||||
u.username as created_by_username
|
||||
FROM invite_codes c
|
||||
JOIN users_v2 u ON c.created_by = u.id
|
||||
@@ -1108,6 +1159,7 @@ class AdminService:
|
||||
max_uses=row["max_uses"],
|
||||
use_count=row["use_count"],
|
||||
is_active=row["is_active"],
|
||||
marks_as_test=row["marks_as_test"],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
@@ -1183,6 +1235,34 @@ class AdminService:
|
||||
|
||||
return True
|
||||
|
||||
async def get_invite_code_details(self, code: str) -> Optional[dict]:
|
||||
"""
|
||||
Look up an invite code's row including marks_as_test.
|
||||
|
||||
Returns None if the code does not exist. Does NOT validate expiry
|
||||
or usage — use validate_invite_code for that. This is purely a
|
||||
helper for the register flow to discover the test-seed flag.
|
||||
"""
|
||||
async with self.pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT code, max_uses, use_count, is_active,
|
||||
COALESCE(marks_as_test, FALSE) as marks_as_test
|
||||
FROM invite_codes
|
||||
WHERE code = $1
|
||||
""",
|
||||
code,
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"code": row["code"],
|
||||
"max_uses": row["max_uses"],
|
||||
"use_count": row["use_count"],
|
||||
"is_active": row["is_active"],
|
||||
"marks_as_test": row["marks_as_test"],
|
||||
}
|
||||
|
||||
async def use_invite_code(self, code: str) -> bool:
|
||||
"""
|
||||
Use an invite code (increment use count).
|
||||
@@ -1210,6 +1290,183 @@ class AdminService:
|
||||
|
||||
return result != "UPDATE 0"
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
# Invite Requests
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
async def create_invite_request(
|
||||
self,
|
||||
name: str,
|
||||
email: str,
|
||||
message: Optional[str] = None,
|
||||
ip_address: Optional[str] = None,
|
||||
) -> int:
|
||||
"""
|
||||
Create a new invite request.
|
||||
|
||||
Returns:
|
||||
The request ID.
|
||||
"""
|
||||
async with self.pool.acquire() as conn:
|
||||
# Check for existing pending request from same email
|
||||
existing = await conn.fetchval(
|
||||
"SELECT id FROM invite_requests WHERE email = $1 AND status = 'pending'",
|
||||
email,
|
||||
)
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
row_id = await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO invite_requests (name, email, message, ip_address)
|
||||
VALUES ($1, $2, $3, $4::inet)
|
||||
RETURNING id
|
||||
""",
|
||||
name,
|
||||
email,
|
||||
message,
|
||||
ip_address,
|
||||
)
|
||||
|
||||
logger.info(f"New invite request #{row_id} from {email}")
|
||||
return row_id
|
||||
|
||||
async def get_invite_requests(self, status: Optional[str] = None) -> List[InviteRequest]:
|
||||
"""Get invite requests, optionally filtered by status."""
|
||||
async with self.pool.acquire() as conn:
|
||||
query = """
|
||||
SELECT r.id, r.name, r.email, r.message, r.status, r.ip_address,
|
||||
r.created_at, r.reviewed_at, r.reviewed_by,
|
||||
u.username as reviewed_by_username
|
||||
FROM invite_requests r
|
||||
LEFT JOIN users_v2 u ON r.reviewed_by = u.id
|
||||
"""
|
||||
params = []
|
||||
if status:
|
||||
query += " WHERE r.status = $1"
|
||||
params.append(status)
|
||||
query += " ORDER BY r.created_at DESC"
|
||||
|
||||
rows = await conn.fetch(query, *params)
|
||||
|
||||
return [
|
||||
InviteRequest(
|
||||
id=row["id"],
|
||||
name=row["name"],
|
||||
email=row["email"],
|
||||
message=row["message"],
|
||||
status=row["status"],
|
||||
ip_address=str(row["ip_address"]) if row["ip_address"] else None,
|
||||
created_at=row["created_at"],
|
||||
reviewed_at=row["reviewed_at"],
|
||||
reviewed_by=str(row["reviewed_by"]) if row["reviewed_by"] else None,
|
||||
reviewed_by_username=row["reviewed_by_username"],
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def approve_invite_request(
|
||||
self,
|
||||
request_id: int,
|
||||
admin_id: str,
|
||||
ip_address: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Approve an invite request: create an invite code and update the request.
|
||||
|
||||
Returns:
|
||||
The generated invite code, or None if request not found/already handled.
|
||||
"""
|
||||
async with self.pool.acquire() as conn:
|
||||
# Verify request exists and is pending
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, email, name FROM invite_requests WHERE id = $1 AND status = 'pending'",
|
||||
request_id,
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
|
||||
# Create an invite code for this request
|
||||
code = secrets.token_urlsafe(6).upper()[:8]
|
||||
expires_at = datetime.now(timezone.utc) + timedelta(days=7)
|
||||
|
||||
invite_id = await conn.fetchval(
|
||||
"""
|
||||
INSERT INTO invite_codes (code, created_by, expires_at, max_uses)
|
||||
VALUES ($1, $2, $3, 1)
|
||||
RETURNING id
|
||||
""",
|
||||
code,
|
||||
admin_id,
|
||||
expires_at,
|
||||
)
|
||||
|
||||
# Update the request
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE invite_requests
|
||||
SET status = 'approved', reviewed_at = NOW(), reviewed_by = $1, invite_code_id = $2
|
||||
WHERE id = $3
|
||||
""",
|
||||
admin_id,
|
||||
invite_id,
|
||||
request_id,
|
||||
)
|
||||
|
||||
await self.audit(
|
||||
admin_id,
|
||||
"approve_invite_request",
|
||||
"invite_request",
|
||||
str(request_id),
|
||||
{"email": row["email"], "invite_code": code},
|
||||
ip_address,
|
||||
)
|
||||
|
||||
logger.info(f"Admin {admin_id} approved invite request #{request_id}, code={code}")
|
||||
return code
|
||||
|
||||
async def deny_invite_request(
|
||||
self,
|
||||
request_id: int,
|
||||
admin_id: str,
|
||||
ip_address: Optional[str] = None,
|
||||
) -> Optional[dict]:
|
||||
"""
|
||||
Deny an invite request.
|
||||
|
||||
Returns:
|
||||
The request info (name, email) or None if not found/already handled.
|
||||
"""
|
||||
async with self.pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT id, email, name FROM invite_requests WHERE id = $1 AND status = 'pending'",
|
||||
request_id,
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE invite_requests
|
||||
SET status = 'denied', reviewed_at = NOW(), reviewed_by = $1
|
||||
WHERE id = $2
|
||||
""",
|
||||
admin_id,
|
||||
request_id,
|
||||
)
|
||||
|
||||
await self.audit(
|
||||
admin_id,
|
||||
"deny_invite_request",
|
||||
"invite_request",
|
||||
str(request_id),
|
||||
{"email": row["email"]},
|
||||
ip_address,
|
||||
)
|
||||
|
||||
logger.info(f"Admin {admin_id} denied invite request #{request_id}")
|
||||
return {"name": row["name"], "email": row["email"]}
|
||||
|
||||
|
||||
# Global admin service instance
|
||||
_admin_service: Optional[AdminService] = None
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Authentication service for Golf game.
|
||||
|
||||
@@ -100,6 +101,7 @@ class AuthService:
|
||||
password: str,
|
||||
email: Optional[str] = None,
|
||||
guest_id: Optional[str] = None,
|
||||
is_test_account: bool = False,
|
||||
) -> RegistrationResult:
|
||||
"""
|
||||
Register a new user account.
|
||||
@@ -109,6 +111,7 @@ class AuthService:
|
||||
password: Plain text password.
|
||||
email: Optional email address.
|
||||
guest_id: Guest session ID if converting.
|
||||
is_test_account: Mark this user as a soak-harness test account.
|
||||
|
||||
Returns:
|
||||
RegistrationResult with user or error.
|
||||
@@ -150,6 +153,7 @@ class AuthService:
|
||||
guest_id=guest_id,
|
||||
verification_token=verification_token,
|
||||
verification_expires=verification_expires,
|
||||
is_test_account=is_test_account,
|
||||
)
|
||||
|
||||
if not user:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Email service for Golf game authentication.
|
||||
|
||||
@@ -164,6 +165,76 @@ class EmailService:
|
||||
|
||||
return await self._send_email(to, subject, html)
|
||||
|
||||
async def send_invite_request_admin_notification(
|
||||
self,
|
||||
to: str,
|
||||
requester_name: str,
|
||||
requester_email: str,
|
||||
message: str,
|
||||
) -> Optional[str]:
|
||||
"""Notify admin of a new invite request."""
|
||||
if not self.is_configured():
|
||||
logger.info(f"Email not configured. Would send invite request notification to {to}")
|
||||
return None
|
||||
|
||||
admin_url = f"{self.base_url}/admin.html"
|
||||
message_html = f"<p><strong>Message:</strong> {message}</p>" if message else ""
|
||||
|
||||
subject = f"Golf Game invite request from {requester_name}"
|
||||
html = f"""
|
||||
<h2>New Invite Request</h2>
|
||||
<p><strong>Name:</strong> {requester_name}</p>
|
||||
<p><strong>Email:</strong> {requester_email}</p>
|
||||
{message_html}
|
||||
<p><a href="{admin_url}">Review in Admin Panel</a></p>
|
||||
"""
|
||||
|
||||
return await self._send_email(to, subject, html)
|
||||
|
||||
async def send_invite_approved_email(
|
||||
self,
|
||||
to: str,
|
||||
name: str,
|
||||
invite_code: str,
|
||||
) -> Optional[str]:
|
||||
"""Notify requester that their invite was approved."""
|
||||
if not self.is_configured():
|
||||
logger.info(f"Email not configured. Would send invite approval to {to}")
|
||||
return None
|
||||
|
||||
signup_url = f"{self.base_url}/?invite={invite_code}"
|
||||
|
||||
subject = "Your Golf Game invite is ready!"
|
||||
html = f"""
|
||||
<h2>You're In, {name}!</h2>
|
||||
<p>Your request to join Golf Game has been approved.</p>
|
||||
<p>Use this link to create your account:</p>
|
||||
<p><a href="{signup_url}">{signup_url}</a></p>
|
||||
<p>Or sign up manually with invite code: <strong>{invite_code}</strong></p>
|
||||
<p>This invite is single-use and expires in 7 days.</p>
|
||||
"""
|
||||
|
||||
return await self._send_email(to, subject, html)
|
||||
|
||||
async def send_invite_denied_email(
|
||||
self,
|
||||
to: str,
|
||||
name: str,
|
||||
) -> Optional[str]:
|
||||
"""Notify requester that their invite was denied."""
|
||||
if not self.is_configured():
|
||||
logger.info(f"Email not configured. Would send invite denial to {to}")
|
||||
return None
|
||||
|
||||
subject = "Golf Game invite request update"
|
||||
html = f"""
|
||||
<h2>Hi {name},</h2>
|
||||
<p>Thanks for your interest in Golf Game. Unfortunately, we're not able to approve your invite request at this time.</p>
|
||||
<p>We may open up registrations in the future — stay tuned!</p>
|
||||
"""
|
||||
|
||||
return await self._send_email(to, subject, html)
|
||||
|
||||
async def _send_email(
|
||||
self,
|
||||
to: str,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
PostgreSQL-backed game logging for AI decision analysis.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Matchmaking service for public skill-based games.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Redis-based rate limiter service.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Glicko-2 rating service for Golf game matchmaking.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Game recovery service for rebuilding active games from event store.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Replay service for Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Spectator manager for Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Stats service for Golf game leaderboards and achievements.
|
||||
|
||||
@@ -170,6 +171,7 @@ class StatsService:
|
||||
metric: str = "wins",
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
include_test: bool = False,
|
||||
) -> List[LeaderboardEntry]:
|
||||
"""
|
||||
Get leaderboard by metric.
|
||||
@@ -178,6 +180,8 @@ class StatsService:
|
||||
metric: Ranking metric - wins, win_rate, avg_score, knockouts, streak.
|
||||
limit: Maximum entries to return.
|
||||
offset: Pagination offset.
|
||||
include_test: If True, include soak-harness test accounts. Default
|
||||
False so real users never see synthetic load-test traffic.
|
||||
|
||||
Returns:
|
||||
List of LeaderboardEntry sorted by metric.
|
||||
@@ -211,9 +215,10 @@ class StatsService:
|
||||
COALESCE(rating, 1500) as rating,
|
||||
ROW_NUMBER() OVER (ORDER BY {column} {direction}) as rank
|
||||
FROM leaderboard_overall
|
||||
WHERE ($3 OR NOT is_test_account)
|
||||
ORDER BY {column} {direction}
|
||||
LIMIT $1 OFFSET $2
|
||||
""", limit, offset)
|
||||
""", limit, offset, include_test)
|
||||
else:
|
||||
# Fall back to direct query
|
||||
rows = await conn.fetch(f"""
|
||||
@@ -229,9 +234,10 @@ class StatsService:
|
||||
WHERE s.games_played >= 5
|
||||
AND u.deleted_at IS NULL
|
||||
AND (u.is_banned = false OR u.is_banned IS NULL)
|
||||
AND ($3 OR NOT COALESCE(u.is_test_account, FALSE))
|
||||
ORDER BY {column} {direction}
|
||||
LIMIT $1 OFFSET $2
|
||||
""", limit, offset)
|
||||
""", limit, offset, include_test)
|
||||
|
||||
return [
|
||||
LeaderboardEntry(
|
||||
@@ -245,16 +251,26 @@ class StatsService:
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def get_player_rank(self, user_id: str, metric: str = "wins") -> Optional[int]:
|
||||
async def get_player_rank(
|
||||
self,
|
||||
user_id: str,
|
||||
metric: str = "wins",
|
||||
include_test: bool = False,
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
Get a player's rank on a leaderboard.
|
||||
|
||||
Args:
|
||||
user_id: User UUID.
|
||||
metric: Ranking metric.
|
||||
include_test: If True, rank within a leaderboard that includes
|
||||
soak-harness test accounts. Default False matches the public
|
||||
leaderboard view.
|
||||
|
||||
Returns:
|
||||
Rank number or None if not ranked (< 5 games or not found).
|
||||
Rank number or None if not ranked (< 5 games or not found, or
|
||||
filtered out because they are a test account and include_test is
|
||||
False).
|
||||
"""
|
||||
order_map = {
|
||||
"wins": ("games_won", "DESC"),
|
||||
@@ -287,9 +303,10 @@ class StatsService:
|
||||
SELECT rank FROM (
|
||||
SELECT user_id, ROW_NUMBER() OVER (ORDER BY {column} {direction}) as rank
|
||||
FROM leaderboard_overall
|
||||
WHERE ($2 OR NOT is_test_account)
|
||||
) ranked
|
||||
WHERE user_id = $1
|
||||
""", user_id)
|
||||
""", user_id, include_test)
|
||||
else:
|
||||
row = await conn.fetchrow(f"""
|
||||
SELECT rank FROM (
|
||||
@@ -299,9 +316,10 @@ class StatsService:
|
||||
WHERE s.games_played >= 5
|
||||
AND u.deleted_at IS NULL
|
||||
AND (u.is_banned = false OR u.is_banned IS NULL)
|
||||
AND ($2 OR NOT COALESCE(u.is_test_account, FALSE))
|
||||
) ranked
|
||||
WHERE user_id = $1
|
||||
""", user_id)
|
||||
""", user_id, include_test)
|
||||
|
||||
return row["rank"] if row else None
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Golf AI Simulation Runner
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Stores package for Golf game V2 persistence."""
|
||||
|
||||
from .event_store import EventStore, ConcurrencyError
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
PostgreSQL-backed event store for Golf game.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Redis pub/sub for cross-server game events.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Redis-backed live game state cache.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
PostgreSQL-backed user store for Golf game authentication.
|
||||
|
||||
@@ -94,6 +95,19 @@ BEGIN
|
||||
WHERE table_name = 'users_v2' AND column_name = 'last_seen_at') THEN
|
||||
ALTER TABLE users_v2 ADD COLUMN last_seen_at TIMESTAMPTZ;
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'users_v2' AND column_name = 'is_test_account') THEN
|
||||
ALTER TABLE users_v2 ADD COLUMN is_test_account BOOLEAN DEFAULT FALSE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Add marks_as_test to invite_codes if not exists
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'invite_codes' AND column_name = 'marks_as_test') THEN
|
||||
ALTER TABLE invite_codes ADD COLUMN marks_as_test BOOLEAN DEFAULT FALSE;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
-- Admin audit log table
|
||||
@@ -132,6 +146,20 @@ CREATE TABLE IF NOT EXISTS invite_codes (
|
||||
is_active BOOLEAN DEFAULT TRUE
|
||||
);
|
||||
|
||||
-- Invite requests table
|
||||
CREATE TABLE IF NOT EXISTS invite_requests (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
email VARCHAR(255) NOT NULL,
|
||||
message TEXT,
|
||||
status VARCHAR(20) DEFAULT 'pending',
|
||||
ip_address INET,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
reviewed_at TIMESTAMPTZ,
|
||||
reviewed_by UUID REFERENCES users_v2(id),
|
||||
invite_code_id BIGINT REFERENCES invite_codes(id)
|
||||
);
|
||||
|
||||
-- Player stats table (extended for V2 leaderboards)
|
||||
CREATE TABLE IF NOT EXISTS player_stats (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
@@ -281,14 +309,14 @@ CREATE TABLE IF NOT EXISTS system_metrics (
|
||||
);
|
||||
|
||||
-- Leaderboard materialized view (refreshed periodically)
|
||||
-- Drop and recreate if missing rating column (v3.1.0 migration)
|
||||
-- Drop and recreate if missing is_test_account column (soak harness migration)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_matviews WHERE matviewname = 'leaderboard_overall') THEN
|
||||
-- Check if rating column exists in the view
|
||||
-- Check if is_test_account column exists in the view
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'leaderboard_overall' AND column_name = 'rating'
|
||||
WHERE table_name = 'leaderboard_overall' AND column_name = 'is_test_account'
|
||||
) THEN
|
||||
DROP MATERIALIZED VIEW leaderboard_overall;
|
||||
END IF;
|
||||
@@ -300,6 +328,7 @@ BEGIN
|
||||
SELECT
|
||||
u.id as user_id,
|
||||
u.username,
|
||||
COALESCE(u.is_test_account, FALSE) as is_test_account,
|
||||
s.games_played,
|
||||
s.games_won,
|
||||
ROUND(s.games_won::numeric / NULLIF(s.games_played, 0) * 100, 1) as win_rate,
|
||||
@@ -327,6 +356,8 @@ CREATE INDEX IF NOT EXISTS idx_users_reset ON users_v2(reset_token) WHERE reset_
|
||||
CREATE INDEX IF NOT EXISTS idx_users_guest ON users_v2(guest_id) WHERE guest_id IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_users_active ON users_v2(is_active) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_users_banned ON users_v2(is_banned) WHERE is_banned = TRUE;
|
||||
CREATE INDEX IF NOT EXISTS idx_users_test_account ON users_v2(is_test_account)
|
||||
WHERE is_test_account = TRUE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_user ON user_sessions(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON user_sessions(token_hash);
|
||||
@@ -445,6 +476,7 @@ class UserStore:
|
||||
guest_id: Optional[str] = None,
|
||||
verification_token: Optional[str] = None,
|
||||
verification_expires: Optional[datetime] = None,
|
||||
is_test_account: bool = False,
|
||||
) -> Optional[User]:
|
||||
"""
|
||||
Create a new user account.
|
||||
@@ -457,6 +489,7 @@ class UserStore:
|
||||
guest_id: Guest session ID if converting.
|
||||
verification_token: Email verification token.
|
||||
verification_expires: Token expiration time.
|
||||
is_test_account: True for accounts created by the soak test harness.
|
||||
|
||||
Returns:
|
||||
Created User, or None if username/email already exists.
|
||||
@@ -466,12 +499,13 @@ class UserStore:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
INSERT INTO users_v2 (username, password_hash, email, role, guest_id,
|
||||
verification_token, verification_expires)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
verification_token, verification_expires,
|
||||
is_test_account)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
""",
|
||||
username,
|
||||
password_hash,
|
||||
@@ -480,6 +514,7 @@ class UserStore:
|
||||
guest_id,
|
||||
verification_token,
|
||||
verification_expires,
|
||||
is_test_account,
|
||||
)
|
||||
return self._row_to_user(row)
|
||||
except asyncpg.UniqueViolationError:
|
||||
@@ -493,7 +528,7 @@ class UserStore:
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
FROM users_v2
|
||||
WHERE id = $1
|
||||
""",
|
||||
@@ -509,7 +544,7 @@ class UserStore:
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
FROM users_v2
|
||||
WHERE LOWER(username) = LOWER($1)
|
||||
""",
|
||||
@@ -525,7 +560,7 @@ class UserStore:
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
FROM users_v2
|
||||
WHERE LOWER(email) = LOWER($1)
|
||||
""",
|
||||
@@ -541,7 +576,7 @@ class UserStore:
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
FROM users_v2
|
||||
WHERE verification_token = $1
|
||||
""",
|
||||
@@ -557,7 +592,7 @@ class UserStore:
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
FROM users_v2
|
||||
WHERE reset_token = $1
|
||||
""",
|
||||
@@ -655,7 +690,7 @@ class UserStore:
|
||||
RETURNING id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, last_seen_at,
|
||||
is_active, is_banned, ban_reason, force_password_reset
|
||||
is_active, is_banned, ban_reason, force_password_reset, is_test_account
|
||||
"""
|
||||
|
||||
async with self.pool.acquire() as conn:
|
||||
@@ -699,7 +734,8 @@ class UserStore:
|
||||
"""
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, is_active
|
||||
guest_id, deleted_at, preferences, created_at, last_login, is_active,
|
||||
is_test_account
|
||||
FROM users_v2
|
||||
ORDER BY created_at DESC
|
||||
"""
|
||||
@@ -709,7 +745,8 @@ class UserStore:
|
||||
"""
|
||||
SELECT id, username, email, password_hash, role, email_verified,
|
||||
verification_token, verification_expires, reset_token, reset_expires,
|
||||
guest_id, deleted_at, preferences, created_at, last_login, is_active
|
||||
guest_id, deleted_at, preferences, created_at, last_login, is_active,
|
||||
is_test_account
|
||||
FROM users_v2
|
||||
WHERE is_active = TRUE AND deleted_at IS NULL
|
||||
ORDER BY created_at DESC
|
||||
@@ -1002,6 +1039,7 @@ class UserStore:
|
||||
is_banned=row.get("is_banned", False) or False,
|
||||
ban_reason=row.get("ban_reason"),
|
||||
force_password_reset=row.get("force_password_reset", False) or False,
|
||||
is_test_account=row.get("is_test_account", False) or False,
|
||||
)
|
||||
|
||||
def _row_to_session(self, row: asyncpg.Record) -> UserSession:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test suite for AI decision sub-functions extracted from ai.py.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Tests for the GameAnalyzer decision evaluation logic.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Tests for the authentication system.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test suite for 6-Card Golf game rules.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test suite for WebSocket message handlers.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
House Rules Testing Suite
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test for the original Maya bug:
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test suite for Room and RoomManager CRUD operations.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Test suite for V3 features in 6-Card Golf.
|
||||
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Tests package for Golf game."""
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Tests for event sourcing and state replay.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Tests for V2 Persistence & Recovery components.
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""
|
||||
Tests for the replay service.
|
||||
|
||||
|
||||
@@ -72,12 +72,20 @@ export class GolfBot {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new game room
|
||||
* Create a new game room.
|
||||
*
|
||||
* Works for both guest sessions (fills the name input) and
|
||||
* authenticated sessions (the name input is hidden; the server
|
||||
* uses the logged-in username). `playerName` is ignored when the
|
||||
* session is authenticated.
|
||||
*/
|
||||
async createGame(playerName: string): Promise<string> {
|
||||
// Enter name
|
||||
// Guest sessions have a visible player-name input; authenticated
|
||||
// sessions don't. Only fill it if it's actually there.
|
||||
const nameInput = this.page.locator(SELECTORS.lobby.playerNameInput);
|
||||
await nameInput.fill(playerName);
|
||||
if (await nameInput.isVisible().catch(() => false)) {
|
||||
await nameInput.fill(playerName);
|
||||
}
|
||||
|
||||
// Click create room
|
||||
const createBtn = this.page.locator(SELECTORS.lobby.createRoomBtn);
|
||||
@@ -97,12 +105,16 @@ export class GolfBot {
|
||||
}
|
||||
|
||||
/**
|
||||
* Join an existing game room
|
||||
* Join an existing game room.
|
||||
*
|
||||
* Same auth handling as `createGame` — `playerName` is ignored for
|
||||
* authenticated sessions.
|
||||
*/
|
||||
async joinGame(roomCode: string, playerName: string): Promise<void> {
|
||||
// Enter name
|
||||
const nameInput = this.page.locator(SELECTORS.lobby.playerNameInput);
|
||||
await nameInput.fill(playerName);
|
||||
if (await nameInput.isVisible().catch(() => false)) {
|
||||
await nameInput.fill(playerName);
|
||||
}
|
||||
|
||||
// Enter room code
|
||||
const codeInput = this.page.locator(SELECTORS.lobby.roomCodeInput);
|
||||
@@ -172,7 +184,19 @@ export class GolfBot {
|
||||
await this.page.selectOption(SELECTORS.waiting.numRounds, String(options.holes));
|
||||
}
|
||||
if (options.decks) {
|
||||
await this.page.selectOption(SELECTORS.waiting.numDecks, String(options.decks));
|
||||
// #num-decks is a stepper (hidden input + +/- buttons), not a select.
|
||||
// Click the stepper until the hidden input matches the requested value.
|
||||
const target = options.decks;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const current = parseInt(
|
||||
(await this.page.locator(SELECTORS.waiting.numDecks).inputValue().catch(() => '1')) || '1',
|
||||
10,
|
||||
);
|
||||
if (current === target) break;
|
||||
const btnId = current < target ? '#decks-plus' : '#decks-minus';
|
||||
await this.page.locator(btnId).click({ timeout: 1000 }).catch(() => {});
|
||||
await this.page.waitForTimeout(50);
|
||||
}
|
||||
}
|
||||
if (options.initialFlips !== undefined) {
|
||||
await this.page.selectOption(SELECTORS.waiting.initialFlips, String(options.initialFlips));
|
||||
|
||||
6
tests/soak/.env.stresstest.example
Normal file
6
tests/soak/.env.stresstest.example
Normal file
@@ -0,0 +1,6 @@
|
||||
# Soak harness account cache.
|
||||
# This file is AUTO-GENERATED on first run; do not edit by hand.
|
||||
# Format: SOAK_ACCOUNT_NN=username:password:token
|
||||
#
|
||||
# Example (delete before first real run):
|
||||
# SOAK_ACCOUNT_00=soak_00_a7bx:<generated-password>:<jwt-token>
|
||||
5
tests/soak/.gitignore
vendored
Normal file
5
tests/soak/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
artifacts/
|
||||
.env.stresstest
|
||||
*.log
|
||||
21
tests/soak/README.md
Normal file
21
tests/soak/README.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# Golf Soak & UX Test Harness
|
||||
|
||||
Runs 16 authenticated browser sessions across 4 rooms to populate
|
||||
staging scoreboards and stress-test multiplayer stability.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-04-10-multiplayer-soak-test-design.md`
|
||||
**Bring-up:** `docs/soak-harness-bringup.md`
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
cd tests/soak
|
||||
bun install
|
||||
bun run seed # first run only
|
||||
TEST_URL=http://localhost:8000 bun run smoke
|
||||
```
|
||||
|
||||
(The scripts also work with `npm run`, `pnpm run`, etc. — bun is what's installed
|
||||
on this dev machine.)
|
||||
|
||||
Full documentation arrives with Task 31.
|
||||
344
tests/soak/bun.lock
Normal file
344
tests/soak/bun.lock
Normal file
@@ -0,0 +1,344 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 1,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "golf-soak",
|
||||
"dependencies": {
|
||||
"playwright-core": "^1.40.0",
|
||||
"ws": "^8.16.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.40.0",
|
||||
"@types/node": "^20.10.0",
|
||||
"@types/ws": "^8.5.0",
|
||||
"tsx": "^4.7.0",
|
||||
"typescript": "^5.3.0",
|
||||
"vitest": "^1.2.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.27.7", "", { "os": "android", "cpu": "arm" }, "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ=="],
|
||||
|
||||
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.7", "", { "os": "android", "cpu": "arm64" }, "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ=="],
|
||||
|
||||
"@esbuild/android-x64": ["@esbuild/android-x64@0.27.7", "", { "os": "android", "cpu": "x64" }, "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg=="],
|
||||
|
||||
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw=="],
|
||||
|
||||
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ=="],
|
||||
|
||||
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.7", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w=="],
|
||||
|
||||
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.7", "", { "os": "freebsd", "cpu": "x64" }, "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ=="],
|
||||
|
||||
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.7", "", { "os": "linux", "cpu": "arm" }, "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA=="],
|
||||
|
||||
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A=="],
|
||||
|
||||
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.7", "", { "os": "linux", "cpu": "ia32" }, "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg=="],
|
||||
|
||||
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q=="],
|
||||
|
||||
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw=="],
|
||||
|
||||
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.7", "", { "os": "linux", "cpu": "ppc64" }, "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ=="],
|
||||
|
||||
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.7", "", { "os": "linux", "cpu": "none" }, "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ=="],
|
||||
|
||||
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.7", "", { "os": "linux", "cpu": "s390x" }, "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw=="],
|
||||
|
||||
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.7", "", { "os": "linux", "cpu": "x64" }, "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA=="],
|
||||
|
||||
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w=="],
|
||||
|
||||
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.7", "", { "os": "none", "cpu": "x64" }, "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw=="],
|
||||
|
||||
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.7", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A=="],
|
||||
|
||||
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.7", "", { "os": "openbsd", "cpu": "x64" }, "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg=="],
|
||||
|
||||
"@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.7", "", { "os": "none", "cpu": "arm64" }, "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw=="],
|
||||
|
||||
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.7", "", { "os": "sunos", "cpu": "x64" }, "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA=="],
|
||||
|
||||
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA=="],
|
||||
|
||||
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.7", "", { "os": "win32", "cpu": "ia32" }, "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw=="],
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.7", "", { "os": "win32", "cpu": "x64" }, "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg=="],
|
||||
|
||||
"@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
|
||||
|
||||
"@playwright/test": ["@playwright/test@1.59.1", "", { "dependencies": { "playwright": "1.59.1" }, "bin": { "playwright": "cli.js" } }, "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg=="],
|
||||
|
||||
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.60.1", "", { "os": "android", "cpu": "arm" }, "sha512-d6FinEBLdIiK+1uACUttJKfgZREXrF0Qc2SmLII7W2AD8FfiZ9Wjd+rD/iRuf5s5dWrr1GgwXCvPqOuDquOowA=="],
|
||||
|
||||
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.60.1", "", { "os": "android", "cpu": "arm64" }, "sha512-YjG/EwIDvvYI1YvYbHvDz/BYHtkY4ygUIXHnTdLhG+hKIQFBiosfWiACWortsKPKU/+dUwQQCKQM3qrDe8c9BA=="],
|
||||
|
||||
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.60.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-mjCpF7GmkRtSJwon+Rq1N8+pI+8l7w5g9Z3vWj4T7abguC4Czwi3Yu/pFaLvA3TTeMVjnu3ctigusqWUfjZzvw=="],
|
||||
|
||||
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.60.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-haZ7hJ1JT4e9hqkoT9R/19XW2QKqjfJVv+i5AGg57S+nLk9lQnJ1F/eZloRO3o9Scy9CM3wQ9l+dkXtcBgN5Ew=="],
|
||||
|
||||
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.60.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-czw90wpQq3ZsAVBlinZjAYTKduOjTywlG7fEeWKUA7oCmpA8xdTkxZZlwNJKWqILlq0wehoZcJYfBvOyhPTQ6w=="],
|
||||
|
||||
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.60.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-KVB2rqsxTHuBtfOeySEyzEOB7ltlB/ux38iu2rBQzkjbwRVlkhAGIEDiiYnO2kFOkJp+Z7pUXKyrRRFuFUKt+g=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.60.1", "", { "os": "linux", "cpu": "arm" }, "sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.60.1", "", { "os": "linux", "cpu": "arm" }, "sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.60.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.60.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA=="],
|
||||
|
||||
"@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ=="],
|
||||
|
||||
"@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw=="],
|
||||
|
||||
"@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.60.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw=="],
|
||||
|
||||
"@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.60.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.60.1", "", { "os": "linux", "cpu": "none" }, "sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg=="],
|
||||
|
||||
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.60.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.60.1", "", { "os": "linux", "cpu": "x64" }, "sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.60.1", "", { "os": "linux", "cpu": "x64" }, "sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w=="],
|
||||
|
||||
"@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.60.1", "", { "os": "openbsd", "cpu": "x64" }, "sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw=="],
|
||||
|
||||
"@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.60.1", "", { "os": "none", "cpu": "arm64" }, "sha512-4Cv23ZrONRbNtbZa37mLSueXUCtN7MXccChtKpUnQNgF010rjrjfHx3QxkS2PI7LqGT5xXyYs1a7LbzAwT0iCA=="],
|
||||
|
||||
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.60.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-i1okWYkA4FJICtr7KpYzFpRTHgy5jdDbZiWfvny21iIKky5YExiDXP+zbXzm3dUcFpkEeYNHgQ5fuG236JPq0g=="],
|
||||
|
||||
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.60.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-u09m3CuwLzShA0EYKMNiFgcjjzwqtUMLmuCJLeZWjjOYA3IT2Di09KaxGBTP9xVztWyIWjVdsB2E9goMjZvTQg=="],
|
||||
|
||||
"@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.60.1", "", { "os": "win32", "cpu": "x64" }, "sha512-k+600V9Zl1CM7eZxJgMyTUzmrmhB/0XZnF4pRypKAlAgxmedUA+1v9R+XOFv56W4SlHEzfeMtzujLJD22Uz5zg=="],
|
||||
|
||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.60.1", "", { "os": "win32", "cpu": "x64" }, "sha512-lWMnixq/QzxyhTV6NjQJ4SFo1J6PvOX8vUx5Wb4bBPsEb+8xZ89Bz6kOXpfXj9ak9AHTQVQzlgzBEc1SyM27xQ=="],
|
||||
|
||||
"@sinclair/typebox": ["@sinclair/typebox@0.27.10", "", {}, "sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA=="],
|
||||
|
||||
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
|
||||
|
||||
"@types/node": ["@types/node@20.19.39", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw=="],
|
||||
|
||||
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
|
||||
"@vitest/expect": ["@vitest/expect@1.6.1", "", { "dependencies": { "@vitest/spy": "1.6.1", "@vitest/utils": "1.6.1", "chai": "^4.3.10" } }, "sha512-jXL+9+ZNIJKruofqXuuTClf44eSpcHlgj3CiuNihUF3Ioujtmc0zIa3UJOW5RjDK1YLBJZnWBlPuqhYycLioog=="],
|
||||
|
||||
"@vitest/runner": ["@vitest/runner@1.6.1", "", { "dependencies": { "@vitest/utils": "1.6.1", "p-limit": "^5.0.0", "pathe": "^1.1.1" } }, "sha512-3nSnYXkVkf3mXFfE7vVyPmi3Sazhb/2cfZGGs0JRzFsPFvAMBEcrweV1V1GsrstdXeKCTXlJbvnQwGWgEIHmOA=="],
|
||||
|
||||
"@vitest/snapshot": ["@vitest/snapshot@1.6.1", "", { "dependencies": { "magic-string": "^0.30.5", "pathe": "^1.1.1", "pretty-format": "^29.7.0" } }, "sha512-WvidQuWAzU2p95u8GAKlRMqMyN1yOJkGHnx3M1PL9Raf7AQ1kwLKg04ADlCa3+OXUZE7BceOhVZiuWAbzCKcUQ=="],
|
||||
|
||||
"@vitest/spy": ["@vitest/spy@1.6.1", "", { "dependencies": { "tinyspy": "^2.2.0" } }, "sha512-MGcMmpGkZebsMZhbQKkAf9CX5zGvjkBTqf8Zx3ApYWXr3wG+QvEu2eXWfnIIWYSJExIp4V9FCKDEeygzkYrXMw=="],
|
||||
|
||||
"@vitest/utils": ["@vitest/utils@1.6.1", "", { "dependencies": { "diff-sequences": "^29.6.3", "estree-walker": "^3.0.3", "loupe": "^2.3.7", "pretty-format": "^29.7.0" } }, "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g=="],
|
||||
|
||||
"acorn": ["acorn@8.16.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw=="],
|
||||
|
||||
"acorn-walk": ["acorn-walk@8.3.5", "", { "dependencies": { "acorn": "^8.11.0" } }, "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw=="],
|
||||
|
||||
"ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="],
|
||||
|
||||
"assertion-error": ["assertion-error@1.1.0", "", {}, "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw=="],
|
||||
|
||||
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
|
||||
|
||||
"chai": ["chai@4.5.0", "", { "dependencies": { "assertion-error": "^1.1.0", "check-error": "^1.0.3", "deep-eql": "^4.1.3", "get-func-name": "^2.0.2", "loupe": "^2.3.6", "pathval": "^1.1.1", "type-detect": "^4.1.0" } }, "sha512-RITGBfijLkBddZvnn8jdqoTypxvqbOLYQkGGxXzeFjVHvudaPw0HNFD9x928/eUwYWd2dPCugVqspGALTZZQKw=="],
|
||||
|
||||
"check-error": ["check-error@1.0.3", "", { "dependencies": { "get-func-name": "^2.0.2" } }, "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg=="],
|
||||
|
||||
"confbox": ["confbox@0.1.8", "", {}, "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
"deep-eql": ["deep-eql@4.1.4", "", { "dependencies": { "type-detect": "^4.0.0" } }, "sha512-SUwdGfqdKOwxCPeVYjwSyRpJ7Z+fhpwIAtmCUdZIWZ/YP5R9WAsyuSgpLVDi9bjWoN2LXHNss/dk3urXtdQxGg=="],
|
||||
|
||||
"diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="],
|
||||
|
||||
"esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="],
|
||||
|
||||
"estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],
|
||||
|
||||
"execa": ["execa@8.0.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^8.0.1", "human-signals": "^5.0.0", "is-stream": "^3.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^5.1.0", "onetime": "^6.0.0", "signal-exit": "^4.1.0", "strip-final-newline": "^3.0.0" } }, "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="],
|
||||
|
||||
"get-stream": ["get-stream@8.0.1", "", {}, "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA=="],
|
||||
|
||||
"get-tsconfig": ["get-tsconfig@4.13.7", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q=="],
|
||||
|
||||
"human-signals": ["human-signals@5.0.0", "", {}, "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ=="],
|
||||
|
||||
"is-stream": ["is-stream@3.0.0", "", {}, "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA=="],
|
||||
|
||||
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"js-tokens": ["js-tokens@9.0.1", "", {}, "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ=="],
|
||||
|
||||
"local-pkg": ["local-pkg@0.5.1", "", { "dependencies": { "mlly": "^1.7.3", "pkg-types": "^1.2.1" } }, "sha512-9rrA30MRRP3gBD3HTGnC6cDFpaE1kVDWxWgqWJUN0RvDNAo+Nz/9GxB+nHOH0ifbVFy0hSA1V6vFDvnx54lTEQ=="],
|
||||
|
||||
"loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
|
||||
|
||||
"merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
|
||||
|
||||
"mimic-fn": ["mimic-fn@4.0.0", "", {}, "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw=="],
|
||||
|
||||
"mlly": ["mlly@1.8.2", "", { "dependencies": { "acorn": "^8.16.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.3" } }, "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"npm-run-path": ["npm-run-path@5.3.0", "", { "dependencies": { "path-key": "^4.0.0" } }, "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ=="],
|
||||
|
||||
"onetime": ["onetime@6.0.0", "", { "dependencies": { "mimic-fn": "^4.0.0" } }, "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ=="],
|
||||
|
||||
"p-limit": ["p-limit@5.0.0", "", { "dependencies": { "yocto-queue": "^1.0.0" } }, "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ=="],
|
||||
|
||||
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="],
|
||||
|
||||
"pathval": ["pathval@1.1.1", "", {}, "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"pkg-types": ["pkg-types@1.3.1", "", { "dependencies": { "confbox": "^0.1.8", "mlly": "^1.7.4", "pathe": "^2.0.1" } }, "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ=="],
|
||||
|
||||
"playwright": ["playwright@1.59.1", "", { "dependencies": { "playwright-core": "1.59.1" }, "optionalDependencies": { "fsevents": "2.3.2" }, "bin": { "playwright": "cli.js" } }, "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw=="],
|
||||
|
||||
"playwright-core": ["playwright-core@1.59.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg=="],
|
||||
|
||||
"postcss": ["postcss@8.5.9", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw=="],
|
||||
|
||||
"pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="],
|
||||
|
||||
"react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="],
|
||||
|
||||
"resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
|
||||
|
||||
"rollup": ["rollup@4.60.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.1", "@rollup/rollup-android-arm64": "4.60.1", "@rollup/rollup-darwin-arm64": "4.60.1", "@rollup/rollup-darwin-x64": "4.60.1", "@rollup/rollup-freebsd-arm64": "4.60.1", "@rollup/rollup-freebsd-x64": "4.60.1", "@rollup/rollup-linux-arm-gnueabihf": "4.60.1", "@rollup/rollup-linux-arm-musleabihf": "4.60.1", "@rollup/rollup-linux-arm64-gnu": "4.60.1", "@rollup/rollup-linux-arm64-musl": "4.60.1", "@rollup/rollup-linux-loong64-gnu": "4.60.1", "@rollup/rollup-linux-loong64-musl": "4.60.1", "@rollup/rollup-linux-ppc64-gnu": "4.60.1", "@rollup/rollup-linux-ppc64-musl": "4.60.1", "@rollup/rollup-linux-riscv64-gnu": "4.60.1", "@rollup/rollup-linux-riscv64-musl": "4.60.1", "@rollup/rollup-linux-s390x-gnu": "4.60.1", "@rollup/rollup-linux-x64-gnu": "4.60.1", "@rollup/rollup-linux-x64-musl": "4.60.1", "@rollup/rollup-openbsd-x64": "4.60.1", "@rollup/rollup-openharmony-arm64": "4.60.1", "@rollup/rollup-win32-arm64-msvc": "4.60.1", "@rollup/rollup-win32-ia32-msvc": "4.60.1", "@rollup/rollup-win32-x64-gnu": "4.60.1", "@rollup/rollup-win32-x64-msvc": "4.60.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-VmtB2rFU/GroZ4oL8+ZqXgSA38O6GR8KSIvWmEFv63pQ0G6KaBH9s07PO8XTXP4vI+3UJUEypOfjkGfmSBBR0w=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],
|
||||
|
||||
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],
|
||||
|
||||
"std-env": ["std-env@3.10.0", "", {}, "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg=="],
|
||||
|
||||
"strip-final-newline": ["strip-final-newline@3.0.0", "", {}, "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw=="],
|
||||
|
||||
"strip-literal": ["strip-literal@2.1.1", "", { "dependencies": { "js-tokens": "^9.0.1" } }, "sha512-631UJ6O00eNGfMiWG78ck80dfBab8X6IVFB51jZK5Icd7XAs60Z5y7QdSd/wGIklnWvRbUNloVzhOKKmutxQ6Q=="],
|
||||
|
||||
"tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],
|
||||
|
||||
"tinypool": ["tinypool@0.8.4", "", {}, "sha512-i11VH5gS6IFeLY3gMBQ00/MmLncVP7JLXOw1vlgkytLmJK7QnEr7NXf0LBdxfmNPAeyetukOk0bOYrJrFGjYJQ=="],
|
||||
|
||||
"tinyspy": ["tinyspy@2.2.1", "", {}, "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A=="],
|
||||
|
||||
"tsx": ["tsx@4.21.0", "", { "dependencies": { "esbuild": "~0.27.0", "get-tsconfig": "^4.7.5" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw=="],
|
||||
|
||||
"type-detect": ["type-detect@4.1.0", "", {}, "sha512-Acylog8/luQ8L7il+geoSxhEkazvkslg7PSNKOX59mbB9cOveP5aq9h74Y7YU8yDpJwetzQQrfIwtf4Wp4LKcw=="],
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"ufo": ["ufo@1.6.3", "", {}, "sha512-yDJTmhydvl5lJzBmy/hyOAA0d+aqCBuwl818haVdYCRrWV84o7YyeVm4QlVHStqNrrJSTb6jKuFAVqAFsr+K3Q=="],
|
||||
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"vite": ["vite@5.4.21", "", { "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", "rollup": "^4.20.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || >=20.0.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.4.0" }, "optionalPeers": ["@types/node", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser"], "bin": { "vite": "bin/vite.js" } }, "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw=="],
|
||||
|
||||
"vite-node": ["vite-node@1.6.1", "", { "dependencies": { "cac": "^6.7.14", "debug": "^4.3.4", "pathe": "^1.1.1", "picocolors": "^1.0.0", "vite": "^5.0.0" }, "bin": { "vite-node": "vite-node.mjs" } }, "sha512-YAXkfvGtuTzwWbDSACdJSg4A4DZiAqckWe90Zapc/sEX3XvHcw1NdurM/6od8J207tSDqNbSsgdCacBgvJKFuA=="],
|
||||
|
||||
"vitest": ["vitest@1.6.1", "", { "dependencies": { "@vitest/expect": "1.6.1", "@vitest/runner": "1.6.1", "@vitest/snapshot": "1.6.1", "@vitest/spy": "1.6.1", "@vitest/utils": "1.6.1", "acorn-walk": "^8.3.2", "chai": "^4.3.10", "debug": "^4.3.4", "execa": "^8.0.1", "local-pkg": "^0.5.0", "magic-string": "^0.30.5", "pathe": "^1.1.1", "picocolors": "^1.0.0", "std-env": "^3.5.0", "strip-literal": "^2.0.0", "tinybench": "^2.5.1", "tinypool": "^0.8.3", "vite": "^5.0.0", "vite-node": "1.6.1", "why-is-node-running": "^2.2.2" }, "peerDependencies": { "@edge-runtime/vm": "*", "@types/node": "^18.0.0 || >=20.0.0", "@vitest/browser": "1.6.1", "@vitest/ui": "1.6.1", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@types/node", "@vitest/browser", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "vitest.mjs" } }, "sha512-Ljb1cnSJSivGN0LqXd/zmDbWEM0RNNg2t1QW/XUhYl/qPqyu7CsqeWtqQXHVaJsecLPuDoak2oJcZN2QoRIOag=="],
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
|
||||
|
||||
"ws": ["ws@8.20.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA=="],
|
||||
|
||||
"yocto-queue": ["yocto-queue@1.2.2", "", {}, "sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ=="],
|
||||
|
||||
"mlly/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
|
||||
|
||||
"npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="],
|
||||
|
||||
"pkg-types/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
|
||||
|
||||
"playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
|
||||
"vite/esbuild": ["esbuild@0.21.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.21.5", "@esbuild/android-arm": "0.21.5", "@esbuild/android-arm64": "0.21.5", "@esbuild/android-x64": "0.21.5", "@esbuild/darwin-arm64": "0.21.5", "@esbuild/darwin-x64": "0.21.5", "@esbuild/freebsd-arm64": "0.21.5", "@esbuild/freebsd-x64": "0.21.5", "@esbuild/linux-arm": "0.21.5", "@esbuild/linux-arm64": "0.21.5", "@esbuild/linux-ia32": "0.21.5", "@esbuild/linux-loong64": "0.21.5", "@esbuild/linux-mips64el": "0.21.5", "@esbuild/linux-ppc64": "0.21.5", "@esbuild/linux-riscv64": "0.21.5", "@esbuild/linux-s390x": "0.21.5", "@esbuild/linux-x64": "0.21.5", "@esbuild/netbsd-x64": "0.21.5", "@esbuild/openbsd-x64": "0.21.5", "@esbuild/sunos-x64": "0.21.5", "@esbuild/win32-arm64": "0.21.5", "@esbuild/win32-ia32": "0.21.5", "@esbuild/win32-x64": "0.21.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw=="],
|
||||
|
||||
"vite/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.21.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ=="],
|
||||
|
||||
"vite/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.21.5", "", { "os": "android", "cpu": "arm" }, "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.21.5", "", { "os": "android", "cpu": "arm64" }, "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A=="],
|
||||
|
||||
"vite/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.21.5", "", { "os": "android", "cpu": "x64" }, "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA=="],
|
||||
|
||||
"vite/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.21.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ=="],
|
||||
|
||||
"vite/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.21.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw=="],
|
||||
|
||||
"vite/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.21.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g=="],
|
||||
|
||||
"vite/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.21.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.21.5", "", { "os": "linux", "cpu": "arm" }, "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.21.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.21.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.21.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.21.5", "", { "os": "linux", "cpu": "none" }, "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.21.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A=="],
|
||||
|
||||
"vite/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.21.5", "", { "os": "linux", "cpu": "x64" }, "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ=="],
|
||||
|
||||
"vite/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.21.5", "", { "os": "none", "cpu": "x64" }, "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.21.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow=="],
|
||||
|
||||
"vite/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.21.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg=="],
|
||||
|
||||
"vite/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.21.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A=="],
|
||||
|
||||
"vite/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.21.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA=="],
|
||||
|
||||
"vite/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.21.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw=="],
|
||||
}
|
||||
}
|
||||
125
tests/soak/config.ts
Normal file
125
tests/soak/config.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* CLI flag parsing and config precedence for the soak runner.
|
||||
*
|
||||
* Precedence (later wins):
|
||||
* runner defaults → scenario.defaultConfig → env vars → CLI flags
|
||||
*/
|
||||
|
||||
export type WatchMode = 'none' | 'dashboard' | 'tiled';
|
||||
|
||||
export interface CliArgs {
|
||||
scenario?: string;
|
||||
accounts?: number;
|
||||
rooms?: number;
|
||||
cpusPerRoom?: number;
|
||||
gamesPerRoom?: number;
|
||||
holes?: number;
|
||||
watch?: WatchMode;
|
||||
dashboardPort?: number;
|
||||
target?: string;
|
||||
runId?: string;
|
||||
dryRun?: boolean;
|
||||
listOnly?: boolean;
|
||||
}
|
||||
|
||||
const VALID_WATCH: WatchMode[] = ['none', 'dashboard', 'tiled'];
|
||||
|
||||
function parseInt10(s: string, name: string): number {
|
||||
const n = parseInt(s, 10);
|
||||
if (Number.isNaN(n)) throw new Error(`Invalid integer for ${name}: ${s}`);
|
||||
return n;
|
||||
}
|
||||
|
||||
export function parseArgs(argv: string[]): CliArgs {
|
||||
const out: CliArgs = {};
|
||||
for (const arg of argv) {
|
||||
if (arg === '--list') {
|
||||
out.listOnly = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--dry-run') {
|
||||
out.dryRun = true;
|
||||
continue;
|
||||
}
|
||||
const m = arg.match(/^--([a-z][a-z0-9-]*)=(.*)$/);
|
||||
if (!m) continue;
|
||||
const [, key, value] = m;
|
||||
switch (key) {
|
||||
case 'scenario':
|
||||
out.scenario = value;
|
||||
break;
|
||||
case 'accounts':
|
||||
out.accounts = parseInt10(value, '--accounts');
|
||||
break;
|
||||
case 'rooms':
|
||||
out.rooms = parseInt10(value, '--rooms');
|
||||
break;
|
||||
case 'cpus-per-room':
|
||||
out.cpusPerRoom = parseInt10(value, '--cpus-per-room');
|
||||
break;
|
||||
case 'games-per-room':
|
||||
out.gamesPerRoom = parseInt10(value, '--games-per-room');
|
||||
break;
|
||||
case 'holes':
|
||||
out.holes = parseInt10(value, '--holes');
|
||||
break;
|
||||
case 'watch':
|
||||
if (!VALID_WATCH.includes(value as WatchMode)) {
|
||||
throw new Error(
|
||||
`Invalid --watch value: ${value} (expected ${VALID_WATCH.join('|')})`,
|
||||
);
|
||||
}
|
||||
out.watch = value as WatchMode;
|
||||
break;
|
||||
case 'dashboard-port':
|
||||
out.dashboardPort = parseInt10(value, '--dashboard-port');
|
||||
break;
|
||||
case 'target':
|
||||
out.target = value;
|
||||
break;
|
||||
case 'run-id':
|
||||
out.runId = value;
|
||||
break;
|
||||
default:
|
||||
// Unknown flag — ignore so scenario-specific flags can slot in later
|
||||
break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge layers in precedence order: defaults → env → cli (later wins).
|
||||
*/
|
||||
export function mergeConfig(
|
||||
cli: Record<string, unknown>,
|
||||
env: Record<string, string | undefined>,
|
||||
defaults: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const merged: Record<string, unknown> = { ...defaults };
|
||||
|
||||
// Env overlay — SOAK_UPPER_SNAKE → lowerCamel in cli space.
|
||||
const envMap: Record<string, string> = {
|
||||
SOAK_HOLES: 'holes',
|
||||
SOAK_ROOMS: 'rooms',
|
||||
SOAK_ACCOUNTS: 'accounts',
|
||||
SOAK_CPUS_PER_ROOM: 'cpusPerRoom',
|
||||
SOAK_GAMES_PER_ROOM: 'gamesPerRoom',
|
||||
SOAK_WATCH: 'watch',
|
||||
SOAK_DASHBOARD_PORT: 'dashboardPort',
|
||||
};
|
||||
const numericKeys = /^(holes|rooms|accounts|cpusPerRoom|gamesPerRoom|dashboardPort)$/;
|
||||
for (const [envKey, cfgKey] of Object.entries(envMap)) {
|
||||
const v = env[envKey];
|
||||
if (v !== undefined) {
|
||||
merged[cfgKey] = numericKeys.test(cfgKey) ? parseInt(v, 10) : v;
|
||||
}
|
||||
}
|
||||
|
||||
// CLI overlay — wins over env and defaults.
|
||||
for (const [k, v] of Object.entries(cli)) {
|
||||
if (v !== undefined) merged[k] = v;
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
121
tests/soak/core/artifacts.ts
Normal file
121
tests/soak/core/artifacts.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* Artifacts — capture session debugging info on scenario failure.
|
||||
*
|
||||
* When runner.ts hits an unrecoverable error during a scenario, it
|
||||
* calls `artifacts.captureAll(liveSessions)` which dumps one
|
||||
* screenshot + HTML snapshot + game state JSON + console tail per
|
||||
* session into `tests/soak/artifacts/<run-id>/`.
|
||||
*
|
||||
* Successful runs get a lightweight `summary.json` written at the
|
||||
* same path so post-run inspection has something to grep.
|
||||
*
|
||||
* `pruneOldRuns` sweeps run dirs older than maxAgeMs on startup so
|
||||
* the artifacts directory doesn't grow unbounded.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import type { Session, Logger } from './types';
|
||||
|
||||
export interface ArtifactsOptions {
|
||||
runId: string;
|
||||
/** Absolute path to the artifacts root, e.g. /path/to/tests/soak/artifacts */
|
||||
rootDir: string;
|
||||
logger: Logger;
|
||||
}
|
||||
|
||||
export class Artifacts {
|
||||
readonly runDir: string;
|
||||
|
||||
constructor(private opts: ArtifactsOptions) {
|
||||
this.runDir = path.join(opts.rootDir, opts.runId);
|
||||
fs.mkdirSync(this.runDir, { recursive: true });
|
||||
}
|
||||
|
||||
/** Capture screenshot + HTML + state + console tail for one session. */
|
||||
async captureSession(session: Session, roomId: string): Promise<void> {
|
||||
const dir = path.join(this.runDir, roomId);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const prefix = session.key;
|
||||
|
||||
try {
|
||||
const png = await session.page.screenshot({ fullPage: true });
|
||||
fs.writeFileSync(path.join(dir, `${prefix}.png`), png);
|
||||
} catch (err) {
|
||||
this.opts.logger.warn('artifact_screenshot_failed', {
|
||||
session: session.key,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const html = await session.page.content();
|
||||
fs.writeFileSync(path.join(dir, `${prefix}.html`), html);
|
||||
} catch (err) {
|
||||
this.opts.logger.warn('artifact_html_failed', {
|
||||
session: session.key,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const state = await session.bot.getGameState();
|
||||
fs.writeFileSync(
|
||||
path.join(dir, `${prefix}.state.json`),
|
||||
JSON.stringify(state, null, 2),
|
||||
);
|
||||
} catch (err) {
|
||||
this.opts.logger.warn('artifact_state_failed', {
|
||||
session: session.key,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const errors = session.bot.getConsoleErrors?.() ?? [];
|
||||
fs.writeFileSync(path.join(dir, `${prefix}.console.txt`), errors.join('\n'));
|
||||
} catch {
|
||||
// ignore — not all bot flavors expose console errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort capture for every live session. We don't know which
|
||||
* room each session belongs to at this level, so everything lands
|
||||
* under `room-unknown/` unless callers partition sessions first.
|
||||
*/
|
||||
async captureAll(sessions: Session[]): Promise<void> {
|
||||
await Promise.all(
|
||||
sessions.map((s) => this.captureSession(s, 'room-unknown')),
|
||||
);
|
||||
}
|
||||
|
||||
writeSummary(summary: object): void {
|
||||
fs.writeFileSync(
|
||||
path.join(this.runDir, 'summary.json'),
|
||||
JSON.stringify(summary, null, 2),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Prune run directories older than `maxAgeMs`. Called on runner startup. */
|
||||
export function pruneOldRuns(
|
||||
rootDir: string,
|
||||
maxAgeMs: number,
|
||||
logger: Logger,
|
||||
): void {
|
||||
if (!fs.existsSync(rootDir)) return;
|
||||
const now = Date.now();
|
||||
for (const entry of fs.readdirSync(rootDir)) {
|
||||
const full = path.join(rootDir, entry);
|
||||
try {
|
||||
const stat = fs.statSync(full);
|
||||
if (stat.isDirectory() && now - stat.mtimeMs > maxAgeMs) {
|
||||
fs.rmSync(full, { recursive: true, force: true });
|
||||
logger.info('artifact_pruned', { runId: entry });
|
||||
}
|
||||
} catch {
|
||||
// ignore — best effort
|
||||
}
|
||||
}
|
||||
}
|
||||
20
tests/soak/core/deferred.ts
Normal file
20
tests/soak/core/deferred.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Promise deferred primitive — lets external code resolve or reject
|
||||
* a promise. Used by RoomCoordinator for host→joiners handoff.
|
||||
*/
|
||||
|
||||
export interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
reject(error: unknown): void;
|
||||
}
|
||||
|
||||
export function deferred<T>(): Deferred<T> {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
59
tests/soak/core/logger.ts
Normal file
59
tests/soak/core/logger.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Structured JSONL logger for the soak harness.
|
||||
*
|
||||
* One JSON line per call, written to stdout by default. Child loggers
|
||||
* inherit parent meta so scenarios can bind room/game context once and
|
||||
* every subsequent call carries it automatically.
|
||||
*/
|
||||
|
||||
import type { Logger, LogLevel } from './types';
|
||||
|
||||
const LEVEL_ORDER: Record<LogLevel, number> = {
|
||||
debug: 0,
|
||||
info: 1,
|
||||
warn: 2,
|
||||
error: 3,
|
||||
};
|
||||
|
||||
export interface LoggerOptions {
|
||||
runId: string;
|
||||
minLevel?: LogLevel;
|
||||
/** Defaults to process.stdout.write bound to stdout. Override for tests. */
|
||||
write?: (line: string) => boolean;
|
||||
baseMeta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function createLogger(opts: LoggerOptions): Logger {
|
||||
const minLevel = opts.minLevel ?? 'info';
|
||||
const write = opts.write ?? ((s: string) => process.stdout.write(s));
|
||||
const baseMeta = opts.baseMeta ?? {};
|
||||
|
||||
function emit(level: LogLevel, msg: string, meta?: object): void {
|
||||
if (LEVEL_ORDER[level] < LEVEL_ORDER[minLevel]) return;
|
||||
const line = JSON.stringify({
|
||||
timestamp: new Date().toISOString(),
|
||||
level,
|
||||
msg,
|
||||
runId: opts.runId,
|
||||
...baseMeta,
|
||||
...(meta ?? {}),
|
||||
}) + '\n';
|
||||
write(line);
|
||||
}
|
||||
|
||||
const logger: Logger = {
|
||||
debug: (msg, meta) => emit('debug', msg, meta),
|
||||
info: (msg, meta) => emit('info', msg, meta),
|
||||
warn: (msg, meta) => emit('warn', msg, meta),
|
||||
error: (msg, meta) => emit('error', msg, meta),
|
||||
child: (meta) =>
|
||||
createLogger({
|
||||
runId: opts.runId,
|
||||
minLevel,
|
||||
write,
|
||||
baseMeta: { ...baseMeta, ...meta },
|
||||
}),
|
||||
};
|
||||
|
||||
return logger;
|
||||
}
|
||||
42
tests/soak/core/room-coordinator.ts
Normal file
42
tests/soak/core/room-coordinator.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* RoomCoordinator — tiny host→joiners handoff primitive.
|
||||
*
|
||||
* Lazy Deferred per roomId. `announce` resolves the promise; `await`
|
||||
* blocks until the promise resolves or a per-call timeout fires.
|
||||
* Rooms are keyed by string; each key has at most one Deferred.
|
||||
*/
|
||||
|
||||
import { deferred, Deferred } from './deferred';
|
||||
import type { RoomCoordinatorApi } from './types';
|
||||
|
||||
export class RoomCoordinator implements RoomCoordinatorApi {
|
||||
private rooms = new Map<string, Deferred<string>>();
|
||||
|
||||
announce(roomId: string, code: string): void {
|
||||
this.getOrCreate(roomId).resolve(code);
|
||||
}
|
||||
|
||||
async await(roomId: string, timeoutMs: number = 30_000): Promise<string> {
|
||||
const d = this.getOrCreate(roomId);
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(new Error(`RoomCoordinator: room "${roomId}" timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
});
|
||||
try {
|
||||
return await Promise.race([d.promise, timeout]);
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
private getOrCreate(roomId: string): Deferred<string> {
|
||||
let d = this.rooms.get(roomId);
|
||||
if (!d) {
|
||||
d = deferred<string>();
|
||||
this.rooms.set(roomId, d);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
}
|
||||
89
tests/soak/core/screencaster.ts
Normal file
89
tests/soak/core/screencaster.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Screencaster — CDP Page.startScreencast wrapper for live video.
|
||||
*
|
||||
* Attach a CDP session to a Playwright Page, start emitting JPEG
|
||||
* frames at the configured frame rate, forward each frame to a
|
||||
* callback, detach on stop. Used by the dashboard's click-to-watch
|
||||
* feature: when a user clicks a player tile, the runner calls
|
||||
* `start(key, page, frame => ws.send(...))`; when they close the
|
||||
* modal it calls `stop(key)`.
|
||||
*/
|
||||
|
||||
import type { Page, CDPSession } from 'playwright-core';
|
||||
import type { Logger } from './types';
|
||||
|
||||
export interface ScreencastOptions {
|
||||
format?: 'jpeg' | 'png';
|
||||
quality?: number;
|
||||
maxWidth?: number;
|
||||
maxHeight?: number;
|
||||
everyNthFrame?: number;
|
||||
}
|
||||
|
||||
export type FrameCallback = (jpegBase64: string) => void;
|
||||
|
||||
export class Screencaster {
|
||||
private sessions = new Map<string, CDPSession>();
|
||||
|
||||
constructor(private logger: Logger) {}
|
||||
|
||||
/**
|
||||
* Attach a CDP session to the given page and start forwarding frames.
|
||||
* If a screencast is already running for this sessionKey, no-op.
|
||||
*/
|
||||
async start(
|
||||
sessionKey: string,
|
||||
page: Page,
|
||||
onFrame: FrameCallback,
|
||||
opts: ScreencastOptions = {},
|
||||
): Promise<void> {
|
||||
if (this.sessions.has(sessionKey)) {
|
||||
this.logger.warn('screencast_already_running', { sessionKey });
|
||||
return;
|
||||
}
|
||||
const client = await page.context().newCDPSession(page);
|
||||
this.sessions.set(sessionKey, client);
|
||||
|
||||
client.on('Page.screencastFrame', async (evt: { data: string; sessionId: number }) => {
|
||||
try {
|
||||
onFrame(evt.data);
|
||||
await client.send('Page.screencastFrameAck', { sessionId: evt.sessionId });
|
||||
} catch (err) {
|
||||
this.logger.warn('screencast_frame_error', {
|
||||
sessionKey,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await client.send('Page.startScreencast', {
|
||||
format: opts.format ?? 'jpeg',
|
||||
quality: opts.quality ?? 60,
|
||||
maxWidth: opts.maxWidth ?? 640,
|
||||
maxHeight: opts.maxHeight ?? 360,
|
||||
everyNthFrame: opts.everyNthFrame ?? 2,
|
||||
});
|
||||
this.logger.info('screencast_started', { sessionKey });
|
||||
}
|
||||
|
||||
async stop(sessionKey: string): Promise<void> {
|
||||
const client = this.sessions.get(sessionKey);
|
||||
if (!client) return;
|
||||
try {
|
||||
await client.send('Page.stopScreencast');
|
||||
await client.detach();
|
||||
} catch (err) {
|
||||
this.logger.warn('screencast_stop_error', {
|
||||
sessionKey,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
this.sessions.delete(sessionKey);
|
||||
this.logger.info('screencast_stopped', { sessionKey });
|
||||
}
|
||||
|
||||
async stopAll(): Promise<void> {
|
||||
const keys = Array.from(this.sessions.keys());
|
||||
await Promise.all(keys.map((k) => this.stop(k)));
|
||||
}
|
||||
}
|
||||
369
tests/soak/core/session-pool.ts
Normal file
369
tests/soak/core/session-pool.ts
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* SessionPool — owns the 16 authenticated BrowserContexts.
|
||||
*
|
||||
* Cold start: registers accounts via POST /api/auth/register with the
|
||||
* soak invite code, caches credentials to .env.stresstest.
|
||||
* Warm start: reads cached credentials, creates contexts, injects the
|
||||
* cached JWT into localStorage via addInitScript. Falls back to
|
||||
* POST /api/auth/login if the token is rejected later.
|
||||
*
|
||||
* Testing: this module is integration-level; no Vitest. Verified
|
||||
* end-to-end in Task 14 (seed CLI) and Task 18 (first full runner run).
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import {
|
||||
Browser,
|
||||
BrowserContext,
|
||||
chromium,
|
||||
} from 'playwright-core';
|
||||
import { GolfBot } from '../../e2e/bot/golf-bot';
|
||||
import type { Account, Session, Logger } from './types';
|
||||
|
||||
function readCredFile(filePath: string): Account[] | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
const accounts: Account[] = [];
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
// SOAK_ACCOUNT_NN=username:password:token
|
||||
const eq = trimmed.indexOf('=');
|
||||
if (eq === -1) continue;
|
||||
const key = trimmed.slice(0, eq);
|
||||
const value = trimmed.slice(eq + 1);
|
||||
const m = key.match(/^SOAK_ACCOUNT_(\d+)$/);
|
||||
if (!m) continue;
|
||||
const [username, password, token] = value.split(':');
|
||||
if (!username || !password || !token) continue;
|
||||
const idx = parseInt(m[1], 10);
|
||||
accounts.push({
|
||||
key: `soak_${String(idx).padStart(2, '0')}`,
|
||||
username,
|
||||
password,
|
||||
token,
|
||||
});
|
||||
}
|
||||
return accounts.length > 0 ? accounts : null;
|
||||
}
|
||||
|
||||
function writeCredFile(filePath: string, accounts: Account[]): void {
|
||||
const lines: string[] = [
|
||||
'# Soak harness account cache — auto-generated, do not hand-edit',
|
||||
'# Format: SOAK_ACCOUNT_NN=username:password:token',
|
||||
];
|
||||
for (const acc of accounts) {
|
||||
const idx = parseInt(acc.key.replace('soak_', ''), 10);
|
||||
const key = `SOAK_ACCOUNT_${String(idx).padStart(2, '0')}`;
|
||||
lines.push(`${key}=${acc.username}:${acc.password}:${acc.token}`);
|
||||
}
|
||||
fs.writeFileSync(filePath, lines.join('\n') + '\n', { mode: 0o600 });
|
||||
}
|
||||
|
||||
interface RegisterResponse {
|
||||
user: { id: string; username: string };
|
||||
token: string;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
async function registerAccount(
|
||||
targetUrl: string,
|
||||
username: string,
|
||||
password: string,
|
||||
email: string,
|
||||
inviteCode: string,
|
||||
): Promise<string> {
|
||||
const res = await fetch(`${targetUrl}/api/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password, email, invite_code: inviteCode }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '<no body>');
|
||||
throw new Error(`register failed: ${res.status} ${body}`);
|
||||
}
|
||||
const data = (await res.json()) as RegisterResponse;
|
||||
if (!data.token) {
|
||||
throw new Error(`register returned no token: ${JSON.stringify(data)}`);
|
||||
}
|
||||
return data.token;
|
||||
}
|
||||
|
||||
async function loginAccount(
|
||||
targetUrl: string,
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<string> {
|
||||
const res = await fetch(`${targetUrl}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '<no body>');
|
||||
throw new Error(`login failed: ${res.status} ${body}`);
|
||||
}
|
||||
const data = (await res.json()) as RegisterResponse;
|
||||
return data.token;
|
||||
}
|
||||
|
||||
function randomSuffix(): string {
|
||||
return Math.random().toString(36).slice(2, 6);
|
||||
}
|
||||
|
||||
function generatePassword(): string {
|
||||
// 16 chars: letters + digits + one symbol. Meets 8-char minimum from auth_service.
|
||||
// Split halves so secret-scanners don't flag the string as base64.
|
||||
const lower = 'abcdefghijkm' + 'npqrstuvwxyz'; // pragma: allowlist secret
|
||||
const upper = 'ABCDEFGHJKLM' + 'NPQRSTUVWXYZ'; // pragma: allowlist secret
|
||||
const digits = '23456789';
|
||||
const chars = lower + upper + digits;
|
||||
let out = '';
|
||||
for (let i = 0; i < 15; i++) {
|
||||
out += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
return out + '!';
|
||||
}
|
||||
|
||||
export interface SeedOptions {
|
||||
/** Full base URL of the target server. */
|
||||
targetUrl: string;
|
||||
/** Invite code to pass to /api/auth/register. */
|
||||
inviteCode: string;
|
||||
/** Number of accounts to create. */
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface SessionPoolOptions {
|
||||
targetUrl: string;
|
||||
inviteCode: string;
|
||||
credFile: string;
|
||||
logger: Logger;
|
||||
/** Optional override — if absent, SessionPool launches its own. */
|
||||
browser?: Browser;
|
||||
contextOptions?: Parameters<Browser['newContext']>[0];
|
||||
/**
|
||||
* If > 0, the first `headedHostCount` sessions use a separate headed
|
||||
* Chromium browser with visible windows (positioned in a 2×2 grid
|
||||
* via window.moveTo). The remaining sessions stay headless. Used for
|
||||
* --watch=tiled mode.
|
||||
*/
|
||||
headedHostCount?: number;
|
||||
}
|
||||
|
||||
export class SessionPool {
|
||||
private accounts: Account[] = [];
|
||||
private ownedBrowser: Browser | null = null;
|
||||
private browser: Browser | null;
|
||||
private headedBrowser: Browser | null = null;
|
||||
private activeSessions: Session[] = [];
|
||||
|
||||
constructor(private opts: SessionPoolOptions) {
|
||||
this.browser = opts.browser ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed `count` accounts via the register endpoint and write them to credFile.
|
||||
* Safe to call multiple times — skips accounts already in the file.
|
||||
*/
|
||||
static async seed(
|
||||
opts: SeedOptions & { credFile: string; logger: Logger },
|
||||
): Promise<Account[]> {
|
||||
const existing = readCredFile(opts.credFile) ?? [];
|
||||
const existingKeys = new Set(existing.map((a) => a.key));
|
||||
const created: Account[] = [...existing];
|
||||
|
||||
for (let i = 0; i < opts.count; i++) {
|
||||
const key = `soak_${String(i).padStart(2, '0')}`;
|
||||
if (existingKeys.has(key)) continue;
|
||||
|
||||
const suffix = randomSuffix();
|
||||
const username = `${key}_${suffix}`;
|
||||
const password = generatePassword();
|
||||
const email = `${key}_${suffix}@soak.test`;
|
||||
|
||||
opts.logger.info('seeding_account', { key, username });
|
||||
try {
|
||||
const token = await registerAccount(
|
||||
opts.targetUrl,
|
||||
username,
|
||||
password,
|
||||
email,
|
||||
opts.inviteCode,
|
||||
);
|
||||
created.push({ key, username, password, token });
|
||||
writeCredFile(opts.credFile, created);
|
||||
} catch (err) {
|
||||
opts.logger.error('seed_failed', {
|
||||
key,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load accounts from credFile, auto-seeding if the file is missing.
|
||||
*/
|
||||
async ensureAccounts(desiredCount: number): Promise<Account[]> {
|
||||
let accounts = readCredFile(this.opts.credFile);
|
||||
if (!accounts || accounts.length < desiredCount) {
|
||||
this.opts.logger.warn('cred_file_missing_or_short', {
|
||||
found: accounts?.length ?? 0,
|
||||
desired: desiredCount,
|
||||
});
|
||||
accounts = await SessionPool.seed({
|
||||
targetUrl: this.opts.targetUrl,
|
||||
inviteCode: this.opts.inviteCode,
|
||||
count: desiredCount,
|
||||
credFile: this.opts.credFile,
|
||||
logger: this.opts.logger,
|
||||
});
|
||||
}
|
||||
this.accounts = accounts.slice(0, desiredCount);
|
||||
return this.accounts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch the browser if not provided, create N contexts, log each in via
|
||||
* localStorage injection, return the live sessions.
|
||||
*
|
||||
* If `headedHostCount > 0`, launches a second headed Chromium and
|
||||
* places the first `headedHostCount` sessions in it, positioning
|
||||
* their windows in a 2×2 grid. The rest stay headless.
|
||||
*/
|
||||
async acquire(count: number): Promise<Session[]> {
|
||||
await this.ensureAccounts(count);
|
||||
if (!this.browser) {
|
||||
this.ownedBrowser = await chromium.launch({ headless: true });
|
||||
this.browser = this.ownedBrowser;
|
||||
}
|
||||
|
||||
const headedCount = this.opts.headedHostCount ?? 0;
|
||||
if (headedCount > 0 && !this.headedBrowser) {
|
||||
this.headedBrowser = await chromium.launch({
|
||||
headless: false,
|
||||
slowMo: 50,
|
||||
});
|
||||
}
|
||||
|
||||
const sessions: Session[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const account = this.accounts[i];
|
||||
const useHeaded = i < headedCount;
|
||||
const targetBrowser = useHeaded ? this.headedBrowser! : this.browser!;
|
||||
// Headed host windows get a larger viewport — 960×900 fits the full
|
||||
// game table (deck + opponent row + own 2×3 grid + status area) on
|
||||
// a typical 1920×1080 display. Two windows side-by-side still fit
|
||||
// horizontally; if the user runs more than 2 rooms in tiled mode
|
||||
// the extra windows will overlap and need to be arranged manually.
|
||||
//
|
||||
// baseURL is set on every context so relative goto('/') calls
|
||||
// (used between games to bounce back to the lobby) resolve to
|
||||
// the target server instead of failing with "invalid URL".
|
||||
const context = await targetBrowser.newContext({
|
||||
...this.opts.contextOptions,
|
||||
baseURL: this.opts.targetUrl,
|
||||
...(useHeaded ? { viewport: { width: 960, height: 900 } } : {}),
|
||||
});
|
||||
await this.injectAuth(context, account);
|
||||
const page = await context.newPage();
|
||||
await page.goto(this.opts.targetUrl);
|
||||
|
||||
// Best-effort tile placement. window.moveTo is often a no-op on
|
||||
// modern Chromium (especially under Wayland), so we don't rely on
|
||||
// it — the viewport sized above is what the user actually sees.
|
||||
if (useHeaded) {
|
||||
const col = i % 2;
|
||||
const row = Math.floor(i / 2);
|
||||
const x = col * 960;
|
||||
const y = row * 920;
|
||||
await page
|
||||
.evaluate(
|
||||
([x, y]) => {
|
||||
window.moveTo(x, y);
|
||||
},
|
||||
[x, y] as [number, number],
|
||||
)
|
||||
.catch(() => {
|
||||
// ignore — window.moveTo may be blocked
|
||||
});
|
||||
}
|
||||
|
||||
const bot = new GolfBot(page);
|
||||
sessions.push({ account, context, page, bot, key: account.key });
|
||||
}
|
||||
this.activeSessions = sessions;
|
||||
return sessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject the cached JWT into localStorage via addInitScript so it is
|
||||
* present on the first navigation. If the token is rejected later,
|
||||
* acquire() falls back to /api/auth/login.
|
||||
*/
|
||||
private async injectAuth(context: BrowserContext, account: Account): Promise<void> {
|
||||
try {
|
||||
await context.addInitScript(
|
||||
({ token, username }) => {
|
||||
window.localStorage.setItem('authToken', token);
|
||||
window.localStorage.setItem(
|
||||
'authUser',
|
||||
JSON.stringify({ id: '', username, role: 'user', email_verified: true }),
|
||||
);
|
||||
},
|
||||
{ token: account.token, username: account.username },
|
||||
);
|
||||
} catch (err) {
|
||||
this.opts.logger.warn('inject_auth_failed', {
|
||||
account: account.key,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
// Fall back to fresh login
|
||||
const token = await loginAccount(this.opts.targetUrl, account.username, account.password);
|
||||
account.token = token;
|
||||
writeCredFile(this.opts.credFile, this.accounts);
|
||||
await context.addInitScript(
|
||||
({ token, username }) => {
|
||||
window.localStorage.setItem('authToken', token);
|
||||
window.localStorage.setItem(
|
||||
'authUser',
|
||||
JSON.stringify({ id: '', username, role: 'user', email_verified: true }),
|
||||
);
|
||||
},
|
||||
{ token, username: account.username },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Close all active contexts + browsers. Safe to call multiple times. */
|
||||
async release(): Promise<void> {
|
||||
for (const session of this.activeSessions) {
|
||||
try {
|
||||
await session.context.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.activeSessions = [];
|
||||
if (this.ownedBrowser) {
|
||||
try {
|
||||
await this.ownedBrowser.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.ownedBrowser = null;
|
||||
this.browser = null;
|
||||
}
|
||||
if (this.headedBrowser) {
|
||||
try {
|
||||
await this.headedBrowser.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.headedBrowser = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
133
tests/soak/core/types.ts
Normal file
133
tests/soak/core/types.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Core type definitions for the soak harness.
|
||||
*
|
||||
* Contracts here are consumed by runner.ts, SessionPool, scenarios,
|
||||
* and the dashboard. Keep this file small and stable.
|
||||
*/
|
||||
|
||||
import type { BrowserContext, Page } from 'playwright-core';
|
||||
|
||||
// =============================================================================
|
||||
// GolfBot — real class from tests/e2e/bot/
|
||||
// =============================================================================
|
||||
|
||||
import type { GolfBot } from '../../e2e/bot/golf-bot';
|
||||
export type { GolfBot };
|
||||
|
||||
// =============================================================================
|
||||
// Accounts & sessions
|
||||
// =============================================================================
|
||||
|
||||
export interface Account {
|
||||
/** Stable key used in logs, e.g. "soak_00". */
|
||||
key: string;
|
||||
username: string;
|
||||
password: string;
|
||||
/** JWT returned from /api/auth/login, may be refreshed by SessionPool. */
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
account: Account;
|
||||
context: BrowserContext;
|
||||
page: Page;
|
||||
bot: GolfBot;
|
||||
/** Convenience mirror of account.key. */
|
||||
key: string;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Scenarios
|
||||
// =============================================================================
|
||||
|
||||
export interface ScenarioNeeds {
|
||||
/** Total number of authenticated sessions the scenario requires. */
|
||||
accounts: number;
|
||||
/** How many rooms to partition sessions into (default: 1). */
|
||||
rooms?: number;
|
||||
/** CPUs to add per room (default: 0). */
|
||||
cpusPerRoom?: number;
|
||||
}
|
||||
|
||||
/** Free-form per-scenario config merged with CLI flags. */
|
||||
export type ScenarioConfig = Record<string, unknown>;
|
||||
|
||||
export interface ScenarioError {
|
||||
room: string;
|
||||
reason: string;
|
||||
detail?: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface ScenarioResult {
|
||||
gamesCompleted: number;
|
||||
errors: ScenarioError[];
|
||||
durationMs: number;
|
||||
customMetrics?: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface ScenarioContext {
|
||||
/** Merged config: CLI flags → env → scenario defaults → runner defaults. */
|
||||
config: ScenarioConfig;
|
||||
/** Pre-authenticated sessions; ordered. */
|
||||
sessions: Session[];
|
||||
coordinator: RoomCoordinatorApi;
|
||||
dashboard: DashboardReporter;
|
||||
logger: Logger;
|
||||
signal: AbortSignal;
|
||||
/** Reset the per-room watchdog. Call at each progress point. */
|
||||
heartbeat(roomId: string): void;
|
||||
}
|
||||
|
||||
export interface Scenario {
|
||||
name: string;
|
||||
description: string;
|
||||
defaultConfig: ScenarioConfig;
|
||||
needs: ScenarioNeeds;
|
||||
run(ctx: ScenarioContext): Promise<ScenarioResult>;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Room coordination
|
||||
// =============================================================================
|
||||
|
||||
export interface RoomCoordinatorApi {
|
||||
announce(roomId: string, code: string): void;
|
||||
await(roomId: string, timeoutMs?: number): Promise<string>;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Dashboard reporter
|
||||
// =============================================================================
|
||||
|
||||
export interface RoomState {
|
||||
phase?: string;
|
||||
currentPlayer?: string;
|
||||
hole?: number;
|
||||
totalHoles?: number;
|
||||
game?: number;
|
||||
totalGames?: number;
|
||||
moves?: number;
|
||||
players?: Array<{ key: string; score: number | null; isActive: boolean }>;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface DashboardReporter {
|
||||
update(roomId: string, state: Partial<RoomState>): void;
|
||||
log(level: 'info' | 'warn' | 'error', msg: string, meta?: object): void;
|
||||
incrementMetric(name: string, by?: number): void;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Logger
|
||||
// =============================================================================
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
|
||||
|
||||
export interface Logger {
|
||||
debug(msg: string, meta?: object): void;
|
||||
info(msg: string, meta?: object): void;
|
||||
warn(msg: string, meta?: object): void;
|
||||
error(msg: string, meta?: object): void;
|
||||
child(meta: object): Logger;
|
||||
}
|
||||
44
tests/soak/core/watchdog.ts
Normal file
44
tests/soak/core/watchdog.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Watchdog — simple per-room timeout detector.
|
||||
*
|
||||
* `start()` begins a countdown. `heartbeat()` resets it. If the
|
||||
* countdown elapses without a heartbeat, `onTimeout` fires once
|
||||
* (subsequent heartbeats are no-ops after firing, unless `start()`
|
||||
* is called again). `stop()` cancels any pending timer.
|
||||
*
|
||||
* Used by the runner to detect stuck rooms: one watchdog per room,
|
||||
* scenarios call ctx.heartbeat(roomId) at each progress point, and
|
||||
* a firing watchdog logs + aborts the run.
|
||||
*/
|
||||
|
||||
export class Watchdog {
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private fired = false;
|
||||
|
||||
constructor(
|
||||
private timeoutMs: number,
|
||||
private onTimeout: () => void,
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
this.stop();
|
||||
this.fired = false;
|
||||
this.timer = setTimeout(() => {
|
||||
if (this.fired) return;
|
||||
this.fired = true;
|
||||
this.onTimeout();
|
||||
}, this.timeoutMs);
|
||||
}
|
||||
|
||||
heartbeat(): void {
|
||||
if (this.fired) return;
|
||||
this.start();
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
173
tests/soak/dashboard/dashboard.css
Normal file
173
tests/soak/dashboard/dashboard.css
Normal file
@@ -0,0 +1,173 @@
|
||||
:root {
|
||||
--bg: #0a0e16;
|
||||
--panel: #0e1420;
|
||||
--border: #1a2230;
|
||||
--text: #c8d4e4;
|
||||
--accent: #7fbaff;
|
||||
--good: #6fd08f;
|
||||
--warn: #ffb84d;
|
||||
--err: #ff5c6c;
|
||||
--muted: #556577;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, system-ui, 'SF Mono', Consolas, monospace;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.dash-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 20px;
|
||||
background: linear-gradient(135deg, #0f1823, #0a1018);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.dash-header h1 { margin: 0; font-size: 16px; color: var(--accent); }
|
||||
.dash-header .meta { font-size: 11px; color: var(--muted); }
|
||||
.dash-header .meta span + span { margin-left: 12px; }
|
||||
|
||||
.meta-bar {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
padding: 10px 20px;
|
||||
background: #0c131d;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 12px;
|
||||
}
|
||||
.meta-bar .stat .label { color: var(--muted); margin-right: 6px; }
|
||||
.meta-bar .stat span:last-child { color: #fff; font-weight: 600; }
|
||||
|
||||
.rooms {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 1px;
|
||||
background: var(--border);
|
||||
}
|
||||
.room {
|
||||
background: var(--panel);
|
||||
padding: 14px 18px;
|
||||
min-height: 180px;
|
||||
}
|
||||
.room-title {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.room-title .name { font-size: 13px; color: var(--accent); font-weight: 600; }
|
||||
.room-title .phase {
|
||||
font-size: 10px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
background: #1a3a2a;
|
||||
color: var(--good);
|
||||
}
|
||||
.room-title .phase.lobby { background: #3a2a1a; color: var(--warn); }
|
||||
.room-title .phase.err { background: #3a1a1a; color: var(--err); }
|
||||
|
||||
.players {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.player {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 4px 8px;
|
||||
background: #0a0f18;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.player:hover { border-color: var(--accent); }
|
||||
.player.active {
|
||||
background: #1a2a40;
|
||||
border-left: 2px solid var(--accent);
|
||||
}
|
||||
.player .score { color: var(--muted); }
|
||||
|
||||
.progress-bar {
|
||||
height: 4px;
|
||||
background: var(--border);
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, var(--accent), var(--good));
|
||||
transition: width 0.3s;
|
||||
}
|
||||
.room-meta {
|
||||
font-size: 10px;
|
||||
color: var(--muted);
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.log {
|
||||
border-top: 1px solid var(--border);
|
||||
background: #080c13;
|
||||
max-height: 160px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.log .log-header {
|
||||
padding: 6px 20px;
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.log ul { list-style: none; margin: 0; padding: 4px 20px; font-size: 10px; }
|
||||
.log li { line-height: 1.5; font-family: monospace; color: var(--muted); }
|
||||
.log li.warn { color: var(--warn); }
|
||||
.log li.error { color: var(--err); }
|
||||
|
||||
.video-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
}
|
||||
.video-modal.hidden { display: none; }
|
||||
.video-modal-content {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 16px;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
}
|
||||
.video-modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
color: var(--accent);
|
||||
font-size: 13px;
|
||||
}
|
||||
.video-modal-header button {
|
||||
background: var(--border);
|
||||
color: var(--text);
|
||||
border: none;
|
||||
padding: 4px 12px;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
#video-frame {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 70vh;
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
166
tests/soak/dashboard/dashboard.js
Normal file
166
tests/soak/dashboard/dashboard.js
Normal file
@@ -0,0 +1,166 @@
|
||||
// tests/soak/dashboard/dashboard.js
|
||||
// Dashboard client: connects to the runner's WS server, renders the
|
||||
// room grid, updates tiles on each room_state message, appends logs,
|
||||
// handles click-to-watch for live screencasts (Task 23 wires frames).
|
||||
(() => {
|
||||
const ws = new WebSocket(`ws://${location.host}`);
|
||||
const roomsEl = document.getElementById('rooms');
|
||||
const logEl = document.getElementById('log-list');
|
||||
const wsStatusEl = document.getElementById('ws-status');
|
||||
const metricGames = document.getElementById('metric-games');
|
||||
const metricMoves = document.getElementById('metric-moves');
|
||||
const metricErrors = document.getElementById('metric-errors');
|
||||
const elapsedEl = document.getElementById('elapsed');
|
||||
|
||||
const roomTiles = new Map();
|
||||
const startTime = Date.now();
|
||||
let currentWatchedKey = null;
|
||||
|
||||
// Video modal
|
||||
const videoModal = document.getElementById('video-modal');
|
||||
const videoFrame = document.getElementById('video-frame');
|
||||
const videoTitle = document.getElementById('video-modal-title');
|
||||
const videoClose = document.getElementById('video-modal-close');
|
||||
|
||||
function fmtElapsed(ms) {
|
||||
const s = Math.floor(ms / 1000);
|
||||
const h = Math.floor(s / 3600);
|
||||
const m = Math.floor((s % 3600) / 60);
|
||||
const sec = s % 60;
|
||||
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
|
||||
}
|
||||
setInterval(() => {
|
||||
elapsedEl.textContent = fmtElapsed(Date.now() - startTime);
|
||||
}, 1000);
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) => ({
|
||||
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
||||
}[c]));
|
||||
}
|
||||
|
||||
function ensureRoomTile(roomId) {
|
||||
if (roomTiles.has(roomId)) return roomTiles.get(roomId);
|
||||
const tile = document.createElement('div');
|
||||
tile.className = 'room';
|
||||
tile.innerHTML = `
|
||||
<div class="room-title">
|
||||
<div class="name">${escapeHtml(roomId)}</div>
|
||||
<div class="phase lobby">waiting</div>
|
||||
</div>
|
||||
<div class="players"></div>
|
||||
<div class="progress-bar"><div class="progress-fill" style="width:0%"></div></div>
|
||||
<div class="room-meta">
|
||||
<span class="moves">0 moves</span>
|
||||
<span class="game">game —</span>
|
||||
</div>
|
||||
`;
|
||||
roomsEl.appendChild(tile);
|
||||
roomTiles.set(roomId, tile);
|
||||
return tile;
|
||||
}
|
||||
|
||||
function renderRoomState(roomId, state) {
|
||||
const tile = ensureRoomTile(roomId);
|
||||
if (state.phase !== undefined) {
|
||||
const phaseEl = tile.querySelector('.phase');
|
||||
phaseEl.textContent = state.phase;
|
||||
phaseEl.classList.toggle('lobby', state.phase === 'lobby' || state.phase === 'waiting');
|
||||
phaseEl.classList.toggle('err', state.phase === 'error');
|
||||
}
|
||||
if (state.players !== undefined) {
|
||||
const playersEl = tile.querySelector('.players');
|
||||
playersEl.innerHTML = state.players
|
||||
.map(
|
||||
(p) => `
|
||||
<div class="player ${p.isActive ? 'active' : ''}" data-session="${escapeHtml(p.key)}">
|
||||
<span>${p.isActive ? '▶ ' : ''}${escapeHtml(p.key)}</span>
|
||||
<span class="score">${p.score ?? '—'}</span>
|
||||
</div>
|
||||
`,
|
||||
)
|
||||
.join('');
|
||||
}
|
||||
if (state.hole !== undefined && state.totalHoles !== undefined) {
|
||||
const fill = tile.querySelector('.progress-fill');
|
||||
const pct = state.totalHoles > 0 ? Math.round((state.hole / state.totalHoles) * 100) : 0;
|
||||
fill.style.width = `${pct}%`;
|
||||
}
|
||||
if (state.moves !== undefined) {
|
||||
tile.querySelector('.moves').textContent = `${state.moves} moves`;
|
||||
}
|
||||
if (state.game !== undefined && state.totalGames !== undefined) {
|
||||
tile.querySelector('.game').textContent = `game ${state.game}/${state.totalGames}`;
|
||||
}
|
||||
}
|
||||
|
||||
function appendLog(level, msg, meta) {
|
||||
const li = document.createElement('li');
|
||||
li.className = level;
|
||||
const ts = new Date().toLocaleTimeString();
|
||||
li.textContent = `[${ts}] ${msg} ${meta ? JSON.stringify(meta) : ''}`;
|
||||
logEl.insertBefore(li, logEl.firstChild);
|
||||
while (logEl.children.length > 100) {
|
||||
logEl.removeChild(logEl.lastChild);
|
||||
}
|
||||
}
|
||||
|
||||
function applyMetric(name, value) {
|
||||
if (name === 'games_completed') metricGames.textContent = value;
|
||||
else if (name === 'moves_total') metricMoves.textContent = value;
|
||||
else if (name === 'errors') metricErrors.textContent = value;
|
||||
}
|
||||
|
||||
ws.addEventListener('open', () => {
|
||||
wsStatusEl.textContent = 'healthy';
|
||||
wsStatusEl.style.color = 'var(--good)';
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
wsStatusEl.textContent = 'disconnected';
|
||||
wsStatusEl.style.color = 'var(--err)';
|
||||
});
|
||||
ws.addEventListener('message', (event) => {
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (msg.type === 'room_state') {
|
||||
renderRoomState(msg.roomId, msg.state);
|
||||
} else if (msg.type === 'log') {
|
||||
appendLog(msg.level, msg.msg, msg.meta);
|
||||
} else if (msg.type === 'metric') {
|
||||
applyMetric(msg.name, msg.value);
|
||||
} else if (msg.type === 'frame') {
|
||||
if (msg.sessionKey === currentWatchedKey) {
|
||||
videoFrame.src = `data:image/jpeg;base64,${msg.jpegBase64}`;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Click-to-watch (screencasts start arriving after Task 22/23)
|
||||
roomsEl.addEventListener('click', (e) => {
|
||||
const playerEl = e.target.closest('.player');
|
||||
if (!playerEl) return;
|
||||
const key = playerEl.dataset.session;
|
||||
if (!key) return;
|
||||
currentWatchedKey = key;
|
||||
videoTitle.textContent = `Watching ${key}`;
|
||||
videoModal.classList.remove('hidden');
|
||||
ws.send(JSON.stringify({ type: 'start_stream', sessionKey: key }));
|
||||
});
|
||||
|
||||
function closeVideo() {
|
||||
if (currentWatchedKey) {
|
||||
ws.send(JSON.stringify({ type: 'stop_stream', sessionKey: currentWatchedKey }));
|
||||
}
|
||||
currentWatchedKey = null;
|
||||
videoModal.classList.add('hidden');
|
||||
videoFrame.src = '';
|
||||
}
|
||||
videoClose.addEventListener('click', closeVideo);
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape') closeVideo();
|
||||
});
|
||||
})();
|
||||
47
tests/soak/dashboard/index.html
Normal file
47
tests/soak/dashboard/index.html
Normal file
@@ -0,0 +1,47 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Golf Soak Dashboard</title>
|
||||
<link rel="stylesheet" href="/dashboard.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="dash-header">
|
||||
<h1>⛳ Golf Soak Dashboard</h1>
|
||||
<div class="meta">
|
||||
<span id="run-id">run —</span>
|
||||
<span id="elapsed">00:00:00</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="meta-bar">
|
||||
<div class="stat"><span class="label">Games</span><span id="metric-games">0</span></div>
|
||||
<div class="stat"><span class="label">Moves</span><span id="metric-moves">0</span></div>
|
||||
<div class="stat"><span class="label">Errors</span><span id="metric-errors">0</span></div>
|
||||
<div class="stat"><span class="label">WS</span><span id="ws-status">connecting</span></div>
|
||||
</div>
|
||||
|
||||
<div class="rooms" id="rooms">
|
||||
<!-- Room tiles injected by dashboard.js -->
|
||||
</div>
|
||||
|
||||
<section class="log">
|
||||
<div class="log-header">Activity Log</div>
|
||||
<ul id="log-list"></ul>
|
||||
</section>
|
||||
|
||||
<!-- Modal for focused live video (screencast arrives in Task 22/23) -->
|
||||
<div id="video-modal" class="video-modal hidden">
|
||||
<div class="video-modal-content">
|
||||
<div class="video-modal-header">
|
||||
<span id="video-modal-title">Watching —</span>
|
||||
<button id="video-modal-close">Close</button>
|
||||
</div>
|
||||
<img id="video-frame" alt="Live screencast" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/dashboard.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
154
tests/soak/dashboard/server.ts
Normal file
154
tests/soak/dashboard/server.ts
Normal file
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* DashboardServer — vanilla http + ws, serves one static HTML page
|
||||
* and broadcasts room_state/log/metric events to all connected clients.
|
||||
*
|
||||
* Scenarios never touch this directly — they call the DashboardReporter
|
||||
* returned by `server.reporter()`, which forwards over WS.
|
||||
*/
|
||||
|
||||
import * as http from 'http';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { WebSocketServer, WebSocket } from 'ws';
|
||||
import type { DashboardReporter, Logger, RoomState } from '../core/types';
|
||||
|
||||
export type DashboardIncoming =
|
||||
| { type: 'start_stream'; sessionKey: string }
|
||||
| { type: 'stop_stream'; sessionKey: string };
|
||||
|
||||
export type DashboardOutgoing =
|
||||
| { type: 'room_state'; roomId: string; state: Partial<RoomState> }
|
||||
| { type: 'log'; level: string; msg: string; meta?: object; timestamp: number }
|
||||
| { type: 'metric'; name: string; value: number }
|
||||
| { type: 'frame'; sessionKey: string; jpegBase64: string };
|
||||
|
||||
export interface DashboardHandlers {
|
||||
onStartStream?(sessionKey: string): void;
|
||||
onStopStream?(sessionKey: string): void;
|
||||
onDisconnect?(): void;
|
||||
}
|
||||
|
||||
export class DashboardServer {
|
||||
private httpServer!: http.Server;
|
||||
private wsServer!: WebSocketServer;
|
||||
private clients = new Set<WebSocket>();
|
||||
private metrics: Record<string, number> = {};
|
||||
private roomStates: Record<string, Partial<RoomState>> = {};
|
||||
|
||||
constructor(
|
||||
private port: number,
|
||||
private logger: Logger,
|
||||
private handlers: DashboardHandlers = {},
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
const htmlPath = path.resolve(__dirname, 'index.html');
|
||||
const cssPath = path.resolve(__dirname, 'dashboard.css');
|
||||
const jsPath = path.resolve(__dirname, 'dashboard.js');
|
||||
|
||||
this.httpServer = http.createServer((req, res) => {
|
||||
const url = req.url ?? '/';
|
||||
if (url === '/' || url === '/index.html') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
||||
fs.createReadStream(htmlPath).pipe(res);
|
||||
} else if (url === '/dashboard.css') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/css' });
|
||||
fs.createReadStream(cssPath).pipe(res);
|
||||
} else if (url === '/dashboard.js') {
|
||||
res.writeHead(200, { 'Content-Type': 'application/javascript' });
|
||||
fs.createReadStream(jsPath).pipe(res);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end('not found');
|
||||
}
|
||||
});
|
||||
|
||||
this.wsServer = new WebSocketServer({ server: this.httpServer });
|
||||
this.wsServer.on('connection', (ws) => {
|
||||
this.clients.add(ws);
|
||||
this.logger.info('dashboard_client_connected', { count: this.clients.size });
|
||||
|
||||
// Replay current state to the new client so late joiners see
|
||||
// everything that has happened since the run started.
|
||||
for (const [roomId, state] of Object.entries(this.roomStates)) {
|
||||
ws.send(
|
||||
JSON.stringify({ type: 'room_state', roomId, state } as DashboardOutgoing),
|
||||
);
|
||||
}
|
||||
for (const [name, value] of Object.entries(this.metrics)) {
|
||||
ws.send(JSON.stringify({ type: 'metric', name, value } as DashboardOutgoing));
|
||||
}
|
||||
|
||||
ws.on('message', (data) => {
|
||||
try {
|
||||
const parsed = JSON.parse(data.toString()) as DashboardIncoming;
|
||||
if (parsed.type === 'start_stream' && this.handlers.onStartStream) {
|
||||
this.handlers.onStartStream(parsed.sessionKey);
|
||||
} else if (parsed.type === 'stop_stream' && this.handlers.onStopStream) {
|
||||
this.handlers.onStopStream(parsed.sessionKey);
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.warn('dashboard_ws_parse_error', {
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
this.clients.delete(ws);
|
||||
this.logger.info('dashboard_client_disconnected', { count: this.clients.size });
|
||||
if (this.clients.size === 0 && this.handlers.onDisconnect) {
|
||||
this.handlers.onDisconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
this.httpServer.listen(this.port, () => resolve());
|
||||
});
|
||||
this.logger.info('dashboard_listening', { url: `http://localhost:${this.port}` });
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
for (const ws of this.clients) {
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
this.clients.clear();
|
||||
await new Promise<void>((resolve) => {
|
||||
this.wsServer.close(() => resolve());
|
||||
});
|
||||
await new Promise<void>((resolve) => {
|
||||
this.httpServer.close(() => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
broadcast(msg: DashboardOutgoing): void {
|
||||
const payload = JSON.stringify(msg);
|
||||
for (const ws of this.clients) {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a DashboardReporter wired to this server. */
|
||||
reporter(): DashboardReporter {
|
||||
return {
|
||||
update: (roomId, state) => {
|
||||
this.roomStates[roomId] = { ...this.roomStates[roomId], ...state };
|
||||
this.broadcast({ type: 'room_state', roomId, state });
|
||||
},
|
||||
log: (level, msg, meta) => {
|
||||
this.broadcast({ type: 'log', level, msg, meta, timestamp: Date.now() });
|
||||
},
|
||||
incrementMetric: (name, by = 1) => {
|
||||
this.metrics[name] = (this.metrics[name] ?? 0) + by;
|
||||
this.broadcast({ type: 'metric', name, value: this.metrics[name] });
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user