@hiai-gg/docsmint 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2669 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+
17
+ // ../db/src/schema.ts
18
+ var exports_schema = {};
19
+ __export(exports_schema, {
20
+ versions: () => versions,
21
+ versionRelations: () => versionRelations,
22
+ verifications: () => verifications,
23
+ users: () => users,
24
+ tags: () => tags,
25
+ tagRelations: () => tagRelations,
26
+ shareRoleEnum: () => shareRoleEnum,
27
+ shareLinks: () => shareLinks,
28
+ shareLinkRelations: () => shareLinkRelations,
29
+ sessions: () => sessions,
30
+ pipelineStatusEnum: () => pipelineStatusEnum,
31
+ pipelineStageEnum: () => pipelineStageEnum,
32
+ lifecycleOperations: () => lifecycleOperations,
33
+ lifecycleOperationStatusEnum: () => lifecycleOperationStatusEnum,
34
+ lifecycleOperationKindEnum: () => lifecycleOperationKindEnum,
35
+ guestAccessRelations: () => guestAccessRelations,
36
+ guestAccess: () => guestAccess,
37
+ folders: () => folders,
38
+ folderRelations: () => folderRelations,
39
+ embeddingStatusEnum: () => embeddingStatusEnum,
40
+ documents: () => documents,
41
+ documentVisibilityEnum: () => documentVisibilityEnum,
42
+ documentTags: () => documentTags,
43
+ documentTagRelations: () => documentTagRelations,
44
+ documentRelations: () => documentRelations,
45
+ documentPipelineRuns: () => documentPipelineRuns,
46
+ documentPipelineBatches: () => documentPipelineBatches,
47
+ documentEmbeddings: () => documentEmbeddings,
48
+ documentEmbeddingRelations: () => documentEmbeddingRelations,
49
+ documentCreateOperations: () => documentCreateOperations,
50
+ categoryRelations: () => categoryRelations,
51
+ categories: () => categories,
52
+ auditLog: () => auditLog,
53
+ attachments: () => attachments,
54
+ attachmentRelations: () => attachmentRelations,
55
+ apiKeys: () => apiKeys,
56
+ apiKeyRelations: () => apiKeyRelations,
57
+ accounts: () => accounts
58
+ });
59
+ import { pgTable, uuid, text, timestamp, bigint, jsonb, index, uniqueIndex, customType, boolean, check, integer, pgEnum } from "drizzle-orm/pg-core";
60
+ import { relations, sql } from "drizzle-orm";
61
+ var vector = customType({
62
+ dataType(config) {
63
+ return `vector(${config.dimensions})`;
64
+ },
65
+ toDriver(value) {
66
+ return JSON.stringify(value);
67
+ },
68
+ fromDriver(value) {
69
+ if (typeof value === "string")
70
+ return JSON.parse(value);
71
+ return value;
72
+ }
73
+ });
74
+ var tsvector = customType({
75
+ dataType() {
76
+ return "tsvector";
77
+ }
78
+ });
79
+ var documentVisibilityEnum = pgEnum("document_visibility", ["private", "shared", "public"]);
80
+ var shareRoleEnum = pgEnum("share_role", ["viewer", "commenter", "editor"]);
81
+ var embeddingStatusEnum = pgEnum("embedding_status", [
82
+ "pending",
83
+ "processing",
84
+ "ready",
85
+ "failed",
86
+ "stale"
87
+ ]);
88
+ var pipelineStageEnum = pgEnum("pipeline_stage", [
89
+ "prepare",
90
+ "embed",
91
+ "graph",
92
+ "summarize",
93
+ "finalize"
94
+ ]);
95
+ var pipelineStatusEnum = pgEnum("pipeline_status", [
96
+ "pending",
97
+ "processing",
98
+ "ready",
99
+ "retrying",
100
+ "failed",
101
+ "ready_with_warnings",
102
+ "skipped",
103
+ "cancelled"
104
+ ]);
105
+ var lifecycleOperationKindEnum = pgEnum("lifecycle_operation_kind", [
106
+ "export",
107
+ "purge"
108
+ ]);
109
+ var lifecycleOperationStatusEnum = pgEnum("lifecycle_operation_status", [
110
+ "pending",
111
+ "running",
112
+ "retryable",
113
+ "completed",
114
+ "rejected"
115
+ ]);
116
+ var users = pgTable("users", {
117
+ id: uuid("id").primaryKey().defaultRandom(),
118
+ email: text("email").notNull().unique(),
119
+ name: text("name"),
120
+ emailVerified: boolean("email_verified").default(false),
121
+ image: text("image"),
122
+ createdAt: timestamp("created_at").defaultNow().notNull(),
123
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
124
+ });
125
+ var sessions = pgTable("sessions", {
126
+ id: uuid("id").primaryKey().defaultRandom(),
127
+ userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
128
+ token: text("token").notNull().unique(),
129
+ expiresAt: timestamp("expires_at").notNull(),
130
+ ipAddress: text("ip_address"),
131
+ userAgent: text("user_agent"),
132
+ revokedAt: timestamp("revoked_at"),
133
+ createdAt: timestamp("created_at").defaultNow().notNull(),
134
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
135
+ }, (table) => [
136
+ index("sessions_user_id_idx").on(table.userId),
137
+ index("sessions_revoked_at_idx").on(table.revokedAt).where(sql`${table.revokedAt} IS NOT NULL`)
138
+ ]);
139
+ var accounts = pgTable("accounts", {
140
+ id: uuid("id").primaryKey().defaultRandom(),
141
+ userId: uuid("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
142
+ accountId: text("account_id").notNull(),
143
+ providerId: text("provider_id").notNull(),
144
+ accessToken: text("access_token"),
145
+ refreshToken: text("refresh_token"),
146
+ accessTokenExpiresAt: timestamp("access_token_expires_at"),
147
+ refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
148
+ scope: text("scope"),
149
+ password: text("password"),
150
+ createdAt: timestamp("created_at").defaultNow().notNull(),
151
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
152
+ }, (table) => [
153
+ index("accounts_user_id_idx").on(table.userId),
154
+ uniqueIndex("accounts_provider_account_idx").on(table.providerId, table.accountId)
155
+ ]);
156
+ var verifications = pgTable("verifications", {
157
+ id: uuid("id").primaryKey().defaultRandom(),
158
+ identifier: text("identifier").notNull(),
159
+ value: text("value").notNull(),
160
+ expiresAt: timestamp("expires_at").notNull(),
161
+ createdAt: timestamp("created_at").defaultNow().notNull(),
162
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
163
+ }, (table) => [
164
+ index("verifications_identifier_idx").on(table.identifier)
165
+ ]);
166
+ var folders = pgTable("folders", {
167
+ id: uuid("id").primaryKey().defaultRandom(),
168
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
169
+ workspaceId: text("workspace_id"),
170
+ parentId: uuid("parent_id").references(() => folders.id, {
171
+ onDelete: "set null"
172
+ }),
173
+ categoryId: uuid("category_id").references(() => categories.id, {
174
+ onDelete: "set null"
175
+ }),
176
+ name: text("name").notNull(),
177
+ order: integer("order").notNull().default(0),
178
+ createdAt: timestamp("created_at").defaultNow().notNull(),
179
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
180
+ }, (table) => [
181
+ index("folders_owner_id_idx").on(table.ownerId),
182
+ index("folders_parent_id_idx").on(table.parentId),
183
+ index("folders_category_id_idx").on(table.categoryId)
184
+ ]);
185
+ var folderRelations = relations(folders, ({ one, many }) => ({
186
+ owner: one(users, { fields: [folders.ownerId], references: [users.id] }),
187
+ parent: one(folders, {
188
+ fields: [folders.parentId],
189
+ references: [folders.id],
190
+ relationName: "folderParent"
191
+ }),
192
+ category: one(categories, {
193
+ fields: [folders.categoryId],
194
+ references: [categories.id]
195
+ }),
196
+ children: many(folders, { relationName: "folderParent" }),
197
+ documents: many(documents)
198
+ }));
199
+ var documents = pgTable("documents", {
200
+ id: uuid("id").primaryKey().defaultRandom(),
201
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
202
+ workspaceId: text("workspace_id"),
203
+ folderId: uuid("folder_id").references(() => folders.id, {
204
+ onDelete: "set null"
205
+ }),
206
+ categoryId: uuid("category_id").references(() => categories.id, {
207
+ onDelete: "set null"
208
+ }),
209
+ title: text("title").notNull().default("Untitled"),
210
+ content: text("content").default(""),
211
+ contentJson: jsonb("content_json"),
212
+ metadata: jsonb("metadata"),
213
+ visibility: documentVisibilityEnum("visibility").notNull().default("private"),
214
+ contentHash: text("content_hash"),
215
+ lastSignificantHash: text("last_significant_hash"),
216
+ lastSignificantUpdateAt: timestamp("last_significant_update_at"),
217
+ pendingMinorChanges: boolean("pending_minor_changes").default(false).notNull(),
218
+ metadataChangedAt: timestamp("metadata_changed_at"),
219
+ searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', left(COALESCE(title, '') || ' ' || regexp_replace(COALESCE(content, ''), 'data:[^[:space:])>]+', ' ', 'g'), 200000))`),
220
+ searchVectorSimple: tsvector("search_vector_simple").generatedAlwaysAs(sql`to_tsvector('simple', left(COALESCE(title, '') || ' ' || regexp_replace(COALESCE(content, ''), 'data:[^[:space:])>]+', ' ', 'g'), 200000))`),
221
+ embeddingStatus: embeddingStatusEnum("embedding_status").notNull().default("pending"),
222
+ activeEmbeddingGeneration: uuid("active_embedding_generation"),
223
+ pendingEmbeddingGeneration: uuid("pending_embedding_generation"),
224
+ embeddingProfile: text("embedding_profile"),
225
+ embeddingErrorCode: text("embedding_error_code"),
226
+ embeddingUpdatedAt: timestamp("embedding_updated_at"),
227
+ deletedAt: timestamp("deleted_at"),
228
+ createdAt: timestamp("created_at").defaultNow().notNull(),
229
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
230
+ }, (table) => [
231
+ index("documents_owner_id_idx").on(table.ownerId),
232
+ index("documents_folder_id_idx").on(table.folderId),
233
+ index("documents_category_id_idx").on(table.categoryId),
234
+ index("documents_created_at_idx").on(table.createdAt),
235
+ index("idx_documents_search_vector").using("gin", table.searchVector),
236
+ index("idx_documents_search_vector_simple").using("gin", table.searchVectorSimple),
237
+ index("documents_embedding_status_idx").on(table.embeddingStatus),
238
+ index("documents_workspace_deleted_at_idx").on(table.workspaceId, table.deletedAt),
239
+ index("idx_documents_title_trgm").using("gin", sql`${table.title} gin_trgm_ops`)
240
+ ]);
241
+ var documentRelations = relations(documents, ({ one, many }) => ({
242
+ owner: one(users, { fields: [documents.ownerId], references: [users.id] }),
243
+ folder: one(folders, {
244
+ fields: [documents.folderId],
245
+ references: [folders.id]
246
+ }),
247
+ category: one(categories, {
248
+ fields: [documents.categoryId],
249
+ references: [categories.id]
250
+ }),
251
+ tags: many(documentTags),
252
+ attachments: many(attachments),
253
+ versions: many(versions)
254
+ }));
255
+ var documentPipelineRuns = pgTable("document_pipeline_runs", {
256
+ id: uuid("id").primaryKey().defaultRandom(),
257
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
258
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
259
+ workspaceId: text("workspace_id"),
260
+ generationId: uuid("generation_id").notNull(),
261
+ revision: text("revision").notNull(),
262
+ source: text("source").notNull(),
263
+ status: pipelineStatusEnum("status").notNull().default("pending"),
264
+ prepareStatus: pipelineStatusEnum("prepare_status").notNull().default("pending"),
265
+ embedStatus: pipelineStatusEnum("embed_status").notNull().default("pending"),
266
+ graphStatus: pipelineStatusEnum("graph_status").notNull().default("pending"),
267
+ summarizeStatus: pipelineStatusEnum("summarize_status").notNull().default("pending"),
268
+ finalizeStatus: pipelineStatusEnum("finalize_status").notNull().default("pending"),
269
+ totalBatches: integer("total_batches").notNull().default(0),
270
+ completedBatches: integer("completed_batches").notNull().default(0),
271
+ failedBatches: integer("failed_batches").notNull().default(0),
272
+ errorCode: text("error_code"),
273
+ attempts: integer("attempts").notNull().default(0),
274
+ requestedAt: timestamp("requested_at").defaultNow().notNull(),
275
+ startedAt: timestamp("started_at"),
276
+ completedAt: timestamp("completed_at"),
277
+ heartbeatAt: timestamp("heartbeat_at"),
278
+ availableAt: timestamp("available_at"),
279
+ createdAt: timestamp("created_at").defaultNow().notNull(),
280
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
281
+ }, (table) => [
282
+ uniqueIndex("document_pipeline_runs_document_generation_idx").on(table.documentId, table.generationId),
283
+ index("document_pipeline_runs_owner_status_updated_idx").on(table.ownerId, table.status, table.updatedAt)
284
+ ]);
285
+ var documentPipelineBatches = pgTable("document_pipeline_batches", {
286
+ id: uuid("id").primaryKey().defaultRandom(),
287
+ workspaceId: text("workspace_id"),
288
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
289
+ generationId: uuid("generation_id").notNull(),
290
+ batchIndex: integer("batch_index").notNull(),
291
+ stage: pipelineStageEnum("stage").notNull().default("embed"),
292
+ chunkStart: integer("chunk_start").notNull(),
293
+ chunkEnd: integer("chunk_end").notNull(),
294
+ status: pipelineStatusEnum("status").notNull().default("pending"),
295
+ attempts: integer("attempts").notNull().default(0),
296
+ embeddingProfile: text("embedding_profile"),
297
+ errorCode: text("error_code"),
298
+ availableAt: timestamp("available_at"),
299
+ startedAt: timestamp("started_at"),
300
+ completedAt: timestamp("completed_at"),
301
+ heartbeatAt: timestamp("heartbeat_at"),
302
+ createdAt: timestamp("created_at").defaultNow().notNull(),
303
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
304
+ }, (table) => [
305
+ uniqueIndex("document_pipeline_batches_generation_index_idx").on(table.generationId, table.batchIndex),
306
+ index("document_pipeline_batches_stage_status_available_idx").on(table.stage, table.status, table.availableAt),
307
+ index("document_pipeline_batches_document_id_idx").on(table.documentId)
308
+ ]);
309
+ var tags = pgTable("tags", {
310
+ id: uuid("id").primaryKey().defaultRandom(),
311
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
312
+ workspaceId: text("workspace_id"),
313
+ name: text("name").notNull(),
314
+ color: text("color"),
315
+ createdAt: timestamp("created_at").defaultNow().notNull()
316
+ }, (table) => [
317
+ index("tags_owner_id_idx").on(table.ownerId),
318
+ uniqueIndex("tags_owner_name_idx").on(table.ownerId, table.name)
319
+ ]);
320
+ var tagRelations = relations(tags, ({ many }) => ({
321
+ documents: many(documentTags)
322
+ }));
323
+ var categories = pgTable("categories", {
324
+ id: uuid("id").primaryKey().defaultRandom(),
325
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
326
+ workspaceId: text("workspace_id"),
327
+ name: text("name").notNull(),
328
+ order: integer("order").notNull().default(0),
329
+ apiMode: text("api_mode").notNull().default("unavailable"),
330
+ apiPermissionRead: boolean("api_permission_read").notNull().default(false),
331
+ apiPermissionEdit: boolean("api_permission_edit").notNull().default(false),
332
+ apiPermissionWrite: boolean("api_permission_write").notNull().default(false),
333
+ createdAt: timestamp("created_at").defaultNow().notNull(),
334
+ updatedAt: timestamp("updated_at").defaultNow().notNull()
335
+ }, (table) => [
336
+ index("categories_owner_id_idx").on(table.ownerId),
337
+ index("categories_api_mode_idx").on(table.apiMode)
338
+ ]);
339
+ var categoryRelations = relations(categories, ({ one, many }) => ({
340
+ owner: one(users, { fields: [categories.ownerId], references: [users.id] }),
341
+ folders: many(folders),
342
+ documents: many(documents)
343
+ }));
344
+ var documentTags = pgTable("document_tags", {
345
+ workspaceId: text("workspace_id"),
346
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
347
+ tagId: uuid("tag_id").notNull().references(() => tags.id, { onDelete: "cascade" })
348
+ }, (table) => [
349
+ uniqueIndex("document_tags_unique_idx").on(table.documentId, table.tagId)
350
+ ]);
351
+ var documentTagRelations = relations(documentTags, ({ one }) => ({
352
+ document: one(documents, {
353
+ fields: [documentTags.documentId],
354
+ references: [documents.id]
355
+ }),
356
+ tag: one(tags, { fields: [documentTags.tagId], references: [tags.id] })
357
+ }));
358
+ var shareLinks = pgTable("share_links", {
359
+ id: uuid("id").primaryKey().defaultRandom(),
360
+ documentId: uuid("document_id").references(() => documents.id, {
361
+ onDelete: "cascade"
362
+ }),
363
+ folderId: uuid("folder_id").references(() => folders.id, {
364
+ onDelete: "cascade"
365
+ }),
366
+ categoryId: uuid("category_id").references(() => categories.id, {
367
+ onDelete: "cascade"
368
+ }),
369
+ token: text("token").notNull().unique(),
370
+ passwordHash: text("password_hash"),
371
+ role: shareRoleEnum("role").notNull().default("viewer"),
372
+ expiresAt: timestamp("expires_at"),
373
+ createdBy: uuid("created_by").notNull().references(() => users.id, { onDelete: "cascade" }),
374
+ workspaceId: text("workspace_id"),
375
+ createdAt: timestamp("created_at").defaultNow().notNull()
376
+ }, (table) => [
377
+ index("share_links_token_idx").on(table.token),
378
+ index("share_links_document_id_idx").on(table.documentId),
379
+ index("share_links_folder_id_idx").on(table.folderId),
380
+ index("share_links_category_id_idx").on(table.categoryId),
381
+ check("share_links_exactly_one_target_check", sql`num_nonnulls(${table.documentId}, ${table.folderId}, ${table.categoryId}) = 1`)
382
+ ]);
383
+ var shareLinkRelations = relations(shareLinks, ({ one, many }) => ({
384
+ document: one(documents, {
385
+ fields: [shareLinks.documentId],
386
+ references: [documents.id]
387
+ }),
388
+ folder: one(folders, {
389
+ fields: [shareLinks.folderId],
390
+ references: [folders.id]
391
+ }),
392
+ category: one(categories, {
393
+ fields: [shareLinks.categoryId],
394
+ references: [categories.id]
395
+ }),
396
+ creator: one(users, {
397
+ fields: [shareLinks.createdBy],
398
+ references: [users.id]
399
+ }),
400
+ guestAccess: many(guestAccess)
401
+ }));
402
+ var guestAccess = pgTable("guest_access", {
403
+ id: uuid("id").primaryKey().defaultRandom(),
404
+ shareLinkId: uuid("share_link_id").notNull().references(() => shareLinks.id, { onDelete: "cascade" }),
405
+ workspaceId: text("workspace_id"),
406
+ guestEmail: text("guest_email").notNull(),
407
+ grantedAt: timestamp("granted_at").defaultNow().notNull()
408
+ }, (table) => [index("guest_access_share_link_idx").on(table.shareLinkId)]);
409
+ var guestAccessRelations = relations(guestAccess, ({ one }) => ({
410
+ shareLink: one(shareLinks, {
411
+ fields: [guestAccess.shareLinkId],
412
+ references: [shareLinks.id]
413
+ })
414
+ }));
415
+ var attachments = pgTable("attachments", {
416
+ id: uuid("id").primaryKey().defaultRandom(),
417
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
418
+ workspaceId: text("workspace_id"),
419
+ filename: text("filename").notNull(),
420
+ mimeType: text("mime_type").notNull(),
421
+ size: bigint("size", { mode: "number" }).notNull(),
422
+ storageKey: text("storage_key").notNull(),
423
+ createdAt: timestamp("created_at").defaultNow().notNull()
424
+ }, (table) => [index("attachments_document_id_idx").on(table.documentId)]);
425
+ var attachmentRelations = relations(attachments, ({ one }) => ({
426
+ document: one(documents, {
427
+ fields: [attachments.documentId],
428
+ references: [documents.id]
429
+ })
430
+ }));
431
+ var versions = pgTable("versions", {
432
+ id: uuid("id").primaryKey().defaultRandom(),
433
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
434
+ workspaceId: text("workspace_id"),
435
+ content: text("content").notNull(),
436
+ contentJson: jsonb("content_json"),
437
+ createdBy: uuid("created_by").notNull().references(() => users.id, { onDelete: "cascade" }),
438
+ createdAt: timestamp("created_at").defaultNow().notNull(),
439
+ label: text("label"),
440
+ description: text("description"),
441
+ isSnapshot: boolean("is_snapshot").default(false),
442
+ restoredFrom: uuid("restored_from")
443
+ }, (table) => [
444
+ index("versions_document_id_idx").on(table.documentId),
445
+ index("versions_created_at_idx").on(table.createdAt),
446
+ index("versions_is_snapshot_idx").on(table.isSnapshot)
447
+ ]);
448
+ var documentEmbeddings = pgTable("document_embeddings", {
449
+ id: uuid("id").primaryKey().defaultRandom(),
450
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
451
+ workspaceId: text("workspace_id"),
452
+ chunkIndex: bigint("chunk_index", { mode: "number" }).notNull(),
453
+ chunkText: text("chunk_text").notNull(),
454
+ chunkHash: text("chunk_hash"),
455
+ charStart: integer("char_start").notNull().default(0),
456
+ charEnd: integer("char_end").notNull().default(0),
457
+ embedding: vector("embedding", { dimensions: 1024 }),
458
+ embeddingModel: text("embedding_model").notNull().default(""),
459
+ generationId: uuid("generation_id").notNull(),
460
+ embeddingDimensions: integer("embedding_dimensions").notNull().default(1024),
461
+ embeddingProfile: text("embedding_profile").notNull().default("legacy"),
462
+ isValid: boolean("is_valid").notNull().default(false),
463
+ createdAt: timestamp("created_at").defaultNow().notNull()
464
+ }, (table) => [
465
+ index("document_embeddings_doc_id_idx").on(table.documentId),
466
+ uniqueIndex("document_embeddings_doc_chunk_idx").on(table.documentId, table.generationId, table.chunkIndex),
467
+ index("document_embeddings_generation_valid_idx").on(table.documentId, table.generationId, table.isValid),
468
+ index("idx_document_embeddings_embedding_model").on(table.embeddingModel),
469
+ index("idx_document_embeddings_hnsw").using("hnsw", sql`${table.embedding} vector_cosine_ops`),
470
+ index("idx_document_embeddings_diskann").using("diskann", sql`${table.embedding} vector_cosine_ops`)
471
+ ]);
472
+ var documentEmbeddingRelations = relations(documentEmbeddings, ({ one }) => ({
473
+ document: one(documents, {
474
+ fields: [documentEmbeddings.documentId],
475
+ references: [documents.id]
476
+ })
477
+ }));
478
+ var apiKeys = pgTable("api_keys", {
479
+ id: uuid("id").primaryKey().defaultRandom(),
480
+ ownerId: uuid("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
481
+ workspaceId: text("workspace_id"),
482
+ name: text("name").notNull(),
483
+ keyHash: text("key_hash").notNull().unique(),
484
+ prefix: text("prefix").notNull(),
485
+ encryptedKey: text("encrypted_key"),
486
+ scopes: jsonb("scopes").notNull().default("[]"),
487
+ lastUsedAt: timestamp("last_used_at"),
488
+ expiresAt: timestamp("expires_at"),
489
+ createdAt: timestamp("created_at").defaultNow().notNull()
490
+ }, (table) => [
491
+ index("idx_api_keys_owner").on(table.ownerId),
492
+ index("idx_api_keys_prefix").on(table.prefix)
493
+ ]);
494
+ var apiKeyRelations = relations(apiKeys, ({ one }) => ({
495
+ owner: one(users, { fields: [apiKeys.ownerId], references: [users.id] })
496
+ }));
497
+ var auditLog = pgTable("audit_log", {
498
+ id: uuid("id").primaryKey().defaultRandom(),
499
+ actorId: uuid("actor_id").notNull(),
500
+ workspaceId: text("workspace_id"),
501
+ action: text("action").notNull(),
502
+ resourceType: text("resource_type").notNull(),
503
+ resourceId: uuid("resource_id"),
504
+ details: jsonb("details").notNull().default("{}"),
505
+ ipAddress: text("ip_address"),
506
+ userAgent: text("user_agent"),
507
+ createdAt: timestamp("created_at").defaultNow().notNull()
508
+ }, (table) => [
509
+ index("idx_audit_log_actor").on(table.actorId),
510
+ index("idx_audit_log_resource").on(table.resourceType, table.resourceId),
511
+ index("idx_audit_log_created").on(table.createdAt)
512
+ ]);
513
+ var lifecycleOperations = pgTable("lifecycle_operations", {
514
+ id: uuid("id").primaryKey().defaultRandom(),
515
+ actorUserId: uuid("actor_user_id").references(() => users.id, { onDelete: "set null" }),
516
+ actorSubjectHash: text("actor_subject_hash").notNull(),
517
+ idempotencyKey: text("idempotency_key").notNull(),
518
+ operationKind: lifecycleOperationKindEnum("operation_kind").notNull(),
519
+ status: lifecycleOperationStatusEnum("status").notNull().default("pending"),
520
+ leaseOwner: text("lease_owner"),
521
+ leaseExpiresAt: timestamp("lease_expires_at"),
522
+ fenceTokenHash: text("fence_token_hash"),
523
+ completedSteps: jsonb("completed_steps").notNull().default("[]"),
524
+ terminalResult: jsonb("terminal_result"),
525
+ safeErrorCode: text("safe_error_code"),
526
+ attemptCount: integer("attempt_count").notNull().default(0),
527
+ createdAt: timestamp("created_at").defaultNow().notNull(),
528
+ updatedAt: timestamp("updated_at").defaultNow().notNull(),
529
+ completedAt: timestamp("completed_at")
530
+ }, (table) => [
531
+ uniqueIndex("lifecycle_operations_actor_idempotency_idx").on(table.actorUserId, table.idempotencyKey),
532
+ index("lifecycle_operations_status_lease_idx").on(table.status, table.leaseExpiresAt),
533
+ index("lifecycle_operations_actor_idx").on(table.actorUserId),
534
+ index("lifecycle_operations_retryable_idx").on(table.status).where(sql`${table.status} = 'retryable'`),
535
+ check("lifecycle_operations_actor_subject_hash", sql`${table.actorSubjectHash} ~ '^[a-f0-9]{64}$'`)
536
+ ]);
537
+ var documentCreateOperations = pgTable("document_create_operations", {
538
+ id: uuid("id").primaryKey().defaultRandom(),
539
+ workspaceId: text("workspace_id").notNull(),
540
+ actorUserId: uuid("actor_user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
541
+ idempotencyKey: text("idempotency_key").notNull(),
542
+ documentId: uuid("document_id").notNull().references(() => documents.id, { onDelete: "cascade" }),
543
+ createdAt: timestamp("created_at").defaultNow().notNull()
544
+ }, (table) => [
545
+ uniqueIndex("document_create_operations_workspace_actor_key_idx").on(table.workspaceId, table.actorUserId, table.idempotencyKey),
546
+ uniqueIndex("document_create_operations_document_idx").on(table.documentId)
547
+ ]);
548
+ var versionRelations = relations(versions, ({ one }) => ({
549
+ document: one(documents, {
550
+ fields: [versions.documentId],
551
+ references: [documents.id]
552
+ }),
553
+ creator: one(users, {
554
+ fields: [versions.createdBy],
555
+ references: [users.id]
556
+ })
557
+ }));
558
+
559
+ // src/pipeline-cancellation.ts
560
+ var REMOVABLE_STATES = ["waiting", "delayed", "paused", "prioritized"];
561
+ async function cancelAccountPipelineJobs(actorUserId, deps, signal) {
562
+ if (signal?.aborted)
563
+ throw signal.reason ?? new DOMException("Aborted", "AbortError");
564
+ let affected = await deps.cancelRuns(actorUserId, signal);
565
+ for (const queue of deps.queues) {
566
+ const jobs = await queue.getJobs([...REMOVABLE_STATES]);
567
+ for (const job of jobs) {
568
+ if (job.data?.ownerId !== actorUserId)
569
+ continue;
570
+ const state = await job.getState();
571
+ if (!REMOVABLE_STATES.includes(state))
572
+ continue;
573
+ try {
574
+ await job.remove();
575
+ affected += 1;
576
+ } catch (error) {
577
+ const message = error instanceof Error ? error.message.toLowerCase() : "";
578
+ if (!message.includes("not found") && !message.includes("locked") && !message.includes("active"))
579
+ throw error;
580
+ }
581
+ }
582
+ }
583
+ return affected;
584
+ }
585
+
586
+ // ../../backend/src/queue/account-pipeline-cancellation.ts
587
+ import { Queue as Queue2 } from "bullmq";
588
+ import { and, eq, inArray, ne, sql as sql2 } from "drizzle-orm";
589
+ import { drizzle } from "drizzle-orm/postgres-js";
590
+
591
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/index.js
592
+ import os from "os";
593
+ import fs from "fs";
594
+
595
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/query.js
596
+ var originCache = new Map;
597
+ var originStackCache = new Map;
598
+ var originError = Symbol("OriginError");
599
+ var CLOSE = {};
600
+
601
+ class Query extends Promise {
602
+ constructor(strings, args, handler, canceller, options = {}) {
603
+ let resolve, reject;
604
+ super((a, b) => {
605
+ resolve = a;
606
+ reject = b;
607
+ });
608
+ this.tagged = Array.isArray(strings.raw);
609
+ this.strings = strings;
610
+ this.args = args;
611
+ this.handler = handler;
612
+ this.canceller = canceller;
613
+ this.options = options;
614
+ this.state = null;
615
+ this.statement = null;
616
+ this.resolve = (x) => (this.active = false, resolve(x));
617
+ this.reject = (x) => (this.active = false, reject(x));
618
+ this.active = false;
619
+ this.cancelled = null;
620
+ this.executed = false;
621
+ this.signature = "";
622
+ this[originError] = this.handler.debug ? new Error : this.tagged && cachedError(this.strings);
623
+ }
624
+ get origin() {
625
+ return (this.handler.debug ? this[originError].stack : this.tagged && originStackCache.has(this.strings) ? originStackCache.get(this.strings) : originStackCache.set(this.strings, this[originError].stack).get(this.strings)) || "";
626
+ }
627
+ static get [Symbol.species]() {
628
+ return Promise;
629
+ }
630
+ cancel() {
631
+ return this.canceller && (this.canceller(this), this.canceller = null);
632
+ }
633
+ simple() {
634
+ this.options.simple = true;
635
+ this.options.prepare = false;
636
+ return this;
637
+ }
638
+ async readable() {
639
+ this.simple();
640
+ this.streaming = true;
641
+ return this;
642
+ }
643
+ async writable() {
644
+ this.simple();
645
+ this.streaming = true;
646
+ return this;
647
+ }
648
+ cursor(rows = 1, fn) {
649
+ this.options.simple = false;
650
+ if (typeof rows === "function") {
651
+ fn = rows;
652
+ rows = 1;
653
+ }
654
+ this.cursorRows = rows;
655
+ if (typeof fn === "function")
656
+ return this.cursorFn = fn, this;
657
+ let prev;
658
+ return {
659
+ [Symbol.asyncIterator]: () => ({
660
+ next: () => {
661
+ if (this.executed && !this.active)
662
+ return { done: true };
663
+ prev && prev();
664
+ const promise = new Promise((resolve, reject) => {
665
+ this.cursorFn = (value) => {
666
+ resolve({ value, done: false });
667
+ return new Promise((r) => prev = r);
668
+ };
669
+ this.resolve = () => (this.active = false, resolve({ done: true }));
670
+ this.reject = (x) => (this.active = false, reject(x));
671
+ });
672
+ this.execute();
673
+ return promise;
674
+ },
675
+ return() {
676
+ prev && prev(CLOSE);
677
+ return { done: true };
678
+ }
679
+ })
680
+ };
681
+ }
682
+ describe() {
683
+ this.options.simple = false;
684
+ this.onlyDescribe = this.options.prepare = true;
685
+ return this;
686
+ }
687
+ stream() {
688
+ throw new Error(".stream has been renamed to .forEach");
689
+ }
690
+ forEach(fn) {
691
+ this.forEachFn = fn;
692
+ this.handle();
693
+ return this;
694
+ }
695
+ raw() {
696
+ this.isRaw = true;
697
+ return this;
698
+ }
699
+ values() {
700
+ this.isRaw = "values";
701
+ return this;
702
+ }
703
+ async handle() {
704
+ !this.executed && (this.executed = true) && await 1 && this.handler(this);
705
+ }
706
+ execute() {
707
+ this.handle();
708
+ return this;
709
+ }
710
+ then() {
711
+ this.handle();
712
+ return super.then.apply(this, arguments);
713
+ }
714
+ catch() {
715
+ this.handle();
716
+ return super.catch.apply(this, arguments);
717
+ }
718
+ finally() {
719
+ this.handle();
720
+ return super.finally.apply(this, arguments);
721
+ }
722
+ }
723
+ function cachedError(xs) {
724
+ if (originCache.has(xs))
725
+ return originCache.get(xs);
726
+ const x = Error.stackTraceLimit;
727
+ Error.stackTraceLimit = 4;
728
+ originCache.set(xs, new Error);
729
+ Error.stackTraceLimit = x;
730
+ return originCache.get(xs);
731
+ }
732
+
733
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/errors.js
734
+ class PostgresError extends Error {
735
+ constructor(x) {
736
+ super(x.message);
737
+ this.name = this.constructor.name;
738
+ Object.assign(this, x);
739
+ }
740
+ }
741
+ var Errors = {
742
+ connection,
743
+ postgres,
744
+ generic,
745
+ notSupported
746
+ };
747
+ function connection(x, options, socket) {
748
+ const { host, port } = socket || options;
749
+ const error = Object.assign(new Error("write " + x + " " + (options.path || host + ":" + port)), {
750
+ code: x,
751
+ errno: x,
752
+ address: options.path || host
753
+ }, options.path ? {} : { port });
754
+ Error.captureStackTrace(error, connection);
755
+ return error;
756
+ }
757
+ function postgres(x) {
758
+ const error = new PostgresError(x);
759
+ Error.captureStackTrace(error, postgres);
760
+ return error;
761
+ }
762
+ function generic(code, message) {
763
+ const error = Object.assign(new Error(code + ": " + message), { code });
764
+ Error.captureStackTrace(error, generic);
765
+ return error;
766
+ }
767
+ function notSupported(x) {
768
+ const error = Object.assign(new Error(x + " (B) is not supported"), {
769
+ code: "MESSAGE_NOT_SUPPORTED",
770
+ name: x
771
+ });
772
+ Error.captureStackTrace(error, notSupported);
773
+ return error;
774
+ }
775
+
776
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/types.js
777
+ var types = {
778
+ string: {
779
+ to: 25,
780
+ from: null,
781
+ serialize: (x) => "" + x
782
+ },
783
+ number: {
784
+ to: 0,
785
+ from: [21, 23, 26, 700, 701],
786
+ serialize: (x) => "" + x,
787
+ parse: (x) => +x
788
+ },
789
+ json: {
790
+ to: 114,
791
+ from: [114, 3802],
792
+ serialize: (x) => JSON.stringify(x),
793
+ parse: (x) => JSON.parse(x)
794
+ },
795
+ boolean: {
796
+ to: 16,
797
+ from: 16,
798
+ serialize: (x) => x === true ? "t" : "f",
799
+ parse: (x) => x === "t"
800
+ },
801
+ date: {
802
+ to: 1184,
803
+ from: [1082, 1114, 1184],
804
+ serialize: (x) => (x instanceof Date ? x : new Date(x)).toISOString(),
805
+ parse: (x) => new Date(x)
806
+ },
807
+ bytea: {
808
+ to: 17,
809
+ from: 17,
810
+ serialize: (x) => "\\x" + Buffer.from(x).toString("hex"),
811
+ parse: (x) => Buffer.from(x.slice(2), "hex")
812
+ }
813
+ };
814
+
815
+ class NotTagged {
816
+ then() {
817
+ notTagged();
818
+ }
819
+ catch() {
820
+ notTagged();
821
+ }
822
+ finally() {
823
+ notTagged();
824
+ }
825
+ }
826
+
827
+ class Identifier extends NotTagged {
828
+ constructor(value) {
829
+ super();
830
+ this.value = escapeIdentifier(value);
831
+ }
832
+ }
833
+
834
+ class Parameter extends NotTagged {
835
+ constructor(value, type, array) {
836
+ super();
837
+ this.value = value;
838
+ this.type = type;
839
+ this.array = array;
840
+ }
841
+ }
842
+
843
+ class Builder extends NotTagged {
844
+ constructor(first, rest) {
845
+ super();
846
+ this.first = first;
847
+ this.rest = rest;
848
+ }
849
+ build(before, parameters, types2, options) {
850
+ const keyword = builders.map(([x, fn]) => ({ fn, i: before.search(x) })).sort((a, b) => a.i - b.i).pop();
851
+ return keyword.i === -1 ? escapeIdentifiers(this.first, options) : keyword.fn(this.first, this.rest, parameters, types2, options);
852
+ }
853
+ }
854
+ function handleValue(x, parameters, types2, options) {
855
+ let value = x instanceof Parameter ? x.value : x;
856
+ if (value === undefined) {
857
+ x instanceof Parameter ? x.value = options.transform.undefined : value = x = options.transform.undefined;
858
+ if (value === undefined)
859
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
860
+ }
861
+ return "$" + types2.push(x instanceof Parameter ? (parameters.push(x.value), x.array ? x.array[x.type || inferType(x.value)] || x.type || firstIsString(x.value) : x.type) : (parameters.push(x), inferType(x)));
862
+ }
863
+ var defaultHandlers = typeHandlers(types);
864
+ function stringify(q, string, value, parameters, types2, options) {
865
+ for (let i = 1;i < q.strings.length; i++) {
866
+ string += stringifyValue(string, value, parameters, types2, options) + q.strings[i];
867
+ value = q.args[i];
868
+ }
869
+ return string;
870
+ }
871
+ function stringifyValue(string, value, parameters, types2, o) {
872
+ return value instanceof Builder ? value.build(string, parameters, types2, o) : value instanceof Query ? fragment(value, parameters, types2, o) : value instanceof Identifier ? value.value : value && value[0] instanceof Query ? value.reduce((acc, x) => acc + " " + fragment(x, parameters, types2, o), "") : handleValue(value, parameters, types2, o);
873
+ }
874
+ function fragment(q, parameters, types2, options) {
875
+ q.fragment = true;
876
+ return stringify(q, q.strings[0], q.args[0], parameters, types2, options);
877
+ }
878
+ function valuesBuilder(first, parameters, types2, columns, options) {
879
+ return first.map((row) => "(" + columns.map((column) => stringifyValue("values", row[column], parameters, types2, options)).join(",") + ")").join(",");
880
+ }
881
+ function values(first, rest, parameters, types2, options) {
882
+ const multi = Array.isArray(first[0]);
883
+ const columns = rest.length ? rest.flat() : Object.keys(multi ? first[0] : first);
884
+ return valuesBuilder(multi ? first : [first], parameters, types2, columns, options);
885
+ }
886
+ function select(first, rest, parameters, types2, options) {
887
+ typeof first === "string" && (first = [first].concat(rest));
888
+ if (Array.isArray(first))
889
+ return escapeIdentifiers(first, options);
890
+ let value;
891
+ const columns = rest.length ? rest.flat() : Object.keys(first);
892
+ return columns.map((x) => {
893
+ value = first[x];
894
+ return (value instanceof Query ? fragment(value, parameters, types2, options) : value instanceof Identifier ? value.value : handleValue(value, parameters, types2, options)) + " as " + escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x);
895
+ }).join(",");
896
+ }
897
+ var builders = Object.entries({
898
+ values,
899
+ in: (...xs) => {
900
+ const x = values(...xs);
901
+ return x === "()" ? "(null)" : x;
902
+ },
903
+ select,
904
+ as: select,
905
+ returning: select,
906
+ "\\(": select,
907
+ update(first, rest, parameters, types2, options) {
908
+ return (rest.length ? rest.flat() : Object.keys(first)).map((x) => escapeIdentifier(options.transform.column.to ? options.transform.column.to(x) : x) + "=" + stringifyValue("values", first[x], parameters, types2, options));
909
+ },
910
+ insert(first, rest, parameters, types2, options) {
911
+ const columns = rest.length ? rest.flat() : Object.keys(Array.isArray(first) ? first[0] : first);
912
+ return "(" + escapeIdentifiers(columns, options) + ")values" + valuesBuilder(Array.isArray(first) ? first : [first], parameters, types2, columns, options);
913
+ }
914
+ }).map(([x, fn]) => [new RegExp("((?:^|[\\s(])" + x + "(?:$|[\\s(]))(?![\\s\\S]*\\1)", "i"), fn]);
915
+ function notTagged() {
916
+ throw Errors.generic("NOT_TAGGED_CALL", "Query not called as a tagged template literal");
917
+ }
918
+ var serializers = defaultHandlers.serializers;
919
+ var parsers = defaultHandlers.parsers;
920
+ function firstIsString(x) {
921
+ if (Array.isArray(x))
922
+ return firstIsString(x[0]);
923
+ return typeof x === "string" ? 1009 : 0;
924
+ }
925
+ var mergeUserTypes = function(types2) {
926
+ const user = typeHandlers(types2 || {});
927
+ return {
928
+ serializers: Object.assign({}, serializers, user.serializers),
929
+ parsers: Object.assign({}, parsers, user.parsers)
930
+ };
931
+ };
932
+ function typeHandlers(types2) {
933
+ return Object.keys(types2).reduce((acc, k) => {
934
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.parsers[x] = types2[k].parse);
935
+ if (types2[k].serialize) {
936
+ acc.serializers[types2[k].to] = types2[k].serialize;
937
+ types2[k].from && [].concat(types2[k].from).forEach((x) => acc.serializers[x] = types2[k].serialize);
938
+ }
939
+ return acc;
940
+ }, { parsers: {}, serializers: {} });
941
+ }
942
+ function escapeIdentifiers(xs, { transform: { column } }) {
943
+ return xs.map((x) => escapeIdentifier(column.to ? column.to(x) : x)).join(",");
944
+ }
945
+ var escapeIdentifier = function escape(str) {
946
+ return '"' + str.replace(/"/g, '""').replace(/\./g, '"."') + '"';
947
+ };
948
+ var inferType = function inferType2(x) {
949
+ return x instanceof Parameter ? x.type : x instanceof Date ? 1184 : x instanceof Uint8Array ? 17 : x === true || x === false ? 16 : typeof x === "bigint" ? 20 : Array.isArray(x) ? inferType2(x[0]) : 0;
950
+ };
951
+ var escapeBackslash = /\\/g;
952
+ var escapeQuote = /"/g;
953
+ function arrayEscape(x) {
954
+ return x.replace(escapeBackslash, "\\\\").replace(escapeQuote, "\\\"");
955
+ }
956
+ var arraySerializer = function arraySerializer2(xs, serializer, options, typarray) {
957
+ if (Array.isArray(xs) === false)
958
+ return xs;
959
+ if (!xs.length)
960
+ return "{}";
961
+ const first = xs[0];
962
+ const delimiter = typarray === 1020 ? ";" : ",";
963
+ if (Array.isArray(first) && !first.type)
964
+ return "{" + xs.map((x) => arraySerializer2(x, serializer, options, typarray)).join(delimiter) + "}";
965
+ return "{" + xs.map((x) => {
966
+ if (x === undefined) {
967
+ x = options.transform.undefined;
968
+ if (x === undefined)
969
+ throw Errors.generic("UNDEFINED_VALUE", "Undefined values are not allowed");
970
+ }
971
+ return x === null ? "null" : '"' + arrayEscape(serializer ? serializer(x.type ? x.value : x) : "" + x) + '"';
972
+ }).join(delimiter) + "}";
973
+ };
974
+ var arrayParserState = {
975
+ i: 0,
976
+ char: null,
977
+ str: "",
978
+ quoted: false,
979
+ last: 0
980
+ };
981
+ var arrayParser = function arrayParser2(x, parser, typarray) {
982
+ arrayParserState.i = arrayParserState.last = 0;
983
+ return arrayParserLoop(arrayParserState, x, parser, typarray);
984
+ };
985
+ function arrayParserLoop(s, x, parser, typarray) {
986
+ const xs = [];
987
+ const delimiter = typarray === 1020 ? ";" : ",";
988
+ for (;s.i < x.length; s.i++) {
989
+ s.char = x[s.i];
990
+ if (s.quoted) {
991
+ if (s.char === "\\") {
992
+ s.str += x[++s.i];
993
+ } else if (s.char === '"') {
994
+ xs.push(parser ? parser(s.str) : s.str);
995
+ s.str = "";
996
+ s.quoted = x[s.i + 1] === '"';
997
+ s.last = s.i + 2;
998
+ } else {
999
+ s.str += s.char;
1000
+ }
1001
+ } else if (s.char === '"') {
1002
+ s.quoted = true;
1003
+ } else if (s.char === "{") {
1004
+ s.last = ++s.i;
1005
+ xs.push(arrayParserLoop(s, x, parser, typarray));
1006
+ } else if (s.char === "}") {
1007
+ s.quoted = false;
1008
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
1009
+ s.last = s.i + 1;
1010
+ break;
1011
+ } else if (s.char === delimiter && s.p !== "}" && s.p !== '"') {
1012
+ xs.push(parser ? parser(x.slice(s.last, s.i)) : x.slice(s.last, s.i));
1013
+ s.last = s.i + 1;
1014
+ }
1015
+ s.p = s.char;
1016
+ }
1017
+ s.last < s.i && xs.push(parser ? parser(x.slice(s.last, s.i + 1)) : x.slice(s.last, s.i + 1));
1018
+ return xs;
1019
+ }
1020
+ var toCamel = (x) => {
1021
+ let str = x[0];
1022
+ for (let i = 1;i < x.length; i++)
1023
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
1024
+ return str;
1025
+ };
1026
+ var toPascal = (x) => {
1027
+ let str = x[0].toUpperCase();
1028
+ for (let i = 1;i < x.length; i++)
1029
+ str += x[i] === "_" ? x[++i].toUpperCase() : x[i];
1030
+ return str;
1031
+ };
1032
+ var toKebab = (x) => x.replace(/_/g, "-");
1033
+ var fromCamel = (x) => x.replace(/([A-Z])/g, "_$1").toLowerCase();
1034
+ var fromPascal = (x) => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, "_$1")).toLowerCase();
1035
+ var fromKebab = (x) => x.replace(/-/g, "_");
1036
+ function createJsonTransform(fn) {
1037
+ return function jsonTransform(x, column) {
1038
+ return typeof x === "object" && x !== null && (column.type === 114 || column.type === 3802) ? Array.isArray(x) ? x.map((x2) => jsonTransform(x2, column)) : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) : x;
1039
+ };
1040
+ }
1041
+ toCamel.column = { from: toCamel };
1042
+ toCamel.value = { from: createJsonTransform(toCamel) };
1043
+ fromCamel.column = { to: fromCamel };
1044
+ var camel = { ...toCamel };
1045
+ camel.column.to = fromCamel;
1046
+ toPascal.column = { from: toPascal };
1047
+ toPascal.value = { from: createJsonTransform(toPascal) };
1048
+ fromPascal.column = { to: fromPascal };
1049
+ var pascal = { ...toPascal };
1050
+ pascal.column.to = fromPascal;
1051
+ toKebab.column = { from: toKebab };
1052
+ toKebab.value = { from: createJsonTransform(toKebab) };
1053
+ fromKebab.column = { to: fromKebab };
1054
+ var kebab = { ...toKebab };
1055
+ kebab.column.to = fromKebab;
1056
+
1057
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/connection.js
1058
+ import net from "net";
1059
+ import tls from "tls";
1060
+ import crypto from "crypto";
1061
+ import Stream from "stream";
1062
+ import { performance } from "perf_hooks";
1063
+
1064
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/result.js
1065
+ class Result extends Array {
1066
+ constructor() {
1067
+ super();
1068
+ Object.defineProperties(this, {
1069
+ count: { value: null, writable: true },
1070
+ state: { value: null, writable: true },
1071
+ command: { value: null, writable: true },
1072
+ columns: { value: null, writable: true },
1073
+ statement: { value: null, writable: true }
1074
+ });
1075
+ }
1076
+ static get [Symbol.species]() {
1077
+ return Array;
1078
+ }
1079
+ }
1080
+
1081
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/queue.js
1082
+ var queue_default = Queue;
1083
+ function Queue(initial = []) {
1084
+ let xs = initial.slice();
1085
+ let index2 = 0;
1086
+ return {
1087
+ get length() {
1088
+ return xs.length - index2;
1089
+ },
1090
+ remove: (x) => {
1091
+ const index3 = xs.indexOf(x);
1092
+ return index3 === -1 ? null : (xs.splice(index3, 1), x);
1093
+ },
1094
+ push: (x) => (xs.push(x), x),
1095
+ shift: () => {
1096
+ const out = xs[index2++];
1097
+ if (index2 === xs.length) {
1098
+ index2 = 0;
1099
+ xs = [];
1100
+ } else {
1101
+ xs[index2 - 1] = undefined;
1102
+ }
1103
+ return out;
1104
+ }
1105
+ };
1106
+ }
1107
+
1108
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/bytes.js
1109
+ var size = 256;
1110
+ var buffer = Buffer.allocUnsafe(size);
1111
+ var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
1112
+ const v = x.charCodeAt(0);
1113
+ acc[x] = () => {
1114
+ buffer[0] = v;
1115
+ b.i = 5;
1116
+ return b;
1117
+ };
1118
+ return acc;
1119
+ }, {});
1120
+ var b = Object.assign(reset, messages, {
1121
+ N: String.fromCharCode(0),
1122
+ i: 0,
1123
+ inc(x) {
1124
+ b.i += x;
1125
+ return b;
1126
+ },
1127
+ str(x) {
1128
+ const length = Buffer.byteLength(x);
1129
+ fit(length);
1130
+ b.i += buffer.write(x, b.i, length, "utf8");
1131
+ return b;
1132
+ },
1133
+ i16(x) {
1134
+ fit(2);
1135
+ buffer.writeUInt16BE(x, b.i);
1136
+ b.i += 2;
1137
+ return b;
1138
+ },
1139
+ i32(x, i) {
1140
+ if (i || i === 0) {
1141
+ buffer.writeUInt32BE(x, i);
1142
+ return b;
1143
+ }
1144
+ fit(4);
1145
+ buffer.writeUInt32BE(x, b.i);
1146
+ b.i += 4;
1147
+ return b;
1148
+ },
1149
+ z(x) {
1150
+ fit(x);
1151
+ buffer.fill(0, b.i, b.i + x);
1152
+ b.i += x;
1153
+ return b;
1154
+ },
1155
+ raw(x) {
1156
+ buffer = Buffer.concat([buffer.subarray(0, b.i), x]);
1157
+ b.i = buffer.length;
1158
+ return b;
1159
+ },
1160
+ end(at = 1) {
1161
+ buffer.writeUInt32BE(b.i - at, at);
1162
+ const out = buffer.subarray(0, b.i);
1163
+ b.i = 0;
1164
+ buffer = Buffer.allocUnsafe(size);
1165
+ return out;
1166
+ }
1167
+ });
1168
+ var bytes_default = b;
1169
+ function fit(x) {
1170
+ if (buffer.length - b.i < x) {
1171
+ const prev = buffer, length = prev.length;
1172
+ buffer = Buffer.allocUnsafe(length + (length >> 1) + x);
1173
+ prev.copy(buffer);
1174
+ }
1175
+ }
1176
+ function reset() {
1177
+ b.i = 0;
1178
+ return b;
1179
+ }
1180
+
1181
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/connection.js
1182
+ var connection_default = Connection;
1183
+ var uid = 1;
1184
+ var Sync = bytes_default().S().end();
1185
+ var Flush = bytes_default().H().end();
1186
+ var SSLRequest = bytes_default().i32(8).i32(80877103).end(8);
1187
+ var ExecuteUnnamed = Buffer.concat([bytes_default().E().str(bytes_default.N).i32(0).end(), Sync]);
1188
+ var DescribeUnnamed = bytes_default().D().str("S").str(bytes_default.N).end();
1189
+ var noop = () => {};
1190
+ var retryRoutines = new Set([
1191
+ "FetchPreparedStatement",
1192
+ "RevalidateCachedQuery",
1193
+ "transformAssignedExpr"
1194
+ ]);
1195
+ var errorFields = {
1196
+ 83: "severity_local",
1197
+ 86: "severity",
1198
+ 67: "code",
1199
+ 77: "message",
1200
+ 68: "detail",
1201
+ 72: "hint",
1202
+ 80: "position",
1203
+ 112: "internal_position",
1204
+ 113: "internal_query",
1205
+ 87: "where",
1206
+ 115: "schema_name",
1207
+ 116: "table_name",
1208
+ 99: "column_name",
1209
+ 100: "data type_name",
1210
+ 110: "constraint_name",
1211
+ 70: "file",
1212
+ 76: "line",
1213
+ 82: "routine"
1214
+ };
1215
+ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
1216
+ const {
1217
+ sslnegotiation,
1218
+ ssl,
1219
+ max,
1220
+ user,
1221
+ host,
1222
+ port,
1223
+ database,
1224
+ parsers: parsers2,
1225
+ transform,
1226
+ onnotice,
1227
+ onnotify,
1228
+ onparameter,
1229
+ max_pipeline,
1230
+ keep_alive,
1231
+ backoff,
1232
+ target_session_attrs
1233
+ } = options;
1234
+ const sent = queue_default(), id = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
1235
+ let socket = null, cancelMessage, errorResponse = null, result = new Result, incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
1236
+ const connection2 = {
1237
+ queue: queues.closed,
1238
+ idleTimer,
1239
+ connect(query2) {
1240
+ initial = query2;
1241
+ reconnect();
1242
+ },
1243
+ terminate,
1244
+ execute,
1245
+ cancel,
1246
+ end,
1247
+ count: 0,
1248
+ id
1249
+ };
1250
+ queues.closed && queues.closed.push(connection2);
1251
+ return connection2;
1252
+ async function createSocket() {
1253
+ let x;
1254
+ try {
1255
+ x = options.socket ? await Promise.resolve(options.socket(options)) : new net.Socket;
1256
+ } catch (e) {
1257
+ error(e);
1258
+ return;
1259
+ }
1260
+ x.on("error", error);
1261
+ x.on("close", closed);
1262
+ x.on("drain", drain);
1263
+ return x;
1264
+ }
1265
+ async function cancel({ pid, secret }, resolve, reject) {
1266
+ try {
1267
+ cancelMessage = bytes_default().i32(16).i32(80877102).i32(pid).i32(secret).end(16);
1268
+ await connect();
1269
+ socket.once("error", reject);
1270
+ socket.once("close", resolve);
1271
+ } catch (error2) {
1272
+ reject(error2);
1273
+ }
1274
+ }
1275
+ function execute(q) {
1276
+ if (terminated)
1277
+ return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
1278
+ if (stream)
1279
+ return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
1280
+ if (q.cancelled)
1281
+ return;
1282
+ try {
1283
+ q.state = backend;
1284
+ query ? sent.push(q) : (query = q, query.active = true);
1285
+ build(q);
1286
+ return write(toBuffer(q)) && !q.describeFirst && !q.cursorFn && sent.length < max_pipeline && (!q.options.onexecute || q.options.onexecute(connection2));
1287
+ } catch (error2) {
1288
+ sent.length === 0 && write(Sync);
1289
+ errored(error2);
1290
+ return true;
1291
+ }
1292
+ }
1293
+ function toBuffer(q) {
1294
+ if (q.parameters.length >= 65534)
1295
+ throw Errors.generic("MAX_PARAMETERS_EXCEEDED", "Max number of parameters (65534) exceeded");
1296
+ return q.options.simple ? bytes_default().Q().str(q.statement.string + bytes_default.N).end() : q.describeFirst ? Buffer.concat([describe(q), Flush]) : q.prepare ? q.prepared ? prepared(q) : Buffer.concat([describe(q), prepared(q)]) : unnamed(q);
1297
+ }
1298
+ function describe(q) {
1299
+ return Buffer.concat([
1300
+ Parse(q.statement.string, q.parameters, q.statement.types, q.statement.name),
1301
+ Describe("S", q.statement.name)
1302
+ ]);
1303
+ }
1304
+ function prepared(q) {
1305
+ return Buffer.concat([
1306
+ Bind(q.parameters, q.statement.types, q.statement.name, q.cursorName),
1307
+ q.cursorFn ? Execute("", q.cursorRows) : ExecuteUnnamed
1308
+ ]);
1309
+ }
1310
+ function unnamed(q) {
1311
+ return Buffer.concat([
1312
+ Parse(q.statement.string, q.parameters, q.statement.types),
1313
+ DescribeUnnamed,
1314
+ prepared(q)
1315
+ ]);
1316
+ }
1317
+ function build(q) {
1318
+ const parameters = [], types2 = [];
1319
+ const string = stringify(q, q.strings[0], q.args[0], parameters, types2, options);
1320
+ !q.tagged && q.args.forEach((x) => handleValue(x, parameters, types2, options));
1321
+ q.prepare = options.prepare && ("prepare" in q.options ? q.options.prepare : true);
1322
+ q.string = string;
1323
+ q.signature = q.prepare && types2 + string;
1324
+ q.onlyDescribe && delete statements[q.signature];
1325
+ q.parameters = q.parameters || parameters;
1326
+ q.prepared = q.prepare && q.signature in statements;
1327
+ q.describeFirst = q.onlyDescribe || parameters.length && !q.prepared;
1328
+ q.statement = q.prepared ? statements[q.signature] : { string, types: types2, name: q.prepare ? statementId + statementCount++ : "" };
1329
+ typeof options.debug === "function" && options.debug(id, string, parameters, types2);
1330
+ }
1331
+ function write(x, fn) {
1332
+ chunk = chunk ? Buffer.concat([chunk, x]) : Buffer.from(x);
1333
+ if (fn || chunk.length >= 1024)
1334
+ return nextWrite(fn);
1335
+ nextWriteTimer === null && (nextWriteTimer = setImmediate(nextWrite));
1336
+ return true;
1337
+ }
1338
+ function nextWrite(fn) {
1339
+ const x = socket.write(chunk, fn);
1340
+ nextWriteTimer !== null && clearImmediate(nextWriteTimer);
1341
+ chunk = nextWriteTimer = null;
1342
+ return x;
1343
+ }
1344
+ function connectTimedOut() {
1345
+ errored(Errors.connection("CONNECT_TIMEOUT", options, socket));
1346
+ socket.destroy();
1347
+ }
1348
+ async function secure() {
1349
+ if (sslnegotiation !== "direct") {
1350
+ write(SSLRequest);
1351
+ const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
1352
+ if (!canSSL && ssl === "prefer")
1353
+ return connected();
1354
+ }
1355
+ const options2 = {
1356
+ socket,
1357
+ servername: net.isIP(socket.host) ? undefined : socket.host
1358
+ };
1359
+ if (sslnegotiation === "direct")
1360
+ options2.ALPNProtocols = ["postgresql"];
1361
+ if (ssl === "require" || ssl === "allow" || ssl === "prefer")
1362
+ options2.rejectUnauthorized = false;
1363
+ else if (typeof ssl === "object")
1364
+ Object.assign(options2, ssl);
1365
+ socket.removeAllListeners();
1366
+ socket = tls.connect(options2);
1367
+ socket.on("secureConnect", connected);
1368
+ socket.on("error", error);
1369
+ socket.on("close", closed);
1370
+ socket.on("drain", drain);
1371
+ }
1372
+ function drain() {
1373
+ !query && onopen(connection2);
1374
+ }
1375
+ function data(x) {
1376
+ if (incomings) {
1377
+ incomings.push(x);
1378
+ remaining -= x.length;
1379
+ if (remaining > 0)
1380
+ return;
1381
+ }
1382
+ incoming = incomings ? Buffer.concat(incomings, length - remaining) : incoming.length === 0 ? x : Buffer.concat([incoming, x], incoming.length + x.length);
1383
+ while (incoming.length > 4) {
1384
+ length = incoming.readUInt32BE(1);
1385
+ if (length >= incoming.length) {
1386
+ remaining = length - incoming.length;
1387
+ incomings = [incoming];
1388
+ break;
1389
+ }
1390
+ try {
1391
+ handle(incoming.subarray(0, length + 1));
1392
+ } catch (e) {
1393
+ query && (query.cursorFn || query.describeFirst) && write(Sync);
1394
+ errored(e);
1395
+ }
1396
+ incoming = incoming.subarray(length + 1);
1397
+ remaining = 0;
1398
+ incomings = null;
1399
+ }
1400
+ }
1401
+ async function connect() {
1402
+ terminated = false;
1403
+ backendParameters = {};
1404
+ socket || (socket = await createSocket());
1405
+ if (!socket)
1406
+ return;
1407
+ connectTimer.start();
1408
+ if (options.socket)
1409
+ return ssl ? secure() : connected();
1410
+ socket.on("connect", ssl ? secure : connected);
1411
+ if (options.path)
1412
+ return socket.connect(options.path);
1413
+ socket.ssl = ssl;
1414
+ socket.connect(port[hostIndex], host[hostIndex]);
1415
+ socket.host = host[hostIndex];
1416
+ socket.port = port[hostIndex];
1417
+ hostIndex = (hostIndex + 1) % port.length;
1418
+ }
1419
+ function reconnect() {
1420
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
1421
+ }
1422
+ function connected() {
1423
+ try {
1424
+ statements = {};
1425
+ needsTypes = options.fetch_types;
1426
+ statementId = Math.random().toString(36).slice(2);
1427
+ statementCount = 1;
1428
+ lifeTimer.start();
1429
+ socket.on("data", data);
1430
+ keep_alive && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * keep_alive);
1431
+ const s = StartupMessage();
1432
+ write(s);
1433
+ } catch (err) {
1434
+ error(err);
1435
+ }
1436
+ }
1437
+ function error(err) {
1438
+ if (connection2.queue === queues.connecting && options.host[retries + 1])
1439
+ return;
1440
+ errored(err);
1441
+ while (sent.length)
1442
+ queryError(sent.shift(), err);
1443
+ }
1444
+ function errored(err) {
1445
+ stream && (stream.destroy(err), stream = null);
1446
+ query && queryError(query, err);
1447
+ initial && (queryError(initial, err), initial = null);
1448
+ }
1449
+ function queryError(query2, err) {
1450
+ if (query2.reserve)
1451
+ return query2.reject(err);
1452
+ if (!err || typeof err !== "object")
1453
+ err = new Error(err);
1454
+ "query" in err || "parameters" in err || Object.defineProperties(err, {
1455
+ stack: { value: err.stack + query2.origin.replace(/.*\n/, `
1456
+ `), enumerable: options.debug },
1457
+ query: { value: query2.string, enumerable: options.debug },
1458
+ parameters: { value: query2.parameters, enumerable: options.debug },
1459
+ args: { value: query2.args, enumerable: options.debug },
1460
+ types: { value: query2.statement && query2.statement.types, enumerable: options.debug }
1461
+ });
1462
+ query2.reject(err);
1463
+ }
1464
+ function end() {
1465
+ return ending || (!connection2.reserved && onend(connection2), !connection2.reserved && !initial && !query && sent.length === 0 ? (terminate(), new Promise((r) => socket && socket.readyState !== "closed" ? socket.once("close", r) : r())) : ending = new Promise((r) => ended = r));
1466
+ }
1467
+ function terminate() {
1468
+ terminated = true;
1469
+ if (stream || query || initial || sent.length)
1470
+ error(Errors.connection("CONNECTION_DESTROYED", options));
1471
+ clearImmediate(nextWriteTimer);
1472
+ if (socket) {
1473
+ socket.removeListener("data", data);
1474
+ socket.removeListener("connect", connected);
1475
+ socket.readyState === "open" && socket.end(bytes_default().X().end());
1476
+ }
1477
+ ended && (ended(), ending = ended = null);
1478
+ }
1479
+ async function closed(hadError) {
1480
+ incoming = Buffer.alloc(0);
1481
+ remaining = 0;
1482
+ incomings = null;
1483
+ clearImmediate(nextWriteTimer);
1484
+ socket.removeListener("data", data);
1485
+ socket.removeListener("connect", connected);
1486
+ idleTimer.cancel();
1487
+ lifeTimer.cancel();
1488
+ connectTimer.cancel();
1489
+ socket.removeAllListeners();
1490
+ socket = null;
1491
+ if (initial)
1492
+ return reconnect();
1493
+ !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
1494
+ closedTime = performance.now();
1495
+ hadError && options.shared.retries++;
1496
+ delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1000;
1497
+ onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
1498
+ }
1499
+ function handle(xs, x = xs[0]) {
1500
+ (x === 68 ? DataRow : x === 100 ? CopyData : x === 65 ? NotificationResponse : x === 83 ? ParameterStatus : x === 90 ? ReadyForQuery : x === 67 ? CommandComplete : x === 50 ? BindComplete : x === 49 ? ParseComplete : x === 116 ? ParameterDescription : x === 84 ? RowDescription : x === 82 ? Authentication : x === 110 ? NoData : x === 75 ? BackendKeyData : x === 69 ? ErrorResponse : x === 115 ? PortalSuspended : x === 51 ? CloseComplete : x === 71 ? CopyInResponse : x === 78 ? NoticeResponse : x === 72 ? CopyOutResponse : x === 99 ? CopyDone : x === 73 ? EmptyQueryResponse : x === 86 ? FunctionCallResponse : x === 118 ? NegotiateProtocolVersion : x === 87 ? CopyBothResponse : UnknownMessage)(xs);
1501
+ }
1502
+ function DataRow(x) {
1503
+ let index2 = 7;
1504
+ let length2;
1505
+ let column;
1506
+ let value;
1507
+ const row = query.isRaw ? new Array(query.statement.columns.length) : {};
1508
+ for (let i = 0;i < query.statement.columns.length; i++) {
1509
+ column = query.statement.columns[i];
1510
+ length2 = x.readInt32BE(index2);
1511
+ index2 += 4;
1512
+ value = length2 === -1 ? null : query.isRaw === true ? x.subarray(index2, index2 += length2) : column.parser === undefined ? x.toString("utf8", index2, index2 += length2) : column.parser.array === true ? column.parser(x.toString("utf8", index2 + 1, index2 += length2)) : column.parser(x.toString("utf8", index2, index2 += length2));
1513
+ query.isRaw ? row[i] = query.isRaw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
1514
+ }
1515
+ query.forEachFn ? query.forEachFn(transform.row.from ? transform.row.from(row) : row, result) : result[rows++] = transform.row.from ? transform.row.from(row) : row;
1516
+ }
1517
+ function ParameterStatus(x) {
1518
+ const [k, v] = x.toString("utf8", 5, x.length - 1).split(bytes_default.N);
1519
+ backendParameters[k] = v;
1520
+ if (options.parameters[k] !== v) {
1521
+ options.parameters[k] = v;
1522
+ onparameter && onparameter(k, v);
1523
+ }
1524
+ }
1525
+ function ReadyForQuery(x) {
1526
+ if (query) {
1527
+ if (errorResponse) {
1528
+ query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
1529
+ } else {
1530
+ query.resolve(results || result);
1531
+ }
1532
+ } else if (errorResponse) {
1533
+ errored(errorResponse);
1534
+ }
1535
+ query = results = errorResponse = null;
1536
+ result = new Result;
1537
+ connectTimer.cancel();
1538
+ if (initial) {
1539
+ if (target_session_attrs) {
1540
+ if (!backendParameters.in_hot_standby || !backendParameters.default_transaction_read_only)
1541
+ return fetchState();
1542
+ else if (tryNext(target_session_attrs, backendParameters))
1543
+ return terminate();
1544
+ }
1545
+ if (needsTypes) {
1546
+ initial.reserve && (initial = null);
1547
+ return fetchArrayTypes();
1548
+ }
1549
+ initial && !initial.reserve && execute(initial);
1550
+ options.shared.retries = retries = 0;
1551
+ initial = null;
1552
+ return;
1553
+ }
1554
+ while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
1555
+ Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject);
1556
+ if (query)
1557
+ return;
1558
+ connection2.reserved ? !connection2.reserved.release && x[5] === 73 ? ending ? terminate() : (connection2.reserved = null, onopen(connection2)) : connection2.reserved() : ending ? terminate() : onopen(connection2);
1559
+ }
1560
+ function CommandComplete(x) {
1561
+ rows = 0;
1562
+ for (let i = x.length - 1;i > 0; i--) {
1563
+ if (x[i] === 32 && x[i + 1] < 58 && result.count === null)
1564
+ result.count = +x.toString("utf8", i + 1, x.length - 1);
1565
+ if (x[i - 1] >= 65) {
1566
+ result.command = x.toString("utf8", 5, i);
1567
+ result.state = backend;
1568
+ break;
1569
+ }
1570
+ }
1571
+ final && (final(), final = null);
1572
+ if (result.command === "BEGIN" && max !== 1 && !connection2.reserved)
1573
+ return errored(Errors.generic("UNSAFE_TRANSACTION", "Only use sql.begin, sql.reserved or max: 1"));
1574
+ if (query.options.simple)
1575
+ return BindComplete();
1576
+ if (query.cursorFn) {
1577
+ result.count && query.cursorFn(result);
1578
+ write(Sync);
1579
+ }
1580
+ }
1581
+ function ParseComplete() {
1582
+ query.parsing = false;
1583
+ }
1584
+ function BindComplete() {
1585
+ !result.statement && (result.statement = query.statement);
1586
+ result.columns = query.statement.columns;
1587
+ }
1588
+ function ParameterDescription(x) {
1589
+ const length2 = x.readUInt16BE(5);
1590
+ for (let i = 0;i < length2; ++i)
1591
+ !query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4));
1592
+ query.prepare && (statements[query.signature] = query.statement);
1593
+ query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false);
1594
+ }
1595
+ function RowDescription(x) {
1596
+ if (result.command) {
1597
+ results = results || [result];
1598
+ results.push(result = new Result);
1599
+ result.count = null;
1600
+ query.statement.columns = null;
1601
+ }
1602
+ const length2 = x.readUInt16BE(5);
1603
+ let index2 = 7;
1604
+ let start;
1605
+ query.statement.columns = Array(length2);
1606
+ for (let i = 0;i < length2; ++i) {
1607
+ start = index2;
1608
+ while (x[index2++] !== 0)
1609
+ ;
1610
+ const table = x.readUInt32BE(index2);
1611
+ const number = x.readUInt16BE(index2 + 4);
1612
+ const type = x.readUInt32BE(index2 + 6);
1613
+ query.statement.columns[i] = {
1614
+ name: transform.column.from ? transform.column.from(x.toString("utf8", start, index2 - 1)) : x.toString("utf8", start, index2 - 1),
1615
+ parser: parsers2[type],
1616
+ table,
1617
+ number,
1618
+ type
1619
+ };
1620
+ index2 += 18;
1621
+ }
1622
+ result.statement = query.statement;
1623
+ if (query.onlyDescribe)
1624
+ return query.resolve(query.statement), write(Sync);
1625
+ }
1626
+ async function Authentication(x, type = x.readUInt32BE(5)) {
1627
+ (type === 3 ? AuthenticationCleartextPassword : type === 5 ? AuthenticationMD5Password : type === 10 ? SASL : type === 11 ? SASLContinue : type === 12 ? SASLFinal : type !== 0 ? UnknownAuth : noop)(x, type);
1628
+ }
1629
+ async function AuthenticationCleartextPassword() {
1630
+ const payload = await Pass();
1631
+ write(bytes_default().p().str(payload).z(1).end());
1632
+ }
1633
+ async function AuthenticationMD5Password(x) {
1634
+ const payload = "md5" + await md5(Buffer.concat([
1635
+ Buffer.from(await md5(await Pass() + user)),
1636
+ x.subarray(9)
1637
+ ]));
1638
+ write(bytes_default().p().str(payload).z(1).end());
1639
+ }
1640
+ async function SASL() {
1641
+ nonce = (await crypto.randomBytes(18)).toString("base64");
1642
+ bytes_default().p().str("SCRAM-SHA-256" + bytes_default.N);
1643
+ const i = bytes_default.i;
1644
+ write(bytes_default.inc(4).str("n,,n=*,r=" + nonce).i32(bytes_default.i - i - 4, i).end());
1645
+ }
1646
+ async function SASLContinue(x) {
1647
+ const res = x.toString("utf8", 9).split(",").reduce((acc, x2) => (acc[x2[0]] = x2.slice(2), acc), {});
1648
+ const saltedPassword = await crypto.pbkdf2Sync(await Pass(), Buffer.from(res.s, "base64"), parseInt(res.i), 32, "sha256");
1649
+ const clientKey = await hmac(saltedPassword, "Client Key");
1650
+ const auth = "n=*,r=" + nonce + "," + "r=" + res.r + ",s=" + res.s + ",i=" + res.i + ",c=biws,r=" + res.r;
1651
+ serverSignature = (await hmac(await hmac(saltedPassword, "Server Key"), auth)).toString("base64");
1652
+ const payload = "c=biws,r=" + res.r + ",p=" + xor(clientKey, Buffer.from(await hmac(await sha256(clientKey), auth))).toString("base64");
1653
+ write(bytes_default().p().str(payload).end());
1654
+ }
1655
+ function SASLFinal(x) {
1656
+ if (x.toString("utf8", 9).split(bytes_default.N, 1)[0].slice(2) === serverSignature)
1657
+ return;
1658
+ errored(Errors.generic("SASL_SIGNATURE_MISMATCH", "The server did not return the correct signature"));
1659
+ socket.destroy();
1660
+ }
1661
+ function Pass() {
1662
+ return Promise.resolve(typeof options.pass === "function" ? options.pass() : options.pass);
1663
+ }
1664
+ function NoData() {
1665
+ result.statement = query.statement;
1666
+ result.statement.columns = [];
1667
+ if (query.onlyDescribe)
1668
+ return query.resolve(query.statement), write(Sync);
1669
+ }
1670
+ function BackendKeyData(x) {
1671
+ backend.pid = x.readUInt32BE(5);
1672
+ backend.secret = x.readUInt32BE(9);
1673
+ }
1674
+ async function fetchArrayTypes() {
1675
+ needsTypes = false;
1676
+ const types2 = await new Query([`
1677
+ select b.oid, b.typarray
1678
+ from pg_catalog.pg_type a
1679
+ left join pg_catalog.pg_type b on b.oid = a.typelem
1680
+ where a.typcategory = 'A'
1681
+ group by b.oid, b.typarray
1682
+ order by b.oid
1683
+ `], [], execute);
1684
+ types2.forEach(({ oid, typarray }) => addArrayType(oid, typarray));
1685
+ }
1686
+ function addArrayType(oid, typarray) {
1687
+ if (!!options.parsers[typarray] && !!options.serializers[typarray])
1688
+ return;
1689
+ const parser = options.parsers[oid];
1690
+ options.shared.typeArrayMap[oid] = typarray;
1691
+ options.parsers[typarray] = (xs) => arrayParser(xs, parser, typarray);
1692
+ options.parsers[typarray].array = true;
1693
+ options.serializers[typarray] = (xs) => arraySerializer(xs, options.serializers[oid], options, typarray);
1694
+ }
1695
+ function tryNext(x, xs) {
1696
+ return x === "read-write" && xs.default_transaction_read_only === "on" || x === "read-only" && xs.default_transaction_read_only === "off" || x === "primary" && xs.in_hot_standby === "on" || x === "standby" && xs.in_hot_standby === "off" || x === "prefer-standby" && xs.in_hot_standby === "off" && options.host[retries];
1697
+ }
1698
+ function fetchState() {
1699
+ const query2 = new Query([`
1700
+ show transaction_read_only;
1701
+ select pg_catalog.pg_is_in_recovery()
1702
+ `], [], execute, null, { simple: true });
1703
+ query2.resolve = ([[a], [b2]]) => {
1704
+ backendParameters.default_transaction_read_only = a.transaction_read_only;
1705
+ backendParameters.in_hot_standby = b2.pg_is_in_recovery ? "on" : "off";
1706
+ };
1707
+ query2.execute();
1708
+ }
1709
+ function ErrorResponse(x) {
1710
+ if (query) {
1711
+ (query.cursorFn || query.describeFirst) && write(Sync);
1712
+ errorResponse = Errors.postgres(parseError(x));
1713
+ } else {
1714
+ errored(Errors.postgres(parseError(x)));
1715
+ }
1716
+ }
1717
+ function retry(q, error2) {
1718
+ delete statements[q.signature];
1719
+ q.retried = error2;
1720
+ execute(q);
1721
+ }
1722
+ function NotificationResponse(x) {
1723
+ if (!onnotify)
1724
+ return;
1725
+ let index2 = 9;
1726
+ while (x[index2++] !== 0)
1727
+ ;
1728
+ onnotify(x.toString("utf8", 9, index2 - 1), x.toString("utf8", index2, x.length - 1));
1729
+ }
1730
+ async function PortalSuspended() {
1731
+ try {
1732
+ const x = await Promise.resolve(query.cursorFn(result));
1733
+ rows = 0;
1734
+ x === CLOSE ? write(Close(query.portal)) : (result = new Result, write(Execute("", query.cursorRows)));
1735
+ } catch (err) {
1736
+ write(Sync);
1737
+ query.reject(err);
1738
+ }
1739
+ }
1740
+ function CloseComplete() {
1741
+ result.count && query.cursorFn(result);
1742
+ query.resolve(result);
1743
+ }
1744
+ function CopyInResponse() {
1745
+ stream = new Stream.Writable({
1746
+ autoDestroy: true,
1747
+ write(chunk2, encoding, callback) {
1748
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
1749
+ },
1750
+ destroy(error2, callback) {
1751
+ callback(error2);
1752
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1753
+ stream = null;
1754
+ },
1755
+ final(callback) {
1756
+ socket.write(bytes_default().c().end());
1757
+ final = callback;
1758
+ stream = null;
1759
+ }
1760
+ });
1761
+ query.resolve(stream);
1762
+ }
1763
+ function CopyOutResponse() {
1764
+ stream = new Stream.Readable({
1765
+ read() {
1766
+ socket.resume();
1767
+ }
1768
+ });
1769
+ query.resolve(stream);
1770
+ }
1771
+ function CopyBothResponse() {
1772
+ stream = new Stream.Duplex({
1773
+ autoDestroy: true,
1774
+ read() {
1775
+ socket.resume();
1776
+ },
1777
+ write(chunk2, encoding, callback) {
1778
+ socket.write(bytes_default().d().raw(chunk2).end(), callback);
1779
+ },
1780
+ destroy(error2, callback) {
1781
+ callback(error2);
1782
+ socket.write(bytes_default().f().str(error2 + bytes_default.N).end());
1783
+ stream = null;
1784
+ },
1785
+ final(callback) {
1786
+ socket.write(bytes_default().c().end());
1787
+ final = callback;
1788
+ }
1789
+ });
1790
+ query.resolve(stream);
1791
+ }
1792
+ function CopyData(x) {
1793
+ stream && (stream.push(x.subarray(5)) || socket.pause());
1794
+ }
1795
+ function CopyDone() {
1796
+ stream && stream.push(null);
1797
+ stream = null;
1798
+ }
1799
+ function NoticeResponse(x) {
1800
+ onnotice ? onnotice(parseError(x)) : console.log(parseError(x));
1801
+ }
1802
+ function EmptyQueryResponse() {}
1803
+ function FunctionCallResponse() {
1804
+ errored(Errors.notSupported("FunctionCallResponse"));
1805
+ }
1806
+ function NegotiateProtocolVersion() {
1807
+ errored(Errors.notSupported("NegotiateProtocolVersion"));
1808
+ }
1809
+ function UnknownMessage(x) {
1810
+ console.error("Postgres.js : Unknown Message:", x[0]);
1811
+ }
1812
+ function UnknownAuth(x, type) {
1813
+ console.error("Postgres.js : Unknown Auth:", type);
1814
+ }
1815
+ function Bind(parameters, types2, statement = "", portal = "") {
1816
+ let prev, type;
1817
+ bytes_default().B().str(portal + bytes_default.N).str(statement + bytes_default.N).i16(0).i16(parameters.length);
1818
+ parameters.forEach((x, i) => {
1819
+ if (x === null)
1820
+ return bytes_default.i32(4294967295);
1821
+ type = types2[i];
1822
+ parameters[i] = x = type in options.serializers ? options.serializers[type](x) : "" + x;
1823
+ prev = bytes_default.i;
1824
+ bytes_default.inc(4).str(x).i32(bytes_default.i - prev - 4, prev);
1825
+ });
1826
+ bytes_default.i16(0);
1827
+ return bytes_default.end();
1828
+ }
1829
+ function Parse(str, parameters, types2, name = "") {
1830
+ bytes_default().P().str(name + bytes_default.N).str(str + bytes_default.N).i16(parameters.length);
1831
+ parameters.forEach((x, i) => bytes_default.i32(types2[i] || 0));
1832
+ return bytes_default.end();
1833
+ }
1834
+ function Describe(x, name = "") {
1835
+ return bytes_default().D().str(x).str(name + bytes_default.N).end();
1836
+ }
1837
+ function Execute(portal = "", rows2 = 0) {
1838
+ return Buffer.concat([
1839
+ bytes_default().E().str(portal + bytes_default.N).i32(rows2).end(),
1840
+ Flush
1841
+ ]);
1842
+ }
1843
+ function Close(portal = "") {
1844
+ return Buffer.concat([
1845
+ bytes_default().C().str("P").str(portal + bytes_default.N).end(),
1846
+ bytes_default().S().end()
1847
+ ]);
1848
+ }
1849
+ function StartupMessage() {
1850
+ return cancelMessage || bytes_default().inc(4).i16(3).z(2).str(Object.entries(Object.assign({
1851
+ user,
1852
+ database,
1853
+ client_encoding: "UTF8"
1854
+ }, options.connection)).filter(([, v]) => v).map(([k, v]) => k + bytes_default.N + v).join(bytes_default.N)).z(2).end(0);
1855
+ }
1856
+ }
1857
+ function parseError(x) {
1858
+ const error = {};
1859
+ let start = 5;
1860
+ for (let i = 5;i < x.length - 1; i++) {
1861
+ if (x[i] === 0) {
1862
+ error[errorFields[x[start]]] = x.toString("utf8", start + 1, i);
1863
+ start = i + 1;
1864
+ }
1865
+ }
1866
+ return error;
1867
+ }
1868
+ function md5(x) {
1869
+ return crypto.createHash("md5").update(x).digest("hex");
1870
+ }
1871
+ function hmac(key, x) {
1872
+ return crypto.createHmac("sha256", key).update(x).digest();
1873
+ }
1874
+ function sha256(x) {
1875
+ return crypto.createHash("sha256").update(x).digest();
1876
+ }
1877
+ function xor(a, b2) {
1878
+ const length = Math.max(a.length, b2.length);
1879
+ const buffer2 = Buffer.allocUnsafe(length);
1880
+ for (let i = 0;i < length; i++)
1881
+ buffer2[i] = a[i] ^ b2[i];
1882
+ return buffer2;
1883
+ }
1884
+ function timer(fn, seconds) {
1885
+ seconds = typeof seconds === "function" ? seconds() : seconds;
1886
+ if (!seconds)
1887
+ return { cancel: noop, start: noop };
1888
+ let timer2;
1889
+ return {
1890
+ cancel() {
1891
+ timer2 && (clearTimeout(timer2), timer2 = null);
1892
+ },
1893
+ start() {
1894
+ timer2 && clearTimeout(timer2);
1895
+ timer2 = setTimeout(done, seconds * 1000, arguments);
1896
+ }
1897
+ };
1898
+ function done(args) {
1899
+ fn.apply(null, args);
1900
+ timer2 = null;
1901
+ }
1902
+ }
1903
+
1904
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/subscribe.js
1905
+ var noop2 = () => {};
1906
+ function Subscribe(postgres2, options) {
1907
+ const subscribers = new Map, slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
1908
+ let connection2, stream, ended = false;
1909
+ const sql2 = subscribe.sql = postgres2({
1910
+ ...options,
1911
+ transform: { column: {}, value: {}, row: {} },
1912
+ max: 1,
1913
+ fetch_types: false,
1914
+ idle_timeout: null,
1915
+ max_lifetime: null,
1916
+ connection: {
1917
+ ...options.connection,
1918
+ replication: "database"
1919
+ },
1920
+ onclose: async function() {
1921
+ if (ended)
1922
+ return;
1923
+ stream = null;
1924
+ state.pid = state.secret = undefined;
1925
+ connected(await init(sql2, slot, options.publications));
1926
+ subscribers.forEach((event) => event.forEach(({ onsubscribe }) => onsubscribe()));
1927
+ },
1928
+ no_subscribe: true
1929
+ });
1930
+ const { end, close } = sql2;
1931
+ sql2.end = async () => {
1932
+ ended = true;
1933
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1934
+ return end();
1935
+ };
1936
+ sql2.close = async () => {
1937
+ stream && await new Promise((r) => (stream.once("close", r), stream.end()));
1938
+ return close();
1939
+ };
1940
+ return subscribe;
1941
+ async function subscribe(event, fn, onsubscribe = noop2, onerror = noop2) {
1942
+ event = parseEvent(event);
1943
+ if (!connection2)
1944
+ connection2 = init(sql2, slot, options.publications);
1945
+ const subscriber = { fn, onsubscribe };
1946
+ const fns = subscribers.has(event) ? subscribers.get(event).add(subscriber) : subscribers.set(event, new Set([subscriber])).get(event);
1947
+ const unsubscribe = () => {
1948
+ fns.delete(subscriber);
1949
+ fns.size === 0 && subscribers.delete(event);
1950
+ };
1951
+ return connection2.then((x) => {
1952
+ connected(x);
1953
+ onsubscribe();
1954
+ stream && stream.on("error", onerror);
1955
+ return { unsubscribe, state, sql: sql2 };
1956
+ });
1957
+ }
1958
+ function connected(x) {
1959
+ stream = x.stream;
1960
+ state.pid = x.state.pid;
1961
+ state.secret = x.state.secret;
1962
+ }
1963
+ async function init(sql3, slot2, publications) {
1964
+ if (!publications)
1965
+ throw new Error("Missing publication names");
1966
+ const xs = await sql3.unsafe(`CREATE_REPLICATION_SLOT ${slot2} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`);
1967
+ const [x] = xs;
1968
+ const stream2 = await sql3.unsafe(`START_REPLICATION SLOT ${slot2} LOGICAL ${x.consistent_point} (proto_version '1', publication_names '${publications}')`).writable();
1969
+ const state2 = {
1970
+ lsn: Buffer.concat(x.consistent_point.split("/").map((x2) => Buffer.from(("00000000" + x2).slice(-8), "hex")))
1971
+ };
1972
+ stream2.on("data", data);
1973
+ stream2.on("error", error);
1974
+ stream2.on("close", sql3.close);
1975
+ return { stream: stream2, state: xs.state };
1976
+ function error(e) {
1977
+ console.error("Unexpected error during logical streaming - reconnecting", e);
1978
+ }
1979
+ function data(x2) {
1980
+ if (x2[0] === 119) {
1981
+ parse(x2.subarray(25), state2, sql3.options.parsers, handle, options.transform);
1982
+ } else if (x2[0] === 107 && x2[17]) {
1983
+ state2.lsn = x2.subarray(1, 9);
1984
+ pong();
1985
+ }
1986
+ }
1987
+ function handle(a, b2) {
1988
+ const path = b2.relation.schema + "." + b2.relation.table;
1989
+ call("*", a, b2);
1990
+ call("*:" + path, a, b2);
1991
+ b2.relation.keys.length && call("*:" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1992
+ call(b2.command, a, b2);
1993
+ call(b2.command + ":" + path, a, b2);
1994
+ b2.relation.keys.length && call(b2.command + ":" + path + "=" + b2.relation.keys.map((x2) => a[x2.name]), a, b2);
1995
+ }
1996
+ function pong() {
1997
+ const x2 = Buffer.alloc(34);
1998
+ x2[0] = 114;
1999
+ x2.fill(state2.lsn, 1);
2000
+ x2.writeBigInt64BE(BigInt(Date.now() - Date.UTC(2000, 0, 1)) * BigInt(1000), 25);
2001
+ stream2.write(x2);
2002
+ }
2003
+ }
2004
+ function call(x, a, b2) {
2005
+ subscribers.has(x) && subscribers.get(x).forEach(({ fn }) => fn(a, b2, x));
2006
+ }
2007
+ }
2008
+ function Time(x) {
2009
+ return new Date(Date.UTC(2000, 0, 1) + Number(x / BigInt(1000)));
2010
+ }
2011
+ function parse(x, state, parsers2, handle, transform) {
2012
+ const char = (acc, [k, v]) => (acc[k.charCodeAt(0)] = v, acc);
2013
+ Object.entries({
2014
+ R: (x2) => {
2015
+ let i = 1;
2016
+ const r = state[x2.readUInt32BE(i)] = {
2017
+ schema: x2.toString("utf8", i += 4, i = x2.indexOf(0, i)) || "pg_catalog",
2018
+ table: x2.toString("utf8", i + 1, i = x2.indexOf(0, i + 1)),
2019
+ columns: Array(x2.readUInt16BE(i += 2)),
2020
+ keys: []
2021
+ };
2022
+ i += 2;
2023
+ let columnIndex = 0, column;
2024
+ while (i < x2.length) {
2025
+ column = r.columns[columnIndex++] = {
2026
+ key: x2[i++],
2027
+ name: transform.column.from ? transform.column.from(x2.toString("utf8", i, i = x2.indexOf(0, i))) : x2.toString("utf8", i, i = x2.indexOf(0, i)),
2028
+ type: x2.readUInt32BE(i += 1),
2029
+ parser: parsers2[x2.readUInt32BE(i)],
2030
+ atttypmod: x2.readUInt32BE(i += 4)
2031
+ };
2032
+ column.key && r.keys.push(column);
2033
+ i += 4;
2034
+ }
2035
+ },
2036
+ Y: () => {},
2037
+ O: () => {},
2038
+ B: (x2) => {
2039
+ state.date = Time(x2.readBigInt64BE(9));
2040
+ state.lsn = x2.subarray(1, 9);
2041
+ },
2042
+ I: (x2) => {
2043
+ let i = 1;
2044
+ const relation = state[x2.readUInt32BE(i)];
2045
+ const { row } = tuples(x2, relation.columns, i += 7, transform);
2046
+ handle(row, {
2047
+ command: "insert",
2048
+ relation
2049
+ });
2050
+ },
2051
+ D: (x2) => {
2052
+ let i = 1;
2053
+ const relation = state[x2.readUInt32BE(i)];
2054
+ i += 4;
2055
+ const key = x2[i] === 75;
2056
+ handle(key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform).row : null, {
2057
+ command: "delete",
2058
+ relation,
2059
+ key
2060
+ });
2061
+ },
2062
+ U: (x2) => {
2063
+ let i = 1;
2064
+ const relation = state[x2.readUInt32BE(i)];
2065
+ i += 4;
2066
+ const key = x2[i] === 75;
2067
+ const xs = key || x2[i] === 79 ? tuples(x2, relation.columns, i += 3, transform) : null;
2068
+ xs && (i = xs.i);
2069
+ const { row } = tuples(x2, relation.columns, i + 3, transform);
2070
+ handle(row, {
2071
+ command: "update",
2072
+ relation,
2073
+ key,
2074
+ old: xs && xs.row
2075
+ });
2076
+ },
2077
+ T: () => {},
2078
+ C: () => {}
2079
+ }).reduce(char, {})[x[0]](x);
2080
+ }
2081
+ function tuples(x, columns, xi, transform) {
2082
+ let type, column, value;
2083
+ const row = transform.raw ? new Array(columns.length) : {};
2084
+ for (let i = 0;i < columns.length; i++) {
2085
+ type = x[xi++];
2086
+ column = columns[i];
2087
+ value = type === 110 ? null : type === 117 ? undefined : column.parser === undefined ? x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)) : column.parser.array === true ? column.parser(x.toString("utf8", xi + 5, xi += 4 + x.readUInt32BE(xi))) : column.parser(x.toString("utf8", xi + 4, xi += 4 + x.readUInt32BE(xi)));
2088
+ transform.raw ? row[i] = transform.raw === true ? value : transform.value.from ? transform.value.from(value, column) : value : row[column.name] = transform.value.from ? transform.value.from(value, column) : value;
2089
+ }
2090
+ return { i: xi, row: transform.row.from ? transform.row.from(row) : row };
2091
+ }
2092
+ function parseEvent(x) {
2093
+ const xs = x.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) || [];
2094
+ if (!xs)
2095
+ throw new Error("Malformed subscribe pattern: " + x);
2096
+ const [, command, path, key] = xs;
2097
+ return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
2098
+ }
2099
+
2100
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/large.js
2101
+ import Stream2 from "stream";
2102
+ function largeObject(sql2, oid, mode = 131072 | 262144) {
2103
+ return new Promise(async (resolve, reject) => {
2104
+ await sql2.begin(async (sql3) => {
2105
+ let finish;
2106
+ !oid && ([{ oid }] = await sql3`select lo_creat(-1) as oid`);
2107
+ const [{ fd }] = await sql3`select lo_open(${oid}, ${mode}) as fd`;
2108
+ const lo = {
2109
+ writable,
2110
+ readable,
2111
+ close: () => sql3`select lo_close(${fd})`.then(finish),
2112
+ tell: () => sql3`select lo_tell64(${fd})`,
2113
+ read: (x) => sql3`select loread(${fd}, ${x}) as data`,
2114
+ write: (x) => sql3`select lowrite(${fd}, ${x})`,
2115
+ truncate: (x) => sql3`select lo_truncate64(${fd}, ${x})`,
2116
+ seek: (x, whence = 0) => sql3`select lo_lseek64(${fd}, ${x}, ${whence})`,
2117
+ size: () => sql3`
2118
+ select
2119
+ lo_lseek64(${fd}, location, 0) as position,
2120
+ seek.size
2121
+ from (
2122
+ select
2123
+ lo_lseek64($1, 0, 2) as size,
2124
+ tell.location
2125
+ from (select lo_tell64($1) as location) tell
2126
+ ) seek
2127
+ `
2128
+ };
2129
+ resolve(lo);
2130
+ return new Promise(async (r) => finish = r);
2131
+ async function readable({
2132
+ highWaterMark = 2048 * 8,
2133
+ start = 0,
2134
+ end = Infinity
2135
+ } = {}) {
2136
+ let max = end - start;
2137
+ start && await lo.seek(start);
2138
+ return new Stream2.Readable({
2139
+ highWaterMark,
2140
+ async read(size2) {
2141
+ const l = size2 > max ? size2 - max : size2;
2142
+ max -= size2;
2143
+ const [{ data }] = await lo.read(l);
2144
+ this.push(data);
2145
+ if (data.length < size2)
2146
+ this.push(null);
2147
+ }
2148
+ });
2149
+ }
2150
+ async function writable({
2151
+ highWaterMark = 2048 * 8,
2152
+ start = 0
2153
+ } = {}) {
2154
+ start && await lo.seek(start);
2155
+ return new Stream2.Writable({
2156
+ highWaterMark,
2157
+ write(chunk, encoding, callback) {
2158
+ lo.write(chunk).then(() => callback(), callback);
2159
+ }
2160
+ });
2161
+ }
2162
+ }).catch(reject);
2163
+ });
2164
+ }
2165
+
2166
+ // ../../node_modules/.bun/postgres@3.4.9/node_modules/postgres/src/index.js
2167
+ Object.assign(Postgres, {
2168
+ PostgresError,
2169
+ toPascal,
2170
+ pascal,
2171
+ toCamel,
2172
+ camel,
2173
+ toKebab,
2174
+ kebab,
2175
+ fromPascal,
2176
+ fromCamel,
2177
+ fromKebab,
2178
+ BigInt: {
2179
+ to: 20,
2180
+ from: [20],
2181
+ parse: (x) => BigInt(x),
2182
+ serialize: (x) => x.toString()
2183
+ }
2184
+ });
2185
+ var src_default = Postgres;
2186
+ function Postgres(a, b2) {
2187
+ const options = parseOptions(a, b2), subscribe = options.no_subscribe || Subscribe(Postgres, { ...options });
2188
+ let ending = false;
2189
+ const queries = queue_default(), connecting = queue_default(), reserved = queue_default(), closed = queue_default(), ended = queue_default(), open = queue_default(), busy = queue_default(), full = queue_default(), queues = { connecting, reserved, closed, ended, open, busy, full };
2190
+ const connections = [...Array(options.max)].map(() => connection_default(options, queues, { onopen, onend, onclose }));
2191
+ const sql2 = Sql(handler);
2192
+ Object.assign(sql2, {
2193
+ get parameters() {
2194
+ return options.parameters;
2195
+ },
2196
+ largeObject: largeObject.bind(null, sql2),
2197
+ subscribe,
2198
+ CLOSE,
2199
+ END: CLOSE,
2200
+ PostgresError,
2201
+ options,
2202
+ reserve,
2203
+ listen,
2204
+ begin,
2205
+ close,
2206
+ end
2207
+ });
2208
+ return sql2;
2209
+ function Sql(handler2) {
2210
+ handler2.debug = options.debug;
2211
+ Object.entries(options.types).reduce((acc, [name, type]) => {
2212
+ acc[name] = (x) => new Parameter(x, type.to);
2213
+ return acc;
2214
+ }, typed);
2215
+ Object.assign(sql3, {
2216
+ types: typed,
2217
+ typed,
2218
+ unsafe,
2219
+ notify,
2220
+ array,
2221
+ json,
2222
+ file
2223
+ });
2224
+ return sql3;
2225
+ function typed(value, type) {
2226
+ return new Parameter(value, type);
2227
+ }
2228
+ function sql3(strings, ...args) {
2229
+ const query = strings && Array.isArray(strings.raw) ? new Query(strings, args, handler2, cancel) : typeof strings === "string" && !args.length ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) : new Builder(strings, args);
2230
+ return query;
2231
+ }
2232
+ function unsafe(string, args = [], options2 = {}) {
2233
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
2234
+ const query = new Query([string], args, handler2, cancel, {
2235
+ prepare: false,
2236
+ ...options2,
2237
+ simple: "simple" in options2 ? options2.simple : args.length === 0
2238
+ });
2239
+ return query;
2240
+ }
2241
+ function file(path, args = [], options2 = {}) {
2242
+ arguments.length === 2 && !Array.isArray(args) && (options2 = args, args = []);
2243
+ const query = new Query([], args, (query2) => {
2244
+ fs.readFile(path, "utf8", (err, string) => {
2245
+ if (err)
2246
+ return query2.reject(err);
2247
+ query2.strings = [string];
2248
+ handler2(query2);
2249
+ });
2250
+ }, cancel, {
2251
+ ...options2,
2252
+ simple: "simple" in options2 ? options2.simple : args.length === 0
2253
+ });
2254
+ return query;
2255
+ }
2256
+ }
2257
+ async function listen(name, fn, onlisten) {
2258
+ const listener = { fn, onlisten };
2259
+ const sql3 = listen.sql || (listen.sql = Postgres({
2260
+ ...options,
2261
+ max: 1,
2262
+ idle_timeout: null,
2263
+ max_lifetime: null,
2264
+ fetch_types: false,
2265
+ onclose() {
2266
+ Object.entries(listen.channels).forEach(([name2, { listeners }]) => {
2267
+ delete listen.channels[name2];
2268
+ Promise.all(listeners.map((l) => listen(name2, l.fn, l.onlisten).catch(() => {})));
2269
+ });
2270
+ },
2271
+ onnotify(c, x) {
2272
+ c in listen.channels && listen.channels[c].listeners.forEach((l) => l.fn(x));
2273
+ }
2274
+ }));
2275
+ const channels = listen.channels || (listen.channels = {}), exists = name in channels;
2276
+ if (exists) {
2277
+ channels[name].listeners.push(listener);
2278
+ const result2 = await channels[name].result;
2279
+ listener.onlisten && listener.onlisten();
2280
+ return { state: result2.state, unlisten };
2281
+ }
2282
+ channels[name] = { result: sql3`listen ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`, listeners: [listener] };
2283
+ const result = await channels[name].result;
2284
+ listener.onlisten && listener.onlisten();
2285
+ return { state: result.state, unlisten };
2286
+ async function unlisten() {
2287
+ if (name in channels === false)
2288
+ return;
2289
+ channels[name].listeners = channels[name].listeners.filter((x) => x !== listener);
2290
+ if (channels[name].listeners.length)
2291
+ return;
2292
+ delete channels[name];
2293
+ return sql3`unlisten ${sql3.unsafe('"' + name.replace(/"/g, '""') + '"')}`;
2294
+ }
2295
+ }
2296
+ async function notify(channel, payload) {
2297
+ return await sql2`select pg_notify(${channel}, ${"" + payload})`;
2298
+ }
2299
+ async function reserve() {
2300
+ const queue = queue_default();
2301
+ const c = open.length ? open.shift() : await new Promise((resolve, reject) => {
2302
+ const query = { reserve: resolve, reject };
2303
+ queries.push(query);
2304
+ closed.length && connect(closed.shift(), query);
2305
+ });
2306
+ move(c, reserved);
2307
+ c.reserved = () => queue.length ? c.execute(queue.shift()) : move(c, reserved);
2308
+ c.reserved.release = true;
2309
+ const sql3 = Sql(handler2);
2310
+ sql3.release = () => {
2311
+ c.reserved = null;
2312
+ onopen(c);
2313
+ };
2314
+ return sql3;
2315
+ function handler2(q) {
2316
+ c.queue === full ? queue.push(q) : c.execute(q) || move(c, full);
2317
+ }
2318
+ }
2319
+ async function begin(options2, fn) {
2320
+ !fn && (fn = options2, options2 = "");
2321
+ const queries2 = queue_default();
2322
+ let savepoints = 0, connection2, prepare = null;
2323
+ try {
2324
+ await sql2.unsafe("begin " + options2.replace(/[^a-z ]/ig, ""), [], { onexecute }).execute();
2325
+ return await Promise.race([
2326
+ scope(connection2, fn),
2327
+ new Promise((_, reject) => connection2.onclose = reject)
2328
+ ]);
2329
+ } catch (error) {
2330
+ throw error;
2331
+ }
2332
+ async function scope(c, fn2, name) {
2333
+ const sql3 = Sql(handler2);
2334
+ sql3.savepoint = savepoint;
2335
+ sql3.prepare = (x) => prepare = x.replace(/[^a-z0-9$-_. ]/gi);
2336
+ let uncaughtError, result;
2337
+ name && await sql3`savepoint ${sql3(name)}`;
2338
+ try {
2339
+ result = await new Promise((resolve, reject) => {
2340
+ const x = fn2(sql3);
2341
+ Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject);
2342
+ });
2343
+ if (uncaughtError)
2344
+ throw uncaughtError;
2345
+ } catch (e) {
2346
+ await (name ? sql3`rollback to ${sql3(name)}` : sql3`rollback`);
2347
+ throw e instanceof PostgresError && e.code === "25P02" && uncaughtError || e;
2348
+ }
2349
+ if (!name) {
2350
+ prepare ? await sql3`prepare transaction '${sql3.unsafe(prepare)}'` : await sql3`commit`;
2351
+ }
2352
+ return result;
2353
+ function savepoint(name2, fn3) {
2354
+ if (name2 && Array.isArray(name2.raw))
2355
+ return savepoint((sql4) => sql4.apply(sql4, arguments));
2356
+ arguments.length === 1 && (fn3 = name2, name2 = null);
2357
+ return scope(c, fn3, "s" + savepoints++ + (name2 ? "_" + name2 : ""));
2358
+ }
2359
+ function handler2(q) {
2360
+ q.catch((e) => uncaughtError || (uncaughtError = e));
2361
+ c.queue === full ? queries2.push(q) : c.execute(q) || move(c, full);
2362
+ }
2363
+ }
2364
+ function onexecute(c) {
2365
+ connection2 = c;
2366
+ move(c, reserved);
2367
+ c.reserved = () => queries2.length ? c.execute(queries2.shift()) : move(c, reserved);
2368
+ }
2369
+ }
2370
+ function move(c, queue) {
2371
+ c.queue.remove(c);
2372
+ queue.push(c);
2373
+ c.queue = queue;
2374
+ queue === open ? c.idleTimer.start() : c.idleTimer.cancel();
2375
+ return c;
2376
+ }
2377
+ function json(x) {
2378
+ return new Parameter(x, 3802);
2379
+ }
2380
+ function array(x, type) {
2381
+ if (!Array.isArray(x))
2382
+ return array(Array.from(arguments));
2383
+ return new Parameter(x, type || (x.length ? inferType(x) || 25 : 0), options.shared.typeArrayMap);
2384
+ }
2385
+ function handler(query) {
2386
+ if (ending)
2387
+ return query.reject(Errors.connection("CONNECTION_ENDED", options, options));
2388
+ if (open.length)
2389
+ return go(open.shift(), query);
2390
+ if (closed.length)
2391
+ return connect(closed.shift(), query);
2392
+ busy.length ? go(busy.shift(), query) : queries.push(query);
2393
+ }
2394
+ function go(c, query) {
2395
+ return c.execute(query) ? move(c, busy) : move(c, full);
2396
+ }
2397
+ function cancel(query) {
2398
+ return new Promise((resolve, reject) => {
2399
+ query.state ? query.active ? connection_default(options).cancel(query.state, resolve, reject) : query.cancelled = { resolve, reject } : (queries.remove(query), query.cancelled = true, query.reject(Errors.generic("57014", "canceling statement due to user request")), resolve());
2400
+ });
2401
+ }
2402
+ async function end({ timeout = null } = {}) {
2403
+ if (ending)
2404
+ return ending;
2405
+ await 1;
2406
+ let timer2;
2407
+ return ending = Promise.race([
2408
+ new Promise((r) => timeout !== null && (timer2 = setTimeout(destroy, timeout * 1000, r))),
2409
+ Promise.all(connections.map((c) => c.end()).concat(listen.sql ? listen.sql.end({ timeout: 0 }) : [], subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : []))
2410
+ ]).then(() => clearTimeout(timer2));
2411
+ }
2412
+ async function close() {
2413
+ await Promise.all(connections.map((c) => c.end()));
2414
+ }
2415
+ async function destroy(resolve) {
2416
+ await Promise.all(connections.map((c) => c.terminate()));
2417
+ while (queries.length)
2418
+ queries.shift().reject(Errors.connection("CONNECTION_DESTROYED", options));
2419
+ resolve();
2420
+ }
2421
+ function connect(c, query) {
2422
+ move(c, connecting);
2423
+ c.connect(query);
2424
+ return c;
2425
+ }
2426
+ function onend(c) {
2427
+ move(c, ended);
2428
+ }
2429
+ function onopen(c) {
2430
+ if (queries.length === 0)
2431
+ return move(c, open);
2432
+ let max = Math.ceil(queries.length / (connecting.length + 1)), ready = true;
2433
+ while (ready && queries.length && max-- > 0) {
2434
+ const query = queries.shift();
2435
+ if (query.reserve)
2436
+ return query.reserve(c);
2437
+ ready = c.execute(query);
2438
+ }
2439
+ ready ? move(c, busy) : move(c, full);
2440
+ }
2441
+ function onclose(c, e) {
2442
+ move(c, closed);
2443
+ c.reserved = null;
2444
+ c.onclose && (c.onclose(e), c.onclose = null);
2445
+ options.onclose && options.onclose(c.id);
2446
+ queries.length && connect(c, queries.shift());
2447
+ }
2448
+ }
2449
+ function parseOptions(a, b2) {
2450
+ if (a && a.shared)
2451
+ return a;
2452
+ const env = process.env, o = (!a || typeof a === "string" ? b2 : a) || {}, { url, multihost } = parseUrl(a), query = [...url.searchParams].reduce((a2, [b3, c]) => (a2[b3] = c, a2), {}), host = o.hostname || o.host || multihost || url.hostname || env.PGHOST || "localhost", port = o.port || url.port || env.PGPORT || 5432, user = o.user || o.username || url.username || env.PGUSERNAME || env.PGUSER || osUsername();
2453
+ o.no_prepare && (o.prepare = false);
2454
+ query.sslmode && (query.ssl = query.sslmode, delete query.sslmode);
2455
+ "timeout" in o && (console.log("The timeout option is deprecated, use idle_timeout instead"), o.idle_timeout = o.timeout);
2456
+ query.sslrootcert === "system" && (query.ssl = "verify-full");
2457
+ const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
2458
+ const defaults = {
2459
+ max: globalThis.Cloudflare ? 3 : 10,
2460
+ ssl: false,
2461
+ sslnegotiation: null,
2462
+ idle_timeout: null,
2463
+ connect_timeout: 30,
2464
+ max_lifetime,
2465
+ max_pipeline: 100,
2466
+ backoff,
2467
+ keep_alive: 60,
2468
+ prepare: true,
2469
+ debug: false,
2470
+ fetch_types: true,
2471
+ publications: "alltables",
2472
+ target_session_attrs: null
2473
+ };
2474
+ return {
2475
+ host: Array.isArray(host) ? host : host.split(",").map((x) => x.split(":")[0]),
2476
+ port: Array.isArray(port) ? port : host.split(",").map((x) => parseInt(x.split(":")[1] || port)),
2477
+ path: o.path || host.indexOf("/") > -1 && host + "/.s.PGSQL." + port,
2478
+ database: o.database || o.db || (url.pathname || "").slice(1) || env.PGDATABASE || user,
2479
+ user,
2480
+ pass: o.pass || o.password || url.password || env.PGPASSWORD || "",
2481
+ ...Object.entries(defaults).reduce((acc, [k, d]) => {
2482
+ const value = k in o ? o[k] : (k in query) ? query[k] === "disable" || query[k] === "false" ? false : query[k] : env["PG" + k.toUpperCase()] || d;
2483
+ acc[k] = typeof value === "string" && ints.includes(k) ? +value : value;
2484
+ return acc;
2485
+ }, {}),
2486
+ connection: {
2487
+ application_name: env.PGAPPNAME || "postgres.js",
2488
+ ...o.connection,
2489
+ ...Object.entries(query).reduce((acc, [k, v]) => ((k in defaults) || (acc[k] = v), acc), {})
2490
+ },
2491
+ types: o.types || {},
2492
+ target_session_attrs: tsa(o, url, env),
2493
+ onnotice: o.onnotice,
2494
+ onnotify: o.onnotify,
2495
+ onclose: o.onclose,
2496
+ onparameter: o.onparameter,
2497
+ socket: o.socket,
2498
+ transform: parseTransform(o.transform || { undefined: undefined }),
2499
+ parameters: {},
2500
+ shared: { retries: 0, typeArrayMap: {} },
2501
+ ...mergeUserTypes(o.types)
2502
+ };
2503
+ }
2504
+ function tsa(o, url, env) {
2505
+ const x = o.target_session_attrs || url.searchParams.get("target_session_attrs") || env.PGTARGETSESSIONATTRS;
2506
+ if (!x || ["read-write", "read-only", "primary", "standby", "prefer-standby"].includes(x))
2507
+ return x;
2508
+ throw new Error("target_session_attrs " + x + " is not supported");
2509
+ }
2510
+ function backoff(retries) {
2511
+ return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20);
2512
+ }
2513
+ function max_lifetime() {
2514
+ return 60 * (30 + Math.random() * 30);
2515
+ }
2516
+ function parseTransform(x) {
2517
+ return {
2518
+ undefined: x.undefined,
2519
+ column: {
2520
+ from: typeof x.column === "function" ? x.column : x.column && x.column.from,
2521
+ to: x.column && x.column.to
2522
+ },
2523
+ value: {
2524
+ from: typeof x.value === "function" ? x.value : x.value && x.value.from,
2525
+ to: x.value && x.value.to
2526
+ },
2527
+ row: {
2528
+ from: typeof x.row === "function" ? x.row : x.row && x.row.from,
2529
+ to: x.row && x.row.to
2530
+ }
2531
+ };
2532
+ }
2533
+ function parseUrl(url) {
2534
+ if (!url || typeof url !== "string")
2535
+ return { url: { searchParams: new Map } };
2536
+ let host = url;
2537
+ host = host.slice(host.indexOf("://") + 3).split(/[?/]/)[0];
2538
+ host = decodeURIComponent(host.slice(host.indexOf("@") + 1));
2539
+ const urlObj = new URL(url.replace(host, host.split(",")[0]));
2540
+ return {
2541
+ url: {
2542
+ username: decodeURIComponent(urlObj.username),
2543
+ password: decodeURIComponent(urlObj.password),
2544
+ host: urlObj.host,
2545
+ hostname: urlObj.hostname,
2546
+ port: urlObj.port,
2547
+ pathname: urlObj.pathname,
2548
+ searchParams: urlObj.searchParams
2549
+ },
2550
+ multihost: host.indexOf(",") > -1 && host
2551
+ };
2552
+ }
2553
+ function osUsername() {
2554
+ try {
2555
+ return os.userInfo().username;
2556
+ } catch (_) {
2557
+ return process.env.USERNAME || process.env.USER || process.env.LOGNAME;
2558
+ }
2559
+ }
2560
+
2561
+ // ../../backend/src/queue/connection.ts
2562
+ function createBullMqConnection(redisUrl) {
2563
+ const url = new URL(redisUrl);
2564
+ if (url.protocol !== "redis:" && url.protocol !== "rediss:") {
2565
+ throw new Error("BullMQ requires a redis:// or rediss:// URL");
2566
+ }
2567
+ const database = url.pathname.slice(1);
2568
+ return {
2569
+ host: url.hostname,
2570
+ port: Number(url.port || 6379),
2571
+ username: url.username ? decodeURIComponent(url.username) : undefined,
2572
+ password: url.password ? decodeURIComponent(url.password) : undefined,
2573
+ db: database ? Number(database) : 0,
2574
+ tls: url.protocol === "rediss:" ? {} : undefined,
2575
+ maxRetriesPerRequest: null
2576
+ };
2577
+ }
2578
+
2579
+ // ../../backend/src/queue/names.ts
2580
+ var QUEUE_NAMES = {
2581
+ prepare: "hiai-docs-prepare-v1",
2582
+ embed: "hiai-docs-embed-v1",
2583
+ graph: "hiai-docs-graph-v1",
2584
+ summarize: "hiai-docs-summarize-v1",
2585
+ finalize: "hiai-docs-finalize-v1"
2586
+ };
2587
+ var DEFAULT_JOB_OPTIONS = {
2588
+ attempts: 5,
2589
+ backoff: { type: "exponential", delay: 1000 },
2590
+ removeOnComplete: { count: 1000 },
2591
+ removeOnFail: { count: 5000 }
2592
+ };
2593
+
2594
+ // ../../backend/src/queue/account-pipeline-cancellation.ts
2595
+ var STAGES = [
2596
+ "prepare",
2597
+ "embed",
2598
+ "graph",
2599
+ "summarize",
2600
+ "finalize"
2601
+ ];
2602
+ function createAccountPipelineCancellation(options) {
2603
+ const databaseClient = src_default(options.databaseUrl, {
2604
+ max: 4,
2605
+ idle_timeout: 30,
2606
+ connect_timeout: 10
2607
+ });
2608
+ const database = drizzle(databaseClient, { schema: exports_schema });
2609
+ const queues = STAGES.map((stage) => new Queue2(QUEUE_NAMES[stage], {
2610
+ connection: createBullMqConnection(options.redisUrl),
2611
+ defaultJobOptions: DEFAULT_JOB_OPTIONS
2612
+ }));
2613
+ const cancellationQueues = queues.map((queue) => ({
2614
+ getJobs: (states) => queue.getJobs(states)
2615
+ }));
2616
+ let closed = false;
2617
+ return {
2618
+ async cancelActorPipeline(actorUserId, signal) {
2619
+ if (closed)
2620
+ throw new Error("pipeline_cancellation_closed");
2621
+ let runs = 0;
2622
+ const total = await cancelAccountPipelineJobs(actorUserId, {
2623
+ queues: cancellationQueues,
2624
+ async cancelRuns(ownerId) {
2625
+ return database.transaction(async (tx) => {
2626
+ await tx.execute(sql2`SELECT set_config('app.current_user_id', ${ownerId}, true)`);
2627
+ await tx.execute(sql2`SELECT set_config('app.current_user_role', 'admin', true)`);
2628
+ await tx.execute(sql2`SELECT set_config('app.current_workspace_id', '', true)`);
2629
+ const cancelled = await tx.update(documentPipelineRuns).set({
2630
+ status: "cancelled",
2631
+ prepareStatus: "cancelled",
2632
+ embedStatus: "cancelled",
2633
+ graphStatus: "cancelled",
2634
+ summarizeStatus: "cancelled",
2635
+ finalizeStatus: "cancelled",
2636
+ errorCode: "account_cancelled",
2637
+ completedAt: new Date,
2638
+ updatedAt: new Date
2639
+ }).where(and(eq(documentPipelineRuns.ownerId, ownerId), ne(documentPipelineRuns.status, "cancelled"), inArray(documentPipelineRuns.status, [
2640
+ "pending",
2641
+ "processing",
2642
+ "retrying"
2643
+ ]))).returning({ generationId: documentPipelineRuns.generationId });
2644
+ if (cancelled.length > 0) {
2645
+ await tx.update(documentPipelineBatches).set({
2646
+ status: "cancelled",
2647
+ errorCode: "account_cancelled",
2648
+ updatedAt: new Date
2649
+ }).where(inArray(documentPipelineBatches.generationId, cancelled.map((row) => row.generationId)));
2650
+ }
2651
+ runs = cancelled.length;
2652
+ return runs;
2653
+ });
2654
+ }
2655
+ }, signal);
2656
+ return { runs, jobs: total - runs };
2657
+ },
2658
+ async close() {
2659
+ if (closed)
2660
+ return;
2661
+ closed = true;
2662
+ await Promise.all(queues.map((queue) => queue.close()));
2663
+ await databaseClient.end();
2664
+ }
2665
+ };
2666
+ }
2667
+ export {
2668
+ createAccountPipelineCancellation
2669
+ };