25 changed files with 324 additions and 237 deletions
-39
View File
@@ -74,60 +74,21 @@ export function useLoginForm({ onSubmitSuccess }: UseLoginFormProps = {}) {
setIsLoading(true)
console.log('Submitting login data:', formData)
// --- TODO: Replace with actual API call to your RageMP server ---
try {
// Example: Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000))
// Assuming API returns success:
console.log('Login successful!')
// Here you would typically receive a token or session info
// Handle 'saveLogin' and 'savePassword' (e.g., using localStorage/sessionStorage)
if (formData.saveLogin) {
localStorage.setItem('savedUsername', formData.identifier) // Example
} else {
localStorage.removeItem('savedUsername') // Example
}
// Password saving is generally discouraged for security reasons,
// but if required:
if (formData.savePassword) {
// Be VERY careful with storing passwords. Consider secure storage or tokens.
// localStorage.setItem('savedPassword', formData.password); // **Highly discouraged**
console.warn(
'Password saving enabled - ensure secure storage mechanism.',
)
}
setErrors({}) // Clear errors on success
if (onSubmitSuccess) {
onSubmitSuccess(formData) // Call success callback
}
// You might redirect the user or update application state here
// --- Mock Error Handling (remove in real implementation) ---
// if (formData.identifier === 'wrong') {
// throw new Error("Invalid credentials.");
// }
// --- End Mock Error Handling ---
} catch (apiError: unknown) {
console.error('Login API error:', apiError)
setSubmitError('Login failed. Please check your credentials.')
} finally {
setIsLoading(false)
}
// --- End API call section ---
},
[formData, validateForm, onSubmitSuccess],
)
// Effect to potentially load saved username on initial render (example)
// useEffect(() => {
// const savedUser = localStorage.getItem('savedUsername');
// if (savedUser) {
// setFormData(prev => ({ ...prev, identifier: savedUser, saveLogin: true }));
// }
// }, []);
return {
formData,
errors,
-14
View File
@@ -74,13 +74,7 @@ export function useRegisterForm({
setIsLoading(true)
console.log('Submitting registration data:', formData)
// --- TODO: Replace with actual API call to your RageMP server ---
try {
// Example: Simulate API call
await new Promise(resolve => setTimeout(resolve, 1500))
// Assuming API returns success:
console.log('Registration successful!')
setFormData({
username: '',
email: '',
@@ -92,20 +86,12 @@ export function useRegisterForm({
if (onSubmitSuccess) {
onSubmitSuccess(formData) // Call success callback if provided
}
// --- Mock Error Handling (remove in real implementation) ---
// if (formData.email.includes('fail')) {
// throw new Error("Registration failed: Email already exists.");
// }
// --- End Mock Error Handling ---
} catch (apiError: unknown) {
console.error('Registration API error:', apiError)
// Try to set a user-friendly error message
setSubmitError('Registration failed. Please try again.')
} finally {
setIsLoading(false)
}
// --- End API call section ---
},
[formData, validateForm, onSubmitSuccess],
)
@@ -1,4 +1,8 @@
import React from 'react'
import { fw } from '@entityseven/rage-fw-browser'
import { AuthEvent } from '../../../../shared/events'
import Input from '../../components/ui/Input'
import Checkbox from '../../components/ui/Checkbox'
import Button from '../../components/ui/Button'
@@ -6,10 +10,17 @@ import { useLoginForm } from '../../hooks/useLoginForm'
import { LoginFormData } from '../../validation'
const LoginPage: React.FC = () => {
const handleLoginSuccess = (data: LoginFormData) => {
console.log('Login success callback triggered:', data)
// Redirect user or update app state
alert(`Login successful for ${data.identifier}!`)
const handleLoginSuccess = async (data: LoginFormData) => {
const tempData = {
login: data.identifier,
password: data.password,
}
const response = await fw.event.triggerServer(AuthEvent.LOGIN, [
tempData,
])
console.log(response)
}
const {
@@ -56,13 +67,13 @@ const LoginPage: React.FC = () => {
<div className="rounded-md shadow-sm -space-y-px">
<Input
label="Email or Username"
label="Username"
id="identifier"
name="identifier"
type="text" // Use text to allow both email and username
autoComplete="username" // Browsers often use 'username' for this field
required
placeholder="Email address or Username"
placeholder="Username"
value={formData.identifier}
onChange={handleChange}
error={errors.identifier}
@@ -1,14 +1,27 @@
import React from 'react'
import { fw } from '@entityseven/rage-fw-browser'
import { AuthEvent } from '../../../../shared/events'
import Input from '../../components/ui/Input'
import Button from '../../components/ui/Button'
import { useRegisterForm } from '../../hooks/useRegisterForm'
import { RegisterFormData } from '../../validation'
const RegisterPage: React.FC = () => {
const handleRegistrationSuccess = (data: RegisterFormData) => {
console.log('Registration success callback triggered:', data)
// Maybe show a success message or redirect
alert(`Registration successful for ${data.username}!`)
const handleRegistrationSuccess = async (data: RegisterFormData) => {
const tempData = {
login: data.username,
password: data.password,
email: data.email,
}
const response = await fw.event.triggerServer(AuthEvent.REGISTER, [
tempData,
])
console.log(response)
}
const {
+1 -1
View File
@@ -1,3 +1,3 @@
import { fw } from '@entityseven/rage-fw-client'
fw.player.browser = mp.browsers.new('https://localhost:5173')
fw.player.browser = mp.browsers.new('package://cef/index.html')
+5
View File
@@ -0,0 +1,5 @@
POSTGRES_USER="postgres"
POSTGRES_PASSWORD="mypassword"
POSTGRES_DB="postgres"
DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}"
+20
View File
@@ -0,0 +1,20 @@
services:
database:
image: postgres:17
ports:
- "5432:5432"
healthcheck:
test:
[ "CMD", "pg_isready", "-U", "${POSTGRES_USER}", "-d", "${POSTGRES_DB}" ]
interval: 5s
timeout: 10s
retries: 5
environment:
- POSTGRES_PASSWORD
- POSTGRES_USER
- POSTGRES_DB
volumes:
- rage_fw_db_data:/var/lib/postgresql/data
volumes:
rage_fw_db_data:
+15
View File
@@ -0,0 +1,15 @@
import 'dotenv/config'
import { defineConfig } from 'drizzle-kit'
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'postgresql',
dbCredentials: {
user: process.env.POSTGRES_USER!,
password: process.env.POSTGRES_PASSWORD!,
database: process.env.POSTGRES_DB!,
host: 'localhost',
ssl: false,
},
})
@@ -0,0 +1,10 @@
CREATE TABLE "users" (
"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "users_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1),
"socialClub" varchar(255) NOT NULL,
"email" varchar(255) NOT NULL,
"login" varchar(255) NOT NULL,
"password" varchar(255) NOT NULL,
CONSTRAINT "users_socialClub_unique" UNIQUE("socialClub"),
CONSTRAINT "users_email_unique" UNIQUE("email"),
CONSTRAINT "users_login_unique" UNIQUE("login")
);
@@ -0,0 +1,95 @@
{
"id": "690592ed-01d9-40ee-91c5-45e2ed38926b",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.users": {
"name": "users",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"identity": {
"type": "always",
"name": "users_id_seq",
"schema": "public",
"increment": "1",
"startWith": "1",
"minValue": "1",
"maxValue": "2147483647",
"cache": "1",
"cycle": false
}
},
"socialClub": {
"name": "socialClub",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"login": {
"name": "login",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"password": {
"name": "password",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"users_socialClub_unique": {
"name": "users_socialClub_unique",
"nullsNotDistinct": false,
"columns": [
"socialClub"
]
},
"users_email_unique": {
"name": "users_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
},
"users_login_unique": {
"name": "users_login_unique",
"nullsNotDistinct": false,
"columns": [
"login"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1744901803714,
"tag": "0000_burly_jubilee",
"breakpoints": true
}
]
}
+11 -1
View File
@@ -8,6 +8,16 @@
"build": "esbuild src/index.ts --bundle --platform=node --target=node14.10 --format=cjs --outfile=../../server/packages/server/index.js"
},
"dependencies": {
"@entityseven/rage-fw-server": "latest"
"@entityseven/rage-fw-server": "latest",
"dotenv": "^16.5.0",
"drizzle-orm": "^0.42.0",
"md5": "^2.3.0",
"pg": "^8.14.1"
},
"devDependencies": {
"@types/pg": "^8.11.13",
"drizzle-kit": "^0.31.0",
"tsx": "^4.19.3",
"@types/md5": "^2.3.5"
}
}
-58
View File
@@ -1,58 +0,0 @@
/**
* Calculates Pi using the Leibniz formula for a given number of iterations.
* (Identical logic to the AssemblyScript version)
* @param iterations Number of terms in the series.
* @returns Approximate value of Pi.
*/
export function calculatePiLeibnizTs(iterations: number): number {
let pi_div_4: number = 0.0
let sign: number = 1.0
for (let i: number = 0; i < iterations; i++) {
let term = sign / (2.0 * i + 1.0)
pi_div_4 += term
sign = -sign // Flip the sign
}
return pi_div_4 * 4.0
}
/**
* Helper function to check if a number is prime (Trial Division).
* (Identical logic to the AssemblyScript version)
* @param num The number to check.
* @returns True if prime, false otherwise.
*/
function isPrimeTs(num: number): boolean {
if (num <= 1) return false
if (num <= 3) return true
if (num % 2 == 0 || num % 3 == 0) return false
// Only need to check up to sqrt(num)
// Optimized loop: check 6k ± 1
for (let i: number = 5; i * i <= num; i = i + 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return false
}
}
return true
}
/**
* Counts prime numbers up to a given limit using trial division.
* (Identical logic to the AssemblyScript version)
* @param limit The upper bound (exclusive) to search for primes.
* @returns The count of prime numbers found.
*/
export function countPrimesTs(limit: number): number {
let count: number = 0
for (let i: number = 2; i < limit; i++) {
if (isPrimeTs(i)) {
count++
}
}
return count
}
export function addTs(a: number, b: number): number {
return a + b
}
+6
View File
@@ -0,0 +1,6 @@
import 'dotenv/config'
import { drizzle } from 'drizzle-orm/node-postgres'
const connUrl = `postgres://${process.env.POSTGRES_USER}:${process.env.POSTGRES_PASSWORD}@localhost:5432/${process.env.POSTGRES_DB}`
export const db = drizzle(connUrl)
+9
View File
@@ -0,0 +1,9 @@
import { integer, pgTable, varchar } from 'drizzle-orm/pg-core'
export const usersTable = pgTable('users', {
id: integer().primaryKey().generatedAlwaysAsIdentity(),
socialClub: varchar({ length: 255 }).notNull().unique(),
email: varchar({ length: 255 }).notNull().unique(),
login: varchar({ length: 255 }).notNull().unique(),
password: varchar({ length: 255 }).notNull(),
})
+74 -60
View File
@@ -1,71 +1,85 @@
import { InitWasm } from './wasm'
import { addTs, calculatePiLeibnizTs, countPrimesTs } from './benchmark'
import { fw } from '@entityseven/rage-fw-server'
import { AuthEvent } from '@shared/events'
import { performance } from 'perf_hooks'
/**
* Runs a function, measures its execution time, and prints the result.
* @param name Name of the benchmark.
* @param func The function to execute.
* @param args Arguments to pass to the function.
*/
function runBenchmark(
name: string,
func: (...args: any[]) => any,
...args: any[]
) {
console.log(`\nRunning benchmark: ${name}`)
console.log(`Arguments: ${args.join(', ')}`)
import md5 from 'md5'
const startTime = performance.now()
const result = func(...args)
const endTime = performance.now()
const duration = endTime - startTime
import { eq, or } from 'drizzle-orm'
console.log(`Result: ${result}`)
console.log(`Execution Time: ${duration.toFixed(3)} ms`)
return duration
}
import { usersTable } from './db/schema'
import { db } from './db'
// --- Benchmark Parameters ---
const PI_ITERATIONS = 100_000_000_000 // High number for Pi calculation
const PRIME_LIMIT = 100_000_000 // Limit for prime counting
// --- End Benchmark Parameters ---
fw.event.register(AuthEvent.REGISTER, async (player, [data]) => {
const { login, email, password } = data
InitWasm().then(wasm => {
// Verify AS module loaded
const sumAs = wasm.addAs(5, 7)
console.log(`AS Module Loaded Verification (addAs(5, 7)): ${sumAs}`)
if (sumAs !== 12) {
console.warn('AS addAs function did not return expected result!')
const normalizedEmail = email.toLowerCase()
const normalizedLogin = login.toLowerCase()
try {
const existingUser = await db
.select()
.from(usersTable)
.where(
or(
eq(usersTable.login, normalizedLogin),
eq(usersTable.email, normalizedEmail),
eq(usersTable.socialClub, player.socialClub),
),
)
if (existingUser.length > 0) {
return 'User already exists'
}
const sumTs = addTs(5, 7)
console.log(`TS Implementation Verification (addTs(5, 7)): ${sumTs}`)
// --- Run Benchmarks ---
const user: typeof usersTable.$inferInsert = {
socialClub: player.socialClub,
password: md5(password), // we can use md5 for simplicity, but in production you should use more secure hashing algorithms
email: normalizedEmail,
login: normalizedLogin,
}
// Benchmark: Calculate Pi
runBenchmark(
'TypeScript: Calculate Pi (Leibniz)',
calculatePiLeibnizTs,
PI_ITERATIONS,
)
runBenchmark(
'AssemblyScript: Calculate Pi (Leibniz)',
wasm.calculatePiLeibnizAs,
PI_ITERATIONS,
)
await db.insert(usersTable).values(user)
} catch (e) {
console.log(e)
return 'Something went wrong'
}
// Benchmark: Count Primes
runBenchmark(
'TypeScript: Count Primes (Trial Division)',
countPrimesTs,
PRIME_LIMIT,
)
runBenchmark(
'AssemblyScript: Count Primes (Trial Division)',
wasm.countPrimesAs,
PRIME_LIMIT,
)
console.log('User registered:', player.socialClub)
console.log('\nBenchmark finished.')
return 'User created successfully'
})
fw.event.register(AuthEvent.LOGIN, async (player, [data]) => {
const { login, password } = data
const normalizedLogin = login.toLowerCase()
console.log('Login data', data)
try {
const users = await db
.select()
.from(usersTable)
.where(eq(usersTable.login, normalizedLogin))
if (users.length === 0) {
return 'Invalid credentials'
}
const user = users[0]
if (user.password !== md5(password)) {
return 'Invalid credentials'
}
if (user.socialClub !== player.socialClub) {
return 'Invalid credentials'
}
console.log('User logged in:', user, player.socialClub)
// Auth success
return 'Login successful'
} catch (e) {
console.error('Login error:', e)
return 'Internal server error'
}
})
-21
View File
@@ -1,21 +0,0 @@
import { __AdaptedExports, instantiate } from './release'
import * as path from 'node:path'
import * as fs from 'node:fs/promises'
export async function InitWasm(): Promise<typeof __AdaptedExports> {
return new Promise(async resolve => {
const wasmFilePath = path.resolve(__dirname, 'release.wasm')
const wasm: typeof __AdaptedExports = await instantiate(
await (async () => {
return globalThis.WebAssembly.compile(
await fs.readFile(wasmFilePath),
)
})(),
{ env: '' },
)
resolve(wasm)
})
}
-24
View File
@@ -1,24 +0,0 @@
declare namespace __AdaptedExports {
/**
* assembly/index/calculatePiLeibnizAs
* @param iterations `i32`
* @returns `f64`
*/
export function calculatePiLeibnizAs(iterations: number): number;
/**
* assembly/index/countPrimesAs
* @param limit `i32`
* @returns `i32`
*/
export function countPrimesAs(limit: number): number;
/**
* assembly/index/addAs
* @param a `i32`
* @param b `i32`
* @returns `i32`
*/
export function addAs(a: number, b: number): number;
}
/** Instantiates the compiled WebAssembly module with the given imports. */
export declare function instantiate(module: WebAssembly.Module, imports: {
}): Promise<typeof __AdaptedExports>;
-4
View File
@@ -1,4 +0,0 @@
export async function instantiate(module, imports = {}) {
const { exports } = await WebAssembly.instantiate(module, imports);
return exports;
}
+8 -1
View File
@@ -1,10 +1,17 @@
import { AuthEvent } from '../../events'
declare module '@entityseven/rage-fw-shared-types' {
export interface RageFW_ICustomClientEvent {
customClientEvent(greetings: string): string
}
export interface RageFW_ICustomServerEvent {
customServerEvent(greetings: string): string
[AuthEvent.LOGIN](data: { login: string; password: string }): string
[AuthEvent.REGISTER](data: {
login: string
email: string
password: string
}): string
}
export interface RageFW_ICustomBrowserEvent {
+4
View File
@@ -0,0 +1,4 @@
export enum AuthEvent {
LOGIN = 'AuthEvent::LOGIN',
REGISTER = 'AuthEvent::REGISTER',
}
+7
View File
@@ -0,0 +1,7 @@
{
"name": "@shared",
"version": "0.1.0",
"author": "Entity Seven Group",
"license": "CC BY-ND",
"description": "Shared types for rage-fw example"
}
+5 -2
View File
@@ -1,7 +1,9 @@
{
"name": "framework-example",
"description": "This project is example of RAGE FW usage.",
"workspaces": ["apps/*"],
"workspaces": [
"apps/*"
],
"scripts": {
"server:update": "cd server && rage-win64.exe",
"build:client": "cd apps/client && pnpm build",
@@ -20,5 +22,6 @@
},
"author": "Entity Seven Group",
"license": "MIT",
"version": "0.1.0"
"version": "0.1.0",
"packageManager": "[email protected]+sha512.398035c7bd696d0ba0b10a688ed558285329d27ea994804a52bad9167d8e3a72bcb993f9699585d3ca25779ac64949ef422757a6c31102c12ab932e5cbe5cc92"
}
+5
View File
@@ -0,0 +1,5 @@
POSTGRES_USER="postgres"
POSTGRES_PASSWORD="mypassword"
POSTGRES_DB="postgres"
DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}"
Binary file not shown.