avrae-ls 0.5.1__py3-none-any.whl → 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- avrae_ls/__init__.py +3 -0
- avrae_ls/__main__.py +210 -0
- avrae_ls/alias_preview.py +371 -0
- avrae_ls/alias_tests.py +311 -0
- avrae_ls/api.py +2015 -0
- avrae_ls/argparser.py +430 -0
- avrae_ls/argument_parsing.py +67 -0
- avrae_ls/code_actions.py +282 -0
- avrae_ls/codes.py +3 -0
- avrae_ls/completions.py +1695 -0
- avrae_ls/config.py +474 -0
- avrae_ls/context.py +337 -0
- avrae_ls/cvars.py +115 -0
- avrae_ls/diagnostics.py +826 -0
- avrae_ls/dice.py +33 -0
- avrae_ls/parser.py +68 -0
- avrae_ls/runtime.py +750 -0
- avrae_ls/server.py +447 -0
- avrae_ls/signature_help.py +248 -0
- avrae_ls/symbols.py +274 -0
- {avrae_ls-0.5.1.dist-info → avrae_ls-0.6.1.dist-info}/METADATA +34 -4
- avrae_ls-0.6.1.dist-info/RECORD +34 -0
- {avrae_ls-0.5.1.dist-info → avrae_ls-0.6.1.dist-info}/WHEEL +1 -1
- draconic/__init__.py +4 -0
- draconic/exceptions.py +157 -0
- draconic/helpers.py +236 -0
- draconic/interpreter.py +1091 -0
- draconic/string.py +100 -0
- draconic/types.py +364 -0
- draconic/utils.py +78 -0
- draconic/versions.py +4 -0
- avrae_ls-0.5.1.dist-info/RECORD +0 -6
- {avrae_ls-0.5.1.dist-info → avrae_ls-0.6.1.dist-info}/entry_points.txt +0 -0
- {avrae_ls-0.5.1.dist-info → avrae_ls-0.6.1.dist-info}/licenses/LICENSE +0 -0
avrae_ls/__init__.py
ADDED
avrae_ls/__main__.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
import logging
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Iterable
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from lsprotocol import types
|
|
13
|
+
|
|
14
|
+
from .alias_tests import AliasTestError, AliasTestResult, discover_test_files, parse_alias_tests, run_alias_tests
|
|
15
|
+
from .config import CONFIG_FILENAME, load_config
|
|
16
|
+
from .context import ContextBuilder
|
|
17
|
+
from .diagnostics import DiagnosticProvider
|
|
18
|
+
from .runtime import MockExecutor
|
|
19
|
+
from .server import create_server, __version__
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main(argv: list[str] | None = None) -> None:
|
|
23
|
+
parser = argparse.ArgumentParser(description="Avrae draconic alias language server")
|
|
24
|
+
parser.add_argument("--tcp", action="store_true", help="Run in TCP mode instead of stdio")
|
|
25
|
+
parser.add_argument("--host", default="127.0.0.1", help="TCP host (when --tcp is set)")
|
|
26
|
+
parser.add_argument("--port", type=int, default=2087, help="TCP port (when --tcp is set)")
|
|
27
|
+
parser.add_argument("--stdio", action="store_true", help="Accept stdio flag for VS Code clients (ignored)")
|
|
28
|
+
parser.add_argument("--log-level", default="WARNING", help="Logging level (DEBUG, INFO, WARNING, ERROR)")
|
|
29
|
+
parser.add_argument("--analyze", metavar="FILE", help="Run diagnostics for a file and print them to stdout")
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--run-tests",
|
|
32
|
+
metavar="PATH",
|
|
33
|
+
nargs="?",
|
|
34
|
+
const=".",
|
|
35
|
+
help="Run alias tests in PATH (defaults to current directory)",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument("--version", action="store_true", help="Print version and exit")
|
|
38
|
+
args = parser.parse_args(argv)
|
|
39
|
+
|
|
40
|
+
_configure_logging(args.log_level)
|
|
41
|
+
|
|
42
|
+
if args.version:
|
|
43
|
+
print(__version__)
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
if args.run_tests is not None:
|
|
47
|
+
if args.tcp:
|
|
48
|
+
parser.error("--run-tests cannot be combined with --tcp")
|
|
49
|
+
if args.analyze:
|
|
50
|
+
parser.error("--run-tests cannot be combined with --analyze")
|
|
51
|
+
sys.exit(_run_alias_tests(Path(args.run_tests)))
|
|
52
|
+
|
|
53
|
+
if args.analyze:
|
|
54
|
+
if args.tcp:
|
|
55
|
+
parser.error("--analyze cannot be combined with --tcp")
|
|
56
|
+
sys.exit(_run_analysis(Path(args.analyze)))
|
|
57
|
+
|
|
58
|
+
server = create_server()
|
|
59
|
+
if args.tcp:
|
|
60
|
+
server.start_tcp(args.host, args.port)
|
|
61
|
+
else:
|
|
62
|
+
server.start_io()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _configure_logging(level: str) -> None:
|
|
66
|
+
numeric = getattr(logging, level.upper(), logging.WARNING)
|
|
67
|
+
if not isinstance(numeric, int):
|
|
68
|
+
numeric = logging.WARNING
|
|
69
|
+
logging.basicConfig(
|
|
70
|
+
level=numeric,
|
|
71
|
+
format="%(levelname)s %(name)s: %(message)s",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _run_analysis(path: Path) -> int:
|
|
76
|
+
if not path.exists():
|
|
77
|
+
print(f"File not found: {path}", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
|
|
80
|
+
workspace_root = _discover_workspace_root(path)
|
|
81
|
+
log = logging.getLogger(__name__)
|
|
82
|
+
log.info("Analyzing %s (workspace root: %s)", path, workspace_root)
|
|
83
|
+
|
|
84
|
+
config, warnings = load_config(workspace_root)
|
|
85
|
+
for warning in warnings:
|
|
86
|
+
log.warning(warning)
|
|
87
|
+
|
|
88
|
+
builder = ContextBuilder(config)
|
|
89
|
+
ctx_data = builder.build()
|
|
90
|
+
executor = MockExecutor(config.service)
|
|
91
|
+
diagnostics = DiagnosticProvider(executor, config.diagnostics)
|
|
92
|
+
|
|
93
|
+
source = path.read_text()
|
|
94
|
+
results = asyncio.run(diagnostics.analyze(source, ctx_data, builder.gvar_resolver))
|
|
95
|
+
_print_diagnostics(path, results)
|
|
96
|
+
return 1 if results else 0
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _run_alias_tests(target: Path) -> int:
|
|
100
|
+
if not target.exists():
|
|
101
|
+
print(f"Test path not found: {target}", file=sys.stderr)
|
|
102
|
+
return 2
|
|
103
|
+
|
|
104
|
+
workspace_root = _discover_workspace_root(target)
|
|
105
|
+
log = logging.getLogger(__name__)
|
|
106
|
+
log.info("Running alias tests in %s (workspace root: %s)", target, workspace_root)
|
|
107
|
+
|
|
108
|
+
config, warnings = load_config(workspace_root)
|
|
109
|
+
for warning in warnings:
|
|
110
|
+
log.warning(warning)
|
|
111
|
+
|
|
112
|
+
builder = ContextBuilder(config)
|
|
113
|
+
executor = MockExecutor(config.service)
|
|
114
|
+
|
|
115
|
+
test_files = discover_test_files(target)
|
|
116
|
+
cases = []
|
|
117
|
+
parse_errors: list[str] = []
|
|
118
|
+
for test_file in test_files:
|
|
119
|
+
try:
|
|
120
|
+
cases.extend(parse_alias_tests(test_file))
|
|
121
|
+
except AliasTestError as exc:
|
|
122
|
+
parse_errors.append(str(exc))
|
|
123
|
+
|
|
124
|
+
if parse_errors:
|
|
125
|
+
for err in parse_errors:
|
|
126
|
+
print(err, file=sys.stderr)
|
|
127
|
+
if not cases:
|
|
128
|
+
print(f"No alias tests found under {target}")
|
|
129
|
+
return 1 if parse_errors else 0
|
|
130
|
+
|
|
131
|
+
results = asyncio.run(run_alias_tests(cases, builder, executor))
|
|
132
|
+
_print_test_results(results, workspace_root)
|
|
133
|
+
|
|
134
|
+
failures = [res for res in results if not res.passed]
|
|
135
|
+
return 1 if failures or parse_errors else 0
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _print_test_results(results: Iterable[AliasTestResult], workspace_root: Path) -> None:
|
|
139
|
+
total = len(results)
|
|
140
|
+
passed = 0
|
|
141
|
+
for res in results:
|
|
142
|
+
rel = _relative_to_workspace(res.case.path, workspace_root)
|
|
143
|
+
label = f"{rel} ({res.case.name})" if res.case.name else rel
|
|
144
|
+
status = "PASS" if res.passed else "FAIL"
|
|
145
|
+
print(f"[{status}] {label} (alias: {res.case.alias_name})")
|
|
146
|
+
if res.passed:
|
|
147
|
+
if res.stdout:
|
|
148
|
+
print(f" Stdout: {res.stdout.strip()}")
|
|
149
|
+
passed += 1
|
|
150
|
+
continue
|
|
151
|
+
if res.error:
|
|
152
|
+
print(f" Error: {res.error}")
|
|
153
|
+
if res.details:
|
|
154
|
+
print(f" {res.details}")
|
|
155
|
+
expected = _format_value(res.case.expected)
|
|
156
|
+
actual = _format_value(res.actual)
|
|
157
|
+
print(f" Expected: {expected}")
|
|
158
|
+
print(f" Actual: {actual}")
|
|
159
|
+
if res.stdout:
|
|
160
|
+
print(f" Stdout: {res.stdout.strip()}")
|
|
161
|
+
print(f"{passed}/{total} tests passed")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _relative_to_workspace(path: Path, workspace_root: Path) -> str:
|
|
165
|
+
try:
|
|
166
|
+
return str(path.relative_to(workspace_root))
|
|
167
|
+
except ValueError:
|
|
168
|
+
return str(path)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _format_value(value) -> str:
|
|
172
|
+
if value is None:
|
|
173
|
+
return "None"
|
|
174
|
+
if isinstance(value, (dict, list)):
|
|
175
|
+
return (yaml.safe_dump(value, sort_keys=False) or "").strip()
|
|
176
|
+
return str(value)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _discover_workspace_root(target: Path) -> Path:
|
|
180
|
+
current = target if target.is_dir() else target.parent
|
|
181
|
+
for folder in [current, *current.parents]:
|
|
182
|
+
if (folder / CONFIG_FILENAME).exists():
|
|
183
|
+
return folder
|
|
184
|
+
return current
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _print_diagnostics(path: Path, diagnostics: Iterable[types.Diagnostic]) -> None:
|
|
188
|
+
diags = list(diagnostics)
|
|
189
|
+
if not diags:
|
|
190
|
+
print(f"{path}: no issues found")
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
for diag in diags:
|
|
194
|
+
start = diag.range.start
|
|
195
|
+
severity = _severity_label(diag.severity)
|
|
196
|
+
source = diag.source or "avrae-ls"
|
|
197
|
+
print(f"{path}:{start.line + 1}:{start.character + 1}: {severity} [{source}] {diag.message}")
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _severity_label(severity: types.DiagnosticSeverity | None) -> str:
|
|
201
|
+
if severity is None:
|
|
202
|
+
return "info"
|
|
203
|
+
try:
|
|
204
|
+
return types.DiagnosticSeverity(severity).name.lower()
|
|
205
|
+
except Exception:
|
|
206
|
+
return str(severity).lower()
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
if __name__ == "__main__":
|
|
210
|
+
main()
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import shlex
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from typing import Any, Optional, Tuple
|
|
7
|
+
|
|
8
|
+
from .parser import DRACONIC_RE, INLINE_DRACONIC_RE, INLINE_ROLL_RE
|
|
9
|
+
from .runtime import ExecutionResult, MockExecutor, _roll_dice
|
|
10
|
+
from .context import ContextData, GVarResolver
|
|
11
|
+
from .argument_parsing import apply_argument_parsing
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class RenderedAlias:
|
|
16
|
+
command: str
|
|
17
|
+
stdout: str
|
|
18
|
+
error: Optional[BaseException]
|
|
19
|
+
last_value: Any | None = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class EmbedFieldPreview:
|
|
24
|
+
name: str
|
|
25
|
+
value: str
|
|
26
|
+
inline: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class EmbedPreview:
|
|
31
|
+
title: str | None = None
|
|
32
|
+
description: str | None = None
|
|
33
|
+
footer: str | None = None
|
|
34
|
+
thumbnail: str | None = None
|
|
35
|
+
image: str | None = None
|
|
36
|
+
color: str | None = None
|
|
37
|
+
timeout: int | None = None
|
|
38
|
+
fields: list[EmbedFieldPreview] = field(default_factory=list)
|
|
39
|
+
|
|
40
|
+
def to_dict(self) -> dict[str, Any]:
|
|
41
|
+
return {
|
|
42
|
+
"title": self.title,
|
|
43
|
+
"description": self.description,
|
|
44
|
+
"footer": self.footer,
|
|
45
|
+
"thumbnail": self.thumbnail,
|
|
46
|
+
"image": self.image,
|
|
47
|
+
"color": self.color,
|
|
48
|
+
"timeout": self.timeout,
|
|
49
|
+
"fields": [asdict(f) for f in self.fields],
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class SimulatedCommand:
|
|
55
|
+
preview: str | None
|
|
56
|
+
command_name: str | None
|
|
57
|
+
validation_error: str | None
|
|
58
|
+
embed: EmbedPreview | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _strip_alias_header(text: str) -> str:
|
|
62
|
+
lines = text.splitlines()
|
|
63
|
+
if lines and lines[0].lstrip().startswith("!alias"):
|
|
64
|
+
first = lines[0].lstrip()
|
|
65
|
+
parts = first.split(maxsplit=2)
|
|
66
|
+
remainder = parts[2] if len(parts) > 2 else ""
|
|
67
|
+
body = "\n".join(lines[1:])
|
|
68
|
+
if remainder:
|
|
69
|
+
return remainder + ("\n" + body if body else "")
|
|
70
|
+
return body
|
|
71
|
+
return text
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def render_alias_command(
|
|
75
|
+
text: str,
|
|
76
|
+
executor: MockExecutor,
|
|
77
|
+
ctx_data: ContextData,
|
|
78
|
+
resolver: GVarResolver,
|
|
79
|
+
args: list[str] | None = None,
|
|
80
|
+
) -> RenderedAlias:
|
|
81
|
+
"""Replace <drac2> blocks with their evaluated values and return final command."""
|
|
82
|
+
body = _strip_alias_header(text)
|
|
83
|
+
body = apply_argument_parsing(body, args)
|
|
84
|
+
stdout_parts: list[str] = []
|
|
85
|
+
parts: list[str] = []
|
|
86
|
+
last_value = None
|
|
87
|
+
error: BaseException | None = None
|
|
88
|
+
|
|
89
|
+
pos = 0
|
|
90
|
+
matches: list[tuple[str, re.Match[str]]] = []
|
|
91
|
+
for match in DRACONIC_RE.finditer(body):
|
|
92
|
+
matches.append(("block", match))
|
|
93
|
+
for match in INLINE_DRACONIC_RE.finditer(body):
|
|
94
|
+
matches.append(("inline", match))
|
|
95
|
+
for match in INLINE_ROLL_RE.finditer(body):
|
|
96
|
+
matches.append(("roll", match))
|
|
97
|
+
|
|
98
|
+
matches.sort(key=lambda item: item[1].start())
|
|
99
|
+
|
|
100
|
+
for kind, match in matches:
|
|
101
|
+
if match.start() < pos:
|
|
102
|
+
continue
|
|
103
|
+
parts.append(body[pos: match.start()])
|
|
104
|
+
|
|
105
|
+
if kind in {"block", "inline"}:
|
|
106
|
+
code = match.group(1)
|
|
107
|
+
result: ExecutionResult = await executor.run(code, ctx_data, resolver)
|
|
108
|
+
if result.stdout:
|
|
109
|
+
stdout_parts.append(result.stdout)
|
|
110
|
+
if result.error:
|
|
111
|
+
error = result.error
|
|
112
|
+
break
|
|
113
|
+
last_value = result.value
|
|
114
|
+
if result.value is not None:
|
|
115
|
+
parts.append(str(result.value))
|
|
116
|
+
else:
|
|
117
|
+
roll_expr = match.group(1)
|
|
118
|
+
roll_total = _roll_dice(roll_expr)
|
|
119
|
+
last_value = roll_total
|
|
120
|
+
parts.append(str(roll_total))
|
|
121
|
+
pos = match.end()
|
|
122
|
+
|
|
123
|
+
if error is None:
|
|
124
|
+
parts.append(body[pos:])
|
|
125
|
+
|
|
126
|
+
final_command = "".join(parts)
|
|
127
|
+
return RenderedAlias(command=final_command, stdout="".join(stdout_parts), error=error, last_value=last_value)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def validate_embed_payload(payload: str) -> Tuple[bool, str | None]:
|
|
131
|
+
"""
|
|
132
|
+
Light validation for embed previews using Avrae-style flags.
|
|
133
|
+
|
|
134
|
+
Accepts strings such as "-title Foo -f \"T|Body\"" and validates arguments.
|
|
135
|
+
Returns (is_valid, error_message) without attempting to parse JSON objects.
|
|
136
|
+
"""
|
|
137
|
+
text = payload.strip()
|
|
138
|
+
if not text:
|
|
139
|
+
return False, "Embed payload is empty."
|
|
140
|
+
|
|
141
|
+
return _validate_embed_flags(text)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def parse_embed_payload(payload: str) -> EmbedPreview:
|
|
145
|
+
"""Parse an embed payload into a structured preview object."""
|
|
146
|
+
tokens = shlex.split(payload.strip())
|
|
147
|
+
preview = EmbedPreview()
|
|
148
|
+
|
|
149
|
+
i = 0
|
|
150
|
+
while i < len(tokens):
|
|
151
|
+
tok = tokens[i]
|
|
152
|
+
if not tok.startswith("-"):
|
|
153
|
+
i += 1
|
|
154
|
+
continue
|
|
155
|
+
key = tok.lower()
|
|
156
|
+
next_val = tokens[i + 1] if i + 1 < len(tokens) else None
|
|
157
|
+
if key == "-title":
|
|
158
|
+
preview.title = next_val or ""
|
|
159
|
+
i += 2
|
|
160
|
+
continue
|
|
161
|
+
if key == "-desc":
|
|
162
|
+
preview.description = next_val or ""
|
|
163
|
+
i += 2
|
|
164
|
+
continue
|
|
165
|
+
if key == "-footer":
|
|
166
|
+
preview.footer = next_val or ""
|
|
167
|
+
i += 2
|
|
168
|
+
continue
|
|
169
|
+
if key == "-thumb":
|
|
170
|
+
preview.thumbnail = next_val or ""
|
|
171
|
+
i += 2
|
|
172
|
+
continue
|
|
173
|
+
if key == "-image":
|
|
174
|
+
preview.image = next_val or ""
|
|
175
|
+
i += 2
|
|
176
|
+
continue
|
|
177
|
+
if key == "-color":
|
|
178
|
+
preview.color = _normalize_color(next_val)
|
|
179
|
+
i += 2 if next_val is not None else 1
|
|
180
|
+
continue
|
|
181
|
+
if key == "-t":
|
|
182
|
+
preview.timeout = _parse_timeout(next_val)
|
|
183
|
+
i += 2
|
|
184
|
+
continue
|
|
185
|
+
if key == "-f":
|
|
186
|
+
field = _parse_field_value(next_val)
|
|
187
|
+
if field:
|
|
188
|
+
preview.fields.append(field)
|
|
189
|
+
i += 2
|
|
190
|
+
continue
|
|
191
|
+
i += 1
|
|
192
|
+
|
|
193
|
+
return preview
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _validate_embed_flags(text: str) -> Tuple[bool, str | None]:
|
|
197
|
+
"""Validate embed flags according to Avrae's help text."""
|
|
198
|
+
if not text:
|
|
199
|
+
return False, "Embed payload is empty."
|
|
200
|
+
|
|
201
|
+
try:
|
|
202
|
+
tokens = shlex.split(text)
|
|
203
|
+
except ValueError as exc: # pragma: no cover - defensive only
|
|
204
|
+
return False, f"Embed payload could not be parsed: {exc}"
|
|
205
|
+
|
|
206
|
+
flag_handlers = {
|
|
207
|
+
"-title": lambda val: _require_value("-title", val),
|
|
208
|
+
"-desc": lambda val: _require_value("-desc", val),
|
|
209
|
+
"-thumb": lambda val: _require_value("-thumb", val),
|
|
210
|
+
"-image": lambda val: _require_value("-image", val),
|
|
211
|
+
"-footer": lambda val: _require_value("-footer", val),
|
|
212
|
+
"-f": _validate_field_arg,
|
|
213
|
+
"-color": _validate_color_arg,
|
|
214
|
+
"-t": _validate_timeout_arg,
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
i = 0
|
|
218
|
+
while i < len(tokens):
|
|
219
|
+
tok = tokens[i]
|
|
220
|
+
key = tok.lower()
|
|
221
|
+
if not tok.startswith("-"):
|
|
222
|
+
i += 1
|
|
223
|
+
continue
|
|
224
|
+
if key not in flag_handlers:
|
|
225
|
+
return False, f"Embed payload contains unknown flag '{tok}'."
|
|
226
|
+
next_val = tokens[i + 1] if i + 1 < len(tokens) else None
|
|
227
|
+
ok, err, consumed = flag_handlers[key](next_val)
|
|
228
|
+
if not ok:
|
|
229
|
+
return False, err
|
|
230
|
+
i += consumed + 1
|
|
231
|
+
return True, None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _require_value(flag: str, value: str | None) -> Tuple[bool, str | None, int]:
|
|
235
|
+
if value is None or value.startswith("-"):
|
|
236
|
+
return False, f"Embed flag '{flag}' requires a value.", 0
|
|
237
|
+
return True, None, 1
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _validate_field_arg(value: str | None) -> Tuple[bool, str | None, int]:
|
|
241
|
+
ok, err, consumed = _require_value("-f", value)
|
|
242
|
+
if not ok:
|
|
243
|
+
return ok, err, consumed
|
|
244
|
+
assert value is not None # for type checker
|
|
245
|
+
parts = value.split("|")
|
|
246
|
+
if len(parts) < 2 or len(parts) > 3:
|
|
247
|
+
return False, "Embed field must be in the form \"Title|Text[|inline]\".", consumed
|
|
248
|
+
if not parts[0] or not parts[1]:
|
|
249
|
+
return False, "Embed field title and text cannot be empty.", consumed
|
|
250
|
+
if len(parts) == 3 and parts[2].lower() not in ("inline", ""):
|
|
251
|
+
return False, "Embed field inline value must be 'inline' or omitted.", consumed
|
|
252
|
+
return True, None, consumed
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _validate_color_arg(value: str | None) -> Tuple[bool, str | None, int]:
|
|
256
|
+
if value is None or value.startswith("-"):
|
|
257
|
+
# Random color is allowed when omitted
|
|
258
|
+
return True, None, 0
|
|
259
|
+
if str(value).strip().lower() == "<color>":
|
|
260
|
+
# Avrae placeholder accepted
|
|
261
|
+
return True, None, 1
|
|
262
|
+
if not re.match(r"^(?:#|0x)?[0-9a-fA-F]{6}$", value):
|
|
263
|
+
return False, "Embed color must be a 6-hex value (e.g. #ff00ff).", 1
|
|
264
|
+
return True, None, 1
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _validate_timeout_arg(value: str | None) -> Tuple[bool, str | None, int]:
|
|
268
|
+
ok, err, consumed = _require_value("-t", value)
|
|
269
|
+
if not ok:
|
|
270
|
+
return ok, err, consumed
|
|
271
|
+
assert value is not None # for type checker
|
|
272
|
+
try:
|
|
273
|
+
num = int(value)
|
|
274
|
+
except ValueError:
|
|
275
|
+
return False, "Embed timeout (-t) must be an integer.", consumed
|
|
276
|
+
if num < 0 or num > 600:
|
|
277
|
+
return False, "Embed timeout (-t) must be between 0 and 600 seconds.", consumed
|
|
278
|
+
return True, None, consumed
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _parse_timeout(value: str | None) -> int | None:
|
|
282
|
+
if value is None:
|
|
283
|
+
return None
|
|
284
|
+
try:
|
|
285
|
+
return int(value)
|
|
286
|
+
except (TypeError, ValueError):
|
|
287
|
+
return None
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _normalize_color(value: str | None) -> str | None:
|
|
291
|
+
if value is None:
|
|
292
|
+
return None
|
|
293
|
+
if not value:
|
|
294
|
+
return None
|
|
295
|
+
if str(value).strip().lower() == "<color>":
|
|
296
|
+
return "<color>"
|
|
297
|
+
match = re.match(r"^(?:#|0x)?([0-9a-fA-F]{6})$", value)
|
|
298
|
+
if not match:
|
|
299
|
+
return value
|
|
300
|
+
return f"#{match.group(1)}"
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _parse_field_value(value: str | None) -> EmbedFieldPreview | None:
|
|
304
|
+
if value is None:
|
|
305
|
+
return None
|
|
306
|
+
parts = value.split("|")
|
|
307
|
+
if len(parts) < 2:
|
|
308
|
+
return None
|
|
309
|
+
inline_flag = parts[2].lower() == "inline" if len(parts) == 3 else False
|
|
310
|
+
return EmbedFieldPreview(name=parts[0], value=parts[1], inline=inline_flag)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def simulate_command(command: str) -> SimulatedCommand:
|
|
314
|
+
"""Very small shim to preview common commands."""
|
|
315
|
+
text = _strip_alias_header(command).strip()
|
|
316
|
+
if not text:
|
|
317
|
+
return SimulatedCommand(None, None, None, None)
|
|
318
|
+
head, payload = _extract_command_head_and_payload(text)
|
|
319
|
+
if not head:
|
|
320
|
+
return SimulatedCommand(None, None, None, None)
|
|
321
|
+
lowered = head.lower()
|
|
322
|
+
if lowered == "echo":
|
|
323
|
+
return SimulatedCommand(payload, "echo", None, None)
|
|
324
|
+
if lowered == "embed":
|
|
325
|
+
valid, error = validate_embed_payload(payload)
|
|
326
|
+
embed_preview = parse_embed_payload(payload) if valid else None
|
|
327
|
+
return SimulatedCommand(payload, "embed", error, embed_preview)
|
|
328
|
+
if head.startswith("-") and _is_embed_flag(head):
|
|
329
|
+
payload = text
|
|
330
|
+
valid, error = validate_embed_payload(payload)
|
|
331
|
+
embed_preview = parse_embed_payload(payload) if valid else None
|
|
332
|
+
return SimulatedCommand(payload, "embed", error, embed_preview)
|
|
333
|
+
return SimulatedCommand(None, head, None, None)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _extract_command_head_and_payload(text: str) -> tuple[str | None, str]:
|
|
337
|
+
"""Prefer the first non-empty line; fall back to any embed line later."""
|
|
338
|
+
lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
|
|
339
|
+
if not lines:
|
|
340
|
+
return None, ""
|
|
341
|
+
head, payload = _split_head_and_payload_from_line(lines[0])
|
|
342
|
+
if _is_embed_flag(head):
|
|
343
|
+
# Treat the entire payload (including the head line) as embed flags so multiple lines are preserved.
|
|
344
|
+
return head, "\n".join(lines)
|
|
345
|
+
if head and head.lower() in ("embed", "echo"):
|
|
346
|
+
return head, _merge_payload(payload, lines[1:])
|
|
347
|
+
for idx, line in enumerate(lines[1:], start=1):
|
|
348
|
+
possible_head, possible_payload = _split_head_and_payload_from_line(line)
|
|
349
|
+
if possible_head and (possible_head.lower() == "embed" or _is_embed_flag(possible_head)):
|
|
350
|
+
return possible_head, _merge_payload(possible_payload, lines[idx + 1 :])
|
|
351
|
+
return head, _merge_payload(payload, lines[1:])
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _split_head_and_payload_from_line(line: str) -> tuple[str | None, str]:
|
|
355
|
+
if not line:
|
|
356
|
+
return None, ""
|
|
357
|
+
parts = line.split(maxsplit=1)
|
|
358
|
+
head = parts[0]
|
|
359
|
+
payload = parts[1] if len(parts) > 1 else ""
|
|
360
|
+
return head, payload
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _merge_payload(first_payload: str, trailing_lines: list[str]) -> str:
|
|
364
|
+
payload = first_payload
|
|
365
|
+
if trailing_lines:
|
|
366
|
+
payload = (payload + "\n" if payload else "") + "\n".join(trailing_lines)
|
|
367
|
+
return payload
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _is_embed_flag(flag: str) -> bool:
|
|
371
|
+
return flag.lower() in {"-title", "-desc", "-thumb", "-image", "-footer", "-f", "-color", "-t"}
|