@promakeai/cli 0.4.9 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.js +183 -176
  2. package/dist/registry/blog-core.json +26 -7
  3. package/dist/registry/blog-list-page.json +2 -2
  4. package/dist/registry/blog-section.json +1 -1
  5. package/dist/registry/cart-drawer.json +1 -1
  6. package/dist/registry/cart-page.json +1 -1
  7. package/dist/registry/category-section.json +1 -1
  8. package/dist/registry/checkout-page.json +1 -1
  9. package/dist/registry/contact-page-centered.json +1 -1
  10. package/dist/registry/contact-page-map-overlay.json +1 -1
  11. package/dist/registry/contact-page-map-split.json +1 -1
  12. package/dist/registry/contact-page-split.json +1 -1
  13. package/dist/registry/contact-page.json +1 -1
  14. package/dist/registry/db.json +129 -0
  15. package/dist/registry/docs/blog-core.md +13 -12
  16. package/dist/registry/docs/blog-list-page.md +1 -1
  17. package/dist/registry/docs/ecommerce-core.md +13 -10
  18. package/dist/registry/docs/featured-products.md +1 -1
  19. package/dist/registry/docs/post-detail-page.md +2 -2
  20. package/dist/registry/docs/product-detail-page.md +2 -2
  21. package/dist/registry/docs/products-page.md +1 -1
  22. package/dist/registry/ecommerce-core.json +25 -5
  23. package/dist/registry/featured-products.json +2 -2
  24. package/dist/registry/forgot-password-page-split.json +1 -1
  25. package/dist/registry/forgot-password-page.json +1 -1
  26. package/dist/registry/header-centered-pill.json +1 -1
  27. package/dist/registry/header-ecommerce.json +1 -1
  28. package/dist/registry/index.json +1 -0
  29. package/dist/registry/login-page-split.json +1 -1
  30. package/dist/registry/login-page.json +1 -1
  31. package/dist/registry/newsletter-section.json +1 -1
  32. package/dist/registry/post-card.json +1 -1
  33. package/dist/registry/post-detail-block.json +1 -1
  34. package/dist/registry/post-detail-page.json +3 -3
  35. package/dist/registry/product-card-detailed.json +1 -1
  36. package/dist/registry/product-card.json +1 -1
  37. package/dist/registry/product-detail-block.json +1 -1
  38. package/dist/registry/product-detail-page.json +3 -3
  39. package/dist/registry/product-detail-section.json +1 -1
  40. package/dist/registry/product-quick-view.json +1 -1
  41. package/dist/registry/products-page.json +2 -2
  42. package/dist/registry/register-page-split.json +1 -1
  43. package/dist/registry/register-page.json +1 -1
  44. package/dist/registry/related-products-block.json +1 -1
  45. package/dist/registry/reset-password-page-split.json +1 -1
  46. package/package.json +2 -4
  47. package/template/README.md +58 -39
  48. package/template/eslint.config.js +37 -37
  49. package/template/package.json +3 -4
  50. package/template/public/data/database.db +0 -0
  51. package/template/scripts/init-db.ts +126 -13
  52. package/template/src/App.tsx +5 -8
  53. package/template/src/PasswordInput.tsx +61 -0
  54. package/template/src/components/FormField.tsx +11 -5
  55. package/template/src/lang/index.ts +86 -86
  56. package/README.md +0 -71
  57. package/template/public/data/database.db-shm +0 -0
  58. package/template/public/data/database.db-wal +0 -0
  59. package/template/src/db/index.ts +0 -20
  60. package/template/src/db/provider.tsx +0 -77
  61. package/template/src/db/schema.json +0 -259
  62. package/template/src/db/types.ts +0 -195
  63. package/template/src/hooks/use-debounced-value.ts +0 -12
@@ -0,0 +1,129 @@
1
+ {
2
+ "name": "db",
3
+ "type": "registry:module",
4
+ "title": "Database Module",
5
+ "description": "Universal data management with adapter pattern and React Query integration. Includes SQLite adapter for client-side persistence, DataManager for CRUD operations, and useRepository hook for React components. Supports complex queries, pagination, joins, and type-safe operations.",
6
+ "dependencies": [
7
+ "sql.js",
8
+ "@tanstack/react-query"
9
+ ],
10
+ "registryDependencies": [],
11
+ "files": [
12
+ {
13
+ "path": "db/index.ts",
14
+ "type": "registry:index",
15
+ "target": "$modules$/db/index.ts",
16
+ "content": "/**\r\n * DB Module\r\n * Universal data management with adapter pattern + React Query\r\n */\r\n\r\n// Core\r\nexport { DataManager } from \"./core/DataManager\";\r\nexport type {\r\n QueryOptions,\r\n OrderBy,\r\n PaginatedResult,\r\n // Complex query types\r\n WhereOperator,\r\n WhereCondition,\r\n WhereGroup,\r\n JoinType,\r\n JoinClause,\r\n} from \"./core/types\";\r\n\r\n// Adapters\r\nexport type { IDataAdapter } from \"./adapters/IDataAdapter\";\r\nexport { SqliteAdapter } from \"./adapters/SqliteAdapter\";\r\n\r\n// Config\r\nexport { getAdapter, createAdapter, resetAdapter } from \"./config\";\r\nexport type { DataConfig, AdapterType } from \"./config\";\r\n\r\n// React exports (re-export from react/index.ts)\r\nexport * from \"./react\";\r\n\r\n// Re-export for convenience\r\nexport { DBQueryProvider as QueryProvider } from \"./react\";\r\n\r\n// Utility exports (parsers for client-side data transformation)\r\nexport {\r\n parseCommaSeparatedString,\r\n parseJSONStringToArray,\r\n parseStringToArray,\r\n parseJSONString,\r\n parseSQLiteBoolean,\r\n parseNumberSafe,\r\n} from \"./utils/parsers\";\r\n"
17
+ },
18
+ {
19
+ "path": "db/config.ts",
20
+ "type": "registry:lib",
21
+ "target": "$modules$/db/config.ts",
22
+ "content": "import type { IDataAdapter } from \"./adapters/IDataAdapter\";\r\nimport { SqliteAdapter } from \"./adapters/SqliteAdapter\";\r\n\r\nexport type AdapterType = \"sqlite\";\r\n\r\nexport interface DataConfig {\r\n adapter: AdapterType;\r\n options?: {\r\n dbPath?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Get configuration from environment variables\r\n */\r\nfunction getConfig(): DataConfig {\r\n const adapter =\r\n (import.meta.env.VITE_DATA_ADAPTER as AdapterType) || \"sqlite\";\r\n\r\n return {\r\n adapter,\r\n options: {\r\n dbPath: import.meta.env.VITE_DB_PATH || \"/data/database.db\",\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create adapter instance based on configuration\r\n */\r\nexport function createAdapter(config: DataConfig): IDataAdapter {\r\n switch (config.adapter) {\r\n case \"sqlite\":\r\n return new SqliteAdapter(config.options?.dbPath);\r\n\r\n default:\r\n throw new Error(`Unknown adapter: ${config.adapter}`);\r\n }\r\n}\r\n\r\n/**\r\n * Get the configured adapter instance (singleton)\r\n */\r\nlet adapterInstance: IDataAdapter | null = null;\r\n\r\nexport function getAdapter(): IDataAdapter {\r\n if (!adapterInstance) {\r\n const config = getConfig();\r\n adapterInstance = createAdapter(config);\r\n }\r\n return adapterInstance;\r\n}\r\n\r\n/**\r\n * Reset adapter instance (useful for testing or switching adapters)\r\n */\r\nexport function resetAdapter(): void {\r\n adapterInstance = null;\r\n}\r\n"
23
+ },
24
+ {
25
+ "path": "db/core/DataManager.ts",
26
+ "type": "registry:lib",
27
+ "target": "$modules$/db/core/DataManager.ts",
28
+ "content": "import type { IDataAdapter } from \"../adapters/IDataAdapter\";\r\nimport type { QueryOptions, PaginatedResult } from \"./types\";\r\n\r\n/**\r\n * DataManager - Simple proxy to adapter\r\n */\r\nexport class DataManager {\r\n private static instance: DataManager;\r\n private adapter: IDataAdapter;\r\n\r\n private constructor(adapter: IDataAdapter) {\r\n this.adapter = adapter;\r\n }\r\n\r\n static getInstance(adapter: IDataAdapter): DataManager {\r\n if (!DataManager.instance) {\r\n DataManager.instance = new DataManager(adapter);\r\n }\r\n return DataManager.instance;\r\n }\r\n\r\n // Simple pass-through methods - no cache logic\r\n async query<T = any>(table: string, options?: QueryOptions): Promise<T[]> {\r\n return this.adapter.findMany<T>(table, options);\r\n }\r\n\r\n async queryOne<T = any>(\r\n table: string,\r\n options?: QueryOptions,\r\n ): Promise<T | null> {\r\n const results = await this.query<T>(table, { ...options, limit: 1 });\r\n return results[0] || null;\r\n }\r\n\r\n async queryById<T = any>(\r\n table: string,\r\n id: number | string,\r\n ): Promise<T | null> {\r\n return this.adapter.findById<T>(table, id);\r\n }\r\n\r\n async count(table: string, options?: QueryOptions): Promise<number> {\r\n return this.adapter.count(table, options);\r\n }\r\n\r\n async paginate<T = any>(\r\n table: string,\r\n page: number = 1,\r\n limit: number = 10,\r\n options?: QueryOptions,\r\n ): Promise<PaginatedResult<T>> {\r\n const offset = (page - 1) * limit;\r\n\r\n const [data, total] = await Promise.all([\r\n this.query<T>(table, { ...options, limit, offset }),\r\n this.count(table, options),\r\n ]);\r\n\r\n return {\r\n data,\r\n page,\r\n limit,\r\n total,\r\n totalPages: Math.ceil(total / limit),\r\n hasMore: page * limit < total,\r\n };\r\n }\r\n\r\n // Mutations - no cache invalidation here (React Query handles it)\r\n async create<T = any>(table: string, data: Partial<T>): Promise<T> {\r\n return this.adapter.create<T>(table, data);\r\n }\r\n\r\n async update<T = any>(\r\n table: string,\r\n id: number | string,\r\n data: Partial<T>,\r\n ): Promise<T> {\r\n return this.adapter.update<T>(table, id, data);\r\n }\r\n\r\n async delete(table: string, id: number | string): Promise<boolean> {\r\n return this.adapter.delete(table, id);\r\n }\r\n\r\n // Direct adapter access for advanced use cases\r\n getAdapter(): IDataAdapter {\r\n return this.adapter;\r\n }\r\n\r\n // ============================================\r\n // RAW SQL QUERIES\r\n // ============================================\r\n\r\n /**\r\n * Execute raw SQL query - returns multiple rows\r\n * Use for complex queries that can't be expressed with QueryOptions\r\n *\r\n * @example\r\n * const posts = await dm.raw<Post>(`\r\n * SELECT DISTINCT p.*, c.name as category_name\r\n * FROM posts p\r\n * JOIN post_categories pc ON p.id = pc.post_id\r\n * JOIN blog_categories c ON pc.category_id = c.id\r\n * WHERE c.slug = ? AND p.published = 1\r\n * `, [categorySlug]);\r\n */\r\n async raw<T = any>(sql: string, params?: any[]): Promise<T[]> {\r\n return this.adapter.raw<T>(sql, params);\r\n }\r\n\r\n /**\r\n * Execute raw SQL query - returns single row or null\r\n * Use for aggregations, single record lookups\r\n *\r\n * @example\r\n * const priceRange = await dm.rawOne<{min: number, max: number}>(`\r\n * SELECT MIN(price) as min, MAX(price) as max\r\n * FROM products WHERE published = 1\r\n * `);\r\n */\r\n async rawOne<T = any>(sql: string, params?: any[]): Promise<T | null> {\r\n return this.adapter.rawOne<T>(sql, params);\r\n }\r\n}\r\n"
29
+ },
30
+ {
31
+ "path": "db/core/types.ts",
32
+ "type": "registry:type",
33
+ "target": "$modules$/db/core/types.ts",
34
+ "content": "/**\r\n * Core type definitions for data-access module\r\n */\r\n\r\n// ============================================\r\n// WHERE CONDITIONS\r\n// ============================================\r\n\r\n/** WHERE condition operators */\r\nexport type WhereOperator =\r\n | \"=\"\r\n | \"!=\"\r\n | \"<>\"\r\n | \">\"\r\n | \"<\"\r\n | \">=\"\r\n | \"<=\"\r\n | \"LIKE\"\r\n | \"NOT LIKE\"\r\n | \"IN\"\r\n | \"NOT IN\"\r\n | \"BETWEEN\"\r\n | \"NOT BETWEEN\"\r\n | \"IS NULL\"\r\n | \"IS NOT NULL\";\r\n\r\n/** Single WHERE condition */\r\nexport interface WhereCondition {\r\n field: string;\r\n operator: WhereOperator;\r\n value: any;\r\n}\r\n\r\n/** WHERE groups (AND/OR) - recursive structure */\r\nexport interface WhereGroup {\r\n type: \"AND\" | \"OR\";\r\n conditions: (WhereCondition | WhereGroup)[];\r\n}\r\n\r\n// ============================================\r\n// JOIN DEFINITIONS\r\n// ============================================\r\n\r\n/** JOIN types */\r\nexport type JoinType = \"INNER\" | \"LEFT\" | \"RIGHT\" | \"CROSS\";\r\n\r\n/** JOIN definition */\r\nexport interface JoinClause {\r\n type: JoinType;\r\n table: string;\r\n alias?: string;\r\n on: {\r\n leftField: string;\r\n rightField: string;\r\n };\r\n}\r\n\r\n// ============================================\r\n// QUERY OPTIONS\r\n// ============================================\r\n\r\n/** Order definition */\r\nexport interface OrderBy {\r\n field: string;\r\n direction: \"ASC\" | \"DESC\";\r\n}\r\n\r\n/** Extended Query Options */\r\nexport interface QueryOptions {\r\n // Existing (backwards compatible)\r\n where?: Record<string, any>;\r\n limit?: number;\r\n offset?: number;\r\n orderBy?: OrderBy[];\r\n include?: string[];\r\n\r\n // New features\r\n select?: string[]; // SELECT fields: ['p.*', 'c.name as category_name']\r\n distinct?: boolean; // DISTINCT usage\r\n joins?: JoinClause[]; // JOIN definitions\r\n whereAdvanced?: WhereGroup; // Complex WHERE conditions (AND/OR groups)\r\n groupBy?: string[]; // GROUP BY fields\r\n having?: WhereGroup; // HAVING conditions\r\n}\r\n\r\n// ============================================\r\n// RESULT TYPES\r\n// ============================================\r\n\r\n/** Paginated result */\r\nexport interface PaginatedResult<T> {\r\n data: T[];\r\n page: number;\r\n limit: number;\r\n total: number;\r\n totalPages: number;\r\n hasMore: boolean;\r\n}\r\n\r\n/** Query key (for cache) */\r\nexport type QueryKey = (string | number | object)[];\r\n"
35
+ },
36
+ {
37
+ "path": "db/adapters/IDataAdapter.ts",
38
+ "type": "registry:type",
39
+ "target": "$modules$/db/adapters/IDataAdapter.ts",
40
+ "content": "import type { QueryOptions } from \"../core/types\";\r\n\r\n/**\r\n * Data Adapter Interface\r\n * Implement this interface to create custom data sources\r\n */\r\nexport interface IDataAdapter {\r\n // Connection\r\n connect(): Promise<void>;\r\n disconnect(): Promise<void>;\r\n\r\n // CRUD operations\r\n findMany<T>(table: string, options?: QueryOptions): Promise<T[]>;\r\n findOne<T>(table: string, options: QueryOptions): Promise<T | null>;\r\n findById<T>(table: string, id: number | string): Promise<T | null>;\r\n create<T>(table: string, data: Partial<T>): Promise<T>;\r\n update<T>(table: string, id: number | string, data: Partial<T>): Promise<T>;\r\n delete(table: string, id: number | string): Promise<boolean>;\r\n\r\n // Utilities\r\n count(table: string, options?: QueryOptions): Promise<number>;\r\n\r\n // Raw SQL queries - for complex queries that can't be expressed with QueryOptions\r\n raw<T>(sql: string, params?: any[]): Promise<T[]>;\r\n rawOne<T>(sql: string, params?: any[]): Promise<T | null>;\r\n}\r\n"
41
+ },
42
+ {
43
+ "path": "db/adapters/index.ts",
44
+ "type": "registry:index",
45
+ "target": "$modules$/db/adapters/index.ts",
46
+ "content": "export type { IDataAdapter } from \"./IDataAdapter\";\r\nexport { SqliteAdapter } from \"./SqliteAdapter\";\r\n"
47
+ },
48
+ {
49
+ "path": "db/adapters/SqliteAdapter.ts",
50
+ "type": "registry:lib",
51
+ "target": "$modules$/db/adapters/SqliteAdapter.ts",
52
+ "content": "import initSqlJs from \"sql.js\";\r\nimport type { Database } from \"sql.js\";\r\nimport type { IDataAdapter } from \"./IDataAdapter\";\r\nimport type {\r\n QueryOptions,\r\n WhereCondition,\r\n WhereGroup,\r\n JoinClause,\r\n} from \"../core/types\";\r\n\r\n/**\r\n * SQLite Adapter\r\n * Loads database from file using sql.js\r\n * Supports complex queries: JOIN, WHERE groups, LIKE, IN, BETWEEN\r\n */\r\nexport class SqliteAdapter implements IDataAdapter {\r\n private db: Database | null = null;\r\n private dbPath: string;\r\n\r\n constructor(dbPath: string = \"/data/database.db\") {\r\n this.dbPath = dbPath;\r\n }\r\n\r\n // ============================================\r\n // CONNECTION\r\n // ============================================\r\n\r\n async connect(): Promise<void> {\r\n if (this.db) return;\r\n\r\n try {\r\n const SQL = await initSqlJs({\r\n locateFile: (file: string) => `https://sql.js.org/dist/${file}`,\r\n });\r\n\r\n const response = await fetch(this.dbPath);\r\n if (!response.ok) {\r\n throw new Error(`Database file not found: ${this.dbPath}`);\r\n }\r\n\r\n const buffer = await response.arrayBuffer();\r\n this.db = new SQL.Database(new Uint8Array(buffer));\r\n console.log(\"SQLite adapter connected\");\r\n } catch (error) {\r\n console.error(\"SQLite adapter connection failed:\", error);\r\n throw error;\r\n }\r\n }\r\n\r\n async disconnect(): Promise<void> {\r\n if (this.db) {\r\n this.db.close();\r\n this.db = null;\r\n }\r\n }\r\n\r\n // ============================================\r\n // CRUD OPERATIONS\r\n // ============================================\r\n\r\n async findMany<T>(table: string, options?: QueryOptions): Promise<T[]> {\r\n await this.connect();\r\n if (!this.db) {\r\n console.warn(\"Database not connected\");\r\n return [];\r\n }\r\n try {\r\n const { sql, params } = this.buildSelectQuery(table, options);\r\n return this.executeQuery<T>(sql, params);\r\n } catch (error) {\r\n console.error(`Error querying table ${table}:`, error);\r\n return [];\r\n }\r\n }\r\n\r\n async findOne<T>(table: string, options: QueryOptions): Promise<T | null> {\r\n const results = await this.findMany<T>(table, { ...options, limit: 1 });\r\n return results[0] || null;\r\n }\r\n\r\n async findById<T>(table: string, id: number | string): Promise<T | null> {\r\n return this.findOne<T>(table, { where: { id } });\r\n }\r\n\r\n async create<T>(table: string, data: Partial<T>): Promise<T> {\r\n await this.connect();\r\n\r\n // Otomatik timestamp - sadece yoksa ekle\r\n const dataWithTimestamps: any = { ...data };\r\n\r\n if (!dataWithTimestamps.created_at) {\r\n dataWithTimestamps.created_at = new Date().toISOString();\r\n }\r\n\r\n if (!dataWithTimestamps.updated_at) {\r\n dataWithTimestamps.updated_at = new Date().toISOString();\r\n }\r\n\r\n const keys = Object.keys(dataWithTimestamps);\r\n const values = Object.values(dataWithTimestamps) as any[];\r\n const placeholders = keys.map(() => \"?\").join(\", \");\r\n\r\n const sql = `INSERT INTO ${table} (${keys.join(\", \")}) VALUES (${placeholders})`;\r\n this.db!.run(sql, values);\r\n\r\n const lastIdResult = this.db!.exec(\"SELECT last_insert_rowid() as id\");\r\n const lastId = lastIdResult[0]?.values[0]?.[0] as number;\r\n\r\n return this.findById<T>(table, lastId) as Promise<T>;\r\n }\r\n\r\n async update<T>(\r\n table: string,\r\n id: number | string,\r\n data: Partial<T>,\r\n ): Promise<T> {\r\n await this.connect();\r\n\r\n // Otomatik updated_at - her zaman güncelle\r\n const dataWithTimestamp = {\r\n ...data,\r\n updated_at: new Date().toISOString(),\r\n };\r\n\r\n const keys = Object.keys(dataWithTimestamp);\r\n const values = Object.values(dataWithTimestamp) as any[];\r\n const setClause = keys.map((key) => `${key} = ?`).join(\", \");\r\n\r\n const sql = `UPDATE ${table} SET ${setClause} WHERE id = ?`;\r\n this.db!.run(sql, [...values, id]);\r\n\r\n return this.findById<T>(table, id) as Promise<T>;\r\n }\r\n\r\n async delete(table: string, id: number | string): Promise<boolean> {\r\n await this.connect();\r\n const sql = `DELETE FROM ${table} WHERE id = ?`;\r\n this.db!.run(sql, [id]);\r\n return true;\r\n }\r\n\r\n async count(table: string, options?: QueryOptions): Promise<number> {\r\n await this.connect();\r\n const { sql, params } = this.buildCountQuery(table, options);\r\n const results = await this.executeQuery<{ count: number }>(sql, params);\r\n return results[0]?.count || 0;\r\n }\r\n\r\n // ============================================\r\n // RAW SQL QUERIES\r\n // ============================================\r\n\r\n async raw<T>(sql: string, params?: any[]): Promise<T[]> {\r\n await this.connect();\r\n return this.executeQuery<T>(sql, params);\r\n }\r\n\r\n async rawOne<T>(sql: string, params?: any[]): Promise<T | null> {\r\n const results = await this.raw<T>(sql, params);\r\n return results[0] || null;\r\n }\r\n\r\n // ============================================\r\n // PRIVATE: QUERY EXECUTION\r\n // ============================================\r\n\r\n private async executeQuery<T>(sql: string, params?: any[]): Promise<T[]> {\r\n if (!this.db) {\r\n console.warn(\"Database not connected\");\r\n return [];\r\n }\r\n try {\r\n const stmt = this.db.prepare(sql);\r\n if (params && params.length > 0) stmt.bind(params);\r\n\r\n const results: T[] = [];\r\n while (stmt.step()) {\r\n results.push(stmt.getAsObject() as T);\r\n }\r\n stmt.free();\r\n return results;\r\n } catch (error) {\r\n console.error(`Query error: ${sql}`, error);\r\n return [];\r\n }\r\n }\r\n\r\n // ============================================\r\n // PRIVATE: QUERY BUILDERS\r\n // ============================================\r\n\r\n private buildSelectQuery(\r\n table: string,\r\n options?: QueryOptions,\r\n ): { sql: string; params: any[] } {\r\n const params: any[] = [];\r\n\r\n // SELECT clause\r\n const selectFields = options?.select?.join(\", \") || \"*\";\r\n const distinct = options?.distinct ? \"DISTINCT \" : \"\";\r\n let sql = `SELECT ${distinct}${selectFields} FROM ${table}`;\r\n\r\n // JOIN clauses\r\n if (options?.joins && options.joins.length > 0) {\r\n sql += this.buildJoinClause(options.joins);\r\n }\r\n\r\n // WHERE clause\r\n const whereClause = this.buildWhereClause(options, params);\r\n if (whereClause) {\r\n sql += ` WHERE ${whereClause}`;\r\n }\r\n\r\n // GROUP BY clause\r\n if (options?.groupBy && options.groupBy.length > 0) {\r\n sql += ` GROUP BY ${options.groupBy.join(\", \")}`;\r\n }\r\n\r\n // HAVING clause\r\n if (options?.having) {\r\n const havingClause = this.buildWhereGroupClause(options.having, params);\r\n if (havingClause) {\r\n sql += ` HAVING ${havingClause}`;\r\n }\r\n }\r\n\r\n // ORDER BY clause\r\n if (options?.orderBy && options.orderBy.length > 0) {\r\n const orderClauses = options.orderBy.map(\r\n (o) => `${o.field} ${o.direction}`,\r\n );\r\n sql += ` ORDER BY ${orderClauses.join(\", \")}`;\r\n }\r\n\r\n // LIMIT & OFFSET\r\n if (options?.limit) {\r\n sql += ` LIMIT ?`;\r\n params.push(options.limit);\r\n }\r\n\r\n if (options?.offset) {\r\n sql += ` OFFSET ?`;\r\n params.push(options.offset);\r\n }\r\n\r\n return { sql, params };\r\n }\r\n\r\n private buildCountQuery(\r\n table: string,\r\n options?: QueryOptions,\r\n ): { sql: string; params: any[] } {\r\n const params: any[] = [];\r\n let sql = `SELECT COUNT(*) as count FROM ${table}`;\r\n\r\n // JOIN clauses\r\n if (options?.joins && options.joins.length > 0) {\r\n sql += this.buildJoinClause(options.joins);\r\n }\r\n\r\n // WHERE clause\r\n const whereClause = this.buildWhereClause(options, params);\r\n if (whereClause) {\r\n sql += ` WHERE ${whereClause}`;\r\n }\r\n\r\n return { sql, params };\r\n }\r\n\r\n private buildJoinClause(joins: JoinClause[]): string {\r\n return joins\r\n .map((join) => {\r\n const alias = join.alias ? ` ${join.alias}` : \"\";\r\n const leftField = join.on.leftField;\r\n const rightField = join.on.rightField;\r\n return ` ${join.type} JOIN ${join.table}${alias} ON ${leftField} = ${rightField}`;\r\n })\r\n .join(\"\");\r\n }\r\n\r\n private buildWhereClause(\r\n options: QueryOptions | undefined,\r\n params: any[],\r\n ): string {\r\n const clauses: string[] = [];\r\n\r\n // Simple where (backwards compatible)\r\n if (options?.where) {\r\n const simpleConditions = Object.entries(options.where).map(\r\n ([key, value]) => {\r\n params.push(value);\r\n return `${key} = ?`;\r\n },\r\n );\r\n if (simpleConditions.length > 0) {\r\n clauses.push(simpleConditions.join(\" AND \"));\r\n }\r\n }\r\n\r\n // Advanced where (new feature)\r\n if (options?.whereAdvanced) {\r\n const advancedClause = this.buildWhereGroupClause(\r\n options.whereAdvanced,\r\n params,\r\n );\r\n if (advancedClause) {\r\n clauses.push(advancedClause);\r\n }\r\n }\r\n\r\n return clauses.length > 0 ? clauses.join(\" AND \") : \"\";\r\n }\r\n\r\n private buildWhereGroupClause(group: WhereGroup, params: any[]): string {\r\n const conditions = group.conditions\r\n .map((condition) => {\r\n // Recursive: WhereGroup\r\n if (\"type\" in condition && \"conditions\" in condition) {\r\n return `(${this.buildWhereGroupClause(condition as WhereGroup, params)})`;\r\n }\r\n // WhereCondition\r\n return this.buildConditionClause(condition as WhereCondition, params);\r\n })\r\n .filter(Boolean);\r\n\r\n return conditions.join(` ${group.type} `);\r\n }\r\n\r\n private buildConditionClause(\r\n condition: WhereCondition,\r\n params: any[],\r\n ): string {\r\n const { field, operator, value } = condition;\r\n\r\n switch (operator) {\r\n case \"IS NULL\":\r\n return `${field} IS NULL`;\r\n\r\n case \"IS NOT NULL\":\r\n return `${field} IS NOT NULL`;\r\n\r\n case \"IN\":\r\n case \"NOT IN\":\r\n if (Array.isArray(value)) {\r\n const placeholders = value.map(() => \"?\").join(\", \");\r\n params.push(...value);\r\n return `${field} ${operator} (${placeholders})`;\r\n }\r\n return \"\";\r\n\r\n case \"BETWEEN\":\r\n case \"NOT BETWEEN\":\r\n if (Array.isArray(value) && value.length === 2) {\r\n params.push(value[0], value[1]);\r\n return `${field} ${operator} ? AND ?`;\r\n }\r\n return \"\";\r\n\r\n default:\r\n // =, !=, <>, >, <, >=, <=, LIKE, NOT LIKE\r\n params.push(value);\r\n return `${field} ${operator} ?`;\r\n }\r\n }\r\n}\r\n"
53
+ },
54
+ {
55
+ "path": "db/react/index.ts",
56
+ "type": "registry:index",
57
+ "target": "$modules$/db/react/index.ts",
58
+ "content": "// Provider\r\nexport { DBQueryProvider } from \"./QueryProvider\";\r\n\r\n// Query client and utilities\r\nexport { queryClient, queryKeys, cacheUtils } from \"./queryClient\";\r\n\r\n// Generic repository hooks\r\nexport {\r\n useRepositoryQuery,\r\n useRepositoryQueryOne,\r\n useRepositoryQueryById,\r\n useRepositoryPagination,\r\n useRepositoryInfiniteQuery,\r\n useRepositoryCreate,\r\n useRepositoryUpdate,\r\n useRepositoryDelete,\r\n // Raw SQL hooks\r\n useRawQuery,\r\n useRawQueryOne,\r\n} from \"./useRepository\";\r\n\r\n// Types\r\nexport type { RepositoryQueryOptions } from \"./useRepository\";\r\n"
59
+ },
60
+ {
61
+ "path": "db/react/queryClient.ts",
62
+ "type": "registry:lib",
63
+ "target": "$modules$/db/react/queryClient.ts",
64
+ "content": "import { QueryClient } from \"@tanstack/react-query\";\r\n\r\n/**\r\n * React Query handles ALL caching, refetching, and invalidation\r\n * No custom cache needed!\r\n */\r\nexport const queryClient = new QueryClient({\r\n defaultOptions: {\r\n queries: {\r\n staleTime: 30 * 1000, // 30 seconds fresh\r\n gcTime: 5 * 60 * 1000, // 5 minutes in cache (was cacheTime)\r\n retry: 1,\r\n refetchOnWindowFocus: false, // Don't auto-refetch on window focus\r\n refetchOnReconnect: false, // Don't refetch on reconnect\r\n refetchOnMount: false, // Don't refetch on component mount (prevent loops)\r\n },\r\n mutations: {\r\n retry: 0,\r\n },\r\n },\r\n});\r\n\r\n/**\r\n * Query key factory - for cache management\r\n * React Query uses these keys to cache and invalidate queries\r\n */\r\nexport const queryKeys = {\r\n all: (table: string) => [table] as const,\r\n lists: (table: string) => [table, \"list\"] as const,\r\n list: (table: string, options?: any) => [table, \"list\", options] as const,\r\n details: (table: string) => [table, \"detail\"] as const,\r\n detail: (table: string, id: number | string) =>\r\n [table, \"detail\", id] as const,\r\n paginated: (table: string, page: number, limit: number, options?: any) =>\r\n [table, \"paginated\", page, limit, options] as const,\r\n infinite: (table: string, limit: number, options?: any) =>\r\n [table, \"infinite\", limit, options] as const,\r\n count: (table: string, options?: any) => [table, \"count\", options] as const,\r\n};\r\n\r\n/**\r\n * Manual cache utilities (rarely needed)\r\n */\r\nexport const cacheUtils = {\r\n // Invalidate all queries for a table\r\n invalidateTable: (table: string) => {\r\n return queryClient.invalidateQueries({ queryKey: queryKeys.all(table) });\r\n },\r\n\r\n // Clear all cache\r\n clearAll: () => {\r\n return queryClient.clear();\r\n },\r\n\r\n // Get cached data\r\n getCachedData: <T>(queryKey: any[]) => {\r\n return queryClient.getQueryData<T>(queryKey);\r\n },\r\n\r\n // Set cached data manually\r\n setCachedData: <T>(queryKey: any[], data: T) => {\r\n return queryClient.setQueryData<T>(queryKey, data);\r\n },\r\n};\r\n"
65
+ },
66
+ {
67
+ "path": "db/react/QueryProvider.tsx",
68
+ "type": "registry:component",
69
+ "target": "$modules$/db/react/QueryProvider.tsx",
70
+ "content": "import { QueryClientProvider } from \"@tanstack/react-query\";\r\nimport { queryClient } from \"./queryClient\";\r\n\r\ninterface DBQueryProviderProps {\r\n children: React.ReactNode;\r\n}\r\n\r\n/**\r\n * DBQueryProvider - DB module's React Query provider\r\n * Wraps components that use db module hooks\r\n */\r\nexport function DBQueryProvider({ children }: DBQueryProviderProps) {\r\n return (\r\n <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>\r\n );\r\n}\r\n"
71
+ },
72
+ {
73
+ "path": "db/react/useRepository.ts",
74
+ "type": "registry:hook",
75
+ "target": "$modules$/db/react/useRepository.ts",
76
+ "content": "import {\r\n useQuery,\r\n useMutation,\r\n useQueryClient,\r\n useInfiniteQuery,\r\n type UseQueryOptions,\r\n type UseMutationOptions,\r\n type UseInfiniteQueryOptions,\r\n} from \"@tanstack/react-query\";\r\nimport { DataManager } from \"../core/DataManager\";\r\nimport { getAdapter } from \"../config\";\r\nimport { queryKeys } from \"./queryClient\";\r\nimport type { QueryOptions } from \"../core/types\";\r\n\r\n// Singleton manager\r\nlet managerInstance: DataManager | null = null;\r\nfunction getManager() {\r\n if (!managerInstance) {\r\n managerInstance = DataManager.getInstance(getAdapter());\r\n }\r\n return managerInstance;\r\n}\r\n\r\n// ==========================================\r\n// QUERY HOOKS\r\n// ==========================================\r\n\r\n// Omit 'select' from QueryOptions to avoid conflict with React Query's select\r\nexport interface RepositoryQueryOptions<T> extends Omit<\r\n QueryOptions,\r\n \"select\"\r\n> {\r\n // SQL SELECT fields (renamed to avoid conflict)\r\n selectFields?: string[];\r\n\r\n // React Query options\r\n enabled?: boolean;\r\n staleTime?: number;\r\n gcTime?: number;\r\n refetchOnWindowFocus?: boolean;\r\n refetchInterval?: number | false;\r\n select?: (data: T[]) => any; // React Query data transformation\r\n}\r\n\r\n/**\r\n * Generic query hook - React Query handles all caching\r\n * @example\r\n * // Simple query\r\n * const { data: posts, isLoading } = useRepositoryQuery('posts', {\r\n * where: { published: 1 },\r\n * orderBy: [{ field: 'created_at', direction: 'DESC' }],\r\n * staleTime: 60000\r\n * });\r\n *\r\n * // With JOIN\r\n * const { data: posts } = useRepositoryQuery('posts', {\r\n * selectFields: ['posts.*', 'c.name as category_name'],\r\n * joins: [{\r\n * type: 'INNER',\r\n * table: 'post_categories',\r\n * alias: 'pc',\r\n * on: { leftField: 'posts.id', rightField: 'pc.post_id' }\r\n * }],\r\n * distinct: true\r\n * });\r\n *\r\n * // With complex WHERE\r\n * const { data: products } = useRepositoryQuery('products', {\r\n * whereAdvanced: {\r\n * type: 'AND',\r\n * conditions: [\r\n * { field: 'published', operator: '=', value: 1 },\r\n * { type: 'OR', conditions: [\r\n * { field: 'name', operator: 'LIKE', value: '%phone%' },\r\n * { field: 'description', operator: 'LIKE', value: '%phone%' }\r\n * ]}\r\n * ]\r\n * }\r\n * });\r\n */\r\nexport function useRepositoryQuery<T = any>(\r\n table: string,\r\n options: RepositoryQueryOptions<T> = {},\r\n queryOptions?: Omit<UseQueryOptions<T[], Error>, \"queryKey\" | \"queryFn\">,\r\n) {\r\n const manager = getManager();\r\n const {\r\n // QueryOptions fields\r\n where,\r\n limit,\r\n offset,\r\n orderBy,\r\n include,\r\n // New complex query fields\r\n selectFields,\r\n distinct,\r\n joins,\r\n whereAdvanced,\r\n groupBy,\r\n having,\r\n // React Query options\r\n select,\r\n enabled,\r\n staleTime,\r\n gcTime,\r\n refetchOnWindowFocus,\r\n refetchInterval,\r\n } = options;\r\n\r\n const queryOpts: QueryOptions = {\r\n where,\r\n limit,\r\n offset,\r\n orderBy,\r\n include,\r\n select: selectFields,\r\n distinct,\r\n joins,\r\n whereAdvanced,\r\n groupBy,\r\n having,\r\n };\r\n\r\n return useQuery<T[], Error>({\r\n queryKey: queryKeys.list(table, queryOpts),\r\n queryFn: () => manager.query<T>(table, queryOpts),\r\n select,\r\n enabled,\r\n staleTime,\r\n gcTime,\r\n refetchOnWindowFocus,\r\n refetchInterval,\r\n ...queryOptions,\r\n });\r\n}\r\n\r\n/**\r\n * Query single record\r\n * @example\r\n * const { data: post } = useRepositoryQueryOne('posts', {\r\n * where: { slug: 'my-post' }\r\n * });\r\n */\r\nexport function useRepositoryQueryOne<T = any>(\r\n table: string,\r\n options: RepositoryQueryOptions<T> = {},\r\n) {\r\n const result = useRepositoryQuery<T>(table, { ...options, limit: 1 });\r\n\r\n return {\r\n ...result,\r\n data: result.data?.[0] || null,\r\n };\r\n}\r\n\r\n/**\r\n * Query by ID - React Query caches by ID automatically\r\n * @example\r\n * const { data: post, isLoading } = useRepositoryQueryById('posts', postId);\r\n */\r\nexport function useRepositoryQueryById<T = any>(\r\n table: string,\r\n id: number | string | null | undefined,\r\n options: Omit<UseQueryOptions<T | null, Error>, \"queryKey\" | \"queryFn\"> = {},\r\n) {\r\n const manager = getManager();\r\n\r\n return useQuery<T | null, Error>({\r\n queryKey: queryKeys.detail(table, id as any),\r\n queryFn: () => manager.queryById<T>(table, id as any),\r\n enabled: options.enabled !== false && id != null,\r\n ...options,\r\n });\r\n}\r\n\r\n/**\r\n * Paginated query - React Query caches each page\r\n * @example\r\n * const { data, totalPages, hasMore } = useRepositoryPagination('products', page, 20);\r\n */\r\nexport function useRepositoryPagination<T = any>(\r\n table: string,\r\n page: number = 1,\r\n limit: number = 10,\r\n options: QueryOptions = {},\r\n) {\r\n const manager = getManager();\r\n\r\n return useQuery({\r\n queryKey: queryKeys.paginated(table, page, limit, options),\r\n queryFn: () => manager.paginate<T>(table, page, limit, options),\r\n });\r\n}\r\n\r\n/**\r\n * Infinite query for infinite scroll / load more\r\n * @example\r\n * const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =\r\n * useRepositoryInfiniteQuery('posts', 20, {\r\n * where: { published: 1 },\r\n * orderBy: [{ field: 'created_at', direction: 'DESC' }]\r\n * });\r\n *\r\n * // data.pages = [page1Data, page2Data, page3Data, ...]\r\n * const allPosts = data?.pages.flatMap(page => page.data) ?? [];\r\n */\r\nexport function useRepositoryInfiniteQuery<T = any>(\r\n table: string,\r\n pageSize: number = 20,\r\n options: QueryOptions = {},\r\n queryOptions?: Omit<\r\n UseInfiniteQueryOptions<\r\n { data: T[]; page: number; totalPages: number; hasMore: boolean },\r\n Error\r\n >,\r\n \"queryKey\" | \"queryFn\" | \"getNextPageParam\" | \"initialPageParam\"\r\n >,\r\n) {\r\n const manager = getManager();\r\n\r\n return useInfiniteQuery({\r\n queryKey: queryKeys.infinite(table, pageSize, options),\r\n queryFn: ({ pageParam }) =>\r\n manager.paginate<T>(table, pageParam as number, pageSize, options),\r\n initialPageParam: 1,\r\n getNextPageParam: (lastPage) => {\r\n if (!lastPage.hasMore) return undefined;\r\n return lastPage.page + 1;\r\n },\r\n ...queryOptions,\r\n });\r\n}\r\n\r\n// ==========================================\r\n// MUTATION HOOKS (Auto-invalidation via React Query)\r\n// ==========================================\r\n\r\n/**\r\n * Create mutation - React Query handles cache invalidation\r\n * @example\r\n * const { mutate: createPost } = useRepositoryCreate('posts', {\r\n * onSuccess: () => toast.success('Created!')\r\n * });\r\n */\r\nexport function useRepositoryCreate<T = any>(\r\n table: string,\r\n options: Omit<UseMutationOptions<T, Error, Partial<T>>, \"mutationFn\"> & {\r\n invalidate?: string[];\r\n } = {},\r\n) {\r\n const manager = getManager();\r\n const queryClient = useQueryClient();\r\n const { invalidate = [table], ...mutationOptions } = options;\r\n\r\n return useMutation<T, Error, Partial<T>>({\r\n mutationFn: (data) => manager.create<T>(table, data),\r\n onSuccess: () => {\r\n // React Query automatically invalidates and refetches\r\n invalidate.forEach((t) => {\r\n queryClient.invalidateQueries({ queryKey: queryKeys.all(t) });\r\n });\r\n },\r\n ...mutationOptions,\r\n });\r\n}\r\n\r\n/**\r\n * Update mutation - Optimistic update via React Query\r\n * @example\r\n * const { mutate: updatePost } = useRepositoryUpdate('posts', {\r\n * onSuccess: () => toast.success('Updated!')\r\n * });\r\n * updatePost({ id: 1, data: { title: 'New Title' } });\r\n */\r\nexport function useRepositoryUpdate<T = any>(\r\n table: string,\r\n options: Omit<\r\n UseMutationOptions<T, Error, { id: number | string; data: Partial<T> }>,\r\n \"mutationFn\"\r\n > = {},\r\n) {\r\n const manager = getManager();\r\n const queryClient = useQueryClient();\r\n\r\n return useMutation<T, Error, { id: number | string; data: Partial<T> }>({\r\n mutationFn: ({ id, data }) => manager.update<T>(table, id, data),\r\n onSuccess: (data, variables) => {\r\n // Invalidate list queries\r\n queryClient.invalidateQueries({ queryKey: queryKeys.all(table) });\r\n\r\n // Update detail cache optimistically\r\n queryClient.setQueryData(queryKeys.detail(table, variables.id), data);\r\n },\r\n ...options,\r\n });\r\n}\r\n\r\n/**\r\n * Delete mutation\r\n * @example\r\n * const { mutate: deletePost } = useRepositoryDelete('posts', {\r\n * onSuccess: () => toast.success('Deleted!')\r\n * });\r\n * deletePost(postId);\r\n */\r\nexport function useRepositoryDelete(\r\n table: string,\r\n options: Omit<\r\n UseMutationOptions<boolean, Error, number | string>,\r\n \"mutationFn\"\r\n > = {},\r\n) {\r\n const manager = getManager();\r\n const queryClient = useQueryClient();\r\n\r\n return useMutation<boolean, Error, number | string>({\r\n mutationFn: (id) => manager.delete(table, id),\r\n onSuccess: (_data, id) => {\r\n // Invalidate and remove from cache\r\n queryClient.invalidateQueries({ queryKey: queryKeys.all(table) });\r\n queryClient.removeQueries({ queryKey: queryKeys.detail(table, id) });\r\n },\r\n ...options,\r\n });\r\n}\r\n\r\n// ==========================================\r\n// RAW SQL QUERY HOOKS\r\n// ==========================================\r\n\r\n/**\r\n * Raw SQL query hook - for complex queries that can't be expressed with QueryOptions\r\n * @example\r\n * // Complex JOIN query\r\n * const { data: posts } = useRawQuery<Post>(\r\n * ['posts-with-categories', categorySlug],\r\n * `SELECT DISTINCT p.*, c.name as category_name\r\n * FROM posts p\r\n * JOIN post_categories pc ON p.id = pc.post_id\r\n * JOIN blog_categories c ON pc.category_id = c.id\r\n * WHERE c.slug = ? AND p.published = 1\r\n * ORDER BY p.published_at DESC`,\r\n * [categorySlug]\r\n * );\r\n *\r\n * // Aggregation query\r\n * const { data: stats } = useRawQuery<{total: number, avg: number}>(\r\n * ['product-stats'],\r\n * `SELECT COUNT(*) as total, AVG(price) as avg FROM products WHERE published = 1`\r\n * );\r\n */\r\nexport function useRawQuery<T = any>(\r\n queryKey: any[],\r\n sql: string,\r\n params?: any[],\r\n options?: Omit<UseQueryOptions<T[], Error>, \"queryKey\" | \"queryFn\">,\r\n) {\r\n const manager = getManager();\r\n\r\n return useQuery<T[], Error>({\r\n queryKey: [\"raw\", ...queryKey],\r\n queryFn: () => manager.raw<T>(sql, params),\r\n ...options,\r\n });\r\n}\r\n\r\n/**\r\n * Raw SQL query hook for single result - aggregations, single lookups\r\n * @example\r\n * // Get price range\r\n * const { data: priceRange } = useRawQueryOne<{min: number, max: number}>(\r\n * ['price-range'],\r\n * `SELECT MIN(price) as min, MAX(price) as max FROM products WHERE published = 1`\r\n * );\r\n *\r\n * // Get single post with category\r\n * const { data: post } = useRawQueryOne<Post>(\r\n * ['post-detail', slug],\r\n * `SELECT p.*, c.name as category_name\r\n * FROM posts p\r\n * LEFT JOIN post_categories pc ON p.id = pc.post_id\r\n * LEFT JOIN blog_categories c ON pc.category_id = c.id\r\n * WHERE p.slug = ?`,\r\n * [slug]\r\n * );\r\n */\r\nexport function useRawQueryOne<T = any>(\r\n queryKey: any[],\r\n sql: string,\r\n params?: any[],\r\n options?: Omit<UseQueryOptions<T | null, Error>, \"queryKey\" | \"queryFn\">,\r\n) {\r\n const manager = getManager();\r\n\r\n return useQuery<T | null, Error>({\r\n queryKey: [\"raw\", ...queryKey],\r\n queryFn: () => manager.rawOne<T>(sql, params),\r\n ...options,\r\n });\r\n}\r\n"
77
+ },
78
+ {
79
+ "path": "db/utils/parsers.ts",
80
+ "type": "registry:lib",
81
+ "target": "$modules$/db/utils/parsers.ts",
82
+ "content": "/**\r\n * Database field parsers - Client-side utilities\r\n * NO automatic parsing - client decides what to parse and when\r\n */\r\n\r\n/**\r\n * Parse comma-separated string to array\r\n * @example \"tag1,tag2,tag3\" -> [\"tag1\", \"tag2\", \"tag3\"]\r\n */\r\nexport const parseCommaSeparatedString = (value: string): string[] => {\r\n if (!value || typeof value !== \"string\") return [];\r\n return value\r\n .split(\",\")\r\n .map((item) => item.trim())\r\n .filter(Boolean);\r\n};\r\n\r\n/**\r\n * Parse JSON string to array\r\n * @example '[\"img1.jpg\",\"img2.jpg\"]' -> [\"img1.jpg\", \"img2.jpg\"]\r\n */\r\nexport const parseJSONStringToArray = (value: string): string[] => {\r\n if (!value || typeof value !== \"string\") return [];\r\n try {\r\n const parsed = JSON.parse(value);\r\n return Array.isArray(parsed) ? parsed : [];\r\n } catch (e) {\r\n console.warn(\"Failed to parse JSON array:\", value);\r\n return [];\r\n }\r\n};\r\n\r\n/**\r\n * Smart array parser - tries JSON first, falls back to comma-separated\r\n * @example '[\"a\",\"b\"]' -> [\"a\", \"b\"] OR \"a,b\" -> [\"a\", \"b\"]\r\n */\r\nexport const parseStringToArray = (value: any): string[] => {\r\n if (!value) return [];\r\n if (Array.isArray(value)) return value;\r\n if (typeof value !== \"string\") return [];\r\n\r\n // Try JSON first\r\n if (value.trim().startsWith(\"[\")) {\r\n const jsonResult = parseJSONStringToArray(value);\r\n if (jsonResult.length > 0) return jsonResult;\r\n }\r\n\r\n // Fall back to comma-separated\r\n return parseCommaSeparatedString(value);\r\n};\r\n\r\n/**\r\n * Parse JSON string to object\r\n * @example '{\"key\":\"value\"}' -> {key: \"value\"}\r\n */\r\nexport const parseJSONString = <T = any>(\r\n value: any,\r\n defaultValue: T | null = null,\r\n): T | null => {\r\n if (!value) return defaultValue;\r\n if (typeof value === \"object\") return value; // Already parsed\r\n if (typeof value !== \"string\") return defaultValue;\r\n\r\n try {\r\n return JSON.parse(value);\r\n } catch (e) {\r\n console.warn(\"Failed to parse JSON:\", value);\r\n return defaultValue;\r\n }\r\n};\r\n\r\n/**\r\n * Parse SQLite boolean (0/1) to JavaScript boolean\r\n * @example 1 -> true, 0 -> false\r\n */\r\nexport const parseSQLiteBoolean = (value: any): boolean => {\r\n if (typeof value === \"boolean\") return value;\r\n if (typeof value === \"number\") return value !== 0;\r\n if (typeof value === \"string\") {\r\n const lower = value.toLowerCase();\r\n return lower === \"true\" || lower === \"1\" || lower === \"yes\";\r\n }\r\n return Boolean(value);\r\n};\r\n\r\n/**\r\n * Parse number safely with default fallback\r\n * @example \"123\" -> 123, \"invalid\" -> 0 (or provided default)\r\n */\r\nexport const parseNumberSafe = (\r\n value: any,\r\n defaultValue: number = 0,\r\n): number => {\r\n const num = Number(value);\r\n return isNaN(num) ? defaultValue : num;\r\n};\r\n"
83
+ }
84
+ ],
85
+ "exports": {
86
+ "types": [
87
+ "AdapterType",
88
+ "DataConfig",
89
+ "IDataAdapter",
90
+ "JoinClause",
91
+ "JoinType",
92
+ "OrderBy",
93
+ "PaginatedResult",
94
+ "QueryOptions",
95
+ "RepositoryQueryOptions",
96
+ "WhereCondition",
97
+ "WhereGroup",
98
+ "WhereOperator"
99
+ ],
100
+ "variables": [
101
+ "DBQueryProvider",
102
+ "DataManager",
103
+ "QueryProvider",
104
+ "SqliteAdapter",
105
+ "cacheUtils",
106
+ "createAdapter",
107
+ "getAdapter",
108
+ "parseCommaSeparatedString",
109
+ "parseJSONString",
110
+ "parseJSONStringToArray",
111
+ "parseNumberSafe",
112
+ "parseSQLiteBoolean",
113
+ "parseStringToArray",
114
+ "queryClient",
115
+ "queryKeys",
116
+ "resetAdapter",
117
+ "useRawQuery",
118
+ "useRawQueryOne",
119
+ "useRepositoryCreate",
120
+ "useRepositoryDelete",
121
+ "useRepositoryInfiniteQuery",
122
+ "useRepositoryPagination",
123
+ "useRepositoryQuery",
124
+ "useRepositoryQueryById",
125
+ "useRepositoryQueryOne",
126
+ "useRepositoryUpdate"
127
+ ]
128
+ }
129
+ }
@@ -1,6 +1,6 @@
1
1
  # Blog Core
2
2
 
3
- Complete blog state management with Zustand. Includes useBlogStore for saved/favorite posts functionality. TypeScript types for Post, Category, and Author. No provider wrapping needed. Data fetching uses useDbList/useDbGet from @/db.
3
+ Complete blog state management with Zustand. Includes useBlogStore for saved/favorite posts functionality, useDbPosts hook for fetching posts with category filtering, search, and pagination. TypeScript types for Post, Category, and Author. No provider wrapping needed.
4
4
 
5
5
  ## Files
6
6
 
@@ -9,33 +9,34 @@ Complete blog state management with Zustand. Includes useBlogStore for saved/fav
9
9
  | `$modules$/blog-core/index.ts` | index |
10
10
  | `$modules$/blog-core/types.ts` | type |
11
11
  | `$modules$/blog-core/stores/blog-store.ts` | store |
12
+ | `$modules$/blog-core/useDbPosts.ts` | hook |
12
13
  | `$modules$/blog-core/lang/en.json` | lang |
13
14
  | `$modules$/blog-core/lang/tr.json` | lang |
14
15
 
15
16
  ## Exports
16
17
 
17
- **Types:** `Author`, `BlogCategory`, `BlogContextType`, `BlogSettings`, `Comment`, `Post`
18
+ **Types:** `Author`, `BlogCategory`, `BlogContextType`, `BlogSettings`, `Comment`, `Post`, `PostCategory`
18
19
 
19
- **Components/Functions:** `useBlog`, `useBlogStore`
20
+ **Components/Functions:** `useBlog`, `useBlogStore`, `useDbBlogCategories`, `useDbFeaturedPosts`, `useDbPopularPosts`, `useDbPostBySlug`, `useDbPostSearch`, `useDbPostStats`, `useDbPosts`, `useDbPostsByCategory`, `useDbPostsByTag`, `useDbRecentPosts`
20
21
 
21
22
  ```typescript
22
- import { useBlog, useBlogStore, Author, ... } from '@/modules/blog-core';
23
+ import { useBlog, useBlogStore, useDbBlogCategories, ... } from '@/modules/blog-core';
23
24
  ```
24
25
 
25
26
  ## Usage
26
27
 
27
28
  ```
28
- import { useBlog } from '@/modules/blog-core';
29
- import { useDbList, useDbGet } from '@/db';
30
- import type { Post } from '@/modules/blog-core';
29
+ import { useBlog, useDbPosts, useDbPostBySlug } from '@/modules/blog-core';
31
30
 
32
- // Blog store (favorites, saved posts):
31
+ // No provider needed - just use the hooks:
33
32
  const { favorites, addToFavorites, isFavorite } = useBlog();
34
-
35
- // Data fetching via @/db hooks:
36
- const { data: posts } = useDbList<Post>('posts');
37
- const { data: post } = useDbGet<Post>('posts', { where: { slug } });
33
+ const { posts, loading } = useDbPosts();
38
34
 
39
35
  // Or use store directly with selectors:
40
36
  const favorites = useBlogStore((s) => s.favorites);
41
37
  ```
38
+
39
+ ## Dependencies
40
+
41
+ This component requires:
42
+ - `db`
@@ -26,7 +26,7 @@ import { BlogListPage } from '@/modules/blog-list-page';
26
26
 
27
27
  <Route path="/blog" element={<BlogListPage />} />
28
28
 
29
- • Uses useDbList() from @/db for post fetching
29
+ • Uses useDbPosts() from blog-core (Zustand)
30
30
  • Features: category tabs, search, grid/list view
31
31
  • Sidebar: popular posts, categories, newsletter
32
32
  ```
@@ -1,6 +1,6 @@
1
1
  # E-commerce Core
2
2
 
3
- Complete e-commerce state management with Zustand. Includes useCartStore for shopping cart operations (add/remove/update items, totals), useFavoritesStore for wishlist, formatPrice utility, and payment config. No provider wrapping needed. Data fetching uses useDbList/useDbGet from @/db.
3
+ Complete e-commerce state management with Zustand. Includes useCartStore for shopping cart operations (add/remove/update items, totals), useFavoritesStore for wishlist, useDbProducts hook for product fetching with filtering/sorting/pagination, and useDbSearch hook. No provider wrapping needed.
4
4
 
5
5
  ## Files
6
6
 
@@ -10,6 +10,8 @@ Complete e-commerce state management with Zustand. Includes useCartStore for sho
10
10
  | `$modules$/ecommerce-core/types.ts` | type |
11
11
  | `$modules$/ecommerce-core/stores/cart-store.ts` | store |
12
12
  | `$modules$/ecommerce-core/stores/favorites-store.ts` | store |
13
+ | `$modules$/ecommerce-core/useDbProducts.ts` | hook |
14
+ | `$modules$/ecommerce-core/useDbSearch.ts` | hook |
13
15
  | `$modules$/ecommerce-core/format-price.ts` | lib |
14
16
  | `$modules$/ecommerce-core/payment-config.ts` | lib |
15
17
  | `$modules$/ecommerce-core/lang/en.json` | lang |
@@ -17,9 +19,9 @@ Complete e-commerce state management with Zustand. Includes useCartStore for sho
17
19
 
18
20
  ## Exports
19
21
 
20
- **Types:** `Address`, `CartContextType`, `CartItem`, `CartState`, `Category`, `FavoritesContextType`, `OnlinePaymentProvider`, `Order`, `OrderItem`, `PaymentMethod`, `PaymentMethodConfig`, `Product`, `ProductVariant`, `User`
22
+ **Types:** `Address`, `CartContextType`, `CartItem`, `CartState`, `Category`, `FavoritesContextType`, `OnlinePaymentProvider`, `Order`, `OrderItem`, `PaymentMethod`, `PaymentMethodConfig`, `Product`, `ProductCategory`, `ProductVariant`, `User`
21
23
 
22
- **Components/Functions:** `ONLINE_PROVIDER_CONFIGS`, `PAYMENT_METHOD_CONFIGS`, `formatPrice`, `getAvailablePaymentMethods`, `getFilteredPaymentMethodConfigs`, `getOnlinePaymentProviders`, `isOnlineProviderAvailable`, `isPaymentMethodAvailable`, `useCart`, `useCartStore`, `useFavorites`, `useFavoritesStore`
24
+ **Components/Functions:** `ONLINE_PROVIDER_CONFIGS`, `PAYMENT_METHOD_CONFIGS`, `formatPrice`, `getAvailablePaymentMethods`, `getFilteredPaymentMethodConfigs`, `getOnlinePaymentProviders`, `isOnlineProviderAvailable`, `isPaymentMethodAvailable`, `useCart`, `useCartStore`, `useDbCategories`, `useDbFeaturedProducts`, `useDbProductBySlug`, `useDbProducts`, `useDbSearch`, `useFavorites`, `useFavoritesStore`
23
25
 
24
26
  ```typescript
25
27
  import { ONLINE_PROVIDER_CONFIGS, PAYMENT_METHOD_CONFIGS, formatPrice, ... } from '@/modules/ecommerce-core';
@@ -28,17 +30,18 @@ import { ONLINE_PROVIDER_CONFIGS, PAYMENT_METHOD_CONFIGS, formatPrice, ... } fro
28
30
  ## Usage
29
31
 
30
32
  ```
31
- import { useCart, useFavorites } from '@/modules/ecommerce-core';
32
- import { useDbList } from '@/db';
33
- import type { Product } from '@/modules/ecommerce-core';
33
+ import { useCart, useFavorites, useDbProducts } from '@/modules/ecommerce-core';
34
34
 
35
- // Cart & favorites stores:
35
+ // No provider needed - just use the hooks:
36
36
  const { addItem, removeItem, state, itemCount } = useCart();
37
37
  const { addToFavorites, isFavorite } = useFavorites();
38
-
39
- // Data fetching via @/db hooks:
40
- const { data: products } = useDbList<Product>('products');
38
+ const { products, loading } = useDbProducts();
41
39
 
42
40
  // Or use stores directly with selectors:
43
41
  const itemCount = useCartStore((s) => s.itemCount);
44
42
  ```
43
+
44
+ ## Dependencies
45
+
46
+ This component requires:
47
+ - `db`
@@ -28,7 +28,7 @@ import { FeaturedProducts } from '@/modules/featured-products';
28
28
 
29
29
  • Installed at: src/modules/featured-products/
30
30
  • Customize content: src/modules/featured-products/lang/*.json
31
- • Products auto-loaded via useDbList from @/db
31
+ • Products auto-loaded via useDbProducts hook
32
32
  ```
33
33
 
34
34
  ## Dependencies
@@ -1,6 +1,6 @@
1
1
  # Post Detail Page
2
2
 
3
- Blog post detail page that fetches post data by slug from URL params. Uses useDbGet from @/db and renders PostDetailBlock. Includes loading skeleton, error handling for not found posts, and automatic page title.
3
+ Blog post detail page that fetches post data by slug from URL params. Uses useDbPostBySlug hook from blog-core and renders PostDetailBlock. Includes loading skeleton, error handling for not found posts, and automatic page title.
4
4
 
5
5
  ## Files
6
6
 
@@ -26,7 +26,7 @@ import { PostDetailPage } from '@/modules/post-detail-page';
26
26
 
27
27
  <Route path="/blog/:slug" element={<PostDetailPage />} />
28
28
 
29
- • Uses useDbGet() from @/db to fetch post by slug
29
+ • Uses useDbPostBySlug() from blog-core
30
30
  • Fetches post by slug from URL params
31
31
  • Shows loading skeleton while fetching
32
32
  • Handles post not found state
@@ -1,6 +1,6 @@
1
1
  # Product Detail Page
2
2
 
3
- Product detail page that fetches product data by slug from URL params. Uses useDbGet from @/db and renders ProductDetailBlock. Includes loading skeleton, error handling for not found products, and automatic page title.
3
+ Product detail page that fetches product data by slug from URL params. Uses useDbProductBySlug hook from ecommerce-core and renders ProductDetailBlock. Includes loading skeleton, error handling for not found products, and automatic page title.
4
4
 
5
5
  ## Files
6
6
 
@@ -26,7 +26,7 @@ import { ProductDetailPage } from '@/modules/product-detail-page';
26
26
 
27
27
  <Route path="/products/:slug" element={<ProductDetailPage />} />
28
28
 
29
- • Uses useDbGet() from @/db to fetch product by slug
29
+ • Uses useDbProductBySlug() from ecommerce-core
30
30
  • Fetches product by slug from URL params
31
31
  • Shows loading skeleton while fetching
32
32
  • Handles product not found state
@@ -29,7 +29,7 @@ import ProductsPage from '@/modules/products-page';
29
29
  • Installed at: src/modules/products-page/
30
30
  • Add link: <Link to="/products">Browse Products</Link>
31
31
  • Supports filters, sorting, grid/list view, pagination
32
- • Uses useDbList from @/db for data fetching
32
+ • Uses useDbProducts hook for data fetching
33
33
  ```
34
34
 
35
35
  ## Dependencies
@@ -2,24 +2,26 @@
2
2
  "name": "ecommerce-core",
3
3
  "type": "registry:module",
4
4
  "title": "E-commerce Core",
5
- "description": "Complete e-commerce state management with Zustand. Includes useCartStore for shopping cart operations (add/remove/update items, totals), useFavoritesStore for wishlist, formatPrice utility, and payment config. No provider wrapping needed. Data fetching uses useDbList/useDbGet from @/db.",
5
+ "description": "Complete e-commerce state management with Zustand. Includes useCartStore for shopping cart operations (add/remove/update items, totals), useFavoritesStore for wishlist, useDbProducts hook for product fetching with filtering/sorting/pagination, and useDbSearch hook. No provider wrapping needed.",
6
6
  "dependencies": [
7
7
  "zustand"
8
8
  ],
9
- "registryDependencies": [],
10
- "usage": "import { useCart, useFavorites } from '@/modules/ecommerce-core';\nimport { useDbList } from '@/db';\nimport type { Product } from '@/modules/ecommerce-core';\n\n// Cart & favorites stores:\nconst { addItem, removeItem, state, itemCount } = useCart();\nconst { addToFavorites, isFavorite } = useFavorites();\n\n// Data fetching via @/db hooks:\nconst { data: products } = useDbList<Product>('products');\n\n// Or use stores directly with selectors:\nconst itemCount = useCartStore((s) => s.itemCount);",
9
+ "registryDependencies": [
10
+ "db"
11
+ ],
12
+ "usage": "import { useCart, useFavorites, useDbProducts } from '@/modules/ecommerce-core';\n\n// No provider needed - just use the hooks:\nconst { addItem, removeItem, state, itemCount } = useCart();\nconst { addToFavorites, isFavorite } = useFavorites();\nconst { products, loading } = useDbProducts();\n\n// Or use stores directly with selectors:\nconst itemCount = useCartStore((s) => s.itemCount);",
11
13
  "files": [
12
14
  {
13
15
  "path": "ecommerce-core/index.ts",
14
16
  "type": "registry:index",
15
17
  "target": "$modules$/ecommerce-core/index.ts",
16
- "content": "// Types\r\nexport * from './types';\r\n\r\n// Stores (Zustand)\r\nexport { useCartStore, useCart } from './stores/cart-store';\r\nexport { useFavoritesStore, useFavorites } from './stores/favorites-store';\r\n\r\n// Utilities\r\nexport { formatPrice } from './format-price';\r\n\r\n// Payment Config\r\nexport {\r\n type PaymentMethod,\r\n type OnlinePaymentProvider,\r\n type PaymentMethodConfig,\r\n PAYMENT_METHOD_CONFIGS,\r\n ONLINE_PROVIDER_CONFIGS,\r\n getAvailablePaymentMethods,\r\n getOnlinePaymentProviders,\r\n getFilteredPaymentMethodConfigs,\r\n isPaymentMethodAvailable,\r\n isOnlineProviderAvailable,\r\n} from './payment-config';\r\n"
18
+ "content": "// Types\r\nexport * from './types';\r\n\r\n// Stores (Zustand)\r\nexport { useCartStore, useCart } from './stores/cart-store';\r\nexport { useFavoritesStore, useFavorites } from './stores/favorites-store';\r\n\r\n// Hooks\r\nexport { useDbProducts, useDbProductBySlug, useDbFeaturedProducts, useDbCategories } from './useDbProducts';\r\nexport { useDbSearch } from './useDbSearch';\r\n\r\n// Utilities\r\nexport { formatPrice } from './format-price';\r\n\r\n// Payment Config\r\nexport {\r\n type PaymentMethod,\r\n type OnlinePaymentProvider,\r\n type PaymentMethodConfig,\r\n PAYMENT_METHOD_CONFIGS,\r\n ONLINE_PROVIDER_CONFIGS,\r\n getAvailablePaymentMethods,\r\n getOnlinePaymentProviders,\r\n getFilteredPaymentMethodConfigs,\r\n isPaymentMethodAvailable,\r\n isOnlineProviderAvailable,\r\n} from './payment-config';\r\n"
17
19
  },
18
20
  {
19
21
  "path": "ecommerce-core/types.ts",
20
22
  "type": "registry:type",
21
23
  "target": "$modules$/ecommerce-core/types.ts",
22
- "content": "export interface Product {\r\n id: number;\r\n name: string;\r\n slug: string;\r\n description: string;\r\n price: number;\r\n sale_price?: number;\r\n on_sale: boolean;\r\n images: string[];\r\n categories: number[];\r\n brand?: string;\r\n sku?: string;\r\n stock: number;\r\n tags: string[];\r\n rating: number;\r\n review_count: number;\r\n featured: boolean;\r\n is_new: boolean;\r\n published: boolean;\r\n specifications?: Record<string, string | number | boolean>;\r\n variants?: ProductVariant[];\r\n created_at?: string;\r\n updated_at?: string;\r\n meta_description?: string;\r\n meta_keywords?: string;\r\n}\r\n\r\nexport interface ProductVariant {\r\n id: string;\r\n name: string;\r\n value: string;\r\n price?: number;\r\n image?: string;\r\n stockQuantity: number;\r\n}\r\n\r\nexport interface CartItem {\r\n id: string | number;\r\n product: Product;\r\n quantity: number;\r\n}\r\n\r\nexport interface CartState {\r\n items: CartItem[];\r\n total: number;\r\n}\r\n\r\nexport interface CartContextType {\r\n state: CartState;\r\n addItem: (product: Product) => void;\r\n removeItem: (id: string | number) => void;\r\n updateQuantity: (id: string | number, quantity: number) => void;\r\n clearCart: () => void;\r\n itemCount: number;\r\n}\r\n\r\nexport interface FavoritesContextType {\r\n favorites: Product[];\r\n addToFavorites: (product: Product) => void;\r\n removeFromFavorites: (productId: string | number) => void;\r\n isFavorite: (productId: string | number) => boolean;\r\n favoriteCount: number;\r\n clearFavorites: () => void;\r\n}\r\n\r\nexport interface Category {\r\n id: number;\r\n name: string;\r\n slug: string;\r\n description?: string;\r\n image?: string;\r\n}\r\n\r\nexport interface User {\r\n id: string;\r\n email: string;\r\n name: string;\r\n avatar?: string;\r\n addresses?: Address[];\r\n orders?: Order[];\r\n}\r\n\r\nexport interface Address {\r\n name: string;\r\n line1: string;\r\n line2?: string;\r\n city: string;\r\n state: string;\r\n postalCode: string;\r\n country: string;\r\n}\r\n\r\nexport interface Order {\r\n id: number;\r\n user_id: string;\r\n total_price: number;\r\n status: 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';\r\n payment_method: string;\r\n shipping_address: Address;\r\n notes?: string;\r\n created_at?: string;\r\n}\r\n\r\nexport interface OrderItem {\r\n id: number;\r\n order_id: number;\r\n product_id: number;\r\n quantity: number;\r\n price: number;\r\n product?: {\r\n name: string;\r\n slug: string;\r\n images: string[];\r\n price: number;\r\n };\r\n}\r\n"
24
+ "content": "export interface ProductCategory {\r\n id: number;\r\n name: string;\r\n slug: string;\r\n is_primary: boolean;\r\n}\r\n\r\nexport interface Product {\r\n id: number;\r\n name: string;\r\n slug: string;\r\n description: string;\r\n price: number;\r\n sale_price?: number;\r\n on_sale: boolean;\r\n images: string[];\r\n category: string; // Primary category slug (backward compatibility)\r\n category_name?: string; // Primary category name (backward compatibility)\r\n categories: ProductCategory[]; // NEW: Multi-category support\r\n brand?: string;\r\n sku?: string;\r\n stock: number;\r\n tags: string[];\r\n rating: number;\r\n review_count: number;\r\n featured: boolean;\r\n is_new: boolean;\r\n published: boolean;\r\n specifications?: Record<string, any>;\r\n variants?: any;\r\n created_at?: string;\r\n updated_at?: string;\r\n meta_description?: string;\r\n meta_keywords?: string;\r\n}\r\n\r\nexport interface ProductVariant {\r\n id: string;\r\n name: string;\r\n value: string;\r\n price?: number;\r\n image?: string;\r\n stockQuantity: number;\r\n}\r\n\r\nexport interface CartItem {\r\n id: string | number;\r\n product: Product;\r\n quantity: number;\r\n}\r\n\r\nexport interface CartState {\r\n items: CartItem[];\r\n total: number;\r\n}\r\n\r\nexport interface CartContextType {\r\n state: CartState;\r\n addItem: (product: Product) => void;\r\n removeItem: (id: string | number) => void;\r\n updateQuantity: (id: string | number, quantity: number) => void;\r\n clearCart: () => void;\r\n itemCount: number;\r\n}\r\n\r\nexport interface FavoritesContextType {\r\n favorites: Product[];\r\n addToFavorites: (product: Product) => void;\r\n removeFromFavorites: (productId: string | number) => void;\r\n isFavorite: (productId: string | number) => boolean;\r\n favoriteCount: number;\r\n clearFavorites: () => void;\r\n}\r\n\r\nexport interface Category {\r\n id: number;\r\n name: string;\r\n slug: string;\r\n description?: string;\r\n image?: string;\r\n}\r\n\r\nexport interface User {\r\n id: string;\r\n email: string;\r\n name: string;\r\n avatar?: string;\r\n addresses?: Address[];\r\n orders?: Order[];\r\n}\r\n\r\nexport interface Address {\r\n name: string;\r\n line1: string;\r\n line2?: string;\r\n city: string;\r\n state: string;\r\n postalCode: string;\r\n country: string;\r\n}\r\n\r\nexport interface Order {\r\n id: number;\r\n user_id: string;\r\n total_price: number;\r\n status: 'pending' | 'confirmed' | 'shipped' | 'delivered' | 'cancelled';\r\n payment_method: string;\r\n shipping_address: Address;\r\n notes?: string;\r\n created_at?: string;\r\n}\r\n\r\nexport interface OrderItem {\r\n id: number;\r\n order_id: number;\r\n product_id: number;\r\n quantity: number;\r\n price: number;\r\n product?: {\r\n name: string;\r\n slug: string;\r\n images: string[];\r\n price: number;\r\n };\r\n}\r\n"
23
25
  },
24
26
  {
25
27
  "path": "ecommerce-core/stores/cart-store.ts",
@@ -33,6 +35,18 @@
33
35
  "target": "$modules$/ecommerce-core/stores/favorites-store.ts",
34
36
  "content": "import { create } from \"zustand\";\r\nimport { persist } from \"zustand/middleware\";\r\nimport type { Product, FavoritesContextType } from \"../types\";\r\n\r\ninterface FavoritesStore {\r\n favorites: Product[];\r\n favoriteCount: number;\r\n addToFavorites: (product: Product) => void;\r\n removeFromFavorites: (productId: string | number) => void;\r\n isFavorite: (productId: string | number) => boolean;\r\n clearFavorites: () => void;\r\n}\r\n\r\nexport const useFavoritesStore = create<FavoritesStore>()(\r\n persist(\r\n (set, get) => ({\r\n favorites: [],\r\n favoriteCount: 0,\r\n\r\n addToFavorites: (product) =>\r\n set((state) => {\r\n if (state.favorites.some((fav) => fav.id === product.id)) {\r\n return state;\r\n }\r\n const favorites = [...state.favorites, product];\r\n return { favorites, favoriteCount: favorites.length };\r\n }),\r\n\r\n removeFromFavorites: (productId) =>\r\n set((state) => {\r\n const favorites = state.favorites.filter((fav) => fav.id !== productId);\r\n return { favorites, favoriteCount: favorites.length };\r\n }),\r\n\r\n isFavorite: (productId) => {\r\n return get().favorites.some((fav) => fav.id === productId);\r\n },\r\n\r\n clearFavorites: () => set({ favorites: [], favoriteCount: 0 }),\r\n }),\r\n { name: \"ecommerce_favorites\" }\r\n )\r\n);\r\n\r\n// Backward compatible hook - matches FavoritesContextType\r\nexport const useFavorites = (): FavoritesContextType => {\r\n const store = useFavoritesStore();\r\n return {\r\n favorites: store.favorites,\r\n addToFavorites: store.addToFavorites,\r\n removeFromFavorites: store.removeFromFavorites,\r\n isFavorite: store.isFavorite,\r\n favoriteCount: store.favoriteCount,\r\n clearFavorites: store.clearFavorites,\r\n };\r\n};\r\n"
35
37
  },
38
+ {
39
+ "path": "ecommerce-core/useDbProducts.ts",
40
+ "type": "registry:hook",
41
+ "target": "$modules$/ecommerce-core/useDbProducts.ts",
42
+ "content": "import { useMemo } from 'react';\r\nimport type { Product, Category, ProductCategory } from './types';\r\nimport {\r\n useRepositoryQuery,\r\n useRawQuery,\r\n useRawQueryOne,\r\n parseStringToArray,\r\n parseJSONString,\r\n parseSQLiteBoolean,\r\n parseNumberSafe\r\n} from '@/modules/db';\r\n\r\nconst transformProduct = (row: any): Product => {\r\n const categoryNames = row.category_names ? row.category_names.split(',') : [];\r\n const categorySlugs = row.category_slugs ? row.category_slugs.split(',') : [];\r\n const categoryIds = row.category_ids ? row.category_ids.split(',').map(Number) : [];\r\n\r\n const categories: ProductCategory[] = categoryIds.map((id: number, index: number) => ({\r\n id,\r\n name: categoryNames[index] || '',\r\n slug: categorySlugs[index] || '',\r\n is_primary: index === 0\r\n }));\r\n\r\n const primaryCategory = categories.length > 0 ? categories[0] : null;\r\n\r\n return {\r\n id: parseNumberSafe(row.id),\r\n name: String(row.name || ''),\r\n slug: String(row.slug || ''),\r\n description: row.description || '',\r\n price: parseNumberSafe(row.price),\r\n sale_price: row.sale_price ? parseNumberSafe(row.sale_price) : undefined,\r\n on_sale: parseSQLiteBoolean(row.on_sale),\r\n images: parseStringToArray(row.images),\r\n brand: row.brand || '',\r\n sku: row.sku || '',\r\n stock: parseNumberSafe(row.stock),\r\n tags: parseJSONString(row.tags, []) || [],\r\n rating: parseNumberSafe(row.rating),\r\n review_count: parseNumberSafe(row.review_count),\r\n featured: parseSQLiteBoolean(row.featured),\r\n is_new: parseSQLiteBoolean(row.is_new),\r\n published: parseSQLiteBoolean(row.published),\r\n specifications: parseJSONString(row.specifications, {}) || {},\r\n variants: parseJSONString(row.variants, []) || [],\r\n created_at: row.created_at || new Date().toISOString(),\r\n updated_at: row.updated_at || new Date().toISOString(),\r\n meta_description: row.meta_description || '',\r\n meta_keywords: row.meta_keywords || '',\r\n category: primaryCategory?.slug || '',\r\n category_name: primaryCategory?.name || '',\r\n categories\r\n };\r\n};\r\n\r\nconst PRODUCTS_WITH_CATEGORIES_SQL = `\r\n SELECT p.*,\r\n GROUP_CONCAT(c.name) as category_names,\r\n GROUP_CONCAT(c.slug) as category_slugs,\r\n GROUP_CONCAT(c.id) as category_ids\r\n FROM products p\r\n LEFT JOIN product_category_relations pcr ON p.id = pcr.product_id\r\n LEFT JOIN product_categories c ON pcr.category_id = c.id\r\n WHERE p.published = 1\r\n GROUP BY p.id\r\n`;\r\n\r\nexport function useDbCategories() {\r\n const { data, isLoading: loading, error } = useRepositoryQuery<Category>('product_categories', {\r\n orderBy: [{ field: 'name', direction: 'ASC' }]\r\n });\r\n\r\n return {\r\n categories: data ?? [],\r\n loading,\r\n error: error?.message ?? null\r\n };\r\n}\r\n\r\nexport function useDbProducts() {\r\n const sql = `${PRODUCTS_WITH_CATEGORIES_SQL} ORDER BY p.name`;\r\n\r\n const { data, isLoading: loading, error } = useRawQuery<any>(\r\n ['products', 'all'],\r\n sql\r\n );\r\n\r\n const products = useMemo(() => {\r\n if (!data) return [];\r\n return data.map(transformProduct);\r\n }, [data]);\r\n\r\n return { products, loading, error: error?.message ?? null };\r\n}\r\n\r\nexport function useDbProductBySlug(slug: string) {\r\n const sql = `\r\n SELECT p.*,\r\n GROUP_CONCAT(c.name) as category_names,\r\n GROUP_CONCAT(c.slug) as category_slugs,\r\n GROUP_CONCAT(c.id) as category_ids\r\n FROM products p\r\n LEFT JOIN product_category_relations pcr ON p.id = pcr.product_id\r\n LEFT JOIN product_categories c ON pcr.category_id = c.id\r\n WHERE p.slug = ? AND p.published = 1\r\n GROUP BY p.id\r\n `;\r\n\r\n const { data, isLoading: loading, error } = useRawQueryOne<any>(\r\n ['products', 'slug', slug],\r\n sql,\r\n [slug],\r\n { enabled: !!slug }\r\n );\r\n\r\n const product = useMemo(() => {\r\n if (!data) return null;\r\n return transformProduct(data);\r\n }, [data]);\r\n\r\n return {\r\n product,\r\n loading,\r\n error: !data && !loading && slug ? 'Product not found' : (error?.message ?? null)\r\n };\r\n}\r\n\r\nexport function useDbFeaturedProducts() {\r\n const sql = `\r\n SELECT p.*,\r\n GROUP_CONCAT(c.name) as category_names,\r\n GROUP_CONCAT(c.slug) as category_slugs,\r\n GROUP_CONCAT(c.id) as category_ids\r\n FROM products p\r\n LEFT JOIN product_category_relations pcr ON p.id = pcr.product_id\r\n LEFT JOIN product_categories c ON pcr.category_id = c.id\r\n WHERE p.published = 1 AND p.featured = 1\r\n GROUP BY p.id\r\n ORDER BY p.created_at DESC LIMIT 8\r\n `;\r\n\r\n const { data, isLoading: loading, error } = useRawQuery<any>(\r\n ['products', 'featured'],\r\n sql\r\n );\r\n\r\n const products = useMemo(() => {\r\n if (!data) return [];\r\n return data.map(transformProduct);\r\n }, [data]);\r\n\r\n return { products, loading, error: error?.message ?? null };\r\n}\r\n"
43
+ },
44
+ {
45
+ "path": "ecommerce-core/useDbSearch.ts",
46
+ "type": "registry:hook",
47
+ "target": "$modules$/ecommerce-core/useDbSearch.ts",
48
+ "content": "import { useState, useEffect, useCallback } from 'react';\r\nimport type { Product } from './types';\r\nimport { useDbProducts } from './useDbProducts';\r\n\r\nexport const useDbSearch = () => {\r\n const [searchTerm, setSearchTerm] = useState('');\r\n const [results, setResults] = useState<Product[]>([]);\r\n const [isSearching, setIsSearching] = useState(false);\r\n\r\n // Load all products via useDbProducts hook\r\n const { products: allProducts } = useDbProducts();\r\n\r\n // Perform search when searchTerm changes\r\n useEffect(() => {\r\n if (!searchTerm.trim()) {\r\n setResults([]);\r\n setIsSearching(false);\r\n return;\r\n }\r\n\r\n setIsSearching(true);\r\n\r\n const searchTimeout = setTimeout(() => {\r\n const filtered = allProducts.filter(product => {\r\n const term = searchTerm.toLowerCase();\r\n \r\n // Search in product name\r\n if (product.name.toLowerCase().includes(term)) return true;\r\n \r\n // Search in description\r\n if (product.description.toLowerCase().includes(term)) return true;\r\n \r\n // Search in category\r\n if (product.category_name?.toLowerCase().includes(term)) return true;\r\n \r\n // Search in brand\r\n if (product.brand?.toLowerCase().includes(term)) return true;\r\n \r\n // Search in tags\r\n if (product.tags.some(tag => tag.toLowerCase().includes(term))) return true;\r\n \r\n return false;\r\n });\r\n\r\n setResults(filtered);\r\n setIsSearching(false);\r\n }, 300); // Debounce search\r\n\r\n return () => clearTimeout(searchTimeout);\r\n }, [searchTerm, allProducts]);\r\n\r\n const clearSearch = useCallback(() => {\r\n setSearchTerm('');\r\n setResults([]);\r\n setIsSearching(false);\r\n }, []);\r\n\r\n // search function that takes a term and sets the searchTerm\r\n const search = useCallback((term: string) => {\r\n setSearchTerm(term);\r\n }, []);\r\n\r\n return {\r\n searchTerm,\r\n setSearchTerm,\r\n results,\r\n isSearching,\r\n clearSearch,\r\n clearResults: clearSearch, // alias for header-ecommerce compatibility\r\n search, // function to trigger search\r\n hasResults: results.length > 0\r\n };\r\n};\r\n"
49
+ },
36
50
  {
37
51
  "path": "ecommerce-core/format-price.ts",
38
52
  "type": "registry:lib",
@@ -72,6 +86,7 @@
72
86
  "PaymentMethod",
73
87
  "PaymentMethodConfig",
74
88
  "Product",
89
+ "ProductCategory",
75
90
  "ProductVariant",
76
91
  "User"
77
92
  ],
@@ -86,6 +101,11 @@
86
101
  "isPaymentMethodAvailable",
87
102
  "useCart",
88
103
  "useCartStore",
104
+ "useDbCategories",
105
+ "useDbFeaturedProducts",
106
+ "useDbProductBySlug",
107
+ "useDbProducts",
108
+ "useDbSearch",
89
109
  "useFavorites",
90
110
  "useFavoritesStore"
91
111
  ]
@@ -7,7 +7,7 @@
7
7
  "ecommerce-core",
8
8
  "product-card"
9
9
  ],
10
- "usage": "import { FeaturedProducts } from '@/modules/featured-products';\n\n<FeaturedProducts />\n\n• Installed at: src/modules/featured-products/\n• Customize content: src/modules/featured-products/lang/*.json\n• Products auto-loaded via useDbList from @/db",
10
+ "usage": "import { FeaturedProducts } from '@/modules/featured-products';\n\n<FeaturedProducts />\n\n• Installed at: src/modules/featured-products/\n• Customize content: src/modules/featured-products/lang/*.json\n• Products auto-loaded via useDbProducts hook",
11
11
  "files": [
12
12
  {
13
13
  "path": "featured-products/index.ts",
@@ -19,7 +19,7 @@
19
19
  "path": "featured-products/featured-products.tsx",
20
20
  "type": "registry:component",
21
21
  "target": "$modules$/featured-products/featured-products.tsx",
22
- "content": "import { Link } from \"react-router\";\r\nimport { ArrowRight } from \"lucide-react\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { ProductCard } from \"@/modules/product-card/product-card\";\r\nimport { useTranslation } from \"react-i18next\";\r\nimport { useDbList } from \"@/db\";\r\nimport type { Product } from \"@/modules/ecommerce-core/types\";\r\n\r\ninterface FeaturedProductsProps {\r\n products?: Product[];\r\n loading?: boolean;\r\n}\r\n\r\nexport function FeaturedProducts({\r\n products: propProducts,\r\n loading: propLoading,\r\n}: FeaturedProductsProps) {\r\n const { t } = useTranslation(\"featured-products\");\r\n const { data: hookProducts = [], isLoading: hookLoading } = useDbList<Product>(\"products\", {\r\n where: { featured: 1 },\r\n limit: 8,\r\n });\r\n\r\n const products = propProducts ?? hookProducts;\r\n const loading = propLoading ?? hookLoading;\r\n\r\n return (\r\n <section className=\"py-8 sm:py-12 md:py-16 lg:py-20 bg-background border-t border-border/20 relative\">\r\n <div className=\"absolute top-0 left-1/2 transform -translate-x-1/2 w-16 sm:w-24 h-px bg-primary/30\"></div>\r\n <div className=\"w-full max-w-[var(--container-max-width)] mx-auto px-3 sm:px-4 lg:px-8\">\r\n <div className=\"text-center mb-6 sm:mb-8 md:mb-12 lg:mb-16 px-2\">\r\n <h2 className=\"text-xl sm:text-2xl md:text-3xl lg:text-4xl xl:text-5xl font-bold mb-2 sm:mb-3 md:mb-4 bg-gradient-to-r from-primary to-primary/80 bg-clip-text text-transparent leading-normal pb-1\">\r\n {t('title', 'Featured Products')}\r\n </h2>\r\n <div className=\"w-12 sm:w-16 md:w-20 h-1 bg-gradient-to-r from-primary/50 to-primary/20 mx-auto mb-3 sm:mb-4 md:mb-6 rounded-full\"></div>\r\n <p className=\"text-xs sm:text-sm md:text-base lg:text-lg xl:text-xl text-muted-foreground max-w-2xl mx-auto leading-relaxed\">\r\n {t('subtitle', 'Hand-picked favorites from our collection')}\r\n </p>\r\n </div>\r\n\r\n <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 lg:gap-8 xl:gap-10\">\r\n {loading ? (\r\n [...Array(3)].map((_, i) => (\r\n <div key={i} className=\"animate-pulse group\">\r\n <div className=\"aspect-square bg-gradient-to-br from-muted to-muted/50 rounded-2xl mb-6\"></div>\r\n <div className=\"space-y-3\">\r\n <div className=\"h-6 bg-muted rounded-lg w-3/4\"></div>\r\n <div className=\"h-4 bg-muted rounded w-1/2\"></div>\r\n <div className=\"h-5 bg-muted rounded w-2/3\"></div>\r\n </div>\r\n </div>\r\n ))\r\n ) : (\r\n products.map((product) => (\r\n <div key={product.id} className=\"contents\" data-db-table=\"products\" data-db-id={product.id}>\r\n <ProductCard\r\n product={product}\r\n variant=\"featured\"\r\n />\r\n </div>\r\n ))\r\n )}\r\n </div>\r\n\r\n <div className=\"text-center mt-8 sm:mt-12 lg:mt-16\">\r\n <Button size=\"lg\" asChild className=\"px-6 sm:px-8 py-3 sm:py-4 text-base sm:text-lg\">\r\n <Link to=\"/products\">\r\n {t('viewAll', 'View All Products')}\r\n <ArrowRight className=\"w-4 h-4 sm:w-5 sm:h-5 ml-2\" />\r\n </Link>\r\n </Button>\r\n </div>\r\n </div>\r\n </section>\r\n );\r\n}\r\n"
22
+ "content": "import { Link } from \"react-router\";\r\nimport { ArrowRight } from \"lucide-react\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { ProductCard } from \"@/modules/product-card/product-card\";\r\nimport { useTranslation } from \"react-i18next\";\r\nimport { useDbFeaturedProducts } from \"@/modules/ecommerce-core\";\r\nimport type { Product } from \"@/modules/ecommerce-core/types\";\r\n\r\ninterface FeaturedProductsProps {\r\n products?: Product[];\r\n loading?: boolean;\r\n}\r\n\r\nexport function FeaturedProducts({\r\n products: propProducts,\r\n loading: propLoading,\r\n}: FeaturedProductsProps) {\r\n const { t } = useTranslation(\"featured-products\");\r\n const { products: hookProducts, loading: hookLoading } = useDbFeaturedProducts();\r\n\r\n const products = propProducts ?? hookProducts;\r\n const loading = propLoading ?? hookLoading;\r\n\r\n return (\r\n <section className=\"py-8 sm:py-12 md:py-16 lg:py-20 bg-background border-t border-border/20 relative\">\r\n <div className=\"absolute top-0 left-1/2 transform -translate-x-1/2 w-16 sm:w-24 h-px bg-primary/30\"></div>\r\n <div className=\"w-full max-w-[var(--container-max-width)] mx-auto px-3 sm:px-4 lg:px-8\">\r\n <div className=\"text-center mb-6 sm:mb-8 md:mb-12 lg:mb-16 px-2\">\r\n <h2 className=\"text-xl sm:text-2xl md:text-3xl lg:text-4xl xl:text-5xl font-bold mb-2 sm:mb-3 md:mb-4 bg-gradient-to-r from-primary to-primary/80 bg-clip-text text-transparent leading-normal pb-1\">\r\n {t('title', 'Featured Products')}\r\n </h2>\r\n <div className=\"w-12 sm:w-16 md:w-20 h-1 bg-gradient-to-r from-primary/50 to-primary/20 mx-auto mb-3 sm:mb-4 md:mb-6 rounded-full\"></div>\r\n <p className=\"text-xs sm:text-sm md:text-base lg:text-lg xl:text-xl text-muted-foreground max-w-2xl mx-auto leading-relaxed\">\r\n {t('subtitle', 'Hand-picked favorites from our collection')}\r\n </p>\r\n </div>\r\n\r\n <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6 lg:gap-8 xl:gap-10\">\r\n {loading ? (\r\n [...Array(3)].map((_, i) => (\r\n <div key={i} className=\"animate-pulse group\">\r\n <div className=\"aspect-square bg-gradient-to-br from-muted to-muted/50 rounded-2xl mb-6\"></div>\r\n <div className=\"space-y-3\">\r\n <div className=\"h-6 bg-muted rounded-lg w-3/4\"></div>\r\n <div className=\"h-4 bg-muted rounded w-1/2\"></div>\r\n <div className=\"h-5 bg-muted rounded w-2/3\"></div>\r\n </div>\r\n </div>\r\n ))\r\n ) : (\r\n products.map((product) => (\r\n <div key={product.id} className=\"contents\" data-db-table=\"products\" data-db-id={product.id}>\r\n <ProductCard\r\n product={product}\r\n variant=\"featured\"\r\n />\r\n </div>\r\n ))\r\n )}\r\n </div>\r\n\r\n <div className=\"text-center mt-8 sm:mt-12 lg:mt-16\">\r\n <Button size=\"lg\" asChild className=\"px-6 sm:px-8 py-3 sm:py-4 text-base sm:text-lg\">\r\n <Link to=\"/products\">\r\n {t('viewAll', 'View All Products')}\r\n <ArrowRight className=\"w-4 h-4 sm:w-5 sm:h-5 ml-2\" />\r\n </Link>\r\n </Button>\r\n </div>\r\n </div>\r\n </section>\r\n );\r\n}\r\n"
23
23
  },
24
24
  {
25
25
  "path": "featured-products/lang/en.json",
@@ -23,7 +23,7 @@
23
23
  "path": "forgot-password-page-split/forgot-password-page-split.tsx",
24
24
  "type": "registry:page",
25
25
  "target": "$modules$/forgot-password-page-split/forgot-password-page-split.tsx",
26
- "content": "import { useState } from \"react\";\r\nimport { Link } from \"react-router\";\r\nimport { toast } from \"sonner\";\r\nimport { useTranslation } from \"react-i18next\";\r\nimport { usePageTitle } from \"@/hooks/use-page-title\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { Input } from \"@/components/ui/input\";\r\nimport { Label } from \"@/components/ui/label\";\r\nimport { Logo } from \"@/components/Logo\";\r\nimport { Mail, ArrowLeft, CheckCircle } from \"lucide-react\";\r\nimport { useAuth } from \"@/modules/auth-core\";\r\nimport { getErrorMessage } from \"@/modules/api\";\r\n\r\ninterface ForgotPasswordPageSplitProps {\r\n image?: string;\r\n}\r\n\r\nexport function ForgotPasswordPageSplit({\r\n image = \"/images/placeholder.png\",\r\n}: ForgotPasswordPageSplitProps) {\r\n const { t } = useTranslation(\"forgot-password-page-split\");\r\n usePageTitle({ title: t(\"title\", \"Forgot Password\") });\r\n const { forgotPassword } = useAuth();\r\n\r\n const [username, setUsername] = useState(\"\");\r\n const [isLoading, setIsLoading] = useState(false);\r\n const [error, setError] = useState<string | null>(null);\r\n const [isEmailSent, setIsEmailSent] = useState(false);\r\n\r\n const handleSubmit = async (e: React.FormEvent) => {\r\n e.preventDefault();\r\n setError(null);\r\n setIsLoading(true);\r\n\r\n try {\r\n await forgotPassword(username);\r\n\r\n setIsEmailSent(true);\r\n toast.success(t(\"emailSent\", \"Reset link sent!\"), {\r\n description: t(\"checkInbox\", \"Please check your email inbox.\"),\r\n });\r\n } catch (err) {\r\n const errorMessage = getErrorMessage(\r\n err,\r\n t(\"forgotPasswordError\", \"Failed to send reset link. Please try again.\")\r\n );\r\n setError(errorMessage);\r\n } finally {\r\n setIsLoading(false);\r\n }\r\n };\r\n\r\n // Success state - email sent\r\n if (isEmailSent) {\r\n return (\r\n <section className=\"w-full md:grid md:min-h-screen md:grid-cols-2\">\r\n <div className=\"flex items-center justify-center px-4 py-12\">\r\n <div className=\"mx-auto grid w-full max-w-sm gap-6 text-center\">\r\n <Logo />\r\n <hr />\r\n\r\n <div className=\"flex justify-center\">\r\n <div className=\"w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center\">\r\n <CheckCircle className=\"w-8 h-8 text-green-600 dark:text-green-400\" />\r\n </div>\r\n </div>\r\n\r\n <div>\r\n <h1 className=\"text-xl font-bold tracking-tight\">\r\n {t(\"checkYourEmail\", \"Check your email\")}\r\n </h1>\r\n <p className=\"text-sm text-muted-foreground mt-2\">\r\n {t(\"emailSentTo\", \"We've sent a password reset link to\")}\r\n </p>\r\n <p className=\"text-sm font-medium mt-1\">{username}</p>\r\n </div>\r\n\r\n <div className=\"text-sm text-muted-foreground\">\r\n <p>{t(\"didntReceive\", \"Didn't receive the email?\")}</p>\r\n <Button\r\n variant=\"link\"\r\n className=\"p-0 h-auto\"\r\n onClick={() => {\r\n setIsEmailSent(false);\r\n setError(null);\r\n }}\r\n >\r\n {t(\"tryAgain\", \"Click here to try again\")}\r\n </Button>\r\n </div>\r\n\r\n <Link\r\n to=\"/login\"\r\n className=\"inline-flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\r\n >\r\n <ArrowLeft className=\"w-4 h-4\" />\r\n {t(\"backToLogin\", \"Back to login\")}\r\n </Link>\r\n\r\n <hr />\r\n <p className=\"text-sm text-muted-foreground\">\r\n © {new Date().getFullYear()} {t(\"copyright\", \"All rights reserved.\")}\r\n </p>\r\n </div>\r\n </div>\r\n <div className=\"hidden p-4 md:block\">\r\n <img\r\n loading=\"lazy\"\r\n decoding=\"async\"\r\n width=\"1920\"\r\n height=\"1080\"\r\n alt={t(\"imageAlt\", \"Forgot password background\")}\r\n src={image}\r\n className=\"size-full rounded-lg border bg-muted object-cover object-center\"\r\n />\r\n </div>\r\n </section>\r\n );\r\n }\r\n\r\n return (\r\n <section className=\"w-full md:grid md:min-h-screen md:grid-cols-2\">\r\n <div className=\"flex items-center justify-center px-4 py-12\">\r\n <div className=\"mx-auto grid w-full max-w-sm gap-6\">\r\n <Logo />\r\n <hr />\r\n\r\n <div className=\"flex justify-center\">\r\n <div className=\"w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center\">\r\n <Mail className=\"w-6 h-6 text-primary\" />\r\n </div>\r\n </div>\r\n\r\n <div className=\"text-center\">\r\n <h1 className=\"text-xl font-bold tracking-tight\">\r\n {t(\"title\", \"Forgot Password\")}\r\n </h1>\r\n <p className=\"text-sm text-muted-foreground mt-1\">\r\n {t(\"subtitle\", \"Enter your username to reset your password\")}\r\n </p>\r\n </div>\r\n\r\n {error && (\r\n <div className=\"p-3 text-sm text-red-600 bg-red-50 dark:bg-red-950 dark:text-red-400 rounded-md\">\r\n {error}\r\n </div>\r\n )}\r\n\r\n <form onSubmit={handleSubmit} className=\"grid gap-4\">\r\n <div className=\"grid gap-2\">\r\n <Label htmlFor=\"username\">{t(\"username\", \"Username\")}</Label>\r\n <Input\r\n required\r\n id=\"username\"\r\n type=\"text\"\r\n autoComplete=\"username\"\r\n placeholder={t(\"usernamePlaceholder\", \"Enter your username\")}\r\n value={username}\r\n onChange={(e) => setUsername(e.target.value)}\r\n disabled={isLoading}\r\n />\r\n </div>\r\n\r\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\r\n {isLoading ? (\r\n <>\r\n <div className=\"w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2\" />\r\n {t(\"sending\", \"Sending...\")}\r\n </>\r\n ) : (\r\n t(\"sendLink\", \"Send Reset Link\")\r\n )}\r\n </Button>\r\n </form>\r\n\r\n <Link\r\n to=\"/login\"\r\n className=\"inline-flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\r\n >\r\n <ArrowLeft className=\"w-4 h-4\" />\r\n {t(\"backToLogin\", \"Back to login\")}\r\n </Link>\r\n\r\n <hr />\r\n <p className=\"text-sm text-muted-foreground\">\r\n © {new Date().getFullYear()} {t(\"copyright\", \"All rights reserved.\")}\r\n </p>\r\n </div>\r\n </div>\r\n <div className=\"hidden p-4 md:block\">\r\n <img\r\n loading=\"lazy\"\r\n decoding=\"async\"\r\n width=\"1920\"\r\n height=\"1080\"\r\n alt={t(\"imageAlt\", \"Forgot password background\")}\r\n src={image}\r\n className=\"size-full rounded-lg border bg-muted object-cover object-center\"\r\n />\r\n </div>\r\n </section>\r\n );\r\n}\r\n\r\nexport default ForgotPasswordPageSplit;\r\n"
26
+ "content": "import { useState } from \"react\";\r\nimport { Link } from \"react-router\";\r\nimport { toast } from \"sonner\";\r\nimport { useTranslation } from \"react-i18next\";\r\nimport { usePageTitle } from \"@/hooks/use-page-title\";\r\nimport { Button } from \"@/components/ui/button\";\r\nimport { Input } from \"@/components/ui/input\";\r\nimport { Logo } from \"@/components/Logo\";\r\nimport { Mail, ArrowLeft, CheckCircle } from \"lucide-react\";\r\nimport { useAuth } from \"@/modules/auth-core\";\r\nimport { getErrorMessage } from \"@/modules/api\";\r\nimport { FormField } from \"@/components/FormField\";\r\n\r\ninterface ForgotPasswordPageSplitProps {\r\n image?: string;\r\n}\r\n\r\nexport function ForgotPasswordPageSplit({\r\n image = \"/images/placeholder.png\",\r\n}: ForgotPasswordPageSplitProps) {\r\n const { t } = useTranslation(\"forgot-password-page-split\");\r\n usePageTitle({ title: t(\"title\", \"Forgot Password\") });\r\n const { forgotPassword } = useAuth();\r\n\r\n const [username, setUsername] = useState(\"\");\r\n const [isLoading, setIsLoading] = useState(false);\r\n const [error, setError] = useState<string | null>(null);\r\n const [isEmailSent, setIsEmailSent] = useState(false);\r\n\r\n const handleSubmit = async (e: React.FormEvent) => {\r\n e.preventDefault();\r\n setError(null);\r\n setIsLoading(true);\r\n\r\n try {\r\n await forgotPassword(username);\r\n\r\n setIsEmailSent(true);\r\n toast.success(t(\"emailSent\", \"Reset link sent!\"), {\r\n description: t(\"checkInbox\", \"Please check your email inbox.\"),\r\n });\r\n } catch (err) {\r\n const errorMessage = getErrorMessage(\r\n err,\r\n t(\"forgotPasswordError\", \"Failed to send reset link. Please try again.\")\r\n );\r\n setError(errorMessage);\r\n } finally {\r\n setIsLoading(false);\r\n }\r\n };\r\n\r\n // Success state - email sent\r\n if (isEmailSent) {\r\n return (\r\n <section className=\"w-full md:grid md:min-h-screen md:grid-cols-2\">\r\n <div className=\"flex items-center justify-center px-4 py-12\">\r\n <div className=\"mx-auto grid w-full max-w-sm gap-6 text-center\">\r\n <Logo />\r\n <hr />\r\n\r\n <div className=\"flex justify-center\">\r\n <div className=\"w-16 h-16 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center\">\r\n <CheckCircle className=\"w-8 h-8 text-green-600 dark:text-green-400\" />\r\n </div>\r\n </div>\r\n\r\n <div>\r\n <h1 className=\"text-xl font-bold tracking-tight\">\r\n {t(\"checkYourEmail\", \"Check your email\")}\r\n </h1>\r\n <p className=\"text-sm text-muted-foreground mt-2\">\r\n {t(\"emailSentTo\", \"We've sent a password reset link to\")}\r\n </p>\r\n <p className=\"text-sm font-medium mt-1\">{username}</p>\r\n </div>\r\n\r\n <div className=\"text-sm text-muted-foreground\">\r\n <p>{t(\"didntReceive\", \"Didn't receive the email?\")}</p>\r\n <Button\r\n variant=\"link\"\r\n className=\"p-0 h-auto\"\r\n onClick={() => {\r\n setIsEmailSent(false);\r\n setError(null);\r\n }}\r\n >\r\n {t(\"tryAgain\", \"Click here to try again\")}\r\n </Button>\r\n </div>\r\n\r\n <Link\r\n to=\"/login\"\r\n className=\"inline-flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\r\n >\r\n <ArrowLeft className=\"w-4 h-4\" />\r\n {t(\"backToLogin\", \"Back to login\")}\r\n </Link>\r\n\r\n <hr />\r\n <p className=\"text-sm text-muted-foreground\">\r\n © {new Date().getFullYear()} {t(\"copyright\", \"All rights reserved.\")}\r\n </p>\r\n </div>\r\n </div>\r\n <div className=\"hidden p-4 md:block\">\r\n <img\r\n loading=\"lazy\"\r\n decoding=\"async\"\r\n width=\"1920\"\r\n height=\"1080\"\r\n alt={t(\"imageAlt\", \"Forgot password background\")}\r\n src={image}\r\n className=\"size-full rounded-lg border bg-muted object-cover object-center\"\r\n />\r\n </div>\r\n </section>\r\n );\r\n }\r\n\r\n return (\r\n <section className=\"w-full md:grid md:min-h-screen md:grid-cols-2\">\r\n <div className=\"flex items-center justify-center px-4 py-12\">\r\n <div className=\"mx-auto grid w-full max-w-sm gap-6\">\r\n <Logo />\r\n <hr />\r\n\r\n <div className=\"flex justify-center\">\r\n <div className=\"w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center\">\r\n <Mail className=\"w-6 h-6 text-primary\" />\r\n </div>\r\n </div>\r\n\r\n <div className=\"text-center\">\r\n <h1 className=\"text-xl font-bold tracking-tight\">\r\n {t(\"title\", \"Forgot Password\")}\r\n </h1>\r\n <p className=\"text-sm text-muted-foreground mt-1\">\r\n {t(\"subtitle\", \"Enter your username to reset your password\")}\r\n </p>\r\n </div>\r\n\r\n {error && (\r\n <div className=\"p-3 text-sm text-red-600 bg-red-50 dark:bg-red-950 dark:text-red-400 rounded-md\">\r\n {error}\r\n </div>\r\n )}\r\n\r\n <form onSubmit={handleSubmit} className=\"grid gap-4\">\r\n <div className=\"grid gap-2\">\r\n <FormField label={t(\"username\", \"Username\")} htmlFor=\"username\" required>\r\n <Input\r\n required\r\n id=\"username\"\r\n type=\"text\"\r\n autoComplete=\"username\"\r\n placeholder={t(\"usernamePlaceholder\", \"Enter your username\")}\r\n value={username}\r\n onChange={(e) => setUsername(e.target.value)}\r\n disabled={isLoading}\r\n />\r\n </FormField>\r\n </div>\r\n\r\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\r\n {isLoading ? (\r\n <>\r\n <div className=\"w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2\" />\r\n {t(\"sending\", \"Sending...\")}\r\n </>\r\n ) : (\r\n t(\"sendLink\", \"Send Reset Link\")\r\n )}\r\n </Button>\r\n </form>\r\n\r\n <Link\r\n to=\"/login\"\r\n className=\"inline-flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground\"\r\n >\r\n <ArrowLeft className=\"w-4 h-4\" />\r\n {t(\"backToLogin\", \"Back to login\")}\r\n </Link>\r\n\r\n <hr />\r\n <p className=\"text-sm text-muted-foreground\">\r\n © {new Date().getFullYear()} {t(\"copyright\", \"All rights reserved.\")}\r\n </p>\r\n </div>\r\n </div>\r\n <div className=\"hidden p-4 md:block\">\r\n <img\r\n loading=\"lazy\"\r\n decoding=\"async\"\r\n width=\"1920\"\r\n height=\"1080\"\r\n alt={t(\"imageAlt\", \"Forgot password background\")}\r\n src={image}\r\n className=\"size-full rounded-lg border bg-muted object-cover object-center\"\r\n />\r\n </div>\r\n </section>\r\n );\r\n}\r\n\r\nexport default ForgotPasswordPageSplit;\r\n"
27
27
  },
28
28
  {
29
29
  "path": "forgot-password-page-split/lang/en.json",