@secondlayer/shared 2.1.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.
- package/README.md +2 -2
- package/dist/src/db/index.d.ts +39 -137
- package/dist/src/db/index.js.map +2 -2
- package/dist/src/db/jsonb.d.ts +5 -1
- package/dist/src/db/jsonb.js.map +2 -2
- package/dist/src/db/queries/account-spend-caps.d.ts +379 -0
- package/dist/src/db/queries/account-spend-caps.js +60 -0
- package/dist/src/db/queries/account-spend-caps.js.map +10 -0
- package/dist/src/db/queries/account-usage.d.ts +403 -0
- package/dist/src/db/queries/account-usage.js +222 -0
- package/dist/src/db/queries/account-usage.js.map +11 -0
- package/dist/src/db/queries/accounts.d.ts +41 -115
- package/dist/src/db/queries/accounts.js +15 -1
- package/dist/src/db/queries/accounts.js.map +3 -3
- package/dist/src/db/queries/integrity.d.ts +27 -114
- package/dist/src/db/queries/projects.d.ts +27 -114
- package/dist/src/db/queries/provisioning-audit.d.ts +27 -114
- package/dist/src/db/queries/subgraph-gaps.d.ts +27 -114
- package/dist/src/db/queries/subgraphs.d.ts +27 -115
- package/dist/src/db/queries/subgraphs.js +2 -3
- package/dist/src/db/queries/subgraphs.js.map +4 -4
- package/dist/src/db/queries/{workflows.d.ts → tenant-compute-addons.d.ts} +50 -149
- package/dist/src/db/queries/tenant-compute-addons.js +47 -0
- package/dist/src/db/queries/tenant-compute-addons.js.map +10 -0
- package/dist/src/db/queries/tenants.d.ts +40 -117
- package/dist/src/db/queries/tenants.js +9 -6
- package/dist/src/db/queries/tenants.js.map +3 -3
- package/dist/src/db/queries/usage.d.ts +28 -139
- package/dist/src/db/queries/usage.js +5 -64
- package/dist/src/db/queries/usage.js.map +4 -5
- package/dist/src/db/schema.d.ts +34 -136
- package/dist/src/errors.d.ts +8 -7
- package/dist/src/errors.js +11 -12
- package/dist/src/errors.js.map +3 -3
- package/dist/src/index.d.ts +46 -143
- package/dist/src/index.js +11 -12
- package/dist/src/index.js.map +4 -4
- package/dist/src/node/local-client.d.ts +27 -114
- package/dist/src/pricing.d.ts +20 -1
- package/dist/src/pricing.js +58 -1
- package/dist/src/pricing.js.map +3 -3
- package/migrations/0045_drop_marketplace_columns.ts +47 -0
- package/migrations/0046_tenant_activity_signal.ts +47 -0
- package/migrations/0047_usage_daily_tenant_id.ts +73 -0
- package/migrations/0048_tenant_compute_addons.ts +49 -0
- package/migrations/0049_accounts_stripe_customer_id.ts +30 -0
- package/migrations/0050_account_spend_caps.ts +45 -0
- package/migrations/0051_workflow_ai_usage_daily.ts +40 -0
- package/migrations/0052_sentries.ts +61 -0
- package/migrations/0053_workflow_runtime.ts +88 -0
- package/migrations/0054_accounts_plan_hobby.ts +32 -0
- package/migrations/0055_ai_usage_account_scope.ts +108 -0
- package/migrations/0056_drop_workflow_sentry_residuals.ts +23 -0
- package/package.json +26 -14
- package/dist/src/db/queries/workflows.js +0 -260
- package/dist/src/db/queries/workflows.js.map +0 -12
- package/dist/src/lib/plans.d.ts +0 -9
- package/dist/src/lib/plans.js +0 -37
- package/dist/src/lib/plans.js.map +0 -10
- package/dist/src/schemas/workflows.d.ts +0 -70
- package/dist/src/schemas/workflows.js +0 -43
- 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,
|
|
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 |
|
package/dist/src/db/index.d.ts
CHANGED
|
@@ -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:
|
|
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,16 +290,10 @@ 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;
|
|
377
294
|
tenant_usage_monthly: TenantUsageMonthlyTable;
|
|
295
|
+
tenant_compute_addons: TenantComputeAddonsTable;
|
|
296
|
+
account_spend_caps: AccountSpendCapsTable;
|
|
378
297
|
provisioning_audit_log: ProvisioningAuditLogTable;
|
|
379
298
|
}
|
|
380
299
|
type TenantStatus = "provisioning" | "active" | "suspended" | "error" | "deleted";
|
|
@@ -397,9 +316,9 @@ interface TenantsTable {
|
|
|
397
316
|
service_key_enc: Buffer;
|
|
398
317
|
api_url_internal: string;
|
|
399
318
|
api_url_public: string;
|
|
400
|
-
trial_ends_at: Date;
|
|
401
319
|
suspended_at: Date | null;
|
|
402
320
|
last_health_check_at: Date | null;
|
|
321
|
+
last_active_at: Generated<Date>;
|
|
403
322
|
service_gen: Generated<number>;
|
|
404
323
|
anon_gen: Generated<number>;
|
|
405
324
|
project_id: string | null;
|
|
@@ -423,6 +342,34 @@ interface TenantUsageMonthlyTable {
|
|
|
423
342
|
type TenantUsageMonthly = Selectable<TenantUsageMonthlyTable>;
|
|
424
343
|
type InsertTenantUsageMonthly = Insertable<TenantUsageMonthlyTable>;
|
|
425
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;
|
|
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;
|
|
368
|
+
updated_at: Generated<Date>;
|
|
369
|
+
}
|
|
370
|
+
type AccountSpendCap = Selectable<AccountSpendCapsTable>;
|
|
371
|
+
type InsertAccountSpendCap = Insertable<AccountSpendCapsTable>;
|
|
372
|
+
type UpdateAccountSpendCap = Updateable<AccountSpendCapsTable>;
|
|
426
373
|
type ProvisioningAuditEvent = "provision.start" | "provision.success" | "provision.failure" | "suspend" | "resume" | "resize" | "keys.rotate" | "bastion.key.upload" | "bastion.key.revoke" | "teardown";
|
|
427
374
|
type ProvisioningAuditStatus = "ok" | "error";
|
|
428
375
|
interface ProvisioningAuditLogTable {
|
|
@@ -439,30 +386,6 @@ interface ProvisioningAuditLogTable {
|
|
|
439
386
|
}
|
|
440
387
|
type ProvisioningAuditLog = Selectable<ProvisioningAuditLogTable>;
|
|
441
388
|
type InsertProvisioningAuditLog = Insertable<ProvisioningAuditLogTable>;
|
|
442
|
-
interface WorkflowBudgetsTable {
|
|
443
|
-
id: Generated<string>;
|
|
444
|
-
workflow_definition_id: string;
|
|
445
|
-
/** Period key: "daily:YYYY-MM-DD" | "weekly:YYYY-Www" | "per-run:<uuid>". */
|
|
446
|
-
period: string;
|
|
447
|
-
ai_usd_used: Generated<string>;
|
|
448
|
-
ai_tokens_used: Generated<string>;
|
|
449
|
-
chain_microstx_used: Generated<string>;
|
|
450
|
-
chain_tx_count: Generated<number>;
|
|
451
|
-
run_count: Generated<number>;
|
|
452
|
-
step_count: Generated<number>;
|
|
453
|
-
reset_at: Date;
|
|
454
|
-
created_at: Generated<Date>;
|
|
455
|
-
updated_at: Generated<Date>;
|
|
456
|
-
}
|
|
457
|
-
interface WorkflowSignerSecretsTable {
|
|
458
|
-
id: Generated<string>;
|
|
459
|
-
account_id: string;
|
|
460
|
-
name: string;
|
|
461
|
-
/** AES-GCM ciphertext bytes produced by the runner's KMS on write. */
|
|
462
|
-
encrypted_value: Buffer;
|
|
463
|
-
created_at: Generated<Date>;
|
|
464
|
-
updated_at: Generated<Date>;
|
|
465
|
-
}
|
|
466
389
|
type Block = Selectable<BlocksTable>;
|
|
467
390
|
type InsertBlock = Insertable<BlocksTable>;
|
|
468
391
|
type UpdateBlock = Updateable<BlocksTable>;
|
|
@@ -499,27 +422,6 @@ type SubgraphGap = Selectable<SubgraphGapsTable>;
|
|
|
499
422
|
type InsertSubgraphGap = Insertable<SubgraphGapsTable>;
|
|
500
423
|
type SubgraphUsageDaily = Selectable<SubgraphUsageDailyTable>;
|
|
501
424
|
type InsertSubgraphUsageDaily = Insertable<SubgraphUsageDailyTable>;
|
|
502
|
-
type WorkflowDefinition = Selectable<WorkflowDefinitionsTable>;
|
|
503
|
-
type InsertWorkflowDefinition = Insertable<WorkflowDefinitionsTable>;
|
|
504
|
-
type UpdateWorkflowDefinition = Updateable<WorkflowDefinitionsTable>;
|
|
505
|
-
type WorkflowRun = Selectable<WorkflowRunsTable>;
|
|
506
|
-
type InsertWorkflowRun = Insertable<WorkflowRunsTable>;
|
|
507
|
-
type UpdateWorkflowRun = Updateable<WorkflowRunsTable>;
|
|
508
|
-
type WorkflowStep = Selectable<WorkflowStepsTable>;
|
|
509
|
-
type InsertWorkflowStep = Insertable<WorkflowStepsTable>;
|
|
510
|
-
type UpdateWorkflowStep = Updateable<WorkflowStepsTable>;
|
|
511
|
-
type WorkflowQueueItem = Selectable<WorkflowQueueTable>;
|
|
512
|
-
type InsertWorkflowQueueItem = Insertable<WorkflowQueueTable>;
|
|
513
|
-
type WorkflowSchedule = Selectable<WorkflowSchedulesTable>;
|
|
514
|
-
type InsertWorkflowSchedule = Insertable<WorkflowSchedulesTable>;
|
|
515
|
-
type UpdateWorkflowSchedule = Updateable<WorkflowSchedulesTable>;
|
|
516
|
-
type WorkflowCursor = Selectable<WorkflowCursorsTable>;
|
|
517
|
-
type WorkflowSignerSecret = Selectable<WorkflowSignerSecretsTable>;
|
|
518
|
-
type InsertWorkflowSignerSecret = Insertable<WorkflowSignerSecretsTable>;
|
|
519
|
-
type UpdateWorkflowSignerSecret = Updateable<WorkflowSignerSecretsTable>;
|
|
520
|
-
type WorkflowBudget = Selectable<WorkflowBudgetsTable>;
|
|
521
|
-
type InsertWorkflowBudget = Insertable<WorkflowBudgetsTable>;
|
|
522
|
-
type UpdateWorkflowBudget = Updateable<WorkflowBudgetsTable>;
|
|
523
425
|
type Project = Selectable<ProjectsTable>;
|
|
524
426
|
type InsertProject = Insertable<ProjectsTable>;
|
|
525
427
|
type UpdateProject = Updateable<ProjectsTable>;
|
|
@@ -557,4 +459,4 @@ declare function getDb(connectionString?: string): Kysely<Database>;
|
|
|
557
459
|
declare function getRawClient(role?: "source" | "target"): ReturnType<typeof postgres>;
|
|
558
460
|
/** Close all DB connection pools. Call in CLI commands to allow process exit. */
|
|
559
461
|
declare function closeDb(): Promise<void>;
|
|
560
|
-
export { sql, parseJsonb, jsonb, getTargetDb, getSourceDb, getRawClient, getDb, closeDb,
|
|
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 };
|
package/dist/src/db/index.js.map
CHANGED
|
@@ -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:
|
|
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\nimport { sql } from \"kysely\";\nexport { sql };\nexport * from \"./types.ts\";\nexport { jsonb, parseJsonb } from \"./jsonb.ts\";\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";;;;;;;;;;;;;;;;;AAAA;
|
|
8
|
+
"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;;;AC/BnB;AACA;AACA;AA8GA,gBAAS;AA3GT,IAAM,cACL;AAaD,IAAM,QAAQ,IAAI;AAElB,SAAS,gBAAgB,GAAW;AAAA,EACnC,OACC,QAAQ,IAAI,uBAAuB,QAAQ,IAAI,gBAAgB;AAAA;AAIjE,SAAS,gBAAgB,GAAW;AAAA,EACnC,OACC,QAAQ,IAAI,uBAAuB,QAAQ,IAAI,gBAAgB;AAAA;AAIjE,SAAS,eAAe,CAAC,KAAwB;AAAA,EAChD,MAAM,WAAW,MAAM,IAAI,GAAG;AAAA,EAC9B,IAAI;AAAA,IAAU,OAAO;AAAA,EAIrB,MAAM,QAAQ,MAAM;AAAA,IACnB,IAAI;AAAA,MACH,OAAO,IAAI,IAAI,GAAG,EAAE;AAAA,MACnB,MAAM;AAAA,MACP,OAAO;AAAA;AAAA,KAEN;AAAA,EACH,MAAM,UACL,SAAS,eAAe,SAAS,eAAe,CAAC,KAAK,SAAS,GAAG;AAAA,EACnE,MAAM,UAAU,OAAO,SAAS,QAAQ,IAAI,qBAAqB,MAAM,EAAE;AAAA,EACzE,MAAM,YAAY,SAAS,KAAK;AAAA,IAC/B,KAAK;AAAA,IACL,KAAK,UACF,YACA;AAAA,MACA,oBAAoB,QAAQ,IAAI,iCAAiC;AAAA,IAClE;AAAA,EACH,CAAC;AAAA,EACD,MAAM,KAAK,IAAI,OAAiB;AAAA,IAC/B,SAAS,IAAI,kBAAkB,EAAE,UAAU,UAAU,CAAC;AAAA,EACvD,CAAC;AAAA,EACD,MAAM,QAAmB,EAAE,IAAI,UAAU;AAAA,EACzC,MAAM,IAAI,KAAK,KAAK;AAAA,EACpB,OAAO;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
|
}
|
package/dist/src/db/jsonb.d.ts
CHANGED
|
@@ -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:
|
|
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
|
package/dist/src/db/jsonb.js.map
CHANGED
|
@@ -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:
|
|
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;
|
|
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
|
}
|