feat(v1.5.0): Full-Stack Web Engine, F-Strings, Cyber OSINT & Terminal UI Suite
This commit is contained in:
1 parent
619492bdbf
commit
f90ea8cdd1
13 files changed
+766
-26
No files matched your search
@@ -0,0 +1,81 @@
|
|||||||
|
// ========================================================
|
||||||
|
// AiraLang v1.5.0 - Showcase & Feature Demonstration
|
||||||
|
// Engineered by Er. Adam Eehan (Aira Group of Technology)
|
||||||
|
// ========================================================
|
||||||
|
|
||||||
|
import "term";
|
||||||
|
import "crypto";
|
||||||
|
import "env";
|
||||||
|
import "sec";
|
||||||
|
import "serve";
|
||||||
|
import "http";
|
||||||
|
|
||||||
|
// 1. Sleek Terminal Box & Rainbow Header
|
||||||
|
term.box("AIRALANG v1.5.0 POWERHOUSE", [
|
||||||
|
"• F-Strings String Interpolation",
|
||||||
|
"• Native Micro Web Server (serve)",
|
||||||
|
"• Cyber OSINT & SSL Inspection (sec)",
|
||||||
|
"• Modern JWT & UUID Cryptography",
|
||||||
|
"• Functional Array Methods (.map, .filter)"
|
||||||
|
], "cyan");
|
||||||
|
|
||||||
|
say term.rainbow("⚡ AiraLang is fully compiled and active! ⚡");
|
||||||
|
|
||||||
|
// 2. F-Strings & Variables
|
||||||
|
let author = "Er. Adam Eehan";
|
||||||
|
let release_edition = "Full-Stack Web & Cyber OSINT Edition";
|
||||||
|
say f"Language: AiraLang v1.5.0 ({release_edition})";
|
||||||
|
say f"Lead Architect: {author}";
|
||||||
|
|
||||||
|
// 3. Functional Array Transformations
|
||||||
|
let scores = [45, 88, 92, 33, 76, 100];
|
||||||
|
let high_scores = scores.filter(fn(s) { return s >= 75; });
|
||||||
|
let formatted = high_scores.map(fn(s) { return f"Score: {s} pts"; }).join(" | ");
|
||||||
|
say f"High Scorers: {formatted}";
|
||||||
|
|
||||||
|
// 4. Crypto JWT Generation & Verification
|
||||||
|
let secret_key = "adam_aira_2026_master_key";
|
||||||
|
let auth_payload = {"user": "adameehan", "role": "CEO", "org": "Aira Group of Technology"};
|
||||||
|
let jwt_token = crypto.jwt_sign(auth_payload, secret_key);
|
||||||
|
say f"Generated JWT: {jwt_token}";
|
||||||
|
|
||||||
|
let verified = crypto.jwt_verify(jwt_token, secret_key);
|
||||||
|
say f"JWT Status: Valid={verified['valid']}, User={verified['payload']['user']}";
|
||||||
|
say f"Unique Device UUID: {crypto.uuid()}";
|
||||||
|
|
||||||
|
// 5. Environmental Secrets Handling
|
||||||
|
env.set("APP_ENV", "production");
|
||||||
|
say f"Environment Mode: {env.get('APP_ENV')}";
|
||||||
|
|
||||||
|
// 6. Cyber OSINT Recon
|
||||||
|
let target = "google.com";
|
||||||
|
let dns = sec.dns(target);
|
||||||
|
say f"DNS Resolution for {target}: Found {dns['count']} IPs -> {dns['ips'][0]}";
|
||||||
|
|
||||||
|
// 7. Micro Web Server Engine
|
||||||
|
serve.route("/api/v1/status", fn(req) {
|
||||||
|
return {
|
||||||
|
"status": "online",
|
||||||
|
"version": "1.5.0",
|
||||||
|
"framework": "AiraLang Native Web Engine",
|
||||||
|
"creator": "Adam Eehan"
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
let server = serve.start(port=9911, background=true);
|
||||||
|
say f"Native Web Server running on port {server['port']}";
|
||||||
|
|
||||||
|
let response = http.get("http://127.0.0.1:9911/api/v1/status");
|
||||||
|
say f"Web Server Test Response: {response}";
|
||||||
|
|
||||||
|
// 8. Visual Summary Table
|
||||||
|
term.table(["Feature", "Module", "Version", "Status"], [
|
||||||
|
["F-Strings", "core", "v1.5.0", "VERIFIED"],
|
||||||
|
["Micro Server", "serve", "v1.5.0", "VERIFIED"],
|
||||||
|
["Terminal UI", "term", "v1.5.0", "VERIFIED"],
|
||||||
|
["Webhooks", "webhook", "v1.5.0", "VERIFIED"],
|
||||||
|
["Bot Dispatcher", "bot", "v1.5.0", "VERIFIED"],
|
||||||
|
["Dotenv & Secrets", "env", "v1.5.0", "VERIFIED"],
|
||||||
|
["JWT & UUID", "crypto", "v1.5.0", "VERIFIED"],
|
||||||
|
["SSL & DNS Recon", "sec", "v1.5.0", "VERIFIED"]
|
||||||
|
]);
|
||||||
+26
-21
@@ -1,11 +1,11 @@
|
|||||||
# 📦 AiraLang Standard Library Modules Directory
|
# 📦 AiraLang Standard Library Modules Directory
|
||||||
> **Official Module Catalog for AiraLang (v1.4.4 Cross-Platform & System Edition)**
|
> **Official Module Catalog for AiraLang (v1.5.0 Full-Stack Web & Cyber OSINT Edition)**
|
||||||
> **Author & Creator:** Adam Eehan (Founder & CEO, Aira Group of Technology) 👑
|
> **Author & Creator:** Er. Adam Eehan (Founder & CEO, Aira Group of Technology) 👑
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🌟 Overview
|
## 🌟 Overview
|
||||||
AiraLang features 16 built-in standard library modules engineered natively for speed, AI capabilities, cyber security recon, system operations, and developer joy.
|
AiraLang features 22 built-in standard library modules engineered natively for full-stack web serving, AI capabilities, cyber security recon, system operations, and terminal aesthetics.
|
||||||
|
|
||||||
All modules are loaded natively via the `import` statement:
|
All modules are loaded natively via the `import` statement:
|
||||||
```aira
|
```aira
|
||||||
@@ -18,23 +18,28 @@ import "<module_name>";
|
|||||||
|
|
||||||
| # | Module | Category | Primary Purpose | Key Methods |
|
| # | Module | Category | Primary Purpose | Key Methods |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| 1 | [`ai`](./ai.md) | Artificial Intelligence | Universal LLM engine (OpenAI, DeepSeek, Claude, Gemini, Groq, Ollama, OpenRouter, etc.) | `ask()`, `set_provider()`, `set_endpoint()`, `set_key()`, `providers()` |
|
| 1 | [`serve`](./serve.md) / `server` | Web Backend | Native Micro Web Server for building REST APIs | `route()`, `get()`, `post()`, `start()` |
|
||||||
| 2 | [`system`](./system.md) / `hardware` | PC & Hardware Telemetry | Cross-platform GPU, CPU, RAM, battery, and OS hardware telemetry | `info()`, `gpu()`, `battery()`, `ram()`, `cpu()` |
|
| 2 | [`term`](./term.md) / `ui` | Terminal Aesthetics | ANSI colors, stylized boxes, ASCII data tables, braille spinners | `color()`, `rainbow()`, `box()`, `table()`, `spinner()`, `clear()` |
|
||||||
| 3 | [`android`](./android.md) / `droidsec` | Mobile Security & Recon | Android device integrity audit, root detection, and static APK security analyzer | `device_info()`, `audit_device()`, `audit_apk()`, `audit_package()`, `check_root()` |
|
| 3 | [`webhook`](./webhook.md) | Event Automation | Instant JSON webhook dispatcher and background listener | `send()`, `listen()` |
|
||||||
| 4 | [`sec`](./sec.md) | Cybersecurity | Port scanning, header auditing, subdomain discovery | `scan_ports()`, `audit_headers()`, `subdomains()`, `crack_md5()` |
|
| 4 | [`bot`](./bot.md) / `telegram` | Messaging Bots | Telegram Bot API and Discord webhook notifications | `telegram_send()`, `discord_send()` |
|
||||||
| 5 | [`proposal`](./proposal.md) | Fun & Cyber-Prank | Automated HTTP 500 love timeout & AI sentiment checker | `ask()`, `set_key()`, `set_system()`, `wish()`, `set_wish()` |
|
| 5 | [`env`](./env.md) / `dotenv` | Secrets & Config | `.env` file loader and environment variable manager | `load()`, `get()`, `set()`, `all()` |
|
||||||
| 6 | [`http`](./http.md) | Networking | Web requests, REST APIs, and file downloads | `get()`, `post()`, `download()`, `status()` |
|
| 6 | [`ai`](./ai.md) | Artificial Intelligence | Universal LLM engine (OpenAI, DeepSeek, Claude, Gemini, Groq, Ollama, OpenRouter, etc.) | `ask()`, `set_provider()`, `set_endpoint()`, `set_key()`, `providers()` |
|
||||||
| 7 | [`file`](./file.md) | System I/O | Read, write, append, and inspect local files | `read()`, `write()`, `append()`, `exists()`, `delete()` |
|
| 7 | [`sec`](./sec.md) | Cybersecurity | Port scanning, header auditing, subdomain recon, SSL inspection, DNS lookup | `scan_ports()`, `audit_headers()`, `subdomains()`, `ssl_check()`, `dns_lookup()`, `crack_md5()` |
|
||||||
| 8 | [`os`](./os.md) | System | Shell commands, environment variables, CLI args, directories | `cmd()`, `env()`, `cwd()`, `listdir()`, `mkdir()`, `args()`, `is_windows()` |
|
| 8 | [`crypto`](./crypto.md) | Security | Cryptographic hashes, JWT signing/verifying, UUIDs, Base64 | `jwt_sign()`, `jwt_verify()`, `uuid()`, `hmac()`, `sha256()`, `md5()`, `base64_encode()` |
|
||||||
| 9 | [`math`](./math.md) | Mathematics | Math functions, trigonometry, and constants | `sqrt()`, `pow()`, `abs()`, `random()`, `round()`, `pi`, `e` |
|
| 9 | [`system`](./system.md) / `hardware` | PC & Hardware Telemetry | Cross-platform GPU, CPU, RAM, battery, and OS hardware telemetry | `info()`, `gpu()`, `battery()`, `ram()`, `cpu()` |
|
||||||
| 10 | [`time`](./time.md) | System | Epoch time, timestamps, and execution delays | `now()`, `time()`, `sleep()` |
|
| 10 | [`android`](./android.md) / `droidsec` | Mobile Security & Recon | Android device integrity audit, root detection, and static APK security analyzer | `device_info()`, `audit_device()`, `audit_apk()`, `audit_package()`, `check_root()` |
|
||||||
| 11 | [`json`](./json.md) | Data | Parsing and serialization of JSON payloads | `parse()`, `stringify()`, `mkstring()` |
|
| 11 | [`proposal`](./proposal.md) | Fun & Cyber-Prank | Automated HTTP 500 love timeout & AI sentiment checker | `ask()`, `set_key()`, `set_system()`, `wish()`, `set_wish()` |
|
||||||
| 12 | [`crypto`](./crypto.md) | Security | Cryptographic hashes and encoding utilities | `md5()`, `sha256()`, `sha1()`, `base64_encode()`, `base64_decode()` |
|
| 12 | [`http`](./http.md) | Networking | Web requests, REST APIs, and file downloads | `get()`, `post()`, `download()`, `status()` |
|
||||||
| 13 | [`string`](./string.md) | Utilities | Advanced text manipulation and transformation | `split()`, `replace()`, `upper()`, `lower()`, `trim()`, `join()` |
|
| 13 | [`file`](./file.md) | System I/O | Read, write, append, and inspect local files | `read()`, `write()`, `append()`, `exists()`, `delete()` |
|
||||||
| 14 | [`sqlite`](./sqlite.md) | Database | Lightweight embedded SQL relational database | `open()`, `query()`, `execute()`, `close()` |
|
| 14 | [`os`](./os.md) | System | Shell commands, environment variables, CLI args, directories | `cmd()`, `env()`, `cwd()`, `listdir()`, `mkdir()`, `args()`, `is_windows()` |
|
||||||
| 15 | [`net`](./net.md) | Networking | Host pings, TCP port checks, and IP discovery | `ping()`, `port_open()`, `local_ip()`, `fetch()` |
|
| 15 | [`math`](./math.md) | Mathematics | Math functions, trigonometry, and constants | `sqrt()`, `pow()`, `abs()`, `random()`, `round()`, `pi`, `e` |
|
||||||
| 16 | [`thread`](./thread.md) | Concurrency | Thread spawning, worker pools, and parallel execution | `spawn()`, `join()`, `pool()`, `sleep()` |
|
| 16 | [`time`](./time.md) | System | Epoch time, timestamps, and execution delays | `now()`, `time()`, `sleep()` |
|
||||||
| 17 | [`youtube`](./youtube.md) / `yt` | Media & Video | YouTube video/audio download engine via APM with progressive stream resolution | `get()`, `stream()`, `download()`, `title`, `duration` |
|
| 17 | [`json`](./json.md) | Data | Parsing and serialization of JSON payloads | `parse()`, `stringify()`, `mkstring()` |
|
||||||
|
| 18 | [`string`](./string.md) | Utilities | Advanced text manipulation and transformation | `split()`, `replace()`, `upper()`, `lower()`, `trim()`, `join()` |
|
||||||
|
| 19 | [`sqlite`](./sqlite.md) | Database | Lightweight embedded SQL relational database | `open()`, `query()`, `execute()`, `close()` |
|
||||||
|
| 20 | [`net`](./net.md) | Networking | Host pings, TCP port checks, and IP discovery | `ping()`, `port_open()`, `local_ip()`, `fetch()` |
|
||||||
|
| 21 | [`thread`](./thread.md) | Concurrency | Thread spawning, worker pools, and parallel execution | `spawn()`, `join()`, `pool()`, `sleep()` |
|
||||||
|
| 22 | [`youtube`](./youtube.md) / `yt` | Media & Video | YouTube video/audio download engine via APM | `get()`, `stream()`, `download()`, `title`, `duration` |
|
||||||
|
|
||||||
---
|
---
|
||||||
*Maintained by the AiraLang Core Engineering Team. Created by Adam Eehan.*
|
*Maintained by the AiraLang Core Engineering Team. Created by Er. Adam Eehan.*
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 🤖 AiraLang Module: `bot`
|
||||||
|
|
||||||
|
The `bot` module provides 1-line notification and messaging integrations for Telegram and Discord bots.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 Functions
|
||||||
|
|
||||||
|
### 1. `bot.telegram_send(bot_token, chat_id, message, parse_mode="HTML")`
|
||||||
|
Sends a message via the official Telegram Bot API.
|
||||||
|
```airalang
|
||||||
|
import "bot";
|
||||||
|
|
||||||
|
let token = "123456:ABC-DEF...";
|
||||||
|
let chat = "987654321";
|
||||||
|
bot.telegram_send(token, chat, "<b>AiraLang Alert:</b> Port scan finished!");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. `bot.discord_send(webhook_url, content, username="Aira Bot", avatar_url=null)`
|
||||||
|
Dispatches an alert to a Discord channel via incoming webhook.
|
||||||
|
```airalang
|
||||||
|
bot.discord_send(
|
||||||
|
"https://discord.com/api/webhooks/...",
|
||||||
|
"Deployment completed on Vercel! 🚀",
|
||||||
|
username="Aira CI/CD"
|
||||||
|
);
|
||||||
|
```
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# 🛡️ AiraLang Module: `env`
|
||||||
|
|
||||||
|
The `env` module provides seamless `.env` file loading and secure environment variable access.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 Functions
|
||||||
|
|
||||||
|
### 1. `env.load(filepath=".env")`
|
||||||
|
Loads key-value pairs from a `.env` file into the environment. Returns `true` if loaded, `false` if file does not exist.
|
||||||
|
```airalang
|
||||||
|
import "env";
|
||||||
|
|
||||||
|
env.load(".env");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. `env.get(key, default=null)`
|
||||||
|
Retrieves an environment variable.
|
||||||
|
```airalang
|
||||||
|
let key = env.get("GEMINI_API_KEY", "default_key");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. `env.set(key, value)`
|
||||||
|
Sets an environment variable in the current process.
|
||||||
|
```airalang
|
||||||
|
env.set("APP_MODE", "development");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. `env.all()`
|
||||||
|
Returns a dictionary of all current environment variables.
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# 🌐 AiraLang Module: `serve`
|
||||||
|
|
||||||
|
The `serve` module provides a native, zero-dependency micro web server engine directly inside AiraLang. Build REST APIs, microservices, and webhook endpoints with minimal code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 Functions
|
||||||
|
|
||||||
|
### 1. `serve.route(path, handler_fn, method="GET")`
|
||||||
|
Registers a route endpoint. `handler_fn` receives a request dictionary containing `path`, `method`, `query`, `body`, and `headers`.
|
||||||
|
```airalang
|
||||||
|
import "serve";
|
||||||
|
|
||||||
|
serve.route("/api/hello", fn(req) {
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"message": "Hello from AiraLang Web Engine!",
|
||||||
|
"client_path": req["path"]
|
||||||
|
};
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. `serve.get(path, handler_fn)`
|
||||||
|
Shortcut to register a `GET` route.
|
||||||
|
```airalang
|
||||||
|
serve.get("/api/status", fn(req) {
|
||||||
|
return {"status": "online", "uptime": "100%"};
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. `serve.post(path, handler_fn)`
|
||||||
|
Shortcut to register a `POST` route.
|
||||||
|
```airalang
|
||||||
|
serve.post("/api/echo", fn(req) {
|
||||||
|
return {"received": req["body"]};
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. `serve.start(port=8080, host="0.0.0.0", background=false)`
|
||||||
|
Starts the HTTP server. If `background=true`, the server runs in a daemon thread so the script can continue executing.
|
||||||
|
```airalang
|
||||||
|
serve.start(port=8080);
|
||||||
|
```
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# 🎨 AiraLang Module: `term`
|
||||||
|
|
||||||
|
The `term` module provides native terminal styling, ANSI colors, ASCII bounding boxes, data tables, animated spinners, and screen controls for building high-aesthetic CLI and cyber reconnaissance tools.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 Functions
|
||||||
|
|
||||||
|
### 1. `term.color(color_name, text)`
|
||||||
|
Returns text formatted with the specified ANSI color.
|
||||||
|
* **Colors supported:** `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `bright_red`, `bright_green`, `bright_cyan`, `bold`, `dim`, `italic`, `underline`.
|
||||||
|
```airalang
|
||||||
|
import "term";
|
||||||
|
say term.color("green", "Audit Passed Successfully!");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. `term.rainbow(text)`
|
||||||
|
Returns text with alternating bright rainbow color grading.
|
||||||
|
```airalang
|
||||||
|
say term.rainbow("AIRALANG v1.5.0 - CYBER ENGINE");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. `term.box(title, content, color="cyan", width=50)`
|
||||||
|
Renders a stylized Unicode framed box in the terminal.
|
||||||
|
```airalang
|
||||||
|
term.box("SECURITY SCAN REPORT", [
|
||||||
|
"Target: google.com",
|
||||||
|
"Open Ports: 80, 443",
|
||||||
|
"Status: SECURE"
|
||||||
|
], "cyan");
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. `term.table(headers, rows)`
|
||||||
|
Renders structured tabular data in an ASCII grid table.
|
||||||
|
```airalang
|
||||||
|
term.table(["Port", "Service", "State"], [
|
||||||
|
["22", "SSH", "Open"],
|
||||||
|
["80", "HTTP", "Open"],
|
||||||
|
["443", "HTTPS", "Open"]
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. `term.spinner(message="Working...", seconds=1.5)`
|
||||||
|
Displays an asynchronous animated terminal braille spinner.
|
||||||
|
```airalang
|
||||||
|
term.spinner("Inspecting SSL certificate...", seconds=2);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. `term.clear()`
|
||||||
|
Clears the active terminal screen.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# ⚡ AiraLang Module: `webhook`
|
||||||
|
|
||||||
|
The `webhook` module enables instant event-driven webhook dispatching and lightweight background webhook receivers.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 Functions
|
||||||
|
|
||||||
|
### 1. `webhook.send(url, payload, headers=null, timeout=10)`
|
||||||
|
Sends an HTTP POST JSON payload to the target webhook URL.
|
||||||
|
```airalang
|
||||||
|
import "webhook";
|
||||||
|
|
||||||
|
let res = webhook.send("https://webhook.site/test", {
|
||||||
|
"event": "alert",
|
||||||
|
"user": "adam",
|
||||||
|
"timestamp": "2026-10-12"
|
||||||
|
});
|
||||||
|
say f"Webhook response status: {res['status']}";
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. `webhook.listen(port, callback_handler)`
|
||||||
|
Spins up a background HTTP webhook listener. Any incoming POST request payload is parsed and passed to `callback_handler`.
|
||||||
|
```airalang
|
||||||
|
webhook.listen(5000, fn(req) {
|
||||||
|
say f"Received webhook on {req['path']}: {req['body']}";
|
||||||
|
return {"status": "processed"};
|
||||||
|
});
|
||||||
|
```
|
||||||
@@ -182,3 +182,9 @@ class NamedArgNode(ASTNode):
|
|||||||
self.value = value
|
self.value = value
|
||||||
self.line = line
|
self.line = line
|
||||||
|
|
||||||
|
class FStringNode(ASTNode):
|
||||||
|
def __init__(self, parts, line):
|
||||||
|
self.parts = parts
|
||||||
|
self.line = line
|
||||||
|
|
||||||
|
|
||||||
+3
-2
@@ -26,7 +26,7 @@ from lexer import Lexer
|
|||||||
from parser import Parser
|
from parser import Parser
|
||||||
from evaluator import Evaluator
|
from evaluator import Evaluator
|
||||||
|
|
||||||
VERSION = "1.4.6 (Aira Package Manager & YouTube Edition)"
|
VERSION = "1.5.0 (Full-Stack Web, Cyber OSINT & F-Strings Edition)"
|
||||||
AUTHOR = "Adam Eehan (Aira Group of Technology)"
|
AUTHOR = "Adam Eehan (Aira Group of Technology)"
|
||||||
|
|
||||||
ASCII_BANNER = f"""\033[1;36m
|
ASCII_BANNER = f"""\033[1;36m
|
||||||
@@ -39,12 +39,13 @@ ASCII_BANNER = f"""\033[1;36m
|
|||||||
\033[0m\033[1;30m---------------------------------------------------\033[0m
|
\033[0m\033[1;30m---------------------------------------------------\033[0m
|
||||||
\033[1;32m[+]\033[0m \033[1;37mEngine:\033[0m AiraLang v{VERSION}
|
\033[1;32m[+]\033[0m \033[1;37mEngine:\033[0m AiraLang v{VERSION}
|
||||||
\033[1;34m[*]\033[0m \033[1;37mCreator:\033[0m {AUTHOR}
|
\033[1;34m[*]\033[0m \033[1;37mCreator:\033[0m {AUTHOR}
|
||||||
\033[1;35m[⚡]\033[0m \033[1;37mModules:\033[0m system, android, ai, sec, sqlite, net, crypto
|
\033[1;35m[⚡]\033[0m \033[1;37mModules:\033[0m serve, term, webhook, bot, env, sec, ai, crypto, sqlite
|
||||||
\033[1;33m[!]\033[0m Multiline support: open \033[1;32m{{\033[0m will continue on next line.
|
\033[1;33m[!]\033[0m Multiline support: open \033[1;32m{{\033[0m will continue on next line.
|
||||||
\033[1;33m[!]\033[0m Type \033[1;31m'exit'\033[0m or \033[1;31m'quit'\033[0m to close REPL.
|
\033[1;33m[!]\033[0m Type \033[1;31m'exit'\033[0m or \033[1;31m'quit'\033[0m to close REPL.
|
||||||
\033[1;30m---------------------------------------------------\033[0m
|
\033[1;30m---------------------------------------------------\033[0m
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def is_balanced(code):
|
def is_balanced(code):
|
||||||
in_single_quote = False
|
in_single_quote = False
|
||||||
in_double_quote = False
|
in_double_quote = False
|
||||||
|
|||||||
@@ -341,6 +341,17 @@ class Evaluator:
|
|||||||
elif nodetype == "LiteralNode":
|
elif nodetype == "LiteralNode":
|
||||||
return node.value
|
return node.value
|
||||||
|
|
||||||
|
elif nodetype == "FStringNode":
|
||||||
|
result_pieces = []
|
||||||
|
for is_expr, item in node.parts:
|
||||||
|
if is_expr:
|
||||||
|
val = self.eval_node(item, env)
|
||||||
|
result_pieces.append(str(val) if val is not None else "null")
|
||||||
|
else:
|
||||||
|
result_pieces.append(item)
|
||||||
|
return "".join(result_pieces)
|
||||||
|
|
||||||
|
|
||||||
elif nodetype == "IdentifierNode":
|
elif nodetype == "IdentifierNode":
|
||||||
return env.get(node.name, node.line)
|
return env.get(node.name, node.line)
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ TOKEN_TYPES = [
|
|||||||
("COMMENT", r"(#|//).*"),
|
("COMMENT", r"(#|//).*"),
|
||||||
("WHITESPACE", r"[ \t\r\n]+"),
|
("WHITESPACE", r"[ \t\r\n]+"),
|
||||||
("NUMBER", r"\d+(\.\d+)?"),
|
("NUMBER", r"\d+(\.\d+)?"),
|
||||||
|
("FSTRING", r'f("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
|
||||||
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
|
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
|
||||||
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
|
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
|
||||||
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
|
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
|
||||||
@@ -72,6 +73,10 @@ class Lexer:
|
|||||||
self.col = len(val) - val.rfind('\n')
|
self.col = len(val) - val.rfind('\n')
|
||||||
else:
|
else:
|
||||||
self.col += len(val)
|
self.col += len(val)
|
||||||
|
elif token_type == "FSTRING":
|
||||||
|
raw_str = val[2:-1].encode('utf-8').decode('unicode_escape')
|
||||||
|
self.tokens.append(Token("FSTRING", raw_str, self.line, self.col))
|
||||||
|
self.col += len(val)
|
||||||
elif token_type == "STRING":
|
elif token_type == "STRING":
|
||||||
raw_str = val[1:-1].encode('utf-8').decode('unicode_escape')
|
raw_str = val[1:-1].encode('utf-8').decode('unicode_escape')
|
||||||
self.tokens.append(Token("STRING", raw_str, self.line, self.col))
|
self.tokens.append(Token("STRING", raw_str, self.line, self.col))
|
||||||
|
|||||||
@@ -410,12 +410,63 @@ class Parser:
|
|||||||
break
|
break
|
||||||
return atom
|
return atom
|
||||||
|
|
||||||
|
def parse_fstring(self, tok):
|
||||||
|
from lexer import Lexer
|
||||||
|
raw_str = tok.value
|
||||||
|
line = tok.line
|
||||||
|
parts = []
|
||||||
|
i = 0
|
||||||
|
n = len(raw_str)
|
||||||
|
cur_text = []
|
||||||
|
while i < n:
|
||||||
|
if raw_str[i] == '{':
|
||||||
|
if i + 1 < n and raw_str[i+1] == '{':
|
||||||
|
cur_text.append('{')
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
if cur_text:
|
||||||
|
parts.append((False, "".join(cur_text)))
|
||||||
|
cur_text = []
|
||||||
|
i += 1
|
||||||
|
start = i
|
||||||
|
brace_count = 1
|
||||||
|
while i < n and brace_count > 0:
|
||||||
|
if raw_str[i] == '{':
|
||||||
|
brace_count += 1
|
||||||
|
elif raw_str[i] == '}':
|
||||||
|
brace_count -= 1
|
||||||
|
i += 1
|
||||||
|
if brace_count > 0:
|
||||||
|
raise SyntaxError(f"AiraLang SyntaxError: Unclosed '{{' in f-string at line {line}")
|
||||||
|
expr_str = raw_str[start:i-1].strip()
|
||||||
|
if expr_str:
|
||||||
|
sub_tokens = Lexer(expr_str).tokenize()
|
||||||
|
sub_parser = Parser(sub_tokens)
|
||||||
|
expr_ast = sub_parser.parse_expression()
|
||||||
|
parts.append((True, expr_ast))
|
||||||
|
elif raw_str[i] == '}':
|
||||||
|
if i + 1 < n and raw_str[i+1] == '}':
|
||||||
|
cur_text.append('}')
|
||||||
|
i += 2
|
||||||
|
continue
|
||||||
|
cur_text.append('}')
|
||||||
|
i += 1
|
||||||
|
else:
|
||||||
|
cur_text.append(raw_str[i])
|
||||||
|
i += 1
|
||||||
|
if cur_text:
|
||||||
|
parts.append((False, "".join(cur_text)))
|
||||||
|
return FStringNode(parts, line)
|
||||||
|
|
||||||
def parse_atom(self):
|
def parse_atom(self):
|
||||||
tok = self.current()
|
tok = self.current()
|
||||||
if self.match("NUMBER"):
|
if self.match("NUMBER"):
|
||||||
return LiteralNode(tok.value, "NUMBER", tok.line)
|
return LiteralNode(tok.value, "NUMBER", tok.line)
|
||||||
if self.match("STRING"):
|
if self.match("STRING"):
|
||||||
return LiteralNode(tok.value, "STRING", tok.line)
|
return LiteralNode(tok.value, "STRING", tok.line)
|
||||||
|
if self.match("FSTRING"):
|
||||||
|
return self.parse_fstring(tok)
|
||||||
|
|
||||||
if self.match("TRUE"):
|
if self.match("TRUE"):
|
||||||
return LiteralNode(True, "BOOLEAN", tok.line)
|
return LiteralNode(True, "BOOLEAN", tok.line)
|
||||||
if self.match("FALSE"):
|
if self.match("FALSE"):
|
||||||
|
|||||||
+404
-3
@@ -16,6 +16,10 @@ import struct
|
|||||||
import zipfile
|
import zipfile
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import ssl
|
||||||
|
import hmac
|
||||||
|
import uuid
|
||||||
|
import datetime
|
||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
class AiraModule:
|
class AiraModule:
|
||||||
@@ -344,6 +348,38 @@ def create_crypto_module():
|
|||||||
def b64decode(s):
|
def b64decode(s):
|
||||||
return base64.b64decode(str(s).encode('utf-8')).decode('utf-8')
|
return base64.b64decode(str(s).encode('utf-8')).decode('utf-8')
|
||||||
|
|
||||||
|
def hmac_sha256(key, message):
|
||||||
|
return hmac.new(str(key).encode('utf-8'), str(message).encode('utf-8'), hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
def uuid_str():
|
||||||
|
return str(uuid.uuid4())
|
||||||
|
|
||||||
|
def jwt_sign(payload, secret, alg="HS256"):
|
||||||
|
header = {"alg": alg, "typ": "JWT"}
|
||||||
|
h_json = json.dumps(header, separators=(',', ':')).encode('utf-8')
|
||||||
|
p_json = json.dumps(payload, separators=(',', ':')).encode('utf-8')
|
||||||
|
h_b64 = base64.urlsafe_b64encode(h_json).decode('utf-8').rstrip('=')
|
||||||
|
p_b64 = base64.urlsafe_b64encode(p_json).decode('utf-8').rstrip('=')
|
||||||
|
signing_input = f"{h_b64}.{p_b64}".encode('utf-8')
|
||||||
|
sig = hmac.new(str(secret).encode('utf-8'), signing_input, hashlib.sha256).digest()
|
||||||
|
sig_b64 = base64.urlsafe_b64encode(sig).decode('utf-8').rstrip('=')
|
||||||
|
return f"{h_b64}.{p_b64}.{sig_b64}"
|
||||||
|
|
||||||
|
def jwt_verify(token, secret):
|
||||||
|
parts = str(token).split('.')
|
||||||
|
if len(parts) != 3:
|
||||||
|
return {"valid": False, "error": "Invalid JWT format"}
|
||||||
|
h_b64, p_b64, sig_b64 = parts
|
||||||
|
signing_input = f"{h_b64}.{p_b64}".encode('utf-8')
|
||||||
|
expected_sig = hmac.new(str(secret).encode('utf-8'), signing_input, hashlib.sha256).digest()
|
||||||
|
pad = '=' * (-len(sig_b64) % 4)
|
||||||
|
actual_sig = base64.urlsafe_b64decode(sig_b64 + pad)
|
||||||
|
if not hmac.compare_digest(expected_sig, actual_sig):
|
||||||
|
return {"valid": False, "error": "Invalid signature"}
|
||||||
|
pad_p = '=' * (-len(p_b64) % 4)
|
||||||
|
payload_data = json.loads(base64.urlsafe_b64decode(p_b64 + pad_p).decode('utf-8'))
|
||||||
|
return {"valid": True, "payload": payload_data}
|
||||||
|
|
||||||
return AiraModule("crypto", {
|
return AiraModule("crypto", {
|
||||||
"md5": md5,
|
"md5": md5,
|
||||||
"sha256": sha256,
|
"sha256": sha256,
|
||||||
@@ -351,9 +387,14 @@ def create_crypto_module():
|
|||||||
"base64_encode": b64encode,
|
"base64_encode": b64encode,
|
||||||
"base64_decode": b64decode,
|
"base64_decode": b64decode,
|
||||||
"b64encode": b64encode,
|
"b64encode": b64encode,
|
||||||
"b64decode": b64decode
|
"b64decode": b64decode,
|
||||||
|
"hmac": hmac_sha256,
|
||||||
|
"uuid": uuid_str,
|
||||||
|
"jwt_sign": jwt_sign,
|
||||||
|
"jwt_verify": jwt_verify
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
def create_string_module():
|
def create_string_module():
|
||||||
return AiraModule("string", {
|
return AiraModule("string", {
|
||||||
"upper": lambda s: str(s).upper(),
|
"upper": lambda s: str(s).upper(),
|
||||||
@@ -1034,6 +1075,42 @@ def create_sec_module():
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return str(e)
|
return str(e)
|
||||||
|
|
||||||
|
def ssl_check(domain, port=443, timeout=5.0):
|
||||||
|
clean_dom = str(domain).replace("https://", "").replace("http://", "").split("/")[0].split(":")[0]
|
||||||
|
try:
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
with socket.create_connection((clean_dom, int(port)), timeout=float(timeout)) as sock:
|
||||||
|
with ctx.wrap_socket(sock, server_hostname=clean_dom) as ssock:
|
||||||
|
cert = ssock.getpeercert()
|
||||||
|
cipher = ssock.cipher()
|
||||||
|
version = ssock.version()
|
||||||
|
not_after = cert.get('notAfter')
|
||||||
|
expiry = datetime.datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z") if not_after else None
|
||||||
|
days_left = (expiry - datetime.datetime.utcnow()).days if expiry else None
|
||||||
|
issuer_dict = dict(x[0] for x in cert.get('issuer', []))
|
||||||
|
subject_dict = dict(x[0] for x in cert.get('subject', []))
|
||||||
|
return {
|
||||||
|
"domain": clean_dom,
|
||||||
|
"valid": days_left > 0 if days_left is not None else False,
|
||||||
|
"days_left": days_left,
|
||||||
|
"expires_on": not_after,
|
||||||
|
"tls_version": version,
|
||||||
|
"cipher": cipher[0] if cipher else None,
|
||||||
|
"issuer": issuer_dict.get('commonName', issuer_dict.get('organizationName', 'Unknown')),
|
||||||
|
"subject": subject_dict.get('commonName', 'Unknown')
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
return {"domain": clean_dom, "valid": False, "error": str(e)}
|
||||||
|
|
||||||
|
def dns_lookup(domain):
|
||||||
|
clean_dom = str(domain).replace("https://", "").replace("http://", "").split("/")[0]
|
||||||
|
try:
|
||||||
|
addr_info = socket.getaddrinfo(clean_dom, None)
|
||||||
|
ips = sorted(list(set(item[4][0] for item in addr_info)))
|
||||||
|
return {"domain": clean_dom, "ips": ips, "count": len(ips)}
|
||||||
|
except Exception as e:
|
||||||
|
return {"domain": clean_dom, "error": str(e), "ips": []}
|
||||||
|
|
||||||
return AiraModule("sec", {
|
return AiraModule("sec", {
|
||||||
"scan_port": scan_port,
|
"scan_port": scan_port,
|
||||||
"scan_ports": scan_ports,
|
"scan_ports": scan_ports,
|
||||||
@@ -1044,9 +1121,14 @@ def create_sec_module():
|
|||||||
"hash_identify": hash_identify,
|
"hash_identify": hash_identify,
|
||||||
"crack_md5": crack_md5,
|
"crack_md5": crack_md5,
|
||||||
"resolve": resolve,
|
"resolve": resolve,
|
||||||
"reverse_dns": reverse_dns
|
"reverse_dns": reverse_dns,
|
||||||
|
"ssl_check": ssl_check,
|
||||||
|
"ssl": ssl_check,
|
||||||
|
"dns_lookup": dns_lookup,
|
||||||
|
"dns": dns_lookup
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
def create_thread_module():
|
def create_thread_module():
|
||||||
def spawn(fn, args=None):
|
def spawn(fn, args=None):
|
||||||
if args is None:
|
if args is None:
|
||||||
@@ -1797,6 +1879,314 @@ def create_youtube_module():
|
|||||||
"download": quick_download
|
"download": quick_download
|
||||||
})
|
})
|
||||||
|
|
||||||
|
def create_term_module():
|
||||||
|
COLORS = {
|
||||||
|
"black": "\033[30m", "red": "\033[31m", "green": "\033[32m", "yellow": "\033[33m",
|
||||||
|
"blue": "\033[34m", "magenta": "\033[35m", "cyan": "\033[36m", "white": "\033[37m",
|
||||||
|
"bright_black": "\033[90m", "bright_red": "\033[91m", "bright_green": "\033[92m",
|
||||||
|
"bright_yellow": "\033[93m", "bright_blue": "\033[94m", "bright_magenta": "\033[95m",
|
||||||
|
"bright_cyan": "\033[96m", "bright_white": "\033[97m",
|
||||||
|
"bold": "\033[1m", "dim": "\033[2m", "italic": "\033[3m", "underline": "\033[4m",
|
||||||
|
"reset": "\033[0m"
|
||||||
|
}
|
||||||
|
|
||||||
|
def color(col_name, text):
|
||||||
|
c = COLORS.get(str(col_name).lower(), "")
|
||||||
|
return f"{c}{text}\033[0m"
|
||||||
|
|
||||||
|
def rainbow(text):
|
||||||
|
rainbow_colors = ["\033[91m", "\033[93m", "\033[92m", "\033[96m", "\033[94m", "\033[95m"]
|
||||||
|
res = []
|
||||||
|
for i, ch in enumerate(str(text)):
|
||||||
|
c = rainbow_colors[i % len(rainbow_colors)]
|
||||||
|
res.append(f"{c}{ch}")
|
||||||
|
res.append("\033[0m")
|
||||||
|
return "".join(res)
|
||||||
|
|
||||||
|
def box(title, content=None, color_name="cyan", width=50):
|
||||||
|
w = max(int(width), len(str(title)) + 6)
|
||||||
|
c = COLORS.get(str(color_name).lower(), "\033[36m")
|
||||||
|
reset = "\033[0m"
|
||||||
|
top = f"{c}┌{'─' * (w - 2)}┐{reset}"
|
||||||
|
title_line = f"{c}│{reset} {COLORS.get('bold', '')}{str(title).center(w - 4)}{reset} {c}│{reset}"
|
||||||
|
div = f"{c}├{'─' * (w - 2)}┤{reset}"
|
||||||
|
bot = f"{c}└{'─' * (w - 2)}┘{reset}"
|
||||||
|
lines = [top, title_line]
|
||||||
|
if content:
|
||||||
|
lines.append(div)
|
||||||
|
if isinstance(content, list):
|
||||||
|
for item in content:
|
||||||
|
item_str = str(item)
|
||||||
|
if len(item_str) > w - 4: item_str = item_str[:w-7] + "..."
|
||||||
|
lines.append(f"{c}│{reset} {item_str.ljust(w - 4)} {c}│{reset}")
|
||||||
|
else:
|
||||||
|
for line in str(content).splitlines():
|
||||||
|
if len(line) > w - 4: line = line[:w-7] + "..."
|
||||||
|
lines.append(f"{c}│{reset} {line.ljust(w - 4)} {c}│{reset}")
|
||||||
|
lines.append(bot)
|
||||||
|
res = "\n".join(lines)
|
||||||
|
print(res)
|
||||||
|
return res
|
||||||
|
|
||||||
|
def table(headers, rows):
|
||||||
|
headers = [str(h) for h in headers]
|
||||||
|
str_rows = [[str(cell) for cell in row] for row in rows]
|
||||||
|
col_widths = [len(h) for h in headers]
|
||||||
|
for row in str_rows:
|
||||||
|
for i, cell in enumerate(row):
|
||||||
|
if i < len(col_widths):
|
||||||
|
col_widths[i] = max(col_widths[i], len(cell))
|
||||||
|
else:
|
||||||
|
col_widths.append(len(cell))
|
||||||
|
sep = "┌" + "┬".join("─" * (w + 2) for w in col_widths) + "┐"
|
||||||
|
mid_sep = "├" + "┼".join("─" * (w + 2) for w in col_widths) + "┤"
|
||||||
|
bot_sep = "└" + "┴".join("─" * (w + 2) for w in col_widths) + "┘"
|
||||||
|
header_line = "│ " + " │ ".join(headers[i].ljust(col_widths[i]) for i in range(len(headers))) + " │"
|
||||||
|
lines = [sep, f"\033[1;36m{header_line}\033[0m", mid_sep]
|
||||||
|
for row in str_rows:
|
||||||
|
row_padded = [row[i].ljust(col_widths[i]) if i < len(row) else "".ljust(col_widths[i]) for i in range(len(col_widths))]
|
||||||
|
lines.append("│ " + " │ ".join(row_padded) + " │")
|
||||||
|
lines.append(bot_sep)
|
||||||
|
res = "\n".join(lines)
|
||||||
|
print(res)
|
||||||
|
return res
|
||||||
|
|
||||||
|
def spinner(message="Working...", seconds=1.5):
|
||||||
|
frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
|
||||||
|
end_time = time.time() + float(seconds)
|
||||||
|
i = 0
|
||||||
|
while time.time() < end_time:
|
||||||
|
frame = frames[i % len(frames)]
|
||||||
|
sys.stdout.write(f"\r\033[36m{frame}\033[0m {message}")
|
||||||
|
sys.stdout.flush()
|
||||||
|
time.sleep(0.08)
|
||||||
|
i += 1
|
||||||
|
sys.stdout.write(f"\r\033[32m✔\033[0m {message}\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def clear():
|
||||||
|
os.system('clear' if os.name != 'nt' else 'cls')
|
||||||
|
return True
|
||||||
|
|
||||||
|
return AiraModule("term", {
|
||||||
|
"color": color,
|
||||||
|
"rainbow": rainbow,
|
||||||
|
"box": box,
|
||||||
|
"table": table,
|
||||||
|
"spinner": spinner,
|
||||||
|
"clear": clear
|
||||||
|
})
|
||||||
|
|
||||||
|
def create_webhook_module():
|
||||||
|
def send(url, payload, headers=None, timeout=10.0):
|
||||||
|
if not isinstance(payload, (dict, list, str)):
|
||||||
|
payload = {"data": str(payload)}
|
||||||
|
body_data = json.dumps(payload).encode('utf-8') if not isinstance(payload, str) else payload.encode('utf-8')
|
||||||
|
req_headers = {"Content-Type": "application/json", "User-Agent": "AiraLang-Webhook/1.5.0"}
|
||||||
|
if isinstance(headers, dict):
|
||||||
|
req_headers.update(headers)
|
||||||
|
req = urllib.request.Request(str(url), data=body_data, headers=req_headers, method="POST")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=float(timeout)) as resp:
|
||||||
|
resp_text = resp.read().decode('utf-8')
|
||||||
|
try:
|
||||||
|
return {"status": resp.status, "data": json.loads(resp_text), "ok": True}
|
||||||
|
except:
|
||||||
|
return {"status": resp.status, "data": resp_text, "ok": True}
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return {"status": e.code, "error": str(e), "ok": False}
|
||||||
|
except Exception as e:
|
||||||
|
return {"status": 0, "error": str(e), "ok": False}
|
||||||
|
|
||||||
|
def listen(port, callback_handler):
|
||||||
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||||
|
class WebhookHandler(BaseHTTPRequestHandler):
|
||||||
|
def do_POST(self):
|
||||||
|
content_len = int(self.headers.get('Content-Length', 0))
|
||||||
|
post_body = self.rfile.read(content_len).decode('utf-8')
|
||||||
|
try:
|
||||||
|
data = json.loads(post_body)
|
||||||
|
except:
|
||||||
|
data = post_body
|
||||||
|
req_obj = {"body": data, "headers": dict(self.headers), "path": self.path}
|
||||||
|
if hasattr(callback_handler, 'call'):
|
||||||
|
res = callback_handler(req_obj)
|
||||||
|
elif callable(callback_handler):
|
||||||
|
res = callback_handler(req_obj)
|
||||||
|
else:
|
||||||
|
res = {"received": True}
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(json.dumps(res if isinstance(res, (dict, list)) else {"status": "ok"}).encode())
|
||||||
|
def log_message(self, format, *args):
|
||||||
|
pass
|
||||||
|
server = HTTPServer(('0.0.0.0', int(port)), WebhookHandler)
|
||||||
|
t = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
t.start()
|
||||||
|
return {"listening": True, "port": int(port)}
|
||||||
|
|
||||||
|
return AiraModule("webhook", {
|
||||||
|
"send": send,
|
||||||
|
"listen": listen
|
||||||
|
})
|
||||||
|
|
||||||
|
def create_bot_module():
|
||||||
|
def telegram_send(bot_token, chat_id, message, parse_mode="HTML"):
|
||||||
|
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
|
||||||
|
payload = {"chat_id": chat_id, "text": str(message), "parse_mode": parse_mode}
|
||||||
|
data = json.dumps(payload).encode('utf-8')
|
||||||
|
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||||
|
return json.loads(resp.read().decode('utf-8'))
|
||||||
|
except Exception as e:
|
||||||
|
return {"ok": False, "error": str(e)}
|
||||||
|
|
||||||
|
def discord_send(webhook_url, content, username="Aira Bot", avatar_url=None):
|
||||||
|
payload = {"content": str(content), "username": username}
|
||||||
|
if avatar_url:
|
||||||
|
payload["avatar_url"] = avatar_url
|
||||||
|
data = json.dumps(payload).encode('utf-8')
|
||||||
|
req = urllib.request.Request(str(webhook_url), data=data, headers={"Content-Type": "application/json", "User-Agent": "AiraLang-Bot/1.5.0"})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||||
|
return {"ok": True, "status": resp.status}
|
||||||
|
except Exception as e:
|
||||||
|
return {"ok": False, "error": str(e)}
|
||||||
|
|
||||||
|
return AiraModule("bot", {
|
||||||
|
"telegram_send": telegram_send,
|
||||||
|
"telegram": telegram_send,
|
||||||
|
"discord_send": discord_send,
|
||||||
|
"discord": discord_send
|
||||||
|
})
|
||||||
|
|
||||||
|
def create_env_module():
|
||||||
|
def load(filepath=".env"):
|
||||||
|
if not os.path.exists(filepath):
|
||||||
|
return False
|
||||||
|
with open(filepath, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#"):
|
||||||
|
continue
|
||||||
|
if "=" in line:
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
k = k.strip()
|
||||||
|
v = v.strip().strip('"').strip("'")
|
||||||
|
os.environ[k] = v
|
||||||
|
return True
|
||||||
|
|
||||||
|
def get_env(key, default=None):
|
||||||
|
return os.environ.get(str(key), default)
|
||||||
|
|
||||||
|
def set_env(key, value):
|
||||||
|
os.environ[str(key)] = str(value)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def all_env():
|
||||||
|
return dict(os.environ)
|
||||||
|
|
||||||
|
return AiraModule("env", {
|
||||||
|
"load": load,
|
||||||
|
"get": get_env,
|
||||||
|
"set": set_env,
|
||||||
|
"all": all_env
|
||||||
|
})
|
||||||
|
|
||||||
|
def create_serve_module():
|
||||||
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||||
|
routes = {}
|
||||||
|
|
||||||
|
def route(path, handler_fn, method="GET"):
|
||||||
|
routes[(str(method).upper(), str(path))] = handler_fn
|
||||||
|
return True
|
||||||
|
|
||||||
|
def get_route(path, handler_fn):
|
||||||
|
return route(path, handler_fn, "GET")
|
||||||
|
|
||||||
|
def post_route(path, handler_fn):
|
||||||
|
return route(path, handler_fn, "POST")
|
||||||
|
|
||||||
|
class AiraHttpServerHandler(BaseHTTPRequestHandler):
|
||||||
|
def _handle(self, method):
|
||||||
|
parsed = urllib.parse.urlparse(self.path)
|
||||||
|
clean_path = parsed.path
|
||||||
|
handler = routes.get((method, clean_path))
|
||||||
|
if not handler:
|
||||||
|
handler = routes.get(("*", clean_path))
|
||||||
|
if not handler:
|
||||||
|
self.send_response(404)
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(json.dumps({"error": "Not Found", "path": clean_path}).encode())
|
||||||
|
return
|
||||||
|
req_data = None
|
||||||
|
if method in ("POST", "PUT", "PATCH"):
|
||||||
|
length = int(self.headers.get('Content-Length', 0))
|
||||||
|
raw_body = self.rfile.read(length).decode('utf-8', errors='ignore')
|
||||||
|
try: req_data = json.loads(raw_body)
|
||||||
|
except: req_data = raw_body
|
||||||
|
query_params = dict(urllib.parse.parse_qsl(parsed.query))
|
||||||
|
req_obj = {
|
||||||
|
"path": clean_path,
|
||||||
|
"method": method,
|
||||||
|
"query": query_params,
|
||||||
|
"body": req_data,
|
||||||
|
"headers": dict(self.headers)
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
if callable(handler):
|
||||||
|
res = handler(req_obj)
|
||||||
|
else:
|
||||||
|
res = str(handler)
|
||||||
|
except Exception as e:
|
||||||
|
self.send_response(500)
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(json.dumps({"error": str(e)}).encode())
|
||||||
|
return
|
||||||
|
self.send_response(200)
|
||||||
|
if isinstance(res, (dict, list)):
|
||||||
|
self.send_header('Content-Type', 'application/json')
|
||||||
|
body_bytes = json.dumps(res).encode('utf-8')
|
||||||
|
elif isinstance(res, str) and (res.strip().startswith("<html") or res.strip().startswith("<!DOCTYPE")):
|
||||||
|
self.send_header('Content-Type', 'text/html')
|
||||||
|
body_bytes = res.encode('utf-8')
|
||||||
|
else:
|
||||||
|
self.send_header('Content-Type', 'text/plain')
|
||||||
|
body_bytes = str(res).encode('utf-8')
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body_bytes)
|
||||||
|
|
||||||
|
def do_GET(self): self._handle("GET")
|
||||||
|
def do_POST(self): self._handle("POST")
|
||||||
|
def do_PUT(self): self._handle("PUT")
|
||||||
|
def do_DELETE(self): self._handle("DELETE")
|
||||||
|
def log_message(self, format, *args): pass
|
||||||
|
|
||||||
|
def start(port=8080, host="0.0.0.0", background=False):
|
||||||
|
server = HTTPServer((str(host), int(port)), AiraHttpServerHandler)
|
||||||
|
print(f"\033[32m[AiraLang Serve]\033[0m HTTP Server running at http://{host}:{port}/")
|
||||||
|
if background:
|
||||||
|
t = threading.Thread(target=server.serve_forever, daemon=True)
|
||||||
|
t.start()
|
||||||
|
return {"running": True, "port": int(port)}
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
server.serve_forever()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print("\n[AiraLang Serve] Server stopped.")
|
||||||
|
|
||||||
|
return AiraModule("serve", {
|
||||||
|
"route": route,
|
||||||
|
"get": get_route,
|
||||||
|
"post": post_route,
|
||||||
|
"start": start
|
||||||
|
})
|
||||||
|
|
||||||
BUILTIN_MODULES = {
|
BUILTIN_MODULES = {
|
||||||
"file": create_file_module,
|
"file": create_file_module,
|
||||||
"os": create_os_module,
|
"os": create_os_module,
|
||||||
@@ -1817,6 +2207,17 @@ BUILTIN_MODULES = {
|
|||||||
"system": create_system_module,
|
"system": create_system_module,
|
||||||
"hardware": create_system_module,
|
"hardware": create_system_module,
|
||||||
"youtube": create_youtube_module,
|
"youtube": create_youtube_module,
|
||||||
"yt": create_youtube_module
|
"yt": create_youtube_module,
|
||||||
|
"term": create_term_module,
|
||||||
|
"ui": create_term_module,
|
||||||
|
"cli_ui": create_term_module,
|
||||||
|
"webhook": create_webhook_module,
|
||||||
|
"bot": create_bot_module,
|
||||||
|
"telegram": create_bot_module,
|
||||||
|
"env": create_env_module,
|
||||||
|
"dotenv": create_env_module,
|
||||||
|
"serve": create_serve_module,
|
||||||
|
"server": create_serve_module
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user