Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# `@gabriel20xx/design-tokens`
|
||||
|
||||
The package exports `theme.css`. Import it directly when an application needs only the shared tokens, or use `@gabriel20xx/web-ui/styles.css`, which imports it automatically.
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@gabriel20xx/design-tokens",
|
||||
"version": "0.1.0",
|
||||
"description": "Shared visual tokens for Gabriel20xx web projects.",
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"theme.css",
|
||||
"README.md"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"default": "./theme.css"
|
||||
},
|
||||
"./theme.css": "./theme.css",
|
||||
"./package.json": "./package.json"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
:root,
|
||||
[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
--sc-bg: #0b1020;
|
||||
--sc-surface: #121a2d;
|
||||
--sc-surface-raised: #18233b;
|
||||
--sc-surface-hover: #202d49;
|
||||
--sc-border: #2d3b59;
|
||||
--sc-border-strong: #405273;
|
||||
--sc-fg: #f4f7fb;
|
||||
--sc-muted-fg: #a8b4c7;
|
||||
--sc-subtle-fg: #74839d;
|
||||
--sc-primary: #7c9cff;
|
||||
--sc-primary-hover: #94adff;
|
||||
--sc-primary-fg: #081127;
|
||||
--sc-secondary: #253452;
|
||||
--sc-secondary-hover: #304363;
|
||||
--sc-secondary-fg: #e8eefb;
|
||||
--sc-accent: #61d5c7;
|
||||
--sc-accent-fg: #06201d;
|
||||
--sc-danger: #ef767a;
|
||||
--sc-danger-hover: #f58d90;
|
||||
--sc-danger-fg: #2d0809;
|
||||
--sc-success: #70d69d;
|
||||
--sc-success-fg: #062012;
|
||||
--sc-warning: #f3c969;
|
||||
--sc-warning-fg: #241a02;
|
||||
--sc-ring: #9fb4ff;
|
||||
--sc-backdrop: rgb(2 6 23 / 72%);
|
||||
--sc-radius-sm: 0.375rem;
|
||||
--sc-radius-md: 0.625rem;
|
||||
--sc-radius-lg: 0.875rem;
|
||||
--sc-radius-xl: 1.125rem;
|
||||
--sc-font-sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--sc-font-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
|
||||
--sc-shadow-sm: 0 2px 8px rgb(0 0 0 / 14%);
|
||||
--sc-shadow-lg: 0 20px 60px rgb(0 0 0 / 32%);
|
||||
}
|
||||
|
||||
[data-theme='light'] {
|
||||
color-scheme: light;
|
||||
--sc-bg: #f5f7fb;
|
||||
--sc-surface: #ffffff;
|
||||
--sc-surface-raised: #ffffff;
|
||||
--sc-surface-hover: #eef2f8;
|
||||
--sc-border: #d7deea;
|
||||
--sc-border-strong: #b7c2d4;
|
||||
--sc-fg: #172033;
|
||||
--sc-muted-fg: #53627a;
|
||||
--sc-subtle-fg: #74839d;
|
||||
--sc-primary: #466ee8;
|
||||
--sc-primary-hover: #345bd4;
|
||||
--sc-primary-fg: #ffffff;
|
||||
--sc-secondary: #e7edf8;
|
||||
--sc-secondary-hover: #dbe4f3;
|
||||
--sc-secondary-fg: #1d2b44;
|
||||
--sc-accent: #168f83;
|
||||
--sc-accent-fg: #ffffff;
|
||||
--sc-danger: #cf3d45;
|
||||
--sc-danger-hover: #b93139;
|
||||
--sc-danger-fg: #ffffff;
|
||||
--sc-success: #208751;
|
||||
--sc-success-fg: #ffffff;
|
||||
--sc-warning: #a66e00;
|
||||
--sc-warning-fg: #ffffff;
|
||||
--sc-ring: #466ee8;
|
||||
--sc-backdrop: rgb(15 23 42 / 42%);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# `@gabriel20xx/node-backend`
|
||||
|
||||
Shared Node.js backend infrastructure for services that use PostgreSQL:
|
||||
|
||||
- validated `DATABASE_URL` and pool settings;
|
||||
- one pool owner with startup retry, transient query retry, transactions, and shutdown;
|
||||
- PBKDF2 password hashing and secure session-token helpers;
|
||||
- common account/session persistence;
|
||||
- transaction-locked ordered migrations.
|
||||
|
||||
The package does not depend on Express. Each service keeps its own routes,
|
||||
cookies, roles, validation policy, and domain repositories. Existing
|
||||
`MediaShared` code can be migrated into this package incrementally; keep the
|
||||
legacy package as a compatibility layer until every consumer has moved.
|
||||
|
||||
Pass a service-specific `tableName` to `runMigrations` when multiple services
|
||||
share one PostgreSQL database, so their migration histories cannot collide.
|
||||
|
||||
Run `npm test` from this package or `npm run test --workspace=@gabriel20xx/node-backend` from `SharedCode`.
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@gabriel20xx/node-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "Shared PostgreSQL, configuration, migration, and authentication primitives for Node.js services.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"src",
|
||||
"test",
|
||||
"README.md"
|
||||
],
|
||||
"exports": {
|
||||
".": "./src/index.js",
|
||||
"./config": "./src/config.js",
|
||||
"./db": "./src/db.js",
|
||||
"./auth": "./src/auth.js",
|
||||
"./migrate": "./src/migrate.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"pg": "^8.17.2"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const PASSWORD_ITERATIONS = 100000;
|
||||
const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
|
||||
export const AUTH_SCHEMA = `
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||
`;
|
||||
|
||||
export function hashPassword(password, { iterations = PASSWORD_ITERATIONS } = {}) {
|
||||
if (typeof password !== 'string' || password.length < 8) {
|
||||
throw new Error('Password must be at least 8 characters');
|
||||
}
|
||||
const salt = crypto.randomBytes(16).toString('hex');
|
||||
const hash = crypto.pbkdf2Sync(password, salt, iterations, PASSWORD_KEY_LENGTH, PASSWORD_DIGEST);
|
||||
return `${salt}:${hash.toString('hex')}`;
|
||||
}
|
||||
|
||||
export function verifyPassword(password, stored) {
|
||||
try {
|
||||
const [salt, expected] = String(stored).split(':');
|
||||
if (!salt || !expected) return false;
|
||||
const actual = crypto.pbkdf2Sync(
|
||||
String(password),
|
||||
salt,
|
||||
PASSWORD_ITERATIONS,
|
||||
PASSWORD_KEY_LENGTH,
|
||||
PASSWORD_DIGEST
|
||||
);
|
||||
const expectedBytes = Buffer.from(expected, 'hex');
|
||||
return expectedBytes.length === actual.length && crypto.timingSafeEqual(expectedBytes, actual);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function createSessionToken() {
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
return { token, tokenHash: hashToken(token) };
|
||||
}
|
||||
|
||||
export function hashToken(token) {
|
||||
return crypto.createHash('sha256').update(String(token)).digest('hex');
|
||||
}
|
||||
|
||||
/** Persistence-only auth store; cookies, roles, and HTTP policy stay in the app. */
|
||||
export class AuthStore {
|
||||
constructor(database, { singleUser = true } = {}) {
|
||||
if (!database || typeof database.query !== 'function') {
|
||||
throw new TypeError('AuthStore requires a Database-like query object');
|
||||
}
|
||||
this.database = database;
|
||||
this.singleUser = singleUser;
|
||||
}
|
||||
|
||||
async ensureSchema() {
|
||||
await this.database.query(AUTH_SCHEMA);
|
||||
if (this.singleUser) {
|
||||
await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))');
|
||||
}
|
||||
}
|
||||
|
||||
async countUsers() {
|
||||
const result = await this.database.query('SELECT count(*)::int AS count FROM auth_users');
|
||||
return result.rows[0].count;
|
||||
}
|
||||
|
||||
async createUser(username, email, passwordHash) {
|
||||
try {
|
||||
const result = await this.database.query(
|
||||
`INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at`,
|
||||
[username, email, passwordHash]
|
||||
);
|
||||
return result.rows[0];
|
||||
} catch (error) {
|
||||
if (error?.code === '23505') {
|
||||
const duplicate = new Error('auth user already exists');
|
||||
duplicate.code = 'AUTH_USER_EXISTS';
|
||||
throw duplicate;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async findByIdentifier(identifier) {
|
||||
const result = await this.database.query(
|
||||
`SELECT id, username, email, password_hash, created_at, updated_at
|
||||
FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`,
|
||||
[identifier]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async updateCredentials(id, username, email, passwordHash) {
|
||||
await this.database.query(
|
||||
`UPDATE auth_users SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4`,
|
||||
[username, email, passwordHash, id]
|
||||
);
|
||||
}
|
||||
|
||||
async createSession(userId, tokenHash, expiresAt) {
|
||||
await this.database.query(
|
||||
'INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)',
|
||||
[userId, tokenHash, expiresAt]
|
||||
);
|
||||
}
|
||||
|
||||
async findSessionUser(tokenHash) {
|
||||
const result = await this.database.query(
|
||||
`SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()`,
|
||||
[tokenHash]
|
||||
);
|
||||
return result.rows[0] || null;
|
||||
}
|
||||
|
||||
async deleteSession(tokenHash) {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE token_hash = $1', [tokenHash]);
|
||||
}
|
||||
|
||||
async deleteSessionsForUser(userId) {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE user_id = $1', [userId]);
|
||||
}
|
||||
|
||||
async pruneExpiredSessions() {
|
||||
await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
const DEFAULTS = Object.freeze({
|
||||
max: 20,
|
||||
min: 0,
|
||||
connectionTimeoutMillis: 5000,
|
||||
idleTimeoutMillis: 30000,
|
||||
queryTimeout: 15000,
|
||||
});
|
||||
|
||||
function positiveInt(value, fallback, minimum = 0) {
|
||||
const parsed = Number.parseInt(String(value ?? ''), 10);
|
||||
return Number.isInteger(parsed) && parsed >= minimum ? parsed : fallback;
|
||||
}
|
||||
|
||||
/** Return DATABASE_URL or throw an actionable startup error. */
|
||||
export function databaseUrlFromEnv(env = process.env) {
|
||||
const url = String(env.DATABASE_URL || '').trim();
|
||||
if (!url) {
|
||||
const error = new Error('DATABASE_URL is required');
|
||||
error.code = 'DB_NOT_CONFIGURED';
|
||||
throw error;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Build a pg.Pool-compatible configuration from environment variables. */
|
||||
export function databaseConfigFromEnv(env = process.env) {
|
||||
const max = positiveInt(env.DATABASE_MAX_CONNS, DEFAULTS.max, 1);
|
||||
const min = positiveInt(env.DATABASE_MIN_CONNS, DEFAULTS.min, 0);
|
||||
if (min > max) {
|
||||
throw new Error('DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS');
|
||||
}
|
||||
|
||||
return {
|
||||
connectionString: databaseUrlFromEnv(env),
|
||||
max,
|
||||
min,
|
||||
connectionTimeoutMillis: positiveInt(
|
||||
env.DATABASE_CONNECT_TIMEOUT_MS,
|
||||
DEFAULTS.connectionTimeoutMillis,
|
||||
1
|
||||
),
|
||||
idleTimeoutMillis: positiveInt(
|
||||
env.DATABASE_IDLE_TIMEOUT_MS,
|
||||
DEFAULTS.idleTimeoutMillis,
|
||||
0
|
||||
),
|
||||
query_timeout: positiveInt(env.DATABASE_QUERY_TIMEOUT_MS, DEFAULTS.queryTimeout, 1),
|
||||
ssl:
|
||||
/^(true|require|1)$/i.test(String(env.DATABASE_SSL || ''))
|
||||
? { rejectUnauthorized: !/^(true|1)$/i.test(String(env.DATABASE_SSL_ALLOW_INVALID || '')) }
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export { DEFAULTS as DATABASE_DEFAULTS };
|
||||
@@ -0,0 +1,92 @@
|
||||
import pg from 'pg';
|
||||
import { databaseConfigFromEnv } from './config.js';
|
||||
|
||||
const { Pool } = pg;
|
||||
|
||||
const TRANSIENT_CODES = new Set(['ECONNRESET', 'EPIPE', '57P01', '08006', '08003']);
|
||||
const TRANSIENT_MESSAGE = /connection terminated|connection reset|econnreset|epipe|server closed the connection/i;
|
||||
|
||||
export function isTransientConnectionError(error) {
|
||||
return Boolean(
|
||||
error &&
|
||||
(TRANSIENT_CODES.has(error.code) || TRANSIENT_MESSAGE.test(String(error.message || '')))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one pg pool and exposes bounded startup, retry, transaction, and
|
||||
* shutdown behavior. Domain repositories should depend on this abstraction
|
||||
* instead of creating independent pools.
|
||||
*/
|
||||
export class Database {
|
||||
constructor(options = {}) {
|
||||
const { pool, ...poolOptions } = options;
|
||||
this.pool = pool || new Pool(poolOptions);
|
||||
this.ownsPool = !pool;
|
||||
this.ready = false;
|
||||
}
|
||||
|
||||
static fromEnv(env = process.env) {
|
||||
return new Database(databaseConfigFromEnv(env));
|
||||
}
|
||||
|
||||
async connect({ retries = 10, retryDelayMs = 2000 } = {}) {
|
||||
if (this.ready) return this;
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= Math.max(1, retries); attempt += 1) {
|
||||
try {
|
||||
await this.pool.query('SELECT 1');
|
||||
this.ready = true;
|
||||
return this;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt >= retries || !isTransientConnectionError(error)) throw error;
|
||||
const delay = Math.min(Math.max(100, retryDelayMs) * 2 ** (attempt - 1), 30000);
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
async query(text, values = []) {
|
||||
await this.connect();
|
||||
try {
|
||||
return await this.pool.query(text, values);
|
||||
} catch (error) {
|
||||
if (!isTransientConnectionError(error)) throw error;
|
||||
return this.pool.query(text, values);
|
||||
}
|
||||
}
|
||||
|
||||
async transaction(callback) {
|
||||
if (typeof callback !== 'function') throw new TypeError('transaction callback is required');
|
||||
await this.connect();
|
||||
const client = await this.pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await callback(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
try {
|
||||
await client.query('ROLLBACK');
|
||||
} catch {
|
||||
// Preserve the original application error.
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (!this.pool || !this.ownsPool) return;
|
||||
await this.pool.end();
|
||||
this.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function createDatabaseFromEnv(env = process.env) {
|
||||
return Database.fromEnv(env);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export {
|
||||
databaseConfigFromEnv,
|
||||
databaseUrlFromEnv,
|
||||
DATABASE_DEFAULTS,
|
||||
} from './config.js';
|
||||
export {
|
||||
Database,
|
||||
createDatabaseFromEnv,
|
||||
isTransientConnectionError,
|
||||
} from './db.js';
|
||||
export {
|
||||
AUTH_SCHEMA,
|
||||
AuthStore,
|
||||
createSessionToken,
|
||||
hashPassword,
|
||||
hashToken,
|
||||
verifyPassword,
|
||||
} from './auth.js';
|
||||
export { runMigrations } from './migrate.js';
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Apply ordered SQL migrations using the shared Database transaction wrapper.
|
||||
* Each migration is { id: string, up: async (client) => void }.
|
||||
*/
|
||||
export async function runMigrations(
|
||||
database,
|
||||
migrations,
|
||||
{ lockKey = 70420320, tableName = 'schema_migrations' } = {}
|
||||
) {
|
||||
if (!database || typeof database.transaction !== 'function') {
|
||||
throw new TypeError('runMigrations requires a Database-like transaction object');
|
||||
}
|
||||
if (!Array.isArray(migrations)) throw new TypeError('migrations must be an array');
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tableName)) {
|
||||
throw new TypeError('migration tableName must be a simple SQL identifier');
|
||||
}
|
||||
const table = `"${tableName}"`;
|
||||
|
||||
const ordered = [...migrations].sort((left, right) => String(left.id).localeCompare(String(right.id)));
|
||||
await database.transaction(async client => {
|
||||
await client.query('SELECT pg_advisory_xact_lock($1)', [lockKey]);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS ${table} (
|
||||
id TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
`);
|
||||
|
||||
for (const migration of ordered) {
|
||||
if (!migration?.id || typeof migration.up !== 'function') {
|
||||
throw new TypeError('each migration requires an id and up(client) function');
|
||||
}
|
||||
const existing = await client.query(
|
||||
`SELECT 1 FROM ${table} WHERE id = $1`,
|
||||
[migration.id]
|
||||
);
|
||||
if (existing.rowCount > 0) continue;
|
||||
await migration.up(client);
|
||||
await client.query(`INSERT INTO ${table} (id) VALUES ($1)`, [migration.id]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createSessionToken,
|
||||
hashPassword,
|
||||
hashToken,
|
||||
verifyPassword,
|
||||
} from '../src/auth.js';
|
||||
|
||||
test('password hashes verify and reject a different password', () => {
|
||||
const hash = hashPassword('correct horse battery staple');
|
||||
assert.equal(verifyPassword('correct horse battery staple', hash), true);
|
||||
assert.equal(verifyPassword('wrong password', hash), false);
|
||||
});
|
||||
|
||||
test('session token hashes are not the raw token', () => {
|
||||
const { token, tokenHash } = createSessionToken();
|
||||
assert.notEqual(token, tokenHash);
|
||||
assert.equal(hashToken(token), tokenHash);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
# `gabriel20xx-shared-backend`
|
||||
|
||||
Shared Python backend infrastructure for services using `asyncpg`:
|
||||
|
||||
- validated `DATABASE_URL` and pool settings;
|
||||
- one async pool owner with ping and graceful shutdown;
|
||||
- bcrypt password and secure session-token helpers;
|
||||
- common account/session persistence for the single-admin or optional multi-user model.
|
||||
|
||||
HTTP framework adapters stay in each service. Install this package from the
|
||||
published index or directly from the SharedCode repository with a subdirectory
|
||||
install during development:
|
||||
|
||||
```bash
|
||||
pip install "git+https://repos.gfranz.ch/Gabriel20xx/SharedCode.git@v0.1.0#subdirectory=packages/python-backend"
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "gabriel20xx-shared-backend"
|
||||
version = "0.1.0"
|
||||
description = "Shared PostgreSQL and authentication primitives for Python services."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = { text = "MIT" }
|
||||
dependencies = [
|
||||
"asyncpg>=0.30",
|
||||
"bcrypt>=4.2",
|
||||
]
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Shared PostgreSQL and authentication primitives for Python services."""
|
||||
|
||||
from .auth import AuthStore, AuthUser, hash_password, verify_password
|
||||
from .config import DatabaseConfig, database_url_from_env
|
||||
from .postgres import Database
|
||||
from .tokens import hash_token, new_session_token
|
||||
|
||||
__all__ = [
|
||||
"AuthStore",
|
||||
"AuthUser",
|
||||
"Database",
|
||||
"DatabaseConfig",
|
||||
"database_url_from_env",
|
||||
"hash_password",
|
||||
"hash_token",
|
||||
"new_session_token",
|
||||
"verify_password",
|
||||
]
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Shared account/session persistence and password helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
import asyncpg
|
||||
import bcrypt
|
||||
|
||||
from .postgres import Database
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuthUser:
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
password_hash: str
|
||||
created_at: datetime | None = None
|
||||
updated_at: datetime | None = None
|
||||
|
||||
|
||||
class UserExistsError(Exception):
|
||||
"""Raised when a user violates a unique or single-user constraint."""
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
if len(password) < 8:
|
||||
raise ValueError("Password must be at least 8 characters")
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
class AuthStore:
|
||||
def __init__(self, database: Database, *, single_user: bool = True) -> None:
|
||||
self.database = database
|
||||
self.single_user = single_user
|
||||
|
||||
async def ensure_schema(self) -> None:
|
||||
await self.database.execute(_SCHEMA)
|
||||
if self.single_user:
|
||||
await self.database.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))"
|
||||
)
|
||||
|
||||
async def count_users(self) -> int:
|
||||
return int(await self.database.fetchval("SELECT count(*) FROM auth_users"))
|
||||
|
||||
async def create_user(self, username: str, email: str, password_hash: str) -> AuthUser:
|
||||
try:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email, password_hash, created_at, updated_at
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError as exc:
|
||||
raise UserExistsError from exc
|
||||
assert row is not None
|
||||
return AuthUser(**dict(row))
|
||||
|
||||
async def find_by_identifier(self, identifier: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT id, username, email, password_hash, created_at, updated_at
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
""",
|
||||
identifier,
|
||||
)
|
||||
return AuthUser(**dict(row)) if row else None
|
||||
|
||||
async def update_credentials(
|
||||
self, user_id: int, username: str, email: str, password_hash: str
|
||||
) -> None:
|
||||
await self.database.execute(
|
||||
"""
|
||||
UPDATE auth_users
|
||||
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4
|
||||
""",
|
||||
username,
|
||||
email,
|
||||
password_hash,
|
||||
user_id,
|
||||
)
|
||||
|
||||
async def create_session(self, user_id: int, token_hash: str, expires_at: datetime) -> None:
|
||||
await self.database.execute(
|
||||
"INSERT INTO auth_sessions (user_id, token_hash, expires_at) VALUES ($1, $2, $3)",
|
||||
user_id,
|
||||
token_hash,
|
||||
expires_at,
|
||||
)
|
||||
|
||||
async def find_session_user(self, token_hash: str) -> AuthUser | None:
|
||||
row = await self.database.fetchrow(
|
||||
"""
|
||||
SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
""",
|
||||
token_hash,
|
||||
)
|
||||
return AuthUser(**dict(row)) if row else None
|
||||
|
||||
async def delete_session(self, token_hash: str) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE token_hash = $1", token_hash)
|
||||
|
||||
async def delete_sessions_for_user(self, user_id: int) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id)
|
||||
|
||||
async def prune_expired_sessions(self) -> None:
|
||||
await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()")
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Dependency-free environment configuration helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
def _int_value(env: Mapping[str, str], key: str, fallback: int, minimum: int) -> int:
|
||||
try:
|
||||
value = int(env.get(key, ""))
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
return value if value >= minimum else fallback
|
||||
|
||||
|
||||
def database_url_from_env(env: Mapping[str, str] | None = None) -> str:
|
||||
source = os.environ if env is None else env
|
||||
value = str(source.get("DATABASE_URL", "")).strip()
|
||||
if not value:
|
||||
raise RuntimeError("DATABASE_URL environment variable is required")
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DatabaseConfig:
|
||||
dsn: str
|
||||
min_size: int = 0
|
||||
max_size: int = 20
|
||||
timeout: float = 5.0
|
||||
command_timeout: float = 15.0
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, env: Mapping[str, str] | None = None) -> "DatabaseConfig":
|
||||
source = os.environ if env is None else env
|
||||
max_size = _int_value(source, "DATABASE_MAX_CONNS", 20, 1)
|
||||
min_size = _int_value(source, "DATABASE_MIN_CONNS", 0, 0)
|
||||
if min_size > max_size:
|
||||
raise ValueError("DATABASE_MIN_CONNS must not exceed DATABASE_MAX_CONNS")
|
||||
return cls(
|
||||
dsn=database_url_from_env(source),
|
||||
min_size=min_size,
|
||||
max_size=max_size,
|
||||
timeout=float(_int_value(source, "DATABASE_CONNECT_TIMEOUT_SECONDS", 5, 1)),
|
||||
command_timeout=float(
|
||||
_int_value(source, "DATABASE_COMMAND_TIMEOUT_SECONDS", 15, 1)
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Shared asyncpg pool and transaction wrapper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Awaitable, Callable, Sequence
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .config import DatabaseConfig
|
||||
|
||||
|
||||
class Database:
|
||||
"""Own one asyncpg pool and expose common lifecycle/query operations."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
@classmethod
|
||||
async def connect(cls, config: DatabaseConfig | str) -> "Database":
|
||||
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn=settings.dsn,
|
||||
min_size=settings.min_size,
|
||||
max_size=settings.max_size,
|
||||
timeout=settings.timeout,
|
||||
command_timeout=settings.command_timeout,
|
||||
)
|
||||
try:
|
||||
await pool.fetchval("SELECT 1")
|
||||
except Exception:
|
||||
await pool.close()
|
||||
raise
|
||||
return cls(pool)
|
||||
|
||||
async def ping(self) -> None:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pool.close()
|
||||
|
||||
async def execute(self, query: str, *args: Any) -> str:
|
||||
return await self.pool.execute(query, *args)
|
||||
|
||||
async def fetch(self, query: str, *args: Any) -> list[asyncpg.Record]:
|
||||
return await self.pool.fetch(query, *args)
|
||||
|
||||
async def fetchrow(self, query: str, *args: Any) -> asyncpg.Record | None:
|
||||
return await self.pool.fetchrow(query, *args)
|
||||
|
||||
async def fetchval(self, query: str, *args: Any) -> Any:
|
||||
return await self.pool.fetchval(query, *args)
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[asyncpg.Connection]:
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
yield connection
|
||||
|
||||
async def with_transaction(
|
||||
self,
|
||||
callback: Callable[[asyncpg.Connection], Awaitable[Any]],
|
||||
) -> Any:
|
||||
async with self.transaction() as connection:
|
||||
return await callback(connection)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Opaque session-token generation and storage hashing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
|
||||
def new_session_token() -> tuple[str, str]:
|
||||
token = secrets.token_urlsafe(32)
|
||||
return token, hash_token(token)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,3 @@
|
||||
# `@gabriel20xx/web-ui`
|
||||
|
||||
Reusable Svelte 5 components for the shared application shell and account UI. See the workspace [README](../../README.md) for installation, publishing, and integration examples.
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "@gabriel20xx/web-ui",
|
||||
"version": "0.1.0",
|
||||
"description": "Shared Svelte UI, layout, authentication, and account components for Gabriel20xx web projects.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"sideEffects": [
|
||||
"**/*.css"
|
||||
],
|
||||
"peerDependencies": {
|
||||
"svelte": "^5.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gabriel20xx/design-tokens": "0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/package": "^2.5.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.0.0",
|
||||
"svelte": "^5.0.0",
|
||||
"svelte-check": "^4.0.0",
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json",
|
||||
"package": "svelte-package"
|
||||
},
|
||||
"svelte": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"svelte": "./dist/index.js",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./styles.css": "./dist/styles.css",
|
||||
"./package.json": "./package.json"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './lib/index.js';
|
||||
@@ -0,0 +1,41 @@
|
||||
<script lang="ts">
|
||||
import type { AboutLink } from '../types';
|
||||
import Dialog from './Dialog.svelte';
|
||||
|
||||
let {
|
||||
brand = 'Application',
|
||||
description = '',
|
||||
links = [],
|
||||
open = $bindable(false),
|
||||
version = ''
|
||||
}: {
|
||||
brand?: string;
|
||||
description?: string;
|
||||
links?: AboutLink[];
|
||||
open?: boolean;
|
||||
version?: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<Dialog bind:open title={`About ${brand}`}>
|
||||
<div class="sc-auth-brand">
|
||||
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
|
||||
<strong>{brand}</strong>
|
||||
</div>
|
||||
|
||||
{#if version}
|
||||
<p class="sc-muted">Version {version}</p>
|
||||
{/if}
|
||||
|
||||
{#if description}
|
||||
<p class="sc-muted">{description}</p>
|
||||
{/if}
|
||||
|
||||
{#if links.length > 0}
|
||||
<div class="sc-about-links">
|
||||
{#each links as link}
|
||||
<a href={link.href} rel="noreferrer" target="_blank">{link.label}</a>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</Dialog>
|
||||
@@ -0,0 +1,51 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import type { NavItem } from '../types';
|
||||
import Header from './Header.svelte';
|
||||
|
||||
let {
|
||||
brand = 'Application',
|
||||
brandHref = '/',
|
||||
children,
|
||||
class: className = '',
|
||||
currentPath = '',
|
||||
navItems = [],
|
||||
onLogout,
|
||||
onProfile,
|
||||
onSettings,
|
||||
showSettings = true,
|
||||
theme = 'dark',
|
||||
username = ''
|
||||
}: {
|
||||
brand?: string;
|
||||
brandHref?: string;
|
||||
children?: Snippet;
|
||||
class?: string;
|
||||
currentPath?: string;
|
||||
navItems?: NavItem[];
|
||||
onLogout?: () => void | Promise<void>;
|
||||
onProfile?: () => void;
|
||||
onSettings?: () => void;
|
||||
showSettings?: boolean;
|
||||
theme?: 'dark' | 'light' | 'system';
|
||||
username?: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div class={`sc-root sc-app-shell ${className}`} data-theme={theme === 'system' ? undefined : theme}>
|
||||
<Header
|
||||
{brand}
|
||||
{brandHref}
|
||||
{currentPath}
|
||||
{navItems}
|
||||
{onLogout}
|
||||
{onProfile}
|
||||
{onSettings}
|
||||
{showSettings}
|
||||
{username}
|
||||
/>
|
||||
|
||||
<main class="sc-main">
|
||||
{@render children?.()}
|
||||
</main>
|
||||
</div>
|
||||
@@ -0,0 +1,124 @@
|
||||
<script lang="ts">
|
||||
import type { AuthLoginInput, AuthSetupInput } from '../types';
|
||||
import Button from './Button.svelte';
|
||||
|
||||
let {
|
||||
brand = 'Application',
|
||||
error = '',
|
||||
loading = false,
|
||||
onLogin,
|
||||
onSetup,
|
||||
setupRequired = false,
|
||||
tagline = ''
|
||||
}: {
|
||||
brand?: string;
|
||||
error?: string;
|
||||
loading?: boolean;
|
||||
onLogin?: (input: AuthLoginInput) => void | Promise<void>;
|
||||
onSetup?: (input: AuthSetupInput) => void | Promise<void>;
|
||||
setupRequired?: boolean;
|
||||
tagline?: string;
|
||||
} = $props();
|
||||
|
||||
let username = $state('');
|
||||
let email = $state('');
|
||||
let identifier = $state('');
|
||||
let password = $state('');
|
||||
let submitError = $state('');
|
||||
let submitting = $state(false);
|
||||
|
||||
async function submit(event: SubmitEvent): Promise<void> {
|
||||
event.preventDefault();
|
||||
submitError = '';
|
||||
submitting = true;
|
||||
|
||||
try {
|
||||
if (setupRequired) {
|
||||
if (!onSetup) throw new Error('The application has not configured its setup handler.');
|
||||
await onSetup({ username, email, password });
|
||||
} else {
|
||||
if (!onLogin) throw new Error('The application has not configured its login handler.');
|
||||
await onLogin({ identifier, password });
|
||||
}
|
||||
} catch (caught) {
|
||||
submitError = caught instanceof Error ? caught.message : 'Authentication failed.';
|
||||
} finally {
|
||||
submitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="sc-root sc-auth-page">
|
||||
<section aria-labelledby="sc-auth-title" class="sc-auth-card">
|
||||
<div class="sc-auth-brand">
|
||||
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
|
||||
<span>{brand}</span>
|
||||
</div>
|
||||
|
||||
<h1 id="sc-auth-title">{setupRequired ? 'Create your account' : 'Welcome back'}</h1>
|
||||
{#if tagline}
|
||||
<p class="sc-auth-subtitle">{tagline}</p>
|
||||
{/if}
|
||||
|
||||
<form class="sc-form sc-auth-form" onsubmit={submit}>
|
||||
{#if setupRequired}
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Username</span>
|
||||
<input
|
||||
autocomplete="username"
|
||||
class="sc-input"
|
||||
name="username"
|
||||
required
|
||||
type="text"
|
||||
bind:value={username}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Email</span>
|
||||
<input
|
||||
autocomplete="email"
|
||||
class="sc-input"
|
||||
name="email"
|
||||
required
|
||||
type="email"
|
||||
bind:value={email}
|
||||
/>
|
||||
</label>
|
||||
{:else}
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Username or email</span>
|
||||
<input
|
||||
autocomplete="username"
|
||||
class="sc-input"
|
||||
name="identifier"
|
||||
required
|
||||
type="text"
|
||||
bind:value={identifier}
|
||||
/>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Password</span>
|
||||
<input
|
||||
autocomplete={setupRequired ? 'new-password' : 'current-password'}
|
||||
class="sc-input"
|
||||
minlength="8"
|
||||
name="password"
|
||||
required
|
||||
type="password"
|
||||
bind:value={password}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{#if error || submitError}
|
||||
<p aria-live="polite" class="sc-error">{submitError || error}</p>
|
||||
{/if}
|
||||
|
||||
<Button disabled={loading || submitting} fullWidth size="lg" type="submit">
|
||||
{loading || submitting ? 'Please wait…' : setupRequired ? 'Create account' : 'Log in'}
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,19 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
type BadgeVariant = 'default' | 'success' | 'warning' | 'danger';
|
||||
|
||||
let {
|
||||
children,
|
||||
class: className = '',
|
||||
variant = 'default'
|
||||
}: {
|
||||
children?: Snippet;
|
||||
class?: string;
|
||||
variant?: BadgeVariant;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<span class={`sc-badge ${className}`} data-variant={variant}>
|
||||
{@render children?.()}
|
||||
</span>
|
||||
@@ -0,0 +1,35 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
|
||||
type ButtonSize = 'sm' | 'md' | 'lg';
|
||||
|
||||
let {
|
||||
children,
|
||||
class: className = '',
|
||||
disabled = false,
|
||||
fullWidth = false,
|
||||
onclick,
|
||||
size = 'md',
|
||||
type = 'button',
|
||||
variant = 'primary'
|
||||
}: {
|
||||
children?: Snippet;
|
||||
class?: string;
|
||||
disabled?: boolean;
|
||||
fullWidth?: boolean;
|
||||
onclick?: (event: MouseEvent) => void;
|
||||
size?: ButtonSize;
|
||||
type?: 'button' | 'submit' | 'reset';
|
||||
variant?: ButtonVariant;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
class={`sc-button sc-button-${variant} sc-button-${size}${fullWidth ? ' sc-button-full' : ''} ${className}`}
|
||||
{disabled}
|
||||
{onclick}
|
||||
{type}
|
||||
>
|
||||
{@render children?.()}
|
||||
</button>
|
||||
@@ -0,0 +1,15 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
let {
|
||||
children,
|
||||
class: className = ''
|
||||
}: {
|
||||
children?: Snippet;
|
||||
class?: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<section class={`sc-card ${className}`}>
|
||||
{@render children?.()}
|
||||
</section>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
let {
|
||||
children,
|
||||
description = '',
|
||||
footer,
|
||||
open = $bindable(false),
|
||||
title
|
||||
}: {
|
||||
children?: Snippet;
|
||||
description?: string;
|
||||
footer?: Snippet;
|
||||
open?: boolean;
|
||||
title: string;
|
||||
} = $props();
|
||||
|
||||
function close(): void {
|
||||
open = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if open}
|
||||
<div
|
||||
aria-label={title}
|
||||
class="sc-dialog-backdrop"
|
||||
role="presentation"
|
||||
onclick={(event) => {
|
||||
if (event.target === event.currentTarget) close();
|
||||
}}
|
||||
>
|
||||
<section aria-modal="true" class="sc-dialog" role="dialog">
|
||||
<div class="sc-dialog-header">
|
||||
<div>
|
||||
<h2 class="sc-dialog-title">{title}</h2>
|
||||
{#if description}
|
||||
<p class="sc-dialog-description">{description}</p>
|
||||
{/if}
|
||||
</div>
|
||||
<button aria-label="Close" class="sc-dialog-close" type="button" onclick={close}>×</button>
|
||||
</div>
|
||||
|
||||
<div class="sc-dialog-body">
|
||||
{@render children?.()}
|
||||
</div>
|
||||
|
||||
{#if footer}
|
||||
<div class="sc-dialog-footer">
|
||||
{@render footer()}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import type { NavItem } from '../types';
|
||||
|
||||
let {
|
||||
brand = 'Application',
|
||||
brandHref = '/',
|
||||
currentPath = '',
|
||||
navItems = [],
|
||||
onLogout,
|
||||
onProfile,
|
||||
onSettings,
|
||||
showSettings = true,
|
||||
username = ''
|
||||
}: {
|
||||
brand?: string;
|
||||
brandHref?: string;
|
||||
currentPath?: string;
|
||||
navItems?: NavItem[];
|
||||
onLogout?: () => void | Promise<void>;
|
||||
onProfile?: () => void;
|
||||
onSettings?: () => void;
|
||||
showSettings?: boolean;
|
||||
username?: string;
|
||||
} = $props();
|
||||
|
||||
let navOpen = $state(false);
|
||||
|
||||
function isActive(item: NavItem): boolean {
|
||||
return item.href === '/'
|
||||
? currentPath === '/'
|
||||
: currentPath === item.href || currentPath.startsWith(`${item.href}/`);
|
||||
}
|
||||
</script>
|
||||
|
||||
<header class="sc-header">
|
||||
<a class="sc-brand" href={brandHref} onclick={() => (navOpen = false)}>
|
||||
<span aria-hidden="true" class="sc-brand-mark">{brand.slice(0, 1).toUpperCase()}</span>
|
||||
<span>{brand}</span>
|
||||
</a>
|
||||
|
||||
<nav aria-label="Primary navigation" class="sc-nav" data-open={navOpen}>
|
||||
{#each navItems as item}
|
||||
<a
|
||||
aria-current={isActive(item) ? 'page' : undefined}
|
||||
class="sc-nav-link"
|
||||
data-active={isActive(item)}
|
||||
href={item.href}
|
||||
onclick={() => (navOpen = false)}
|
||||
>
|
||||
{item.label}
|
||||
</a>
|
||||
{/each}
|
||||
</nav>
|
||||
|
||||
<div class="sc-header-actions">
|
||||
{#if showSettings && onSettings}
|
||||
<button aria-label="Open settings" class="sc-icon-button" type="button" onclick={onSettings}>⚙</button>
|
||||
{/if}
|
||||
|
||||
{#if username && onProfile}
|
||||
<button class="sc-profile-button" type="button" onclick={onProfile}>{username}</button>
|
||||
{/if}
|
||||
|
||||
{#if onLogout}
|
||||
<button class="sc-button sc-button-ghost sc-button-sm" type="button" onclick={() => void onLogout?.()}>
|
||||
Log out
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
<button
|
||||
aria-expanded={navOpen}
|
||||
aria-label={navOpen ? 'Close navigation menu' : 'Open navigation menu'}
|
||||
class="sc-icon-button sc-mobile-menu-button"
|
||||
type="button"
|
||||
onclick={() => (navOpen = !navOpen)}
|
||||
>
|
||||
{navOpen ? '×' : '☰'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
@@ -0,0 +1,31 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
let {
|
||||
actions,
|
||||
children,
|
||||
description = '',
|
||||
title
|
||||
}: {
|
||||
actions?: Snippet;
|
||||
children?: Snippet;
|
||||
description?: string;
|
||||
title: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<div class="sc-page-header">
|
||||
<div>
|
||||
<h1>{title}</h1>
|
||||
{#if description}
|
||||
<p>{description}</p>
|
||||
{/if}
|
||||
{@render children?.()}
|
||||
</div>
|
||||
|
||||
{#if actions}
|
||||
<div>
|
||||
{@render actions()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script lang="ts">
|
||||
import type { ProfileUpdateInput } from '../types';
|
||||
import Button from './Button.svelte';
|
||||
import Dialog from './Dialog.svelte';
|
||||
|
||||
let {
|
||||
currentEmail = '',
|
||||
currentUsername = '',
|
||||
onSave,
|
||||
open = $bindable(false)
|
||||
}: {
|
||||
currentEmail?: string;
|
||||
currentUsername?: string;
|
||||
onSave?: (input: ProfileUpdateInput) => void | Promise<void>;
|
||||
open?: boolean;
|
||||
} = $props();
|
||||
|
||||
let username = $state('');
|
||||
let email = $state('');
|
||||
let error = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
$effect(() => {
|
||||
if (open) {
|
||||
username = currentUsername;
|
||||
email = currentEmail;
|
||||
error = '';
|
||||
}
|
||||
});
|
||||
|
||||
async function save(event: SubmitEvent): Promise<void> {
|
||||
event.preventDefault();
|
||||
error = '';
|
||||
|
||||
if (!onSave) {
|
||||
error = 'The application has not configured its profile update handler.';
|
||||
return;
|
||||
}
|
||||
|
||||
saving = true;
|
||||
try {
|
||||
await onSave({ username, email });
|
||||
open = false;
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Profile update failed.';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Dialog bind:open title="Profile">
|
||||
<div class="sc-profile-summary">
|
||||
<strong>{currentUsername || 'Your profile'}</strong>
|
||||
{#if currentEmail}
|
||||
<span>{currentEmail}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<form class="sc-form" onsubmit={save}>
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Username</span>
|
||||
<input autocomplete="username" class="sc-input" required type="text" bind:value={username} />
|
||||
</label>
|
||||
|
||||
<label class="sc-field">
|
||||
<span class="sc-label">Email</span>
|
||||
<input autocomplete="email" class="sc-input" required type="email" bind:value={email} />
|
||||
</label>
|
||||
|
||||
{#if error}
|
||||
<p aria-live="polite" class="sc-error">{error}</p>
|
||||
{/if}
|
||||
|
||||
<div class="sc-form-actions">
|
||||
<Button variant="secondary" type="button" onclick={() => (open = false)}>Cancel</Button>
|
||||
<Button disabled={saving} type="submit">{saving ? 'Saving…' : 'Save changes'}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
@@ -0,0 +1,24 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import Dialog from './Dialog.svelte';
|
||||
|
||||
let {
|
||||
children,
|
||||
description = '',
|
||||
open = $bindable(false),
|
||||
title = 'Settings'
|
||||
}: {
|
||||
children?: Snippet;
|
||||
description?: string;
|
||||
open?: boolean;
|
||||
title?: string;
|
||||
} = $props();
|
||||
</script>
|
||||
|
||||
<Dialog bind:open {description} {title}>
|
||||
{#if children}
|
||||
{@render children()}
|
||||
{:else}
|
||||
<p class="sc-muted">No settings have been configured for this application yet.</p>
|
||||
{/if}
|
||||
</Dialog>
|
||||
@@ -0,0 +1,20 @@
|
||||
export { default as AboutDialog } from './components/AboutDialog.svelte';
|
||||
export { default as AppShell } from './components/AppShell.svelte';
|
||||
export { default as AuthPage } from './components/AuthPage.svelte';
|
||||
export { default as Badge } from './components/Badge.svelte';
|
||||
export { default as Button } from './components/Button.svelte';
|
||||
export { default as Card } from './components/Card.svelte';
|
||||
export { default as Dialog } from './components/Dialog.svelte';
|
||||
export { default as Header } from './components/Header.svelte';
|
||||
export { default as PageHeader } from './components/PageHeader.svelte';
|
||||
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
|
||||
export { default as SettingsDialog } from './components/SettingsDialog.svelte';
|
||||
export type {
|
||||
AboutLink,
|
||||
AsyncAction,
|
||||
AuthLoginInput,
|
||||
AuthSetupInput,
|
||||
ContentSnippet,
|
||||
NavItem,
|
||||
ProfileUpdateInput
|
||||
} from './types';
|
||||
@@ -0,0 +1,573 @@
|
||||
@import '@gabriel20xx/design-tokens/theme.css';
|
||||
|
||||
:where(.sc-root, .sc-root *) {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.sc-root {
|
||||
min-height: 100%;
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-bg);
|
||||
font-family: var(--sc-font-sans);
|
||||
}
|
||||
|
||||
.sc-root button,
|
||||
.sc-root input,
|
||||
.sc-root textarea,
|
||||
.sc-root select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.sc-root a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.sc-app-shell {
|
||||
min-height: 100vh;
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-bg);
|
||||
}
|
||||
|
||||
.sc-main {
|
||||
width: min(100% - 2rem, 90rem);
|
||||
margin: 0 auto;
|
||||
padding: 2rem 0 3rem;
|
||||
}
|
||||
|
||||
.sc-header {
|
||||
position: sticky;
|
||||
z-index: 20;
|
||||
top: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1.25rem;
|
||||
min-height: 4rem;
|
||||
padding: 0 1rem;
|
||||
color: var(--sc-fg);
|
||||
background: color-mix(in srgb, var(--sc-surface) 92%, transparent);
|
||||
border-bottom: 1px solid var(--sc-border);
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.sc-brand {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
color: var(--sc-fg);
|
||||
font-size: 1rem;
|
||||
font-weight: 750;
|
||||
text-decoration: none;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.sc-brand-mark {
|
||||
display: grid;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
place-items: center;
|
||||
color: var(--sc-primary-fg);
|
||||
background: var(--sc-primary);
|
||||
border-radius: var(--sc-radius-md);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.sc-nav {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.sc-nav-link,
|
||||
.sc-profile-button,
|
||||
.sc-icon-button {
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--sc-radius-md);
|
||||
transition: color 140ms ease, background 140ms ease, border-color 140ms ease;
|
||||
}
|
||||
|
||||
.sc-nav-link {
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.9rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sc-nav-link:hover,
|
||||
.sc-nav-link[data-active='true'] {
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface-hover);
|
||||
border-color: var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-header-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.sc-icon-button,
|
||||
.sc-profile-button {
|
||||
color: var(--sc-muted-fg);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sc-icon-button {
|
||||
display: grid;
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
place-items: center;
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.sc-profile-button {
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.sc-icon-button:hover,
|
||||
.sc-profile-button:hover {
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface-hover);
|
||||
border-color: var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-mobile-menu-button {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sc-page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.sc-page-header h1,
|
||||
.sc-page-header h2,
|
||||
.sc-dialog-title,
|
||||
.sc-auth-card h1 {
|
||||
margin: 0;
|
||||
color: var(--sc-fg);
|
||||
font-weight: 750;
|
||||
letter-spacing: -0.025em;
|
||||
}
|
||||
|
||||
.sc-page-header h1 {
|
||||
font-size: clamp(1.5rem, 3vw, 2.25rem);
|
||||
}
|
||||
|
||||
.sc-page-header p,
|
||||
.sc-dialog-description,
|
||||
.sc-auth-subtitle,
|
||||
.sc-muted {
|
||||
margin: 0.5rem 0 0;
|
||||
color: var(--sc-muted-fg);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.sc-card {
|
||||
padding: 1.25rem;
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: var(--sc-radius-lg);
|
||||
box-shadow: var(--sc-shadow-sm);
|
||||
}
|
||||
|
||||
.sc-card-header {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.sc-card-header h2,
|
||||
.sc-card-header h3 {
|
||||
margin: 0;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.sc-card-header p {
|
||||
margin: 0.375rem 0 0;
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.sc-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 1.5rem;
|
||||
padding: 0.125rem 0.5rem;
|
||||
color: var(--sc-secondary-fg);
|
||||
background: var(--sc-secondary);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.sc-badge[data-variant='success'] {
|
||||
color: var(--sc-success-fg);
|
||||
background: var(--sc-success);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.sc-badge[data-variant='warning'] {
|
||||
color: var(--sc-warning-fg);
|
||||
background: var(--sc-warning);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.sc-badge[data-variant='danger'] {
|
||||
color: var(--sc-danger-fg);
|
||||
background: var(--sc-danger);
|
||||
border-color: transparent;
|
||||
}
|
||||
|
||||
.sc-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
min-height: 2.5rem;
|
||||
padding: 0.625rem 1rem;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--sc-radius-md);
|
||||
font-size: 0.9rem;
|
||||
font-weight: 650;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
transition: color 140ms ease, background 140ms ease, border-color 140ms ease, opacity 140ms ease;
|
||||
}
|
||||
|
||||
.sc-button:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.sc-button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.sc-button:focus-visible,
|
||||
.sc-icon-button:focus-visible,
|
||||
.sc-profile-button:focus-visible,
|
||||
.sc-nav-link:focus-visible,
|
||||
.sc-dialog-close:focus-visible {
|
||||
outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.sc-button-primary {
|
||||
color: var(--sc-primary-fg);
|
||||
background: var(--sc-primary);
|
||||
}
|
||||
|
||||
.sc-button-primary:hover:not(:disabled) {
|
||||
background: var(--sc-primary-hover);
|
||||
}
|
||||
|
||||
.sc-button-secondary {
|
||||
color: var(--sc-secondary-fg);
|
||||
background: var(--sc-secondary);
|
||||
border-color: var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-button-secondary:hover:not(:disabled) {
|
||||
background: var(--sc-secondary-hover);
|
||||
}
|
||||
|
||||
.sc-button-ghost {
|
||||
color: var(--sc-muted-fg);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.sc-button-ghost:hover:not(:disabled) {
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface-hover);
|
||||
}
|
||||
|
||||
.sc-button-danger {
|
||||
color: var(--sc-danger-fg);
|
||||
background: var(--sc-danger);
|
||||
}
|
||||
|
||||
.sc-button-danger:hover:not(:disabled) {
|
||||
background: var(--sc-danger-hover);
|
||||
}
|
||||
|
||||
.sc-button-sm {
|
||||
min-height: 2rem;
|
||||
padding: 0.45rem 0.75rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.sc-button-lg {
|
||||
min-height: 2.875rem;
|
||||
padding: 0.75rem 1.25rem;
|
||||
}
|
||||
|
||||
.sc-button-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sc-form {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.sc-field {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.sc-label {
|
||||
color: var(--sc-fg);
|
||||
font-size: 0.85rem;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.sc-input,
|
||||
.sc-select,
|
||||
.sc-textarea {
|
||||
width: 100%;
|
||||
min-height: 2.6rem;
|
||||
padding: 0.625rem 0.75rem;
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-bg);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: var(--sc-radius-md);
|
||||
outline: none;
|
||||
transition: border-color 140ms ease, box-shadow 140ms ease;
|
||||
}
|
||||
|
||||
.sc-textarea {
|
||||
min-height: 7rem;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.sc-input::placeholder,
|
||||
.sc-textarea::placeholder {
|
||||
color: var(--sc-subtle-fg);
|
||||
}
|
||||
|
||||
.sc-input:focus,
|
||||
.sc-select:focus,
|
||||
.sc-textarea:focus {
|
||||
border-color: var(--sc-ring);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-ring) 22%, transparent);
|
||||
}
|
||||
|
||||
.sc-form-actions,
|
||||
.sc-dialog-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.625rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.sc-error {
|
||||
padding: 0.75rem;
|
||||
color: var(--sc-danger);
|
||||
background: color-mix(in srgb, var(--sc-danger) 12%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--sc-danger) 35%, transparent);
|
||||
border-radius: var(--sc-radius-md);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.sc-success {
|
||||
color: var(--sc-success);
|
||||
}
|
||||
|
||||
.sc-auth-page {
|
||||
display: grid;
|
||||
min-height: 100vh;
|
||||
place-items: center;
|
||||
padding: 1.5rem;
|
||||
color: var(--sc-fg);
|
||||
background:
|
||||
radial-gradient(circle at 15% 10%, color-mix(in srgb, var(--sc-primary) 18%, transparent), transparent 35%),
|
||||
var(--sc-bg);
|
||||
}
|
||||
|
||||
.sc-auth-card {
|
||||
width: min(100%, 28rem);
|
||||
padding: clamp(1.5rem, 5vw, 2.5rem);
|
||||
background: var(--sc-surface);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: var(--sc-radius-xl);
|
||||
box-shadow: var(--sc-shadow-lg);
|
||||
}
|
||||
|
||||
.sc-auth-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1.5rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.sc-auth-card h1 {
|
||||
font-size: 1.7rem;
|
||||
}
|
||||
|
||||
.sc-auth-form {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.sc-dialog-backdrop {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 1rem;
|
||||
background: var(--sc-backdrop);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.sc-dialog {
|
||||
width: min(100%, 34rem);
|
||||
max-height: min(90vh, 48rem);
|
||||
overflow: auto;
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface-raised);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: var(--sc-radius-xl);
|
||||
box-shadow: var(--sc-shadow-lg);
|
||||
}
|
||||
|
||||
.sc-dialog-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1.25rem 1.25rem 0;
|
||||
}
|
||||
|
||||
.sc-dialog-title {
|
||||
font-size: 1.25rem;
|
||||
}
|
||||
|
||||
.sc-dialog-close {
|
||||
display: grid;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
place-items: center;
|
||||
color: var(--sc-muted-fg);
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--sc-radius-sm);
|
||||
font-size: 1.35rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sc-dialog-close:hover {
|
||||
color: var(--sc-fg);
|
||||
background: var(--sc-surface-hover);
|
||||
border-color: var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-dialog-body {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.sc-dialog-footer {
|
||||
padding: 0 1.25rem 1.25rem;
|
||||
}
|
||||
|
||||
.sc-about-links {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.sc-about-links a {
|
||||
color: var(--sc-primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sc-about-links a:hover {
|
||||
color: var(--sc-primary-hover);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.sc-profile-summary {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
margin-bottom: 1.25rem;
|
||||
padding: 0.875rem;
|
||||
background: var(--sc-bg);
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: var(--sc-radius-md);
|
||||
}
|
||||
|
||||
.sc-profile-summary strong {
|
||||
color: var(--sc-fg);
|
||||
}
|
||||
|
||||
.sc-profile-summary span {
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
@media (max-width: 45rem) {
|
||||
.sc-header {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
|
||||
.sc-mobile-menu-button {
|
||||
display: grid;
|
||||
order: 3;
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
margin-left: auto;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.sc-nav {
|
||||
display: none;
|
||||
flex-basis: 100%;
|
||||
order: 4;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.sc-nav[data-open='true'] {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.sc-nav-link {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sc-header-actions {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.sc-profile-button {
|
||||
max-width: 9rem;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 30rem) {
|
||||
.sc-main {
|
||||
width: min(100% - 1.25rem, 90rem);
|
||||
padding-top: 1.25rem;
|
||||
}
|
||||
|
||||
.sc-page-header {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
export type AsyncAction<T = void> = (value: T) => void | Promise<void>;
|
||||
|
||||
export interface NavItem {
|
||||
href: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface AuthSetupInput {
|
||||
username: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AuthLoginInput {
|
||||
identifier: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface ProfileUpdateInput {
|
||||
username: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface AboutLink {
|
||||
label: string;
|
||||
href: string;
|
||||
}
|
||||
|
||||
export type ContentSnippet = Snippet;
|
||||
@@ -0,0 +1,5 @@
|
||||
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
||||
|
||||
export default {
|
||||
preprocess: vitePreprocess()
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"moduleResolution": "bundler",
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"target": "ES2022",
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.d.ts",
|
||||
"src/**/*.ts",
|
||||
"src/**/*.svelte"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user