@secondlayer/shared 2.0.0 → 3.0.0-alpha.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 (78) hide show
  1. package/README.md +2 -2
  2. package/dist/src/db/index.d.ts +64 -130
  3. package/dist/src/db/index.js.map +2 -2
  4. package/dist/src/db/jsonb.d.ts +5 -1
  5. package/dist/src/db/jsonb.js.map +2 -2
  6. package/dist/src/db/queries/account-spend-caps.d.ts +379 -0
  7. package/dist/src/db/queries/account-spend-caps.js +60 -0
  8. package/dist/src/db/queries/account-spend-caps.js.map +10 -0
  9. package/dist/src/db/queries/account-usage.d.ts +403 -0
  10. package/dist/src/db/queries/account-usage.js +222 -0
  11. package/dist/src/db/queries/account-usage.js.map +11 -0
  12. package/dist/src/db/queries/accounts.d.ts +61 -108
  13. package/dist/src/db/queries/accounts.js +15 -1
  14. package/dist/src/db/queries/accounts.js.map +3 -3
  15. package/dist/src/db/queries/integrity.d.ts +47 -107
  16. package/dist/src/db/queries/projects.d.ts +47 -107
  17. package/dist/src/db/queries/{workflows.d.ts → provisioning-audit.d.ts} +70 -142
  18. package/dist/src/db/queries/provisioning-audit.js +40 -0
  19. package/dist/src/db/queries/provisioning-audit.js.map +10 -0
  20. package/dist/src/db/queries/subgraph-gaps.d.ts +47 -107
  21. package/dist/src/db/queries/subgraphs.d.ts +47 -108
  22. package/dist/src/db/queries/subgraphs.js +2 -3
  23. package/dist/src/db/queries/subgraphs.js.map +4 -4
  24. package/dist/src/db/queries/{marketplace.d.ts → tenant-compute-addons.d.ts} +66 -159
  25. package/dist/src/db/queries/tenant-compute-addons.js +47 -0
  26. package/dist/src/db/queries/tenant-compute-addons.js.map +10 -0
  27. package/dist/src/db/queries/tenants.d.ts +67 -110
  28. package/dist/src/db/queries/tenants.js +35 -6
  29. package/dist/src/db/queries/tenants.js.map +3 -3
  30. package/dist/src/db/queries/usage.d.ts +48 -132
  31. package/dist/src/db/queries/usage.js +5 -64
  32. package/dist/src/db/queries/usage.js.map +4 -5
  33. package/dist/src/db/schema.d.ts +59 -129
  34. package/dist/src/errors.d.ts +8 -7
  35. package/dist/src/errors.js +11 -12
  36. package/dist/src/errors.js.map +3 -3
  37. package/dist/src/index.d.ts +98 -212
  38. package/dist/src/index.js +69 -80
  39. package/dist/src/index.js.map +6 -6
  40. package/dist/src/mode.d.ts +4 -5
  41. package/dist/src/mode.js.map +2 -2
  42. package/dist/src/node/local-client.d.ts +47 -107
  43. package/dist/src/pricing.d.ts +20 -1
  44. package/dist/src/pricing.js +58 -1
  45. package/dist/src/pricing.js.map +3 -3
  46. package/dist/src/schemas/accounts.d.ts +14 -0
  47. package/dist/src/schemas/{marketplace.js → accounts.js} +4 -14
  48. package/dist/src/schemas/accounts.js.map +10 -0
  49. package/dist/src/schemas/index.d.ts +28 -77
  50. package/dist/src/schemas/index.js +59 -69
  51. package/dist/src/schemas/index.js.map +4 -4
  52. package/migrations/0043_tenant_usage_monthly.ts +36 -0
  53. package/migrations/0044_provisioning_audit_log.ts +40 -0
  54. package/migrations/0045_drop_marketplace_columns.ts +47 -0
  55. package/migrations/0046_tenant_activity_signal.ts +47 -0
  56. package/migrations/0047_usage_daily_tenant_id.ts +73 -0
  57. package/migrations/0048_tenant_compute_addons.ts +49 -0
  58. package/migrations/0049_accounts_stripe_customer_id.ts +30 -0
  59. package/migrations/0050_account_spend_caps.ts +45 -0
  60. package/migrations/0051_workflow_ai_usage_daily.ts +40 -0
  61. package/migrations/0052_sentries.ts +61 -0
  62. package/migrations/0053_workflow_runtime.ts +88 -0
  63. package/migrations/0054_accounts_plan_hobby.ts +32 -0
  64. package/migrations/0055_ai_usage_account_scope.ts +108 -0
  65. package/migrations/0056_drop_workflow_sentry_residuals.ts +23 -0
  66. package/package.json +33 -21
  67. package/dist/src/db/queries/marketplace.js +0 -139
  68. package/dist/src/db/queries/marketplace.js.map +0 -10
  69. package/dist/src/db/queries/workflows.js +0 -260
  70. package/dist/src/db/queries/workflows.js.map +0 -12
  71. package/dist/src/lib/plans.d.ts +0 -9
  72. package/dist/src/lib/plans.js +0 -37
  73. package/dist/src/lib/plans.js.map +0 -10
  74. package/dist/src/schemas/marketplace.d.ts +0 -63
  75. package/dist/src/schemas/marketplace.js.map +0 -10
  76. package/dist/src/schemas/workflows.d.ts +0 -70
  77. package/dist/src/schemas/workflows.js +0 -43
  78. package/dist/src/schemas/workflows.js.map +0 -10
package/README.md CHANGED
@@ -24,10 +24,11 @@ DATABASE_URL=... bun run migrate
24
24
  |------|-------------|
25
25
  | `@secondlayer/shared` | Core utilities |
26
26
  | `@secondlayer/shared/db` | Kysely database layer |
27
- | `@secondlayer/shared/db/queries/*` | Query helpers (integrity, accounts, usage, subgraphs, marketplace, projects, subgraph-gaps, workflows) |
27
+ | `@secondlayer/shared/db/queries/*` | Query helpers (integrity, accounts, usage, subgraphs, projects, subgraph-gaps, tenants, provisioning-audit) |
28
28
  | `@secondlayer/shared/db/schema` | Database schema |
29
29
  | `@secondlayer/shared/db/jsonb` | JSONB helpers |
30
30
  | `@secondlayer/shared/schemas` | Zod schemas |
31
+ | `@secondlayer/shared/schemas/accounts` | Account profile schemas |
31
32
  | `@secondlayer/shared/schemas/filters` | Event filter schemas |
32
33
  | `@secondlayer/shared/schemas/subgraphs` | Subgraph schemas |
33
34
  | `@secondlayer/shared/types` | Shared TypeScript types |
@@ -38,4 +39,3 @@ DATABASE_URL=... bun run migrate
38
39
  | `@secondlayer/shared/crypto` | HMAC signing |
39
40
  | `@secondlayer/shared/node` | Stacks node client |
40
41
  | `@secondlayer/shared/node/hiro-pg-client` | Direct PG queries against Hiro DB |
41
- | `@secondlayer/shared/lib/plans` | Plan definitions |
@@ -3,8 +3,12 @@ import { RawBuilder } from "kysely";
3
3
  * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.
4
4
  * Kysely + postgres.js double-encodes JSON when using parameterized queries
5
5
  * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.
6
+ *
7
+ * Generic parameter lets callers set the RawBuilder's output type so they
8
+ * don't need to cast at the insert site. Default is `unknown` — widen at
9
+ * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.
6
10
  */
7
- declare function jsonb(value: unknown): RawBuilder<unknown>;
11
+ declare function jsonb<T = unknown>(value: T): RawBuilder<T>;
8
12
  /**
9
13
  * Safely parse a JSONB value from the database.
10
14
  * Handles double-encoded strings where postgres.js returns a JSON string
@@ -74,10 +78,6 @@ interface SubgraphsTable {
74
78
  handler_code: string | null;
75
79
  source_code: string | null;
76
80
  project_id: string | null;
77
- is_public: Generated<boolean>;
78
- tags: Generated<string[]>;
79
- description: string | null;
80
- forked_from_id: string | null;
81
81
  created_at: Generated<Date>;
82
82
  updated_at: Generated<Date>;
83
83
  }
@@ -112,6 +112,7 @@ interface AccountsTable {
112
112
  bio: string | null;
113
113
  avatar_url: string | null;
114
114
  slug: string | null;
115
+ stripe_customer_id: string | null;
115
116
  created_at: Generated<Date>;
116
117
  }
117
118
  interface SessionsTable {
@@ -137,6 +138,7 @@ interface MagicLinksTable {
137
138
  }
138
139
  interface UsageDailyTable {
139
140
  account_id: string;
141
+ tenant_id: string | null;
140
142
  date: string;
141
143
  api_requests: Generated<number>;
142
144
  deliveries: Generated<number>;
@@ -263,83 +265,6 @@ interface ChatMessagesTable {
263
265
  metadata: unknown | null;
264
266
  created_at: Generated<Date>;
265
267
  }
266
- interface WorkflowDefinitionsTable {
267
- id: Generated<string>;
268
- name: string;
269
- version: Generated<string>;
270
- status: Generated<string>;
271
- trigger_type: string;
272
- trigger_config: unknown;
273
- handler_path: string;
274
- source_code: string | null;
275
- retries_config: unknown | null;
276
- timeout_ms: number | null;
277
- api_key_id: string;
278
- project_id: string | null;
279
- created_at: Generated<Date>;
280
- updated_at: Generated<Date>;
281
- }
282
- interface WorkflowRunsTable {
283
- id: Generated<string>;
284
- definition_id: string;
285
- status: Generated<string>;
286
- trigger_type: string;
287
- trigger_data: unknown | null;
288
- dedup_key: string | null;
289
- error: string | null;
290
- started_at: Date | null;
291
- completed_at: Date | null;
292
- duration_ms: number | null;
293
- total_ai_tokens: Generated<number>;
294
- created_at: Generated<Date>;
295
- }
296
- interface WorkflowStepsTable {
297
- id: Generated<string>;
298
- run_id: string;
299
- step_index: number;
300
- step_id: string;
301
- step_type: string;
302
- status: Generated<string>;
303
- input: unknown | null;
304
- output: unknown | null;
305
- error: string | null;
306
- retry_count: Generated<number>;
307
- ai_tokens_used: Generated<number>;
308
- started_at: Date | null;
309
- completed_at: Date | null;
310
- duration_ms: number | null;
311
- memo_key: string | null;
312
- parent_step_id: string | null;
313
- created_at: Generated<Date>;
314
- }
315
- interface WorkflowQueueTable {
316
- id: Generated<string>;
317
- run_id: string;
318
- status: Generated<string>;
319
- attempts: Generated<number>;
320
- max_attempts: Generated<number>;
321
- scheduled_for: Generated<Date>;
322
- locked_at: Date | null;
323
- locked_by: string | null;
324
- error: string | null;
325
- created_at: Generated<Date>;
326
- completed_at: Date | null;
327
- }
328
- interface WorkflowSchedulesTable {
329
- id: Generated<string>;
330
- definition_id: string;
331
- cron_expr: string;
332
- timezone: Generated<string>;
333
- next_run_at: Date;
334
- last_run_at: Date | null;
335
- enabled: Generated<boolean>;
336
- created_at: Generated<Date>;
337
- }
338
- interface WorkflowCursorsTable {
339
- name: string;
340
- block_height: Generated<number>;
341
- updated_at: Generated<Date>;
342
- }
343
268
  interface Database {
344
269
  blocks: BlocksTable;
345
270
  transactions: TransactionsTable;
@@ -365,15 +290,11 @@ interface Database {
365
290
  team_invitations: TeamInvitationsTable;
366
291
  chat_sessions: ChatSessionsTable;
367
292
  chat_messages: ChatMessagesTable;
368
- workflow_definitions: WorkflowDefinitionsTable;
369
- workflow_runs: WorkflowRunsTable;
370
- workflow_steps: WorkflowStepsTable;
371
- workflow_queue: WorkflowQueueTable;
372
- workflow_schedules: WorkflowSchedulesTable;
373
- workflow_cursors: WorkflowCursorsTable;
374
- workflow_signer_secrets: WorkflowSignerSecretsTable;
375
- workflow_budgets: WorkflowBudgetsTable;
376
293
  tenants: TenantsTable;
294
+ tenant_usage_monthly: TenantUsageMonthlyTable;
295
+ tenant_compute_addons: TenantComputeAddonsTable;
296
+ account_spend_caps: AccountSpendCapsTable;
297
+ provisioning_audit_log: ProvisioningAuditLogTable;
377
298
  }
378
299
  type TenantStatus = "provisioning" | "active" | "suspended" | "error" | "deleted";
379
300
  interface TenantsTable {
@@ -395,9 +316,9 @@ interface TenantsTable {
395
316
  service_key_enc: Buffer;
396
317
  api_url_internal: string;
397
318
  api_url_public: string;
398
- trial_ends_at: Date;
399
319
  suspended_at: Date | null;
400
320
  last_health_check_at: Date | null;
321
+ last_active_at: Generated<Date>;
401
322
  service_gen: Generated<number>;
402
323
  anon_gen: Generated<number>;
403
324
  project_id: string | null;
@@ -407,30 +328,64 @@ interface TenantsTable {
407
328
  type Tenant = Selectable<TenantsTable>;
408
329
  type InsertTenant = Insertable<TenantsTable>;
409
330
  type UpdateTenant = Updateable<TenantsTable>;
410
- interface WorkflowBudgetsTable {
331
+ interface TenantUsageMonthlyTable {
411
332
  id: Generated<string>;
412
- workflow_definition_id: string;
413
- /** Period key: "daily:YYYY-MM-DD" | "weekly:YYYY-Www" | "per-run:<uuid>". */
414
- period: string;
415
- ai_usd_used: Generated<string>;
416
- ai_tokens_used: Generated<string>;
417
- chain_microstx_used: Generated<string>;
418
- chain_tx_count: Generated<number>;
419
- run_count: Generated<number>;
420
- step_count: Generated<number>;
421
- reset_at: Date;
333
+ tenant_id: string;
334
+ period_month: Date;
335
+ storage_peak_mb: Generated<number>;
336
+ storage_avg_mb: Generated<number>;
337
+ storage_last_mb: Generated<number>;
338
+ measurements: Generated<number>;
339
+ first_at: Generated<Date>;
340
+ last_at: Generated<Date>;
341
+ }
342
+ type TenantUsageMonthly = Selectable<TenantUsageMonthlyTable>;
343
+ type InsertTenantUsageMonthly = Insertable<TenantUsageMonthlyTable>;
344
+ type UpdateTenantUsageMonthly = Updateable<TenantUsageMonthlyTable>;
345
+ interface TenantComputeAddonsTable {
346
+ id: Generated<string>;
347
+ tenant_id: string;
348
+ memory_mb_delta: Generated<number>;
349
+ cpu_delta: Generated<number | string>;
350
+ storage_mb_delta: Generated<number>;
351
+ effective_from: Generated<Date>;
352
+ effective_until: Date | null;
353
+ stripe_subscription_item_id: string | null;
422
354
  created_at: Generated<Date>;
355
+ }
356
+ type TenantComputeAddon = Selectable<TenantComputeAddonsTable>;
357
+ type InsertTenantComputeAddon = Insertable<TenantComputeAddonsTable>;
358
+ type UpdateTenantComputeAddon = Updateable<TenantComputeAddonsTable>;
359
+ interface AccountSpendCapsTable {
360
+ account_id: string;
361
+ monthly_cap_cents: number | null;
362
+ compute_cap_cents: number | null;
363
+ storage_cap_cents: number | null;
364
+ ai_cap_cents: number | null;
365
+ alert_threshold_pct: Generated<number>;
366
+ alert_sent_at: Date | null;
367
+ frozen_at: Date | null;
423
368
  updated_at: Generated<Date>;
424
369
  }
425
- interface WorkflowSignerSecretsTable {
370
+ type AccountSpendCap = Selectable<AccountSpendCapsTable>;
371
+ type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;
372
+ type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;
373
+ type ProvisioningAuditEvent = "provision.start" | "provision.success" | "provision.failure" | "suspend" | "resume" | "resize" | "keys.rotate" | "bastion.key.upload" | "bastion.key.revoke" | "teardown";
374
+ type ProvisioningAuditStatus = "ok" | "error";
375
+ interface ProvisioningAuditLogTable {
426
376
  id: Generated<string>;
427
- account_id: string;
428
- name: string;
429
- /** AES-GCM ciphertext bytes produced by the runner's KMS on write. */
430
- encrypted_value: Buffer;
377
+ tenant_id: string | null;
378
+ tenant_slug: string | null;
379
+ account_id: string | null;
380
+ actor: string;
381
+ event: ProvisioningAuditEvent;
382
+ status: ProvisioningAuditStatus;
383
+ detail: unknown | null;
384
+ error: string | null;
431
385
  created_at: Generated<Date>;
432
- updated_at: Generated<Date>;
433
386
  }
387
+ type ProvisioningAuditLog = Selectable<ProvisioningAuditLogTable>;
388
+ type InsertProvisioningAuditLog = Insertable<ProvisioningAuditLogTable>;
434
389
  type Block = Selectable<BlocksTable>;
435
390
  type InsertBlock = Insertable<BlocksTable>;
436
391
  type UpdateBlock = Updateable<BlocksTable>;
@@ -467,27 +422,6 @@ type SubgraphGap = Selectable<SubgraphGapsTable>;
467
422
  type InsertSubgraphGap = Insertable<SubgraphGapsTable>;
468
423
  type SubgraphUsageDaily = Selectable<SubgraphUsageDailyTable>;
469
424
  type InsertSubgraphUsageDaily = Insertable<SubgraphUsageDailyTable>;
470
- type WorkflowDefinition = Selectable<WorkflowDefinitionsTable>;
471
- type InsertWorkflowDefinition = Insertable<WorkflowDefinitionsTable>;
472
- type UpdateWorkflowDefinition = Updateable<WorkflowDefinitionsTable>;
473
- type WorkflowRun = Selectable<WorkflowRunsTable>;
474
- type InsertWorkflowRun = Insertable<WorkflowRunsTable>;
475
- type UpdateWorkflowRun = Updateable<WorkflowRunsTable>;
476
- type WorkflowStep = Selectable<WorkflowStepsTable>;
477
- type InsertWorkflowStep = Insertable<WorkflowStepsTable>;
478
- type UpdateWorkflowStep = Updateable<WorkflowStepsTable>;
479
- type WorkflowQueueItem = Selectable<WorkflowQueueTable>;
480
- type InsertWorkflowQueueItem = Insertable<WorkflowQueueTable>;
481
- type WorkflowSchedule = Selectable<WorkflowSchedulesTable>;
482
- type InsertWorkflowSchedule = Insertable<WorkflowSchedulesTable>;
483
- type UpdateWorkflowSchedule = Updateable<WorkflowSchedulesTable>;
484
- type WorkflowCursor = Selectable<WorkflowCursorsTable>;
485
- type WorkflowSignerSecret = Selectable<WorkflowSignerSecretsTable>;
486
- type InsertWorkflowSignerSecret = Insertable<WorkflowSignerSecretsTable>;
487
- type UpdateWorkflowSignerSecret = Updateable<WorkflowSignerSecretsTable>;
488
- type WorkflowBudget = Selectable<WorkflowBudgetsTable>;
489
- type InsertWorkflowBudget = Insertable<WorkflowBudgetsTable>;
490
- type UpdateWorkflowBudget = Updateable<WorkflowBudgetsTable>;
491
425
  type Project = Selectable<ProjectsTable>;
492
426
  type InsertProject = Insertable<ProjectsTable>;
493
427
  type UpdateProject = Updateable<ProjectsTable>;
@@ -525,4 +459,4 @@ declare function getDb(connectionString?: string): Kysely<Database>;
525
459
  declare function getRawClient(role?: "source" | "target"): ReturnType<typeof postgres>;
526
460
  /** Close all DB connection pools. Call in CLI commands to allow process exit. */
527
461
  declare function closeDb(): Promise<void>;
528
- export { sql, parseJsonb, jsonb, getTargetDb, getSourceDb, getRawClient, getDb, closeDb, WorkflowStepsTable, WorkflowStep, WorkflowSignerSecretsTable, WorkflowSignerSecret, WorkflowSchedulesTable, WorkflowSchedule, WorkflowRunsTable, WorkflowRun, WorkflowQueueTable, WorkflowQueueItem, WorkflowDefinitionsTable, WorkflowDefinition, WorkflowCursorsTable, WorkflowCursor, WorkflowBudgetsTable, WorkflowBudget, WaitlistTable, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateWorkflowStep, UpdateWorkflowSignerSecret, UpdateWorkflowSchedule, UpdateWorkflowRun, UpdateWorkflowDefinition, UpdateWorkflowBudget, UpdateTransaction, UpdateTenant, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateChatSession, UpdateBlock, UpdateApiKey, TransactionsTable, Transaction, TenantsTable, TenantStatus, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, SessionsTable, Session, ProjectsTable, Project, MagicLinksTable, MagicLink, InsertWorkflowStep, InsertWorkflowSignerSecret, InsertWorkflowSchedule, InsertWorkflowRun, InsertWorkflowQueueItem, InsertWorkflowDefinition, InsertWorkflowBudget, InsertTransaction, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubgraphUsageDaily, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProject, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, EventsTable, Event, Database, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
462
+ export { sql, parseJsonb, jsonb, getTargetDb, getSourceDb, getRawClient, getDb, closeDb, WaitlistTable, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateTransaction, UpdateTenantUsageMonthly, UpdateTenantComputeAddon, UpdateTenant, UpdateSubgraph, UpdateProject, UpdateIndexProgress, UpdateEvent, UpdateChatSession, UpdateBlock, UpdateApiKey, UpdateAccountSpendCap, TransactionsTable, Transaction, TenantsTable, TenantUsageMonthlyTable, TenantUsageMonthly, TenantStatus, TenantComputeAddonsTable, TenantComputeAddon, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphProcessingStatsTable, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGap, Subgraph, SessionsTable, Session, ProvisioningAuditStatus, ProvisioningAuditLogTable, ProvisioningAuditLog, ProvisioningAuditEvent, ProjectsTable, Project, MagicLinksTable, MagicLink, InsertTransaction, InsertTenantUsageMonthly, InsertTenantComputeAddon, InsertTenant, InsertTeamMember, InsertTeamInvitation, InsertSubgraphUsageDaily, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProvisioningAuditLog, InsertProject, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountSpendCap, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, EventsTable, Event, Database, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, BlocksTable, Block, ApiKeysTable, ApiKey, AccountsTable, AccountSpendCapsTable, AccountSpendCap, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
@@ -2,10 +2,10 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/jsonb.ts", "../src/db/index.ts"],
4
4
  "sourcesContent": [
5
- "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n */\nexport function jsonb(value: unknown): RawBuilder<unknown> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
5
+ "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n",
6
6
  "import { Kysely } from \"kysely\";\nimport { PostgresJSDialect } from \"kysely-postgres-js\";\nimport postgres from \"postgres\";\nimport type { Database } from \"./types.ts\";\n\nconst DEFAULT_URL =\n\t\"postgres://postgres:postgres@localhost:5432/secondlayer_dev\";\n\ninterface PoolEntry {\n\tdb: Kysely<Database>;\n\trawClient: ReturnType<typeof postgres>;\n}\n\n/**\n * Cache of Kysely + raw postgres.js pools keyed by resolved URL.\n * Two getters resolving to the same URL share one entry (single pool) —\n * this is the single-DB backward-compat contract: when only `DATABASE_URL`\n * is set, `getSourceDb() === getTargetDb()` (zero regression vs. pre-dual-DB).\n */\nconst pools = new Map<string, PoolEntry>();\n\nfunction resolveSourceUrl(): string {\n\treturn (\n\t\tprocess.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction resolveTargetUrl(): string {\n\treturn (\n\t\tprocess.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL\n\t);\n}\n\nfunction getOrCreatePool(url: string): PoolEntry {\n\tconst existing = pools.get(url);\n\tif (existing) return existing;\n\n\t// \"Local\" = we skip TLS. Any Docker service alias (single-label hostname\n\t// with no dots) is on an internal network and won't serve TLS.\n\tconst host = (() => {\n\t\ttry {\n\t\t\treturn new URL(url).hostname;\n\t\t} catch {\n\t\t\treturn \"\";\n\t\t}\n\t})();\n\tconst isLocal =\n\t\thost === \"localhost\" || host === \"127.0.0.1\" || !host.includes(\".\");\n\tconst poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? \"20\", 10);\n\tconst rawClient = postgres(url, {\n\t\tmax: poolMax,\n\t\tssl: isLocal\n\t\t\t? undefined\n\t\t\t: {\n\t\t\t\t\trejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== \"0\",\n\t\t\t\t},\n\t});\n\tconst db = new Kysely<Database>({\n\t\tdialect: new PostgresJSDialect({ postgres: rawClient }),\n\t});\n\tconst entry: PoolEntry = { db, rawClient };\n\tpools.set(url, entry);\n\treturn entry;\n}\n\n/**\n * Kysely instance for the SOURCE DB (block/tx/event reads from the shared\n * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.\n */\nexport function getSourceDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveSourceUrl()).db;\n}\n\n/**\n * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,\n * account-scoped data — tenant-side writes). Resolution:\n * `TARGET_DATABASE_URL || DATABASE_URL`.\n */\nexport function getTargetDb(): Kysely<Database> {\n\treturn getOrCreatePool(resolveTargetUrl()).db;\n}\n\n/**\n * Backward-compat alias for `getTargetDb()`. Accepts an optional\n * `connectionString` override used by seed/test helpers — when supplied,\n * bypasses env resolution and uses the provided URL directly (still cached).\n */\nexport function getDb(connectionString?: string): Kysely<Database> {\n\tif (connectionString) return getOrCreatePool(connectionString).db;\n\treturn getTargetDb();\n}\n\n/**\n * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).\n * Defaults to the target role (tenant schemas live in the target DB).\n */\nexport function getRawClient(\n\trole: \"source\" | \"target\" = \"target\",\n): ReturnType<typeof postgres> {\n\tconst url = role === \"source\" ? resolveSourceUrl() : resolveTargetUrl();\n\treturn getOrCreatePool(url).rawClient;\n}\n\n/** Close all DB connection pools. Call in CLI commands to allow process exit. */\nexport async function closeDb(): Promise<void> {\n\tfor (const entry of pools.values()) {\n\t\tawait entry.db.destroy();\n\t\tawait entry.rawClient.end();\n\t}\n\tpools.clear();\n}\n\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;AAAA;AAOD,SAAS,WAAW,GAAqB;AAAA,EAC/C,OAAO,gBAAgB,iBAAiB,CAAC,EAAE;AAAA;AAQrC,SAAS,WAAW,GAAqB;AAAA,EAC/C,OAAO,gBAAgB,iBAAiB,CAAC,EAAE;AAAA;AAQrC,SAAS,KAAK,CAAC,kBAA6C;AAAA,EAClE,IAAI;AAAA,IAAkB,OAAO,gBAAgB,gBAAgB,EAAE;AAAA,EAC/D,OAAO,YAAY;AAAA;AAOb,SAAS,YAAY,CAC3B,OAA4B,UACE;AAAA,EAC9B,MAAM,MAAM,SAAS,WAAW,iBAAiB,IAAI,iBAAiB;AAAA,EACtE,OAAO,gBAAgB,GAAG,EAAE;AAAA;AAI7B,eAAsB,OAAO,GAAkB;AAAA,EAC9C,WAAW,SAAS,MAAM,OAAO,GAAG;AAAA,IACnC,MAAM,MAAM,GAAG,QAAQ;AAAA,IACvB,MAAM,MAAM,UAAU,IAAI;AAAA,EAC3B;AAAA,EACA,MAAM,MAAM;AAAA;",
9
9
  "debugId": "C0DD7408E000897364756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -3,8 +3,12 @@ import { RawBuilder } from "kysely";
3
3
  * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.
4
4
  * Kysely + postgres.js double-encodes JSON when using parameterized queries
5
5
  * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.
6
+ *
7
+ * Generic parameter lets callers set the RawBuilder's output type so they
8
+ * don't need to cast at the insert site. Default is `unknown` — widen at
9
+ * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.
6
10
  */
7
- declare function jsonb(value: unknown): RawBuilder<unknown>;
11
+ declare function jsonb<T = unknown>(value: T): RawBuilder<T>;
8
12
  /**
9
13
  * Safely parse a JSONB value from the database.
10
14
  * Handles double-encoded strings where postgres.js returns a JSON string
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/db/jsonb.ts"],
4
4
  "sourcesContent": [
5
- "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n */\nexport function jsonb(value: unknown): RawBuilder<unknown> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n"
5
+ "import { type RawBuilder, sql } from \"kysely\";\n\n/**\n * Safely encode a JS value as a JSONB literal for Kysely inserts/updates.\n * Kysely + postgres.js double-encodes JSON when using parameterized queries\n * with ::jsonb casts. This uses sql.raw to inline a properly escaped literal.\n *\n * Generic parameter lets callers set the RawBuilder's output type so they\n * don't need to cast at the insert site. Default is `unknown` — widen at\n * the call site when the column type is narrower, e.g. `jsonb<MyShape>(...)`.\n */\nexport function jsonb<T = unknown>(value: T): RawBuilder<T> {\n\tconst escaped = JSON.stringify(value, (_k, v) =>\n\t\ttypeof v === \"bigint\" ? v.toString() : v,\n\t).replace(/'/g, \"''\");\n\treturn sql`${sql.raw(`'${escaped}'::jsonb`)}`;\n}\n\n/**\n * Safely parse a JSONB value from the database.\n * Handles double-encoded strings where postgres.js returns a JSON string\n * instead of a parsed object.\n */\nexport function parseJsonb<T = unknown>(value: unknown): T {\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\treturn JSON.parse(value) as T;\n\t\t} catch {\n\t\t\treturn value as T;\n\t\t}\n\t}\n\treturn (value ?? {}) as T;\n}\n"
6
6
  ],
7
- "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAOO,SAAS,KAAK,CAAC,OAAqC;AAAA,EAC1D,MAAM,UAAU,KAAK,UAAU,OAAO,CAAC,IAAI,MAC1C,OAAO,MAAM,WAAW,EAAE,SAAS,IAAI,CACxC,EAAE,QAAQ,MAAM,IAAI;AAAA,EACpB,OAAO,MAAM,IAAI,IAAI,IAAI,iBAAiB;AAAA;AAQpC,SAAS,UAAuB,CAAC,OAAmB;AAAA,EAC1D,IAAI,OAAO,UAAU,UAAU;AAAA,IAC9B,IAAI;AAAA,MACH,OAAO,KAAK,MAAM,KAAK;AAAA,MACtB,MAAM;AAAA,MACP,OAAO;AAAA;AAAA,EAET;AAAA,EACA,OAAQ,SAAS,CAAC;AAAA;",
7
+ "mappings": ";;;;;;;;;;;;;;;;;AAAA;AAWO,SAAS,KAAkB,CAAC,OAAyB;AAAA,EAC3D,MAAM,UAAU,KAAK,UAAU,OAAO,CAAC,IAAI,MAC1C,OAAO,MAAM,WAAW,EAAE,SAAS,IAAI,CACxC,EAAE,QAAQ,MAAM,IAAI;AAAA,EACpB,OAAO,MAAM,IAAI,IAAI,IAAI,iBAAiB;AAAA;AAQpC,SAAS,UAAuB,CAAC,OAAmB;AAAA,EAC1D,IAAI,OAAO,UAAU,UAAU;AAAA,IAC9B,IAAI;AAAA,MACH,OAAO,KAAK,MAAM,KAAK;AAAA,MACtB,MAAM;AAAA,MACP,OAAO;AAAA;AAAA,EAET;AAAA,EACA,OAAQ,SAAS,CAAC;AAAA;",
8
8
  "debugId": "DA6ABA81E2ABDC7864756E2164756E21",
9
9
  "names": []
10
10
  }