@secondlayer/shared 1.0.0 → 2.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 (65) hide show
  1. package/dist/src/crypto/secrets.d.ts +5 -0
  2. package/dist/src/crypto/secrets.js +69 -0
  3. package/dist/src/crypto/secrets.js.map +10 -0
  4. package/dist/src/db/index.d.ts +91 -6
  5. package/dist/src/db/index.js +53 -29
  6. package/dist/src/db/index.js.map +4 -4
  7. package/dist/src/db/jsonb.js.map +2 -2
  8. package/dist/src/db/queries/accounts.d.ts +59 -2
  9. package/dist/src/db/queries/integrity.d.ts +59 -2
  10. package/dist/src/db/queries/marketplace.d.ts +59 -2
  11. package/dist/src/db/queries/marketplace.js +6 -9
  12. package/dist/src/db/queries/marketplace.js.map +3 -3
  13. package/dist/src/db/queries/projects.d.ts +59 -2
  14. package/dist/src/db/queries/projects.js.map +2 -2
  15. package/dist/src/db/queries/subgraph-gaps.d.ts +59 -2
  16. package/dist/src/db/queries/subgraphs.d.ts +63 -5
  17. package/dist/src/db/queries/subgraphs.js +3 -9
  18. package/dist/src/db/queries/subgraphs.js.map +4 -4
  19. package/dist/src/db/queries/tenants.d.ts +493 -0
  20. package/dist/src/db/queries/tenants.js +194 -0
  21. package/dist/src/db/queries/tenants.js.map +11 -0
  22. package/dist/src/db/queries/usage.d.ts +59 -2
  23. package/dist/src/db/queries/usage.js +3 -3
  24. package/dist/src/db/queries/usage.js.map +3 -3
  25. package/dist/src/db/queries/workflows.d.ts +59 -2
  26. package/dist/src/db/queries/workflows.js +31 -3
  27. package/dist/src/db/queries/workflows.js.map +4 -4
  28. package/dist/src/db/schema.d.ts +69 -3
  29. package/dist/src/env.d.ts +10 -0
  30. package/dist/src/env.js +3 -1
  31. package/dist/src/env.js.map +3 -3
  32. package/dist/src/errors.d.ts +17 -3
  33. package/dist/src/errors.js +34 -3
  34. package/dist/src/errors.js.map +3 -3
  35. package/dist/src/index.d.ts +117 -8
  36. package/dist/src/index.js +88 -31
  37. package/dist/src/index.js.map +6 -6
  38. package/dist/src/logger.js +3 -1
  39. package/dist/src/logger.js.map +3 -3
  40. package/dist/src/mode.d.ts +30 -0
  41. package/dist/src/mode.js +43 -0
  42. package/dist/src/mode.js.map +10 -0
  43. package/dist/src/node/archive-client.js +3 -1
  44. package/dist/src/node/archive-client.js.map +3 -3
  45. package/dist/src/node/hiro-client.js +3 -1
  46. package/dist/src/node/hiro-client.js.map +3 -3
  47. package/dist/src/node/local-client.d.ts +59 -2
  48. package/dist/src/pricing.d.ts +28 -0
  49. package/dist/src/pricing.js +47 -0
  50. package/dist/src/pricing.js.map +10 -0
  51. package/dist/src/queue/listener.d.ts +11 -2
  52. package/dist/src/queue/listener.js +11 -12
  53. package/dist/src/queue/listener.js.map +3 -3
  54. package/dist/src/types.d.ts +10 -0
  55. package/migrations/0033_workflow_steps_memo_key.ts +54 -0
  56. package/migrations/0034_workflow_signer_secrets.ts +42 -0
  57. package/migrations/0035_workflow_budgets.ts +53 -0
  58. package/migrations/0036_tx_confirmed_notify.ts +36 -0
  59. package/migrations/0037_nullable_api_key.ts +35 -0
  60. package/migrations/0038_drop_workflow_tables.ts +46 -0
  61. package/migrations/0039_tenants.ts +66 -0
  62. package/migrations/0040_tenant_key_generations.ts +29 -0
  63. package/migrations/0041_subgraphs_drop_api_key_id.ts +49 -0
  64. package/migrations/0042_tenant_project_id.ts +25 -0
  65. package/package.json +18 -2
@@ -7,6 +7,11 @@ declare const ErrorCodes: {
7
7
  readonly FORBIDDEN: "FORBIDDEN"
8
8
  readonly VERSION_CONFLICT: "VERSION_CONFLICT"
9
9
  readonly NOT_FOUND: "NOT_FOUND"
10
+ readonly KEY_ROTATED: "KEY_ROTATED"
11
+ readonly TRIAL_EXPIRED: "TRIAL_EXPIRED"
12
+ readonly TENANT_SUSPENDED: "TENANT_SUSPENDED"
13
+ readonly NO_TENANT_FOR_PROJECT: "NO_TENANT_FOR_PROJECT"
14
+ readonly INSTANCE_EXISTS: "INSTANCE_EXISTS"
10
15
  };
11
16
  type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
12
17
  /** Base error class for all Secondlayer errors. */
@@ -48,9 +53,18 @@ declare class VersionConflictError extends SecondLayerError {
48
53
  expectedVersion: string;
49
54
  constructor(currentVersion: string, expectedVersion: string);
50
55
  }
56
+ declare class KeyRotatedError extends SecondLayerError {
57
+ constructor(message?: string);
58
+ }
59
+ declare class TrialExpiredError extends SecondLayerError {
60
+ constructor(message: string);
61
+ }
62
+ declare class TenantSuspendedError extends SecondLayerError {
63
+ constructor(message?: string);
64
+ }
51
65
  /** Error code → HTTP status. Used by API middleware for code-based matching
52
66
  * (avoids cross-bundle instanceof failures from bunup class duplication). */
53
- type MappedCode = Extract<ErrorCode, "AUTHENTICATION_ERROR" | "AUTHORIZATION_ERROR" | "RATE_LIMIT_ERROR" | "FORBIDDEN" | "NOT_FOUND" | "VALIDATION_ERROR">;
54
- declare const CODE_TO_STATUS: Record<MappedCode, 400 | 401 | 403 | 404 | 429>;
67
+ type MappedCode = Extract<ErrorCode, "AUTHENTICATION_ERROR" | "AUTHORIZATION_ERROR" | "RATE_LIMIT_ERROR" | "FORBIDDEN" | "NOT_FOUND" | "VALIDATION_ERROR" | "KEY_ROTATED" | "TRIAL_EXPIRED" | "TENANT_SUSPENDED" | "NO_TENANT_FOR_PROJECT" | "INSTANCE_EXISTS">;
68
+ declare const CODE_TO_STATUS: Record<MappedCode, 400 | 401 | 402 | 403 | 404 | 409 | 423 | 429>;
55
69
  declare function getErrorMessage(err: unknown): string;
56
- export { getErrorMessage, VersionConflictError, ValidationError, SecondLayerError, RateLimitError, NotFoundError, ForbiddenError, ErrorCodes, ErrorCode, DatabaseError, CODE_TO_STATUS, AuthorizationError, AuthenticationError };
70
+ export { getErrorMessage, VersionConflictError, ValidationError, TrialExpiredError, TenantSuspendedError, SecondLayerError, RateLimitError, NotFoundError, KeyRotatedError, ForbiddenError, ErrorCodes, ErrorCode, DatabaseError, CODE_TO_STATUS, AuthorizationError, AuthenticationError };
@@ -23,7 +23,12 @@ var ErrorCodes = {
23
23
  RATE_LIMIT_ERROR: "RATE_LIMIT_ERROR",
24
24
  FORBIDDEN: "FORBIDDEN",
25
25
  VERSION_CONFLICT: "VERSION_CONFLICT",
26
- NOT_FOUND: "NOT_FOUND"
26
+ NOT_FOUND: "NOT_FOUND",
27
+ KEY_ROTATED: "KEY_ROTATED",
28
+ TRIAL_EXPIRED: "TRIAL_EXPIRED",
29
+ TENANT_SUSPENDED: "TENANT_SUSPENDED",
30
+ NO_TENANT_FOR_PROJECT: "NO_TENANT_FOR_PROJECT",
31
+ INSTANCE_EXISTS: "INSTANCE_EXISTS"
27
32
  };
28
33
 
29
34
  class SecondLayerError extends Error {
@@ -98,13 +103,36 @@ class VersionConflictError extends SecondLayerError {
98
103
  this.expectedVersion = expectedVersion;
99
104
  }
100
105
  }
106
+
107
+ class KeyRotatedError extends SecondLayerError {
108
+ constructor(message = "Token has been rotated") {
109
+ super("KEY_ROTATED", message);
110
+ }
111
+ }
112
+
113
+ class TrialExpiredError extends SecondLayerError {
114
+ constructor(message) {
115
+ super("TRIAL_EXPIRED", message);
116
+ }
117
+ }
118
+
119
+ class TenantSuspendedError extends SecondLayerError {
120
+ constructor(message = "Instance is suspended") {
121
+ super("TENANT_SUSPENDED", message);
122
+ }
123
+ }
101
124
  var CODE_TO_STATUS = {
102
125
  AUTHENTICATION_ERROR: 401,
103
126
  AUTHORIZATION_ERROR: 403,
104
127
  RATE_LIMIT_ERROR: 429,
105
128
  FORBIDDEN: 403,
106
129
  NOT_FOUND: 404,
107
- VALIDATION_ERROR: 400
130
+ VALIDATION_ERROR: 400,
131
+ KEY_ROTATED: 401,
132
+ TRIAL_EXPIRED: 402,
133
+ TENANT_SUSPENDED: 423,
134
+ NO_TENANT_FOR_PROJECT: 404,
135
+ INSTANCE_EXISTS: 409
108
136
  };
109
137
  function getErrorMessage(err) {
110
138
  return err instanceof Error ? err.message : String(err);
@@ -113,9 +141,12 @@ export {
113
141
  getErrorMessage,
114
142
  VersionConflictError,
115
143
  ValidationError,
144
+ TrialExpiredError,
145
+ TenantSuspendedError,
116
146
  SecondLayerError,
117
147
  RateLimitError,
118
148
  NotFoundError,
149
+ KeyRotatedError,
119
150
  ForbiddenError,
120
151
  ErrorCodes,
121
152
  DatabaseError,
@@ -124,5 +155,5 @@ export {
124
155
  AuthenticationError
125
156
  };
126
157
 
127
- //# debugId=49DAFCD22173A4BC64756E2164756E21
158
+ //# debugId=6F538984C15B186D64756E2164756E21
128
159
  //# sourceMappingURL=errors.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/errors.ts"],
4
4
  "sourcesContent": [
5
- "export const ErrorCodes = {\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tDATABASE_ERROR: \"DATABASE_ERROR\",\n\tAUTHENTICATION_ERROR: \"AUTHENTICATION_ERROR\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tRATE_LIMIT_ERROR: \"RATE_LIMIT_ERROR\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tVERSION_CONFLICT: \"VERSION_CONFLICT\",\n\tNOT_FOUND: \"NOT_FOUND\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Base error class for all Secondlayer errors. */\nexport class SecondLayerError extends Error {\n\tpublic code: ErrorCode;\n\tpublic override cause?: unknown;\n\n\tconstructor(code: ErrorCode, message: string, cause?: unknown) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.cause = cause;\n\t\tthis.name = this.constructor.name;\n\t\tError.captureStackTrace?.(this, this.constructor);\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tcode: string;\n\t\tmessage: string;\n\t\tstack: string | undefined;\n\t\tcause: unknown;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t};\n\t}\n}\n\nexport class NotFoundError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"NOT_FOUND\", message);\n\t}\n}\n\nexport class ValidationError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"VALIDATION_ERROR\", message, cause);\n\t}\n}\n\nexport class DatabaseError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"DATABASE_ERROR\", message, cause);\n\t}\n}\n\nexport class AuthenticationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHENTICATION_ERROR\", message);\n\t}\n}\n\nexport class AuthorizationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHORIZATION_ERROR\", message);\n\t}\n}\n\nexport class RateLimitError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"RATE_LIMIT_ERROR\", message);\n\t}\n}\n\nexport class ForbiddenError extends SecondLayerError {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(\"FORBIDDEN\", message);\n\t}\n}\n\nexport class VersionConflictError extends SecondLayerError {\n\tpublic currentVersion: string;\n\tpublic expectedVersion: string;\n\n\tconstructor(currentVersion: string, expectedVersion: string) {\n\t\tsuper(\n\t\t\t\"VERSION_CONFLICT\",\n\t\t\t`Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t\t);\n\t\tthis.currentVersion = currentVersion;\n\t\tthis.expectedVersion = expectedVersion;\n\t}\n}\n\n/** Error code → HTTP status. Used by API middleware for code-based matching\n * (avoids cross-bundle instanceof failures from bunup class duplication). */\ntype MappedCode = Extract<\n\tErrorCode,\n\t| \"AUTHENTICATION_ERROR\"\n\t| \"AUTHORIZATION_ERROR\"\n\t| \"RATE_LIMIT_ERROR\"\n\t| \"FORBIDDEN\"\n\t| \"NOT_FOUND\"\n\t| \"VALIDATION_ERROR\"\n>;\nexport const CODE_TO_STATUS: Record<MappedCode, 400 | 401 | 403 | 404 | 429> = {\n\tAUTHENTICATION_ERROR: 401,\n\tAUTHORIZATION_ERROR: 403,\n\tRATE_LIMIT_ERROR: 429,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tVALIDATION_ERROR: 400,\n} as const;\n\nexport function getErrorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n"
5
+ "export const ErrorCodes = {\n\tVALIDATION_ERROR: \"VALIDATION_ERROR\",\n\tDATABASE_ERROR: \"DATABASE_ERROR\",\n\tAUTHENTICATION_ERROR: \"AUTHENTICATION_ERROR\",\n\tAUTHORIZATION_ERROR: \"AUTHORIZATION_ERROR\",\n\tRATE_LIMIT_ERROR: \"RATE_LIMIT_ERROR\",\n\tFORBIDDEN: \"FORBIDDEN\",\n\tVERSION_CONFLICT: \"VERSION_CONFLICT\",\n\tNOT_FOUND: \"NOT_FOUND\",\n\t// Tenant lifecycle (CLI surfaces these verbatim)\n\tKEY_ROTATED: \"KEY_ROTATED\",\n\tTRIAL_EXPIRED: \"TRIAL_EXPIRED\",\n\tTENANT_SUSPENDED: \"TENANT_SUSPENDED\",\n\tNO_TENANT_FOR_PROJECT: \"NO_TENANT_FOR_PROJECT\",\n\tINSTANCE_EXISTS: \"INSTANCE_EXISTS\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Base error class for all Secondlayer errors. */\nexport class SecondLayerError extends Error {\n\tpublic code: ErrorCode;\n\tpublic override cause?: unknown;\n\n\tconstructor(code: ErrorCode, message: string, cause?: unknown) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.cause = cause;\n\t\tthis.name = this.constructor.name;\n\t\tError.captureStackTrace?.(this, this.constructor);\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tcode: string;\n\t\tmessage: string;\n\t\tstack: string | undefined;\n\t\tcause: unknown;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t};\n\t}\n}\n\nexport class NotFoundError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"NOT_FOUND\", message);\n\t}\n}\n\nexport class ValidationError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"VALIDATION_ERROR\", message, cause);\n\t}\n}\n\nexport class DatabaseError extends SecondLayerError {\n\tconstructor(message: string, cause?: unknown) {\n\t\tsuper(\"DATABASE_ERROR\", message, cause);\n\t}\n}\n\nexport class AuthenticationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHENTICATION_ERROR\", message);\n\t}\n}\n\nexport class AuthorizationError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"AUTHORIZATION_ERROR\", message);\n\t}\n}\n\nexport class RateLimitError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"RATE_LIMIT_ERROR\", message);\n\t}\n}\n\nexport class ForbiddenError extends SecondLayerError {\n\tconstructor(message = \"Forbidden\") {\n\t\tsuper(\"FORBIDDEN\", message);\n\t}\n}\n\nexport class VersionConflictError extends SecondLayerError {\n\tpublic currentVersion: string;\n\tpublic expectedVersion: string;\n\n\tconstructor(currentVersion: string, expectedVersion: string) {\n\t\tsuper(\n\t\t\t\"VERSION_CONFLICT\",\n\t\t\t`Version conflict: expected ${expectedVersion}, current ${currentVersion}`,\n\t\t);\n\t\tthis.currentVersion = currentVersion;\n\t\tthis.expectedVersion = expectedVersion;\n\t}\n}\n\nexport class KeyRotatedError extends SecondLayerError {\n\tconstructor(message = \"Token has been rotated\") {\n\t\tsuper(\"KEY_ROTATED\", message);\n\t}\n}\n\nexport class TrialExpiredError extends SecondLayerError {\n\tconstructor(message: string) {\n\t\tsuper(\"TRIAL_EXPIRED\", message);\n\t}\n}\n\nexport class TenantSuspendedError extends SecondLayerError {\n\tconstructor(message = \"Instance is suspended\") {\n\t\tsuper(\"TENANT_SUSPENDED\", message);\n\t}\n}\n\n/** Error code → HTTP status. Used by API middleware for code-based matching\n * (avoids cross-bundle instanceof failures from bunup class duplication). */\ntype MappedCode = Extract<\n\tErrorCode,\n\t| \"AUTHENTICATION_ERROR\"\n\t| \"AUTHORIZATION_ERROR\"\n\t| \"RATE_LIMIT_ERROR\"\n\t| \"FORBIDDEN\"\n\t| \"NOT_FOUND\"\n\t| \"VALIDATION_ERROR\"\n\t| \"KEY_ROTATED\"\n\t| \"TRIAL_EXPIRED\"\n\t| \"TENANT_SUSPENDED\"\n\t| \"NO_TENANT_FOR_PROJECT\"\n\t| \"INSTANCE_EXISTS\"\n>;\nexport const CODE_TO_STATUS: Record<\n\tMappedCode,\n\t400 | 401 | 402 | 403 | 404 | 409 | 423 | 429\n> = {\n\tAUTHENTICATION_ERROR: 401,\n\tAUTHORIZATION_ERROR: 403,\n\tRATE_LIMIT_ERROR: 429,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tVALIDATION_ERROR: 400,\n\tKEY_ROTATED: 401,\n\tTRIAL_EXPIRED: 402,\n\tTENANT_SUSPENDED: 423,\n\tNO_TENANT_FOR_PROJECT: 404,\n\tINSTANCE_EXISTS: 409,\n} as const;\n\nexport function getErrorMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n"
6
6
  ],
7
- "mappings": ";;;;;;;;;;;;;;;;;AAAO,IAAM,aAAa;AAAA,EACzB,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,WAAW;AACZ;AAAA;AAKO,MAAM,yBAAyB,MAAM;AAAA,EACpC;AAAA,EACS;AAAA,EAEhB,WAAW,CAAC,MAAiB,SAAiB,OAAiB;AAAA,IAC9D,MAAM,OAAO;AAAA,IACb,KAAK,OAAO;AAAA,IACZ,KAAK,QAAQ;A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A;AAEnC;AAkBO,IAAM,iBAGT;AAAA,EACH,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,kBAAkB;AAAA,EAClB,WAAW;AAAA,EACX,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,eAAe;AAAA,EACf,kBAAkB;AAAA,EAClB,uBAAuB;AAAA,EACvB,iBAAiB;AAClB;AAEO,SAAS,eAAe,CAAC,KAAsB;AAAA,EACrD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA;",
8
+ "debugId": "6F538984C15B186D64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,4 +1,4 @@
1
- import { Generated, Insertable, Selectable, Updateable } from "kysely";
1
+ import { ColumnType, Generated, Insertable, Selectable, Updateable } from "kysely";
2
2
  interface BlocksTable {
3
3
  height: number;
4
4
  hash: string;
@@ -55,7 +55,6 @@ interface SubgraphsTable {
55
55
  last_error_at: Date | null;
56
56
  total_processed: Generated<number>;
57
57
  total_errors: Generated<number>;
58
- api_key_id: string | null;
59
58
  account_id: string;
60
59
  handler_code: string | null;
61
60
  source_code: string | null;
@@ -294,6 +293,8 @@ interface WorkflowStepsTable {
294
293
  started_at: Date | null;
295
294
  completed_at: Date | null;
296
295
  duration_ms: number | null;
296
+ memo_key: string | null;
297
+ parent_step_id: string | null;
297
298
  created_at: Generated<Date>;
298
299
  }
299
300
  interface WorkflowQueueTable {
@@ -355,6 +356,65 @@ interface Database {
355
356
  workflow_queue: WorkflowQueueTable;
356
357
  workflow_schedules: WorkflowSchedulesTable;
357
358
  workflow_cursors: WorkflowCursorsTable;
359
+ workflow_signer_secrets: WorkflowSignerSecretsTable;
360
+ workflow_budgets: WorkflowBudgetsTable;
361
+ tenants: TenantsTable;
362
+ }
363
+ type TenantStatus = "provisioning" | "active" | "suspended" | "error" | "deleted";
364
+ interface TenantsTable {
365
+ id: Generated<string>;
366
+ account_id: string;
367
+ slug: string;
368
+ status: ColumnType<TenantStatus, TenantStatus | undefined, TenantStatus>;
369
+ plan: string;
370
+ cpus: ColumnType<number, number | string, number | string>;
371
+ memory_mb: number;
372
+ storage_limit_mb: number;
373
+ storage_used_mb: number | null;
374
+ pg_container_id: string | null;
375
+ api_container_id: string | null;
376
+ processor_container_id: string | null;
377
+ target_database_url_enc: Buffer;
378
+ tenant_jwt_secret_enc: Buffer;
379
+ anon_key_enc: Buffer;
380
+ service_key_enc: Buffer;
381
+ api_url_internal: string;
382
+ api_url_public: string;
383
+ trial_ends_at: Date;
384
+ suspended_at: Date | null;
385
+ last_health_check_at: Date | null;
386
+ service_gen: Generated<number>;
387
+ anon_gen: Generated<number>;
388
+ project_id: string | null;
389
+ created_at: Generated<Date>;
390
+ updated_at: Generated<Date>;
391
+ }
392
+ type Tenant = Selectable<TenantsTable>;
393
+ type InsertTenant = Insertable<TenantsTable>;
394
+ type UpdateTenant = Updateable<TenantsTable>;
395
+ interface WorkflowBudgetsTable {
396
+ id: Generated<string>;
397
+ workflow_definition_id: string;
398
+ /** Period key: "daily:YYYY-MM-DD" | "weekly:YYYY-Www" | "per-run:<uuid>". */
399
+ period: string;
400
+ ai_usd_used: Generated<string>;
401
+ ai_tokens_used: Generated<string>;
402
+ chain_microstx_used: Generated<string>;
403
+ chain_tx_count: Generated<number>;
404
+ run_count: Generated<number>;
405
+ step_count: Generated<number>;
406
+ reset_at: Date;
407
+ created_at: Generated<Date>;
408
+ updated_at: Generated<Date>;
409
+ }
410
+ interface WorkflowSignerSecretsTable {
411
+ id: Generated<string>;
412
+ account_id: string;
413
+ name: string;
414
+ /** AES-GCM ciphertext bytes produced by the runner's KMS on write. */
415
+ encrypted_value: Buffer;
416
+ created_at: Generated<Date>;
417
+ updated_at: Generated<Date>;
358
418
  }
359
419
  type Block = Selectable<BlocksTable>;
360
420
  type InsertBlock = Insertable<BlocksTable>;
@@ -407,6 +467,12 @@ type WorkflowSchedule = Selectable<WorkflowSchedulesTable>;
407
467
  type InsertWorkflowSchedule = Insertable<WorkflowSchedulesTable>;
408
468
  type UpdateWorkflowSchedule = Updateable<WorkflowSchedulesTable>;
409
469
  type WorkflowCursor = Selectable<WorkflowCursorsTable>;
470
+ type WorkflowSignerSecret = Selectable<WorkflowSignerSecretsTable>;
471
+ type InsertWorkflowSignerSecret = Insertable<WorkflowSignerSecretsTable>;
472
+ type UpdateWorkflowSignerSecret = Updateable<WorkflowSignerSecretsTable>;
473
+ type WorkflowBudget = Selectable<WorkflowBudgetsTable>;
474
+ type InsertWorkflowBudget = Insertable<WorkflowBudgetsTable>;
475
+ type UpdateWorkflowBudget = Updateable<WorkflowBudgetsTable>;
410
476
  type Project = Selectable<ProjectsTable>;
411
477
  type InsertProject = Insertable<ProjectsTable>;
412
478
  type UpdateProject = Updateable<ProjectsTable>;
@@ -421,6 +487,16 @@ type ChatMessage = Selectable<ChatMessagesTable>;
421
487
  type InsertChatMessage = Insertable<ChatMessagesTable>;
422
488
  interface EnvSchemaOutput {
423
489
  DATABASE_URL?: string;
490
+ /**
491
+ * Shared indexer DB (blocks/txs/events). Falls back to DATABASE_URL.
492
+ * Set this alongside TARGET_DATABASE_URL to enable dual-DB mode.
493
+ */
494
+ SOURCE_DATABASE_URL?: string;
495
+ /**
496
+ * Tenant DB (subgraph schemas + subgraphs table). Falls back to DATABASE_URL.
497
+ * Set this alongside SOURCE_DATABASE_URL to enable dual-DB mode.
498
+ */
499
+ TARGET_DATABASE_URL?: string;
424
500
  NETWORK?: "mainnet" | "testnet";
425
501
  NETWORKS?: ("mainnet" | "testnet")[];
426
502
  LOG_LEVEL: "debug" | "info" | "warn" | "error";
@@ -446,10 +522,29 @@ declare function parseJsonb<T = unknown>(value: unknown): T;
446
522
  import { Kysely } from "kysely";
447
523
  import postgres from "postgres";
448
524
  import { sql } from "kysely";
525
+ /**
526
+ * Kysely instance for the SOURCE DB (block/tx/event reads from the shared
527
+ * indexer). Resolution: `SOURCE_DATABASE_URL || DATABASE_URL`.
528
+ */
529
+ declare function getSourceDb(): Kysely<Database>;
530
+ /**
531
+ * Kysely instance for the TARGET DB (subgraph schemas, subgraphs table,
532
+ * account-scoped data — tenant-side writes). Resolution:
533
+ * `TARGET_DATABASE_URL || DATABASE_URL`.
534
+ */
535
+ declare function getTargetDb(): Kysely<Database>;
536
+ /**
537
+ * Backward-compat alias for `getTargetDb()`. Accepts an optional
538
+ * `connectionString` override used by seed/test helpers — when supplied,
539
+ * bypasses env resolution and uses the provided URL directly (still cached).
540
+ */
449
541
  declare function getDb(connectionString?: string): Kysely<Database>;
450
- /** Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.) */
451
- declare function getRawClient(): ReturnType<typeof postgres>;
452
- /** Close the DB connection pool. Call in CLI commands to allow process exit. */
542
+ /**
543
+ * Raw postgres.js client for dynamic schema DDL (CREATE SCHEMA, DROP, etc.).
544
+ * Defaults to the target role (tenant schemas live in the target DB).
545
+ */
546
+ declare function getRawClient(role?: "source" | "target"): ReturnType<typeof postgres>;
547
+ /** Close all DB connection pools. Call in CLI commands to allow process exit. */
453
548
  declare function closeDb(): Promise<void>;
454
549
  declare const ErrorCodes: {
455
550
  readonly VALIDATION_ERROR: "VALIDATION_ERROR"
@@ -460,6 +555,11 @@ declare const ErrorCodes: {
460
555
  readonly FORBIDDEN: "FORBIDDEN"
461
556
  readonly VERSION_CONFLICT: "VERSION_CONFLICT"
462
557
  readonly NOT_FOUND: "NOT_FOUND"
558
+ readonly KEY_ROTATED: "KEY_ROTATED"
559
+ readonly TRIAL_EXPIRED: "TRIAL_EXPIRED"
560
+ readonly TENANT_SUSPENDED: "TENANT_SUSPENDED"
561
+ readonly NO_TENANT_FOR_PROJECT: "NO_TENANT_FOR_PROJECT"
562
+ readonly INSTANCE_EXISTS: "INSTANCE_EXISTS"
463
563
  };
464
564
  type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
465
565
  /** Base error class for all Secondlayer errors. */
@@ -501,10 +601,19 @@ declare class VersionConflictError extends SecondLayerError {
501
601
  expectedVersion: string;
502
602
  constructor(currentVersion: string, expectedVersion: string);
503
603
  }
604
+ declare class KeyRotatedError extends SecondLayerError {
605
+ constructor(message?: string);
606
+ }
607
+ declare class TrialExpiredError extends SecondLayerError {
608
+ constructor(message: string);
609
+ }
610
+ declare class TenantSuspendedError extends SecondLayerError {
611
+ constructor(message?: string);
612
+ }
504
613
  /** Error code → HTTP status. Used by API middleware for code-based matching
505
614
  * (avoids cross-bundle instanceof failures from bunup class duplication). */
506
- type MappedCode = Extract<ErrorCode, "AUTHENTICATION_ERROR" | "AUTHORIZATION_ERROR" | "RATE_LIMIT_ERROR" | "FORBIDDEN" | "NOT_FOUND" | "VALIDATION_ERROR">;
507
- declare const CODE_TO_STATUS: Record<MappedCode, 400 | 401 | 403 | 404 | 429>;
615
+ type MappedCode = Extract<ErrorCode, "AUTHENTICATION_ERROR" | "AUTHORIZATION_ERROR" | "RATE_LIMIT_ERROR" | "FORBIDDEN" | "NOT_FOUND" | "VALIDATION_ERROR" | "KEY_ROTATED" | "TRIAL_EXPIRED" | "TENANT_SUSPENDED" | "NO_TENANT_FOR_PROJECT" | "INSTANCE_EXISTS">;
616
+ declare const CODE_TO_STATUS: Record<MappedCode, 400 | 401 | 402 | 403 | 404 | 409 | 423 | 429>;
508
617
  declare function getErrorMessage(err: unknown): string;
509
618
  declare class Logger {
510
619
  private _level?;
@@ -819,4 +928,4 @@ declare function createSignatureHeader(payload: string, secret: string, timestam
819
928
  * Returns true if valid, false otherwise
820
929
  */
821
930
  declare function verifySignatureHeader(payload: string, header: string, secret: string, toleranceSeconds?: number): boolean;
822
- export { sql, parseJsonb, logger, jsonb, getRawClient, getErrorMessage, getEnv, getDb, exports_hmac as crypto, closeDb, WorkflowStepsTable, WorkflowStep, WorkflowSchedulesTable, WorkflowSchedule, WorkflowRunsTable, WorkflowRun, WorkflowQueueTable, WorkflowQueueItem, WorkflowDefinitionsTable, WorkflowDefinition, WorkflowCursorsTable, WorkflowCursor, WaitlistTable, VersionConflictError, ValidationError, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateWorkflowStep, UpdateWorkflowSchedule, UpdateWorkflowRun, UpdateWorkflowDefinition, UpdateTransaction, UpdateSubgraph, UpdateProject, UpdateProfileRequestSchema, UpdateProfileRequest, UpdateIndexProgress, UpdateEvent, UpdateChatSession, UpdateBlock, UpdateApiKey, TransactionsTable, Transaction, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphSyncInfo, SubgraphSummary, SubgraphQueryParams, SubgraphProcessingStatsTable, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGapsResponse, SubgraphGapRange, SubgraphGapEntry, SubgraphGap, SubgraphDetail, Subgraph, StxTransferFilterSchema, StxTransferFilter, StxMintFilterSchema, StxMintFilter, StxLockFilterSchema, StxLockFilter, StxBurnFilterSchema, StxBurnFilter, SessionsTable, Session, SecondLayerError, ReindexResponse, RateLimitError, PublishSubgraphRequestSchema, PublishSubgraphRequest, ProjectsTable, Project, PrintEventFilterSchema, PrintEventFilter, NotFoundError, NftTransferFilterSchema, NftTransferFilter, NftMintFilterSchema, NftMintFilter, NftBurnFilterSchema, NftBurnFilter, MarketplaceSubgraphSummary, MarketplaceSubgraphDetail, MarketplaceCreator, MagicLinksTable, MagicLink, InsertWorkflowStep, InsertWorkflowSchedule, InsertWorkflowRun, InsertWorkflowQueueItem, InsertWorkflowDefinition, InsertTransaction, InsertTeamMember, InsertTeamInvitation, InsertSubgraphUsageDaily, InsertSubgraphHealthSnapshot, InsertSubgraphGap, InsertSubgraph, InsertSession, InsertProject, InsertMagicLink, InsertIndexProgress, InsertEvent, InsertChatSession, InsertChatMessage, InsertBlock, InsertApiKey, InsertAccountInsight, InsertAccountAgentRun, InsertAccount, IndexProgressTable, IndexProgress, FtTransferFilterSchema, FtTransferFilter, FtMintFilterSchema, FtMintFilter, FtBurnFilterSchema, FtBurnFilter, ForkSubgraphRequestSchema, ForkSubgraphRequest, ForbiddenError, EventsTable, EventFilterSchema, EventFilter, Event, ErrorCodes, ErrorCode, Env, DeploySubgraphResponse, DeploySubgraphRequestSchema, DeploySubgraphRequest, DatabaseError, Database, CreatorProfile, ContractDeployFilterSchema, ContractDeployFilter, ContractCallFilterSchema, ContractCallFilter, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, CODE_TO_STATUS, BlocksTable, Block, AuthorizationError, AuthenticationError, ApiKeysTable, ApiKey, AccountsTable, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
931
+ export { sql, parseJsonb, logger, jsonb, getTargetDb, getSourceDb, getRawClient, getErrorMessage, getEnv, getDb, exports_hmac as crypto, closeDb, WorkflowStepsTable, WorkflowStep, WorkflowSignerSecretsTable, WorkflowSignerSecret, WorkflowSchedulesTable, WorkflowSchedule, WorkflowRunsTable, WorkflowRun, WorkflowQueueTable, WorkflowQueueItem, WorkflowDefinitionsTable, WorkflowDefinition, WorkflowCursorsTable, WorkflowCursor, WorkflowBudgetsTable, WorkflowBudget, WaitlistTable, VersionConflictError, ValidationError, UsageSnapshotsTable, UsageSnapshot, UsageDailyTable, UsageDaily, UpdateWorkflowStep, UpdateWorkflowSignerSecret, UpdateWorkflowSchedule, UpdateWorkflowRun, UpdateWorkflowDefinition, UpdateWorkflowBudget, UpdateTransaction, UpdateTenant, UpdateSubgraph, UpdateProject, UpdateProfileRequestSchema, UpdateProfileRequest, UpdateIndexProgress, UpdateEvent, UpdateChatSession, UpdateBlock, UpdateApiKey, TrialExpiredError, TransactionsTable, Transaction, TenantsTable, TenantSuspendedError, TenantStatus, Tenant, TeamMembersTable, TeamMember, TeamInvitationsTable, TeamInvitation, SubgraphsTable, SubgraphUsageDailyTable, SubgraphUsageDaily, SubgraphTableSnapshotsTable, SubgraphSyncInfo, SubgraphSummary, SubgraphQueryParams, SubgraphProcessingStatsTable, SubgraphHealthSnapshotsTable, SubgraphHealthSnapshot, SubgraphGapsTable, SubgraphGapsResponse, SubgraphGapRange, SubgraphGapEntry, SubgraphGap, SubgraphDetail, Subgraph, StxTransferFilterSchema, StxTransferFilter, StxMintFilterSchema, StxMintFilter, StxLockFilterSchema, StxLockFilter, StxBurnFilterSchema, StxBurnFilter, SessionsTable, Session, SecondLayerError, ReindexResponse, RateLimitError, PublishSubgraphRequestSchema, PublishSubgraphRequest, ProjectsTable, Project, PrintEventFilterSchema, PrintEventFilter, NotFoundError, NftTransferFilterSchema, NftTransferFilter, NftMintFilterSchema, NftMintFilter, NftBurnFilterSchema, NftBurnFilter, MarketplaceSubgraphSummary, MarketplaceSubgraphDetail, MarketplaceCreator, MagicLinksTable, MagicLink, KeyRotatedError, 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, FtTransferFilterSchema, FtTransferFilter, FtMintFilterSchema, FtMintFilter, FtBurnFilterSchema, FtBurnFilter, ForkSubgraphRequestSchema, ForkSubgraphRequest, ForbiddenError, EventsTable, EventFilterSchema, EventFilter, Event, ErrorCodes, ErrorCode, Env, DeploySubgraphResponse, DeploySubgraphRequestSchema, DeploySubgraphRequest, DatabaseError, Database, CreatorProfile, ContractDeployFilterSchema, ContractDeployFilter, ContractCallFilterSchema, ContractCallFilter, ChatSessionsTable, ChatSession, ChatMessagesTable, ChatMessage, CODE_TO_STATUS, BlocksTable, Block, AuthorizationError, AuthenticationError, ApiKeysTable, ApiKey, AccountsTable, AccountInsightsTable, AccountInsight, AccountAgentRunsTable, AccountAgentRun, Account };
package/dist/src/index.js CHANGED
@@ -35,39 +35,61 @@ import { Kysely } from "kysely";
35
35
  import { PostgresJSDialect } from "kysely-postgres-js";
36
36
  import postgres from "postgres";
37
37
  import { sql as sql2 } from "kysely";
38
- var db = null;
39
- var rawClient = null;
38
+ var DEFAULT_URL = "postgres://postgres:postgres@localhost:5432/secondlayer_dev";
39
+ var pools = new Map;
40
+ function resolveSourceUrl() {
41
+ return process.env.SOURCE_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
42
+ }
43
+ function resolveTargetUrl() {
44
+ return process.env.TARGET_DATABASE_URL || process.env.DATABASE_URL || DEFAULT_URL;
45
+ }
46
+ function getOrCreatePool(url) {
47
+ const existing = pools.get(url);
48
+ if (existing)
49
+ return existing;
50
+ const host = (() => {
51
+ try {
52
+ return new URL(url).hostname;
53
+ } catch {
54
+ return "";
55
+ }
56
+ })();
57
+ const isLocal = host === "localhost" || host === "127.0.0.1" || !host.includes(".");
58
+ const poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? "20", 10);
59
+ const rawClient = postgres(url, {
60
+ max: poolMax,
61
+ ssl: isLocal ? undefined : {
62
+ rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0"
63
+ }
64
+ });
65
+ const db = new Kysely({
66
+ dialect: new PostgresJSDialect({ postgres: rawClient })
67
+ });
68
+ const entry = { db, rawClient };
69
+ pools.set(url, entry);
70
+ return entry;
71
+ }
72
+ function getSourceDb() {
73
+ return getOrCreatePool(resolveSourceUrl()).db;
74
+ }
75
+ function getTargetDb() {
76
+ return getOrCreatePool(resolveTargetUrl()).db;
77
+ }
40
78
  function getDb(connectionString) {
41
- if (!db) {
42
- const url = connectionString || process.env.DATABASE_URL || "postgres://postgres:postgres@localhost:5432/secondlayer_dev";
43
- const isLocal = url.includes("localhost") || url.includes("127.0.0.1") || url.includes("@postgres:");
44
- const poolMax = Number.parseInt(process.env.DATABASE_POOL_MAX ?? "20", 10);
45
- rawClient = postgres(url, {
46
- max: poolMax,
47
- ssl: isLocal ? undefined : {
48
- rejectUnauthorized: process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0"
49
- }
50
- });
51
- db = new Kysely({
52
- dialect: new PostgresJSDialect({ postgres: rawClient })
53
- });
54
- }
55
- return db;
79
+ if (connectionString)
80
+ return getOrCreatePool(connectionString).db;
81
+ return getTargetDb();
56
82
  }
57
- function getRawClient() {
58
- if (!rawClient)
59
- getDb();
60
- return rawClient;
83
+ function getRawClient(role = "target") {
84
+ const url = role === "source" ? resolveSourceUrl() : resolveTargetUrl();
85
+ return getOrCreatePool(url).rawClient;
61
86
  }
62
87
  async function closeDb() {
63
- if (db) {
64
- await db.destroy();
65
- db = null;
66
- }
67
- if (rawClient) {
68
- await rawClient.end();
69
- rawClient = null;
88
+ for (const entry of pools.values()) {
89
+ await entry.db.destroy();
90
+ await entry.rawClient.end();
70
91
  }
92
+ pools.clear();
71
93
  }
72
94
  // src/errors.ts
73
95
  var ErrorCodes = {
@@ -78,7 +100,12 @@ var ErrorCodes = {
78
100
  RATE_LIMIT_ERROR: "RATE_LIMIT_ERROR",
79
101
  FORBIDDEN: "FORBIDDEN",
80
102
  VERSION_CONFLICT: "VERSION_CONFLICT",
81
- NOT_FOUND: "NOT_FOUND"
103
+ NOT_FOUND: "NOT_FOUND",
104
+ KEY_ROTATED: "KEY_ROTATED",
105
+ TRIAL_EXPIRED: "TRIAL_EXPIRED",
106
+ TENANT_SUSPENDED: "TENANT_SUSPENDED",
107
+ NO_TENANT_FOR_PROJECT: "NO_TENANT_FOR_PROJECT",
108
+ INSTANCE_EXISTS: "INSTANCE_EXISTS"
82
109
  };
83
110
 
84
111
  class SecondLayerError extends Error {
@@ -153,13 +180,36 @@ class VersionConflictError extends SecondLayerError {
153
180
  this.expectedVersion = expectedVersion;
154
181
  }
155
182
  }
183
+
184
+ class KeyRotatedError extends SecondLayerError {
185
+ constructor(message = "Token has been rotated") {
186
+ super("KEY_ROTATED", message);
187
+ }
188
+ }
189
+
190
+ class TrialExpiredError extends SecondLayerError {
191
+ constructor(message) {
192
+ super("TRIAL_EXPIRED", message);
193
+ }
194
+ }
195
+
196
+ class TenantSuspendedError extends SecondLayerError {
197
+ constructor(message = "Instance is suspended") {
198
+ super("TENANT_SUSPENDED", message);
199
+ }
200
+ }
156
201
  var CODE_TO_STATUS = {
157
202
  AUTHENTICATION_ERROR: 401,
158
203
  AUTHORIZATION_ERROR: 403,
159
204
  RATE_LIMIT_ERROR: 429,
160
205
  FORBIDDEN: 403,
161
206
  NOT_FOUND: 404,
162
- VALIDATION_ERROR: 400
207
+ VALIDATION_ERROR: 400,
208
+ KEY_ROTATED: 401,
209
+ TRIAL_EXPIRED: 402,
210
+ TENANT_SUSPENDED: 423,
211
+ NO_TENANT_FOR_PROJECT: 404,
212
+ INSTANCE_EXISTS: 409
163
213
  };
164
214
  function getErrorMessage(err) {
165
215
  return err instanceof Error ? err.message : String(err);
@@ -179,6 +229,8 @@ var networksSchema = z.string().transform((val) => {
179
229
  });
180
230
  var envSchema = z.object({
181
231
  DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
232
+ SOURCE_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
233
+ TARGET_DATABASE_URL: z.preprocess((val) => typeof val === "string" && val.length === 0 ? undefined : val, z.string().url().optional()),
182
234
  NETWORK: z.enum(["mainnet", "testnet"]).optional(),
183
235
  NETWORKS: networksSchema.optional(),
184
236
  LOG_LEVEL: z.enum(["debug", "info", "warn", "error"]).default("info"),
@@ -468,6 +520,8 @@ export {
468
520
  parseJsonb,
469
521
  logger,
470
522
  jsonb,
523
+ getTargetDb,
524
+ getSourceDb,
471
525
  getRawClient,
472
526
  getErrorMessage,
473
527
  getEnv,
@@ -477,6 +531,8 @@ export {
477
531
  VersionConflictError,
478
532
  ValidationError,
479
533
  UpdateProfileRequestSchema,
534
+ TrialExpiredError,
535
+ TenantSuspendedError,
480
536
  StxTransferFilterSchema,
481
537
  StxMintFilterSchema,
482
538
  StxLockFilterSchema,
@@ -489,6 +545,7 @@ export {
489
545
  NftTransferFilterSchema,
490
546
  NftMintFilterSchema,
491
547
  NftBurnFilterSchema,
548
+ KeyRotatedError,
492
549
  FtTransferFilterSchema,
493
550
  FtMintFilterSchema,
494
551
  FtBurnFilterSchema,
@@ -505,5 +562,5 @@ export {
505
562
  AuthenticationError
506
563
  };
507
564
 
508
- //# debugId=7EDE06567E6D25DE64756E2164756E21
565
+ //# debugId=C27B5257F4D1169564756E2164756E21
509
566
  //# sourceMappingURL=index.js.map