@vrplatform/kysely 1.3.45-6098 → 1.3.45-61
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/build/.data.tar +0 -0
- package/build/main/control-plane/index.d.ts +175 -0
- package/build/main/control-plane/index.js.map +1 -1
- package/build/main/index.d.ts +2 -2
- package/build/main/index.js +111 -22
- package/build/main/index.js.map +1 -1
- package/build/main/local/generate.js +2 -0
- package/build/main/local/generate.js.map +1 -1
- package/build/main/local/index.js +12 -0
- package/build/main/local/index.js.map +1 -1
- package/build/main/query/listing/status.js +2 -6
- package/build/main/query/listing/status.js.map +1 -1
- package/build/main/query/tenant/status.js +2 -2
- package/build/main/query/tenant/status.js.map +1 -1
- package/build/main/test/index.d.ts +0 -3
- package/build/main/test/index.js +0 -9
- package/build/main/test/index.js.map +1 -1
- package/build/main/v1.generated.d.ts +253 -2
- package/build/main/v1.generated.js.map +1 -1
- package/build/migrations-v2/0000000000015-durable-flow-events.ts +163 -0
- package/build/migrations-v2/0000000000016-billing-listing-facts.ts +539 -0
- package/build/migrations-v2/0000000000016-managed-team-access.ts +34 -0
- package/build/migrations-v2/0000000000017-drop-trial-until.ts +42 -0
- package/build/migrations-v2/0000000000017-webhook-secret-reencryption-failures.ts +18 -0
- package/build/migrations-v2/0000000000018-accounting-integrity-monitoring.ts +276 -0
- package/build/migrations-v2/0000000000018-durable-flow-event-sensitive-input.ts +28 -0
- package/build/migrations-v2/0000000000019-accounting-integrity-run-shards.ts +26 -0
- package/build/migrations-v2/0000000000019-asynchronous-operations.ts +736 -0
- package/build/migrations-v2/0000000000020-accounting-integrity-case-classification.ts +52 -0
- package/build/migrations-v2/0000000000021-payment-line-classification-monitor-indexes.ts +31 -0
- package/build/migrations-v2/0000000000022-accounting-integrity-controlled-repairs.ts +281 -0
- package/build/migrations-v2/0000000000023-line-classification-usage.ts +325 -0
- package/build/migrations-v2/0000000000024-tenant-region-migration.ts +108 -0
- package/build/migrations-v2/0000000000025-partner-ach-denial-default.ts +30 -0
- package/build/migrations-v2/0000000000026-line-classification-usage-capture.ts +399 -0
- package/build/migrations-v2/0000000000027-payout-replacement-chain.ts +27 -0
- package/build/migrations-v2/0000000000028-accounting-integrity-operator-workflow.ts +108 -0
- package/build/migrations-v2/0000000000029-accounting-integrity-definition-artifacts.ts +40 -0
- package/build/migrations-v2/0000000000030-accounting-integrity-review-metadata-compatibility.ts +49 -0
- package/build/migrations-v2/0000000000031-ui-permission-role-simplification.ts +70 -0
- package/build/migrations-v2/0000000000032-tenant-delete-ownership-cascades.ts +44 -0
- package/build/module/control-plane/index.d.ts +175 -0
- package/build/module/control-plane/index.js.map +1 -1
- package/build/module/index.d.ts +2 -2
- package/build/module/index.js +113 -23
- package/build/module/index.js.map +1 -1
- package/build/module/local/generate.js +2 -0
- package/build/module/local/generate.js.map +1 -1
- package/build/module/local/index.js +12 -0
- package/build/module/local/index.js.map +1 -1
- package/build/module/query/listing/status.js +2 -6
- package/build/module/query/listing/status.js.map +1 -1
- package/build/module/query/tenant/status.js +2 -2
- package/build/module/query/tenant/status.js.map +1 -1
- package/build/module/test/index.d.ts +0 -3
- package/build/module/test/index.js +0 -9
- package/build/module/test/index.js.map +1 -1
- package/build/module/v1.generated.d.ts +253 -2
- package/build/module/v1.generated.js.map +1 -1
- package/package.json +1 -1
package/build/.data.tar
CHANGED
|
Binary file
|
|
@@ -7,6 +7,7 @@ export type JsonObject = {
|
|
|
7
7
|
};
|
|
8
8
|
export type JsonPrimitive = boolean | number | string | null;
|
|
9
9
|
export type JsonValue = JsonArray | JsonObject | JsonPrimitive;
|
|
10
|
+
export type Int8 = ColumnType<string, number | string | bigint, number | string | bigint>;
|
|
10
11
|
export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;
|
|
11
12
|
export interface ControlPlaneApp {
|
|
12
13
|
authentication: Generated<Json>;
|
|
@@ -21,6 +22,56 @@ export interface ControlPlaneApp {
|
|
|
21
22
|
type: string;
|
|
22
23
|
version: Generated<number>;
|
|
23
24
|
}
|
|
25
|
+
export interface ControlPlaneAccountingIntegrityEvaluation {
|
|
26
|
+
caseCount: Generated<Int8>;
|
|
27
|
+
completedAt: Timestamp | null;
|
|
28
|
+
completedRunCount: Generated<number>;
|
|
29
|
+
createdAt: Generated<Timestamp>;
|
|
30
|
+
environment: string;
|
|
31
|
+
error: Json | null;
|
|
32
|
+
expectedRunCount: number;
|
|
33
|
+
failedRunCount: Generated<number>;
|
|
34
|
+
findingRowCount: Generated<Int8>;
|
|
35
|
+
gitRevision: string;
|
|
36
|
+
id: string;
|
|
37
|
+
results: Generated<Json>;
|
|
38
|
+
rowsScanned: Generated<Int8>;
|
|
39
|
+
skippedRunCount: Generated<number>;
|
|
40
|
+
source: string;
|
|
41
|
+
startedAt: Timestamp;
|
|
42
|
+
status: string;
|
|
43
|
+
updatedAt: Generated<Timestamp>;
|
|
44
|
+
}
|
|
45
|
+
export interface ControlPlaneAccountingIntegrityDefinitionDraft {
|
|
46
|
+
artifact: Json;
|
|
47
|
+
artifactHash: string;
|
|
48
|
+
code: string;
|
|
49
|
+
createdAt: Generated<Timestamp>;
|
|
50
|
+
id: Generated<string>;
|
|
51
|
+
ownerId: string;
|
|
52
|
+
previewResult: Json | null;
|
|
53
|
+
rationale: string;
|
|
54
|
+
revision: Generated<number>;
|
|
55
|
+
status: string;
|
|
56
|
+
templateId: string;
|
|
57
|
+
templateVersion: number;
|
|
58
|
+
title: string;
|
|
59
|
+
updatedAt: Generated<Timestamp>;
|
|
60
|
+
validationResult: Json | null;
|
|
61
|
+
}
|
|
62
|
+
export interface ControlPlaneAccountingIntegrityDefinitionVersion {
|
|
63
|
+
artifact: Json;
|
|
64
|
+
artifactHash: string;
|
|
65
|
+
code: string;
|
|
66
|
+
draftId: string;
|
|
67
|
+
id: Generated<string>;
|
|
68
|
+
publishedAt: Generated<Timestamp>;
|
|
69
|
+
publishedBy: string;
|
|
70
|
+
rollout: string;
|
|
71
|
+
templateId: string;
|
|
72
|
+
templateVersion: number;
|
|
73
|
+
version: number;
|
|
74
|
+
}
|
|
24
75
|
export interface ControlPlaneBookingChannel {
|
|
25
76
|
channelRef: string | null;
|
|
26
77
|
color: string | null;
|
|
@@ -98,6 +149,25 @@ export interface ControlPlaneFeatureApproval {
|
|
|
98
149
|
updatedAt: Generated<Timestamp>;
|
|
99
150
|
userId: string;
|
|
100
151
|
}
|
|
152
|
+
export interface ControlPlaneFlow {
|
|
153
|
+
appId: string;
|
|
154
|
+
createdAt: Generated<Timestamp>;
|
|
155
|
+
description: string | null;
|
|
156
|
+
eventListening: Generated<Json>;
|
|
157
|
+
id: Generated<string>;
|
|
158
|
+
isPublic: Generated<boolean>;
|
|
159
|
+
leftType: string | null;
|
|
160
|
+
mappingSchema: Generated<Json>;
|
|
161
|
+
revision: Generated<number>;
|
|
162
|
+
rightType: string | null;
|
|
163
|
+
runSchema: Generated<Json>;
|
|
164
|
+
settingSchema: Generated<Json>;
|
|
165
|
+
title: string;
|
|
166
|
+
type: 'pull' | 'push' | null;
|
|
167
|
+
uniqueRef: string;
|
|
168
|
+
updatedAt: Generated<Timestamp>;
|
|
169
|
+
useGlobalMapping: Generated<boolean>;
|
|
170
|
+
}
|
|
101
171
|
export interface ControlPlaneIssueMessageOverwrite {
|
|
102
172
|
createdAt: Generated<Timestamp>;
|
|
103
173
|
id: Generated<string>;
|
|
@@ -105,6 +175,74 @@ export interface ControlPlaneIssueMessageOverwrite {
|
|
|
105
175
|
pattern: string;
|
|
106
176
|
updatedAt: Generated<Timestamp>;
|
|
107
177
|
}
|
|
178
|
+
export interface ControlPlaneLineClassification {
|
|
179
|
+
appConflict: Generated<boolean>;
|
|
180
|
+
appId: string | null;
|
|
181
|
+
createdAt: Generated<Timestamp>;
|
|
182
|
+
firstSeenAt: Timestamp;
|
|
183
|
+
id: Generated<string>;
|
|
184
|
+
kind: string;
|
|
185
|
+
lastSeenAt: Timestamp;
|
|
186
|
+
name: string;
|
|
187
|
+
updatedAt: Generated<Timestamp>;
|
|
188
|
+
}
|
|
189
|
+
export interface ControlPlaneLineClassificationTeamUsage {
|
|
190
|
+
classificationId: string;
|
|
191
|
+
createdAt: Generated<Timestamp>;
|
|
192
|
+
dataRegion: string;
|
|
193
|
+
firstSeenAt: Timestamp;
|
|
194
|
+
lastSeenAt: Timestamp;
|
|
195
|
+
mappingStatus: string | null;
|
|
196
|
+
revision: number;
|
|
197
|
+
tenantId: string;
|
|
198
|
+
updatedAt: Generated<Timestamp>;
|
|
199
|
+
}
|
|
200
|
+
export interface ControlPlaneReservationLineDefault {
|
|
201
|
+
accountKey: string | null;
|
|
202
|
+
bookingChannel: string | null;
|
|
203
|
+
bookingChannelKey: Generated<string>;
|
|
204
|
+
classificationId: string;
|
|
205
|
+
createdAt: Generated<Timestamp>;
|
|
206
|
+
id: Generated<string>;
|
|
207
|
+
partnerTenantId: string | null;
|
|
208
|
+
revenueRecognition: string | null;
|
|
209
|
+
revision: Generated<number>;
|
|
210
|
+
updatedAt: Generated<Timestamp>;
|
|
211
|
+
}
|
|
212
|
+
export interface ControlPlaneRolloutMonitorSnapshot {
|
|
213
|
+
monitorName: string;
|
|
214
|
+
result: Json;
|
|
215
|
+
snapshotDate: Timestamp;
|
|
216
|
+
}
|
|
217
|
+
export interface ControlPlaneTransactionLineMapping {
|
|
218
|
+
accountAssignmentType: string | null;
|
|
219
|
+
createdAt: Generated<Timestamp>;
|
|
220
|
+
deletedAt: Timestamp | null;
|
|
221
|
+
id: Generated<string>;
|
|
222
|
+
lineType: string;
|
|
223
|
+
revision: Generated<number>;
|
|
224
|
+
updatedAt: Generated<Timestamp>;
|
|
225
|
+
}
|
|
226
|
+
export interface ControlPlaneGeneralLedgerDefaultSet {
|
|
227
|
+
createdAt: Generated<Timestamp>;
|
|
228
|
+
id: Generated<string>;
|
|
229
|
+
partnerTenantId: string | null;
|
|
230
|
+
publishedVersion: number | null;
|
|
231
|
+
sourceDataRegion: string;
|
|
232
|
+
sourceDigest: string | null;
|
|
233
|
+
sourceTenantId: string;
|
|
234
|
+
templateKey: string;
|
|
235
|
+
updatedAt: Generated<Timestamp>;
|
|
236
|
+
}
|
|
237
|
+
export interface ControlPlaneGeneralLedgerDefaultVersion {
|
|
238
|
+
dataJson: Json;
|
|
239
|
+
defaultSetId: string;
|
|
240
|
+
id: Generated<string>;
|
|
241
|
+
publishedAt: Generated<Timestamp>;
|
|
242
|
+
sourceDigest: string;
|
|
243
|
+
sourceTenantId: string;
|
|
244
|
+
version: number;
|
|
245
|
+
}
|
|
108
246
|
export interface ControlPlaneOutbox {
|
|
109
247
|
aggregateId: string;
|
|
110
248
|
aggregateType: string;
|
|
@@ -118,12 +256,19 @@ export interface ControlPlaneOutbox {
|
|
|
118
256
|
payload: Generated<Json>;
|
|
119
257
|
publishedAt: Timestamp | null;
|
|
120
258
|
}
|
|
259
|
+
export interface ControlPlanePartnerManagedTeamAssignment {
|
|
260
|
+
createdAt: Generated<Timestamp>;
|
|
261
|
+
managedTeamId: string;
|
|
262
|
+
partnerTenantId: string;
|
|
263
|
+
userId: string;
|
|
264
|
+
}
|
|
121
265
|
export interface ControlPlaneTenant {
|
|
122
266
|
billingPartnerId: string | null;
|
|
123
267
|
billingPlan: string | null;
|
|
124
268
|
createdAt: Generated<Timestamp>;
|
|
125
269
|
dataRegion: Generated<string>;
|
|
126
270
|
id: Generated<string>;
|
|
271
|
+
migrationStatus: Generated<string>;
|
|
127
272
|
name: string;
|
|
128
273
|
partnerId: string | null;
|
|
129
274
|
partnerDeniedPermissions: Generated<string[]>;
|
|
@@ -134,10 +279,26 @@ export interface ControlPlaneTenant {
|
|
|
134
279
|
uniqueRef: string | null;
|
|
135
280
|
updatedAt: Generated<Timestamp | null>;
|
|
136
281
|
}
|
|
282
|
+
export interface ControlPlaneTenantRegionMigration {
|
|
283
|
+
actor: string;
|
|
284
|
+
completedAt: Timestamp | null;
|
|
285
|
+
error: Json | null;
|
|
286
|
+
id: string;
|
|
287
|
+
reason: string;
|
|
288
|
+
sourceManifest: Json | null;
|
|
289
|
+
sourceRegion: string;
|
|
290
|
+
startedAt: Generated<Timestamp>;
|
|
291
|
+
status: Generated<string>;
|
|
292
|
+
targetManifest: Json | null;
|
|
293
|
+
targetRegion: string;
|
|
294
|
+
tenantId: string;
|
|
295
|
+
updatedAt: Generated<Timestamp>;
|
|
296
|
+
}
|
|
137
297
|
export interface ControlPlaneTenantUser {
|
|
138
298
|
createdAt: Generated<Timestamp | null>;
|
|
139
299
|
id: Generated<string>;
|
|
140
300
|
lastInvitedAt: Timestamp | null;
|
|
301
|
+
managedTeamAccess: Generated<'all' | 'assigned'>;
|
|
141
302
|
permissionBundles: Generated<string[]>;
|
|
142
303
|
role: Generated<string | null>;
|
|
143
304
|
status: Generated<string | null>;
|
|
@@ -161,6 +322,7 @@ export interface ControlPlaneUser {
|
|
|
161
322
|
email: string | null;
|
|
162
323
|
firstName: string | null;
|
|
163
324
|
id: Generated<string>;
|
|
325
|
+
internalOperationGrants: Generated<string[]>;
|
|
164
326
|
isAdmin: Generated<boolean>;
|
|
165
327
|
lastName: string | null;
|
|
166
328
|
lastSeen: Timestamp | null;
|
|
@@ -174,6 +336,9 @@ export interface ControlPlaneUser {
|
|
|
174
336
|
updatedAt: Generated<Timestamp | null>;
|
|
175
337
|
}
|
|
176
338
|
export interface ControlPlaneDB {
|
|
339
|
+
'controlPlane.accountingIntegrityDefinitionDraft': ControlPlaneAccountingIntegrityDefinitionDraft;
|
|
340
|
+
'controlPlane.accountingIntegrityDefinitionVersion': ControlPlaneAccountingIntegrityDefinitionVersion;
|
|
341
|
+
'controlPlane.accountingIntegrityEvaluation': ControlPlaneAccountingIntegrityEvaluation;
|
|
177
342
|
'controlPlane.app': ControlPlaneApp;
|
|
178
343
|
'controlPlane.bookingChannel': ControlPlaneBookingChannel;
|
|
179
344
|
'controlPlane.bookingChannelIconCandidate': ControlPlaneBookingChannelIconCandidate;
|
|
@@ -184,10 +349,20 @@ export interface ControlPlaneDB {
|
|
|
184
349
|
'controlPlane.feature': ControlPlaneFeature;
|
|
185
350
|
'controlPlane.featureApproval': ControlPlaneFeatureApproval;
|
|
186
351
|
'controlPlane.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;
|
|
352
|
+
'controlPlane.generalLedgerDefaultSet': ControlPlaneGeneralLedgerDefaultSet;
|
|
353
|
+
'controlPlane.generalLedgerDefaultVersion': ControlPlaneGeneralLedgerDefaultVersion;
|
|
354
|
+
'controlPlane.lineClassification': ControlPlaneLineClassification;
|
|
355
|
+
'controlPlane.lineClassificationTeamUsage': ControlPlaneLineClassificationTeamUsage;
|
|
356
|
+
'controlPlane.partnerManagedTeamAssignment': ControlPlanePartnerManagedTeamAssignment;
|
|
357
|
+
'controlPlane.reservationLineDefault': ControlPlaneReservationLineDefault;
|
|
358
|
+
'controlPlane.rolloutMonitorSnapshot': ControlPlaneRolloutMonitorSnapshot;
|
|
187
359
|
'controlPlane.tenant': ControlPlaneTenant;
|
|
360
|
+
'controlPlane.tenantRegionMigration': ControlPlaneTenantRegionMigration;
|
|
188
361
|
'controlPlane.tenantUser': ControlPlaneTenantUser;
|
|
189
362
|
'controlPlane.token': ControlPlaneToken;
|
|
363
|
+
'controlPlane.transactionLineMapping': ControlPlaneTransactionLineMapping;
|
|
190
364
|
'controlPlane.user': ControlPlaneUser;
|
|
365
|
+
'controlPlaneCore.flow': ControlPlaneFlow;
|
|
191
366
|
'controlPlaneCore.issueMessageOverwrite': ControlPlaneIssueMessageOverwrite;
|
|
192
367
|
}
|
|
193
368
|
export declare function withControlPlaneSchema(kysely: Kysely<ControlPlaneDB>, schema: string, issueMessageOverwriteSchema?: string): Kysely<ControlPlaneDB>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["control-plane/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AA2SA,wDAQC;AAnTD,mCAcgB;AA2NhB,MAAM,6BAA8B,SAAQ,iCAAwB;IAClE,YACW,MAAc,EACd,2BAAmC;QAE5C,KAAK,EA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D,MAAM,EACN,2BAA2B,CAC5B,MAAA,CAAC;IACJ,CAAC;IAED,cAAc,CAAC,IAA8B;QAC3C,OAAO,uBAAA,IAAI,6CAAa,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,IAA+B;QAE/B,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;;AAED,SAAgB,sBAAsB,CACpC,MAA8B,EAC9B,MAAc,EACd,2BAA2B,GAAG,MAAM;IAEpC,OAAO,MAAM,CAAC,UAAU,CACtB,IAAI,wBAAwB,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAClE,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ColumnType,\n type FunctionNode,\n IdentifierNode,\n type Kysely,\n type KyselyPlugin,\n OperationNodeTransformer,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type QueryId,\n type QueryResult,\n type RootOperationNode,\n type SchemableIdentifierNode,\n type UnknownRow,\n} from 'kysely';\n\nexport type Generated<T> =\n T extends ColumnType<infer S, infer I, infer U>\n ? ColumnType<S, I | undefined, U>\n : ColumnType<T, T | undefined, T>;\n\nexport type Json = JsonValue;\n\nexport type JsonArray = JsonValue[];\n\nexport type JsonObject = {\n [x: string]: JsonValue | undefined;\n};\n\nexport type JsonPrimitive = boolean | number | string | null;\n\nexport type JsonValue = JsonArray | JsonObject | JsonPrimitive;\n\nexport type Timestamp = ColumnType<Date | string, Date | string, Date | string>;\n\nexport interface ControlPlaneApp {\n authentication: Generated<Json>;\n category: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconRound: string | null;\n id: Generated<string>;\n info: Json | null;\n name: string;\n type: string;\n version: Generated<number>;\n}\n\nexport interface ControlPlaneBookingChannel {\n channelRef: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconProvider: string | null;\n id: Generated<string>;\n lastGenerateRun: Timestamp | null;\n logo: string | null;\n logoProvider: string | null;\n selectedBookingChannelIconCandidateId: string | null;\n selectedBookingChannelLogoCandidateId: string | null;\n uniqueRef: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneBookingChannelIconCandidate {\n bookingChannelId: string;\n cloudflareImageId: string | null;\n color: string | null;\n comment: string | null;\n createdAt: Generated<Timestamp>;\n externalIcon: string | null;\n height: number | null;\n id: Generated<string>;\n provider: Generated<string>;\n source: string | null;\n updatedAt: Generated<Timestamp>;\n width: number | null;\n}\n\nexport interface ControlPlaneCurrency {\n name: string;\n}\n\nexport interface ControlPlaneEvent {\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n name: string;\n packageName: string;\n props: Json;\n tenantId: string | null;\n timestamp: Generated<Timestamp>;\n trackedAt: Generated<Timestamp | null>;\n userId: string | null;\n}\n\nexport interface ControlPlaneConnectionRoute {\n connectionId: string;\n createdAt: Generated<Timestamp>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeature {\n createdAt: Generated<Timestamp>;\n description: string | null;\n id: Generated<string>;\n issueUrl: string | null;\n requiredApprovals: Generated<Json | null>;\n status: Generated<string | null>;\n tenantId: string | null;\n title: string;\n updatedAt: Generated<Timestamp>;\n url: string | null;\n}\n\nexport interface ControlPlaneFeatureEnabledTeam {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeatureApproval {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n updatedAt: Generated<Timestamp>;\n userId: string;\n}\n\nexport interface ControlPlaneIssueMessageOverwrite {\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n message: string;\n pattern: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneOutbox {\n aggregateId: string;\n aggregateType: string;\n attempts: Generated<number>;\n createdAt: Generated<Timestamp>;\n dataRegion: string | null;\n eventType: string;\n eventVersion: number;\n id: Generated<string>;\n lastError: string | null;\n payload: Generated<Json>;\n publishedAt: Timestamp | null;\n}\n\nexport interface ControlPlaneTenant {\n billingPartnerId: string | null;\n billingPlan: string | null;\n createdAt: Generated<Timestamp>;\n dataRegion: Generated<string>;\n id: Generated<string>;\n name: string;\n partnerId: string | null;\n partnerDeniedPermissions: Generated<string[]>;\n slug: string;\n status: Generated<string | null>;\n storageRealm: Generated<string>;\n type: Generated<string | null>;\n uniqueRef: string | null;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneTenantUser {\n createdAt: Generated<Timestamp | null>;\n id: Generated<string>;\n lastInvitedAt: Timestamp | null;\n permissionBundles: Generated<string[]>;\n role: Generated<string | null>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp | null>;\n userId: string;\n}\n\nexport interface ControlPlaneToken {\n createdAt: Generated<Timestamp>;\n expiresAt: Timestamp | null;\n id: Generated<string>;\n nanoId: Generated<string>;\n payload: Generated<Json>;\n tenantId: string | null;\n type: string | null;\n userId: string | null;\n}\n\nexport interface ControlPlaneUser {\n clerkId: string | null;\n createdAt: Generated<Timestamp | null>;\n email: string | null;\n firstName: string | null;\n id: Generated<string>;\n isAdmin: Generated<boolean>;\n lastName: string | null;\n lastSeen: Timestamp | null;\n name: string | null;\n partnerId: string | null;\n phone: string | null;\n secondaryEmails: Generated<Json>;\n status: Generated<string | null>;\n sub: string | null;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneDB {\n 'controlPlane.app': ControlPlaneApp;\n 'controlPlane.bookingChannel': ControlPlaneBookingChannel;\n 'controlPlane.bookingChannelIconCandidate': ControlPlaneBookingChannelIconCandidate;\n 'controlPlane.connectionRoute': ControlPlaneConnectionRoute;\n 'controlPlane.controlPlaneOutbox': ControlPlaneOutbox;\n 'controlPlane.currency': ControlPlaneCurrency;\n 'controlPlane.events': ControlPlaneEvent;\n 'controlPlane.feature': ControlPlaneFeature;\n 'controlPlane.featureApproval': ControlPlaneFeatureApproval;\n 'controlPlane.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;\n 'controlPlane.tenant': ControlPlaneTenant;\n 'controlPlane.tenantUser': ControlPlaneTenantUser;\n 'controlPlane.token': ControlPlaneToken;\n 'controlPlane.user': ControlPlaneUser;\n 'controlPlaneCore.issueMessageOverwrite': ControlPlaneIssueMessageOverwrite;\n}\n\nclass ControlPlaneSchemaTransformer extends OperationNodeTransformer {\n constructor(\n readonly schema: string,\n readonly issueMessageOverwriteSchema: string\n ) {\n super();\n }\n\n protected override transformSchemableIdentifier(\n node: SchemableIdentifierNode,\n queryId: QueryId\n ): SchemableIdentifierNode {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (\n transformed.schema?.name === 'controlPlane' ||\n transformed.schema?.name === 'control_plane'\n ) {\n return { ...transformed, schema: IdentifierNode.create(this.schema) };\n }\n if (\n transformed.schema?.name === 'controlPlaneCore' ||\n transformed.schema?.name === 'control_plane_core'\n ) {\n return {\n ...transformed,\n schema: IdentifierNode.create(this.issueMessageOverwriteSchema),\n };\n }\n return transformed;\n }\n\n protected override transformFunction(\n node: FunctionNode,\n queryId: QueryId\n ): FunctionNode {\n const transformed = super.transformFunction(node, queryId);\n return node.func.startsWith('controlPlane.')\n ? {\n ...transformed,\n func: `${this.schema}.${transformed.func.slice('controlPlane.'.length)}`,\n }\n : transformed;\n }\n}\n\nclass ControlPlaneSchemaPlugin implements KyselyPlugin {\n readonly #transformer: ControlPlaneSchemaTransformer;\n\n constructor(schema: string, issueMessageOverwriteSchema: string) {\n this.#transformer = new ControlPlaneSchemaTransformer(\n schema,\n issueMessageOverwriteSchema\n );\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n\n async transformResult(\n args: PluginTransformResultArgs\n ): Promise<QueryResult<UnknownRow>> {\n return args.result;\n }\n}\n\nexport function withControlPlaneSchema(\n kysely: Kysely<ControlPlaneDB>,\n schema: string,\n issueMessageOverwriteSchema = 'core'\n) {\n return kysely.withPlugin(\n new ControlPlaneSchemaPlugin(schema, issueMessageOverwriteSchema)\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["control-plane/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AA4eA,wDAQC;AApfD,mCAcgB;AA4ZhB,MAAM,6BAA8B,SAAQ,iCAAwB;IAClE,YACW,MAAc,EACd,2BAAmC;QAE5C,KAAK,EAAE,CAAC;QAHC,WAAM,GAAN,MAAM,CAAQ;QACd,gCAA2B,GAA3B,2BAA2B,CAAQ;IAG9C,CAAC;IAEkB,4BAA4B,CAC7C,IAA6B,EAC7B,OAAgB;QAEhB,MAAM,WAAW,GAAG,KAAK,CAAC,4BAA4B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACtE,IACE,WAAW,CAAC,MAAM,EAAE,IAAI,KAAK,cAAc;YAC3C,WAAW,CAAC,MAAM,EAAE,IAAI,KAAK,eAAe,EAC5C,CAAC;YACD,OAAO,EAAE,GAAG,WAAW,EAAE,MAAM,EAAE,uBAAc,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACxE,CAAC;QACD,IACE,WAAW,CAAC,MAAM,EAAE,IAAI,KAAK,kBAAkB;YAC/C,WAAW,CAAC,MAAM,EAAE,IAAI,KAAK,oBAAoB,EACjD,CAAC;YACD,OAAO;gBACL,GAAG,WAAW;gBACd,MAAM,EAAE,uBAAc,CAAC,MAAM,CAAC,IAAI,CAAC,2BAA2B,CAAC;aAChE,CAAC;QACJ,CAAC;QACD,OAAO,WAAW,CAAC;IACrB,CAAC;IAEkB,iBAAiB,CAClC,IAAkB,EAClB,OAAgB;QAEhB,MAAM,WAAW,GAAG,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC3D,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC;YAC1C,CAAC,CAAC;gBACE,GAAG,WAAW;gBACd,IAAI,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE;aACzE;YACH,CAAC,CAAC,WAAW,CAAC;IAClB,CAAC;CACF;AAED,MAAM,wBAAwB;IAG5B,YAAY,MAAc,EAAE,2BAAmC;QAFtD,wDAA4C;QAGnD,uBAAA,IAAI,yCAAgB,IAAI,6BAA6B,CACnD,MAAM,EACN,2BAA2B,CAC5B,MAAA,CAAC;IACJ,CAAC;IAED,cAAc,CAAC,IAA8B;QAC3C,OAAO,uBAAA,IAAI,6CAAa,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAClE,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,IAA+B;QAE/B,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;;AAED,SAAgB,sBAAsB,CACpC,MAA8B,EAC9B,MAAc,EACd,2BAA2B,GAAG,MAAM;IAEpC,OAAO,MAAM,CAAC,UAAU,CACtB,IAAI,wBAAwB,CAAC,MAAM,EAAE,2BAA2B,CAAC,CAClE,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ColumnType,\n type FunctionNode,\n IdentifierNode,\n type Kysely,\n type KyselyPlugin,\n OperationNodeTransformer,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type QueryId,\n type QueryResult,\n type RootOperationNode,\n type SchemableIdentifierNode,\n type UnknownRow,\n} from 'kysely';\n\nexport type Generated<T> =\n T extends ColumnType<infer S, infer I, infer U>\n ? ColumnType<S, I | undefined, U>\n : ColumnType<T, T | undefined, T>;\n\nexport type Json = JsonValue;\n\nexport type JsonArray = JsonValue[];\n\nexport type JsonObject = {\n [x: string]: JsonValue | undefined;\n};\n\nexport type JsonPrimitive = boolean | number | string | null;\n\nexport type JsonValue = JsonArray | JsonObject | JsonPrimitive;\n\nexport type Int8 = ColumnType<\n string,\n number | string | bigint,\n number | string | bigint\n>;\n\nexport type Timestamp = ColumnType<Date | string, Date | string, Date | string>;\n\nexport interface ControlPlaneApp {\n authentication: Generated<Json>;\n category: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconRound: string | null;\n id: Generated<string>;\n info: Json | null;\n name: string;\n type: string;\n version: Generated<number>;\n}\n\nexport interface ControlPlaneAccountingIntegrityEvaluation {\n caseCount: Generated<Int8>;\n completedAt: Timestamp | null;\n completedRunCount: Generated<number>;\n createdAt: Generated<Timestamp>;\n environment: string;\n error: Json | null;\n expectedRunCount: number;\n failedRunCount: Generated<number>;\n findingRowCount: Generated<Int8>;\n gitRevision: string;\n id: string;\n results: Generated<Json>;\n rowsScanned: Generated<Int8>;\n skippedRunCount: Generated<number>;\n source: string;\n startedAt: Timestamp;\n status: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneAccountingIntegrityDefinitionDraft {\n artifact: Json;\n artifactHash: string;\n code: string;\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n ownerId: string;\n previewResult: Json | null;\n rationale: string;\n revision: Generated<number>;\n status: string;\n templateId: string;\n templateVersion: number;\n title: string;\n updatedAt: Generated<Timestamp>;\n validationResult: Json | null;\n}\n\nexport interface ControlPlaneAccountingIntegrityDefinitionVersion {\n artifact: Json;\n artifactHash: string;\n code: string;\n draftId: string;\n id: Generated<string>;\n publishedAt: Generated<Timestamp>;\n publishedBy: string;\n rollout: string;\n templateId: string;\n templateVersion: number;\n version: number;\n}\n\nexport interface ControlPlaneBookingChannel {\n channelRef: string | null;\n color: string | null;\n createdAt: Generated<Timestamp>;\n icon: string | null;\n iconProvider: string | null;\n id: Generated<string>;\n lastGenerateRun: Timestamp | null;\n logo: string | null;\n logoProvider: string | null;\n selectedBookingChannelIconCandidateId: string | null;\n selectedBookingChannelLogoCandidateId: string | null;\n uniqueRef: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneBookingChannelIconCandidate {\n bookingChannelId: string;\n cloudflareImageId: string | null;\n color: string | null;\n comment: string | null;\n createdAt: Generated<Timestamp>;\n externalIcon: string | null;\n height: number | null;\n id: Generated<string>;\n provider: Generated<string>;\n source: string | null;\n updatedAt: Generated<Timestamp>;\n width: number | null;\n}\n\nexport interface ControlPlaneCurrency {\n name: string;\n}\n\nexport interface ControlPlaneEvent {\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n name: string;\n packageName: string;\n props: Json;\n tenantId: string | null;\n timestamp: Generated<Timestamp>;\n trackedAt: Generated<Timestamp | null>;\n userId: string | null;\n}\n\nexport interface ControlPlaneConnectionRoute {\n connectionId: string;\n createdAt: Generated<Timestamp>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeature {\n createdAt: Generated<Timestamp>;\n description: string | null;\n id: Generated<string>;\n issueUrl: string | null;\n requiredApprovals: Generated<Json | null>;\n status: Generated<string | null>;\n tenantId: string | null;\n title: string;\n updatedAt: Generated<Timestamp>;\n url: string | null;\n}\n\nexport interface ControlPlaneFeatureEnabledTeam {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneFeatureApproval {\n createdAt: Generated<Timestamp>;\n featureId: string;\n id: Generated<string>;\n status: Generated<string | null>;\n updatedAt: Generated<Timestamp>;\n userId: string;\n}\n\nexport interface ControlPlaneFlow {\n appId: string;\n createdAt: Generated<Timestamp>;\n description: string | null;\n eventListening: Generated<Json>;\n id: Generated<string>;\n isPublic: Generated<boolean>;\n leftType: string | null;\n mappingSchema: Generated<Json>;\n revision: Generated<number>;\n rightType: string | null;\n runSchema: Generated<Json>;\n settingSchema: Generated<Json>;\n title: string;\n type: 'pull' | 'push' | null;\n uniqueRef: string;\n updatedAt: Generated<Timestamp>;\n useGlobalMapping: Generated<boolean>;\n}\n\nexport interface ControlPlaneIssueMessageOverwrite {\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n message: string;\n pattern: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneLineClassification {\n appConflict: Generated<boolean>;\n appId: string | null;\n createdAt: Generated<Timestamp>;\n firstSeenAt: Timestamp;\n id: Generated<string>;\n kind: string;\n lastSeenAt: Timestamp;\n name: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneLineClassificationTeamUsage {\n classificationId: string;\n createdAt: Generated<Timestamp>;\n dataRegion: string;\n firstSeenAt: Timestamp;\n lastSeenAt: Timestamp;\n mappingStatus: string | null;\n revision: number;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneReservationLineDefault {\n accountKey: string | null;\n bookingChannel: string | null;\n bookingChannelKey: Generated<string>;\n classificationId: string;\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n partnerTenantId: string | null;\n revenueRecognition: string | null;\n revision: Generated<number>;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneRolloutMonitorSnapshot {\n monitorName: string;\n result: Json;\n snapshotDate: Timestamp;\n}\n\nexport interface ControlPlaneTransactionLineMapping {\n accountAssignmentType: string | null;\n createdAt: Generated<Timestamp>;\n deletedAt: Timestamp | null;\n id: Generated<string>;\n lineType: string;\n revision: Generated<number>;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneGeneralLedgerDefaultSet {\n createdAt: Generated<Timestamp>;\n id: Generated<string>;\n partnerTenantId: string | null;\n publishedVersion: number | null;\n sourceDataRegion: string;\n sourceDigest: string | null;\n sourceTenantId: string;\n templateKey: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneGeneralLedgerDefaultVersion {\n dataJson: Json;\n defaultSetId: string;\n id: Generated<string>;\n publishedAt: Generated<Timestamp>;\n sourceDigest: string;\n sourceTenantId: string;\n version: number;\n}\n\nexport interface ControlPlaneOutbox {\n aggregateId: string;\n aggregateType: string;\n attempts: Generated<number>;\n createdAt: Generated<Timestamp>;\n dataRegion: string | null;\n eventType: string;\n eventVersion: number;\n id: Generated<string>;\n lastError: string | null;\n payload: Generated<Json>;\n publishedAt: Timestamp | null;\n}\n\nexport interface ControlPlanePartnerManagedTeamAssignment {\n createdAt: Generated<Timestamp>;\n managedTeamId: string;\n partnerTenantId: string;\n userId: string;\n}\n\nexport interface ControlPlaneTenant {\n billingPartnerId: string | null;\n billingPlan: string | null;\n createdAt: Generated<Timestamp>;\n dataRegion: Generated<string>;\n id: Generated<string>;\n migrationStatus: Generated<string>;\n name: string;\n partnerId: string | null;\n partnerDeniedPermissions: Generated<string[]>;\n slug: string;\n status: Generated<string | null>;\n storageRealm: Generated<string>;\n type: Generated<string | null>;\n uniqueRef: string | null;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneTenantRegionMigration {\n actor: string;\n completedAt: Timestamp | null;\n error: Json | null;\n id: string;\n reason: string;\n sourceManifest: Json | null;\n sourceRegion: string;\n startedAt: Generated<Timestamp>;\n status: Generated<string>;\n targetManifest: Json | null;\n targetRegion: string;\n tenantId: string;\n updatedAt: Generated<Timestamp>;\n}\n\nexport interface ControlPlaneTenantUser {\n createdAt: Generated<Timestamp | null>;\n id: Generated<string>;\n lastInvitedAt: Timestamp | null;\n managedTeamAccess: Generated<'all' | 'assigned'>;\n permissionBundles: Generated<string[]>;\n role: Generated<string | null>;\n status: Generated<string | null>;\n tenantId: string;\n updatedAt: Generated<Timestamp | null>;\n userId: string;\n}\n\nexport interface ControlPlaneToken {\n createdAt: Generated<Timestamp>;\n expiresAt: Timestamp | null;\n id: Generated<string>;\n nanoId: Generated<string>;\n payload: Generated<Json>;\n tenantId: string | null;\n type: string | null;\n userId: string | null;\n}\n\nexport interface ControlPlaneUser {\n clerkId: string | null;\n createdAt: Generated<Timestamp | null>;\n email: string | null;\n firstName: string | null;\n id: Generated<string>;\n internalOperationGrants: Generated<string[]>;\n isAdmin: Generated<boolean>;\n lastName: string | null;\n lastSeen: Timestamp | null;\n name: string | null;\n partnerId: string | null;\n phone: string | null;\n secondaryEmails: Generated<Json>;\n status: Generated<string | null>;\n sub: string | null;\n type: Generated<string | null>;\n updatedAt: Generated<Timestamp | null>;\n}\n\nexport interface ControlPlaneDB {\n 'controlPlane.accountingIntegrityDefinitionDraft': ControlPlaneAccountingIntegrityDefinitionDraft;\n 'controlPlane.accountingIntegrityDefinitionVersion': ControlPlaneAccountingIntegrityDefinitionVersion;\n 'controlPlane.accountingIntegrityEvaluation': ControlPlaneAccountingIntegrityEvaluation;\n 'controlPlane.app': ControlPlaneApp;\n 'controlPlane.bookingChannel': ControlPlaneBookingChannel;\n 'controlPlane.bookingChannelIconCandidate': ControlPlaneBookingChannelIconCandidate;\n 'controlPlane.connectionRoute': ControlPlaneConnectionRoute;\n 'controlPlane.controlPlaneOutbox': ControlPlaneOutbox;\n 'controlPlane.currency': ControlPlaneCurrency;\n 'controlPlane.events': ControlPlaneEvent;\n 'controlPlane.feature': ControlPlaneFeature;\n 'controlPlane.featureApproval': ControlPlaneFeatureApproval;\n 'controlPlane.featureEnabledTeam': ControlPlaneFeatureEnabledTeam;\n 'controlPlane.generalLedgerDefaultSet': ControlPlaneGeneralLedgerDefaultSet;\n 'controlPlane.generalLedgerDefaultVersion': ControlPlaneGeneralLedgerDefaultVersion;\n 'controlPlane.lineClassification': ControlPlaneLineClassification;\n 'controlPlane.lineClassificationTeamUsage': ControlPlaneLineClassificationTeamUsage;\n 'controlPlane.partnerManagedTeamAssignment': ControlPlanePartnerManagedTeamAssignment;\n 'controlPlane.reservationLineDefault': ControlPlaneReservationLineDefault;\n 'controlPlane.rolloutMonitorSnapshot': ControlPlaneRolloutMonitorSnapshot;\n 'controlPlane.tenant': ControlPlaneTenant;\n 'controlPlane.tenantRegionMigration': ControlPlaneTenantRegionMigration;\n 'controlPlane.tenantUser': ControlPlaneTenantUser;\n 'controlPlane.token': ControlPlaneToken;\n 'controlPlane.transactionLineMapping': ControlPlaneTransactionLineMapping;\n 'controlPlane.user': ControlPlaneUser;\n 'controlPlaneCore.flow': ControlPlaneFlow;\n 'controlPlaneCore.issueMessageOverwrite': ControlPlaneIssueMessageOverwrite;\n}\n\nclass ControlPlaneSchemaTransformer extends OperationNodeTransformer {\n constructor(\n readonly schema: string,\n readonly issueMessageOverwriteSchema: string\n ) {\n super();\n }\n\n protected override transformSchemableIdentifier(\n node: SchemableIdentifierNode,\n queryId: QueryId\n ): SchemableIdentifierNode {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (\n transformed.schema?.name === 'controlPlane' ||\n transformed.schema?.name === 'control_plane'\n ) {\n return { ...transformed, schema: IdentifierNode.create(this.schema) };\n }\n if (\n transformed.schema?.name === 'controlPlaneCore' ||\n transformed.schema?.name === 'control_plane_core'\n ) {\n return {\n ...transformed,\n schema: IdentifierNode.create(this.issueMessageOverwriteSchema),\n };\n }\n return transformed;\n }\n\n protected override transformFunction(\n node: FunctionNode,\n queryId: QueryId\n ): FunctionNode {\n const transformed = super.transformFunction(node, queryId);\n return node.func.startsWith('controlPlane.')\n ? {\n ...transformed,\n func: `${this.schema}.${transformed.func.slice('controlPlane.'.length)}`,\n }\n : transformed;\n }\n}\n\nclass ControlPlaneSchemaPlugin implements KyselyPlugin {\n readonly #transformer: ControlPlaneSchemaTransformer;\n\n constructor(schema: string, issueMessageOverwriteSchema: string) {\n this.#transformer = new ControlPlaneSchemaTransformer(\n schema,\n issueMessageOverwriteSchema\n );\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n\n async transformResult(\n args: PluginTransformResultArgs\n ): Promise<QueryResult<UnknownRow>> {\n return args.result;\n }\n}\n\nexport function withControlPlaneSchema(\n kysely: Kysely<ControlPlaneDB>,\n schema: string,\n issueMessageOverwriteSchema = 'core'\n) {\n return kysely.withPlugin(\n new ControlPlaneSchemaPlugin(schema, issueMessageOverwriteSchema)\n );\n}\n"]}
|
package/build/main/index.d.ts
CHANGED
|
@@ -10,15 +10,15 @@ export * from './regional';
|
|
|
10
10
|
export * from './transaction';
|
|
11
11
|
import type { DB } from './v1.generated';
|
|
12
12
|
type KyselyOpts = {
|
|
13
|
+
hyperdrive?: true;
|
|
13
14
|
repositoryName?: string;
|
|
14
15
|
log?: true | LogConfig;
|
|
15
16
|
};
|
|
16
17
|
type PgOpt = {
|
|
17
18
|
forceDisableSSL?: boolean;
|
|
18
|
-
hyperdrive?: true;
|
|
19
19
|
probe?: true;
|
|
20
20
|
retries?: false | number;
|
|
21
|
-
}
|
|
21
|
+
} & Pick<KyselyOpts, 'hyperdrive'>;
|
|
22
22
|
export type Kysely = K<DB>;
|
|
23
23
|
export type ControlPlaneKysely = K<ControlPlaneDB>;
|
|
24
24
|
export type ControlPlaneTransaction = T<ControlPlaneDB>;
|
package/build/main/index.js
CHANGED
|
@@ -39,31 +39,120 @@ const retryableMessages = [
|
|
|
39
39
|
'CONNECTION_CLOSED',
|
|
40
40
|
'CONNECT_TIMEOUT',
|
|
41
41
|
'Idle connection closed by Hyperdrive.',
|
|
42
|
+
'server_login_retry',
|
|
42
43
|
];
|
|
44
|
+
const postgresRetryAttempts = 3;
|
|
45
|
+
function isRetryableConnectionError(error) {
|
|
46
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
47
|
+
return retryableMessages.some((retryable) => message.includes(retryable));
|
|
48
|
+
}
|
|
49
|
+
function retryPostgres(operation, retry) {
|
|
50
|
+
return (0, exponential_backoff_1.backOff)(operation, {
|
|
51
|
+
numOfAttempts: postgresRetryAttempts,
|
|
52
|
+
startingDelay: (0, utils_1.parseDuration)('1s'),
|
|
53
|
+
maxDelay: (0, utils_1.parseDuration)('5s'),
|
|
54
|
+
retry: (error, attemptNumber) => attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
class RetryingPostgresJSDialect extends kysely_postgres_js_1.PostgresJSDialect {
|
|
58
|
+
constructor(config) {
|
|
59
|
+
super(config);
|
|
60
|
+
this.config = config;
|
|
61
|
+
}
|
|
62
|
+
createDriver() {
|
|
63
|
+
const driver = new kysely_postgres_js_1.PostgresJSDriver(this.config);
|
|
64
|
+
const connections = new WeakMap();
|
|
65
|
+
const getConnection = (connection) => {
|
|
66
|
+
const state = connections.get(connection);
|
|
67
|
+
if (!state)
|
|
68
|
+
throw new Error('Postgres connection state is unavailable');
|
|
69
|
+
return state;
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
init: () => driver.init(),
|
|
73
|
+
acquireConnection: async () => {
|
|
74
|
+
const state = {
|
|
75
|
+
connection: await driver.acquireConnection(),
|
|
76
|
+
inTransaction: false,
|
|
77
|
+
};
|
|
78
|
+
const connection = {
|
|
79
|
+
executeQuery: (compiledQuery) => retryPostgres(() => state.connection.executeQuery(compiledQuery), async (error) => {
|
|
80
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
81
|
+
if (state.inTransaction ||
|
|
82
|
+
(!isRetryableConnectionError(error) &&
|
|
83
|
+
(compiledQuery.query.kind !== 'SelectQueryNode' ||
|
|
84
|
+
(message !==
|
|
85
|
+
'Egress connection severed outside of Hyperdrive' &&
|
|
86
|
+
message !== 'Network connection lost.')))) {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
// Postgres.js already ejects a severed reserved connection.
|
|
90
|
+
// Acquire a new reservation before replaying the safe read.
|
|
91
|
+
state.connection = await driver.acquireConnection();
|
|
92
|
+
return true;
|
|
93
|
+
}),
|
|
94
|
+
streamQuery: (compiledQuery, chunkSize) => {
|
|
95
|
+
if (chunkSize === undefined) {
|
|
96
|
+
throw new Error('Postgres stream chunk size is required');
|
|
97
|
+
}
|
|
98
|
+
return state.connection.streamQuery(compiledQuery, chunkSize);
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
connections.set(connection, state);
|
|
102
|
+
return connection;
|
|
103
|
+
},
|
|
104
|
+
beginTransaction: async (connection, settings) => {
|
|
105
|
+
const state = getConnection(connection);
|
|
106
|
+
state.inTransaction = true;
|
|
107
|
+
try {
|
|
108
|
+
await driver.beginTransaction(state.connection, settings);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
state.inTransaction = false;
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
commitTransaction: async (connection) => {
|
|
116
|
+
const state = getConnection(connection);
|
|
117
|
+
try {
|
|
118
|
+
await driver.commitTransaction(state.connection);
|
|
119
|
+
}
|
|
120
|
+
finally {
|
|
121
|
+
state.inTransaction = false;
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
rollbackTransaction: async (connection) => {
|
|
125
|
+
const state = getConnection(connection);
|
|
126
|
+
try {
|
|
127
|
+
await driver.rollbackTransaction(state.connection);
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
state.inTransaction = false;
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
savepoint: (connection, savepointName, compileQuery) => driver.savepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
134
|
+
rollbackToSavepoint: (connection, savepointName, compileQuery) => driver.rollbackToSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
135
|
+
releaseSavepoint: (connection, savepointName, compileQuery) => driver.releaseSavepoint(getConnection(connection).connection, savepointName, compileQuery),
|
|
136
|
+
releaseConnection: async (connection) => {
|
|
137
|
+
await driver.releaseConnection(getConnection(connection).connection);
|
|
138
|
+
connections.delete(connection);
|
|
139
|
+
},
|
|
140
|
+
destroy: () => driver.destroy(),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
43
144
|
function useKysely(postgres, options) {
|
|
44
145
|
console.debug('Creating Kysely instance');
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (retryableMessages.some((m) => message?.includes(m)) ||
|
|
56
|
-
(arg.query.kind === 'SelectQueryNode' &&
|
|
57
|
-
(message ===
|
|
58
|
-
'Egress connection severed outside of Hyperdrive' ||
|
|
59
|
-
message === 'Network connection lost.'))) {
|
|
60
|
-
return true;
|
|
61
|
-
}
|
|
62
|
-
return false;
|
|
63
|
-
},
|
|
64
|
-
});
|
|
65
|
-
},
|
|
66
|
-
}), {
|
|
146
|
+
const reserveConnection = postgres.reserve.bind(postgres);
|
|
147
|
+
postgres.reserve = async () => {
|
|
148
|
+
const connection = await retryPostgres(reserveConnection, isRetryableConnectionError);
|
|
149
|
+
if (options?.hyperdrive) {
|
|
150
|
+
const unsafe = connection.unsafe;
|
|
151
|
+
connection.unsafe = (query, parameters, queryOptions) => unsafe(query, parameters, { ...queryOptions, prepare: true });
|
|
152
|
+
}
|
|
153
|
+
return connection;
|
|
154
|
+
};
|
|
155
|
+
const kysely = (0, plugins_1.getKysely)(new RetryingPostgresJSDialect({ postgres }), {
|
|
67
156
|
repositoryName: options?.repositoryName,
|
|
68
157
|
log: options?.log,
|
|
69
158
|
});
|
package/build/main/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,8BA0CC;AAGD,4CAmDC;AAED,wCAMC;AAED,gEAMC;AAED,sDAUC;AApKD,6DAA8C;AAE9C,2DAAuD;AACvD,wDAA8C;AAC9C,mDAA8E;AAC9E,mCAAsC;AACtC,uCAAsC;AAGtC,0CAAwB;AACxB,+CAA6B;AAC7B,mDAAiC;AACjC,0CAAwB;AACxB,6CAA2B;AAC3B,gDAA8B;AAE9B,6CAAkD;AAelD,MAAM,iBAAiB,GAAG;IACxB,mBAAmB;IACnB,iBAAiB;IACjB,uCAAuC;CACxC,C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;IAC1D,OAAO,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAEM,KAAK,UAAU,0BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,IAAA,sCAAsB,EAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type { Kysely as K, LogConfig, Transaction as T } from 'kysely';\nimport { PostgresJSDialect } from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n hyperdrive?: true;\n probe?: true;\n retries?: false | number;\n};\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n];\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const kysely = getKysely<Database>(\n new PostgresJSDialect({\n postgres,\n onReserveConnection: async (connection) => {\n const executeQuery = connection.executeQuery.bind(connection);\n connection.executeQuery = (arg) =>\n backOff(async () => await executeQuery(arg), {\n numOfAttempts: 3,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n retryableMessages.some((m) => message?.includes(m)) ||\n (arg.query.kind === 'SelectQueryNode' &&\n (message ===\n 'Egress connection severed outside of Hyperdrive' ||\n message === 'Network connection lost.'))\n ) {\n return true;\n }\n return false;\n },\n });\n },\n }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n }),\n });\n\n if (probe) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return withControlPlaneSchema(useKysely<ControlPlaneDB>(sql, opt), 'public');\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"src/","sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqLA,8BA8BC;AAGD,4CAmDC;AAED,wCAMC;AAED,gEAMC;AAED,sDAUC;AArSD,6DAA8C;AAQ9C,2DAI4B;AAC5B,wDAA8C;AAC9C,mDAA8E;AAC9E,mCAAsC;AACtC,uCAAsC;AAGtC,0CAAwB;AACxB,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AK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;YAC5B,MAAM,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IACD,MAAM,IAAI,mBAAW,CAAC,+BAA+B,CAAC,CAAC;AACzD,CAAC;AAEM,KAAK,UAAU,cAAc,CAClC,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAEM,KAAK,UAAU,0BAA0B,CAC9C,gBAAwB,EACxB,GAAwB;IAExB,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;IAC1D,OAAO,IAAA,sCAAsB,EAAC,SAAS,CAAiB,GAAG,EAAE,GAAG,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC/E,CAAC;AAEM,KAAK,UAAU,qBAAqB,CAAC,SAAS,GAAG,IAAI;IAC1D,MAAM,OAAO,CAAC,IAAI,CAAC;QACjB,OAAO,CAAC,GAAG,CACT,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CACtB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAC7D,CACF;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,SAAS,GAAG,IAAI,CAAC,CAAC;KACxD,CAAC,CAAC;IACH,YAAY,GAAG,EAAE,CAAC;AACpB,CAAC","sourcesContent":["import { backOff } from 'exponential-backoff';\nimport type {\n DatabaseConnection,\n Driver,\n Kysely as K,\n LogConfig,\n Transaction as T,\n} from 'kysely';\nimport {\n PostgresJSDialect,\n type PostgresJSDialectConfig,\n PostgresJSDriver,\n} from 'kysely-postgres-js';\nimport postgres, { type Sql } from 'postgres';\nimport { type ControlPlaneDB, withControlPlaneSchema } from './control-plane';\nimport { KyselyError } from './error';\nimport { getKysely } from './plugins';\n\nexport type { Insertable, LogEvent } from 'kysely';\nexport * from './error';\nexport * from './isomorphic';\nexport * from './postgres-error';\nexport * from './query';\nexport * from './regional';\nexport * from './transaction';\n\nimport { parseDuration } from '@vrplatform/utils';\nimport type { DB } from './v1.generated';\n\ntype KyselyOpts = {\n hyperdrive?: true;\n repositoryName?: string;\n log?: true | LogConfig;\n};\n\ntype PgOpt = {\n forceDisableSSL?: boolean;\n probe?: true;\n retries?: false | number;\n} & Pick<KyselyOpts, 'hyperdrive'>;\n\nconst retryableMessages = [\n 'CONNECTION_CLOSED',\n 'CONNECT_TIMEOUT',\n 'Idle connection closed by Hyperdrive.',\n 'server_login_retry',\n];\nconst postgresRetryAttempts = 3;\n\nfunction isRetryableConnectionError(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return retryableMessages.some((retryable) => message.includes(retryable));\n}\n\nfunction retryPostgres<T>(\n operation: () => Promise<T>,\n retry: (error: unknown, attemptNumber: number) => boolean | Promise<boolean>\n) {\n return backOff(operation, {\n numOfAttempts: postgresRetryAttempts,\n startingDelay: parseDuration('1s'),\n maxDelay: parseDuration('5s'),\n retry: (error, attemptNumber) =>\n attemptNumber < postgresRetryAttempts && retry(error, attemptNumber),\n });\n}\n\nclass RetryingPostgresJSDialect extends PostgresJSDialect {\n constructor(private readonly config: PostgresJSDialectConfig) {\n super(config);\n }\n\n override createDriver(): Driver {\n const driver = new PostgresJSDriver(this.config);\n const connections = new WeakMap<\n DatabaseConnection,\n { connection: DatabaseConnection; inTransaction: boolean }\n >();\n const getConnection = (connection: DatabaseConnection) => {\n const state = connections.get(connection);\n if (!state) throw new Error('Postgres connection state is unavailable');\n return state;\n };\n\n return {\n init: () => driver.init(),\n acquireConnection: async () => {\n const state = {\n connection: await driver.acquireConnection(),\n inTransaction: false,\n };\n const connection: DatabaseConnection = {\n executeQuery: (compiledQuery) =>\n retryPostgres(\n () => state.connection.executeQuery(compiledQuery),\n async (error) => {\n const message =\n error instanceof Error ? error.message : String(error);\n if (\n state.inTransaction ||\n (!isRetryableConnectionError(error) &&\n (compiledQuery.query.kind !== 'SelectQueryNode' ||\n (message !==\n 'Egress connection severed outside of Hyperdrive' &&\n message !== 'Network connection lost.')))\n ) {\n return false;\n }\n\n // Postgres.js already ejects a severed reserved connection.\n // Acquire a new reservation before replaying the safe read.\n state.connection = await driver.acquireConnection();\n return true;\n }\n ),\n streamQuery: (compiledQuery, chunkSize) => {\n if (chunkSize === undefined) {\n throw new Error('Postgres stream chunk size is required');\n }\n return state.connection.streamQuery(compiledQuery, chunkSize);\n },\n };\n connections.set(connection, state);\n return connection;\n },\n beginTransaction: async (connection, settings) => {\n const state = getConnection(connection);\n state.inTransaction = true;\n try {\n await driver.beginTransaction(state.connection, settings);\n } catch (error) {\n state.inTransaction = false;\n throw error;\n }\n },\n commitTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.commitTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n rollbackTransaction: async (connection) => {\n const state = getConnection(connection);\n try {\n await driver.rollbackTransaction(state.connection);\n } finally {\n state.inTransaction = false;\n }\n },\n savepoint: (connection, savepointName, compileQuery) =>\n driver.savepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n rollbackToSavepoint: (connection, savepointName, compileQuery) =>\n driver.rollbackToSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseSavepoint: (connection, savepointName, compileQuery) =>\n driver.releaseSavepoint(\n getConnection(connection).connection,\n savepointName,\n compileQuery\n ),\n releaseConnection: async (connection) => {\n await driver.releaseConnection(getConnection(connection).connection);\n connections.delete(connection);\n },\n destroy: () => driver.destroy(),\n };\n }\n}\n\nexport type Kysely = K<DB>;\nexport type ControlPlaneKysely = K<ControlPlaneDB>;\nexport type ControlPlaneTransaction = T<ControlPlaneDB>;\nexport function useKysely<Database = DB>(postgres: Sql, options?: KyselyOpts) {\n console.debug('Creating Kysely instance');\n const reserveConnection = postgres.reserve.bind(postgres);\n postgres.reserve = async () => {\n const connection = await retryPostgres(\n reserveConnection,\n isRetryableConnectionError\n );\n if (options?.hyperdrive) {\n const unsafe = connection.unsafe;\n connection.unsafe = (query, parameters, queryOptions) =>\n unsafe(query, parameters, { ...queryOptions, prepare: true });\n }\n return connection;\n };\n const kysely = getKysely<Database>(\n new RetryingPostgresJSDialect({ postgres }),\n {\n repositoryName: options?.repositoryName,\n log: options?.log,\n }\n );\n kysely.destroy = async () => {\n console.debug('Closing Kysely connection');\n await postgres.end({ timeout: 5 }).catch(() => undefined);\n const index = _connections.indexOf(postgres);\n if (index !== -1) _connections.splice(index, 1);\n };\n\n return kysely;\n}\n\nlet _connections: postgres.Sql[] = [];\nexport async function useAsyncPostgres(connectionString: string, opt?: PgOpt) {\n const delayMs = 2500;\n const probe = opt?.probe === true;\n const retries = probe ? (opt?.retries === false ? 0 : opt?.retries || 3) : 1;\n const ssl = opt?.forceDisableSSL !== true && opt?.hyperdrive !== true;\n const url = new URL(connectionString);\n\n console.debug(\n `Creating Postgres connection with probe=${probe}, ${retries} attempts, ssl=${ssl}, and port=${url.port}`\n );\n if (_connections.length > 0)\n console.warn(`We already have ${_connections.length} Postgres connections`);\n\n for (let attempt = 1; attempt <= retries; attempt++) {\n try {\n const sql = postgres(connectionString, {\n ssl: ssl ? 'require' : false,\n target_session_attrs: 'read-write',\n // enable prepare statements, pgbouncer on crunchy allows for prepared statements\n prepare: true,\n ...(opt?.hyperdrive\n ? {\n max: 5,\n // Retire idle clients before Hyperdrive can close them asynchronously.\n idle_timeout: 10,\n }\n : {\n connect_timeout: 10,\n idle_timeout: 60,\n }),\n });\n\n if (probe) {\n await sql`select 1`;\n }\n // statement_timeout/lock_timeout are role-level settings on the cluster\n // (ALTER ROLE application SET ...) so they cover every pooled\n // connection; per-session SETs here only ever applied to one of them\n\n _connections.push(sql);\n return sql;\n } catch (err) {\n if (attempt === retries) throw err;\n console.warn(\n `Postgres connection failed (attempt ${attempt}), retrying...`\n );\n console.error('error', err);\n await new Promise((res) => setTimeout(res, delayMs));\n }\n }\n throw new KyselyError('Unable to connect to Postgres');\n}\n\nexport async function useAsyncKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return useKysely(sql, opt);\n}\n\nexport async function useAsyncControlPlaneKysely(\n connectionString: string,\n opt?: PgOpt & KyselyOpts\n) {\n const sql = await useAsyncPostgres(connectionString, opt);\n return withControlPlaneSchema(useKysely<ControlPlaneDB>(sql, opt), 'public');\n}\n\nexport async function forceCloseAllPostgres(timeoutMs = 5000) {\n await Promise.race([\n Promise.all(\n _connections.map((pg) =>\n pg.end({ timeout: timeoutMs / 1000 }).catch(() => undefined)\n )\n ),\n new Promise((res) => setTimeout(res, timeoutMs + 1000)),\n ]);\n _connections = [];\n}\n"]}
|
|
@@ -52,6 +52,7 @@ async function normalizeGeneratedTypes(root) {
|
|
|
52
52
|
const current = await Bun.file(outFile).text();
|
|
53
53
|
const next = current
|
|
54
54
|
.replace('export type Timestamp = ColumnType<Date, Date | string, Date | string>;', 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;')
|
|
55
|
+
.replace(' managedTeamAccess: Generated<string>;\n', ' managedTeamAccess: Generated<"all" | "assigned">;\n')
|
|
55
56
|
.replace(' slug: string;\n', ' slug: Generated<string>;\n');
|
|
56
57
|
if (next !== current) {
|
|
57
58
|
await Bun.write(outFile, next);
|
|
@@ -71,6 +72,7 @@ async function migrate(root, client) {
|
|
|
71
72
|
async function migrateKysely(root, kysely) {
|
|
72
73
|
console.log('init migrating kysely ....');
|
|
73
74
|
const migrator = new kysely_1.Migrator({
|
|
75
|
+
allowUnorderedMigrations: true,
|
|
74
76
|
db: kysely,
|
|
75
77
|
migrationTableSchema: migration_1.appMigrationEpoch.tableSchema,
|
|
76
78
|
migrationTableName: migration_1.appMigrationEpoch.tableName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2HA,8CA6BC;AAxJD,qCAAyC;AACzC,+CAA0C;AAC1C,gDAAkC;AAClC,yCAAiC;AACjC,iDAA8C;AAC9C,mCAAsE;AACtE,oEAAqC;AACrC,iEAAsD;AACtD,4CAAiD;AACjD,wCAAuC;AAGvC,KAAK,UAAU,uBAAuB,CAAC,IAAY;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,MAAM,IAAI,GAAG,OAAO;SACjB,OAAO,CACN,yEAAyE,EACzE,kFAAkF,CACnF;SACA,OAAO,CAAC,mBAAmB,EAAE,8BAA8B,CAAC,CAAC;IAEhE,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;AACH,CAAC;AAED,KAAK,UAAU,OAAO,CAAC,IAAY,EAAE,MAAc;IACjD,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;IAC3C,IAAI,KAAK,EAAE,MAAM,SAAS,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAC9C,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,IAAA,gBAAI,EAAC,IAAI,EAAE,SAAS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AAM,YAAY,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAEhD,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,UAAU;IACV,MAAM,MAAM,CAAC,GAAG,CAAA,UAAU,CAAC;IAC3B,MAAM,OAAO,GAAG,IAAI,qCAAa,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,MAAM,GAAG,IAAA,mBAAS,EAAC,OAAO,EAAE;QAChC,cAAc,EAAE,cAAc;QAC9B,GAAG,EAAE,SAAS;KACf,CAAC,CAAC;IAEH,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpD,MAAM,CAAC,OAAO,GAAG,KAAK,IAAI,EAAE;QAC1B,IAAI,WAAW;YAAE,OAAO;QACxB,WAAW,GAAG,IAAI,CAAC;QACnB,yCAAyC;QACzC,MAAM,eAAe,EAAE,CAAC;QACxB,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { appMigrationEpoch } from '../migration';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current\n .replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n )\n .replace(' slug: string;\\n', ' slug: Generated<string>;\\n');\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n db: kysely,\n migrationTableSchema: appMigrationEpoch.tableSchema,\n migrationTableName: appMigrationEpoch.tableName,\n migrationLockTableName: appMigrationEpoch.lockTableName,\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, appMigrationEpoch.folder),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy();\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"generate.js","sourceRoot":"src/","sources":["local/generate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,8CA6BC;AA7JD,qCAAyC;AACzC,+CAA0C;AAC1C,gDAAkC;AAClC,yCAAiC;AACjC,iDAA8C;AAC9C,mCAAsE;AACtE,oEAAqC;AACrC,iEAAsD;AACtD,4CAAiD;AACjD,wCAAuC;AAGvC,KAAK,UAAU,uBAAuB,CAAC,IAAY;IACjD,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,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B,WAAW,GAAG,IAAI,CAAC;QACnB,yCAAyC;QACzC,MAAM,eAAe,EAAE,CAAC;QACxB,cAAc;QACd,0EAA0E;QAC1E,IAAI;IACN,CAAC,CAAC;IAEF,iFAAiF;IAEjF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { exists } from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { join } from 'node:path';\nimport { PGlite } from '@electric-sql/pglite';\nimport { FileMigrationProvider, type Kysely, Migrator } from 'kysely';\nimport codegen from 'kysely-codegen';\nimport { PGliteDialect } from 'kysely-pglite-dialect';\nimport { appMigrationEpoch } from '../migration';\nimport { getKysely } from '../plugins';\nimport type { DB } from '../v1.generated';\n\nasync function normalizeGeneratedTypes(root: string) {\n const outFile = path.join(root, 'src/v1.generated.ts');\n const current = await Bun.file(outFile).text();\n const next = current\n .replace(\n 'export type Timestamp = ColumnType<Date, Date | string, Date | string>;',\n 'export type Timestamp = ColumnType<Date | string, Date | string, Date | string>;'\n )\n .replace(\n ' managedTeamAccess: Generated<string>;\\n',\n ' managedTeamAccess: Generated<\"all\" | \"assigned\">;\\n'\n )\n .replace(' slug: string;\\n', ' slug: Generated<string>;\\n');\n\n if (next !== current) {\n await Bun.write(outFile, next);\n }\n}\n\nasync function migrate(root: string, client: PGlite) {\n console.log('migrating pglite ....');\n const glob = new Bun.Glob('initial/*.sql');\n for await (const migration of glob.scan(root)) {\n const raw = await Bun.file(join(root, migration)).text();\n // `pg_dump` (v17+) prepends `\\restrict`/`\\unrestrict` psql meta commands\n // which PostgreSQL-compatible parsers (like PGlite) cannot execute.\n const sanitized = raw.replace(/^\\s*\\\\(?:un)?restrict.*$/gim, '');\n await client.exec(sanitized);\n }\n}\n\nasync function migrateKysely(root: string, kysely: Kysely<DB>) {\n console.log('init migrating kysely ....');\n const migrator = new Migrator({\n allowUnorderedMigrations: true,\n db: kysely,\n migrationTableSchema: appMigrationEpoch.tableSchema,\n migrationTableName: appMigrationEpoch.tableName,\n migrationLockTableName: appMigrationEpoch.lockTableName,\n provider: new FileMigrationProvider({\n fs,\n path,\n // This needs to be an absolute path.\n migrationFolder: path.join(root, appMigrationEpoch.folder),\n }),\n });\n\n console.log('migrating kysely ....');\n const { error, results } = await migrator.migrateToLatest().catch(() => {\n console.error('failed to migrate');\n process.exit(1);\n });\n\n for (const it of results ?? []) {\n if (it.status === 'Success') {\n console.log(`migration \"${it.migrationName}\" was executed successfully`);\n } else if (it.status === 'Error') {\n console.error(`failed to execute migration \"${it.migrationName}\"`);\n }\n }\n\n if (error) {\n console.error('failed to migrate');\n console.error(error);\n process.exit(1);\n }\n}\n\nasync function generateDump(root: string, dumpPath: string) {\n const dataExists = await exists(dumpPath).catch(() => false);\n if (!dataExists) {\n console.log('Creating initial dump');\n const main = new PGlite();\n await migrate(root, main).catch(async (err) => {\n console.error('failed to migrate initial dump');\n await Bun.write(\n '../logs/migrate-initial-dump.json',\n JSON.stringify(err as any, null, 2)\n );\n process.exit(1);\n });\n const dialect = new PGliteDialect(main);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n await migrateKysely(root, kysely).catch(() => {\n console.error('failed to migrate kysely');\n process.exit(1);\n });\n await codegen\n .generate({\n db: kysely,\n outFile: path.join(root, 'src/v1.generated.ts'),\n defaultSchemas: ['xxx'],\n camelCase: true,\n dialect: codegen.getDialect('postgres'),\n })\n .catch(() => {\n console.error('failed to generate kysely');\n process.exit(1);\n });\n await normalizeGeneratedTypes(root);\n const content = await main.dumpDataDir('none').catch(() => {\n console.error('failed to dump data');\n process.exit(1);\n });\n await Bun.write(dumpPath, content).catch(() => {\n console.error('failed to write dump');\n process.exit(1);\n });\n return content;\n }\n return Bun.file(dumpPath);\n}\n\nexport async function createLocalKysely(root: string, dumpPath: string) {\n let isDestroyed = false;\n //const now = performance.now();\n\n const dump = await generateDump(root, dumpPath);\n\n const pglite = new PGlite({ loadDataDir: dump });\n // warm up\n await pglite.sql`SELECT 1`;\n const dialect = new PGliteDialect(pglite);\n const kysely = getKysely(dialect, {\n repositoryName: 'localTesting',\n log: undefined,\n });\n\n const originalDestroy = kysely.destroy.bind(kysely);\n kysely.destroy = async () => {\n if (isDestroyed) return;\n isDestroyed = true;\n // const destroyTime = performance.now();\n await originalDestroy();\n //console.log(\n // `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`\n //);\n };\n\n // console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);\n\n return kysely;\n}\n"]}
|
|
@@ -48,6 +48,7 @@ exports.root = path.join(__dirname, '../..');
|
|
|
48
48
|
exports.dumpPath = path.join(exports.root, '.data.tar');
|
|
49
49
|
async function migrateToLatest(kysely) {
|
|
50
50
|
const migrator = new kysely_1.Migrator({
|
|
51
|
+
allowUnorderedMigrations: true,
|
|
51
52
|
db: kysely,
|
|
52
53
|
migrationTableSchema: migration_1.appMigrationEpoch.tableSchema,
|
|
53
54
|
migrationTableName: migration_1.appMigrationEpoch.tableName,
|
|
@@ -100,6 +101,7 @@ async function useLocalKysely(args = {}) {
|
|
|
100
101
|
if (controlPlaneMigrationError) {
|
|
101
102
|
throw controlPlaneMigrationError;
|
|
102
103
|
}
|
|
104
|
+
await (0, kysely_1.sql) `alter table core.flow set schema public`.execute(controlPlaneBootstrapKysely);
|
|
103
105
|
await (0, kysely_1.sql) `alter table core.issue_message_overwrite set schema public`.execute(controlPlaneBootstrapKysely);
|
|
104
106
|
await (0, kysely_1.sql) `drop schema core`.execute(controlPlaneBootstrapKysely);
|
|
105
107
|
await (0, kysely_1.sql) `alter schema public rename to control_plane`.execute(controlPlaneBootstrapKysely);
|
|
@@ -119,6 +121,16 @@ async function useLocalKysely(args = {}) {
|
|
|
119
121
|
'control_plane.build_unique_tenant_slug(text,uuid)'::regprocedure
|
|
120
122
|
) into definition;
|
|
121
123
|
execute replace(definition, 'public.', 'control_plane.');
|
|
124
|
+
|
|
125
|
+
select pg_get_functiondef(
|
|
126
|
+
'control_plane.refresh_operation_state(uuid)'::regprocedure
|
|
127
|
+
) into definition;
|
|
128
|
+
execute replace(definition, 'public.', 'control_plane.');
|
|
129
|
+
|
|
130
|
+
select pg_get_functiondef(
|
|
131
|
+
'control_plane.refresh_destructive_job_operation()'::regprocedure
|
|
132
|
+
) into definition;
|
|
133
|
+
execute replace(definition, 'public.', 'control_plane.');
|
|
122
134
|
end;
|
|
123
135
|
$$;
|
|
124
136
|
`.execute(controlPlaneBootstrapKysely);
|