@hivehub/rulebook 2.1.0 → 3.0.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.
Files changed (187) hide show
  1. package/README.md +779 -661
  2. package/dist/cli/commands.d.ts +22 -0
  3. package/dist/cli/commands.d.ts.map +1 -1
  4. package/dist/cli/commands.js +291 -8
  5. package/dist/cli/commands.js.map +1 -1
  6. package/dist/core/claude-mcp.d.ts +32 -0
  7. package/dist/core/claude-mcp.d.ts.map +1 -0
  8. package/dist/core/claude-mcp.js +92 -0
  9. package/dist/core/claude-mcp.js.map +1 -0
  10. package/dist/core/config-manager.d.ts.map +1 -1
  11. package/dist/core/config-manager.js +27 -6
  12. package/dist/core/config-manager.js.map +1 -1
  13. package/dist/core/generator.d.ts.map +1 -1
  14. package/dist/core/generator.js +98 -49
  15. package/dist/core/generator.js.map +1 -1
  16. package/dist/core/migrator.d.ts +13 -0
  17. package/dist/core/migrator.d.ts.map +1 -1
  18. package/dist/core/migrator.js +76 -9
  19. package/dist/core/migrator.js.map +1 -1
  20. package/dist/core/openspec-migrator.d.ts +1 -1
  21. package/dist/core/openspec-migrator.d.ts.map +1 -1
  22. package/dist/core/openspec-migrator.js +14 -7
  23. package/dist/core/openspec-migrator.js.map +1 -1
  24. package/dist/core/workflow-generator.js +297 -261
  25. package/dist/core/workflow-generator.js.map +1 -1
  26. package/dist/index.js +40 -1
  27. package/dist/index.js.map +1 -1
  28. package/dist/mcp/rulebook-server.d.ts.map +1 -1
  29. package/dist/mcp/rulebook-server.js +255 -74
  30. package/dist/mcp/rulebook-server.js.map +1 -1
  31. package/dist/memory/hnsw-index.d.ts +63 -0
  32. package/dist/memory/hnsw-index.d.ts.map +1 -0
  33. package/dist/memory/hnsw-index.js +421 -0
  34. package/dist/memory/hnsw-index.js.map +1 -0
  35. package/dist/memory/memory-cache.d.ts +33 -0
  36. package/dist/memory/memory-cache.d.ts.map +1 -0
  37. package/dist/memory/memory-cache.js +85 -0
  38. package/dist/memory/memory-cache.js.map +1 -0
  39. package/dist/memory/memory-hooks.d.ts +42 -0
  40. package/dist/memory/memory-hooks.d.ts.map +1 -0
  41. package/dist/memory/memory-hooks.js +193 -0
  42. package/dist/memory/memory-hooks.js.map +1 -0
  43. package/dist/memory/memory-manager.d.ts +55 -0
  44. package/dist/memory/memory-manager.d.ts.map +1 -0
  45. package/dist/memory/memory-manager.js +209 -0
  46. package/dist/memory/memory-manager.js.map +1 -0
  47. package/dist/memory/memory-search.d.ts +42 -0
  48. package/dist/memory/memory-search.d.ts.map +1 -0
  49. package/dist/memory/memory-search.js +166 -0
  50. package/dist/memory/memory-search.js.map +1 -0
  51. package/dist/memory/memory-store.d.ts +59 -0
  52. package/dist/memory/memory-store.d.ts.map +1 -0
  53. package/dist/memory/memory-store.js +394 -0
  54. package/dist/memory/memory-store.js.map +1 -0
  55. package/dist/memory/memory-types.d.ts +69 -0
  56. package/dist/memory/memory-types.d.ts.map +1 -0
  57. package/dist/memory/memory-types.js +7 -0
  58. package/dist/memory/memory-types.js.map +1 -0
  59. package/dist/memory/memory-vectorizer.d.ts +29 -0
  60. package/dist/memory/memory-vectorizer.d.ts.map +1 -0
  61. package/dist/memory/memory-vectorizer.js +104 -0
  62. package/dist/memory/memory-vectorizer.js.map +1 -0
  63. package/dist/types.d.ts +7 -0
  64. package/dist/types.d.ts.map +1 -1
  65. package/package.json +107 -106
  66. package/templates/commands/rulebook-memory-save.md +48 -0
  67. package/templates/commands/rulebook-memory-search.md +47 -0
  68. package/templates/commands/rulebook-task-apply.md +2 -2
  69. package/templates/commands/rulebook-task-archive.md +2 -2
  70. package/templates/commands/rulebook-task-create.md +2 -2
  71. package/templates/commands/rulebook-task-list.md +2 -2
  72. package/templates/commands/rulebook-task-show.md +2 -2
  73. package/templates/commands/rulebook-task-validate.md +2 -2
  74. package/templates/git/CI_CD_PATTERNS.md +4 -4
  75. package/templates/git/GITHUB_ACTIONS.md +3 -3
  76. package/templates/git/GITLAB_CI.md +4 -4
  77. package/templates/git/SECRETS_MANAGEMENT.md +4 -4
  78. package/templates/hooks/COMMIT_MSG.md +4 -4
  79. package/templates/hooks/POST_CHECKOUT.md +3 -3
  80. package/templates/hooks/PREPARE_COMMIT_MSG.md +3 -3
  81. package/templates/hooks/PRE_COMMIT.md +4 -4
  82. package/templates/hooks/PRE_PUSH.md +4 -4
  83. package/templates/modules/MEMORY.md +63 -0
  84. package/templates/skills/cli/aider/SKILL.md +59 -0
  85. package/templates/skills/cli/amazon-q/SKILL.md +35 -0
  86. package/templates/skills/cli/auggie/SKILL.md +42 -0
  87. package/templates/skills/cli/claude/SKILL.md +42 -0
  88. package/templates/skills/cli/claude-code/SKILL.md +146 -0
  89. package/templates/skills/cli/cline/SKILL.md +42 -0
  90. package/templates/skills/cli/codebuddy/SKILL.md +30 -0
  91. package/templates/skills/cli/codeium/SKILL.md +30 -0
  92. package/templates/skills/cli/codex/SKILL.md +31 -0
  93. package/templates/skills/cli/continue/SKILL.md +44 -0
  94. package/templates/skills/cli/cursor-cli/SKILL.md +38 -0
  95. package/templates/skills/cli/factory/SKILL.md +28 -0
  96. package/templates/skills/cli/gemini/SKILL.md +45 -0
  97. package/templates/skills/cli/kilocode/SKILL.md +28 -0
  98. package/templates/skills/cli/opencode/SKILL.md +28 -0
  99. package/templates/skills/core/agent-automation/SKILL.md +194 -0
  100. package/templates/skills/core/dag/SKILL.md +314 -0
  101. package/templates/skills/core/documentation-rules/SKILL.md +47 -0
  102. package/templates/skills/core/quality-enforcement/SKILL.md +78 -0
  103. package/templates/skills/frameworks/angular/SKILL.md +46 -0
  104. package/templates/skills/frameworks/django/SKILL.md +93 -0
  105. package/templates/skills/frameworks/electron/SKILL.md +157 -0
  106. package/templates/skills/frameworks/flask/SKILL.md +48 -0
  107. package/templates/skills/frameworks/flutter/SKILL.md +65 -0
  108. package/templates/skills/frameworks/jquery/SKILL.md +42 -0
  109. package/templates/skills/frameworks/laravel/SKILL.md +48 -0
  110. package/templates/skills/frameworks/nestjs/SKILL.md +53 -0
  111. package/templates/skills/frameworks/nextjs/SKILL.md +137 -0
  112. package/templates/skills/frameworks/nuxt/SKILL.md +50 -0
  113. package/templates/skills/frameworks/rails/SKILL.md +76 -0
  114. package/templates/skills/frameworks/react/SKILL.md +48 -0
  115. package/templates/skills/frameworks/react-native/SKILL.md +57 -0
  116. package/templates/skills/frameworks/spring/SKILL.md +49 -0
  117. package/templates/skills/frameworks/symfony/SKILL.md +46 -0
  118. package/templates/skills/frameworks/vue/SKILL.md +46 -0
  119. package/templates/skills/frameworks/zend/SKILL.md +45 -0
  120. package/templates/skills/ides/copilot/SKILL.md +47 -0
  121. package/templates/skills/ides/cursor/SKILL.md +53 -0
  122. package/templates/skills/ides/jetbrains-ai/SKILL.md +45 -0
  123. package/templates/skills/ides/replit/SKILL.md +46 -0
  124. package/templates/skills/ides/tabnine/SKILL.md +39 -0
  125. package/templates/skills/ides/vscode/SKILL.md +50 -0
  126. package/templates/skills/ides/windsurf/SKILL.md +46 -0
  127. package/templates/skills/ides/zed/SKILL.md +42 -0
  128. package/templates/skills/languages/ada/SKILL.md +68 -0
  129. package/templates/skills/languages/c/SKILL.md +343 -0
  130. package/templates/skills/languages/cpp/SKILL.md +753 -0
  131. package/templates/skills/languages/csharp/SKILL.md +427 -0
  132. package/templates/skills/languages/dart/SKILL.md +342 -0
  133. package/templates/skills/languages/elixir/SKILL.md +464 -0
  134. package/templates/skills/languages/erlang/SKILL.md +371 -0
  135. package/templates/skills/languages/go/SKILL.md +655 -0
  136. package/templates/skills/languages/haskell/SKILL.md +187 -0
  137. package/templates/skills/languages/java/SKILL.md +617 -0
  138. package/templates/skills/languages/javascript/SKILL.md +641 -0
  139. package/templates/skills/languages/julia/SKILL.md +107 -0
  140. package/templates/skills/languages/kotlin/SKILL.md +521 -0
  141. package/templates/skills/languages/lisp/SKILL.md +110 -0
  142. package/templates/skills/languages/lua/SKILL.md +84 -0
  143. package/templates/skills/languages/objectivec/SKILL.md +100 -0
  144. package/templates/skills/languages/php/SKILL.md +426 -0
  145. package/templates/skills/languages/python/SKILL.md +692 -0
  146. package/templates/skills/languages/r/SKILL.md +360 -0
  147. package/templates/skills/languages/ruby/SKILL.md +431 -0
  148. package/templates/skills/languages/rust/SKILL.md +487 -0
  149. package/templates/skills/languages/sas/SKILL.md +83 -0
  150. package/templates/skills/languages/scala/SKILL.md +358 -0
  151. package/templates/skills/languages/solidity/SKILL.md +590 -0
  152. package/templates/skills/languages/sql/SKILL.md +147 -0
  153. package/templates/skills/languages/swift/SKILL.md +476 -0
  154. package/templates/skills/languages/zig/SKILL.md +275 -0
  155. package/templates/skills/modules/atlassian/SKILL.md +265 -0
  156. package/templates/skills/modules/context7/SKILL.md +64 -0
  157. package/templates/skills/modules/figma/SKILL.md +277 -0
  158. package/templates/skills/modules/github-mcp/SKILL.md +74 -0
  159. package/templates/skills/modules/grafana/SKILL.md +338 -0
  160. package/templates/skills/modules/memory/SKILL.md +73 -0
  161. package/templates/skills/modules/notion/SKILL.md +257 -0
  162. package/templates/skills/modules/playwright/SKILL.md +100 -0
  163. package/templates/skills/modules/rulebook-mcp/SKILL.md +166 -0
  164. package/templates/skills/modules/serena/SKILL.md +347 -0
  165. package/templates/skills/modules/supabase/SKILL.md +233 -0
  166. package/templates/skills/modules/synap/SKILL.md +79 -0
  167. package/templates/skills/modules/vectorizer/SKILL.md +73 -0
  168. package/templates/skills/services/azure-blob/SKILL.md +194 -0
  169. package/templates/skills/services/cassandra/SKILL.md +249 -0
  170. package/templates/skills/services/dynamodb/SKILL.md +318 -0
  171. package/templates/skills/services/elasticsearch/SKILL.md +357 -0
  172. package/templates/skills/services/gcs/SKILL.md +188 -0
  173. package/templates/skills/services/influxdb/SKILL.md +275 -0
  174. package/templates/skills/services/kafka/SKILL.md +351 -0
  175. package/templates/skills/services/mariadb/SKILL.md +193 -0
  176. package/templates/skills/services/memcached/SKILL.md +252 -0
  177. package/templates/skills/services/minio/SKILL.md +211 -0
  178. package/templates/skills/services/mongodb/SKILL.md +278 -0
  179. package/templates/skills/services/mysql/SKILL.md +368 -0
  180. package/templates/skills/services/neo4j/SKILL.md +257 -0
  181. package/templates/skills/services/oracle/SKILL.md +300 -0
  182. package/templates/skills/services/postgresql/SKILL.md +336 -0
  183. package/templates/skills/services/rabbitmq/SKILL.md +296 -0
  184. package/templates/skills/services/redis/SKILL.md +302 -0
  185. package/templates/skills/services/s3/SKILL.md +308 -0
  186. package/templates/skills/services/sqlite/SKILL.md +304 -0
  187. package/templates/skills/services/sqlserver/SKILL.md +304 -0
@@ -0,0 +1,304 @@
1
+ ---
2
+ name: "SQLite"
3
+ description: "Use SQLite for embedded databases, local storage, development, and small-scale applications with zero configuration."
4
+ version: "1.0.0"
5
+ category: "services"
6
+ author: "Rulebook"
7
+ tags: ["services", "database"]
8
+ dependencies: []
9
+ conflicts: []
10
+ ---
11
+ <!-- SQLITE:START -->
12
+ # SQLite Database Instructions
13
+
14
+ **CRITICAL**: Use SQLite for embedded databases, local storage, development, and small-scale applications with zero configuration.
15
+
16
+ ## Core Features
17
+
18
+ ### Connection
19
+ ```typescript
20
+ // Using better-sqlite3 (synchronous, faster)
21
+ import Database from 'better-sqlite3'
22
+
23
+ const db = new Database(process.env.DB_PATH || './database.db', {
24
+ verbose: process.env.NODE_ENV === 'development' ? console.log : undefined,
25
+ })
26
+
27
+ // Using sqlite3 (asynchronous)
28
+ import sqlite3 from 'sqlite3'
29
+
30
+ const db = new sqlite3.Database(process.env.DB_PATH || './database.db', (err) => {
31
+ if (err) {
32
+ console.error('Error opening database', err)
33
+ }
34
+ })
35
+
36
+ // Using better-sqlite3 with WAL mode (recommended)
37
+ const db = new Database('./database.db')
38
+ db.pragma('journal_mode = WAL') // Write-Ahead Logging
39
+ db.pragma('foreign_keys = ON') // Enable foreign keys
40
+ ```
41
+
42
+ ### Basic Queries
43
+ ```typescript
44
+ // Using better-sqlite3 (synchronous)
45
+ // SELECT
46
+ const stmt = db.prepare('SELECT * FROM users WHERE id = ?')
47
+ const user = stmt.get(userId)
48
+
49
+ // INSERT
50
+ const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
51
+ const info = insert.run('John Doe', 'john@example.com')
52
+ const newId = info.lastInsertRowid
53
+
54
+ // UPDATE
55
+ const update = db.prepare('UPDATE users SET name = ? WHERE id = ?')
56
+ update.run('Jane Doe', userId)
57
+
58
+ // DELETE
59
+ const del = db.prepare('DELETE FROM users WHERE id = ?')
60
+ del.run(userId)
61
+
62
+ // Using sqlite3 (asynchronous)
63
+ db.get('SELECT * FROM users WHERE id = ?', [userId], (err, row) => {
64
+ if (err) throw err
65
+ console.log(row)
66
+ })
67
+
68
+ db.run('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', 'john@example.com'], function(err) {
69
+ if (err) throw err
70
+ console.log('Inserted with ID:', this.lastID)
71
+ })
72
+ ```
73
+
74
+ ### Transactions
75
+ ```typescript
76
+ // Using better-sqlite3
77
+ const insertUser = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
78
+ const insertPost = db.prepare('INSERT INTO posts (user_id, title) VALUES (?, ?)')
79
+
80
+ const insertUserAndPost = db.transaction((userName, userEmail, postTitle) => {
81
+ const userInfo = insertUser.run(userName, userEmail)
82
+ const userId = userInfo.lastInsertRowid
83
+ insertPost.run(userId, postTitle)
84
+ return userId
85
+ })
86
+
87
+ const userId = insertUserAndPost('John Doe', 'john@example.com', 'First Post')
88
+
89
+ // Using sqlite3
90
+ db.serialize(() => {
91
+ db.run('BEGIN TRANSACTION')
92
+ db.run('INSERT INTO users (name, email) VALUES (?, ?)', ['John', 'john@example.com'], function(err) {
93
+ if (err) {
94
+ db.run('ROLLBACK')
95
+ throw err
96
+ }
97
+ const userId = this.lastID
98
+ db.run('INSERT INTO posts (user_id, title) VALUES (?, ?)', [userId, 'Post'], (err) => {
99
+ if (err) {
100
+ db.run('ROLLBACK')
101
+ throw err
102
+ }
103
+ db.run('COMMIT')
104
+ })
105
+ })
106
+ })
107
+ ```
108
+
109
+ ### Advanced Features
110
+ ```typescript
111
+ // JSON operations (SQLite 3.38+)
112
+ const result = db.prepare(`
113
+ SELECT
114
+ id,
115
+ name,
116
+ json_extract(metadata, '$.category') AS category
117
+ FROM products
118
+ WHERE json_extract(metadata, '$.category') = ?
119
+ `).get('electronics')
120
+
121
+ // Full-text search (FTS5)
122
+ db.exec(`
123
+ CREATE VIRTUAL TABLE articles_fts USING fts5(
124
+ title,
125
+ content,
126
+ content_rowid=id
127
+ )
128
+ `)
129
+
130
+ const results = db.prepare(`
131
+ SELECT * FROM articles_fts
132
+ WHERE articles_fts MATCH ?
133
+ `).all('search term')
134
+
135
+ // Window functions (SQLite 3.25+)
136
+ const result = db.prepare(`
137
+ SELECT
138
+ name,
139
+ salary,
140
+ ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rank
141
+ FROM employees
142
+ `).all()
143
+ ```
144
+
145
+ ## Common Patterns
146
+
147
+ ### Prepared Statements
148
+ ```typescript
149
+ // Reuse prepared statements for better performance
150
+ const getUserById = db.prepare('SELECT * FROM users WHERE id = ?')
151
+ const getUserByEmail = db.prepare('SELECT * FROM users WHERE email = ?')
152
+
153
+ // Use in functions
154
+ function getUser(id: number) {
155
+ return getUserById.get(id)
156
+ }
157
+
158
+ function findUserByEmail(email: string) {
159
+ return getUserByEmail.get(email)
160
+ }
161
+ ```
162
+
163
+ ### Batch Operations
164
+ ```typescript
165
+ // Insert multiple rows efficiently
166
+ const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
167
+ const insertMany = db.transaction((users) => {
168
+ for (const user of users) {
169
+ insert.run(user.name, user.email)
170
+ }
171
+ })
172
+
173
+ insertMany([
174
+ { name: 'User 1', email: 'user1@example.com' },
175
+ { name: 'User 2', email: 'user2@example.com' },
176
+ ])
177
+ ```
178
+
179
+ ### Migrations
180
+ ```typescript
181
+ // Simple migration system
182
+ const migrations = [
183
+ `CREATE TABLE IF NOT EXISTS users (
184
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
185
+ name TEXT NOT NULL,
186
+ email TEXT UNIQUE NOT NULL,
187
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
188
+ )`,
189
+ `CREATE TABLE IF NOT EXISTS posts (
190
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
191
+ user_id INTEGER NOT NULL,
192
+ title TEXT NOT NULL,
193
+ content TEXT,
194
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
195
+ FOREIGN KEY (user_id) REFERENCES users(id)
196
+ )`,
197
+ ]
198
+
199
+ db.exec('BEGIN TRANSACTION')
200
+ try {
201
+ for (const migration of migrations) {
202
+ db.exec(migration)
203
+ }
204
+ db.exec('COMMIT')
205
+ } catch (error) {
206
+ db.exec('ROLLBACK')
207
+ throw error
208
+ }
209
+ ```
210
+
211
+ ## Best Practices
212
+
213
+ ✅ **DO:**
214
+ - Use WAL mode for better concurrency
215
+ - Enable foreign keys
216
+ - Use prepared statements
217
+ - Use transactions for multiple operations
218
+ - Create indexes on frequently queried columns
219
+ - Use appropriate data types (TEXT, INTEGER, REAL, BLOB)
220
+ - Backup database regularly
221
+ - Use connection pooling (better-sqlite3 handles this)
222
+ - Monitor database size
223
+ - Use VACUUM periodically
224
+
225
+ ❌ **DON'T:**
226
+ - Use for high-concurrency write scenarios
227
+ - Store large binary data (use external storage)
228
+ - Skip error handling
229
+ - Use string concatenation for queries
230
+ - Ignore database size limits
231
+ - Skip indexes on foreign keys
232
+ - Hardcode database paths
233
+ - Ignore transaction boundaries
234
+ - Use synchronous operations in async contexts (better-sqlite3 is fine)
235
+ - Skip backups
236
+
237
+ ## Configuration
238
+
239
+ ### Environment Variables
240
+ ```bash
241
+ DB_PATH=./database.db
242
+ DB_PATH=/var/lib/myapp/database.db
243
+ ```
244
+
245
+ ### Initialization
246
+ ```typescript
247
+ // Initialize database with schema
248
+ const db = new Database('./database.db')
249
+
250
+ db.pragma('journal_mode = WAL')
251
+ db.pragma('foreign_keys = ON')
252
+ db.pragma('synchronous = NORMAL')
253
+ db.pragma('cache_size = 10000')
254
+ db.pragma('temp_store = MEMORY')
255
+
256
+ // Create tables
257
+ db.exec(`
258
+ CREATE TABLE IF NOT EXISTS users (
259
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
260
+ name TEXT NOT NULL,
261
+ email TEXT UNIQUE NOT NULL,
262
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
263
+ )
264
+
265
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)
266
+ `)
267
+ ```
268
+
269
+ ## Integration with Development
270
+
271
+ ### Testing
272
+ ```typescript
273
+ // Use in-memory database for tests
274
+ const testDb = new Database(':memory:')
275
+
276
+ // Or use separate test database
277
+ const testDb = new Database('./test.db')
278
+
279
+ // Clean up after tests
280
+ afterEach(() => {
281
+ testDb.exec('DELETE FROM users')
282
+ testDb.exec('DELETE FROM posts')
283
+ })
284
+
285
+ afterAll(() => {
286
+ testDb.close()
287
+ // Optionally delete test database file
288
+ })
289
+ ```
290
+
291
+ ### Health Checks
292
+ ```typescript
293
+ function checkDatabaseHealth(): boolean {
294
+ try {
295
+ db.prepare('SELECT 1').get()
296
+ return true
297
+ } catch {
298
+ return false
299
+ }
300
+ }
301
+ ```
302
+
303
+ <!-- SQLITE:END -->
304
+
@@ -0,0 +1,304 @@
1
+ ---
2
+ name: "SQL Server"
3
+ description: "Use SQL Server for enterprise relational data storage with advanced features, high availability, and Windows integration."
4
+ version: "1.0.0"
5
+ category: "services"
6
+ author: "Rulebook"
7
+ tags: ["services", "database"]
8
+ dependencies: []
9
+ conflicts: []
10
+ ---
11
+ <!-- SQLSERVER:START -->
12
+ # SQL Server Database Instructions
13
+
14
+ **CRITICAL**: Use SQL Server for enterprise relational data storage with advanced features, high availability, and Windows integration.
15
+
16
+ ## Core Features
17
+
18
+ ### Connection
19
+ ```typescript
20
+ // Using mssql (Node.js)
21
+ import sql from 'mssql'
22
+
23
+ const pool = await sql.connect({
24
+ server: process.env.DB_HOST || 'localhost',
25
+ port: parseInt(process.env.DB_PORT || '1433'),
26
+ database: process.env.DB_NAME || 'myapp',
27
+ user: process.env.DB_USER,
28
+ password: process.env.DB_PASSWORD,
29
+ options: {
30
+ encrypt: process.env.NODE_ENV === 'production',
31
+ trustServerCertificate: process.env.NODE_ENV !== 'production',
32
+ enableArithAbort: true,
33
+ connectionTimeout: 30000,
34
+ requestTimeout: 30000,
35
+ },
36
+ pool: {
37
+ max: 10,
38
+ min: 0,
39
+ idleTimeoutMillis: 30000,
40
+ },
41
+ })
42
+
43
+ // Using tedious (lower level)
44
+ import { Connection } from 'tedious'
45
+
46
+ const connection = new Connection({
47
+ server: process.env.DB_HOST || 'localhost',
48
+ authentication: {
49
+ type: 'default',
50
+ options: {
51
+ userName: process.env.DB_USER,
52
+ password: process.env.DB_PASSWORD,
53
+ },
54
+ },
55
+ options: {
56
+ encrypt: true,
57
+ database: process.env.DB_NAME,
58
+ trustServerCertificate: true,
59
+ },
60
+ })
61
+ ```
62
+
63
+ ### Basic Queries
64
+ ```typescript
65
+ // SELECT
66
+ const result = await pool.request()
67
+ .input('userId', sql.Int, userId)
68
+ .query('SELECT * FROM Users WHERE Id = @userId')
69
+ const users = result.recordset
70
+
71
+ // INSERT
72
+ const result = await pool.request()
73
+ .input('name', sql.NVarChar, 'John Doe')
74
+ .input('email', sql.NVarChar, 'john@example.com')
75
+ .query('INSERT INTO Users (Name, Email) OUTPUT INSERTED.* VALUES (@name, @email)')
76
+ const newUser = result.recordset[0]
77
+
78
+ // UPDATE
79
+ const result = await pool.request()
80
+ .input('id', sql.Int, userId)
81
+ .input('name', sql.NVarChar, 'Jane Doe')
82
+ .query('UPDATE Users SET Name = @name WHERE Id = @id')
83
+
84
+ // DELETE
85
+ await pool.request()
86
+ .input('id', sql.Int, userId)
87
+ .query('DELETE FROM Users WHERE Id = @id')
88
+ ```
89
+
90
+ ### Transactions
91
+ ```typescript
92
+ const transaction = new sql.Transaction(pool)
93
+
94
+ try {
95
+ await transaction.begin()
96
+
97
+ const request = new sql.Request(transaction)
98
+ await request
99
+ .input('userId', sql.Int, userId)
100
+ .input('amount', sql.Decimal(18, 2), 1000)
101
+ .query('INSERT INTO Accounts (UserId, Balance) VALUES (@userId, @amount)')
102
+
103
+ await request
104
+ .input('accountId', sql.Int, accountId)
105
+ .input('amount', sql.Decimal(18, 2), 1000)
106
+ .query('INSERT INTO Transactions (AccountId, Amount) VALUES (@accountId, @amount)')
107
+
108
+ await transaction.commit()
109
+ } catch (error) {
110
+ await transaction.rollback()
111
+ throw error
112
+ }
113
+ ```
114
+
115
+ ### Advanced Features
116
+ ```typescript
117
+ // Stored procedures
118
+ const result = await pool.request()
119
+ .input('userId', sql.Int, userId)
120
+ .execute('sp_GetUserDetails')
121
+
122
+ // JSON operations (SQL Server 2016+)
123
+ const result = await pool.request()
124
+ .query(`
125
+ SELECT
126
+ Id,
127
+ Name,
128
+ JSON_VALUE(Metadata, '$.category') AS Category
129
+ FROM Products
130
+ WHERE JSON_VALUE(Metadata, '$.category') = 'electronics'
131
+ `)
132
+
133
+ // Full-text search
134
+ const result = await pool.request()
135
+ .input('searchTerm', sql.NVarChar, 'search term')
136
+ .query(`
137
+ SELECT * FROM Articles
138
+ WHERE CONTAINS(Content, @searchTerm)
139
+ `)
140
+
141
+ // Window functions
142
+ const result = await pool.request()
143
+ .query(`
144
+ SELECT
145
+ Name,
146
+ Salary,
147
+ ROW_NUMBER() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS Rank
148
+ FROM Employees
149
+ `)
150
+ ```
151
+
152
+ ## Common Patterns
153
+
154
+ ### Connection Pooling
155
+ ```typescript
156
+ let pool: sql.ConnectionPool | null = null
157
+
158
+ export async function getPool(): Promise<sql.ConnectionPool> {
159
+ if (!pool) {
160
+ pool = await sql.connect({
161
+ // ... config
162
+ })
163
+
164
+ pool.on('error', (err) => {
165
+ console.error('SQL Server pool error', err)
166
+ })
167
+ }
168
+ return pool
169
+ }
170
+
171
+ // Graceful shutdown
172
+ process.on('SIGINT', async () => {
173
+ if (pool) {
174
+ await pool.close()
175
+ }
176
+ process.exit(0)
177
+ })
178
+ ```
179
+
180
+ ### Parameterized Queries
181
+ ```typescript
182
+ // Always use parameters to prevent SQL injection
183
+ // ❌ WRONG
184
+ await pool.request().query(`SELECT * FROM Users WHERE Email = '${email}'`)
185
+
186
+ // ✅ CORRECT
187
+ await pool.request()
188
+ .input('email', sql.NVarChar, email)
189
+ .query('SELECT * FROM Users WHERE Email = @email')
190
+ ```
191
+
192
+ ### Error Handling
193
+ ```typescript
194
+ try {
195
+ const result = await pool.request()
196
+ .input('id', sql.Int, userId)
197
+ .query('SELECT * FROM Users WHERE Id = @id')
198
+
199
+ if (result.recordset.length === 0) {
200
+ throw new Error('User not found')
201
+ }
202
+ return result.recordset[0]
203
+ } catch (error: any) {
204
+ if (error.number === 2627) { // Unique constraint violation
205
+ throw new Error('Duplicate entry')
206
+ }
207
+ if (error.number === 547) { // Foreign key constraint violation
208
+ throw new Error('Referenced record does not exist')
209
+ }
210
+ throw error
211
+ }
212
+ ```
213
+
214
+ ## Best Practices
215
+
216
+ ✅ **DO:**
217
+ - Use connection pooling (10-20 connections)
218
+ - Always use parameterized queries (@param)
219
+ - Use transactions for multi-step operations
220
+ - Create indexes on frequently queried columns
221
+ - Use appropriate data types (NVarChar for Unicode)
222
+ - Enable encryption in production
223
+ - Use stored procedures for complex logic
224
+ - Monitor connection pool usage
225
+ - Use appropriate timeout values
226
+ - Implement retry logic for transient errors
227
+
228
+ ❌ **DON'T:**
229
+ - Use string concatenation for queries (SQL injection risk)
230
+ - Create too many connections
231
+ - Skip error handling
232
+ - Ignore connection pool limits
233
+ - Use SELECT * in production
234
+ - Skip indexes on foreign keys
235
+ - Hardcode connection strings
236
+ - Skip encryption in production
237
+ - Ignore query performance
238
+ - Use synchronous operations
239
+
240
+ ## Configuration
241
+
242
+ ### Environment Variables
243
+ ```bash
244
+ DB_HOST=localhost
245
+ DB_PORT=1433
246
+ DB_NAME=myapp
247
+ DB_USER=sa
248
+ DB_PASSWORD=securepassword
249
+ ```
250
+
251
+ ### Docker Compose
252
+ ```yaml
253
+ services:
254
+ sqlserver:
255
+ image: mcr.microsoft.com/mssql/server:2022-latest
256
+ ports:
257
+ - "1433:1433"
258
+ environment:
259
+ ACCEPT_EULA: Y
260
+ SA_PASSWORD: securepassword
261
+ MSSQL_PID: Developer
262
+ volumes:
263
+ - sqlserver_data:/var/opt/mssql
264
+ healthcheck:
265
+ test: ["CMD-SHELL", "/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P securepassword -Q 'SELECT 1' || exit 1"]
266
+ interval: 10s
267
+ timeout: 5s
268
+ retries: 5
269
+
270
+ volumes:
271
+ sqlserver_data:
272
+ ```
273
+
274
+ ## Integration with Development
275
+
276
+ ### Testing
277
+ ```typescript
278
+ // Use test database
279
+ const testPool = await sql.connect({
280
+ database: 'myapp_test',
281
+ // ... config
282
+ })
283
+
284
+ // Clean up after tests
285
+ afterEach(async () => {
286
+ await testPool.request().query('DELETE FROM Users')
287
+ await testPool.request().query('DELETE FROM Posts')
288
+ })
289
+ ```
290
+
291
+ ### Health Checks
292
+ ```typescript
293
+ async function checkDatabaseHealth(): Promise<boolean> {
294
+ try {
295
+ const result = await pool.request().query('SELECT 1 AS Health')
296
+ return result.recordset.length > 0
297
+ } catch {
298
+ return false
299
+ }
300
+ }
301
+ ```
302
+
303
+ <!-- SQLSERVER:END -->
304
+