@hasna/microservices 0.0.2 → 0.0.4

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 (89) hide show
  1. package/bin/index.js +70 -0
  2. package/bin/mcp.js +71 -1
  3. package/dist/index.js +70 -0
  4. package/microservices/microservice-ads/package.json +27 -0
  5. package/microservices/microservice-ads/src/cli/index.ts +407 -0
  6. package/microservices/microservice-ads/src/db/campaigns.ts +493 -0
  7. package/microservices/microservice-ads/src/db/database.ts +93 -0
  8. package/microservices/microservice-ads/src/db/migrations.ts +60 -0
  9. package/microservices/microservice-ads/src/index.ts +39 -0
  10. package/microservices/microservice-ads/src/mcp/index.ts +320 -0
  11. package/microservices/microservice-contracts/package.json +27 -0
  12. package/microservices/microservice-contracts/src/cli/index.ts +383 -0
  13. package/microservices/microservice-contracts/src/db/contracts.ts +496 -0
  14. package/microservices/microservice-contracts/src/db/database.ts +93 -0
  15. package/microservices/microservice-contracts/src/db/migrations.ts +58 -0
  16. package/microservices/microservice-contracts/src/index.ts +43 -0
  17. package/microservices/microservice-contracts/src/mcp/index.ts +308 -0
  18. package/microservices/microservice-domains/package.json +27 -0
  19. package/microservices/microservice-domains/src/cli/index.ts +438 -0
  20. package/microservices/microservice-domains/src/db/database.ts +93 -0
  21. package/microservices/microservice-domains/src/db/domains.ts +551 -0
  22. package/microservices/microservice-domains/src/db/migrations.ts +60 -0
  23. package/microservices/microservice-domains/src/index.ts +44 -0
  24. package/microservices/microservice-domains/src/mcp/index.ts +368 -0
  25. package/microservices/microservice-hiring/package.json +27 -0
  26. package/microservices/microservice-hiring/src/cli/index.ts +431 -0
  27. package/microservices/microservice-hiring/src/db/database.ts +93 -0
  28. package/microservices/microservice-hiring/src/db/hiring.ts +582 -0
  29. package/microservices/microservice-hiring/src/db/migrations.ts +68 -0
  30. package/microservices/microservice-hiring/src/index.ts +51 -0
  31. package/microservices/microservice-hiring/src/mcp/index.ts +464 -0
  32. package/microservices/microservice-payments/package.json +27 -0
  33. package/microservices/microservice-payments/src/cli/index.ts +357 -0
  34. package/microservices/microservice-payments/src/db/database.ts +93 -0
  35. package/microservices/microservice-payments/src/db/migrations.ts +63 -0
  36. package/microservices/microservice-payments/src/db/payments.ts +652 -0
  37. package/microservices/microservice-payments/src/index.ts +51 -0
  38. package/microservices/microservice-payments/src/mcp/index.ts +460 -0
  39. package/microservices/microservice-payroll/package.json +27 -0
  40. package/microservices/microservice-payroll/src/cli/index.ts +374 -0
  41. package/microservices/microservice-payroll/src/db/database.ts +93 -0
  42. package/microservices/microservice-payroll/src/db/migrations.ts +69 -0
  43. package/microservices/microservice-payroll/src/db/payroll.ts +741 -0
  44. package/microservices/microservice-payroll/src/index.ts +48 -0
  45. package/microservices/microservice-payroll/src/mcp/index.ts +420 -0
  46. package/microservices/microservice-shipping/package.json +27 -0
  47. package/microservices/microservice-shipping/src/cli/index.ts +398 -0
  48. package/microservices/microservice-shipping/src/db/database.ts +93 -0
  49. package/microservices/microservice-shipping/src/db/migrations.ts +61 -0
  50. package/microservices/microservice-shipping/src/db/shipping.ts +643 -0
  51. package/microservices/microservice-shipping/src/index.ts +53 -0
  52. package/microservices/microservice-shipping/src/mcp/index.ts +385 -0
  53. package/microservices/microservice-social/package.json +27 -0
  54. package/microservices/microservice-social/src/cli/index.ts +447 -0
  55. package/microservices/microservice-social/src/db/database.ts +93 -0
  56. package/microservices/microservice-social/src/db/migrations.ts +55 -0
  57. package/microservices/microservice-social/src/db/social.ts +672 -0
  58. package/microservices/microservice-social/src/index.ts +46 -0
  59. package/microservices/microservice-social/src/mcp/index.ts +435 -0
  60. package/microservices/microservice-subscriptions/package.json +27 -0
  61. package/microservices/microservice-subscriptions/src/cli/index.ts +400 -0
  62. package/microservices/microservice-subscriptions/src/db/database.ts +93 -0
  63. package/microservices/microservice-subscriptions/src/db/migrations.ts +57 -0
  64. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +692 -0
  65. package/microservices/microservice-subscriptions/src/index.ts +41 -0
  66. package/microservices/microservice-subscriptions/src/mcp/index.ts +365 -0
  67. package/microservices/microservice-transcriber/package.json +28 -0
  68. package/microservices/microservice-transcriber/src/cli/index.ts +1347 -0
  69. package/microservices/microservice-transcriber/src/db/annotations.ts +37 -0
  70. package/microservices/microservice-transcriber/src/db/database.ts +82 -0
  71. package/microservices/microservice-transcriber/src/db/migrations.ts +72 -0
  72. package/microservices/microservice-transcriber/src/db/transcripts.ts +395 -0
  73. package/microservices/microservice-transcriber/src/index.ts +43 -0
  74. package/microservices/microservice-transcriber/src/lib/config.ts +77 -0
  75. package/microservices/microservice-transcriber/src/lib/diff.ts +91 -0
  76. package/microservices/microservice-transcriber/src/lib/downloader.ts +570 -0
  77. package/microservices/microservice-transcriber/src/lib/feeds.ts +62 -0
  78. package/microservices/microservice-transcriber/src/lib/live.ts +94 -0
  79. package/microservices/microservice-transcriber/src/lib/notion.ts +129 -0
  80. package/microservices/microservice-transcriber/src/lib/providers.ts +713 -0
  81. package/microservices/microservice-transcriber/src/lib/summarizer.ts +147 -0
  82. package/microservices/microservice-transcriber/src/lib/translator.ts +75 -0
  83. package/microservices/microservice-transcriber/src/lib/webhook.ts +37 -0
  84. package/microservices/microservice-transcriber/src/mcp/index.ts +1070 -0
  85. package/microservices/microservice-transcriber/src/server/index.ts +199 -0
  86. package/package.json +1 -1
  87. package/microservices/microservice-invoices/dashboard/dist/assets/index-Bngq7FNM.css +0 -1
  88. package/microservices/microservice-invoices/dashboard/dist/assets/index-aHW4ARZR.js +0 -124
  89. package/microservices/microservice-invoices/dashboard/dist/index.html +0 -13
@@ -0,0 +1,447 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { Command } from "commander";
4
+ import {
5
+ createAccount,
6
+ getAccount,
7
+ listAccounts,
8
+ updateAccount,
9
+ deleteAccount,
10
+ createPost,
11
+ getPost,
12
+ listPosts,
13
+ updatePost,
14
+ deletePost,
15
+ schedulePost,
16
+ publishPost,
17
+ createTemplate,
18
+ listTemplates,
19
+ getTemplate,
20
+ deleteTemplate,
21
+ useTemplate,
22
+ getEngagementStats,
23
+ getStatsByPlatform,
24
+ getCalendar,
25
+ getOverallStats,
26
+ type Platform,
27
+ type PostStatus,
28
+ } from "../db/social.js";
29
+
30
+ const program = new Command();
31
+
32
+ program
33
+ .name("microservice-social")
34
+ .description("Social media management microservice")
35
+ .version("0.0.1");
36
+
37
+ // --- Posts ---
38
+
39
+ const postCmd = program
40
+ .command("post")
41
+ .description("Post management");
42
+
43
+ postCmd
44
+ .command("create")
45
+ .description("Create a new post")
46
+ .requiredOption("--account <id>", "Account ID")
47
+ .requiredOption("--content <text>", "Post content")
48
+ .option("--media <urls>", "Comma-separated media URLs")
49
+ .option("--status <status>", "Post status (draft/scheduled/published/failed)", "draft")
50
+ .option("--scheduled-at <datetime>", "Schedule date/time")
51
+ .option("--tags <tags>", "Comma-separated tags")
52
+ .option("--json", "Output as JSON", false)
53
+ .action((opts) => {
54
+ const post = createPost({
55
+ account_id: opts.account,
56
+ content: opts.content,
57
+ media_urls: opts.media ? opts.media.split(",").map((u: string) => u.trim()) : undefined,
58
+ status: opts.status as PostStatus,
59
+ scheduled_at: opts.scheduledAt,
60
+ tags: opts.tags ? opts.tags.split(",").map((t: string) => t.trim()) : undefined,
61
+ });
62
+
63
+ if (opts.json) {
64
+ console.log(JSON.stringify(post, null, 2));
65
+ } else {
66
+ console.log(`Created post: ${post.id} [${post.status}]`);
67
+ console.log(` Content: ${post.content.substring(0, 80)}${post.content.length > 80 ? "..." : ""}`);
68
+ }
69
+ });
70
+
71
+ postCmd
72
+ .command("list")
73
+ .description("List posts")
74
+ .option("--account <id>", "Filter by account ID")
75
+ .option("--status <status>", "Filter by status")
76
+ .option("--tag <tag>", "Filter by tag")
77
+ .option("--search <query>", "Search post content")
78
+ .option("--limit <n>", "Limit results")
79
+ .option("--json", "Output as JSON", false)
80
+ .action((opts) => {
81
+ const posts = listPosts({
82
+ account_id: opts.account,
83
+ status: opts.status as PostStatus | undefined,
84
+ tag: opts.tag,
85
+ search: opts.search,
86
+ limit: opts.limit ? parseInt(opts.limit) : undefined,
87
+ });
88
+
89
+ if (opts.json) {
90
+ console.log(JSON.stringify(posts, null, 2));
91
+ } else {
92
+ if (posts.length === 0) {
93
+ console.log("No posts found.");
94
+ return;
95
+ }
96
+ for (const p of posts) {
97
+ const preview = p.content.substring(0, 60) + (p.content.length > 60 ? "..." : "");
98
+ const tags = p.tags.length ? ` [${p.tags.join(", ")}]` : "";
99
+ console.log(` [${p.status}] ${preview}${tags}`);
100
+ }
101
+ console.log(`\n${posts.length} post(s)`);
102
+ }
103
+ });
104
+
105
+ postCmd
106
+ .command("get")
107
+ .description("Get a post by ID")
108
+ .argument("<id>", "Post ID")
109
+ .option("--json", "Output as JSON", false)
110
+ .action((id, opts) => {
111
+ const post = getPost(id);
112
+ if (!post) {
113
+ console.error(`Post '${id}' not found.`);
114
+ process.exit(1);
115
+ }
116
+
117
+ if (opts.json) {
118
+ console.log(JSON.stringify(post, null, 2));
119
+ } else {
120
+ console.log(`Post ${post.id} [${post.status}]`);
121
+ console.log(` Content: ${post.content}`);
122
+ console.log(` Account: ${post.account_id}`);
123
+ if (post.scheduled_at) console.log(` Scheduled: ${post.scheduled_at}`);
124
+ if (post.published_at) console.log(` Published: ${post.published_at}`);
125
+ if (post.tags.length) console.log(` Tags: ${post.tags.join(", ")}`);
126
+ if (Object.keys(post.engagement).length) {
127
+ console.log(` Engagement: ${JSON.stringify(post.engagement)}`);
128
+ }
129
+ }
130
+ });
131
+
132
+ postCmd
133
+ .command("schedule")
134
+ .description("Schedule a post")
135
+ .argument("<id>", "Post ID")
136
+ .requiredOption("--at <datetime>", "Schedule date/time")
137
+ .option("--json", "Output as JSON", false)
138
+ .action((id, opts) => {
139
+ const post = schedulePost(id, opts.at);
140
+ if (!post) {
141
+ console.error(`Post '${id}' not found.`);
142
+ process.exit(1);
143
+ }
144
+
145
+ if (opts.json) {
146
+ console.log(JSON.stringify(post, null, 2));
147
+ } else {
148
+ console.log(`Scheduled post ${post.id} for ${post.scheduled_at}`);
149
+ }
150
+ });
151
+
152
+ postCmd
153
+ .command("publish")
154
+ .description("Mark a post as published")
155
+ .argument("<id>", "Post ID")
156
+ .option("--platform-id <id>", "Platform post ID")
157
+ .option("--json", "Output as JSON", false)
158
+ .action((id, opts) => {
159
+ const post = publishPost(id, opts.platformId);
160
+ if (!post) {
161
+ console.error(`Post '${id}' not found.`);
162
+ process.exit(1);
163
+ }
164
+
165
+ if (opts.json) {
166
+ console.log(JSON.stringify(post, null, 2));
167
+ } else {
168
+ console.log(`Published post ${post.id} at ${post.published_at}`);
169
+ }
170
+ });
171
+
172
+ postCmd
173
+ .command("delete")
174
+ .description("Delete a post")
175
+ .argument("<id>", "Post ID")
176
+ .action((id) => {
177
+ const deleted = deletePost(id);
178
+ if (deleted) {
179
+ console.log(`Deleted post ${id}`);
180
+ } else {
181
+ console.error(`Post '${id}' not found.`);
182
+ process.exit(1);
183
+ }
184
+ });
185
+
186
+ // --- Accounts ---
187
+
188
+ const accountCmd = program
189
+ .command("account")
190
+ .description("Account management");
191
+
192
+ accountCmd
193
+ .command("add")
194
+ .description("Add a social media account")
195
+ .requiredOption("--platform <platform>", "Platform (x/linkedin/instagram/threads/bluesky)")
196
+ .requiredOption("--handle <handle>", "Account handle")
197
+ .option("--display-name <name>", "Display name")
198
+ .option("--connected", "Mark as connected", false)
199
+ .option("--token-env <var>", "Environment variable for access token")
200
+ .option("--json", "Output as JSON", false)
201
+ .action((opts) => {
202
+ const account = createAccount({
203
+ platform: opts.platform as Platform,
204
+ handle: opts.handle,
205
+ display_name: opts.displayName,
206
+ connected: opts.connected,
207
+ access_token_env: opts.tokenEnv,
208
+ });
209
+
210
+ if (opts.json) {
211
+ console.log(JSON.stringify(account, null, 2));
212
+ } else {
213
+ console.log(`Added account: @${account.handle} on ${account.platform} (${account.id})`);
214
+ }
215
+ });
216
+
217
+ accountCmd
218
+ .command("list")
219
+ .description("List accounts")
220
+ .option("--platform <platform>", "Filter by platform")
221
+ .option("--connected", "Show only connected accounts")
222
+ .option("--json", "Output as JSON", false)
223
+ .action((opts) => {
224
+ const accounts = listAccounts({
225
+ platform: opts.platform as Platform | undefined,
226
+ connected: opts.connected ? true : undefined,
227
+ });
228
+
229
+ if (opts.json) {
230
+ console.log(JSON.stringify(accounts, null, 2));
231
+ } else {
232
+ if (accounts.length === 0) {
233
+ console.log("No accounts found.");
234
+ return;
235
+ }
236
+ for (const a of accounts) {
237
+ const connected = a.connected ? " (connected)" : "";
238
+ const name = a.display_name ? ` - ${a.display_name}` : "";
239
+ console.log(` [${a.platform}] @${a.handle}${name}${connected}`);
240
+ }
241
+ console.log(`\n${accounts.length} account(s)`);
242
+ }
243
+ });
244
+
245
+ accountCmd
246
+ .command("remove")
247
+ .description("Remove an account")
248
+ .argument("<id>", "Account ID")
249
+ .action((id) => {
250
+ const deleted = deleteAccount(id);
251
+ if (deleted) {
252
+ console.log(`Removed account ${id}`);
253
+ } else {
254
+ console.error(`Account '${id}' not found.`);
255
+ process.exit(1);
256
+ }
257
+ });
258
+
259
+ // --- Calendar ---
260
+
261
+ program
262
+ .command("calendar")
263
+ .description("View scheduled posts by date")
264
+ .option("--start <date>", "Start date (YYYY-MM-DD)")
265
+ .option("--end <date>", "End date (YYYY-MM-DD)")
266
+ .option("--json", "Output as JSON", false)
267
+ .action((opts) => {
268
+ const calendar = getCalendar(opts.start, opts.end);
269
+
270
+ if (opts.json) {
271
+ console.log(JSON.stringify(calendar, null, 2));
272
+ } else {
273
+ const dates = Object.keys(calendar).sort();
274
+ if (dates.length === 0) {
275
+ console.log("No scheduled posts.");
276
+ return;
277
+ }
278
+ for (const date of dates) {
279
+ console.log(`\n${date}:`);
280
+ for (const post of calendar[date]) {
281
+ const preview = post.content.substring(0, 50) + (post.content.length > 50 ? "..." : "");
282
+ console.log(` ${post.scheduled_at} — ${preview}`);
283
+ }
284
+ }
285
+ }
286
+ });
287
+
288
+ // --- Analytics ---
289
+
290
+ program
291
+ .command("analytics")
292
+ .description("View engagement analytics")
293
+ .option("--account <id>", "Filter by account ID")
294
+ .option("--by-platform", "Group by platform")
295
+ .option("--json", "Output as JSON", false)
296
+ .action((opts) => {
297
+ if (opts.byPlatform) {
298
+ const stats = getStatsByPlatform();
299
+
300
+ if (opts.json) {
301
+ console.log(JSON.stringify(stats, null, 2));
302
+ } else {
303
+ if (stats.length === 0) {
304
+ console.log("No platform data.");
305
+ return;
306
+ }
307
+ for (const s of stats) {
308
+ console.log(`\n${s.platform} (${s.account_count} account(s), ${s.post_count} post(s)):`);
309
+ console.log(` Published: ${s.engagement.total_posts}`);
310
+ console.log(` Likes: ${s.engagement.total_likes} (avg ${s.engagement.avg_likes})`);
311
+ console.log(` Shares: ${s.engagement.total_shares} (avg ${s.engagement.avg_shares})`);
312
+ console.log(` Comments: ${s.engagement.total_comments} (avg ${s.engagement.avg_comments})`);
313
+ console.log(` Impressions: ${s.engagement.total_impressions} (avg ${s.engagement.avg_impressions})`);
314
+ }
315
+ }
316
+ } else {
317
+ const stats = getEngagementStats(opts.account);
318
+
319
+ if (opts.json) {
320
+ console.log(JSON.stringify(stats, null, 2));
321
+ } else {
322
+ console.log("Engagement Analytics:");
323
+ console.log(` Published posts: ${stats.total_posts}`);
324
+ console.log(` Total likes: ${stats.total_likes} (avg ${stats.avg_likes})`);
325
+ console.log(` Total shares: ${stats.total_shares} (avg ${stats.avg_shares})`);
326
+ console.log(` Total comments: ${stats.total_comments} (avg ${stats.avg_comments})`);
327
+ console.log(` Total impressions: ${stats.total_impressions} (avg ${stats.avg_impressions})`);
328
+ console.log(` Total clicks: ${stats.total_clicks} (avg ${stats.avg_clicks})`);
329
+ }
330
+ }
331
+ });
332
+
333
+ // --- Templates ---
334
+
335
+ const templateCmd = program
336
+ .command("template")
337
+ .description("Post template management");
338
+
339
+ templateCmd
340
+ .command("create")
341
+ .description("Create a post template")
342
+ .requiredOption("--name <name>", "Template name")
343
+ .requiredOption("--content <content>", "Template content (use {{var}} for variables)")
344
+ .option("--variables <vars>", "Comma-separated variable names")
345
+ .option("--json", "Output as JSON", false)
346
+ .action((opts) => {
347
+ const template = createTemplate({
348
+ name: opts.name,
349
+ content: opts.content,
350
+ variables: opts.variables ? opts.variables.split(",").map((v: string) => v.trim()) : undefined,
351
+ });
352
+
353
+ if (opts.json) {
354
+ console.log(JSON.stringify(template, null, 2));
355
+ } else {
356
+ console.log(`Created template: ${template.name} (${template.id})`);
357
+ }
358
+ });
359
+
360
+ templateCmd
361
+ .command("list")
362
+ .description("List templates")
363
+ .option("--json", "Output as JSON", false)
364
+ .action((opts) => {
365
+ const templates = listTemplates();
366
+
367
+ if (opts.json) {
368
+ console.log(JSON.stringify(templates, null, 2));
369
+ } else {
370
+ if (templates.length === 0) {
371
+ console.log("No templates found.");
372
+ return;
373
+ }
374
+ for (const t of templates) {
375
+ const vars = t.variables.length ? ` (vars: ${t.variables.join(", ")})` : "";
376
+ console.log(` ${t.name}${vars}`);
377
+ }
378
+ console.log(`\n${templates.length} template(s)`);
379
+ }
380
+ });
381
+
382
+ templateCmd
383
+ .command("use")
384
+ .description("Create a post from a template")
385
+ .argument("<template-id>", "Template ID")
386
+ .requiredOption("--account <id>", "Account ID")
387
+ .option("--values <json>", "JSON object of variable values")
388
+ .option("--tags <tags>", "Comma-separated tags")
389
+ .option("--json", "Output as JSON", false)
390
+ .action((templateId, opts) => {
391
+ const values = opts.values ? JSON.parse(opts.values) : {};
392
+ const tags = opts.tags ? opts.tags.split(",").map((t: string) => t.trim()) : undefined;
393
+
394
+ const post = useTemplate(templateId, opts.account, values, tags);
395
+
396
+ if (opts.json) {
397
+ console.log(JSON.stringify(post, null, 2));
398
+ } else {
399
+ console.log(`Created post from template: ${post.id}`);
400
+ console.log(` Content: ${post.content.substring(0, 80)}${post.content.length > 80 ? "..." : ""}`);
401
+ }
402
+ });
403
+
404
+ templateCmd
405
+ .command("delete")
406
+ .description("Delete a template")
407
+ .argument("<id>", "Template ID")
408
+ .action((id) => {
409
+ const deleted = deleteTemplate(id);
410
+ if (deleted) {
411
+ console.log(`Deleted template ${id}`);
412
+ } else {
413
+ console.error(`Template '${id}' not found.`);
414
+ process.exit(1);
415
+ }
416
+ });
417
+
418
+ // --- Stats ---
419
+
420
+ program
421
+ .command("stats")
422
+ .description("Overall statistics")
423
+ .option("--json", "Output as JSON", false)
424
+ .action((opts) => {
425
+ const stats = getOverallStats();
426
+
427
+ if (opts.json) {
428
+ console.log(JSON.stringify(stats, null, 2));
429
+ } else {
430
+ console.log("Social Media Stats:");
431
+ console.log(` Accounts: ${stats.total_accounts}`);
432
+ console.log(` Posts: ${stats.total_posts}`);
433
+ if (Object.keys(stats.posts_by_status).length) {
434
+ for (const [status, count] of Object.entries(stats.posts_by_status)) {
435
+ console.log(` ${status}: ${count}`);
436
+ }
437
+ }
438
+ console.log(` Templates: ${stats.total_templates}`);
439
+ console.log(` Published engagement:`);
440
+ console.log(` Likes: ${stats.engagement.total_likes}`);
441
+ console.log(` Shares: ${stats.engagement.total_shares}`);
442
+ console.log(` Comments: ${stats.engagement.total_comments}`);
443
+ console.log(` Impressions: ${stats.engagement.total_impressions}`);
444
+ }
445
+ });
446
+
447
+ program.parse(process.argv);
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Database connection for microservice-social
3
+ */
4
+
5
+ import { Database } from "bun:sqlite";
6
+ import { existsSync, mkdirSync } from "node:fs";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { MIGRATIONS } from "./migrations.js";
9
+
10
+ let _db: Database | null = null;
11
+
12
+ function getDbPath(): string {
13
+ // Environment variable override
14
+ if (process.env["MICROSERVICES_DIR"]) {
15
+ return join(process.env["MICROSERVICES_DIR"], "microservice-social", "data.db");
16
+ }
17
+
18
+ // Check for .microservices in current or parent directories
19
+ let dir = resolve(process.cwd());
20
+ while (true) {
21
+ const candidate = join(dir, ".microservices", "microservice-social", "data.db");
22
+ const msDir = join(dir, ".microservices");
23
+ if (existsSync(msDir)) return candidate;
24
+ const parent = dirname(dir);
25
+ if (parent === dir) break;
26
+ dir = parent;
27
+ }
28
+
29
+ // Global fallback
30
+ const home = process.env["HOME"] || process.env["USERPROFILE"] || "~";
31
+ return join(home, ".microservices", "microservice-social", "data.db");
32
+ }
33
+
34
+ function ensureDir(filePath: string): void {
35
+ const dir = dirname(resolve(filePath));
36
+ if (!existsSync(dir)) {
37
+ mkdirSync(dir, { recursive: true });
38
+ }
39
+ }
40
+
41
+ export function getDatabase(): Database {
42
+ if (_db) return _db;
43
+
44
+ const dbPath = getDbPath();
45
+ ensureDir(dbPath);
46
+
47
+ _db = new Database(dbPath);
48
+ _db.exec("PRAGMA journal_mode = WAL");
49
+ _db.exec("PRAGMA foreign_keys = ON");
50
+
51
+ // Create migrations table
52
+ _db.exec(`
53
+ CREATE TABLE IF NOT EXISTS _migrations (
54
+ id INTEGER PRIMARY KEY,
55
+ name TEXT NOT NULL,
56
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
57
+ )
58
+ `);
59
+
60
+ // Apply pending migrations
61
+ const applied = _db
62
+ .query("SELECT id FROM _migrations ORDER BY id")
63
+ .all() as { id: number }[];
64
+ const appliedIds = new Set(applied.map((r) => r.id));
65
+
66
+ for (const migration of MIGRATIONS) {
67
+ if (appliedIds.has(migration.id)) continue;
68
+
69
+ _db.exec("BEGIN");
70
+ try {
71
+ _db.exec(migration.sql);
72
+ _db.prepare("INSERT INTO _migrations (id, name) VALUES (?, ?)").run(
73
+ migration.id,
74
+ migration.name
75
+ );
76
+ _db.exec("COMMIT");
77
+ } catch (error) {
78
+ _db.exec("ROLLBACK");
79
+ throw new Error(
80
+ `Migration ${migration.id} (${migration.name}) failed: ${error instanceof Error ? error.message : String(error)}`
81
+ );
82
+ }
83
+ }
84
+
85
+ return _db;
86
+ }
87
+
88
+ export function closeDatabase(): void {
89
+ if (_db) {
90
+ _db.close();
91
+ _db = null;
92
+ }
93
+ }
@@ -0,0 +1,55 @@
1
+ export interface MigrationEntry {
2
+ id: number;
3
+ name: string;
4
+ sql: string;
5
+ }
6
+
7
+ export const MIGRATIONS: MigrationEntry[] = [
8
+ {
9
+ id: 1,
10
+ name: "initial_schema",
11
+ sql: `
12
+ CREATE TABLE IF NOT EXISTS accounts (
13
+ id TEXT PRIMARY KEY,
14
+ platform TEXT NOT NULL CHECK (platform IN ('x', 'linkedin', 'instagram', 'threads', 'bluesky')),
15
+ handle TEXT NOT NULL,
16
+ display_name TEXT,
17
+ connected INTEGER NOT NULL DEFAULT 0,
18
+ access_token_env TEXT,
19
+ metadata TEXT NOT NULL DEFAULT '{}',
20
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
21
+ );
22
+
23
+ CREATE TABLE IF NOT EXISTS posts (
24
+ id TEXT PRIMARY KEY,
25
+ account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
26
+ content TEXT NOT NULL,
27
+ media_urls TEXT NOT NULL DEFAULT '[]',
28
+ status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'scheduled', 'published', 'failed')),
29
+ scheduled_at TEXT,
30
+ published_at TEXT,
31
+ platform_post_id TEXT,
32
+ engagement TEXT NOT NULL DEFAULT '{}',
33
+ tags TEXT NOT NULL DEFAULT '[]',
34
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
35
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
36
+ );
37
+
38
+ CREATE TABLE IF NOT EXISTS templates (
39
+ id TEXT PRIMARY KEY,
40
+ name TEXT NOT NULL,
41
+ content TEXT NOT NULL,
42
+ variables TEXT NOT NULL DEFAULT '[]',
43
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
44
+ );
45
+
46
+ CREATE INDEX IF NOT EXISTS idx_accounts_platform ON accounts(platform);
47
+ CREATE INDEX IF NOT EXISTS idx_accounts_handle ON accounts(handle);
48
+ CREATE INDEX IF NOT EXISTS idx_posts_account ON posts(account_id);
49
+ CREATE INDEX IF NOT EXISTS idx_posts_status ON posts(status);
50
+ CREATE INDEX IF NOT EXISTS idx_posts_scheduled ON posts(scheduled_at);
51
+ CREATE INDEX IF NOT EXISTS idx_posts_published ON posts(published_at);
52
+ CREATE INDEX IF NOT EXISTS idx_templates_name ON templates(name);
53
+ `,
54
+ },
55
+ ];