@promakeai/cli 0.4.7 → 0.5.0
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.
- package/README.md +71 -0
- package/dist/index.js +161 -168
- package/dist/registry/blog-core.json +7 -26
- package/dist/registry/blog-list-page.json +2 -2
- package/dist/registry/blog-section.json +1 -1
- package/dist/registry/cart-drawer.json +1 -1
- package/dist/registry/cart-page.json +1 -1
- package/dist/registry/category-section.json +1 -1
- package/dist/registry/checkout-page.json +1 -1
- package/dist/registry/contact-page-centered.json +1 -1
- package/dist/registry/contact-page-map-overlay.json +1 -1
- package/dist/registry/contact-page-map-split.json +1 -1
- package/dist/registry/contact-page-split.json +1 -1
- package/dist/registry/contact-page.json +1 -1
- package/dist/registry/docs/blog-core.md +12 -13
- package/dist/registry/docs/blog-list-page.md +1 -1
- package/dist/registry/docs/ecommerce-core.md +10 -13
- package/dist/registry/docs/featured-products.md +1 -1
- package/dist/registry/docs/post-detail-page.md +2 -2
- package/dist/registry/docs/product-detail-page.md +2 -2
- package/dist/registry/docs/products-page.md +1 -1
- package/dist/registry/ecommerce-core.json +5 -25
- package/dist/registry/featured-products.json +2 -2
- package/dist/registry/forgot-password-page-split.json +1 -1
- package/dist/registry/forgot-password-page.json +1 -1
- package/dist/registry/header-centered-pill.json +1 -1
- package/dist/registry/header-ecommerce.json +1 -1
- package/dist/registry/index.json +0 -1
- package/dist/registry/login-page-split.json +1 -1
- package/dist/registry/login-page.json +1 -1
- package/dist/registry/newsletter-section.json +1 -1
- package/dist/registry/post-card.json +1 -1
- package/dist/registry/post-detail-block.json +1 -1
- package/dist/registry/post-detail-page.json +3 -3
- package/dist/registry/product-card-detailed.json +1 -1
- package/dist/registry/product-card.json +1 -1
- package/dist/registry/product-detail-block.json +1 -1
- package/dist/registry/product-detail-page.json +3 -3
- package/dist/registry/product-detail-section.json +1 -1
- package/dist/registry/product-quick-view.json +1 -1
- package/dist/registry/products-page.json +2 -2
- package/dist/registry/register-page-split.json +1 -1
- package/dist/registry/register-page.json +1 -1
- package/dist/registry/related-products-block.json +1 -1
- package/dist/registry/reset-password-page-split.json +1 -1
- package/package.json +4 -2
- package/template/README.md +39 -58
- package/template/package.json +4 -3
- package/template/public/data/database.db +0 -0
- package/template/public/data/database.db-shm +0 -0
- package/template/public/data/database.db-wal +0 -0
- package/template/scripts/init-db.ts +13 -126
- package/template/src/App.tsx +8 -5
- package/template/src/components/FormField.tsx +5 -11
- package/template/src/db/index.ts +20 -0
- package/template/src/db/provider.tsx +77 -0
- package/template/src/db/schema.json +259 -0
- package/template/src/db/types.ts +195 -0
- package/template/src/hooks/use-debounced-value.ts +12 -0
- package/dist/registry/db.json +0 -129
- package/template/src/PasswordInput.tsx +0 -61
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Auto-generated from schemas - DO NOT EDIT
|
|
2
|
+
|
|
3
|
+
// From promake schema
|
|
4
|
+
export interface DbBlogCategory {
|
|
5
|
+
id?: number;
|
|
6
|
+
name: string;
|
|
7
|
+
slug: string;
|
|
8
|
+
description?: string;
|
|
9
|
+
image?: string;
|
|
10
|
+
created_at?: string;
|
|
11
|
+
updated_at?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface DbBlogCategoryTranslation {
|
|
15
|
+
id: number;
|
|
16
|
+
blog_category_id: number;
|
|
17
|
+
language_code: string;
|
|
18
|
+
name: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
created_at?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DbBlogCategoryInput {
|
|
24
|
+
id?: number;
|
|
25
|
+
slug: string;
|
|
26
|
+
image?: string;
|
|
27
|
+
created_at?: string;
|
|
28
|
+
updated_at?: string;
|
|
29
|
+
translations?: Record<string, {
|
|
30
|
+
name: string;
|
|
31
|
+
description?: string;
|
|
32
|
+
}>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface DbPost {
|
|
36
|
+
id?: number;
|
|
37
|
+
title: string;
|
|
38
|
+
slug: string;
|
|
39
|
+
content: string;
|
|
40
|
+
excerpt?: string;
|
|
41
|
+
featured_image?: string;
|
|
42
|
+
images?: string[];
|
|
43
|
+
author?: string;
|
|
44
|
+
author_avatar?: string;
|
|
45
|
+
created_at?: string;
|
|
46
|
+
published_at?: string;
|
|
47
|
+
updated_at?: string;
|
|
48
|
+
tags?: string[];
|
|
49
|
+
categories?: number[];
|
|
50
|
+
read_time?: number;
|
|
51
|
+
view_count?: number;
|
|
52
|
+
featured?: boolean;
|
|
53
|
+
published?: boolean;
|
|
54
|
+
meta_description?: string;
|
|
55
|
+
meta_keywords?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface DbPostTranslation {
|
|
59
|
+
id: number;
|
|
60
|
+
post_id: number;
|
|
61
|
+
language_code: string;
|
|
62
|
+
title: string;
|
|
63
|
+
content: string;
|
|
64
|
+
excerpt?: string;
|
|
65
|
+
author?: string;
|
|
66
|
+
meta_description?: string;
|
|
67
|
+
meta_keywords?: string;
|
|
68
|
+
created_at?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface DbPostInput {
|
|
72
|
+
id?: number;
|
|
73
|
+
slug: string;
|
|
74
|
+
featured_image?: string;
|
|
75
|
+
images?: string[];
|
|
76
|
+
author_avatar?: string;
|
|
77
|
+
created_at?: string;
|
|
78
|
+
published_at?: string;
|
|
79
|
+
updated_at?: string;
|
|
80
|
+
tags?: string[];
|
|
81
|
+
categories?: number[];
|
|
82
|
+
read_time?: number;
|
|
83
|
+
view_count?: number;
|
|
84
|
+
featured?: boolean;
|
|
85
|
+
published?: boolean;
|
|
86
|
+
translations?: Record<string, {
|
|
87
|
+
title: string;
|
|
88
|
+
content: string;
|
|
89
|
+
excerpt?: string;
|
|
90
|
+
author?: string;
|
|
91
|
+
meta_description?: string;
|
|
92
|
+
meta_keywords?: string;
|
|
93
|
+
}>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface DbProductCategory {
|
|
97
|
+
id?: number;
|
|
98
|
+
name: string;
|
|
99
|
+
slug: string;
|
|
100
|
+
description?: string;
|
|
101
|
+
image?: string;
|
|
102
|
+
parent_id?: number;
|
|
103
|
+
created_at?: string;
|
|
104
|
+
updated_at?: string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface DbProductCategoryTranslation {
|
|
108
|
+
id: number;
|
|
109
|
+
product_category_id: number;
|
|
110
|
+
language_code: string;
|
|
111
|
+
name: string;
|
|
112
|
+
description?: string;
|
|
113
|
+
created_at?: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface DbProductCategoryInput {
|
|
117
|
+
id?: number;
|
|
118
|
+
slug: string;
|
|
119
|
+
image?: string;
|
|
120
|
+
parent_id?: number;
|
|
121
|
+
created_at?: string;
|
|
122
|
+
updated_at?: string;
|
|
123
|
+
translations?: Record<string, {
|
|
124
|
+
name: string;
|
|
125
|
+
description?: string;
|
|
126
|
+
}>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface DbProduct {
|
|
130
|
+
id?: number;
|
|
131
|
+
name: string;
|
|
132
|
+
slug: string;
|
|
133
|
+
description?: string;
|
|
134
|
+
price: number;
|
|
135
|
+
sale_price?: number;
|
|
136
|
+
on_sale?: boolean;
|
|
137
|
+
images?: string[];
|
|
138
|
+
brand?: string;
|
|
139
|
+
sku?: string;
|
|
140
|
+
stock?: number;
|
|
141
|
+
tags?: string[];
|
|
142
|
+
categories?: number[];
|
|
143
|
+
rating?: number;
|
|
144
|
+
review_count?: number;
|
|
145
|
+
featured?: boolean;
|
|
146
|
+
is_new?: boolean;
|
|
147
|
+
published?: boolean;
|
|
148
|
+
specifications?: Record<string, unknown>;
|
|
149
|
+
variants?: Array<{ id: string; name: string; value: string; price?: number; image?: string; stockQuantity: number }>;
|
|
150
|
+
created_at?: string;
|
|
151
|
+
updated_at?: string;
|
|
152
|
+
meta_description?: string;
|
|
153
|
+
meta_keywords?: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface DbProductTranslation {
|
|
157
|
+
id: number;
|
|
158
|
+
product_id: number;
|
|
159
|
+
language_code: string;
|
|
160
|
+
name: string;
|
|
161
|
+
description?: string;
|
|
162
|
+
brand?: string;
|
|
163
|
+
meta_description?: string;
|
|
164
|
+
meta_keywords?: string;
|
|
165
|
+
created_at?: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface DbProductInput {
|
|
169
|
+
id?: number;
|
|
170
|
+
slug: string;
|
|
171
|
+
price: number;
|
|
172
|
+
sale_price?: number;
|
|
173
|
+
on_sale?: boolean;
|
|
174
|
+
images?: string[];
|
|
175
|
+
sku?: string;
|
|
176
|
+
stock?: number;
|
|
177
|
+
tags?: string[];
|
|
178
|
+
categories?: number[];
|
|
179
|
+
rating?: number;
|
|
180
|
+
review_count?: number;
|
|
181
|
+
featured?: boolean;
|
|
182
|
+
is_new?: boolean;
|
|
183
|
+
published?: boolean;
|
|
184
|
+
specifications?: Record<string, unknown>;
|
|
185
|
+
variants?: Array<{ id: string; name: string; value: string; price?: number; image?: string; stockQuantity: number }>;
|
|
186
|
+
created_at?: string;
|
|
187
|
+
updated_at?: string;
|
|
188
|
+
translations?: Record<string, {
|
|
189
|
+
name: string;
|
|
190
|
+
description?: string;
|
|
191
|
+
brand?: string;
|
|
192
|
+
meta_description?: string;
|
|
193
|
+
meta_keywords?: string;
|
|
194
|
+
}>;
|
|
195
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { useState, useEffect } from "react";
|
|
2
|
+
|
|
3
|
+
export function useDebouncedValue<T>(value: T, delay = 300): T {
|
|
4
|
+
const [debounced, setDebounced] = useState(value);
|
|
5
|
+
|
|
6
|
+
useEffect(() => {
|
|
7
|
+
const timer = setTimeout(() => setDebounced(value), delay);
|
|
8
|
+
return () => clearTimeout(timer);
|
|
9
|
+
}, [value, delay]);
|
|
10
|
+
|
|
11
|
+
return debounced;
|
|
12
|
+
}
|
package/dist/registry/db.json
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
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,61 +0,0 @@
|
|
|
1
|
-
import { useState } from "react";
|
|
2
|
-
import { Input } from "@/components/ui/input";
|
|
3
|
-
import { Eye, EyeOff } from "lucide-react";
|
|
4
|
-
|
|
5
|
-
interface PasswordInputProps {
|
|
6
|
-
id?: string;
|
|
7
|
-
name?: string;
|
|
8
|
-
value: string;
|
|
9
|
-
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
|
10
|
-
placeholder?: string;
|
|
11
|
-
required?: boolean;
|
|
12
|
-
autoComplete?: string;
|
|
13
|
-
className?: string;
|
|
14
|
-
disabled?: boolean;
|
|
15
|
-
minLength?: number;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function PasswordInput({
|
|
19
|
-
id = "password",
|
|
20
|
-
name = "password",
|
|
21
|
-
value,
|
|
22
|
-
onChange,
|
|
23
|
-
placeholder = "Enter password",
|
|
24
|
-
required = false,
|
|
25
|
-
autoComplete = "current-password",
|
|
26
|
-
disabled = false,
|
|
27
|
-
minLength = undefined,
|
|
28
|
-
className = "",
|
|
29
|
-
}: PasswordInputProps) {
|
|
30
|
-
const [showPassword, setShowPassword] = useState(false);
|
|
31
|
-
|
|
32
|
-
return (
|
|
33
|
-
<div className="relative">
|
|
34
|
-
<Input
|
|
35
|
-
id={id}
|
|
36
|
-
name={name}
|
|
37
|
-
type={showPassword ? "text" : "password"}
|
|
38
|
-
value={value}
|
|
39
|
-
onChange={onChange}
|
|
40
|
-
placeholder={placeholder}
|
|
41
|
-
required={required}
|
|
42
|
-
className={`mt-1 pr-10 ${className}`}
|
|
43
|
-
autoComplete={autoComplete}
|
|
44
|
-
disabled={disabled}
|
|
45
|
-
minLength={minLength}
|
|
46
|
-
/>
|
|
47
|
-
<button
|
|
48
|
-
type="button"
|
|
49
|
-
onClick={() => setShowPassword(!showPassword)}
|
|
50
|
-
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
|
51
|
-
aria-label={showPassword ? "Hide password" : "Show password"}
|
|
52
|
-
>
|
|
53
|
-
{showPassword ? (
|
|
54
|
-
<EyeOff className="w-4 h-4" />
|
|
55
|
-
) : (
|
|
56
|
-
<Eye className="w-4 h-4" />
|
|
57
|
-
)}
|
|
58
|
-
</button>
|
|
59
|
-
</div>
|
|
60
|
-
);
|
|
61
|
-
}
|