Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(whatsapp): store attachments as static files, like channel media (#8943)

Wolf Mermelstein7c22e2c8f656
diff --git a/.sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json b/.sqlx/query-0006d940d8e4b1032b1b73f1bcabfc41a88b46f544c726822ad0e9b848b5c690.json
similarity index 78%
rename from .sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json
rename to .sqlx/query-0006d940d8e4b1032b1b73f1bcabfc41a88b46f544c726822ad0e9b848b5c690.json
index 7ff02f07af..68d32f9b0f 100644
--- a/.sqlx/query-4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095.json
+++ b/.sqlx/query-0006d940d8e4b1032b1b73f1bcabfc41a88b46f544c726822ad0e9b848b5c690.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment a SET retry_at = now() + interval '5 minutes'\n FROM whatsapp_media_blob blob\n WHERE (a.binding_id, a.person_id, a.source_id, a.ordinal) IN (\n SELECT binding_id, person_id, source_id, ordinal FROM whatsapp_group_attachment\n WHERE state = 'downloaded' AND retry_at <= now()\n ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)\n AND blob.document_id = a.document_id\n RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.document_id, a.attempts,\n blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256",
+ "query": "UPDATE whatsapp_group_attachment a SET retry_at = now() + interval '5 minutes'\n FROM whatsapp_media_blob blob\n WHERE (a.binding_id, a.person_id, a.source_id, a.ordinal) IN (\n SELECT binding_id, person_id, source_id, ordinal FROM whatsapp_group_attachment\n WHERE state = 'downloaded' AND retry_at <= now()\n ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)\n AND blob.id = a.blob_id\n RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.blob_id, a.attempts,\n blob.group_id, blob.user_id, blob.filename, blob.mime",
"describe": {
"columns": [
{
@@ -25,7 +25,7 @@
},
{
"ordinal": 4,
- "name": "document_id",
+ "name": "blob_id",
"type_info": "Uuid"
},
{
@@ -52,11 +52,6 @@
"ordinal": 9,
"name": "mime",
"type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "sha256",
- "type_info": "Bytea"
}
],
"parameters": {
@@ -74,9 +69,8 @@
false,
false,
false,
- false,
false
]
},
- "hash": "4f38f67e58b2a59dd551ecca8d2b932dbce732e7ff74c33170c7cc771781b095"
+ "hash": "0006d940d8e4b1032b1b73f1bcabfc41a88b46f544c726822ad0e9b848b5c690"
}
diff --git a/.sqlx/query-06ce65435a471eac49a9c153cf97afe2aede91cf9f4e8f335530be0353a6d753.json b/.sqlx/query-06ce65435a471eac49a9c153cf97afe2aede91cf9f4e8f335530be0353a6d753.json
new file mode 100644
index 0000000000..27b5572d9a
--- /dev/null
+++ b/.sqlx/query-06ce65435a471eac49a9c153cf97afe2aede91cf9f4e8f335530be0353a6d753.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO whatsapp_group_attachment (binding_id, person_id, source_id, ordinal, blob_id, sha256, state, account_id, locator, mime, filename, size,\n width, height, duration_seconds, presentation)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)\n ON CONFLICT (binding_id, person_id, source_id, ordinal) DO UPDATE SET account_id = excluded.account_id, locator = excluded.locator\n WHERE whatsapp_group_attachment.state = 'pending'\n AND (whatsapp_group_attachment.claimed_until IS NULL OR whatsapp_group_attachment.claimed_until < now())",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Int2",
+ "Uuid",
+ "Bytea",
+ "Text",
+ "Uuid",
+ "Bytea",
+ "Text",
+ "Text",
+ "Int8",
+ "Int4",
+ "Int4",
+ "Int4",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "06ce65435a471eac49a9c153cf97afe2aede91cf9f4e8f335530be0353a6d753"
+}
diff --git a/.sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.json b/.sqlx/query-0945c57c4fa5ac773095b0d2be3432599d6b91c4f8b64e72ec08a0b608a67dcc.json
similarity index 85%
rename from .sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.json
rename to .sqlx/query-0945c57c4fa5ac773095b0d2be3432599d6b91c4f8b64e72ec08a0b608a67dcc.json
index 30f704b80f..c855971d0a 100644
--- a/.sqlx/query-325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67.json
+++ b/.sqlx/query-0945c57c4fa5ac773095b0d2be3432599d6b91c4f8b64e72ec08a0b608a67dcc.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",
+ "query": "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE id = $1",
"describe": {
"columns": [
{
@@ -42,5 +42,5 @@
true
]
},
- "hash": "325bc4556208b7bfc7afcdb7e7702fb1754ff7050af96e1c92a1a4ab12880f67"
+ "hash": "0945c57c4fa5ac773095b0d2be3432599d6b91c4f8b64e72ec08a0b608a67dcc"
}
diff --git a/.sqlx/query-1ec648607537f38f6f11d01800720aa9d036a1d349e2b3ff71c8ecb299720b5a.json b/.sqlx/query-1ec648607537f38f6f11d01800720aa9d036a1d349e2b3ff71c8ecb299720b5a.json
deleted file mode 100644
index 10b1e7e517..0000000000
--- a/.sqlx/query-1ec648607537f38f6f11d01800720aa9d036a1d349e2b3ff71c8ecb299720b5a.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO whatsapp_group_attachment (binding_id, person_id, source_id, ordinal, document_id, sha256, state, account_id, locator, mime, filename, size,\n width, height, duration_seconds, presentation)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)\n ON CONFLICT (binding_id, person_id, source_id, ordinal) DO UPDATE SET account_id = excluded.account_id, locator = excluded.locator\n WHERE whatsapp_group_attachment.state = 'pending'\n AND (whatsapp_group_attachment.claimed_until IS NULL OR whatsapp_group_attachment.claimed_until < now())",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text",
- "Int2",
- "Uuid",
- "Bytea",
- "Text",
- "Uuid",
- "Bytea",
- "Text",
- "Text",
- "Int8",
- "Int4",
- "Int4",
- "Int4",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "1ec648607537f38f6f11d01800720aa9d036a1d349e2b3ff71c8ecb299720b5a"
-}
diff --git a/.sqlx/query-9867744a1bd9199e10f86c3495e34112e6e052d426edc4a3781b97a68c3cf4ff.json b/.sqlx/query-26e91e35f12489f47cb5e12a76b4d3724a9f41eb8d473076512ce6fb41d8daaa.json
similarity index 51%
rename from .sqlx/query-9867744a1bd9199e10f86c3495e34112e6e052d426edc4a3781b97a68c3cf4ff.json
rename to .sqlx/query-26e91e35f12489f47cb5e12a76b4d3724a9f41eb8d473076512ce6fb41d8daaa.json
index ad2c2a8f92..af555d3fdd 100644
--- a/.sqlx/query-9867744a1bd9199e10f86c3495e34112e6e052d426edc4a3781b97a68c3cf4ff.json
+++ b/.sqlx/query-26e91e35f12489f47cb5e12a76b4d3724a9f41eb8d473076512ce6fb41d8daaa.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "DELETE FROM whatsapp_media_blob WHERE document_id = $1",
+ "query": "DELETE FROM whatsapp_media_blob WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
@@ -10,5 +10,5 @@
},
"nullable": []
},
- "hash": "9867744a1bd9199e10f86c3495e34112e6e052d426edc4a3781b97a68c3cf4ff"
+ "hash": "26e91e35f12489f47cb5e12a76b4d3724a9f41eb8d473076512ce6fb41d8daaa"
}
diff --git a/.sqlx/query-2eb85d8f868a76c45f990f4f94f4c206db1aacd8b84bd71894d6d41fcb90630b.json b/.sqlx/query-2eb85d8f868a76c45f990f4f94f4c206db1aacd8b84bd71894d6d41fcb90630b.json
new file mode 100644
index 0000000000..28c91e99e1
--- /dev/null
+++ b/.sqlx/query-2eb85d8f868a76c45f990f4f94f4c206db1aacd8b84bd71894d6d41fcb90630b.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_group_attachment SET blob_id = $4, state = 'downloaded', retry_at = now()\n WHERE binding_id = $1 AND person_id = $2 AND source_id = $3 AND ordinal = 0 AND state = 'pending'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2eb85d8f868a76c45f990f4f94f4c206db1aacd8b84bd71894d6d41fcb90630b"
+}
diff --git a/.sqlx/query-739be933b590e21d87681ef4cbdfb28c3e30223e01ecd48c65049d4d6a194062.json b/.sqlx/query-3d0050df307aa5e962255321171d17db50716dc0f63e7aa71afbec12c643e0a1.json
similarity index 71%
rename from .sqlx/query-739be933b590e21d87681ef4cbdfb28c3e30223e01ecd48c65049d4d6a194062.json
rename to .sqlx/query-3d0050df307aa5e962255321171d17db50716dc0f63e7aa71afbec12c643e0a1.json
index da1061db1d..d7b24127b4 100644
--- a/.sqlx/query-739be933b590e21d87681ef4cbdfb28c3e30223e01ecd48c65049d4d6a194062.json
+++ b/.sqlx/query-3d0050df307aa5e962255321171d17db50716dc0f63e7aa71afbec12c643e0a1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT m.message_id AS \"message_id!\", a.ordinal, a.state, a.filename, a.mime, a.size, a.document_id,\n a.width, a.height, a.duration_seconds, a.presentation\n FROM whatsapp_group_attachment a\n JOIN whatsapp_group_message m ON m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n WHERE a.binding_id = $1 AND m.message_id = ANY($2) AND a.state <> 'deleted'\n ORDER BY m.message_id, a.ordinal",
+ "query": "SELECT m.message_id AS \"message_id!\", a.ordinal, a.state, a.filename, a.mime, a.size, a.file_id,\n a.width, a.height, a.duration_seconds, a.presentation\n FROM whatsapp_group_attachment a\n JOIN whatsapp_group_message m ON m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n WHERE a.binding_id = $1 AND m.message_id = ANY($2) AND a.state <> 'deleted'\n ORDER BY m.message_id, a.ordinal",
"describe": {
"columns": [
{
@@ -35,7 +35,7 @@
},
{
"ordinal": 6,
- "name": "document_id",
+ "name": "file_id",
"type_info": "Uuid"
},
{
@@ -72,12 +72,12 @@
true,
true,
true,
- false,
+ true,
true,
true,
true,
true
]
},
- "hash": "739be933b590e21d87681ef4cbdfb28c3e30223e01ecd48c65049d4d6a194062"
+ "hash": "3d0050df307aa5e962255321171d17db50716dc0f63e7aa71afbec12c643e0a1"
}
diff --git a/.sqlx/query-b827af1bde86f6148320ff98befd13edb112ec15d7ecfb7777a33fbb0342b1f5.json b/.sqlx/query-543bd61c60b1faa671c5da8a6b2c6339bd9d9b871057430eae008edf3bcc88e0.json
similarity index 63%
rename from .sqlx/query-b827af1bde86f6148320ff98befd13edb112ec15d7ecfb7777a33fbb0342b1f5.json
rename to .sqlx/query-543bd61c60b1faa671c5da8a6b2c6339bd9d9b871057430eae008edf3bcc88e0.json
index 4c7454c871..1cfc5a82c9 100644
--- a/.sqlx/query-b827af1bde86f6148320ff98befd13edb112ec15d7ecfb7777a33fbb0342b1f5.json
+++ b/.sqlx/query-543bd61c60b1faa671c5da8a6b2c6339bd9d9b871057430eae008edf3bcc88e0.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "DELETE FROM whatsapp_media_blob b WHERE b.created_at < now() - interval '1 day'\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)",
+ "query": "DELETE FROM whatsapp_media_blob b WHERE b.created_at < now() - interval '1 day'\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.blob_id = b.id)",
"describe": {
"columns": [],
"parameters": {
@@ -8,5 +8,5 @@
},
"nullable": []
},
- "hash": "b827af1bde86f6148320ff98befd13edb112ec15d7ecfb7777a33fbb0342b1f5"
+ "hash": "543bd61c60b1faa671c5da8a6b2c6339bd9d9b871057430eae008edf3bcc88e0"
}
diff --git a/.sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json b/.sqlx/query-571506ea4ff3bea65b1a6554e631608821ebf5ff30930edb6ab86b5fd2b4a82f.json
similarity index 63%
rename from .sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json
rename to .sqlx/query-571506ea4ff3bea65b1a6554e631608821ebf5ff30930edb6ab86b5fd2b4a82f.json
index 594f9c4715..2cc16a3505 100644
--- a/.sqlx/query-6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74.json
+++ b/.sqlx/query-571506ea4ff3bea65b1a6554e631608821ebf5ff30930edb6ab86b5fd2b4a82f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT bytes FROM whatsapp_media_blob WHERE document_id = $1",
+ "query": "SELECT bytes FROM whatsapp_media_blob WHERE id = $1",
"describe": {
"columns": [
{
@@ -18,5 +18,5 @@
false
]
},
- "hash": "6e30f2660e2a2532a2fca9782b10e0a4695062e13992545fb920cdb6d7520e74"
+ "hash": "571506ea4ff3bea65b1a6554e631608821ebf5ff30930edb6ab86b5fd2b4a82f"
}
diff --git a/.sqlx/query-579c527e197c208822989bdeb5e37d014be1f59ee2937c88bd5081c5160996d0.json b/.sqlx/query-579c527e197c208822989bdeb5e37d014be1f59ee2937c88bd5081c5160996d0.json
deleted file mode 100644
index 6b2056cfea..0000000000
--- a/.sqlx/query-579c527e197c208822989bdeb5e37d014be1f59ee2937c88bd5081c5160996d0.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes)\n VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (document_id) DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Bytea",
- "Bytea"
- ]
- },
- "nullable": []
- },
- "hash": "579c527e197c208822989bdeb5e37d014be1f59ee2937c88bd5081c5160996d0"
-}
diff --git a/.sqlx/query-5951202c39fa5c15f699d23575572efac99ee12570f67658d8132303e1bca1e5.json b/.sqlx/query-5951202c39fa5c15f699d23575572efac99ee12570f67658d8132303e1bca1e5.json
new file mode 100644
index 0000000000..e8fb436652
--- /dev/null
+++ b/.sqlx/query-5951202c39fa5c15f699d23575572efac99ee12570f67658d8132303e1bca1e5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_file_deletion SET retry_at = now() + interval '5 minutes'\n WHERE file_id IN (\n SELECT file_id FROM whatsapp_file_deletion WHERE retry_at <= now()\n ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)\n RETURNING file_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "file_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "5951202c39fa5c15f699d23575572efac99ee12570f67658d8132303e1bca1e5"
+}
diff --git a/.sqlx/query-5de21b1d2cce37e49229b07b85782f8d5ede3d9189ec56c18aa6aa773a5c5acb.json b/.sqlx/query-5de21b1d2cce37e49229b07b85782f8d5ede3d9189ec56c18aa6aa773a5c5acb.json
new file mode 100644
index 0000000000..08c3cc5470
--- /dev/null
+++ b/.sqlx/query-5de21b1d2cce37e49229b07b85782f8d5ede3d9189ec56c18aa6aa773a5c5acb.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO whatsapp_file_deletion (file_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5de21b1d2cce37e49229b07b85782f8d5ede3d9189ec56c18aa6aa773a5c5acb"
+}
diff --git a/.sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json b/.sqlx/query-6265ce89ef6c4a9f51b14198ace78b615fe4037014cd390ab131f74c1569b95f.json
similarity index 59%
rename from .sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json
rename to .sqlx/query-6265ce89ef6c4a9f51b14198ace78b615fe4037014cd390ab131f74c1569b95f.json
index e6cdb8727d..36f3e09017 100644
--- a/.sqlx/query-979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4.json
+++ b/.sqlx/query-6265ce89ef6c4a9f51b14198ace78b615fe4037014cd390ab131f74c1569b95f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT mime FROM whatsapp_media_blob b\n WHERE document_id = $1 AND group_id = $2 AND user_id = $3\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)",
+ "query": "SELECT mime FROM whatsapp_media_blob b\n WHERE id = $1 AND group_id = $2 AND user_id = $3\n AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.blob_id = b.id)",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
false
]
},
- "hash": "979407c035898747bf4b3962791f0aae875d2c708fe650d1f60df0c9e6c4b0d4"
+ "hash": "6265ce89ef6c4a9f51b14198ace78b615fe4037014cd390ab131f74c1569b95f"
}
diff --git a/.sqlx/query-bbdc004911cbdaf82f97e26682029e9cbec7732f94a91ff6c31898f96a3cc99a.json b/.sqlx/query-721019d3636100443e9543bf934ea1b2df23316f9ba6b50b83211e4ef07bce0b.json
similarity index 66%
rename from .sqlx/query-bbdc004911cbdaf82f97e26682029e9cbec7732f94a91ff6c31898f96a3cc99a.json
rename to .sqlx/query-721019d3636100443e9543bf934ea1b2df23316f9ba6b50b83211e4ef07bce0b.json
index 4de1cfe202..21faaca904 100644
--- a/.sqlx/query-bbdc004911cbdaf82f97e26682029e9cbec7732f94a91ff6c31898f96a3cc99a.json
+++ b/.sqlx/query-721019d3636100443e9543bf934ea1b2df23316f9ba6b50b83211e4ef07bce0b.json
@@ -1,11 +1,11 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT a.document_id, a.sha256, a.state, a.mime AS \"mime!\", a.filename AS \"filename!\", b.id AS group_id, b.user_id\n FROM whatsapp_group_attachment a JOIN whatsapp_group b ON b.id = a.binding_id\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.account_id = $5\n FOR UPDATE OF a",
+ "query": "SELECT a.blob_id, a.sha256, a.state, a.mime AS \"mime!\", a.filename AS \"filename!\", b.id AS group_id, b.user_id\n FROM whatsapp_group_attachment a JOIN whatsapp_group b ON b.id = a.binding_id\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.account_id = $5\n FOR UPDATE OF a",
"describe": {
"columns": [
{
"ordinal": 0,
- "name": "document_id",
+ "name": "blob_id",
"type_info": "Uuid"
},
{
@@ -58,5 +58,5 @@
false
]
},
- "hash": "bbdc004911cbdaf82f97e26682029e9cbec7732f94a91ff6c31898f96a3cc99a"
+ "hash": "721019d3636100443e9543bf934ea1b2df23316f9ba6b50b83211e4ef07bce0b"
}
diff --git a/.sqlx/query-72eeee43625c3a400813333ccaa9b3a6272e3bb7199affad0d5b60f65cfb4c6e.json b/.sqlx/query-72eeee43625c3a400813333ccaa9b3a6272e3bb7199affad0d5b60f65cfb4c6e.json
deleted file mode 100644
index 355bc23c40..0000000000
--- a/.sqlx/query-72eeee43625c3a400813333ccaa9b3a6272e3bb7199affad0d5b60f65cfb4c6e.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- A WhatsApp attachment's document is viewable by whoever can view\n -- a chat whose live message holds it, through the chat's one access\n -- rule (whatsapp_group_access_level).\n SELECT 'view'::text AS access_level\n FROM whatsapp_group_attachment wa\n JOIN whatsapp_group_message wm\n ON wm.binding_id = wa.binding_id AND wm.person_id = wa.person_id AND wm.source_id = wa.source_id\n WHERE wa.document_id = $1 AND wa.state = 'ready' AND wm.deleted_at IS NULL\n AND whatsapp_group_access_level(wm.binding_id, $2) IS NOT NULL\n\n UNION ALL\n -- Source 2: document link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"Document\" document\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"documentId\" = document.id\n JOIN \"SharePermission\" share_permission\n ON share_permission.id = document_permission.\"sharePermissionId\"\n WHERE document.id = $3\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM owner_team(document.owner) owner_team\n WHERE owner_team.team_id::text = ANY($2)\n )\n )\n )\n\n UNION ALL\n -- Source 3: email-attachment documents inherit access from any\n -- linked thread the caller can reach. Owning or being delegated\n -- the thread's inbox (macro_user_links) grants Edit, mirroring\n -- calendar-event delegation. A thread-level entity_access grant\n -- inherits as View regardless of its level: a SHA-deduped document\n -- can back attachments in other threads with different audiences,\n -- so a per-thread share must not confer write access to it.\n SELECT CASE\n WHEN l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n THEN 'edit'\n ELSE 'view'\n END AS access_level\n FROM document_email de\n JOIN email_attachments ea ON ea.id = de.email_attachment_id\n JOIN email_messages em ON em.id = ea.message_id\n JOIN email_threads t ON t.id = em.thread_id\n JOIN email_links l ON l.id = t.link_id\n WHERE de.document_id = $3\n AND (\n l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n OR EXISTS (\n SELECT 1\n FROM entity_access thread_access\n WHERE thread_access.entity_id = t.id\n AND thread_access.entity_type = 'email_thread'\n AND thread_access.source_id = ANY($2)\n )\n )\n\n UNION ALL\n -- Source 4: a file attached to a document discussion is visible to\n -- current viewers of that document. Removing the attachment, the\n -- discussion, or the parent grant removes this path; it never\n -- shares the parent itself.\n SELECT 'view' AS access_level\n FROM comms_attachments a\n JOIN comms_messages m ON m.id = a.message_id\n JOIN comms_message_threads mt ON mt.root_id = COALESCE(m.thread_id, m.id)\n JOIN \"Document\" parent_doc\n ON m.parent_entity_type = 'document' AND parent_doc.id = m.parent_entity_id\n LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = parent_doc.id\n LEFT JOIN \"SharePermission\" sp ON sp.id = dp.\"sharePermissionId\"\n WHERE a.entity_type = 'document'\n AND a.entity_id = $3\n AND m.deleted_at IS NULL\n AND mt.deleted_at IS NULL\n AND parent_doc.\"deletedAt\" IS NULL\n AND (\n parent_doc.owner = $4\n OR EXISTS (\n SELECT 1\n FROM entity_access pa\n WHERE pa.entity_type = 'document'\n AND pa.entity_id::text = parent_doc.id\n AND pa.source_id = ANY($2)\n )\n OR (\n sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM owner_team(parent_doc.owner) tu\n WHERE tu.team_id::text = ANY($2)\n )\n )\n )\n )\n )\n ) AS combined_access\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "72eeee43625c3a400813333ccaa9b3a6272e3bb7199affad0d5b60f65cfb4c6e"
-}
diff --git a/.sqlx/query-81ba973cc5b02d72d9ed85f590af3652018b54f98b4c9cab0794e2d1656356d6.json b/.sqlx/query-81ba973cc5b02d72d9ed85f590af3652018b54f98b4c9cab0794e2d1656356d6.json
new file mode 100644
index 0000000000..fc1dabd69b
--- /dev/null
+++ b/.sqlx/query-81ba973cc5b02d72d9ed85f590af3652018b54f98b4c9cab0794e2d1656356d6.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO whatsapp_media_blob (id, group_id, user_id, mime, filename, sha256, bytes)\n VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Bytea",
+ "Bytea"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "81ba973cc5b02d72d9ed85f590af3652018b54f98b4c9cab0794e2d1656356d6"
+}
diff --git a/.sqlx/query-8611553ad006066cda380b1e22f586bdac484ea189aae8dca521d3070c13e76e.json b/.sqlx/query-8611553ad006066cda380b1e22f586bdac484ea189aae8dca521d3070c13e76e.json
new file mode 100644
index 0000000000..43c6aa13dc
--- /dev/null
+++ b/.sqlx/query-8611553ad006066cda380b1e22f586bdac484ea189aae8dca521d3070c13e76e.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: document link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"Document\" document\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"documentId\" = document.id\n JOIN \"SharePermission\" share_permission\n ON share_permission.id = document_permission.\"sharePermissionId\"\n WHERE document.id = $3\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM owner_team(document.owner) owner_team\n WHERE owner_team.team_id::text = ANY($2)\n )\n )\n )\n\n UNION ALL\n -- Source 3: email-attachment documents inherit access from any\n -- linked thread the caller can reach. Owning or being delegated\n -- the thread's inbox (macro_user_links) grants Edit, mirroring\n -- calendar-event delegation. A thread-level entity_access grant\n -- inherits as View regardless of its level: a SHA-deduped document\n -- can back attachments in other threads with different audiences,\n -- so a per-thread share must not confer write access to it.\n SELECT CASE\n WHEN l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n THEN 'edit'\n ELSE 'view'\n END AS access_level\n FROM document_email de\n JOIN email_attachments ea ON ea.id = de.email_attachment_id\n JOIN email_messages em ON em.id = ea.message_id\n JOIN email_threads t ON t.id = em.thread_id\n JOIN email_links l ON l.id = t.link_id\n WHERE de.document_id = $3\n AND (\n l.macro_id = $4\n OR EXISTS (\n SELECT 1\n FROM macro_user_links mul\n WHERE mul.link_id = l.id\n AND mul.primary_macro_id = $4\n )\n OR EXISTS (\n SELECT 1\n FROM entity_access thread_access\n WHERE thread_access.entity_id = t.id\n AND thread_access.entity_type = 'email_thread'\n AND thread_access.source_id = ANY($2)\n )\n )\n\n UNION ALL\n -- Source 4: a file attached to a document discussion is visible to\n -- current viewers of that document. Removing the attachment, the\n -- discussion, or the parent grant removes this path; it never\n -- shares the parent itself.\n SELECT 'view' AS access_level\n FROM comms_attachments a\n JOIN comms_messages m ON m.id = a.message_id\n JOIN comms_message_threads mt ON mt.root_id = COALESCE(m.thread_id, m.id)\n JOIN \"Document\" parent_doc\n ON m.parent_entity_type = 'document' AND parent_doc.id = m.parent_entity_id\n LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = parent_doc.id\n LEFT JOIN \"SharePermission\" sp ON sp.id = dp.\"sharePermissionId\"\n WHERE a.entity_type = 'document'\n AND a.entity_id = $3\n AND m.deleted_at IS NULL\n AND mt.deleted_at IS NULL\n AND parent_doc.\"deletedAt\" IS NULL\n AND (\n parent_doc.owner = $4\n OR EXISTS (\n SELECT 1\n FROM entity_access pa\n WHERE pa.entity_type = 'document'\n AND pa.entity_id::text = parent_doc.id\n AND pa.source_id = ANY($2)\n )\n OR (\n sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM owner_team(parent_doc.owner) tu\n WHERE tu.team_id::text = ANY($2)\n )\n )\n )\n )\n )\n ) AS combined_access\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "8611553ad006066cda380b1e22f586bdac484ea189aae8dca521d3070c13e76e"
+}
diff --git a/.sqlx/query-eb29364085282746d6dda6c0332eaca071da547e59356f80f2db960df706ae8d.json b/.sqlx/query-8ce95f39264cdf91060fa85c1c633224871c8a08ba9c11803c36acdeb0944226.json
similarity index 85%
rename from .sqlx/query-eb29364085282746d6dda6c0332eaca071da547e59356f80f2db960df706ae8d.json
rename to .sqlx/query-8ce95f39264cdf91060fa85c1c633224871c8a08ba9c11803c36acdeb0944226.json
index 820fdba25e..3ba573b1bb 100644
--- a/.sqlx/query-eb29364085282746d6dda6c0332eaca071da547e59356f80f2db960df706ae8d.json
+++ b/.sqlx/query-8ce95f39264cdf91060fa85c1c633224871c8a08ba9c11803c36acdeb0944226.json
@@ -1,11 +1,11 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment a SET state = 'failed', claimed_until = NULL, locator = NULL\n FROM whatsapp_group_message m, whatsapp_group b\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4\n AND a.state IN ('pending', 'downloaded')\n AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n AND b.id = a.binding_id\n RETURNING a.document_id, a.filename, m.message_id, b.id AS group_id",
+ "query": "UPDATE whatsapp_group_attachment a SET state = 'failed', claimed_until = NULL, locator = NULL\n FROM whatsapp_group_message m, whatsapp_group b\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4\n AND a.state IN ('pending', 'downloaded')\n AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n AND b.id = a.binding_id\n RETURNING a.blob_id, a.filename, m.message_id, b.id AS group_id",
"describe": {
"columns": [
{
"ordinal": 0,
- "name": "document_id",
+ "name": "blob_id",
"type_info": "Uuid"
},
{
@@ -39,5 +39,5 @@
false
]
},
- "hash": "eb29364085282746d6dda6c0332eaca071da547e59356f80f2db960df706ae8d"
+ "hash": "8ce95f39264cdf91060fa85c1c633224871c8a08ba9c11803c36acdeb0944226"
}
diff --git a/.sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.json b/.sqlx/query-93924a033844b84c675c9091242401be1cf0d8de48853d08fadc5136a544de2d.json
similarity index 51%
rename from .sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.json
rename to .sqlx/query-93924a033844b84c675c9091242401be1cf0d8de48853d08fadc5136a544de2d.json
index 51de495444..42a677b765 100644
--- a/.sqlx/query-07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554.json
+++ b/.sqlx/query-93924a033844b84c675c9091242401be1cf0d8de48853d08fadc5136a544de2d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
+ "query": "INSERT INTO whatsapp_media_blob (id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
"describe": {
"columns": [],
"parameters": {
@@ -19,5 +19,5 @@
},
"nullable": []
},
- "hash": "07e87b3e4c647003f48d8e7069d13cefd058b0e76e5a6916d3a78c60782a7554"
+ "hash": "93924a033844b84c675c9091242401be1cf0d8de48853d08fadc5136a544de2d"
}
diff --git a/.sqlx/query-95faf4921364a34f0249e1fdcc81ed2b021f31bfa45555622ac20d5025a20e9e.json b/.sqlx/query-95faf4921364a34f0249e1fdcc81ed2b021f31bfa45555622ac20d5025a20e9e.json
deleted file mode 100644
index db6029c5ad..0000000000
--- a/.sqlx/query-95faf4921364a34f0249e1fdcc81ed2b021f31bfa45555622ac20d5025a20e9e.json
+++ /dev/null
@@ -1,25 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment a SET state = 'ready'\n FROM whatsapp_group_message m\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.state = 'downloaded'\n AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n RETURNING m.message_id",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "message_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text",
- "Int2"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "95faf4921364a34f0249e1fdcc81ed2b021f31bfa45555622ac20d5025a20e9e"
-}
diff --git a/.sqlx/query-96d0317ed6e1bb0102aa24655c129e2469a99fe4af71d6a3ae2f41c963ab40b0.json b/.sqlx/query-96d0317ed6e1bb0102aa24655c129e2469a99fe4af71d6a3ae2f41c963ab40b0.json
deleted file mode 100644
index 5fbd8da084..0000000000
--- a/.sqlx/query-96d0317ed6e1bb0102aa24655c129e2469a99fe4af71d6a3ae2f41c963ab40b0.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment SET document_id = $4, state = 'downloaded', retry_at = now()\n WHERE binding_id = $1 AND person_id = $2 AND source_id = $3 AND ordinal = 0 AND state = 'pending'",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "96d0317ed6e1bb0102aa24655c129e2469a99fe4af71d6a3ae2f41c963ab40b0"
-}
diff --git a/.sqlx/query-b997304721b20554d240220adc43275a075f5979f7233709a2d0e3a88e73c4b2.json b/.sqlx/query-b997304721b20554d240220adc43275a075f5979f7233709a2d0e3a88e73c4b2.json
new file mode 100644
index 0000000000..b2bed12f32
--- /dev/null
+++ b/.sqlx/query-b997304721b20554d240220adc43275a075f5979f7233709a2d0e3a88e73c4b2.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM whatsapp_file_deletion WHERE file_id = ANY($1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b997304721b20554d240220adc43275a075f5979f7233709a2d0e3a88e73c4b2"
+}
diff --git a/.sqlx/query-192cc97742e87d07e0bdfdc893de93c2ccc2d9ceeac85c3c48cf84c56a4d223a.json b/.sqlx/query-c047645a30de3ee9038dc99e7d293de8b88f39a302c69ff5f422984d867453f1.json
similarity index 61%
rename from .sqlx/query-192cc97742e87d07e0bdfdc893de93c2ccc2d9ceeac85c3c48cf84c56a4d223a.json
rename to .sqlx/query-c047645a30de3ee9038dc99e7d293de8b88f39a302c69ff5f422984d867453f1.json
index 720e278f96..e9d61c2772 100644
--- a/.sqlx/query-192cc97742e87d07e0bdfdc893de93c2ccc2d9ceeac85c3c48cf84c56a4d223a.json
+++ b/.sqlx/query-c047645a30de3ee9038dc99e7d293de8b88f39a302c69ff5f422984d867453f1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "UPDATE whatsapp_group_attachment SET state = 'deleted' WHERE binding_id = $1 AND person_id = $2 AND source_id = $3",
+ "query": "UPDATE whatsapp_group_attachment SET state = 'deleted', file_id = NULL WHERE binding_id = $1 AND person_id = $2 AND source_id = $3",
"describe": {
"columns": [],
"parameters": {
@@ -12,5 +12,5 @@
},
"nullable": []
},
- "hash": "192cc97742e87d07e0bdfdc893de93c2ccc2d9ceeac85c3c48cf84c56a4d223a"
+ "hash": "c047645a30de3ee9038dc99e7d293de8b88f39a302c69ff5f422984d867453f1"
}
diff --git a/.sqlx/query-c185f99c645c328a2110c98defc2a39303911d5dae6f9a849f5292c1db942ebc.json b/.sqlx/query-c185f99c645c328a2110c98defc2a39303911d5dae6f9a849f5292c1db942ebc.json
new file mode 100644
index 0000000000..f09c0615a2
--- /dev/null
+++ b/.sqlx/query-c185f99c645c328a2110c98defc2a39303911d5dae6f9a849f5292c1db942ebc.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE whatsapp_group_attachment a SET state = 'ready', file_id = $5\n FROM whatsapp_group_message m\n WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.state = 'downloaded'\n AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id\n RETURNING m.message_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "message_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Int2",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "c185f99c645c328a2110c98defc2a39303911d5dae6f9a849f5292c1db942ebc"
+}
diff --git a/.sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json b/.sqlx/query-f0efec994f5c67968d7d16055f3567b08409f634fbf0225c0cc9fca715e852f3.json
similarity index 61%
rename from .sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json
rename to .sqlx/query-f0efec994f5c67968d7d16055f3567b08409f634fbf0225c0cc9fca715e852f3.json
index ff2046113d..5d598cd83f 100644
--- a/.sqlx/query-2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d.json
+++ b/.sqlx/query-f0efec994f5c67968d7d16055f3567b08409f634fbf0225c0cc9fca715e852f3.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s\n JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'uploadId')::uuid\n AND b.user_id = s.user_id AND b.group_id = s.group_id\n WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'\n AND s.payload->'message'->>'type' = 'media'",
+ "query": "SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s\n JOIN whatsapp_media_blob b ON b.id = (s.payload->'message'->>'uploadId')::uuid\n AND b.user_id = s.user_id AND b.group_id = s.group_id\n WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'\n AND s.payload->'message'->>'type' = 'media'",
"describe": {
"columns": [
{
@@ -38,5 +38,5 @@
false
]
},
- "hash": "2123bcd331ed8eef32d42179398b1b8a19abf2243e793918bbb89dbc6ae0433d"
+ "hash": "f0efec994f5c67968d7d16055f3567b08409f634fbf0225c0cc9fca715e852f3"
}
diff --git a/.sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.json b/.sqlx/query-f85f18d0839a3ebb6c70f29f10e92b9db99b980b3258ff8c9485e776b49b4d57.json
similarity index 90%
rename from .sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.json
rename to .sqlx/query-f85f18d0839a3ebb6c70f29f10e92b9db99b980b3258ff8c9485e776b49b4d57.json
index 83b953f94c..b36f30ff56 100644
--- a/.sqlx/query-792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53.json
+++ b/.sqlx/query-f85f18d0839a3ebb6c70f29f10e92b9db99b980b3258ff8c9485e776b49b4d57.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",
+ "query": "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE id = $1",
"describe": {
"columns": [
{
@@ -54,5 +54,5 @@
true
]
},
- "hash": "792b0e56cb37594f6a5473fdc1fe12206b1492433fd4e99fb90964292329cf53"
+ "hash": "f85f18d0839a3ebb6c70f29f10e92b9db99b980b3258ff8c9485e776b49b4d57"
}
diff --git a/apps/web/src/features/whatsapp-group/AGENTS.md b/apps/web/src/features/whatsapp-group/AGENTS.md
index cfe371fd34..abaada263e 100644
--- a/apps/web/src/features/whatsapp-group/AGENTS.md
+++ b/apps/web/src/features/whatsapp-group/AGENTS.md
@@ -55,21 +55,23 @@ lists belong to `features/whatsapp-linked` and `features/external-view`.
above, and says "Importing history…" / "Waiting for … phone" until DSS
reports `done` or `partial`. `waiting_for_message` (no message to import
from yet) shows nothing.
-- Images, video and audio play inline: `fileUrl` resolves the imported
- document's presigned URL and `InboundMedia` hands it to Chat's
- `MediaPreview` (or an audio player); `groupMessageData` keeps them out of
- the document chips. DSS's declared width/height reserve the space (keeps
+- Attachments are static files, like Chat's media: `fileUrl` is
+ `staticFileIdEndpoint`, and images take Chat's sized variants. Images,
+ video and audio play inline: `InboundMedia` hands them to Chat's
+ `MediaPreview` (or an audio player); other ready files are
+ `AttachmentChip` links that open the file. `groupMessageData` passes no
+ attachments to the channel row. DSS's declared width/height reserve the space (keeps
the open-at-bottom scroll right); stickers, GIFs and voice notes follow the
- attachment's `presentation`. A file whose URL can't be resolved, or whose
- image, video or audio fails to load (expired or missing), shows
+ attachment's `presentation`. A file whose image, video or audio fails to
+ load (deleted or missing), shows
"Attachment unavailable" instead of loading forever (Chat's media tiles
report it through `MediaPreview`'s `onError`).
- The timeline and composer use Chat's layout (`macro-message-width` column,
`CustomScrollbar`, `ChannelInputContainer` → centered column). The view
follows the bottom (a `ResizeObserver` on the content) until the reader
scrolls by intent (wheel, touch, keys, scrollbar); layout-driven scroll
- events never change that. Media URLs keep their first presigned URL and
- memoized items so refetches don't remount or reload them.
+ events never change that. Media keep their memoized items so refetches
+ don't remount or reload them.
- Files this page sent keep their local preview and size on the stored
message (`conversation.sentFiles`), so the swap from pending neither
flashes nor jumps.
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx b/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
index ac9c6858c8..92e507a1c6 100644
--- a/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
+++ b/apps/web/src/features/whatsapp-group/components/inbound-attachment.tsx
@@ -1,11 +1,53 @@
+import FileIcon from '@phosphor/file.svg';
import SpinnerIcon from '@phosphor/spinner.svg';
import WarningIcon from '@phosphor/warning-circle.svg';
-import { Match, Switch } from 'solid-js';
+import { Match, Show, Switch } from 'solid-js';
+import type { InboundAttachment } from '../core/attachments';
/**
- * A WhatsApp file that isn't a Macro document yet (still importing, failed,
- * or of a kind Macro can't keep), or one whose file can't be fetched. Every state is the same height, so the
- * channel doesn't jump when it resolves.
+ * A file that doesn't play inline: once stored, a chip that opens it (like
+ * a PDF from Chat), otherwise its placeholder.
+ */
+export function AttachmentChip(props: {
+ attachment: InboundAttachment;
+ url: (fileId: string) => string;
+}) {
+ const stored = () =>
+ props.attachment.state === 'ready' ? props.attachment.fileId : undefined;
+ return (
+ <Show
+ when={stored()}
+ fallback={
+ <InboundAttachmentPlaceholder
+ state={
+ props.attachment.state === 'ready'
+ ? 'loading'
+ : props.attachment.state
+ }
+ fileName={props.attachment.fileName}
+ />
+ }
+ >
+ {(fileId) => (
+ <a
+ href={props.url(fileId())}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="flex h-12 max-w-sm items-center gap-2 rounded-lg border border-edge-muted px-3 text-sm text-ink hover:bg-hover"
+ data-linked-inbound-attachment="ready"
+ >
+ <FileIcon class="size-4 shrink-0" aria-hidden="true" />
+ <span class="min-w-0 truncate">{props.attachment.fileName}</span>
+ </a>
+ )}
+ </Show>
+ );
+}
+
+/**
+ * A WhatsApp file that isn't stored yet (still importing, failed, or of a
+ * kind Macro can't keep), or one whose file can't be fetched. Every state is
+ * the same height, so the channel doesn't jump when it resolves.
*/
export function InboundAttachmentPlaceholder(props: {
state: 'loading' | 'unavailable' | 'unsupported';
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx
index 772a2892f5..3f280b1440 100644
--- a/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx
+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.test.tsx
@@ -23,22 +23,11 @@ it('shows a file that fails to load as unavailable instead of loading forever',
url: 'https://files.example.test/expired-voice',
presentation: 'voice_note',
},
- {
- id: 'sticker',
- kind: 'image',
- fileName: 'sticker.webp',
- url: undefined,
- unavailable: true,
- presentation: 'sticker',
- },
]}
/>
));
- expect(screen.getByText('Attachment unavailable: sticker.webp')).toBeTruthy();
- expect(screen.queryByLabelText('Loading sticker.webp')).toBeNull();
-
const photo = container.querySelector(
- 'img[src="https://files.example.test/expired-photo"]'
+ 'img[src^="https://files.example.test/expired-photo"]'
);
const voice = container.querySelector('audio');
if (!photo || !voice) throw new Error('media not rendered');
@@ -49,7 +38,7 @@ it('shows a file that fails to load as unavailable instead of loading forever',
expect(screen.getByText('Attachment unavailable: voice.ogg')).toBeTruthy();
expect(
container.querySelector(
- 'img[src="https://files.example.test/expired-photo"]'
+ 'img[src^="https://files.example.test/expired-photo"]'
)
).toBeNull();
expect(container.querySelector('audio')).toBeNull();
diff --git a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
index 14dbc9d9b2..0ae5a70240 100644
--- a/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
+++ b/apps/web/src/features/whatsapp-group/components/inbound-media.tsx
@@ -1,20 +1,19 @@
import type { MediaItem } from '@channel/Media/media-items';
import { MediaPreview } from '@channel/Message/MediaPreview';
+import { staticFileSizedUrl } from '@core/constant/servers';
import { constrainImageDimensions } from '@macro-inc/lexical-core/utils/media';
import MicrophoneIcon from '@phosphor/microphone.svg';
import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
import { formatDuration } from '../core/rich';
import { InboundAttachmentPlaceholder } from './inbound-attachment';
-/** An imported image, video or voice note with its resolved file URL. */
+/** A stored image, video or voice note with its static file URL. */
export type InboundMediaFile = {
id: string;
kind: 'image' | 'video' | 'audio';
fileName: string;
- /** Undefined while the URL resolves. */
+ /** The stored file, else the local preview of a file this page sent. */
url: string | undefined;
- /** The URL couldn't be resolved (the file is gone or not readable). */
- unavailable?: boolean;
/** A local preview shown until `url` loads (files this page sent). */
previewUrl?: string;
/** Declared by WhatsApp; reserves the space before the file loads. */
@@ -161,8 +160,7 @@ function Audio(props: { file: InboundMediaFile; onError: () => void }) {
export function InboundMedia(props: { files: InboundMediaFile[] }) {
const [failed, setFailed] = createSignal<ReadonlySet<string>>(new Set());
const fail = (id: string) => setFailed((ids) => new Set(ids).add(id));
- const usable = (file: InboundMediaFile) =>
- !file.unavailable && !failed().has(file.id);
+ const usable = (file: InboundMediaFile) => !failed().has(file.id);
const grid = () =>
props.files.filter(
(file) =>
@@ -177,9 +175,17 @@ export function InboundMedia(props: { files: InboundMediaFile[] }) {
(previous: MediaItem[]) =>
grid().flatMap((file): MediaItem[] => {
if (!file.url || file.kind === 'audio') return [];
+ // Sized like Chat's static images (a local preview stays as is).
const item: MediaItem = {
id: file.id,
- src: file.url,
+ src:
+ file.kind === 'image'
+ ? staticFileSizedUrl(file.url, 'medium')
+ : file.url,
+ thumbSrc:
+ file.kind === 'image'
+ ? staticFileSizedUrl(file.url, 'small')
+ : undefined,
fullSrc: file.url,
previewSrc: file.previewUrl,
kind: file.kind,
diff --git a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
index f070f40f7a..152cc0fac8 100644
--- a/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
+++ b/apps/web/src/features/whatsapp-group/context/whatsapp-group-context.tsx
@@ -33,8 +33,8 @@ export type WhatsAppGroupCapabilities = {
upload: (
file: File
) => Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>>;
- /** A short-lived URL for an imported file's bytes, to play it inline. */
- fileUrl: (documentId: Accessor<string>) => SourceRead<string>;
+ /** A stored file's URL, resolved like Chat's static media. */
+ fileUrl: (fileId: string) => string;
markRead: (messageId: string) => Promise<unknown>;
stopSync: () => Promise<unknown>;
};
diff --git a/apps/web/src/features/whatsapp-group/core/attachments.ts b/apps/web/src/features/whatsapp-group/core/attachments.ts
index ebf9577a85..49ffd19346 100644
--- a/apps/web/src/features/whatsapp-group/core/attachments.ts
+++ b/apps/web/src/features/whatsapp-group/core/attachments.ts
@@ -4,8 +4,8 @@ export type InboundAttachment = {
state: 'loading' | 'ready' | 'unavailable' | 'unsupported';
fileName: string;
mime: string;
- /** The Macro document holding the file, once ready. */
- documentId: string | undefined;
+ /** The static file holding it, once ready. */
+ fileId: string | undefined;
/** As WhatsApp declared them, to reserve space before the file loads. */
width?: number;
height?: number;
@@ -21,7 +21,7 @@ export function inlineMediaKind(
): 'image' | 'video' | 'audio' | undefined {
if (
attachment.state !== 'ready' ||
- !(attachment.documentId || attachment.previewUrl)
+ !(attachment.fileId || attachment.previewUrl)
)
return undefined;
const type = attachment.mime.split('/')[0];
diff --git a/apps/web/src/features/whatsapp-group/core/message-data.ts b/apps/web/src/features/whatsapp-group/core/message-data.ts
index 3caad99b73..be86c2a9a8 100644
--- a/apps/web/src/features/whatsapp-group/core/message-data.ts
+++ b/apps/web/src/features/whatsapp-group/core/message-data.ts
@@ -1,5 +1,4 @@
import type { MessageData } from '@core/messages/types';
-import { inlineMediaKind } from './attachments';
import { whatsappToMarkdown } from './formatting';
import type { GroupMessage } from './group';
@@ -26,22 +25,9 @@ export function groupMessageData(
updated_at: message.sentAt,
edited_at: message.edited ? message.sentAt : null,
deleted_at: message.deleted ? message.sentAt : null,
- // Images, video and audio play inline (the view renders them); other
- // files show as document chips.
- attachments: message.attachments.flatMap((attachment) =>
- attachment.state === 'ready' &&
- attachment.documentId &&
- !inlineMediaKind(attachment)
- ? [
- {
- id: `${message.id}:${attachment.ordinal}`,
- entity_id: attachment.documentId,
- entity_type: 'document',
- created_at: message.sentAt,
- },
- ]
- : []
- ),
+ // Attachments are static files the view renders itself: media inline,
+ // other files as chips that open them.
+ attachments: [],
// WhatsApp reports counts, not reactors; others stay unnamed.
reactions: message.reactions.map((reaction) => {
const mine = reaction.mine && viewerId ? [viewerId] : [];
diff --git a/apps/web/src/features/whatsapp-group/primitives/conversation.ts b/apps/web/src/features/whatsapp-group/primitives/conversation.ts
index 0e041dc030..2153c4dccb 100644
--- a/apps/web/src/features/whatsapp-group/primitives/conversation.ts
+++ b/apps/web/src/features/whatsapp-group/primitives/conversation.ts
@@ -49,7 +49,7 @@ function sentAttachment(file: DraftFile, ordinal: number): InboundAttachment {
state: visual ? 'ready' : 'loading',
fileName: file.name,
mime: file.mime ?? '',
- documentId: undefined,
+ fileId: undefined,
previewUrl: file.previewUrl,
width: file.width,
height: file.height,
diff --git a/apps/web/src/features/whatsapp-group/queries/capabilities.ts b/apps/web/src/features/whatsapp-group/queries/capabilities.ts
index fc743e9545..b967eb9191 100644
--- a/apps/web/src/features/whatsapp-group/queries/capabilities.ts
+++ b/apps/web/src/features/whatsapp-group/queries/capabilities.ts
@@ -1,7 +1,7 @@
+import { staticFileIdEndpoint } from '@core/constant/servers';
import { fireAndForget } from '@core/util/fireAndForget';
import { Telemetry } from '@macro-inc/observability';
import { queryReadyGate } from '@queries/gate';
-import { useBinaryDocumentQuery } from '@queries/storage/binary-document';
import {
invalidateWhatsappGroup,
invalidateWhatsappGroupList,
@@ -146,7 +146,7 @@ export function createWhatsAppGroupCapabilities(
);
return result;
}),
- fileUrl: (documentId) => sourceRead(useBinaryDocumentQuery(documentId)),
+ fileUrl: staticFileIdEndpoint,
markRead: async (messageId) => {
await whatsappOperation(
'group.read',
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
index d62a025b3c..983b6a153c 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.test.ts
@@ -88,7 +88,7 @@ it('decodes pagination, deleted flags, reaction ownership and attachment states
fileName: 'drawing.psd',
mime: 'image/vnd.adobe.photoshop',
size: 1024,
- documentId: null,
+ fileId: null,
},
],
deliveryState: null,
@@ -104,7 +104,7 @@ it('decodes pagination, deleted flags, reaction ownership and attachment states
sender: { name: 'Ana Ruiz' },
reactions: [{ emoji: '👍', count: 2, mine: true }],
attachments: [
- { state: 'unsupported', fileName: 'drawing.psd', documentId: undefined },
+ { state: 'unsupported', fileName: 'drawing.psd', fileId: undefined },
],
});
});
@@ -150,7 +150,7 @@ it('decodes mentions, forwarding, media presentation and every rich type, keepin
fileName: 'sticker.webp',
mime: 'image/webp',
size: 2048,
- documentId: 'doc-1',
+ fileId: 'file-1',
width: 512,
height: 512,
durationSeconds: null,
diff --git a/apps/web/src/features/whatsapp-group/queries/production-api.ts b/apps/web/src/features/whatsapp-group/queries/production-api.ts
index b01c57e22a..372a8e825d 100644
--- a/apps/web/src/features/whatsapp-group/queries/production-api.ts
+++ b/apps/web/src/features/whatsapp-group/queries/production-api.ts
@@ -294,7 +294,7 @@ export const whatsappGroupApi: WhatsAppGroupApi = {
state: attachment.state,
fileName: attachment.fileName,
mime: attachment.mime,
- documentId: attachment.documentId ?? undefined,
+ fileId: attachment.fileId ?? undefined,
width: attachment.width ?? undefined,
height: attachment.height ?? undefined,
durationSeconds: attachment.durationSeconds ?? undefined,
diff --git a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
index a5948dbd0d..bd9e178b0b 100644
--- a/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
+++ b/apps/web/src/features/whatsapp-group/tests/fake-capabilities.ts
@@ -93,8 +93,7 @@ export function createFakeGroup(
): Promise<Result<{ uploadId: string; audio: boolean }, SendFailure>> =>
ok({ uploadId: 'upload-1', audio: false })
),
- fileUrl: (documentId: () => string) =>
- read(() => `https://files.example.test/${documentId()}`),
+ fileUrl: (fileId: string) => `https://files.example.test/${fileId}`,
markRead: vi.fn(async (_messageId: string) => undefined),
stopSync: vi.fn(async () => undefined),
} satisfies WhatsAppGroupCapabilities;
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
index 28181273ed..bd42b5afef 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.test.tsx
@@ -268,7 +268,7 @@ it('tells a shared viewer whose phone the import waits for', () => {
expect(screen.queryByText(/No messages yet/)).toBeNull();
});
-it('plays imported images and voice notes inline, like Chat', () => {
+it('plays stored images and voice notes inline, like Chat, and opens other files', () => {
const fake = createFakeGroup({
messages: [
{
@@ -280,14 +280,21 @@ it('plays imported images and voice notes inline, like Chat', () => {
state: 'ready',
fileName: 'photo.jpeg',
mime: 'image/jpeg',
- documentId: 'document-photo',
+ fileId: 'file-photo',
},
{
ordinal: 1,
state: 'ready',
fileName: 'voice.ogg',
mime: 'audio/ogg',
- documentId: 'document-voice',
+ fileId: 'file-voice',
+ },
+ {
+ ordinal: 2,
+ state: 'ready',
+ fileName: 'quote.pdf',
+ mime: 'application/pdf',
+ fileId: 'file-quote',
},
],
},
@@ -299,10 +306,14 @@ it('plays imported images and voice notes inline, like Chat', () => {
).toBeTruthy();
const voice = screen.getByLabelText('voice.ogg');
expect(voice.getAttribute('src')).toBe(
- 'https://files.example.test/document-voice'
+ 'https://files.example.test/file-voice'
);
- // Not as document chips.
+ // Not as file chips.
expect(screen.queryByText('photo.jpeg')).toBeNull();
+ // Other files open the stored file.
+ expect(
+ screen.getByRole('link', { name: 'quote.pdf' }).getAttribute('href')
+ ).toBe('https://files.example.test/file-quote');
});
it('mentions group participants from the composer as WhatsApp mentions', async () => {
@@ -359,7 +370,7 @@ it('renders every WhatsApp message type with Chat parts and small cards', () =>
state: 'ready',
fileName: `file-${ordinal}`,
mime,
- documentId: `document-${ordinal}`,
+ fileId: `file-${ordinal}`,
...extra,
});
const fake = createFakeGroup({
@@ -614,7 +625,7 @@ it('shows a sent image at once and keeps it in place when WhatsApp stores it', a
state: 'ready',
fileName: 'photo.png',
mime: 'image/png',
- documentId: 'document-sent',
+ fileId: 'file-sent',
},
],
},
@@ -627,9 +638,10 @@ it('shows a sent image at once and keeps it in place when WhatsApp stores it', a
expect(shown).toHaveLength(1);
expect(shown[0]?.style.width).toBe('400px');
expect(
- [...document.querySelectorAll('img')].some(
- (image) =>
- image.getAttribute('src') === 'https://files.example.test/document-sent'
+ [...document.querySelectorAll('img')].some((image) =>
+ image
+ .getAttribute('src')
+ ?.startsWith('https://files.example.test/file-sent')
)
).toBe(true);
});
diff --git a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
index 2a773dd28b..a40011be30 100644
--- a/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
+++ b/apps/web/src/features/whatsapp-group/views/whatsapp-group-view.tsx
@@ -42,7 +42,7 @@ import {
} from 'solid-js';
import { match } from 'ts-pattern';
import { ChatDetails } from '../components/chat-details';
-import { InboundAttachmentPlaceholder } from '../components/inbound-attachment';
+import { AttachmentChip } from '../components/inbound-attachment';
import {
InboundMedia,
type InboundMediaFile,
@@ -163,28 +163,18 @@ function MessageMedia(props: {
})
);
const files = mapArray(
- () => media().map((file) => file.attachment.documentId ?? ''),
- (documentId, index) => {
- const stored = documentId ? source.fileUrl(() => documentId) : undefined;
- // A refetch signs a new URL for the same file; keep the first so the
- // image doesn't reload (and the row shrink and grow) on every refresh.
- let firstUrl: string | undefined;
- const url = () => {
- firstUrl ??= stored?.data;
- return firstUrl;
- };
+ () => media().map((file) => file.attachment.fileId ?? ''),
+ (fileId, index) =>
// One object per change, so Chat's media rows don't remount.
- return createMemo(
+ createMemo(
(): InboundMediaFile | undefined => {
const file = media()[index()];
if (!file) return undefined;
return {
- id: documentId || `${file.attachment.ordinal}`,
+ id: fileId || `${file.attachment.ordinal}`,
kind: file.kind,
fileName: file.attachment.fileName,
- url: url() ?? file.attachment.previewUrl,
- unavailable:
- !url() && !file.attachment.previewUrl && !!stored?.isError,
+ url: fileId ? source.fileUrl(fileId) : file.attachment.previewUrl,
previewUrl: file.attachment.previewUrl,
width: file.attachment.width,
height: file.attachment.height,
@@ -194,8 +184,7 @@ function MessageMedia(props: {
},
undefined,
{ equals: sameMediaFile }
- );
- }
+ )
);
const shown = () => files().flatMap((file) => file() ?? []);
return (
@@ -697,16 +686,11 @@ export function WhatsAppGroupView(props: {
? messagesById().get(message.replyTo)
: undefined;
const actions = actionsFor(message);
+ // Everything that doesn't play inline: files
+ // to open, and files not stored (yet).
const placeholders = () =>
- message.attachments.flatMap((attachment) =>
- attachment.state === 'ready'
- ? []
- : [
- {
- state: attachment.state,
- fileName: attachment.fileName,
- },
- ]
+ message.attachments.filter(
+ (attachment) => !inlineMediaKind(attachment)
);
return (
<Show
@@ -816,9 +800,9 @@ export function WhatsAppGroupView(props: {
<div class="mt-1 flex flex-wrap gap-2">
<For each={placeholders()}>
{(attachment) => (
- <InboundAttachmentPlaceholder
- state={attachment.state}
- fileName={attachment.fileName}
+ <AttachmentChip
+ attachment={attachment}
+ url={source.fileUrl}
/>
)}
</For>
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 46addddab4..49f3d05bcf 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1216,8 +1216,8 @@ export * from './linkedAccountView';
export * from './linkedAccountViewAccount';
export * from './linkedAdoptGroup';
export * from './linkedAttachment';
-export * from './linkedAttachmentDocumentId';
export * from './linkedAttachmentDurationSeconds';
+export * from './linkedAttachmentFileId';
export * from './linkedAttachmentHeight';
export * from './linkedAttachmentPresentation';
export * from './linkedAttachmentState';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
index bb96bf732c..0234bb9a07 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachment.ts
@@ -4,8 +4,8 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { LinkedAttachmentDocumentId } from './linkedAttachmentDocumentId';
import type { LinkedAttachmentDurationSeconds } from './linkedAttachmentDurationSeconds';
+import type { LinkedAttachmentFileId } from './linkedAttachmentFileId';
import type { LinkedAttachmentHeight } from './linkedAttachmentHeight';
import type { LinkedAttachmentPresentation } from './linkedAttachmentPresentation';
import type { LinkedAttachmentState } from './linkedAttachmentState';
@@ -15,13 +15,13 @@ import type { LinkedAttachmentWidth } from './linkedAttachmentWidth';
* One attachment of a linked message.
*/
export interface LinkedAttachment {
- /** The private document, once ready. */
- documentId?: LinkedAttachmentDocumentId;
/**
* Length of audio or video in whole seconds, when declared.
* @minimum 0
*/
durationSeconds?: LinkedAttachmentDurationSeconds;
+ /** The static file holding it, once ready. */
+ fileId?: LinkedAttachmentFileId;
/** Display filename. */
fileName: string;
/**
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentDocumentId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentFileId.ts
similarity index 58%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentDocumentId.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentFileId.ts
index b8f407ae3b..92eabbe98e 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentDocumentId.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedAttachmentFileId.ts
@@ -6,6 +6,6 @@
*/
/**
- * The private document, once ready.
+ * The static file holding it, once ready.
*/
-export type LinkedAttachmentDocumentId = string | null;
+export type LinkedAttachmentFileId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
index 7f6b620b91..883f4c15ed 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedReplyContentOneOfThree.ts
@@ -14,6 +14,6 @@ export type LinkedReplyContentOneOfThree = {
/** Optional caption; audio has none. */
caption?: LinkedReplyContentOneOfThreeCaption;
type: LinkedReplyContentOneOfThreeType;
- /** The staged upload, which becomes the message's private document. */
+ /** The staged upload, imported as the message's static file. */
uploadId: string;
};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
index 3359ba0e21..bddf090f59 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkedUploadedAttachment.ts
@@ -14,6 +14,6 @@ export interface LinkedUploadedAttachment {
filename: string;
/** Category. */
kind: LinkedMediaKind;
- /** Use as `upload_id` in a media send; also the future document id. */
+ /** Use as `upload_id` in a media send. */
uploadId: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 9167ed5005..e0441661f8 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -52188,11 +52188,7 @@ export const linkedUploadResponse = zod
kind: zod
.enum(['image', 'audio', 'video', 'document'])
.describe('Attachment categories WhatsApp distinguishes.'),
- uploadId: zod
- .uuid()
- .describe(
- 'Use as `upload_id` in a media send; also the future document id.'
- ),
+ uploadId: zod.uuid().describe('Use as `upload_id` in a media send.'),
})
.describe('A staged attachment, sent only by a later deliberate send.');
@@ -52249,7 +52245,7 @@ export const linkedDeliveryResponseItem = zod
uploadId: zod
.uuid()
.describe(
- "The staged upload, which becomes the message's private document."
+ "The staged upload, imported as the message's static file."
),
})
.describe('One attachment staged through the attachments route.'),
@@ -52334,10 +52330,6 @@ export const whatsappGroupMessagesResponse = zod
.array(
zod
.object({
- documentId: zod
- .uuid()
- .nullish()
- .describe('The private document, once ready.'),
durationSeconds: zod
.number()
.min(
@@ -52347,6 +52339,10 @@ export const whatsappGroupMessagesResponse = zod
.describe(
'Length of audio or video in whole seconds, when declared.'
),
+ fileId: zod
+ .uuid()
+ .nullish()
+ .describe('The static file holding it, once ready.'),
fileName: zod.string().describe('Display filename.'),
height: zod
.number()
@@ -52777,10 +52773,6 @@ export const linkedMessageAttachmentsResponseItem = zod
.array(
zod
.object({
- documentId: zod
- .uuid()
- .nullish()
- .describe('The private document, once ready.'),
durationSeconds: zod
.number()
.min(
@@ -52790,6 +52782,10 @@ export const linkedMessageAttachmentsResponseItem = zod
.describe(
'Length of audio or video in whole seconds, when declared.'
),
+ fileId: zod
+ .uuid()
+ .nullish()
+ .describe('The static file holding it, once ready.'),
fileName: zod.string().describe('Display filename.'),
height: zod
.number()
@@ -52863,10 +52859,6 @@ export const whatsappGroupMessageResponse = zod
.array(
zod
.object({
- documentId: zod
- .uuid()
- .nullish()
- .describe('The private document, once ready.'),
durationSeconds: zod
.number()
.min(
@@ -52876,6 +52868,10 @@ export const whatsappGroupMessageResponse = zod
.describe(
'Length of audio or video in whole seconds, when declared.'
),
+ fileId: zod
+ .uuid()
+ .nullish()
+ .describe('The static file holding it, once ready.'),
fileName: zod.string().describe('Display filename.'),
height: zod
.number()
@@ -53383,7 +53379,7 @@ export const whatsappGroupSendsResponseItem = zod
uploadId: zod
.uuid()
.describe(
- "The staged upload, which becomes the message's private document."
+ "The staged upload, imported as the message's static file."
),
})
.describe('One attachment staged through the attachments route.'),
@@ -53470,7 +53466,7 @@ export const linkedReplyBody = zod
uploadId: zod
.uuid()
.describe(
- "The staged upload, which becomes the message's private document."
+ "The staged upload, imported as the message's static file."
),
})
.describe('One attachment staged through the attachments route.'),
@@ -53549,7 +53545,7 @@ export const linkedReplyResponse = zod
uploadId: zod
.uuid()
.describe(
- "The staged upload, which becomes the message's private document."
+ "The staged upload, imported as the message's static file."
),
})
.describe('One attachment staged through the attachments route.'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index ec23b9d8fa..89d8e213c3 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -33467,17 +33467,17 @@
"description": "One attachment of a linked message.",
"required": ["ordinal", "state", "fileName", "mime", "size"],
"properties": {
- "documentId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "The private document, once ready."
- },
"durationSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "Length of audio or video in whole seconds, when declared.",
"minimum": 0
},
+ "fileId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The static file holding it, once ready."
+ },
"fileName": {
"type": "string",
"description": "Display filename."
@@ -33965,7 +33965,7 @@
"uploadId": {
"type": "string",
"format": "uuid",
- "description": "The staged upload, which becomes the message's private document."
+ "description": "The staged upload, imported as the message's static file."
}
}
},
@@ -34115,7 +34115,7 @@
"uploadId": {
"type": "string",
"format": "uuid",
- "description": "Use as `upload_id` in a media send; also the future document id."
+ "description": "Use as `upload_id` in a media send."
}
}
},
diff --git a/apps/web/tests/functional/whatsapp-linked.spec.ts b/apps/web/tests/functional/whatsapp-linked.spec.ts
index 170c98935d..aadea1d635 100644
--- a/apps/web/tests/functional/whatsapp-linked.spec.ts
+++ b/apps/web/tests/functional/whatsapp-linked.spec.ts
@@ -56,6 +56,8 @@ type LinkedServer = {
delivery: Record<string, Pick<LinkedSendProgress, 'state' | 'messageId'>>;
/** What `POST /attachments` says it staged. */
upload: Omit<LinkedUploadedAttachment, 'uploadId'>;
+ /** Stored attachments' bytes, by static file id; others never load. */
+ files: Record<string, { body: Buffer; contentType: string }>;
};
function server(): LinkedServer {
@@ -121,6 +123,7 @@ function server(): LinkedServer {
sendReplies: [],
delivery: {},
upload: { filename: 'design.pdf', kind: 'document' },
+ files: {},
};
}
@@ -143,7 +146,7 @@ const incomingMessage = {
ordinal: 0,
state: 'loading',
fileName: 'design.pdf',
- documentId: null,
+ fileId: null,
},
],
deliveryState: null,
@@ -461,6 +464,13 @@ async function mount(page: Page, state: LinkedServer, query = '') {
return route.fulfill({ json: [] });
if (url.pathname === '/dss/comms/channels')
return route.fulfill({ json: { items: [], next_cursor: null } });
+ // Stored attachments are static files, like Chat's media.
+ if (url.pathname.startsWith('/static-file/file/')) {
+ const file = state.files[url.pathname.split('/').at(-1) ?? ''];
+ // Unserved files stay loading, so their reserved shape shows.
+ if (!file) return;
+ return route.fulfill(file);
+ }
if (/^\/(auth|dss|notification|connection-gateway)\//.test(url.pathname))
return route.fulfill({ json: {} });
return route.fulfill({ response: await route.fetch() });
@@ -831,7 +841,7 @@ function everyMessageType() {
fileName: id,
mime,
size: 1024,
- documentId: `document-${id}`,
+ fileId: `file-${id}`,
width: null,
height: null,
durationSeconds: null,
@@ -1029,23 +1039,27 @@ test('every WhatsApp message type renders with Chat parts and small cards', asyn
'Launch party'
);
await expect(timeline.getByText('Voice note · 0:42')).toBeVisible();
- // Media reserves its declared shape while it loads.
- const reserved = await timeline
- .locator('[role="status"][aria-label^="Loading "]')
+ // Media takes its declared shape (within a pixel of rounding) before its
+ // file loads.
+ const shapes = await timeline
+ .locator(
+ '[data-whatsapp-sticker], [data-whatsapp-gif], [data-message-id="type-photo"] button[aria-label="Open image viewer"]'
+ )
.evaluateAll((boxes) =>
boxes.map((box) => [
- box.getAttribute('aria-label'),
- Math.round(box.getBoundingClientRect().width),
- Math.round(box.getBoundingClientRect().height),
+ box.getBoundingClientRect().width,
+ box.getBoundingClientRect().height,
])
);
- expect(reserved).toEqual(
- expect.arrayContaining([
- ['Loading sticker.webp', 144, 144],
- ['Loading gif.mp4', 320, 240],
- ['Loading photo.jpg', 400, 200],
- ])
- );
+ expect(shapes).toHaveLength(3);
+ for (const [[width = 0, height = 0], [declaredWidth, declaredHeight]] of [
+ [shapes[0] ?? [], [144, 144]],
+ [shapes[1] ?? [], [320, 240]],
+ [shapes[2] ?? [], [400, 200]],
+ ] as const) {
+ expect(Math.abs(width - declaredWidth)).toBeLessThanOrEqual(1);
+ expect(Math.abs(height - declaredHeight)).toBeLessThanOrEqual(1);
+ }
await expect(
timeline.getByText("Sent something Macro can't show yet")
).toBeVisible();
@@ -1132,7 +1146,7 @@ test('an image sent from Macro shows at once and stays one image once stored', a
fileName: 'photo.png',
mime: 'image/png',
size: PNG.length,
- documentId: 'document-sent',
+ fileId: 'file-sent',
width: null,
height: null,
durationSeconds: null,
@@ -1141,6 +1155,7 @@ test('an image sent from Macro shows at once and stays one image once stored', a
],
},
];
+ state.files['file-sent'] = { body: PNG, contentType: 'image/png' };
state.delivery[sendId] = { state: 'accepted', messageId: 'message-sent' };
await expect(
timeline.locator('[data-message-id="message-sent"]')
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index b89f8f599e..cb5c54c090 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -68,7 +68,7 @@
{
"name": "channels",
"description": "Read and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.",
- "index": "## channels\nRead and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ChannelActivity\nA user's channel activity marker.\nFields: channel\n- `ChannelActivity.createdAt`: createdAt(): string — Creation time.\n- `ChannelActivity.recordInteraction`: recordInteraction(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `ChannelActivity.toJSON`: toJSON(): ApiActivity — Serialize activity without credentials.\n- `ChannelActivity.user`: user(): User — User who interacted.\n\n### Channel\nA channel.\nExtends `PropertiedEntity`.\nFields: entityType, id, name, type, search\n- `Channel.addParticipants`: addParticipants(users): Promise<void> — Add users to the channel.\n- `Channel.agentConversations`: agentConversations(): Promise<AgentConversation[]> — Conversations maintained by agents in this channel.\n- `Channel.attachments`: attachments(opts?): AsyncGenerator<ApiChannelAttachment> — The attachments posted in this channel, auto-paginated.\n- `Channel.delete`: delete(): Promise<void> — Delete the channel.\n- `Channel.join`: join(): Promise<void> — Join the channel as the current user.\n- `Channel.joinCode`: joinCode(): Promise<string> — A reusable code that lets a user join this channel.\n- `Channel.leave`: leave(): Promise<void> — Leave the channel as the current user.\n- `Channel.message`: message(id): Message — A handle to a message in this channel by id.\n- `Channel.messages`: messages(opts?): AsyncGenerator<Message> — Root messages in this channel, most recent first, auto-paginated.\n- `Channel.messagesAfter`: messagesAfter(after, opts?): AsyncGenerator<Message> — Root messages created or replied to at or after after, most recent first, auto-paginated.\n- `Channel.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Channel.participants`: participants(): Promise<ApiChannelParticipant[]> — The channel's members, with their roles and join times.\n- `Channel.recordActivity`: recordActivity(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `Channel.removeParticipants`: removeParticipants(users): Promise<void> — Remove users from the channel.\n- `Channel.rename`: rename(name): Promise<void> — Rename the channel.\n- `Channel.send`: send(body, opts?): Promise<Message> — Post a message.\n- `Channel.setPicture`: setPicture(picture?): Promise<void> — Set an uploaded profile picture, or clear it.\n- `Channel.timelinePage`: timelinePage(selection?): Promise<{ entries: ({ activity: { action: string; actor: User; actor_id: string; id: string; occurred_at: string; payload?: unknown; }; message?: undefined; type: \"activity\"; } | { activity?: undefined; message: Message; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Channel.typing`: typing(action, opts?): Promise<void> — Broadcast a typing indicator, optionally scoped to a thread.\n- `Channel.webUrl`: webUrl(): string — The channel's URL in the Macro web app.\n- `Channel.byId`: static byId(client, id): Channel — A handle to a channel by id.\n- `Channel.create`: static create(client, opts): Promise<Channel> — Create a channel.\n- `Channel.dm`: static dm(client, recipient): Promise<Channel> — Open (creating if needed) the DM channel with a user.\n- `Channel.private`: static private(client, recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n\n### ChannelLabelsNamespace\nShared or private channel labels: named groups of channels shown in the Chat sidebar.\n- `ChannelLabelsNamespace.create`: create(name, channels?): Promise<ChannelLabel> — Create a label and atomically move channels into it.\n- `ChannelLabelsNamespace.createSmartTag`: createSmartTag(name, rule): Promise<ChannelLabel> — Create a smart tag whose membership follows an attribute rule automatically.\n- `ChannelLabelsNamespace.delete`: delete(label): Promise<void> — Delete a label for the whole team; its channels return to the plain list.\n- `ChannelLabelsNamespace.list`: list(): Promise<ChannelLabel[]> — Every label in the authenticated user's shared or private scope.\n- `ChannelLabelsNamespace.previewSmartTag`: previewSmartTag(rule): Promise<SmartTagPreview> — Preview the first matches and total visible count without creating a tag.\n- `ChannelLabelsNamespace.rename`: rename(label, name): Promise<ChannelLabel> — Rename a label for the whole team.\n- `ChannelLabelsNamespace.setLabel`: setLabel(channel, label): Promise<void> — Move a channel into label, or out of any label when label is undefined.\n- `ChannelLabelsNamespace.updateSmartTag`: updateSmartTag(label, name, rule): Promise<ChannelLabel> — Update the name and matching rule of an existing smart tag.\n\n### Message\nA message in a channel.\nExtends `FavoritableEntity`.\nFields: channelId, content, createdAt, editedAt, entityType, id, mentions, updatedAt\n- `Message.author`: author(): Promise<User> — The user who sent this message.\n- `Message.channel`: channel(): Channel — The channel this message is in.\n- `Message.delete`: delete(): Promise<void> — Delete this message.\n- `Message.edit`: edit(body): Promise<Message> — Replace this message's body.\n- `Message.react`: react(emoji): Promise<Message> — Add an emoji reaction to this message.\n- `Message.reply`: reply(body): Promise<Message> — Post a reply in this message's thread.\n- `Message.thread`: thread(): Thread — The thread rooted at this message.\n- `Message.unreact`: unreact(emoji): Promise<Message> — Remove one of your emoji reactions from this message.\n- `Message.byId`: static byId(client, channelId, id, mentions?): Message — A handle to a message by id.\n- `Message.from`: static from(client, channelId, data): Message — Build a root or reply from a message record (pre-seeded, no fetch).\n\n### ChannelNamespace (`macro.channels`)\nFields: labels\n- `ChannelNamespace.activity`: activity(): Promise<ChannelActivity[]> — Recent channel activity, with channel and user handles.\n- `ChannelNamespace.byId`: byId(id): Channel — Channel\n- `ChannelNamespace.create`: create(opts): Promise<Channel> — Create a channel.\n- `ChannelNamespace.dm`: dm(recipient): Promise<Channel> — Promise<Channel>\n- `ChannelNamespace.list`: list(): Promise<Channel[]> — All channels the authenticated user is a member of.\n- `ChannelNamespace.private`: private(recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n- `ChannelNamespace.search`: search(query, opts?): AsyncGenerator<Channel> — Search channels by name (client-side fuzzy filter on the full channel list) or by content (server-side unified search).\n\n### ChannelPicture\nAn uploaded channel profile picture in static file storage.\nFields: id\n- `ChannelPicture.toJSON`: toJSON(): { id: string; } — Serialize the uploaded picture reference.\n- `ChannelPicture.byId`: static byId(id): ChannelPicture — Construct a reference from the upload receipt.\n\n### Thread\nA thread within a channel, rooted at a top-level message.\nFields: channelId, rootId\n- `Thread.channel`: channel(): Channel — The channel this thread is in.\n- `Thread.replies`: replies(): Promise<Message[]> — List the replies in this thread, oldest first.\n- `Thread.reply`: reply(body): Promise<Message> — Post a reply in this thread.\n- `Thread.root`: root(): Message — The message this thread hangs off.\n- `Thread.toJSON`: toJSON(): { channelId: string; rootId: string; } — Serialize the thread identity without its authenticated client.\n\n### WhatsAppAccount\nThe current user's WhatsApp account, connected through the Macro app.\nExtends `MacroEntity`.\nFields: id, identity, owner, state\n- `WhatsAppAccount.refresh`: refresh(): Promise<WhatsAppAccount> — Discard cached connection state and load its current value.\n- `WhatsAppAccount.byId`: static byId(client, id): WhatsAppAccount — Reference an account; reads still enforce the authenticated owner's scope.\n- `WhatsAppAccount.from`: static from(client, record): WhatsAppAccount — Seed an account handle from an API record.\n\n### WhatsAppChat\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\nExtends `MacroEntity`.\nFields: archived, canAdd, cannotAddReason, community, group, id, kind, lastActivityAt, name, pinned, shared\n- `WhatsAppChat.adopt`: adopt(): Promise<WhatsAppGroup> — Add the chat (a group or a direct chat) to Macro as the current user's own; its earlier messages are imported from the phone.\n- `WhatsAppChat.refresh`: refresh(): Promise<WhatsAppChat> — Reload the chat's list entry.\n- `WhatsAppChat.byId`: static byId(client, id): WhatsAppChat — Reference a chat by its WhatsApp JID.\n- `WhatsAppChat.from`: static from(client, record): WhatsAppChat — Seed a chat handle from the chat list.\n\n### WhatsAppGroup\nIndependently shareable added WhatsApp chat: a group or a direct chat.\nExtends `FavoritableEntity`.\nFields: backfill, canSend, community, disappearingSeconds, entityType, id, kind, limits, name, owner, participants, roster, sendingIdentity, sendReason, unreadCount\n- `WhatsAppGroup.delivery`: delivery(sends): Promise<WhatsAppSend[]> — Read delivery for selected caller-owned intents or messages.\n- `WhatsAppGroup.detach`: detach(): Promise<void> — Stop observation while preserving history and established sharing.\n- `WhatsAppGroup.markRead`: markRead(message): Promise<void> — Advance the caller's own read cursor.\n- `WhatsAppGroup.messageAttachments`: messageAttachments(messages): Promise<{ attachments: { document: Document | undefined; fileName: string; mime: string; ordinal: number; size: number; state: LinkedAttachmentState; }[]; message: WhatsAppMessage; }[]> — Read attachment states for selected messages.\n- `WhatsAppGroup.messages`: messages(options?): AsyncGenerator<WhatsAppMessage> — Iterate newest-first timeline pages lazily.\n- `WhatsAppGroup.permissions`: permissions(): Promise<storage.SharePermissionV2> — Read standard link/team sharing settings.\n- `WhatsAppGroup.refresh`: refresh(): Promise<WhatsAppGroup> — Reload detail, permissions and caller capabilities.\n- `WhatsAppGroup.reply`: reply(content, options): Promise<WhatsAppSend> — Personal sessions and owner API credentials can send.\n- `WhatsAppGroup.sends`: sends(): Promise<WhatsAppSend[]> — Read only the caller's pending, uncertain or failed sends.\n- `WhatsAppGroup.updatePermissions`: updatePermissions(update): Promise<void> — Actual owner updates standard link/team sharing settings.\n- `WhatsAppGroup.upload`: upload(file): Promise<WhatsAppUpload> — Stage a supported attachment for a deliberate send.\n- `WhatsAppGroup.byId`: static byId(client, id): WhatsAppGroup — Reference an adopted group; access is checked on each request.\n\n### WhatsAppMessage\nMessage in an independently shared WhatsApp group.\nExtends `MacroEntity`.\nFields: attachments, body, deleted, deliveryState, editedAt, forwarded, group, id, kind, mentions, reactions, replyTo, rich, sender, sentAt, viewOnce\n- `WhatsAppMessage.byId`: static byId(client, group, id): WhatsAppMessage — Reference a message within its original group.\n- `WhatsAppMessage.from`: static from(client, group, record): WhatsAppMessage — Seed a message handle from a timeline response.\n\n### WhatsAppNamespace (`macro.whatsapp`)\nOperate on an account already paired through the Macro app.\n- `WhatsAppNamespace.account`: account(): Promise<WhatsAppAccount | undefined> — Current owner's account, or undefined when no account has been connected.\n- `WhatsAppNamespace.byId`: byId(id): WhatsAppGroup — Reference an adopted entity without fetching it.\n- `WhatsAppNamespace.groups`: groups(): Promise<WhatsAppGroup[]> — Adopted groups shared with the caller, including without WhatsApp.\n\n### WhatsAppParticipant\nSomeone in an added WhatsApp chat, from its roster; mention them in a text reply.\nFields: group, id\n- `WhatsAppParticipant.toJSON`: toJSON(): { admin: boolean | undefined; displayName: string | undefined; group: string; id: string; } — Serialize the participant reference without credentials.\n- `WhatsAppParticipant.byId`: static byId(group, id): WhatsAppParticipant — Reference a participant of a chat by WhatsApp id.\n- `WhatsAppParticipant.from`: static from(group, record): WhatsAppParticipant — Seed a participant from the chat's roster.\n\n### WhatsAppSend\nOne deliberate send intent.\nExtends `MacroEntity`.\nFields: createdAt, errorCode, group, id, message, state\n- `WhatsAppSend.refresh`: refresh(): Promise<WhatsAppSend> — Fetch current delivery state without retrying or submitting the message.\n- `WhatsAppSend.request`: request(): Promise<{ idempotencyKey: string; message: WhatsAppReply; replyTo?: WhatsAppMessage; }> — Inspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n- `WhatsAppSend.byId`: static byId(client, group, id): WhatsAppSend — Reference a send intent within its original group.\n- `WhatsAppSend.from`: static from(client, group, record): WhatsAppSend — Seed a send handle from a server response.\n\n### WhatsAppUpload\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\nFields: filename?, group, id, kind?\n- `WhatsAppUpload.toJSON`: toJSON(): { filename: string | undefined; group: string; id: string; kind: LinkedMediaKind | undefined; } — Serialize the upload reference without credentials.\n- `WhatsAppUpload.byId`: static byId(group, id): WhatsAppUpload — Reference a previously staged upload in its original group.\n- `WhatsAppUpload.from`: static from(group, record): WhatsAppUpload — Seed a handle from the server's upload receipt.\n\nFunctions: `postToChannel`, `communityOf`\n\nTypes: `ChannelAttachment`, `ChannelParticipant`, `MessageData`, `WhatsAppCommunity`, `WhatsAppReply`\n"
+ "index": "## channels\nRead and send channel messages; list the WhatsApp chat list (groups and direct chats), add chats to Macro, read and share added chats, and send from the credential owner's own account with mentions, media and delivery. Pairing stays in the app.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### ChannelActivity\nA user's channel activity marker.\nFields: channel\n- `ChannelActivity.createdAt`: createdAt(): string — Creation time.\n- `ChannelActivity.recordInteraction`: recordInteraction(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `ChannelActivity.toJSON`: toJSON(): ApiActivity — Serialize activity without credentials.\n- `ChannelActivity.user`: user(): User — User who interacted.\n\n### Channel\nA channel.\nExtends `PropertiedEntity`.\nFields: entityType, id, name, type, search\n- `Channel.addParticipants`: addParticipants(users): Promise<void> — Add users to the channel.\n- `Channel.agentConversations`: agentConversations(): Promise<AgentConversation[]> — Conversations maintained by agents in this channel.\n- `Channel.attachments`: attachments(opts?): AsyncGenerator<ApiChannelAttachment> — The attachments posted in this channel, auto-paginated.\n- `Channel.delete`: delete(): Promise<void> — Delete the channel.\n- `Channel.join`: join(): Promise<void> — Join the channel as the current user.\n- `Channel.joinCode`: joinCode(): Promise<string> — A reusable code that lets a user join this channel.\n- `Channel.leave`: leave(): Promise<void> — Leave the channel as the current user.\n- `Channel.message`: message(id): Message — A handle to a message in this channel by id.\n- `Channel.messages`: messages(opts?): AsyncGenerator<Message> — Root messages in this channel, most recent first, auto-paginated.\n- `Channel.messagesAfter`: messagesAfter(after, opts?): AsyncGenerator<Message> — Root messages created or replied to at or after after, most recent first, auto-paginated.\n- `Channel.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Channel.participants`: participants(): Promise<ApiChannelParticipant[]> — The channel's members, with their roles and join times.\n- `Channel.recordActivity`: recordActivity(type): Promise<ChannelActivity> — Record a view or interaction in this channel.\n- `Channel.removeParticipants`: removeParticipants(users): Promise<void> — Remove users from the channel.\n- `Channel.rename`: rename(name): Promise<void> — Rename the channel.\n- `Channel.send`: send(body, opts?): Promise<Message> — Post a message.\n- `Channel.setPicture`: setPicture(picture?): Promise<void> — Set an uploaded profile picture, or clear it.\n- `Channel.timelinePage`: timelinePage(selection?): Promise<{ entries: ({ activity: { action: string; actor: User; actor_id: string; id: string; occurred_at: string; payload?: unknown; }; message?: undefined; type: \"activity\"; } | { activity?: undefined; message: Message; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Channel.typing`: typing(action, opts?): Promise<void> — Broadcast a typing indicator, optionally scoped to a thread.\n- `Channel.webUrl`: webUrl(): string — The channel's URL in the Macro web app.\n- `Channel.byId`: static byId(client, id): Channel — A handle to a channel by id.\n- `Channel.create`: static create(client, opts): Promise<Channel> — Create a channel.\n- `Channel.dm`: static dm(client, recipient): Promise<Channel> — Open (creating if needed) the DM channel with a user.\n- `Channel.private`: static private(client, recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n\n### ChannelLabelsNamespace\nShared or private channel labels: named groups of channels shown in the Chat sidebar.\n- `ChannelLabelsNamespace.create`: create(name, channels?): Promise<ChannelLabel> — Create a label and atomically move channels into it.\n- `ChannelLabelsNamespace.createSmartTag`: createSmartTag(name, rule): Promise<ChannelLabel> — Create a smart tag whose membership follows an attribute rule automatically.\n- `ChannelLabelsNamespace.delete`: delete(label): Promise<void> — Delete a label for the whole team; its channels return to the plain list.\n- `ChannelLabelsNamespace.list`: list(): Promise<ChannelLabel[]> — Every label in the authenticated user's shared or private scope.\n- `ChannelLabelsNamespace.previewSmartTag`: previewSmartTag(rule): Promise<SmartTagPreview> — Preview the first matches and total visible count without creating a tag.\n- `ChannelLabelsNamespace.rename`: rename(label, name): Promise<ChannelLabel> — Rename a label for the whole team.\n- `ChannelLabelsNamespace.setLabel`: setLabel(channel, label): Promise<void> — Move a channel into label, or out of any label when label is undefined.\n- `ChannelLabelsNamespace.updateSmartTag`: updateSmartTag(label, name, rule): Promise<ChannelLabel> — Update the name and matching rule of an existing smart tag.\n\n### Message\nA message in a channel.\nExtends `FavoritableEntity`.\nFields: channelId, content, createdAt, editedAt, entityType, id, mentions, updatedAt\n- `Message.author`: author(): Promise<User> — The user who sent this message.\n- `Message.channel`: channel(): Channel — The channel this message is in.\n- `Message.delete`: delete(): Promise<void> — Delete this message.\n- `Message.edit`: edit(body): Promise<Message> — Replace this message's body.\n- `Message.react`: react(emoji): Promise<Message> — Add an emoji reaction to this message.\n- `Message.reply`: reply(body): Promise<Message> — Post a reply in this message's thread.\n- `Message.thread`: thread(): Thread — The thread rooted at this message.\n- `Message.unreact`: unreact(emoji): Promise<Message> — Remove one of your emoji reactions from this message.\n- `Message.byId`: static byId(client, channelId, id, mentions?): Message — A handle to a message by id.\n- `Message.from`: static from(client, channelId, data): Message — Build a root or reply from a message record (pre-seeded, no fetch).\n\n### ChannelNamespace (`macro.channels`)\nFields: labels\n- `ChannelNamespace.activity`: activity(): Promise<ChannelActivity[]> — Recent channel activity, with channel and user handles.\n- `ChannelNamespace.byId`: byId(id): Channel — Channel\n- `ChannelNamespace.create`: create(opts): Promise<Channel> — Create a channel.\n- `ChannelNamespace.dm`: dm(recipient): Promise<Channel> — Promise<Channel>\n- `ChannelNamespace.list`: list(): Promise<Channel[]> — All channels the authenticated user is a member of.\n- `ChannelNamespace.private`: private(recipients): Promise<Channel> — Open (creating if needed) the private group channel with a set of users.\n- `ChannelNamespace.search`: search(query, opts?): AsyncGenerator<Channel> — Search channels by name (client-side fuzzy filter on the full channel list) or by content (server-side unified search).\n\n### ChannelPicture\nAn uploaded channel profile picture in static file storage.\nFields: id\n- `ChannelPicture.toJSON`: toJSON(): { id: string; } — Serialize the uploaded picture reference.\n- `ChannelPicture.byId`: static byId(id): ChannelPicture — Construct a reference from the upload receipt.\n\n### Thread\nA thread within a channel, rooted at a top-level message.\nFields: channelId, rootId\n- `Thread.channel`: channel(): Channel — The channel this thread is in.\n- `Thread.replies`: replies(): Promise<Message[]> — List the replies in this thread, oldest first.\n- `Thread.reply`: reply(body): Promise<Message> — Post a reply in this thread.\n- `Thread.root`: root(): Message — The message this thread hangs off.\n- `Thread.toJSON`: toJSON(): { channelId: string; rootId: string; } — Serialize the thread identity without its authenticated client.\n\n### WhatsAppAccount\nThe current user's WhatsApp account, connected through the Macro app.\nExtends `MacroEntity`.\nFields: id, identity, owner, state\n- `WhatsAppAccount.refresh`: refresh(): Promise<WhatsAppAccount> — Discard cached connection state and load its current value.\n- `WhatsAppAccount.byId`: static byId(client, id): WhatsAppAccount — Reference an account; reads still enforce the authenticated owner's scope.\n- `WhatsAppAccount.from`: static from(client, record): WhatsAppAccount — Seed an account handle from an API record.\n\n### WhatsAppChat\nOne chat of the current user's WhatsApp chat list: a group or a direct chat.\nExtends `MacroEntity`.\nFields: archived, canAdd, cannotAddReason, community, group, id, kind, lastActivityAt, name, pinned, shared\n- `WhatsAppChat.adopt`: adopt(): Promise<WhatsAppGroup> — Add the chat (a group or a direct chat) to Macro as the current user's own; its earlier messages are imported from the phone.\n- `WhatsAppChat.refresh`: refresh(): Promise<WhatsAppChat> — Reload the chat's list entry.\n- `WhatsAppChat.byId`: static byId(client, id): WhatsAppChat — Reference a chat by its WhatsApp JID.\n- `WhatsAppChat.from`: static from(client, record): WhatsAppChat — Seed a chat handle from the chat list.\n\n### WhatsAppGroup\nIndependently shareable added WhatsApp chat: a group or a direct chat.\nExtends `FavoritableEntity`.\nFields: backfill, canSend, community, disappearingSeconds, entityType, id, kind, limits, name, owner, participants, roster, sendingIdentity, sendReason, unreadCount\n- `WhatsAppGroup.delivery`: delivery(sends): Promise<WhatsAppSend[]> — Read delivery for selected caller-owned intents or messages.\n- `WhatsAppGroup.detach`: detach(): Promise<void> — Stop observation while preserving history and established sharing.\n- `WhatsAppGroup.markRead`: markRead(message): Promise<void> — Advance the caller's own read cursor.\n- `WhatsAppGroup.messageAttachments`: messageAttachments(messages): Promise<{ attachments: { fileName: string; mime: string; ordinal: number; size: number; state: LinkedAttachmentState; url: string | undefined; }[]; message: WhatsAppMessage; }[]> — Read attachment states for selected messages.\n- `WhatsAppGroup.messages`: messages(options?): AsyncGenerator<WhatsAppMessage> — Iterate newest-first timeline pages lazily.\n- `WhatsAppGroup.permissions`: permissions(): Promise<storage.SharePermissionV2> — Read standard link/team sharing settings.\n- `WhatsAppGroup.refresh`: refresh(): Promise<WhatsAppGroup> — Reload detail, permissions and caller capabilities.\n- `WhatsAppGroup.reply`: reply(content, options): Promise<WhatsAppSend> — Personal sessions and owner API credentials can send.\n- `WhatsAppGroup.sends`: sends(): Promise<WhatsAppSend[]> — Read only the caller's pending, uncertain or failed sends.\n- `WhatsAppGroup.updatePermissions`: updatePermissions(update): Promise<void> — Actual owner updates standard link/team sharing settings.\n- `WhatsAppGroup.upload`: upload(file): Promise<WhatsAppUpload> — Stage a supported attachment for a deliberate send.\n- `WhatsAppGroup.byId`: static byId(client, id): WhatsAppGroup — Reference an adopted group; access is checked on each request.\n\n### WhatsAppMessage\nMessage in an independently shared WhatsApp group.\nExtends `MacroEntity`.\nFields: attachments, body, deleted, deliveryState, editedAt, forwarded, group, id, kind, mentions, reactions, replyTo, rich, sender, sentAt, viewOnce\n- `WhatsAppMessage.byId`: static byId(client, group, id): WhatsAppMessage — Reference a message within its original group.\n- `WhatsAppMessage.from`: static from(client, group, record): WhatsAppMessage — Seed a message handle from a timeline response.\n\n### WhatsAppNamespace (`macro.whatsapp`)\nOperate on an account already paired through the Macro app.\n- `WhatsAppNamespace.account`: account(): Promise<WhatsAppAccount | undefined> — Current owner's account, or undefined when no account has been connected.\n- `WhatsAppNamespace.byId`: byId(id): WhatsAppGroup — Reference an adopted entity without fetching it.\n- `WhatsAppNamespace.groups`: groups(): Promise<WhatsAppGroup[]> — Adopted groups shared with the caller, including without WhatsApp.\n\n### WhatsAppParticipant\nSomeone in an added WhatsApp chat, from its roster; mention them in a text reply.\nFields: group, id\n- `WhatsAppParticipant.toJSON`: toJSON(): { admin: boolean | undefined; displayName: string | undefined; group: string; id: string; } — Serialize the participant reference without credentials.\n- `WhatsAppParticipant.byId`: static byId(group, id): WhatsAppParticipant — Reference a participant of a chat by WhatsApp id.\n- `WhatsAppParticipant.from`: static from(group, record): WhatsAppParticipant — Seed a participant from the chat's roster.\n\n### WhatsAppSend\nOne deliberate send intent.\nExtends `MacroEntity`.\nFields: createdAt, errorCode, group, id, message, state\n- `WhatsAppSend.refresh`: refresh(): Promise<WhatsAppSend> — Fetch current delivery state without retrying or submitting the message.\n- `WhatsAppSend.request`: request(): Promise<{ idempotencyKey: string; message: WhatsAppReply; replyTo?: WhatsAppMessage; }> — Inspect the original intent for reconciliation; never resubmit an unknown outcome automatically.\n- `WhatsAppSend.byId`: static byId(client, group, id): WhatsAppSend — Reference a send intent within its original group.\n- `WhatsAppSend.from`: static from(client, group, record): WhatsAppSend — Seed a send handle from a server response.\n\n### WhatsAppUpload\nA staged attachment scoped to one adopted group; use it in a deliberate media send.\nFields: filename?, group, id, kind?\n- `WhatsAppUpload.toJSON`: toJSON(): { filename: string | undefined; group: string; id: string; kind: LinkedMediaKind | undefined; } — Serialize the upload reference without credentials.\n- `WhatsAppUpload.byId`: static byId(group, id): WhatsAppUpload — Reference a previously staged upload in its original group.\n- `WhatsAppUpload.from`: static from(group, record): WhatsAppUpload — Seed a handle from the server's upload receipt.\n\nFunctions: `postToChannel`, `communityOf`\n\nTypes: `ChannelAttachment`, `ChannelParticipant`, `MessageData`, `WhatsAppCommunity`, `WhatsAppReply`\n"
},
{
"name": "crm",
@@ -626,7 +626,7 @@
"storage.LinkShare": "# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.",
"LinkedAccount": "# Type Alias: LinkedAccount\n\n> **LinkedAccount** = \\{ `authorizationGeneration`: `number`; `id`: `string`; `identityJid?`: `string` \\| `null`; `state`: `LinkedAccountState`; `userId`: `string`; \\}\n\nOne person's account, never owned by a workspace.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-authorizationgeneration\"></a> `authorizationGeneration` | `number` | Explicit consent generation; reconnecting a socket never changes it. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable account identity. |\n| <a id=\"property-identityjid\"></a> `identityJid?` | `string` \\| `null` | WhatsApp-verified identity, absent until the first pairing succeeds. |\n| <a id=\"property-state\"></a> `state` | `LinkedAccountState` | Lifecycle. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Authenticated owner. |",
"LinkedAccountState": "# Type Alias: LinkedAccountState\n\n> **LinkedAccountState** = `\"pairing\"` \\| `\"connected\"` \\| `\"logged_out\"` \\| `\"disconnected\"`\n\nAccount lifecycle. Transport outages are not stored: a connected account\nstays connected while its session service reconnects.",
- "LinkedAttachment": "# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `documentId?`: `string` \\| `null`; `durationSeconds?`: `number` \\| `null`; `fileName`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| `LinkedMediaPresentation`; `size`: `number`; `state`: `LinkedAttachmentState`; `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-documentid\"></a> `documentId?` | `string` \\| `null` | The private document, once ready. |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-filename\"></a> `fileName` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| `LinkedMediaPresentation` | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | `LinkedAttachmentState` | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |",
+ "LinkedAttachment": "# Type Alias: LinkedAttachment\n\n> **LinkedAttachment** = \\{ `durationSeconds?`: `number` \\| `null`; `fileId?`: `string` \\| `null`; `fileName`: `string`; `height?`: `number` \\| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \\| `LinkedMediaPresentation`; `size`: `number`; `state`: `LinkedAttachmentState`; `width?`: `number` \\| `null`; \\}\n\nOne attachment of a linked message.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-durationseconds\"></a> `durationSeconds?` | `number` \\| `null` | Length of audio or video in whole seconds, when declared. |\n| <a id=\"property-fileid\"></a> `fileId?` | `string` \\| `null` | The static file holding it, once ready. |\n| <a id=\"property-filename\"></a> `fileName` | `string` | Display filename. |\n| <a id=\"property-height\"></a> `height?` | `number` \\| `null` | Pixel height, when declared. |\n| <a id=\"property-mime\"></a> `mime` | `string` | Declared MIME type. |\n| <a id=\"property-ordinal\"></a> `ordinal` | `number` | Position within the message. |\n| <a id=\"property-presentation\"></a> `presentation?` | `null` \\| `LinkedMediaPresentation` | - |\n| <a id=\"property-size\"></a> `size` | `number` | Declared size in bytes. |\n| <a id=\"property-state\"></a> `state` | `LinkedAttachmentState` | Current state. |\n| <a id=\"property-width\"></a> `width?` | `number` \\| `null` | Pixel width of an image, sticker or video, when WhatsApp declared it. |",
"LinkedAttachmentState": "# Type Alias: LinkedAttachmentState\n\n> **LinkedAttachmentState** = `\"loading\"` \\| `\"ready\"` \\| `\"unavailable\"` \\| `\"unsupported\"`\n\nWhere an attachment of a linked message stands.",
"LinkedBackfill": "# Type Alias: LinkedBackfill\n\n> **LinkedBackfill** = \\{ `imported`: `number`; `state`: `LinkedBackfillState`; \\}\n\nEarlier messages imported after adding a group.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-imported\"></a> `imported` | `number` | Messages received from the phone so far (including ones already shown). |\n| <a id=\"property-state\"></a> `state` | `LinkedBackfillState` | Progress. |",
"LinkedBackfillState": "# Type Alias: LinkedBackfillState\n\n> **LinkedBackfillState** = `\"waiting_for_message\"` \\| `\"pending\"` \\| `\"running\"` \\| `\"waiting_for_phone\"` \\| `\"done\"` \\| `\"partial\"`\n\nWhere importing a group's earlier messages stands.",
@@ -641,11 +641,11 @@
"LinkedMediaPresentation": "# Type Alias: LinkedMediaPresentation\n\n> **LinkedMediaPresentation** = `\"sticker\"` \\| `\"gif\"` \\| `\"voice_note\"`\n\nHow WhatsApp shows an attachment, when not as a plain file of its kind.",
"LinkedMutation": "# Type Alias: LinkedMutation\n\n> **LinkedMutation** = `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`\n\nDeliberate operations on an existing linked-group message.",
"LinkedReplyBlock": "# Type Alias: LinkedReplyBlock\n\n> **LinkedReplyBlock** = `\"sending_disabled\"` \\| `\"no_account\"` \\| `\"disconnected\"` \\| `\"not_observing\"` \\| `\"not_allowed_in_group\"` \\| `\"group_unavailable\"`\n\nWhy the viewer cannot send now.",
- "LinkedReplyContent": "# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\} \\| \\{ `messageId`: `string`; `operation`: `LinkedMutation`; `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `uploadId` | `string` | The staged upload, which becomes the message's private document. |\n\n***\n\n### Type Literal\n\n\\{ `messageId`: `string`; `operation`: `LinkedMutation`; `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `messageId` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | `LinkedMutation` | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |",
+ "LinkedReplyContent": "# Type Alias: LinkedReplyContent\n\n> **LinkedReplyContent** = \\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\} \\| \\{ `messageId`: `string`; `operation`: `LinkedMutation`; `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\nContent of a deliberate send.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `string`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `string`[] | Group participants the text @-mentions, by their WhatsApp id (`jid` of a roster participant); the text must contain `@<digits before the @ of the id>` for each. |\n| `text` | `string` | UTF-8 text, at most [`TEXT_LIMIT_BYTES`] bytes. |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string` \\| `null`; `type`: `\"media\"`; `uploadId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `caption?` | `string` \\| `null` | Optional caption; audio has none. |\n| `type` | `\"media\"` | - |\n| `uploadId` | `string` | The staged upload, imported as the message's static file. |\n\n***\n\n### Type Literal\n\n\\{ `messageId`: `string`; `operation`: `LinkedMutation`; `text?`: `string` \\| `null`; `type`: `\"mutation\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `messageId` | `string` | Existing group message, resolved to its WhatsApp source by the server. |\n| `operation` | `LinkedMutation` | Explicit operation. |\n| `text?` | `string` \\| `null` | Replacement text or emoji; absent for delete, empty to remove a reaction. |\n| `type` | `\"mutation\"` | - |",
"LinkedSendProgress": "# Type Alias: LinkedSendProgress\n\n> **LinkedSendProgress** = \\{ `createdAt`: `string`; `errorCode?`: `string` \\| `null`; `groupId`: `string`; `id`: `string`; `messageId?`: `string` \\| `null`; `payload`: `LinkedSendReply`; `state`: `LinkedDeliveryState`; `userId`: `string`; \\}\n\nDurable result of a deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Intent creation time. |\n| <a id=\"property-errorcode\"></a> `errorCode?` | `string` \\| `null` | Sanitized failure code. |\n| <a id=\"property-groupid\"></a> `groupId` | `string` | Group entity. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable intent id. |\n| <a id=\"property-messageid\"></a> `messageId?` | `string` \\| `null` | Group message, once WhatsApp accepted it. |\n| <a id=\"property-payload\"></a> `payload` | `LinkedSendReply` | The original request, so a failed draft can be recovered. |\n| <a id=\"property-state\"></a> `state` | `LinkedDeliveryState` | Current state. |\n| <a id=\"property-userid\"></a> `userId` | `string` | Person who submitted it. |",
"LinkedSendReply": "# Type Alias: LinkedSendReply\n\n> **LinkedSendReply** = \\{ `idempotencyKey`: `string`; `message`: `LinkedReplyContent`; `replyTo?`: `string` \\| `null`; \\}\n\nExplicit send action from a person. Only deliberate sends reach WhatsApp.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-idempotencykey\"></a> `idempotencyKey` | `string` | Stable client intent key. A changed payload with this key is a conflict. |\n| <a id=\"property-message\"></a> `message` | `LinkedReplyContent` | Content. |\n| <a id=\"property-replyto\"></a> `replyTo?` | `string` \\| `null` | Group message being quoted, within this group. |",
"LinkedSharedGroupReference": "# Type Alias: LinkedSharedGroupReference\n\n> **LinkedSharedGroupReference** = \\{ `id`: `string`; `name`: `string`; `ownerId`: `string`; \\}\n\nAnother person's group entity the caller can view.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Group entity id. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, following WhatsApp. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who added the group and shared it. |",
- "LinkedUploadedAttachment": "# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: `LinkedMediaKind`; `uploadId`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | `LinkedMediaKind` | Category. |\n| <a id=\"property-uploadid\"></a> `uploadId` | `string` | Use as `upload_id` in a media send; also the future document id. |",
+ "LinkedUploadedAttachment": "# Type Alias: LinkedUploadedAttachment\n\n> **LinkedUploadedAttachment** = \\{ `filename`: `string`; `kind`: `LinkedMediaKind`; `uploadId`: `string`; \\}\n\nA staged attachment, sent only by a later deliberate send.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-filename\"></a> `filename` | `string` | Display filename. |\n| <a id=\"property-kind\"></a> `kind` | `LinkedMediaKind` | Category. |\n| <a id=\"property-uploadid\"></a> `uploadId` | `string` | Use as `upload_id` in a media send. |",
"ListOccurrencesData": "# Type Alias: ListOccurrencesData\n\n> **ListOccurrencesData** = \\{ `body?`: `never`; `path?`: `never`; `query`: \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\}; `url`: `\"/calendar-events\"`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-body\"></a> `body?` | `never` | - |\n| <a id=\"property-path\"></a> `path?` | `never` | - |\n| <a id=\"property-query\"></a> `query` | \\{ `cursor?`: `string`; `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `query.cursor?` | `string` | Opaque continuation cursor returned by the previous page. |\n| `query.end` | `string` | Exclusive UTC viewport end. |\n| `query.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `query.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `query.start` | `string` | Inclusive UTC viewport start. |\n| `query.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n| <a id=\"property-url\"></a> `url` | `\"/calendar-events\"` | - |",
"storage.MacroUserIdStr": "# Type Alias: MacroUserIdStr\n\n> **MacroUserIdStr** = `string`",
"storage.Meeting": "# Type Alias: Meeting\n\n> **Meeting** = \\{ `callId?`: `string` \\| `null`; `channelId?`: `string` \\| `null`; `id`: `string`; `scheduledEnd?`: `string` \\| `null`; `scheduledStart?`: `string` \\| `null`; `shareToken`: `MeetingToken`; `title`: `string`; \\}\n\nPersistent meeting metadata. No channel contents or archived media are exposed.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-callid\"></a> `callId?` | `string` \\| `null` | Currently active call session, if any. |\n| <a id=\"property-channelid\"></a> `channelId?` | `string` \\| `null` | Associated channel, for links to existing channel calls only. |\n| <a id=\"property-id\"></a> `id` | `string` | Persistent meeting identifier. |\n| <a id=\"property-scheduledend\"></a> `scheduledEnd?` | `string` \\| `null` | Scheduled end, or none for an instant meeting. |\n| <a id=\"property-scheduledstart\"></a> `scheduledStart?` | `string` \\| `null` | Scheduled start, or none for an instant meeting. |\n| <a id=\"property-sharetoken\"></a> `shareToken` | `MeetingToken` | Bearer capability embedded in the invitation URL. |\n| <a id=\"property-title\"></a> `title` | `string` | Human-readable meeting title. |",
@@ -1882,7 +1882,7 @@
"WhatsAppGroup.detach": "### detach()\n\n> **detach**(): `Promise`\\<`void`\\>\n\nStop observation while preserving history and established sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"WhatsAppGroup.favorite": "### favorite()\n\n> **favorite**(): `Promise`\\<`WhatsAppGroup`\\>\n\nAdd this entity to the user's favorites. Returns this handle for chaining.\nPlain unwrap: favoriting alters the user's favorites collection, not this\nentity's own detail, so there's nothing cached to invalidate.\n\n#### Returns\n\n`Promise`\\<`WhatsAppGroup`\\>\n\n#### Inherited from\n\n`FavoritableEntity.favorite`",
"WhatsAppGroup.markRead": "### markRead()\n\n> **markRead**(`message`): `Promise`\\<`void`\\>\n\nAdvance the caller's own read cursor.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `message` | `WhatsAppMessage` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "WhatsAppGroup.messageAttachments": "### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `document`: `Document` \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: `LinkedAttachmentState`; \\}[]; `message`: `WhatsAppMessage`; \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | `WhatsAppMessage`[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `document`: `Document` \\| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: `LinkedAttachmentState`; \\}[]; `message`: `WhatsAppMessage`; \\}[]\\>",
+ "WhatsAppGroup.messageAttachments": "### messageAttachments()\n\n> **messageAttachments**(`messages`): `Promise`\\<\\{ `attachments`: \\{ `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: `LinkedAttachmentState`; `url`: `string` \\| `undefined`; \\}[]; `message`: `WhatsAppMessage`; \\}[]\\>\n\nRead attachment states for selected messages.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `messages` | `WhatsAppMessage`[] |\n\n#### Returns\n\n`Promise`\\<\\{ `attachments`: \\{ `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: `LinkedAttachmentState`; `url`: `string` \\| `undefined`; \\}[]; `message`: `WhatsAppMessage`; \\}[]\\>",
"WhatsAppGroup.messages": "### messages()\n\n> **messages**(`options?`): `AsyncGenerator`\\<`WhatsAppMessage`\\>\n\nIterate newest-first timeline pages lazily.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `limit?`: `number`; \\} |\n| `options.limit?` | `number` |\n\n#### Returns\n\n`AsyncGenerator`\\<`WhatsAppMessage`\\>",
"WhatsAppGroup.permission": "### permission()\n\n> **permission**(): `Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\nRead the caller's effective permission on this entity.\n\n#### Returns\n\n`Promise`\\<\\{ `permission`: `EntityPermission`; `status`: `\"access\"`; \\} \\| \\{ `status`: `\"no_access\"`; \\}\\>\n\n#### Inherited from\n\n`FavoritableEntity.permission`",
"WhatsAppGroup.permissions": "### permissions()\n\n> **permissions**(): `Promise`\\<`storage.SharePermissionV2`\\>\n\nRead standard link/team sharing settings.\n\n#### Returns\n\n`Promise`\\<`storage.SharePermissionV2`\\>",
@@ -1895,7 +1895,7 @@
"WhatsAppGroup.upload": "### upload()\n\n> **upload**(`file`): `Promise`\\<`WhatsAppUpload`\\>\n\nStage a supported attachment for a deliberate send.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `file` | `Blob` \\| `File` |\n\n#### Returns\n\n`Promise`\\<`WhatsAppUpload`\\>",
"WhatsAppGroup.byId": "### byId()\n\n> `static` **byId**(`client`, `id`): `WhatsAppGroup`\n\nReference an adopted group; access is checked on each request.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppGroup`",
"WhatsAppReply": "# Type Alias: WhatsAppReply\n\n> **WhatsAppReply** = \\{ `mentions?`: `WhatsAppParticipant`[]; `text`: `string`; `type`: `\"text\"`; \\} \\| \\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: `WhatsAppUpload`; \\} \\| \\{ `message`: `WhatsAppMessage`; `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}\n\nDeliberate content from the credential owner's own WhatsApp account.\n\n## Union Members\n\n### Type Literal\n\n\\{ `mentions?`: `WhatsAppParticipant`[]; `text`: `string`; `type`: `\"text\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `mentions?` | `WhatsAppParticipant`[] | Participants mentioned (from `participants()`); the text names each as `@<mentionToken>`. |\n| `text` | `string` | - |\n| `type` | `\"text\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `caption?`: `string`; `type`: `\"media\"`; `upload`: `WhatsAppUpload`; \\}\n\n***\n\n### Type Literal\n\n\\{ `message`: `WhatsAppMessage`; `operation`: `\"reaction\"` \\| `\"edit\"` \\| `\"delete\"`; `text?`: `string`; `type`: `\"mutation\"`; \\}",
- "WhatsAppMessage": "# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- `MacroEntity`\\<`WhatsAppGroupMessage`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `document`: `Document` \\| `undefined`; `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: `LinkedMediaPresentation` \\| `undefined`; `size`: `number`; `state`: `LinkedAttachmentState`; `width`: `number` \\| `undefined`; \\}[]\\> | Attachment state and imported document handles. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | `WhatsAppGroup` | The chat this message is in. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`WhatsAppMessageKind`\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<`WhatsAppMention`[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<`WhatsAppGroupReaction`[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<`WhatsAppGroupSender`\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `readonly` | () => `Promise`\\<`boolean`\\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |",
+ "WhatsAppMessage": "# Class: WhatsAppMessage\n\nMessage in an independently shared WhatsApp group.\n\n## Extends\n\n- `MacroEntity`\\<`WhatsAppGroupMessage`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments` | `readonly` | () => `Promise`\\<\\{ `durationSeconds`: `number` \\| `undefined`; `fileName`: `string`; `height`: `number` \\| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: `LinkedMediaPresentation` \\| `undefined`; `size`: `number`; `state`: `LinkedAttachmentState`; `url`: `string` \\| `undefined`; `width`: `number` \\| `undefined`; \\}[]\\> | Attachment states, with the stored file's URL once ready. | - |\n| <a id=\"property-body\"></a> `body` | `readonly` | () => `Promise`\\<`string`\\> | Plain WhatsApp text. | - |\n| <a id=\"property-deleted\"></a> `deleted` | `readonly` | () => `Promise`\\<`boolean`\\> | Deleted for everyone. | - |\n| <a id=\"property-deliverystate\"></a> `deliveryState` | `readonly` | () => `Promise`\\<`NonNullable`\\<LinkedDeliveryState \\| null \\| undefined\\> \\| `undefined`\\> | Caller-owned send's delivery state, when present. | - |\n| <a id=\"property-editedat\"></a> `editedAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Last edit time. | - |\n| <a id=\"property-forwarded\"></a> `forwarded` | `readonly` | () => `Promise`\\<`boolean`\\> | Forwarded from another chat. | - |\n| <a id=\"property-group\"></a> `group` | `readonly` | `WhatsAppGroup` | The chat this message is in. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<`WhatsAppMessageKind`\\> | `message`, or `system` for something that happened in the group (see `rich`). | - |\n| <a id=\"property-mentions\"></a> `mentions` | `readonly` | () => `Promise`\\<`WhatsAppMention`[]\\> | People the body @-mentions: `@<token>` in the body is this person. | - |\n| <a id=\"property-reactions\"></a> `reactions` | `readonly` | () => `Promise`\\<`WhatsAppGroupReaction`[]\\> | Grouped emoji counts and caller's own reaction. | - |\n| <a id=\"property-replyto\"></a> `replyTo` | `readonly` | () => `Promise`\\<`WhatsAppMessage` \\| `undefined`\\> | Quoted message in this group. | - |\n| <a id=\"property-rich\"></a> `rich` | `readonly` | () => `Promise`\\<`NonNullable`\\<WhatsAppRichContent \\| null \\| undefined\\> \\| `undefined`\\> | Poll (with tallies), location, contact cards, event or system line. | - |\n| <a id=\"property-sender\"></a> `sender` | `readonly` | () => `Promise`\\<`WhatsAppGroupSender`\\> | Protocol-verified sender association and display name. | - |\n| <a id=\"property-sentat\"></a> `sentAt` | `readonly` | () => `Promise`\\<`string`\\> | WhatsApp timestamp. | - |\n| <a id=\"property-viewonce\"></a> `viewOnce` | `readonly` | () => `Promise`\\<`boolean`\\> | Sent as view-once in WhatsApp; Macro keeps and shows it like any media. | - |",
"WhatsAppMessage.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `WhatsAppGroupMessage`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `WhatsAppGroupMessage`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `WhatsAppGroupMessage` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
"WhatsAppMessage.byId": "### byId()\n\n> `static` **byId**(`client`, `group`, `id`): `WhatsAppMessage`\n\nReference a message within its original group.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | `WhatsAppGroup` |\n| `id` | `string` |\n\n#### Returns\n\n`WhatsAppMessage`",
"WhatsAppMessage.from": "### from()\n\n> `static` **from**(`client`, `group`, `record`): `WhatsAppMessage`\n\nSeed a message handle from a timeline response.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `group` | `WhatsAppGroup` |\n| `record` | `WhatsAppGroupMessage` |\n\n#### Returns\n\n`WhatsAppMessage`",
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index e457770211..6591138fac 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,62 +1,62 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*u($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class I$ extends P{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends I${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var f6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>f6[x]??x);return`<${$}>${j}</${$}>`}function b6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var k6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function g6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(b6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:y6(x)}}function y6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class W$ extends P{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:yx($)}))}}function yx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=v6(O);if(await h6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function v6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function h6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends I${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new vx(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class vx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var m6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??m6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((B)=>B.type===j).map((B)=>x(K,B)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Wj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return u(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class TO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:i$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=G(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class mx{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class cx{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,G(await this.client.storage.createAgent({body:yx($)})))}}class ux{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class n$ extends P{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class dx{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}class H$ extends P{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new H$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new H$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>H$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:c6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function c6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,w.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=G(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>w.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return w.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var u6=8;class w extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new w($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new w($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new w($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new w($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?w.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new w(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,u6,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new w($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class lx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:w.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=l6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:r6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:d6($)}));return $$.fromRecord(this.client,O)}}function d6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function l6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function r6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class R$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends I${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return R$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class rx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class px{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class ax{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new px($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ix{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var p6=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=u(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,p6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends I${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class s$ extends P{tableDetail=new B$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>BO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return u(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>BO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return BO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class BO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new BO($,O,j)}static from($,O,j){return new BO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class nx{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class sx{client;pipelines;constructor($){this.client=$;this.pipelines=new nx($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),m1=Symbol.for("@ts-pattern/isVariadic");var tx=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Tj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(tx($)){if(!tx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[m1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return tx($)?Tj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,Y$):tO(Object.values($),Y$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>$0($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function ex($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[m1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>ex($0($)),select:(O)=>ex(O===void 0?eO($):eO(O,$))})}function $0($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var i6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"and"})})}function c1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function u1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var d1=t(m(u1)),t6=t(m(u1)),e6=d1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),h1=o$(m(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),o6=g$(m(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>m((K)=>e$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,m((O)=>e$(O)&&O>0))),negative:()=>$O(d($,m((O)=>e$(O)&&O<0)))}),$7=$O(m(e$)),O7=t(m(function($){return typeof $=="boolean"})),j7=t(m(function($){return typeof $=="symbol"})),x7=t(m(function($){return $==null})),S7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:$0,array:function(...$){return ex({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:i6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:n6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[h1,$[0]]:$;return{matched:s6(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:c1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:eO,any:d1,unknown:t6,_:e6,string:h1,number:o6,bigint:$7,boolean:O7,symbol:j7,nullish:x7,nonNullable:S7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(a6($)))}};class l1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var ox={matched:!1,value:void 0};function c($){return new Hj($,ox)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ox:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:ox)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z7($){throw new l1($)}var O0,X7=new Uint8Array(16);function Rj(){if(!O0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O0=crypto.getRandomValues.bind(crypto)}return O0(X7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function r1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var j0={};function K7($,O,j){let x;if($)x=p1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();Y7(j0,S,K),x=p1(K,j0.msecs,j0.seq,O,j)}return O??r1(x)}function Y7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function p1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var d$=K7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:B})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,I),columnName:z,to:B}}).exhaustive();return{result:S.result?G7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function G7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Z0 extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Mj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Q7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function J7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Q7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function x0($){return $.map((O)=>({id:d$(),label:O}))}function a1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function S0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!a1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(S0).join(", ")||"none"}`);return x}class V$ extends P{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Z0(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(S0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(J$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Mj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Mj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${J7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:x0(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!a1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?S0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Mj(O.type),...O.options!==void 0?{options:x0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:x0(O)}}]),"column","options_added")}}class X0{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class K0{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return w.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:w.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:w.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return w.byId(this.client,$)}create($){return w.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return w.byId(this.client,O.documentId)}createSnippet($){return w.createSnippet(this.client,$)}createSkill($){return w.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return w.search(this.client,$,O)}recent($){return w.recent(this.client,$)}recentlyDeleted(){return w.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return w.byId(this.client,$)}}class U$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new U$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>H$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=G(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new U$($,O.thread_id)})}class D$ extends P{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>H$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return U$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Y0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Y0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class OO extends P{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new OO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class G0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Y0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:U$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return U$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return H$.byId(this.client,$)}links(){return H$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return U$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>U$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}archive($,O=!0){return U$.archiveMany(this.client,$,O)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Q0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}class J0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class jO extends I${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function i1({login:$,...O}){return{...O,login:$??void 0}}class V0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async bySource($,O){return jO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(i1),assignees:j.map(i1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Aj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Aj($,O)}}class y$ extends P{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Aj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class B0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class L0{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class N0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var V7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function W7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class _$ extends w{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=W7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===V7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new _$($,O.document_id)})}class xO extends P{access=new o(this.client,"initiative",this);static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class U0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>xO.byId(this.client,$.id))}async create($){return xO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class z0{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async create($){return R$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>R$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>R$.from(this.client,$))}async lookup($){return R$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class I0{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class T0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class H0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class CO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new CO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class SO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new SO($,j.id,j)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>CO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return CO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return CO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class R0{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return SO.fromRecord(this.client,x)})}create($){return SO.create(this.client,$)}definition($){return SO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function D0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function L7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(D0)})).with({type:"cron"},D0).with({type:"events"},D0).exhaustive()}class ZO extends P{static byId($,O){return new ZO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new ZO($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:C0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new _0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class _0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function C0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:L7($.trigger),task:{...O}}}class M0{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async create($){return ZO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...C0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>ZO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class A0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class F0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class E0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class XO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new XO($,j.id,j,j.signing_secret)}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class w0{client;constructor($){this.client=$}create($){return XO.create(this.client,$)}byId($){return XO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>XO.fromRecord(this.client,O))}}class MO extends P{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){return G(await this.client.storage.whatsappGroupMessage({path:{group_id:this.group.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,document:O.documentId?w.byId(this.client,O.documentId):void 0})))}class KO{group;id;record;constructor($,O,j){this.group=$;this.id=O;this.record=j}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,group:this.group.id,displayName:this.displayName,admin:this.admin}}}class YO{id;group;filename;kind;constructor($,O,j,x){this.id=$;this.group=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$)}static from($,O){return new YO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,group:this.group.id,filename:this.filename,kind:this.kind}}}class GO extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>KO.byId(this.group,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?C$.byId(this.client,this.group,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends I${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");participants=this.mappedField("roster",($)=>($?.participants??[]).map((O)=>KO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);owner=this.mappedField("userId",($)=>M.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertGroup($.group),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{messageId:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.group);let j=c($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertGroup(Z.group);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertGroup(S.upload.group),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.group),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return GO.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>GO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>GO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.messageId),attachments:O.linkedAttachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,document:j.documentId?w.byId(this.client,j.documentId):void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($.id!==this.id)throw Error("WhatsApp reference belongs to another group")}}function q0($,O){return{chat:IO.byId($,O.id),name:O.name,announcements:O.announcements}}class IO extends P{static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{groupJid:this.id}}));return v$.byId(this.client,$.groupId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class f0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?MO.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>IO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function b0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function n1($,O,j){let x=[];for(let S of b0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:w.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:jO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var s1="00000000-0000-0000-0000-000000000000",k0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),t1=($,O)=>$==null?O:{"&":[$,O]};function g0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){g0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{g0(Z,`${O}.${S}[${X}]`)})}class Ej{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(k0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(k0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)g0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:s1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>Fj(X.email_address)===Fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=t1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(k0))if(!x.includes(S))O[K]={l:{[Z]:s1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=t1(O.propf,X)}return O}}class y0{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>b0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>n1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+async function uO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class B${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*u($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class f extends Error{constructor($){super($);this.name="MacroError"}}class QO extends f{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends f{constructor($){super($);this.name="MacroNotFoundError"}}function G($){if($.error!==void 0)throw new QO($.response?.status??0,$.error);return $.data}class P{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=G(await $(this.client));return this.detail.clear(),O}}class I$ extends P{async permission(){return G(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return G(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends I${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=G(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){G(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return G(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){G(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var f6={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function a$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>f6[x]??x);return`<${$}>${j}</${$}>`}function b6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var k6={toMention:()=>({tag:a$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function g6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(b6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:y6(x)}}function y6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function O$($){return typeof $==="string"?{content:$,mentions:[]}:$}class W$ extends P{static byId($,O){return new W$($,O)}static from($,O){return new W$($,O.id,O)}async fetch(){let $=G(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new E(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class T$ extends P{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=G(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new E(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>b.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?W$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:yx($)}))}}function yx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:Y,...L}=$;return{...L,channel_ids:O?.map((Q)=>Q.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:Y}}async function Wj($,O,j){let{channelId:x,thread:S}=v6(O);if(await h6($)){let{id:Z}=G(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=G(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function v6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function h6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class h${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return b.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=G(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Wj(this.client,this,O$($));return e.byId(this.client,this.channelId,O)}}class e extends I${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new h$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Lj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return T$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:l.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new vx(this.client,this,$))}async startFresh($){G(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class vx{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return l.byId(this.client,this.record.sessionId)}async retry($){G(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class L$ extends P{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new L$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function w$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=G(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var m6=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let Y=X?.searchOn??"name_content",L=X?.pageSize??m6;return u(async(Q)=>{let{results:J,next_cursor:I}=G(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:Y,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((B)=>B.type===j).map((B)=>x(K,B)),nextCursor:I}})}}class JO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class b extends X${async recordActivity($){return new JO(this.client,this,G(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return L$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return w$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return G(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return G(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new b($,O)}static async dm($,O){let{channel_id:j}=G(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=G(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=G(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new b($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Wj(this.client,O?.thread??this,O$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return u(async(O)=>{let j=G(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=G(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return G(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){G(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return u(async(O)=>{let j=G(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=x$({type:"channel",make:($,O)=>new b($,O.channel_id)})}class M extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static fromName($,O){return new M($,O.id,O)}static async me($){let{user_id:O}=G(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return b.dm(this.client,this)}toMention(){return{tag:a$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=G(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?TO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>TO.from(this.client,this,j))}}async submit($,O){return TO.from(this.client,this,G(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){G(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return G(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){G(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){G(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return G(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class TO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new TO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new E(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function i$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new N$($,O,j)}static fromRecord($,O,j){return new N$($,O,j.id,j)}static async create($,O,j){return N$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=G(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return G(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return G(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new hx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class hx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class dO extends P{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new dO($,j,O)}async fetch(){return G(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>N$.create(this.client,this,$),list:()=>N$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Nj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Nj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return G(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){G(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){G(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class lO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new lO($,O,j)}async answer($){return G(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class l extends P{access=new o(this.client,"agent_session",this);toolApprovalById($){return lO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:i$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=G(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new l($,j.id,j)}static async repositories($){let{repositories:O}=G(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=G(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=G(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return G(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=G(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=G(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){G(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){G(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return G(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return G(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return G(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return G(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=G(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return G(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return G(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=G(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return G(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>N$.createForSession(this.client,this,$),byId:($)=>N$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class mx{client;constructor($){this.client=$}byId($){return l.byId(this.client,$)}createManaged($){return l.createManaged(this.client,$)}chooseMode($){return l.chooseMode(this.client,$)}repositories(){return l.repositories(this.client)}repositoryBranches($){return l.repositoryBranches(this.client,$)}forPullRequest($){return l.forPullRequest(this.client,$)}defaultSandboxSize(){return l.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return l.setDefaultSandboxSize(this.client,$)}codingPreferences(){return l.codingPreferences(this.client)}setCodingPreferences($){return l.setCodingPreferences(this.client,$)}}class cx{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return G(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,G(await this.client.storage.createAgent({body:yx($)})))}}class ux{client;async usage($={}){let{users:O,...j}=$;return G(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return G(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return G(await this.client.cognition.decisions({body:$}))}}class n$ extends P{static byId($,O){return new n$($,O)}static from($,O){return new n$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=G(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new E(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class dx{client;constructor($){this.client=$}byId($){return n$.byId(this.client,$)}async list(){return G(await this.client.storage.listUserApiKeys()).keys.map(($)=>n$.from(this.client,$))}async create($){let O=G(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:n$.from(this.client,O),secret:O.key}}async tokenForEmail($){return G(await this.client.auth.macroApiToken({query:{email:$}}))}}class rO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new f("bots.me() requires bot auth — a user API key has no bot identity");return G(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new f("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return G(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new f("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class S$ extends P{async fetch(){let O=G(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new E(`team ${this.id} not found`);return O}static byId($,O){return new S$($,O)}static async current($){let O=G(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new S$($,O.team.id,O.team)}static async list($){return G(await $.auth.getUserTeams()).map((j)=>new S$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=G(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new f("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}class H$ extends P{async fetch(){let{links:$}=G(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`email link ${this.id} not found`);return O}static byId($,O){return new H$($,O)}static async list($){let{links:O}=G(await $.email.listLinks());return O.map((j)=>new H$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return G(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=G(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`calendar ${this.id} not found`);return O}static byId($,O){return new m$($,O)}static async list($){let{calendars:O}=G(await $.calendar.listCalendars());return O.map((j)=>new m$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>H$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return G(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return G(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){G(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),G(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>q$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),G(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),q$.forDocument(this.client,this,O,$)}requireOwnOccurrence($){if($.eventId!==this.id)throw new f("The occurrence belongs to a different event")}async fetch(){throw new f(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new $$($,O)}static fromRecord($,O){return new $$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");guestPolicy=this.field("guestPolicy");viewerCan=this.field("viewerCan");calendar=this.mappedField("calendarId",($)=>$?m$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:c6($)}));return $$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId,inbox:$.inbox}}))}async prepareReplacement($){let O=G(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new pO(this.client,O.operationId)}async providerUrl($={}){return G(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async inviteGuests($){let O=await this.mutate((j)=>j.calendar.inviteCalendarEventGuests({path:{event_id:this.id},body:{guests:$.guests,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}));return $$.fromRecord(this.client,O)}async addToCalendar($={}){let O=await this.mutate((j)=>j.calendar.copyCalendarEvent({path:{event_id:this.id},body:{calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}async ics(){return G(await this.client.storage.eventIcs({path:{event_id:this.id}}))}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return $$.fromRecord(this.client,O)}}function c6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id,inbox:$.inbox}}class q$ extends P{event;occurrence;fromDocument;constructor($,O,j,x,S,K=!1){super($,x.id,S);this.event=O;this.occurrence=j;this.fromDocument=K;if(j.eventId!==O.id)throw new f("Choose an occurrence belonging to this event")}static fromDocumentLink($,O,j){return new q$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new q$($,O,j,x)}static fromRecord($,O,j,x){return new q$($,O,j,q.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).find((S)=>S.eventId===this.event.id&&S.occurrenceKey===this.occurrence.occurrenceKey);if(!x)throw new E("This meeting link has been removed");return{documentId:this.id,name:x.documentName,team:x.team,canManage:!0}}let O=G(await this.client.calendar.eventNotes({path:{event_id:this.event.id},query:{occurrenceKey:this.occurrence.occurrenceKey}})).find((j)=>j.documentId===this.id);if(!O)throw new E("This document is no longer linked to the meeting");return O}document=this.mappedField("documentId",($)=>q.byId(this.client,$));name=this.field("name");team=this.mappedField("team",($)=>$?S$.byId(this.client,$.id):void 0);canManage=this.field("canManage");async setTeam($){await this.mutate((O)=>O.calendar.linkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey},body:{teamId:$?.id??null}}))}async unlink(){await this.mutate(($)=>$.calendar.unlinkEventNote({path:{event_id:this.event.id,document_id:this.id},query:{occurrenceKey:this.occurrence.occurrenceKey}}))}}class n extends X${async sharePermissions(){return G(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return G(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=G(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=G(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=G(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=x$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class VO extends P{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new VO($,O,j)}static from($,O,j){return new VO($,O,j.uuid,j)}async fetch(){let $=G(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new E(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends P{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class aO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new B$(async()=>G(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new aO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var u6=8;class q extends X${async meetingNotes(){return G(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:q$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return G(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>VO.from(this.client,this,$))}async createHighlight($){return VO.from(this.client,this,G(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return aO.byId(this.client,this,$)}async sharePermissions(){return G(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return G(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return G(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return L$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return w$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=G(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=G(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=G(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return u(async(x)=>{let S=G(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=G(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=G(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=G(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new QO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=G(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=u(async(x)=>{let S=G(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return uO(j,u6,async(x)=>{let{state:S,root:K,replies:Z}=G(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...O$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return G(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return G(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=G(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=G(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=x$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:a$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class lx{client;async noteDocuments($=""){let O=G(await this.client.calendar.noteDocuments({query:{query:$}}));return{documents:O.documents.map((j)=>({document:q.byId(this.client,j.documentId),name:j.name})),teams:O.teams.map((j)=>({team:S$.byId(this.client,j.id),name:j.name}))}}async availabilityCalendars(){return G(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return G(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return G(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return u(async(j)=>{let x=G(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=l6(this.client);let S=await O;return{items:x.items.map((K)=>({event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,inbox:K.event.calendarId?S.get(K.event.calendarId):void 0,role:r6(K.event)})),nextCursor:x.nextCursor}})}async teamPage($){let O=G(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=G(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return m$.list(this.client)}calendar($){return m$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=G(await this.client.calendar.createCalendarEvent({body:d6($)}));return $$.fromRecord(this.client,O)}}function d6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,guestPolicy:$.guestPolicy,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}async function l6($){let{calendars:O}=G(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j.emailAddress]))}function r6($){let O=$.attendees.find((j)=>j.isSelf);if($.viewerCan.organize||O?.isOrganizer)return"organizer";return O?"guest":void 0}class R$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.id,O)}async fetch(){if(this.lookupToken)return G(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=G(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new E(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?Q$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return G(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){G(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){G(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class u$ extends P{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new u$($,O,j)}static from($,O,j){return new u$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return Q$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=G(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class Q$ extends I${messageThreadById($){return L$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return w$(this.client,{type:"call",entity:this},(O)=>u$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return R$.from(this.client,G(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return G(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new Q$($,O)}message($){return u$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?b.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=x$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class rx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class px{client;constructor($){this.client=$}async list(){let{labels:$}=G(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return G(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return G(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return G(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return G(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){G(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){G(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class ax{client;async activity(){return G(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new px($)}byId($){return b.byId(this.client,$)}async dm($){return b.dm(this.client,$)}async private($){return b.private(this.client,$)}async create($){return b.create(this.client,$)}async list(){let{items:$}=G(await this.client.storage.getChannels());return $.map((O)=>b.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=G(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield b.byId(this.client,S.id.toString())}else yield*b.search(this.client,$,O)}}class iO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new iO($,O,j,x)}async stop(){G(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class nO extends P{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new nO($,O,j)}async fetch(){let $=G(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new E(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class K$ extends X${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=K$.byId(this.client,S.chat_id);return iO.byId(this.client,K,S.stream_id,nO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=G(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new K$($,O)}static async create($,O){let{id:j}=G(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new K$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new K$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=G(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=x$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new K$($,O.chat_id)});toMention(){return{tag:a$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class ix{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}create($){return K$.create(this.client,$)}search($,O){return K$.search(this.client,$,O)}}var p6=8;class P$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return G(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new P$($,O,j)}static from($,O,j){return new P$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return sO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=O$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Uj($,O){let j={parent_type:O.type,parent_id:O.id},x=u(async(K)=>{let Z=G(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return uO(S,p6,async(K)=>{let{state:Z,root:X,replies:Y}=G(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...Y].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=G(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...O$(j),thread_id:x?.threadId??null}}));return P$.from($,O,S)}class f$ extends I${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>P$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return G(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>b$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class b$ extends X${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>P$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return G(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new b$($,O)}static from($,O){return new b$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>S$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return G(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>f$.from(this.client,O))}static search=x$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new b$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return f$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Uj(this.client,this.commentParent)}async comment($,O){return sO(this.client,this.commentParent,$,O)}commentById($){return P$.byId(this.client,this.commentParent,$)}}class s$ extends P{tableDetail=new B$(async()=>G(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,O)}async fetch(){return G(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>S$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return G(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:i$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return u(async($)=>{let O=G(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>BO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return u(async(O)=>{let j=G(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>BO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class zj extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new zj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Ij.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return BO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class BO extends P{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new BO($,O,j)}static from($,O,j){return new BO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new E(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Ij extends P{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Ij($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new E(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class nx{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return G(await this.client.storage.listCrmPipelines()).map(($)=>s$.from(this.client,$))}async create($){return s$.from(this.client,G(await this.client.storage.createCrmPipeline({body:$})))}}class sx{client;pipelines;constructor($){this.client=$;this.pipelines=new nx($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=G(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=G(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>f$.from(this.client,x))}async createCompany($){return b$.from(this.client,G(await this.client.storage.createCrmCompany({body:$})))}async settings(){return G(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return G(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return G(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){G(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),m1=Symbol.for("@ts-pattern/isVariadic");var tx=($)=>Boolean($&&typeof $=="object"),Tj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Tj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(tx($)){if(!tx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Tj(X)&&X[m1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),Y=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Q)=>s(L,Z[Q],j))&&S.every((L,Q)=>s(L,X[Q],j))&&(K.length===0||s(K[0],Y,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Tj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},Y$=($)=>{var O,j,x;return tx($)?Tj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,Y$):tO(Object.values($),Y$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function a6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>$0($),and:(O)=>d($,O),or:(O)=>c1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function ex($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[m1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>ex($0($)),select:(O)=>ex(O===void 0?eO($):eO(O,$))})}function $0($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(Y$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>Y$($),matcherType:"optional"})})}var i6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},n6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},s6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"and"})})}function c1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,Y$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,Y$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function eO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:Y$(j))})})}function u1($){return!0}function k$($){return typeof $=="number"}function t$($){return typeof $=="string"}function e$($){return typeof $=="bigint"}var d1=t(m(u1)),t6=t(m(u1)),e6=d1,o$=($)=>Object.assign(t($),{startsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.endsWith(j)))));var j},minLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length>=j))(O))),length:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length===j))(O))),maxLength:(O)=>o$(d($,((j)=>m((x)=>t$(x)&&x.length<=j))(O))),includes:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&x.includes(j)))));var j},regex:(O)=>{return o$(d($,(j=O,m((x)=>t$(x)&&Boolean(x.match(j))))));var j}}),h1=o$(m(t$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>m((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>m((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,m((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,m((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,m((O)=>k$(O)&&O>0))),negative:()=>g$(d($,m((O)=>k$(O)&&O<0)))}),o6=g$(m(k$)),$O=($)=>Object.assign(t($),{between:(O,j)=>$O(d($,((x,S)=>m((K)=>e$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<j))(O))),gt:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>j))(O))),lte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x<=j))(O))),gte:(O)=>$O(d($,((j)=>m((x)=>e$(x)&&x>=j))(O))),positive:()=>$O(d($,m((O)=>e$(O)&&O>0))),negative:()=>$O(d($,m((O)=>e$(O)&&O<0)))}),$7=$O(m(e$)),O7=t(m(function($){return typeof $=="boolean"})),j7=t(m(function($){return typeof $=="symbol"})),x7=t(m(function($){return $==null})),S7=t(m(function($){return $!=null})),Z$={__proto__:null,matcher:G$,optional:$0,array:function(...$){return ex({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return Y$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:i6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:Y$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,Y)=>{j[X]=(j[X]||[]).concat([Y])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:n6(O,(X,Y)=>{let L=s(K,Y,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,Y)=>{x[X]=(x[X]||[]).concat([Y])},[K,Z]=$.length===1?[h1,$[0]]:$;return{matched:s6(O,(X,Y)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Q=L!==null&&s(K,L,S),J=s(K,X,S),I=s(Z,Y,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...Y$($[0]),...Y$($[1])]})})},intersection:d,union:c1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:eO,any:d1,unknown:t6,_:e6,string:h1,number:o6,bigint:$7,boolean:O7,symbol:j7,nullish:x7,nonNullable:S7,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(a6($)))}};class l1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var ox={matched:!1,value:void 0};function c($){return new Hj($,ox)}class Hj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(Y,L)=>{S=!0,K[Y]=L},X=!j.some((Y)=>s(Y,this.input,Z))||x&&!Boolean(x(this.input))?ox:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Hj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Hj(this.input,j?{matched:!0,value:O(this.input,this.input)}:ox)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=Z7){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function Z7($){throw new l1($)}var O0,X7=new Uint8Array(16);function Rj(){if(!O0){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");O0=crypto.getRandomValues.bind(crypto)}return O0(X7)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function r1($,O=0){return(j$[$[O+0]]+j$[$[O+1]]+j$[$[O+2]]+j$[$[O+3]]+"-"+j$[$[O+4]]+j$[$[O+5]]+"-"+j$[$[O+6]]+j$[$[O+7]]+"-"+j$[$[O+8]]+j$[$[O+9]]+"-"+j$[$[O+10]]+j$[$[O+11]]+j$[$[O+12]]+j$[$[O+13]]+j$[$[O+14]]+j$[$[O+15]]).toLowerCase()}var j0={};function K7($,O,j){let x;if($)x=p1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();Y7(j0,S,K),x=p1(K,j0.msecs,j0.seq,O,j)}return O??r1(x)}function Y7($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function p1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var d$=K7;class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new E(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class F${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new F$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Dj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Dj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class J${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new J$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new E(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>A$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return F$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Dj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function _j($,O,j,x={}){let S=G(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Q,version:J})=>[Q.id,J]))}})),K=new Map;for(let Q of[x.database,...(x.baseVersions??[]).map(({table:J})=>J.database)]){if(!Q)continue;let J=K.get(Q.id);if(J)J.add(Q);else K.set(Q.id,new Set([Q]))}let Z=(Q)=>{let J=K.get(Q)?.values().next().value;if(J)return J;let I=O($,Q);return K.set(Q,new Set([I])),I},X=(Q)=>{let J=S.tableDatabases[Q];if(!J)throw Error(`SQL response is missing the owner of table ${Q}`);return J$.byId(Z(J),Q)},Y=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")Y.add(S.statement.databaseId);for(let Q of Y)for(let J of K.get(Q)??[])J.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Q)=>Q).with({kind:"schema"},({databaseId:Q,summary:J})=>({kind:"schema",database:Z(Q),summary:J})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Q,tableId:J,tableName:I})=>({kind:Q,table:X(J),tableName:I})).with({kind:"alterColumnType"},({tableId:Q,tableName:J,columnId:I,columnName:z,to:B})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:A$.byId(V,I),columnName:z,to:B}}).exhaustive();return{result:S.result?G7(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Q)=>F$.byId(L.table,Q)):[],newVersions:Object.entries(S.newVersions).map(([Q,J])=>({table:X(Q),version:J})),readVersions:Object.entries(S.readVersions).map(([Q,J])=>({table:X(Q),version:J})),truncatedTables:S.truncatedTables,statement:L}}function G7($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>F$.byId(x,S)):[]}}class Cj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Cj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class Z0 extends QO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function Mj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var Q7={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function J7($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"date_range"},()=>"Time range").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>Q7[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function x0($){return $.map((O)=>({id:d$(),label:O}))}function a1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function S0($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:Z$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function l$($,O,j){let[x]=$;if($.length!==1||!a1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(S0).join(", ")||"none"}`);return x}class V$ extends P{access=new o(this.client,"database",this);async fetch(){return G(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new f(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=G(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return G(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return _j(this.client,V$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>J$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?J$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=l$(await this.applyOps([{kind:"table",table:d$(),change:{kind:"create",name:$.name}}]),"table","created");return J$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new Z0(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new f(`expected one reorder_tables result, got ${O.map(S0).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=G(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=G(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return J$.byId(this,O.id)}webhookOf($){return Cj.fromRecord(J$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=G(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=G(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),G(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return G(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Mj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),G(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Mj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${J7(O.to)})`,S=d$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:x0(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:Y})=>({row:X,cells:[{column:S,value:Y}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!a1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?S0(Z):"none"}`);return A$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new f(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new f(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new f(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new f(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:Mj(O.type),...O.options!==void 0?{options:x0(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=l$(await this.applyOps([{kind:"column",table:$.id,column:d$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return A$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),l$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:x0(O)}}]),"column","options_added")}}class X0{client;constructor($){this.client=$}query($,O){return _j(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=G(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class K0{client;async byTeamSlug($){let O=G(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=G(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=G(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}async createCanvas($){let O=G(await this.client.storage.createCanvasHandler({body:{documentName:$.name,projectId:$.project?.id}}));return q.byId(this.client,O.documentId)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Pj.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class WO extends P{async fetch(){let{attachment:$}=G(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new WO($,O)}static from($,O){return new WO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=G(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class U$ extends X${access=new o(this.client,"email_thread",this);async followup(){return G(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return G(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return G(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=G(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return $$.fromRecord(this.client,x)}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=G(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new U$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>H$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return G(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>D$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>WO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?D$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}static async archiveMany($,O,j=!0){let x=[];for(let S=0;S<O.length;S+=100){let K=O.slice(S,S+100),Z=G(await $.email.archiveThreads({body:{thread_ids:K.map((Y)=>Y.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let Y of K)if(Y.detail.clear(),X.has(Y.id))x.push(Y)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return G(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=x$({filters:{email_filters:{}},type:"email",make:($,O)=>new U$($,O.thread_id)})}class D$ extends P{async fetch(){return G(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.db_id,O)}static async send($,O){let{message:j}=G(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?D$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>H$.byId(this.client,$));async operationStatus(){return G(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($,O=0){let j=await this.link();await this.mutate((x)=>x.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},query:{draft_generation:O},headers:{"X-Email-Link-Id":j.id}}))}async transferDraft($){let O=await this.detail.get();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:{...$,draft_generation:$.draft_generation??O.draft_generation??0},headers:{"X-Email-Link-Id":O.link_id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return U$.byId(this.client,(await this.detail.get()).thread_db_id)}}class LO extends D${async draftContext(){let $=await this.detail.get();return{headers:{"X-Email-Link-Id":$.link_id},query:{draft_generation:$.draft_generation??0}}}static byId($,O){return new LO($,O)}draftGeneration=this.field("draft_generation");async update($){let{headers:O,query:j}=await this.draftContext();await this.mutate((x)=>x.email.createDraft({headers:O,body:{draft:{...Y0($),db_id:this.id,draft_generation:$.draftGeneration??j.draft_generation}}}))}async delete(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteDraft({path:{id:this.id},headers:$,query:O}))}async schedule($,O){let{headers:j,query:x}=await this.draftContext();await this.mutate((S)=>S.email.upsertScheduledMessage({path:{id:this.id},headers:j,query:x,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let{headers:$,query:O}=await this.draftContext();await this.mutate((j)=>j.email.deleteScheduledDraft({path:{message_id:this.id},headers:$,query:O}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},{headers:j,query:x}=await this.draftContext(),S=await this.mutate((K)=>K.email.addDraftAttachment({path:{id:this.id},headers:j,query:x,body:O}));return{attachment:oO.byId(this.client,this,S.attachment_id,!1,x.draft_generation),uploadUrl:S.upload_url,contentType:S.content_type}}async forwardAttachment($){let{headers:O,query:j}=await this.draftContext(),x=await this.mutate((S)=>S.email.addForwardedAttachment({path:{id:this.id},headers:O,query:j,body:{attachment_id:$.id}}));return oO.byId(this.client,this,x.attachment_id,!0,j.draft_generation)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let{headers:O}=await this.draftContext(),j={draft_generation:$.draftGeneration};if($.forwarded)await this.mutate((x)=>x.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}));else await this.mutate((x)=>x.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O,query:j}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id,$.draftGeneration)}}class oO{draft;id;forwarded;draftGeneration;constructor($,O,j,x){this.draft=$;this.id=O;this.forwarded=j;this.draftGeneration=x}static byId($,O,j,x=!1,S=0){return new oO(O,j,x,S)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded,draftGeneration:this.draftGeneration}}}function Y0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:Y,...L}=$;return{...L,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(Q)=>String.fromCharCode(Q)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,draft_generation:Z,thread_db_id:X?.id,replying_to_id:Y?.id}}class NO extends P{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new NO($,O,void 0,j)}static from($,O,j){return new NO($,O.id,O,j)}async fetch(){let $=G(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new E(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class OO extends P{async fetch(){let{labels:$}=G(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new E(`label ${this.id} not found`);return O}static byId($,O){return new OO($,O)}static async list($){let{labels:O}=G(await $.email.listLabels());return O.map((j)=>new OO($,j.id,j))}static async create($,O){let{label:j}=G(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new OO($,j.id)}async delete(){G(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class G0{client;async createDraft($,O){let j=G(await this.client.email.createDraft({body:{draft:Y0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return LO.byId(this.client,j.draft.db_id)}draftById($){return LO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=G(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield LO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return G(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>NO.from(this.client,O,$))}async upsertFilter($,O){return NO.from(this.client,G(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return G(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return u(async(x)=>{let S=G(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:U$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return U$.byId(this.client,$)}message($){return D$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return H$.byId(this.client,$)}links(){return H$.list(this.client)}async connectionProviders(){return G(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return G(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return D$.send(this.client,$)}search($,O){return U$.search(this.client,$,O)}inbox($){return u(async(O)=>{let j=G(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>U$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return OO.byId(this.client,$)}labels(){return OO.list(this.client)}createLabel($){return OO.create(this.client,$)}archive($,O=!0){return U$.archiveMany(this.client,$,O)}async deleteLabel($){G(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){G(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){G(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return G(await this.client.email.listBlockedSenders()).blocked_emails}}class HO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new HO($,O)}async delete(){G(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Q0{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=G(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return HO.byId(this.client,j.id)}}class J0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=G(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return G(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){G(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){G(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class jO extends I${entityType="foreign_entity";async fetch(){return G(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new jO($,O)}static fromRecord($,O){return new jO($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function i1({login:$,...O}){return{...O,login:$??void 0}}class V0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async bySource($,O){return jO.fromRecord(this.client,G(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=G(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(i1),assignees:j.map(i1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class r${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new r$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new E(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return A$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>UO.byId(this,$.id))}}class UO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new UO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new E(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class RO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new B$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new E(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new RO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new B$(()=>this.load(),$),this}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new E(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>r$.byId(this.form,O.id)):[]}}class Aj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Aj($,O)}}class y$ extends P{async fetch(){return G(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=G(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new y$($,j.form.id,j)}static async list($,O){if(!O)return G(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return G(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new y$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>V$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>J$.byId(V$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>p$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>r$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new f(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new f(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(Y)=>({kind:"group",...x(Y)})).with({kind:"condition"},(Y)=>({kind:"condition",column:j(Y.column),test:c(Y.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Q)=>Q.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Q)=>Q.id)})).with({kind:Z$.union("presence","text","number","date","dateRange","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??d$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(Y)=>({...X,kind:"booking",target:Y.target})).with({kind:"gate"},(Y)=>({...X,kind:"gate",rules:x(Y.rules),message:Y.message})).with({kind:"questions"},(Y)=>({...X,kind:"questions",questions:Y.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??d$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new f("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:p$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:p$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=F$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:RO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(G(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=G(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=r$.byId(this,K.question),X=await c(K.value).with({type:"options"},(Y)=>({type:"options",value:Y.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(Y)=>({type:"entities",value:Y.value.map((L)=>({entityType:L.entityType,entity:Aj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(Y)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:Y.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(Y)=>Y).exhaustive(()=>{throw new f(`answer to question ${Z.id} has a type this SDK doesn't know`)});return{question:Z,value:X}})),x=$.response.row?F$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:RO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?p$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=G(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:p$.byId(this,O.section),count:O.count}))}}async tally(){return G(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=r$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:UO.byId(j,S.option)}}]).with({kind:"checkbox"},(S)=>[{count:x.count,value:S}]).exhaustive((S)=>{return console.warn("macro sdk: unknown form tally bucket",S),[]}))}})}async sharePermissions(){return G(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class B0{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return G(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=G(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new W0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class W0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return G(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class L0{client;constructor($){this.client=$}byId($){return DO.byId(this.client,$)}forEntity($){return DO.byId(this.client,$.id)}}class _O extends P{static byId($,O){return new _O($,O)}async fetch(){return G(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return W$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class $j{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new $j($,O)}async claim($){let O=G(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:W$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class N0{client;constructor($){this.client=$}byId($){return W$.byId(this.client,$)}async list(){return G(await this.client.storage.listHarnesses()).map(($)=>W$.from(this.client,$))}async me(){return W$.from(this.client,G(await this.client.storage.getSelfHarness()))}async deleteSelf(){G(await this.client.storage.deleteSelfHarness())}async agents(){return G(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return G(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=G(await this.client.storage.createHarnessPairing({body:$}));return{pairing:_O.byId(this.client,O.code),device:$j.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var V7="00000001-0000-0000-0000-000000000002",B7="00000001-0000-0000-0002-000000000004";function W7($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class _$ extends q{static byId($,O){return new _$($,O)}static async create($,O){let{documentId:j}=G(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new _$($,j)}static async forPullRequest($,O){let j=W7(O),{pullRequests:x}=G(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new _$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===V7)?.value;return j?.type==="SelectOption"&&j.value.includes(B7)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=x$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new _$($,O.document_id)})}class xO extends P{access=new o(this.client,"initiative",this);static byId($,O){return new xO($,O)}static from($,O){return new xO($,O.id,O)}async fetch(){return G(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>_$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?i$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class U0{client;constructor($){this.client=$}byId($){return xO.byId(this.client,$)}async list(){return G(await this.client.storage.listInitiatives()).initiatives.map(($)=>xO.byId(this.client,$.id))}async create($){return xO.from(this.client,G(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class z0{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async create($){return R$.from(this.client,G(await this.client.storage.meetingCreate({body:$})))}async list(){return G(await this.client.storage.meetingList()).meetings.map(($)=>R$.from(this.client,$))}async active(){return G(await this.client.storage.meetingListActive()).meetings.map(($)=>R$.from(this.client,$))}async lookup($){return R$.from(this.client,G(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends P{async fetch(){return G(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new zO($,O)}static from($,O){return new zO($,O.id,O)}static list($,O){return u(async(j)=>{let x=G(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>zO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class I0{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){G(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){G(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){G(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return G(await this.client.notification.getNotificationTypePreferences())}async enableType($){G(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){G(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class T0{client;constructor($){this.client=$}async list(){let{data:$}=G(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){G(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){G(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){G(await this.client.storage.reorderPinsHandler({body:$}))}}class H0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class CO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new CO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){G(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class SO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return G(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=G(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new SO($,j.id,j)}static byId($,O){return new SO($,O)}static fromRecord($,O){return new SO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return G(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return G(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>CO.from(this.client,this.id,O))}async addOption($){let O=G(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return CO.from(this.client,this.id,O)}async updateOption($,O){let j=G(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return CO.from(this.client,this.id,j)}async deleteOption($){return G(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class R0{client;constructor($){this.client=$}async list($){return G(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return SO.fromRecord(this.client,x)})}create($){return SO.create(this.client,$)}definition($){return SO.byId(this.client,$)}async bulkEntityProperties($){return G(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return G(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return G(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return G(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return G(await this.client.properties.listTags({}))}}function D0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function L7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(D0)})).with({type:"cron"},D0).with({type:"events"},D0).exhaustive()}class ZO extends P{static byId($,O){return new ZO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new ZO($,O.id,O)}async fetch(){return G(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");runVisibility=this.field("run_visibility");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:C0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=G(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>K$.byId(this.client,O.id)).exhaustive();return $.chat_id?K$.byId(this.client,$.chat_id):void 0}async history(){return G(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new _0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class _0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function C0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,run_visibility:$.runVisibility,trigger:L7($.trigger),task:{...O}}}class M0{client;constructor($){this.client=$}byId($){return ZO.byId(this.client,$)}async create($){return ZO.from(this.client,G(await this.client.scheduledAction.createScheduledAction({body:{...C0($),enabled:$.enabled??!0}})))}async list($){return G(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>ZO.from(this.client,O))}}class P0{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}create($){return _$.create(this.client,$)}forPullRequest($){return _$.forPullRequest(this.client,$)}search($,O){return _$.search(this.client,$,O)}}class A0{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class F0{client;constructor($){this.client=$}async get($){return G(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return G(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class E0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}async search($){let O=$.trim().toLocaleLowerCase();if(!O)throw Error("A person search needs a name or email.");let j=await this.client.contacts.getContacts();if(j.response?.status===404)return[];let{contacts:x}=G(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:Y}=G(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(Y.map((Q)=>[Q.id,Q]));for(let Q of X){let J=L.get(Q)??{id:Q};if(`${[J.first_name,J.last_name].filter(Boolean).join(" ")} ${Q}`.toLocaleLowerCase().includes(O))K.push(M.fromName(this.client,J))}}return K}}class XO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return G(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=G(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new XO($,j.id,j,j.signing_secret)}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class w0{client;constructor($){this.client=$}create($){return XO.create(this.client,$)}byId($){return XO.byId(this.client,$)}async list(){let{webhooks:$}=G(await this.client.storage.listWebhooks());return $.map((O)=>XO.fromRecord(this.client,O))}}class MO extends P{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=G(await this.client.storage.linkedAccount());if($?.id!==this.id)throw new E("WhatsApp account is not available");return $}state=this.field("state");identity=this.field("identityJid");owner=this.mappedField("userId",($)=>M.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class C$ extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new C$($,O,j)}static from($,O,j){return new C$($,O,j.id,j)}async fetch(){return G(await this.client.storage.whatsappGroupMessage({path:{group_id:this.group.id,message_id:this.id}}))}body=this.field("body");sender=this.field("sender");sentAt=this.field("sentAt");editedAt=this.field("editedAt");deleted=this.field("deleted");reactions=this.field("reactions");deliveryState=this.field("deliveryState");kind=this.field("kind");forwarded=this.field("forwarded");viewOnce=this.field("viewOnce");mentions=this.field("mentions");rich=this.field("rich");replyTo=this.mappedField("replyTo",($)=>$?C$.byId(this.client,this.group,$):void 0);attachments=this.mappedField("attachments",($)=>$.map((O)=>({ordinal:O.ordinal,state:O.state,fileName:O.fileName,mime:O.mime,size:O.size,width:O.width??void 0,height:O.height??void 0,durationSeconds:O.durationSeconds??void 0,presentation:O.presentation??void 0,url:O.fileId?`${this.client.hosts["static-files"]}/file/${O.fileId}`:void 0})))}class KO{group;id;record;constructor($,O,j){this.group=$;this.id=O;this.record=j}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.jid,O)}get displayName(){return this.record?.displayName??void 0}get mentionToken(){return this.id.split("@")[0]??this.id}get admin(){return this.record?.admin}toJSON(){return{id:this.id,group:this.group.id,displayName:this.displayName,admin:this.admin}}}class YO{id;group;filename;kind;constructor($,O,j,x){this.id=$;this.group=O;this.filename=j;this.kind=x}static byId($,O){return new YO(O,$)}static from($,O){return new YO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,group:this.group.id,filename:this.filename,kind:this.kind}}}class GO extends P{group;constructor($,O,j,x){super($,j,x);this.group=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.id,j)}async fetch(){let O=G(await this.client.storage.linkedDelivery({path:{group_id:this.group.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("WhatsApp send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?C$.byId(this.client,this.group,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=c(O).returnType().with({type:"media"},(x)=>({type:"media",upload:YO.byId(this.group,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:C$.byId(this.client,this.group,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>KO.byId(this.group,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?C$.byId(this.client,this.group,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class v$ extends I${entityType="whatsapp_group";static byId($,O){return new v$($,O)}async fetch(){return G(await this.client.storage.whatsappGroup({path:{group_id:this.id}}))}name=this.field("name");kind=this.field("kind");canSend=this.field("canSend");sendReason=this.field("sendReason");sendingIdentity=this.field("sendingIdentity");unreadCount=this.field("unreadCount");backfill=this.field("backfill");limits=this.field("limits");roster=this.field("roster");participants=this.mappedField("roster",($)=>($?.participants??[]).map((O)=>KO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);owner=this.mappedField("userId",($)=>M.byId(this.client,$));async*messages($={}){yield*u(async(O)=>{let j=G(await this.client.storage.whatsappGroupMessages({path:{group_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>C$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertGroup($.group),await this.mutate((O)=>O.storage.whatsappGroupRead({path:{group_id:this.id},body:{messageId:$.id}}))}async permissions(){return G(await this.client.storage.whatsappGroupPermissions({path:{group_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.whatsappGroupUpdatePermissions({path:{group_id:this.id},body:$}))}async detach(){await this.mutate(($)=>$.storage.linkedDetach({path:{group_id:this.id}}))}async upload($){let O=G(await this.client.storage.linkedUpload({path:{group_id:this.id},body:{file:$}}));return YO.from(this,O)}async reply($,O){if(O.replyTo)this.assertGroup(O.replyTo.group);let j=c($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertGroup(Z.group);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertGroup(S.upload.group),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertGroup(S.message.group),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.linkedReply({path:{group_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return GO.from(this.client,this,x)}async sends(){return G(await this.client.storage.whatsappGroupSends({path:{group_id:this.id}})).map(($)=>GO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedDelivery({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>GO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertGroup(O.group);return G(await this.client.storage.linkedMessageAttachments({path:{group_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:C$.byId(this.client,this,O.messageId),attachments:O.linkedAttachments.map((j)=>({ordinal:j.ordinal,state:j.state,fileName:j.fileName,mime:j.mime,size:j.size,url:j.fileId?`${this.client.hosts["static-files"]}/file/${j.fileId}`:void 0}))}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}assertGroup($){if($.id!==this.id)throw Error("WhatsApp reference belongs to another group")}}function q0($,O){return{chat:IO.byId($,O.id),name:O.name,announcements:O.announcements}}class IO extends P{static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.jid,O)}async fetch(){let{chats:$}=G(await this.client.storage.linkedChats()),O=$.find((j)=>j.jid===this.id);if(!O)throw new E("WhatsApp chat is not available");return O}kind=this.field("kind");name=this.field("name");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?q0(this.client,$):void 0);group=this.mappedField("group",($)=>$?v$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?v$.byId(this.client,$.id):void 0);async adopt(){let $=await this.mutate((O)=>O.storage.linkedAdopt({body:{groupJid:this.id}}));return v$.byId(this.client,$.groupId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class f0{client;constructor($){this.client=$}async account(){let{account:$}=G(await this.client.storage.linkedAccount());return $?MO.from(this.client,$):void 0}async groups(){return G(await this.client.storage.whatsappGroups()).map(($)=>v$.byId(this.client,$.id))}async chats(){return G(await this.client.storage.linkedChats()).chats.map(($)=>IO.from(this.client,$))}byId($){return v$.byId(this.client,$)}}function b0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function n1($,O,j){let x=[];for(let S of b0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:K$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:U$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:b.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new h$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:Q$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:$$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:jO.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var s1="00000000-0000-0000-0000-000000000000",k0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Fj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),t1=($,O)=>$==null?O:{"&":[$,O]};function g0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){g0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{g0(Z,`${O}.${S}[${X}]`)})}class Ej{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(G),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(k0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(k0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)g0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:s1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=G(await this.client.email.listLinks()),K=S.filter((X)=>Fj(X.email_address)===Fj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=t1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(k0))if(!x.includes(S))O[K]={l:{[Z]:s1}}}if($.tags?.length){let S=(await this.sets()).flatMap((Y)=>{let L=Y.definition;if(!L)return[];return Y.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:Y.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let Y of $.tags){let L=S.filter((Q)=>Fj(Q.label)===Fj(Y.label.trim())&&(!Y.scope||Q.scope===Y.scope));if(!L.length)throw Error(`Unknown tag "${Y.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${Y.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((Y)=>({l:{pd:Y.definitionId,v:{so:Y.id}}})).reduce((Y,L)=>Y===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[Y,L]},void 0);O.propf=t1(O.propf,X)}return O}}class y0{client;constructor($){this.client=$}async page($={}){let O=new Ej(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Ej(this.client),j=await O.body($);yield*u((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=G(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>b0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>n1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function e1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},qj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z7(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I7=/\{[^{}]+\}/g,T7=({path:$,url:O})=>{let j=O,x=O.match(I7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,wj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,qj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function v0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var O2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var j2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=wj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=qj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},x2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},H7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function S2($){for(let O of $.security??[]){if(H7($,O.name))continue;let j=await $2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var h0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:j2($.querySerializer),url:$.url}),m0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=bj($.headers,O.headers),j},R7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},bj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class fj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var Z2=()=>({error:new fj,request:new fj,response:new fj}),D7=j2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_7={"Content-Type":"application/json"},Oj=($={})=>({...O2,headers:_7,parseAs:"auto",querySerializer:D7,...$});var c0=($={})=>{let O=m0(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=m0(O,Q),j()},S=Z2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:bj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await S2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=h0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:v0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?x2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return e1({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:v0(I),url:z})};return{buildUrl:(Q)=>h0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var X2=c0(Oj());class K2{client;constructor($){this.client=$?.client??X2}}class Y2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class kj extends K2{static __registry=new Y2;constructor($){super($);kj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function G2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},wj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return PO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},PO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},qj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z7(x),X=Object.entries(S).map(([Y,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I7=/\{[^{}]+\}/g,T7=({path:$,url:O})=>{let j=O,x=O.match(I7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,wj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,qj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},o1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function v0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var $2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var O2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var j2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=wj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=qj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=PO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},x2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},H7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function S2($){for(let O of $.security??[]){if(H7($,O.name))continue;let j=await $2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var h0=($)=>o1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:j2($.querySerializer),url:$.url}),m0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=bj($.headers,O.headers),j},R7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},bj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class fj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var Z2=()=>({error:new fj,request:new fj,response:new fj}),D7=j2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_7={"Content-Type":"application/json"},Oj=($={})=>({...O2,headers:_7,parseAs:"auto",querySerializer:D7,...$});var c0=($={})=>{let O=m0(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=m0(O,Q),j()},S=Z2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:bj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await S2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=h0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:v0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?x2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return e1({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:v0(I),url:z})};return{buildUrl:(Q)=>h0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var X2=c0(Oj());class K2{client;constructor($){this.client=$?.client??X2}}class Y2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class kj extends K2{static __registry=new Y2;constructor($){super($);kj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}chooseAgentMode($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-mode-choice",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}reportAgentSessionAppConnected($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/app-connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}classify($){return($.client??this.client).post({url:"/universal_input/classify",...$,headers:{"Content-Type":"application/json",...$.headers}})}extract($){return($.client??this.client).post({url:"/universal_input/extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function G2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P7(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A7=/\{[^{}]+\}/g,F7=({path:$,url:O})=>{let j=O,x=O.match(A7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,yj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},Q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function u0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=yj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},W2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L2($){for(let O of $.security??[]){if(E7($,O.name))continue;let j=await J2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var d0=($)=>Q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),l0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=hj($.headers,O.headers),j},w7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},hj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class vj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new vj,request:new vj,response:new vj}),q7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f7={"Content-Type":"application/json"},jj=($={})=>({...V2,headers:f7,parseAs:"auto",querySerializer:q7,...$});var r0=($={})=>{let O=l0(jj(),$),j=()=>({...O}),x=(Q)=>{return O=l0(O,Q),j()},S=N2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await L2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=d0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:u0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?W2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return G2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:u0(I),url:z})};return{buildUrl:(Q)=>d0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var U2=r0(jj());class z2{client;constructor($){this.client=$?.client??U2}}class I2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends z2{static __registry=new I2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function T2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return AO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},AO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P7(x),X=Object.entries(S).map(([Y,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A7=/\{[^{}]+\}/g,F7=({path:$,url:O})=>{let j=O,x=O.match(A7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,gj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,yj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},Q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function u0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var J2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var V2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=gj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=yj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=AO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},W2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function L2($){for(let O of $.security??[]){if(E7($,O.name))continue;let j=await J2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var d0=($)=>Q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),l0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=hj($.headers,O.headers),j},w7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},hj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class vj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var N2=()=>({error:new vj,request:new vj,response:new vj}),q7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f7={"Content-Type":"application/json"},jj=($={})=>({...V2,headers:f7,parseAs:"auto",querySerializer:q7,...$});var r0=($={})=>{let O=l0(jj(),$),j=()=>({...O}),x=(Q)=>{return O=l0(O,Q),j()},S=N2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await L2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=d0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:u0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?W2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return G2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:u0(I),url:z})};return{buildUrl:(Q)=>d0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var U2=r0(jj());class z2{client;constructor($){this.client=$?.client??U2}}class I2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends z2{static __registry=new I2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function T2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},cj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},uj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g7(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y7=/\{[^{}]+\}/g,v7=({path:$,url:O})=>{let j=O,x=O.match(y7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,cj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,uj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},H2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function p0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var R2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var D2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var _2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=uj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},C2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},h7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function M2($){for(let O of $.security??[]){if(h7($,O.name))continue;let j=await R2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var a0=($)=>H2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:_2($.querySerializer),url:$.url}),i0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=lj($.headers,O.headers),j},m7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},lj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class dj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var P2=()=>({error:new dj,request:new dj,response:new dj}),c7=_2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u7={"Content-Type":"application/json"},xj=($={})=>({...D2,headers:u7,parseAs:"auto",querySerializer:c7,...$});var n0=($={})=>{let O=i0(xj(),$),j=()=>({...O}),x=(Q)=>{return O=i0(O,Q),j()},S=P2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:lj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await M2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=a0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:p0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?C2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return T2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:p0(I),url:z})};return{buildUrl:(Q)=>a0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var A2=n0(xj());class F2{client;constructor($){this.client=$?.client??A2}}class E2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class rj extends F2{static __registry=new E2;constructor($){super($);rj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function w2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},cj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return FO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},FO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},uj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g7(x),X=Object.entries(S).map(([Y,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y7=/\{[^{}]+\}/g,v7=({path:$,url:O})=>{let j=O,x=O.match(y7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,cj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,uj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},H2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function p0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var R2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var D2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var _2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=uj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=FO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},C2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},h7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function M2($){for(let O of $.security??[]){if(h7($,O.name))continue;let j=await R2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var a0=($)=>H2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:_2($.querySerializer),url:$.url}),i0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=lj($.headers,O.headers),j},m7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},lj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class dj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var P2=()=>({error:new dj,request:new dj,response:new dj}),c7=_2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u7={"Content-Type":"application/json"},xj=($={})=>({...D2,headers:u7,parseAs:"auto",querySerializer:c7,...$});var n0=($={})=>{let O=i0(xj(),$),j=()=>({...O}),x=(Q)=>{return O=i0(O,Q),j()},S=P2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:lj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await M2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=a0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:p0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?C2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return T2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:p0(I),url:z})};return{buildUrl:(Q)=>a0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var A2=n0(xj());class F2{client;constructor($){this.client=$?.client??A2}}class E2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class rj extends F2{static __registry=new E2;constructor($){super($);rj.__registry.set(this,$?.key)}getAvailabilityCalendars($){return($?.client??this.client).get({url:"/availability-calendars",...$})}setAvailabilityCalendar($){return($.client??this.client).put({url:"/availability-calendars/{calendar_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCalendars($){return($?.client??this.client).get({url:"/calendars",...$})}createCalendarEvent($){return($.client??this.client).post({url:"/events",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCalendarEvent($){return($.client??this.client).delete({url:"/events/{event_id}",...$})}updateCalendarEvent($){return($.client??this.client).patch({url:"/events/{event_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}copyCalendarEvent($){return($.client??this.client).post({url:"/events/{event_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteCalendarEventGuests($){return($.client??this.client).post({url:"/events/{event_id}/guests",...$,headers:{"Content-Type":"application/json",...$.headers}})}eventNotes($){return($.client??this.client).get({url:"/events/{event_id}/notes",...$})}unlinkEventNote($){return($.client??this.client).delete({url:"/events/{event_id}/notes/{document_id}",...$})}linkEventNote($){return($.client??this.client).put({url:"/events/{event_id}/notes/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}calendarEventProviderUrl($){return($.client??this.client).get({url:"/events/{event_id}/provider-url",...$})}prepareCalendarReplacement($){return($.client??this.client).post({url:"/events/{event_id}/replacement",...$,headers:{"Content-Type":"application/json",...$.headers}})}rsvpCalendarEvent($){return($.client??this.client).put({url:"/events/{event_id}/rsvp",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}respondToJoinRequest($){return($.client??this.client).put({url:"/join-requests/{request_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}noteDocuments($){return($?.client??this.client).get({url:"/meeting-notes/documents",...$})}documentNoteLinks($){return($.client??this.client).get({url:"/meeting-notes/documents/{document_id}/links",...$})}discardCalendarReplacement($){return($.client??this.client).delete({url:"/replacements/{operation_id}",...$})}calendarReplacementStatus($){return($.client??this.client).get({url:"/replacements/{operation_id}",...$})}confirmCalendarReplacement($){return($.client??this.client).post({url:"/replacements/{operation_id}/confirm",...$})}getTeamSharing($){return($?.client??this.client).get({url:"/team-sharing",...$})}setTeamSharing($){return($.client??this.client).put({url:"/team-sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function w2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p7=/\{[^{}]+\}/g,a7=({path:$,url:O})=>{let j=O,x=O.match(p7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function s0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(i7($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var t0=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),e0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=nj($.headers,O.headers),j},n7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},nj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ij{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new ij,request:new ij,response:new ij}),s7=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t7={"Content-Type":"application/json"},Sj=($={})=>({...b2,headers:t7,parseAs:"auto",querySerializer:s7,...$});var o0=($={})=>{let O=e0(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=e0(O,Q),j()},S=v2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=t0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:s0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?g2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:s0(I),url:z})};return{buildUrl:(Q)=>t0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=o0(Sj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends m2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},pj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},aj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r7(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p7=/\{[^{}]+\}/g,a7=({path:$,url:O})=>{let j=O,x=O.match(p7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,pj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,aj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},q2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function s0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var f2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var b2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var k2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=pj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=aj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},g2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function y2($){for(let O of $.security??[]){if(i7($,O.name))continue;let j=await f2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var t0=($)=>q2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:k2($.querySerializer),url:$.url}),e0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=nj($.headers,O.headers),j},n7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},nj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ij{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var v2=()=>({error:new ij,request:new ij,response:new ij}),s7=k2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t7={"Content-Type":"application/json"},Sj=($={})=>({...b2,headers:t7,parseAs:"auto",querySerializer:s7,...$});var o0=($={})=>{let O=e0(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=e0(O,Q),j()},S=v2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:nj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await y2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=t0(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:s0(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?g2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return w2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:s0(I),url:z})};return{buildUrl:(Q)=>t0({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var h2=o0(Sj());class m2{client;constructor($){this.client=$?.client??h2}}class c2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class sj extends m2{static __registry=new c2;constructor($){super($);sj.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function u2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},tj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$5(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O5=/\{[^{}]+\}/g,j5=({path:$,url:O})=>{let j=O,x=O.match(O5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,ej({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},d2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function $1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var l2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var r2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var p2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},a2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function i2($){for(let O of $.security??[]){if(x5($,O.name))continue;let j=await l2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var O1=($)=>d2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:p2($.querySerializer),url:$.url}),j1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=$x($.headers,O.headers),j},S5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},$x=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class oj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var n2=()=>({error:new oj,request:new oj,response:new oj}),Z5=p2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X5={"Content-Type":"application/json"},Zj=($={})=>({...r2,headers:X5,parseAs:"auto",querySerializer:Z5,...$});var x1=($={})=>{let O=j1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=j1(O,Q),j()},S=n2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:$x(O.headers,Q.headers),serializedBody:void 0};if(J.security)await i2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=O1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:$1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?a2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return u2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:$1(I),url:z})};return{buildUrl:(Q)=>O1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var s2=x1(Zj());class t2{client;constructor($){this.client=$?.client??s2}}class e2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Ox extends t2{static __registry=new e2;constructor($){super($);Ox.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function o2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},tj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return wO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},wO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},ej=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$5(x),X=Object.entries(S).map(([Y,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O5=/\{[^{}]+\}/g,j5=({path:$,url:O})=>{let j=O,x=O.match(O5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,ej({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},d2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function $1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var l2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var r2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var p2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=ej({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=wO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},a2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function i2($){for(let O of $.security??[]){if(x5($,O.name))continue;let j=await l2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var O1=($)=>d2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:p2($.querySerializer),url:$.url}),j1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=$x($.headers,O.headers),j},S5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},$x=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class oj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var n2=()=>({error:new oj,request:new oj,response:new oj}),Z5=p2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X5={"Content-Type":"application/json"},Zj=($={})=>({...r2,headers:X5,parseAs:"auto",querySerializer:Z5,...$});var x1=($={})=>{let O=j1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=j1(O,Q),j()},S=n2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:$x(O.headers,Q.headers),serializedBody:void 0};if(J.security)await i2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=O1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:$1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?a2(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return u2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:$1(I),url:z})};return{buildUrl:(Q)=>O1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var s2=x1(Zj());class t2{client;constructor($){this.client=$?.client??s2}}class e2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Ox extends t2{static __registry=new e2;constructor($){super($);Ox.__registry.set(this,$?.key)}getContacts($){return($?.client??this.client).get({url:"/contacts",...$})}addContact($){return($.client??this.client).post({url:"/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function o2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},jx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},xx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G5(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q5=/\{[^{}]+\}/g,J5=({path:$,url:O})=>{let j=O,x=O.match(Q5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,jx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,xx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},$S=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function S1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var OS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var jS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var xS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=xx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},SS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},V5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function ZS($){for(let O of $.security??[]){if(V5($,O.name))continue;let j=await OS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Z1=($)=>$S({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:xS($.querySerializer),url:$.url}),X1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Zx($.headers,O.headers),j},B5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Zx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Sx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var XS=()=>({error:new Sx,request:new Sx,response:new Sx}),W5=xS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L5={"Content-Type":"application/json"},Xj=($={})=>({...jS,headers:L5,parseAs:"auto",querySerializer:W5,...$});var K1=($={})=>{let O=X1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=X1(O,Q),j()},S=XS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Zx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await ZS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=Z1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:S1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?SS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return o2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:S1(I),url:z})};return{buildUrl:(Q)=>Z1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class GS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Xx extends YS{static __registry=new GS;constructor($){super($);Xx.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function QS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},jx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return qO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},qO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},xx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G5(x),X=Object.entries(S).map(([Y,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q5=/\{[^{}]+\}/g,J5=({path:$,url:O})=>{let j=O,x=O.match(Q5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,jx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,xx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},$S=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function S1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var OS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var jS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var xS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=jx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=xx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=qO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},SS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},V5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function ZS($){for(let O of $.security??[]){if(V5($,O.name))continue;let j=await OS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var Z1=($)=>$S({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:xS($.querySerializer),url:$.url}),X1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Zx($.headers,O.headers),j},B5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Zx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Sx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var XS=()=>({error:new Sx,request:new Sx,response:new Sx}),W5=xS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L5={"Content-Type":"application/json"},Xj=($={})=>({...jS,headers:L5,parseAs:"auto",querySerializer:W5,...$});var K1=($={})=>{let O=X1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=X1(O,Q),j()},S=XS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Zx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await ZS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=Z1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:S1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?SS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return o2({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:S1(I),url:z})};return{buildUrl:(Q)=>Z1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var KS=K1(Xj());class YS{client;constructor($){this.client=$?.client??KS}}class GS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Xx extends YS{static __registry=new GS;constructor($){super($);Xx.__registry.set(this,$?.key)}getAttachment($){return($.client??this.client).get({url:"/email/attachments/{id}",...$})}getAttachmentDocumentId($){return($.client??this.client).get({url:"/email/attachments/{id}/document_id",...$})}cancelBackfillGmail($){return($.client??this.client).delete({url:"/email/backfill/gmail",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBackfillGmail($){return($?.client??this.client).get({url:"/email/backfill/gmail",...$})}getBackfillGmailActive($){return($?.client??this.client).get({url:"/email/backfill/gmail/active",...$})}getBackfillGmail($){return($.client??this.client).get({url:"/email/backfill/gmail/{id}",...$})}listContacts($){return($?.client??this.client).get({url:"/email/contacts",...$})}blockSender($){return($.client??this.client).post({url:"/email/contacts/block",...$,headers:{"Content-Type":"application/json",...$.headers}})}listBlockedSenders($){return($?.client??this.client).get({url:"/email/contacts/blocked",...$})}unblockSender($){return($.client??this.client).post({url:"/email/contacts/unblock",...$,headers:{"Content-Type":"application/json",...$.headers}})}recoverDraftTransfer($){return($.client??this.client).post({url:"/email/draft-transfers/{id}/recover",...$})}createDraft($){return($.client??this.client).post({url:"/email/drafts",...$,headers:{"Content-Type":"application/json",...$.headers}})}getScheduledMessages($){return($?.client??this.client).get({url:"/email/drafts/scheduled",...$})}upsertScheduledMessage($){return($.client??this.client).put({url:"/email/drafts/scheduled/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledDraft($){return($.client??this.client).delete({url:"/email/drafts/scheduled/{message_id}",...$})}deleteDraft($){return($.client??this.client).delete({url:"/email/drafts/{id}",...$})}addDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeDraftAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/attachments/{attachment_id}",...$})}completeDraftAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/attachments/{attachment_id}/complete",...$})}addForwardedAttachment($){return($.client??this.client).post({url:"/email/drafts/{id}/forwarded-attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeForwardedAttachment($){return($.client??this.client).delete({url:"/email/drafts/{id}/forwarded-attachments/{attachment_id}",...$})}messageOperationStatus($){return($.client??this.client).get({url:"/email/drafts/{id}/operation",...$})}resolveMessageOperation($){return($.client??this.client).post({url:"/email/drafts/{id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}transferDraft($){return($.client??this.client).post({url:"/email/drafts/{id}/transfer",...$,headers:{"Content-Type":"application/json",...$.headers}})}listEmailFilters($){return($?.client??this.client).get({url:"/email/filters",...$})}upsertEmailFilter($){return($.client??this.client).put({url:"/email/filters",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEmailFilter($){return($.client??this.client).delete({url:"/email/filters/{id}",...$})}initUser($){return($?.client??this.client).post({url:"/email/init",...$})}listLabels($){return($?.client??this.client).get({url:"/email/labels",...$})}createLabel($){return($.client??this.client).post({url:"/email/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteLabel($){return($.client??this.client).delete({url:"/email/labels/{id}",...$})}listLinks($){return($?.client??this.client).get({url:"/email/links",...$})}healthCheckLinks($){return($?.client??this.client).post({url:"/email/links/health-check",...$})}deleteLink($){return($.client??this.client).delete({url:"/email/links/{link_id}",...$})}disableLinkCalendar($){return($.client??this.client).delete({url:"/email/links/{link_id}/calendar",...$})}resyncLink($){return($.client??this.client).post({url:"/email/links/{link_id}/resync",...$})}sendMessage($){return($.client??this.client).post({url:"/email/messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessagesBatch($){return($.client??this.client).post({url:"/email/messages/batch",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveLabel($){return($.client??this.client).patch({url:"/email/messages/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMessage($){return($.client??this.client).get({url:"/email/messages/{id}",...$})}patchSettings($){return($.client??this.client).patch({url:"/email/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}mailboxSettingsOperations($){return($?.client??this.client).get({url:"/email/settings/operations",...$})}disableSync($){return($?.client??this.client).delete({url:"/email/sync",...$})}archiveThreads($){return($.client??this.client).patch({url:"/email/threads/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewsInboxCursor($){return($.client??this.client).get({url:"/email/threads/previews/cursor/{view}",...$})}archiveThread($){return($.client??this.client).patch({url:"/email/threads/{id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}addRemoveThreadLabel($){return($.client??this.client).patch({url:"/email/threads/{id}/labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThreadMessagesHandler($){return($.client??this.client).get({url:"/email/threads/{id}/messages",...$})}threadOperations($){return($.client??this.client).get({url:"/email/threads/{id}/operations",...$})}threadSeen($){return($.client??this.client).post({url:"/email/threads/{id}/seen",...$})}updateThreadState($){return($.client??this.client).patch({url:"/email/threads/{id}/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}getThread($){return($.client??this.client).get({url:"/email/threads/{thread_id}",...$})}getThreadCalendarInvitations($){return($.client??this.client).get({url:"/email/threads/{thread_id}/calendar-invitations",...$})}copyThreadCalendarInvitation($){return($.client??this.client).post({url:"/email/threads/{thread_id}/messages/{message_id}/calendar-invitations/{invitation_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateThreadProject($){return($.client??this.client).patch({url:"/email/threads/{thread_id}/project",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}}function QS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Kx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Yx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z5(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I5=/\{[^{}]+\}/g,T5=({path:$,url:O})=>{let j=O,x=O.match(I5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Kx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Yx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},JS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Y1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var VS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var BS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var WS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Kx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Yx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},LS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},H5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function NS($){for(let O of $.security??[]){if(H5($,O.name))continue;let j=await VS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var G1=($)=>JS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:WS($.querySerializer),url:$.url}),Q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Qx($.headers,O.headers),j},R5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Qx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Gx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var US=()=>({error:new Gx,request:new Gx,response:new Gx}),D5=WS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_5={"Content-Type":"application/json"},Kj=($={})=>({...BS,headers:_5,parseAs:"auto",querySerializer:D5,...$});var J1=($={})=>{let O=Q1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=US(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Qx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await NS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=G1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:Y1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?LS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return QS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:Y1(I),url:z})};return{buildUrl:(Q)=>G1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var zS=J1(Kj());class IS{client;constructor($){this.client=$?.client??zS}}class TS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Jx extends IS{static __registry=new TS;constructor($){super($);Jx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function HS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var N5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},U5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},z5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Kx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(U5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=N5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return fO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},fO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Yx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=z5(x),X=Object.entries(S).map(([Y,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var I5=/\{[^{}]+\}/g,T5=({path:$,url:O})=>{let j=O,x=O.match(I5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Kx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Yx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},JS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=T5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function Y1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var VS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var BS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var WS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Kx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Yx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=fO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},LS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},H5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function NS($){for(let O of $.security??[]){if(H5($,O.name))continue;let j=await VS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var G1=($)=>JS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:WS($.querySerializer),url:$.url}),Q1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Qx($.headers,O.headers),j},R5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Qx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?R5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Gx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var US=()=>({error:new Gx,request:new Gx,response:new Gx}),D5=WS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),_5={"Content-Type":"application/json"},Kj=($={})=>({...BS,headers:_5,parseAs:"auto",querySerializer:D5,...$});var J1=($={})=>{let O=Q1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=US(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Qx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await NS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=G1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:Y1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?LS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return QS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:Y1(I),url:z})};return{buildUrl:(Q)=>G1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var zS=J1(Kj());class IS{client;constructor($){this.client=$?.client??zS}}class TS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Jx extends IS{static __registry=new TS;constructor($){super($);Jx.__registry.set(this,$?.key)}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getUnsubscribes($){return($?.client??this.client).get({url:"/unsubscribe",...$})}unsubscribeEmail($){return($?.client??this.client).post({url:"/unsubscribe/email",...$})}removeUnsubscribeItem($){return($.client??this.client).delete({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}unsubscribeItem($){return($.client??this.client).post({url:"/unsubscribe/item/{item_type}/{item_id}",...$})}removeUnsubscribeAll($){return($?.client??this.client).delete({url:"/unsubscribe/mute",...$})}unsubscribeAll($){return($?.client??this.client).post({url:"/unsubscribe/mute",...$})}listTypedNotifications($){return($?.client??this.client).get({url:"/v1/user_notifications",...$})}bulkGetTypedNotificationsByEventItemIds($){return($.client??this.client).post({url:"/v1/user_notifications/item/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTypedNotificationsByEventItemId($){return($.client??this.client).get({url:"/v1/user_notifications/item/{event_item_id}",...$})}getNotificationTypePreferences($){return($?.client??this.client).get({url:"/v1/user_notifications/preferences",...$})}disableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/disable",...$})}enableNotificationType($){return($.client??this.client).put({url:"/v1/user_notifications/preferences/{notification_event_type}/enable",...$})}getTypedNotificationById($){return($.client??this.client).get({url:"/v1/user_notifications/{notification_id}",...$})}bulkDeleteUserNotificationsV2($){return($.client??this.client).delete({url:"/v2/user_notifications/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsDone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/done",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsSeen($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/seen",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkMarkNotificationsUndone($){return($.client??this.client).patch({url:"/v2/user_notifications/bulk/undone",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserNotificationV2($){return($.client??this.client).delete({url:"/v2/user_notifications/{notification_id}",...$})}}function HS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Vx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Bx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P5(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A5=/\{[^{}]+\}/g,F5=({path:$,url:O})=>{let j=O,x=O.match(A5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Vx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Bx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},RS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function V1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var DS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var _S={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var CS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Vx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Bx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},MS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function PS($){for(let O of $.security??[]){if(E5($,O.name))continue;let j=await DS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var B1=($)=>RS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:CS($.querySerializer),url:$.url}),W1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Lx($.headers,O.headers),j},w5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Lx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Wx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var AS=()=>({error:new Wx,request:new Wx,response:new Wx}),q5=CS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f5={"Content-Type":"application/json"},Yj=($={})=>({..._S,headers:f5,parseAs:"auto",querySerializer:q5,...$});var L1=($={})=>{let O=W1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=W1(O,Q),j()},S=AS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Lx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await PS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=B1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:V1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?MS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return HS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:V1(I),url:z})};return{buildUrl:(Q)=>B1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var FS=L1(Yj());class ES{client;constructor($){this.client=$?.client??FS}}class wS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Nx extends ES{static __registry=new wS;constructor($){super($);Nx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function qS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var C5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Vx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(M5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=C5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return bO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},bO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Bx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=P5(x),X=Object.entries(S).map(([Y,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var A5=/\{[^{}]+\}/g,F5=({path:$,url:O})=>{let j=O,x=O.match(A5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Vx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Bx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},RS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=F5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function V1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var DS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var _S={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var CS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Vx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Bx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=bO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},MS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},E5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function PS($){for(let O of $.security??[]){if(E5($,O.name))continue;let j=await DS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var B1=($)=>RS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:CS($.querySerializer),url:$.url}),W1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Lx($.headers,O.headers),j},w5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Lx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?w5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Wx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var AS=()=>({error:new Wx,request:new Wx,response:new Wx}),q5=CS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),f5={"Content-Type":"application/json"},Yj=($={})=>({..._S,headers:f5,parseAs:"auto",querySerializer:q5,...$});var L1=($={})=>{let O=W1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=W1(O,Q),j()},S=AS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Lx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await PS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=B1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:V1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?MS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return HS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:V1(I),url:z})};return{buildUrl:(Q)=>B1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var FS=L1(Yj());class ES{client;constructor($){this.client=$?.client??FS}}class wS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Nx extends ES{static __registry=new wS;constructor($){super($);Nx.__registry.set(this,$?.key)}listProperties($){return($.client??this.client).get({url:"/properties/definitions",...$})}createPropertyDefinition($){return($.client??this.client).post({url:"/properties/definitions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyDefinition($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}",...$})}getPropertyDefinition($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}",...$})}getPropertyOptions($){return($.client??this.client).get({url:"/properties/definitions/{definition_id}/options",...$})}addPropertyOption($){return($.client??this.client).post({url:"/properties/definitions/{definition_id}/options",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePropertyOption($){return($.client??this.client).delete({url:"/properties/definitions/{definition_id}/options/{option_id}",...$})}updatePropertyOption($){return($.client??this.client).patch({url:"/properties/definitions/{definition_id}/options/{option_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBulkEntityProperties($){return($.client??this.client).post({url:"/properties/entities/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityProperties($){return($.client??this.client).get({url:"/properties/entities/{entity_type}/{entity_id}",...$})}bulkUpdateEntityPropertyOptions($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEntityProperty($){return($.client??this.client).put({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeEntityPropertyOption($){return($.client??this.client).delete({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}addEntityPropertyOption($){return($.client??this.client).post({url:"/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",...$})}deleteEntityProperty($){return($.client??this.client).delete({url:"/properties/entity_properties/{entity_property_id}",...$})}bulkUpdateEntitiesPropertyOptions($){return($.client??this.client).post({url:"/properties/options/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTags($){return($?.client??this.client).get({url:"/properties/tags",...$})}ensureTagSet($){return($.client??this.client).post({url:"/properties/tags",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeTag($){return($.client??this.client).post({url:"/properties/tags/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}promoteTag($){return($.client??this.client).post({url:"/properties/tags/promote",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function qS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ux=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},zx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g5(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y5=/\{[^{}]+\}/g,v5=({path:$,url:O})=>{let j=O,x=O.match(y5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Ux({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,zx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},fS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function N1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var bS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var kS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var gS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Ux({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=zx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},yS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},h5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function vS($){for(let O of $.security??[]){if(h5($,O.name))continue;let j=await bS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var U1=($)=>fS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:gS($.querySerializer),url:$.url}),z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Tx($.headers,O.headers),j},m5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Tx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Ix{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var hS=()=>({error:new Ix,request:new Ix,response:new Ix}),c5=gS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u5={"Content-Type":"application/json"},Gj=($={})=>({...kS,headers:u5,parseAs:"auto",querySerializer:c5,...$});var I1=($={})=>{let O=z1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=z1(O,Q),j()},S=hS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Tx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await vS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=U1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:N1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?yS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return qS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:N1(I),url:z})};return{buildUrl:(Q)=>U1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var mS=I1(Gj());class cS{client;constructor($){this.client=$?.client??mS}}class uS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Hx extends cS{static __registry=new uS;constructor($){super($);Hx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function dS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var b5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},g5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ux=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(k5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=b5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return kO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},kO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},zx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=g5(x),X=Object.entries(S).map(([Y,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var y5=/\{[^{}]+\}/g,v5=({path:$,url:O})=>{let j=O,x=O.match(y5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Ux({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,zx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},fS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=v5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function N1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var bS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var kS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var gS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Ux({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=zx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=kO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},yS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},h5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function vS($){for(let O of $.security??[]){if(h5($,O.name))continue;let j=await bS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var U1=($)=>fS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:gS($.querySerializer),url:$.url}),z1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Tx($.headers,O.headers),j},m5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Tx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?m5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Ix{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var hS=()=>({error:new Ix,request:new Ix,response:new Ix}),c5=gS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),u5={"Content-Type":"application/json"},Gj=($={})=>({...kS,headers:u5,parseAs:"auto",querySerializer:c5,...$});var I1=($={})=>{let O=z1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=z1(O,Q),j()},S=hS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Tx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await vS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=U1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:N1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?yS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return qS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:N1(I),url:z})};return{buildUrl:(Q)=>U1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var mS=I1(Gj());class cS{client;constructor($){this.client=$?.client??mS}}class uS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Hx extends cS{static __registry=new uS;constructor($){super($);Hx.__registry.set(this,$?.key)}scheduledActionHealth($){return($?.client??this.client).get({url:"/health",...$})}listScheduledActions($){return($?.client??this.client).get({url:"/scheduled-actions",...$})}createScheduledAction($){return($.client??this.client).post({url:"/scheduled-actions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteScheduledAction($){return($.client??this.client).delete({url:"/scheduled-actions/{id}",...$})}getScheduledAction($){return($.client??this.client).get({url:"/scheduled-actions/{id}",...$})}updateScheduledAction($){return($.client??this.client).put({url:"/scheduled-actions/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}setScheduledActionEnabled($){return($.client??this.client).put({url:"/scheduled-actions/{id}/enabled",...$,headers:{"Content-Type":"application/json",...$.headers}})}executeScheduledActionNow($){return($.client??this.client).post({url:"/scheduled-actions/{id}/execute",...$})}listScheduledActionHistory($){return($.client??this.client).get({url:"/scheduled-actions/{id}/history",...$})}}function dS({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Rx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Dx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r5(x),X=Object.entries(S).map(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p5=/\{[^{}]+\}/g,a5=({path:$,url:O})=>{let j=O,x=O.match(p5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Rx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Dx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},lS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function T1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var rS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var pS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var aS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Rx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Dx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},iS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function nS($){for(let O of $.security??[]){if(i5($,O.name))continue;let j=await rS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var H1=($)=>lS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:aS($.querySerializer),url:$.url}),R1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Cx($.headers,O.headers),j},n5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Cx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _x{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var sS=()=>({error:new _x,request:new _x,response:new _x}),s5=aS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t5={"Content-Type":"application/json"},Qj=($={})=>({...pS,headers:t5,parseAs:"auto",querySerializer:s5,...$});var D1=($={})=>{let O=R1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=R1(O,Q),j()},S=sS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Cx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await nS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=H1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:T1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?iS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return dS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:T1(I),url:z})};return{buildUrl:(Q)=>H1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var tS=D1(Qj());class eS{client;constructor($){this.client=$?.client??tS}}class oS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Mx extends eS{static __registry=new oS;constructor($){super($);Mx.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var $6=($,O,j)=>{if(typeof j==="string"||j instanceof Blob)$.append(O,j);else if(j instanceof Date)$.append(O,j.toISOString());else $.append(O,JSON.stringify(j))};var _1={bodySerializer:($)=>{let O=new FormData;return Object.entries($).forEach(([j,x])=>{if(x===void 0||x===null)return;if(Array.isArray(x))x.forEach((S)=>$6(O,j,S));else $6(O,j,x)}),O}},C1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function O6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var d5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},l5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},r5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Rx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(l5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=d5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return gO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},gO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Dx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=r5(x),X=Object.entries(S).map(([Y,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var p5=/\{[^{}]+\}/g,a5=({path:$,url:O})=>{let j=O,x=O.match(p5);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Rx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Dx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},lS=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=a5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function T1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var rS=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var pS={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var aS=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Rx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Dx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=gO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},iS=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},i5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function nS($){for(let O of $.security??[]){if(i5($,O.name))continue;let j=await rS(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var H1=($)=>lS({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:aS($.querySerializer),url:$.url}),R1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Cx($.headers,O.headers),j},n5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Cx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?n5(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _x{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var sS=()=>({error:new _x,request:new _x,response:new _x}),s5=aS({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),t5={"Content-Type":"application/json"},Qj=($={})=>({...pS,headers:t5,parseAs:"auto",querySerializer:s5,...$});var D1=($={})=>{let O=R1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=R1(O,Q),j()},S=sS(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Cx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await nS(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=H1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:T1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?iS(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return dS({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:T1(I),url:z})};return{buildUrl:(Q)=>H1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var tS=D1(Qj());class eS{client;constructor($){this.client=$?.client??tS}}class oS{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Mx extends eS{static __registry=new oS;constructor($){super($);Mx.__registry.set(this,$?.key)}unifiedSearch($){return($.client??this.client).post({url:"/search",...$,headers:{"Content-Type":"application/json",...$.headers}})}simpleUnifiedSearch($){return($.client??this.client).post({url:"/search/simple",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var $6=($,O,j)=>{if(typeof j==="string"||j instanceof Blob)$.append(O,j);else if(j instanceof Date)$.append(O,j.toISOString());else $.append(O,JSON.stringify(j))};var _1={bodySerializer:($)=>{let O=new FormData;return Object.entries($).forEach(([j,x])=>{if(x===void 0||x===null)return;if(Array.isArray(x))x.forEach((S)=>$6(O,j,S));else $6(O,j,x)}),O}},C1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function O6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O4=/\{[^{}]+\}/g,j4=({path:$,url:O})=>{let j=O,x=O.match(O4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var x6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(x4($,O.name))continue;let j=await x6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var P1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),A1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ex($.headers,O.headers),j},S4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ex=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Fx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var K6=()=>({error:new Fx,request:new Fx,response:new Fx}),Z4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X4={"Content-Type":"application/json"},Jj=($={})=>({...C1,headers:X4,parseAs:"auto",querySerializer:Z4,...$});var Vj=($={})=>{let O=A1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=K6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ex(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=P1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:M1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?Z6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>P1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class G6{client;constructor($){this.client=$?.client??Y6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class wx extends G6{static __registry=new Q6;constructor($){super($);wx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({..._1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessage($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}",...$})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var e5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},o5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},$4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Px=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(o5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=e5(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return yO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},yO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Ax=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=$4(x),X=Object.entries(S).map(([Y,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var O4=/\{[^{}]+\}/g,j4=({path:$,url:O})=>{let j=O,x=O.match(O4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,Px({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,Ax({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},j6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=j4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function M1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var x6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var S6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=Px({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=Ax({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=yO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},Z6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},x4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function X6($){for(let O of $.security??[]){if(x4($,O.name))continue;let j=await x6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var P1=($)=>j6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:S6($.querySerializer),url:$.url}),A1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ex($.headers,O.headers),j},S4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ex=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?S4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class Fx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var K6=()=>({error:new Fx,request:new Fx,response:new Fx}),Z4=S6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),X4={"Content-Type":"application/json"},Jj=($={})=>({...C1,headers:X4,parseAs:"auto",querySerializer:Z4,...$});var Vj=($={})=>{let O=A1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=K6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:Ex(O.headers,Q.headers),serializedBody:void 0};if(J.security)await X6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=P1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:M1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?Z6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return O6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:M1(I),url:z})};return{buildUrl:(Q)=>P1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var Y6=Vj(Jj());class G6{client;constructor($){this.client=$?.client??Y6}}class Q6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class wx extends G6{static __registry=new Q6;constructor($){super($);wx.__registry.set(this,$?.key)}listAgents($){return($?.client??this.client).get({url:"/agents",...$})}createAgent($){return($.client??this.client).post({url:"/agents",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAgent($){return($.client??this.client).put({url:"/agents/{agent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAnchor($){return($.client??this.client).delete({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}editAnchor($){return($.client??this.client).patch({url:"/annotations/anchors",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentAnchors($){return($.client??this.client).get({url:"/annotations/anchors/document/{document_id}",...$})}createAnchor($){return($.client??this.client).post({url:"/annotations/anchors/document/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSelfBot($){return($?.client??this.client).get({url:"/bots/me",...$})}getBotOwnerProfiles($){return($?.client??this.client).get({url:"/bots/profiles",...$})}listBotChannels($){return($.client??this.client).get({url:"/bots/{bot_id}/channels",...$})}removeBotFromChannelByBot($){return($.client??this.client).delete({url:"/bots/{bot_id}/channels/{channel_id}",...$})}listOccurrences($){return($.client??this.client).get({url:"/calendar-events",...$})}mentionPreviews($){return($.client??this.client).post({url:"/calendar-events/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}listTeamCalendar($){return($.client??this.client).get({url:"/calendar-events/team",...$})}listTeamOutOfOffice($){return($.client??this.client).get({url:"/calendar-events/team-out-of-office",...$})}eventIcs($){return($.client??this.client).get({url:"/calendar-events/{event_id}/ics",...$})}listJoinRequests($){return($.client??this.client).get({url:"/calendar-events/{event_id}/join-requests",...$})}requestToJoin($){return($.client??this.client).post({url:"/calendar-events/{event_id}/join-requests",...$})}getActiveCalls($){return($?.client??this.client).get({url:"/call/active",...$})}guestCallChatRead($){return($.client??this.client).get({url:"/call/guest-chat/{call_id}",...$})}guestCallChatPost($){return($.client??this.client).post({url:"/call/guest-chat/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLookup($){return($.client??this.client).get({url:"/call/join/{token}",...$})}meetingGuestJoin($){return($.client??this.client).post({url:"/call/join/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingLeave($){return($.client??this.client).post({url:"/call/join/{token}/leave",...$})}meetingGuestParticipants($){return($.client??this.client).get({url:"/call/join/{token}/participants",...$})}meetingList($){return($?.client??this.client).get({url:"/call/meetings",...$})}meetingCreate($){return($.client??this.client).post({url:"/call/meetings",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingListActive($){return($?.client??this.client).get({url:"/call/meetings/active",...$})}meetingInvitePermissions($){return($.client??this.client).get({url:"/call/meetings/invite/{token}",...$})}meetingInvite($){return($.client??this.client).post({url:"/call/meetings/invite/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingInviteUsers($){return($.client??this.client).post({url:"/call/meetings/invite/{token}/users",...$,headers:{"Content-Type":"application/json",...$.headers}})}meetingJoin($){return($.client??this.client).post({url:"/call/meetings/join/{token}",...$})}meetingParticipants($){return($.client??this.client).get({url:"/call/meetings/join/{token}/participants",...$})}meetingPrepare($){return($?.client??this.client).post({url:"/call/meetings/prepare",...$})}meetingCancelPreparation($){return($.client??this.client).delete({url:"/call/meetings/prepare/{preparation_id}",...$})}meetingCancel($){return($.client??this.client).delete({url:"/call/meetings/{meeting_id}",...$})}meetingUpdate($){return($.client??this.client).patch({url:"/call/meetings/{meeting_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchCallRecordPreview($){return($.client??this.client).post({url:"/call/record/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCallRecord($){return($.client??this.client).delete({url:"/call/record/{call_id}",...$})}getCallRecord($){return($.client??this.client).get({url:"/call/record/{call_id}",...$})}editCallRecord($){return($.client??this.client).patch({url:"/call/record/{call_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}declineCall($){return($.client??this.client).post({url:"/call/record/{call_id}/decline",...$})}meetingShare($){return($.client??this.client).post({url:"/call/record/{call_id}/link",...$})}toggleShareWithTeam($){return($.client??this.client).post({url:"/call/record/{call_id}/share-with-team/toggle",...$})}editCallTranscript($){return($.client??this.client).patch({url:"/call/record/{call_id}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}getRingStatus($){return($.client??this.client).get({url:"/call/ring-status/{call_id}",...$})}declineRing($){return($.client??this.client).post({url:"/call/ring-status/{call_id}/decline",...$})}callWebhook($){return($?.client??this.client).post({url:"/call/webhook",...$})}leaveOrEndCall($){return($.client??this.client).delete({url:"/call/{channel_id}",...$})}getOrCreateCall($){return($.client??this.client).get({url:"/call/{channel_id}",...$})}checkActiveCall($){return($.client??this.client).get({url:"/call/{channel_id}/active",...$})}ingestTranscript($){return($.client??this.client).post({url:"/call/{room_name}/transcript",...$,headers:{"Content-Type":"application/json",...$.headers}})}listChannelLabels($){return($?.client??this.client).get({url:"/channel-labels",...$})}createChannelLabel($){return($.client??this.client).post({url:"/channel-labels",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelLabel($){return($.client??this.client).put({url:"/channel-labels/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewSmartTag($){return($.client??this.client).post({url:"/channel-labels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannelLabel($){return($.client??this.client).delete({url:"/channel-labels/{label_id}",...$})}renameChannelLabel($){return($.client??this.client).patch({url:"/channel-labels/{label_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createChannel($){return($.client??this.client).post({url:"/channels",...$,headers:{"Content-Type":"application/json",...$.headers}})}getActivity($){return($?.client??this.client).get({url:"/channels/activity",...$})}postActivity($){return($.client??this.client).post({url:"/channels/activity",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAttachmentReferences($){return($.client??this.client).get({url:"/channels/attachments/{entity_type}/{entity_id}/references",...$})}getOrCreateDm($){return($.client??this.client).post({url:"/channels/get_or_create_dm",...$,headers:{"Content-Type":"application/json",...$.headers}})}getOrCreatePrivate($){return($.client??this.client).post({url:"/channels/get_or_create_private",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannelByCode($){return($.client??this.client).post({url:"/channels/join/{join_code}",...$})}createEntityMention($){return($.client??this.client).post({url:"/channels/mentions",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteEntityMention($){return($.client??this.client).delete({url:"/channels/mentions/{mention_id}",...$})}getBatchChannelPreview($){return($.client??this.client).post({url:"/channels/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteChannel($){return($.client??this.client).delete({url:"/channels/{channel_id}",...$})}getChannel($){return($.client??this.client).get({url:"/channels/{channel_id}",...$})}patchChannel($){return($.client??this.client).patch({url:"/channels/{channel_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelAttachments($){return($.client??this.client).get({url:"/channels/{channel_id}/attachments",...$})}createChannelScopedBot($){return($.client??this.client).post({url:"/channels/{channel_id}/bots/scoped",...$,headers:{"Content-Type":"application/json",...$.headers}})}joinChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/join",...$})}getChannelJoinLink($){return($.client??this.client).get({url:"/channels/{channel_id}/join-link",...$})}leaveChannel($){return($.client??this.client).post({url:"/channels/{channel_id}/leave",...$})}removeParticipants($){return($.client??this.client).delete({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChannelParticipants($){return($.client??this.client).get({url:"/channels/{channel_id}/participants",...$})}addParticipants($){return($.client??this.client).post({url:"/channels/{channel_id}/participants",...$,headers:{"Content-Type":"application/json",...$.headers}})}setChannelPicture($){return($.client??this.client).put({url:"/channels/{channel_id}/profile_picture",...$,headers:{"Content-Type":"application/json",...$.headers}})}postChannelBotWebhook($){return($.client??this.client).post({url:"/channels/{channel_id}/webhook",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteCollabSurface($){return($.client??this.client).delete({url:"/collab_surfaces/{id}",...$})}getCollabSurface($){return($.client??this.client).get({url:"/collab_surfaces/{id}",...$})}ensureCollabSurface($){return($.client??this.client).put({url:"/collab_surfaces/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCollabSurfaceToken($){return($.client??this.client).post({url:"/collab_surfaces/{id}/token",...$})}getChannels($){return($?.client??this.client).get({url:"/comms/channels",...$})}createCrmCompany($){return($.client??this.client).post({url:"/crm/companies",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCompany($){return($.client??this.client).get({url:"/crm/companies/{company_id}",...$})}listCompanyContacts($){return($.client??this.client).get({url:"/crm/companies/{company_id}/contacts",...$})}createCrmContact($){return($.client??this.client).post({url:"/crm/companies/{company_id}/contacts",...$,headers:{"Content-Type":"application/json",...$.headers}})}setEmailSync($){return($.client??this.client).put({url:"/crm/companies/{company_id}/email-sync",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCompanyHidden($){return($.client??this.client).put({url:"/crm/companies/{company_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmCompanyName($){return($.client??this.client).put({url:"/crm/companies/{company_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}searchContacts($){return($?.client??this.client).get({url:"/crm/contacts",...$})}getContactByEmail($){return($.client??this.client).get({url:"/crm/contacts/by-email",...$})}getContact($){return($.client??this.client).get({url:"/crm/contacts/{contact_id}",...$})}setContactHidden($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/hidden",...$,headers:{"Content-Type":"application/json",...$.headers}})}setCrmContactName($){return($.client??this.client).put({url:"/crm/contacts/{contact_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCrmPipelines($){return($?.client??this.client).get({url:"/crm/pipelines",...$})}createCrmPipeline($){return($.client??this.client).post({url:"/crm/pipelines",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipeline($){return($.client??this.client).get({url:"/crm/pipelines/{id}",...$})}renameCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyCrmPipelineOps($){return($.client??this.client).post({url:"/crm/pipelines/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelinePermissions($){return($.client??this.client).get({url:"/crm/pipelines/{id}/permissions",...$})}updateCrmPipelinePermissions($){return($.client??this.client).patch({url:"/crm/pipelines/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineRows($){return($.client??this.client).get({url:"/crm/pipelines/{id}/rows",...$})}queryCrmPipelineRows($){return($.client??this.client).post({url:"/crm/pipelines/{id}/rows",...$,headers:{"Content-Type":"application/json",...$.headers}})}shareCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/sharing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmPipelineTable($){return($.client??this.client).get({url:"/crm/pipelines/{id}/table",...$})}trashCrmPipeline($){return($.client??this.client).put({url:"/crm/pipelines/{id}/trash",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCrmTeamSettings($){return($?.client??this.client).get({url:"/crm/settings",...$})}putCrmTeamSettings($){return($.client??this.client).put({url:"/crm/settings",...$,headers:{"Content-Type":"application/json",...$.headers}})}resetCrmTeamStages($){return($?.client??this.client).delete({url:"/crm/stages",...$})}putCrmTeamStages($){return($.client??this.client).put({url:"/crm/stages",...$,headers:{"Content-Type":"application/json",...$.headers}})}listDatabases($){return($?.client??this.client).get({url:"/databases",...$})}createDatabase($){return($.client??this.client).post({url:"/databases",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDatabaseQuery($){return($.client??this.client).post({url:"/databases/queries",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseQuery($){return($.client??this.client).get({url:"/databases/queries/{query_id}",...$})}queryDatabases($){return($.client??this.client).post({url:"/databases/query",...$,headers:{"Content-Type":"application/json",...$.headers}})}ensureStarterHandler($){return($?.client??this.client).post({url:"/databases/starter",...$})}deliverDatabaseWebhook($){return($.client??this.client).post({url:"/databases/webhooks/{token}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabase($){return($.client??this.client).get({url:"/databases/{id}",...$})}shareDatabaseAwareness($){return($.client??this.client).put({url:"/databases/{id}/awareness",...$,headers:{"Content-Type":"application/json",...$.headers}})}undoDatabaseChange($){return($.client??this.client).post({url:"/databases/{id}/changes/{change}/undo",...$})}importDatabaseTable($){return($.client??this.client).post({url:"/databases/{id}/import",...$,headers:{"Content-Type":"application/json",...$.headers}})}applyDatabaseOps($){return($.client??this.client).post({url:"/databases/{id}/ops",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabasePermissions($){return($.client??this.client).get({url:"/databases/{id}/permissions",...$})}updateDatabasePermissions($){return($.client??this.client).patch({url:"/databases/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseTableChanges($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/changes",...$})}listDatabaseColumnCasts($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/casts",...$})}convertDatabaseColumn($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/conversion",...$,headers:{"Content-Type":"application/json",...$.headers}})}inferDatabaseColumnType($){return($.client??this.client).post({url:"/databases/{id}/tables/{table_id}/columns/{column_id}/infer-type",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDatabaseRowHistory($){return($.client??this.client).get({url:"/databases/{id}/tables/{table_id}/rows/{row_id}/history",...$})}getDatabaseViewPositions($){return($.client??this.client).get({url:"/databases/{id}/views/{view_id}/positions",...$})}listDatabaseWebhooks($){return($.client??this.client).get({url:"/databases/{id}/webhooks",...$})}createDatabaseWebhook($){return($.client??this.client).post({url:"/databases/{id}/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteDatabaseWebhook($){return($.client??this.client).delete({url:"/databases/{id}/webhooks/{webhook_id}",...$})}transcribeDictation($){return($.client??this.client).post({bodySerializer:null,url:"/dictation/transcribe",...$,headers:{"Content-Type":"audio/webm",...$.headers}})}getUserDocumentsHandler($){return($.client??this.client).get({url:"/documents",...$})}createDocument($){return($.client??this.client).post({url:"/documents",...$,headers:{"Content-Type":"application/json",...$.headers}})}createCanvasHandler($){return($.client??this.client).post({url:"/documents/create_canvas",...$,headers:{"Content-Type":"application/json",...$.headers}})}createMarkdownHandler($){return($.client??this.client).post({url:"/documents/create_markdown",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSkillHandler($){return($.client??this.client).post({url:"/documents/create_skill",...$,headers:{"Content-Type":"application/json",...$.headers}})}createSnippetHandler($){return($.client??this.client).post({url:"/documents/create_snippet",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTaskHandler($){return($.client??this.client).post({url:"/documents/create_task",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestTasks($){return($.client??this.client).post({url:"/documents/github_prs/tasks",...$,headers:{"Content-Type":"application/json",...$.headers}})}initializeUserDocuments($){return($?.client??this.client).post({url:"/documents/initialize_user_documents",...$})}getDocumentListHandler($){return($?.client??this.client).get({url:"/documents/list",...$})}validateDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/validate",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsToken($){return($.client??this.client).post({url:"/documents/permissions_token/{document_id}",...$})}presaveDocumentHandler($){return($.client??this.client).put({url:"/documents/presave/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getBatchPreviewHandler($){return($.client??this.client).post({url:"/documents/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentByTeamSlug($){return($.client??this.client).get({url:"/documents/slug/{slug}",...$})}handler($){return($?.client??this.client).get({url:"/documents/starter_docs",...$})}getSystemSkillsHandler($){return($?.client??this.client).get({url:"/documents/system_skills",...$})}deleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}",...$})}getDocument($){return($.client??this.client).get({url:"/documents/{document_id}",...$})}editDocument($){return($.client??this.client).patch({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}saveDocumentHandler($){return($.client??this.client).put({url:"/documents/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentBranchName($){return($.client??this.client).get({url:"/documents/{document_id}/branch_name",...$})}copyDocument($){return($.client??this.client).post({url:"/documents/{document_id}/copy",...$,headers:{"Content-Type":"application/json",...$.headers}})}exportDocument($){return($.client??this.client).get({url:"/documents/{document_id}/export",...$})}getDocumentGithubPullRequests($){return($.client??this.client).get({url:"/documents/{document_id}/github_prs",...$})}getLocationHandler($){return($.client??this.client).get({url:"/documents/{document_id}/location",...$})}getDocumentLocationV3($){return($.client??this.client).get({url:"/documents/{document_id}/location_v3",...$})}permanentlyDeleteDocument($){return($.client??this.client).delete({url:"/documents/{document_id}/permanent",...$})}getDocumentProcessingResult($){return($.client??this.client).get({url:"/documents/{document_id}/processing",...$})}jobProcessingResultHandler($){return($.client??this.client).get({url:"/documents/{document_id}/processing/{job_id}",...$})}revertDeleteDocument($){return($.client??this.client).put({url:"/documents/{document_id}/revert_delete",...$})}getDocumentShortId($){return($.client??this.client).get({url:"/documents/{document_id}/short_id",...$})}simpleSave($){return($.client??this.client).put({url:"/documents/{document_id}/simple_save",...$})}getDocumentTeamShare($){return($.client??this.client).get({url:"/documents/{document_id}/team_share",...$})}setDocumentTeamShare($){return($.client??this.client).put({url:"/documents/{document_id}/team_share",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentTextContent($){return($.client??this.client).get({url:"/documents/{document_id}/text-content",...$})}getDocumentViewsHandler($){return($.client??this.client).get({url:"/documents/{document_id}/views",...$})}getDocumentVersion($){return($.client??this.client).get({url:"/documents/{document_id}/{document_version_id}",...$})}accessRequestsState($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/access-requests",...$})}accessRequestsCancel($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$})}accessRequestsSubmit($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/access-requests/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsResolve($){return($.client??this.client).post({url:"/entities/{entity_type}/{entity_id}/access-requests/{request_id}/resolve",...$,headers:{"Content-Type":"application/json",...$.headers}})}accessRequestsDirect($){return($.client??this.client).get({url:"/entities/{entity_type}/{entity_id}/direct-access",...$})}accessRequestsRemoveDirect($){return($.client??this.client).delete({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$})}accessRequestsSetDirect($){return($.client??this.client).put({url:"/entities/{entity_type}/{entity_id}/direct-access/{user_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getEntityPermission($){return($.client??this.client).get({url:"/entity/{entity_type}/{entity_id}/permissions",...$})}listFavorites($){return($?.client??this.client).get({url:"/favorites",...$})}addFavorite($){return($.client??this.client).post({url:"/favorites",...$,headers:{"Content-Type":"application/json",...$.headers}})}reorderFavorites($){return($.client??this.client).patch({url:"/favorites/reorder",...$,headers:{"Content-Type":"application/json",...$.headers}})}removeFavoriteByEntity($){return($.client??this.client).delete({url:"/favorites/{entity_type}/{entity_id}",...$})}getForeignEntityBySource($){return($.client??this.client).get({url:"/foreign_entity/by_source/{source}/{foreign_entity_id}",...$})}getForeignEntity($){return($.client??this.client).get({url:"/foreign_entity/{id}",...$})}listForms($){return($.client??this.client).get({url:"/forms",...$})}createForm($){return($.client??this.client).post({url:"/forms",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAccessibleForms($){return($?.client??this.client).get({url:"/forms/accessible",...$})}getForm($){return($.client??this.client).get({url:"/forms/{id}",...$})}updateForm($){return($.client??this.client).patch({url:"/forms/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}collaborateForm($){return($.client??this.client).post({url:"/forms/{id}/collaboration",...$})}putFormLayout($){return($.client??this.client).put({url:"/forms/{id}/layout",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormPermissions($){return($.client??this.client).get({url:"/forms/{id}/permissions",...$})}updateFormPermissions($){return($.client??this.client).patch({url:"/forms/{id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}submitFormResponse($){return($.client??this.client).post({url:"/forms/{id}/responses",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMyFormResponse($){return($.client??this.client).get({url:"/forms/{id}/responses/mine",...$})}editMyFormResponse($){return($.client??this.client).put({url:"/forms/{id}/responses/mine",...$,headers:{"Content-Type":"application/json",...$.headers}})}getFormResponseSummary($){return($.client??this.client).get({url:"/forms/{id}/responses/summary",...$})}getFormTally($){return($.client??this.client).get({url:"/forms/{id}/tally",...$})}installSync($){return($?.client??this.client).get({url:"/github/install-sync",...$})}getGithubPullRequestFacets($){return($?.client??this.client).get({url:"/github_pull_requests/facets",...$})}getGithubPullRequest($){return($.client??this.client).get({url:"/github_pull_requests/{id}",...$})}getGithubPullRequestChanges($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes",...$})}getGithubPullRequestChangesPatch($){return($.client??this.client).get({url:"/github_pull_requests/{id}/changes/patch",...$})}createHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings",...$,headers:{"Content-Type":"application/json",...$.headers}})}getHarnessPairing($){return($.client??this.client).get({url:"/harness-pairings/{code}",...$})}approveHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{code}/approve",...$,headers:{"Content-Type":"application/json",...$.headers}})}claimHarnessPairing($){return($.client??this.client).post({url:"/harness-pairings/{pairing_id}/claim",...$,headers:{"Content-Type":"application/json",...$.headers}})}listHarnesses($){return($?.client??this.client).get({url:"/harnesses",...$})}deleteSelfHarness($){return($?.client??this.client).delete({url:"/harnesses/me",...$})}getSelfHarness($){return($?.client??this.client).get({url:"/harnesses/me",...$})}listHarnessAgents($){return($?.client??this.client).get({url:"/harnesses/me/agents",...$})}listHarnessSessions($){return($?.client??this.client).get({url:"/harnesses/me/sessions",...$})}deleteHarness($){return($.client??this.client).delete({url:"/harnesses/{harness_id}",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getHistoryHandler($){return($?.client??this.client).get({url:"/history",...$})}deleteHistoryHandler($){return($.client??this.client).delete({url:"/history/{item_type}/{item_id}",...$})}upsertHistoryHandler($){return($.client??this.client).post({url:"/history/{item_type}/{item_id}",...$})}listInitiatives($){return($?.client??this.client).get({url:"/initiatives",...$})}createInitiative($){return($.client??this.client).post({url:"/initiatives",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteInitiative($){return($.client??this.client).delete({url:"/initiatives/{initiative_id}",...$})}getInitiative($){return($.client??this.client).get({url:"/initiatives/{initiative_id}",...$})}updateInitiative($){return($.client??this.client).patch({url:"/initiatives/{initiative_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getInstructionsHandler($){return($?.client??this.client).get({url:"/instructions",...$})}createInstructionsHandler($){return($?.client??this.client).post({url:"/instructions",...$})}getItemsSoup($){return($?.client??this.client).get({url:"/items/soup",...$})}postItemsSoup($){return($.client??this.client).post({url:"/items/soup",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAst($){return($.client??this.client).post({url:"/items/soup/ast",...$,headers:{"Content-Type":"application/json",...$.headers}})}postItemsSoupAstGrouped($){return($.client??this.client).post({url:"/items/soup/ast/grouped",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimeline($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}",...$})}entityMessageCreate($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageDeleteMessage($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageGetMessage($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$})}entityMessageEdit($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/items/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageReact($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/items/{id}/reactions",...$,headers:{"Content-Type":"application/json",...$.headers}})}entityMessageLegacy($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/legacy/{legacy_id}",...$})}entityMessageDeleteThread($){return($.client??this.client).delete({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessageGetThread($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$})}entityMessagePatchThread($){return($.client??this.client).patch({url:"/messages/{parent_type}/{parent_id}/threads/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}messageTimelineEntries($){return($.client??this.client).get({url:"/messages/{parent_type}/{parent_id}/timeline",...$})}entityMessageTyping($){return($.client??this.client).post({url:"/messages/{parent_type}/{parent_id}/typing",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAccount($){return($?.client??this.client).get({url:"/meta/linked/account",...$})}linkedChats($){return($?.client??this.client).get({url:"/meta/linked/chats",...$})}linkedConfiguration($){return($?.client??this.client).get({url:"/meta/linked/configuration",...$})}linkedConnect($){return($.client??this.client).post({url:"/meta/linked/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedDisconnect($){return($.client??this.client).post({url:"/meta/linked/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedAdopt($){return($.client??this.client).post({url:"/meta/linked/groups/adopt",...$,headers:{"Content-Type":"application/json",...$.headers}})}linkedCancelPairing($){return($.client??this.client).delete({url:"/meta/linked/pairing/{id}",...$})}linkedPairing($){return($.client??this.client).get({url:"/meta/linked/pairing/{id}",...$})}linkedPasskey($){return($.client??this.client).post({url:"/meta/linked/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroups($){return($?.client??this.client).get({url:"/meta/linked/whatsapp-groups",...$})}linkedDetach($){return($.client??this.client).delete({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}whatsappGroup($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}",...$})}linkedUpload($){return($.client??this.client).post({..._1,url:"/meta/linked/whatsapp-groups/{group_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}linkedDelivery($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessages($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages",...$})}linkedMessageAttachments($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupMessage($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/messages/{message_id}",...$})}whatsappGroupPermissions($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$})}whatsappGroupUpdatePermissions($){return($.client??this.client).patch({url:"/meta/linked/whatsapp-groups/{group_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupRead($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappGroupSends($){return($.client??this.client).get({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$})}linkedReply($){return($.client??this.client).post({url:"/meta/linked/whatsapp-groups/{group_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPinsHandler($){return($?.client??this.client).get({url:"/pins",...$})}reorderPinsHandler($){return($.client??this.client).patch({url:"/pins",...$,headers:{"Content-Type":"application/json",...$.headers}})}removePinHandler($){return($.client??this.client).delete({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}addPinHandler($){return($.client??this.client).post({url:"/pins/{pinned_item_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getProjectsHandler($){return($?.client??this.client).get({url:"/projects",...$})}createProjectHandler($){return($.client??this.client).post({url:"/projects",...$,headers:{"Content-Type":"application/json",...$.headers}})}getPendingProjectsHandler($){return($?.client??this.client).get({url:"/projects/pending",...$})}getBatchProjectPreview($){return($.client??this.client).post({url:"/projects/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadFolderHandler($){return($.client??this.client).post({url:"/projects/upload",...$,headers:{"Content-Type":"application/json",...$.headers}})}uploadExtractFolderHandler($){return($.client??this.client).post({url:"/projects/upload_extract",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteProjectHandler($){return($.client??this.client).delete({url:"/projects/{id}",...$})}getProjectHandler($){return($.client??this.client).get({url:"/projects/{id}",...$})}getProjectUserAccessLevel($){return($.client??this.client).get({url:"/projects/{id}/access_level",...$})}getProjectContentHandler($){return($.client??this.client).get({url:"/projects/{id}/content",...$})}permanentlyDeleteProject($){return($.client??this.client).delete({url:"/projects/{id}/permanent",...$})}getProjectPermissionsV2($){return($.client??this.client).get({url:"/projects/{id}/permissions",...$})}revertDeleteProject($){return($.client??this.client).put({url:"/projects/{id}/revert_delete",...$})}recentlyDeleted($){return($?.client??this.client).get({url:"/recents/deleted",...$})}listEmailReminders($){return($?.client??this.client).get({url:"/reminders/email/collection",...$})}getEmailFollowup($){return($.client??this.client).get({url:"/reminders/email/{thread_id}",...$})}setEmailFollowup($){return($.client??this.client).put({url:"/reminders/email/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getViewsHandler($){return($?.client??this.client).get({url:"/saved_views",...$})}createViewHandler($){return($.client??this.client).post({url:"/saved_views",...$,headers:{"Content-Type":"application/json",...$.headers}})}excludeDefaultViewHandler($){return($.client??this.client).post({url:"/saved_views/exclude_default",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteViewHandler($){return($.client??this.client).delete({url:"/saved_views/{saved_view_id}",...$})}patchViewHandler($){return($.client??this.client).patch({url:"/saved_views/{saved_view_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSlackImports($){return($?.client??this.client).get({url:"/slack/imports",...$})}createSlackImport($){return($.client??this.client).post({url:"/slack/imports",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSlackImport($){return($.client??this.client).get({url:"/slack/imports/{job_id}",...$})}cancelSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/cancel",...$})}finalizeSlackImport($){return($.client??this.client).post({url:"/slack/imports/{job_id}/finalize",...$})}registerSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads",...$,headers:{"Content-Type":"application/json",...$.headers}})}completeSlackImportUploads($){return($.client??this.client).post({url:"/slack/imports/{job_id}/uploads/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}bulkWakeupSyncServiceDocuments($){return($.client??this.client).post({url:"/sync_service/wakeup",...$,headers:{"Content-Type":"application/json",...$.headers}})}editThreadV2($){return($.client??this.client).patch({url:"/threads/{thread_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}listUserApiKeys($){return($?.client??this.client).get({url:"/user-api-keys",...$})}createUserApiKey($){return($.client??this.client).post({url:"/user-api-keys",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteUserApiKey($){return($.client??this.client).delete({url:"/user-api-keys/{id}",...$})}deleteUserDocumentViewLocation($){return($.client??this.client).delete({url:"/user_document_view_location/{document_id}",...$})}getUserDocumentViewLocation($){return($.client??this.client).get({url:"/user_document_view_location/{document_id}",...$})}upsertUserDocumentViewLocation($){return($.client??this.client).post({url:"/user_document_view_location/{document_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}getDocumentPermissionsV2($){return($.client??this.client).get({url:"/v2/documents/{document_id}/permissions",...$})}editProjectV2($){return($.client??this.client).patch({url:"/v2/projects/{id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}streamEvents($){return($.client??this.client).sse.get({url:"/webhook/events/stream",...$})}listWebhooks($){return($?.client??this.client).get({url:"/webhook/webhooks",...$})}createWebhook($){return($.client??this.client).post({url:"/webhook/webhooks",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteWebhook($){return($.client??this.client).delete({url:"/webhook/webhooks/{webhook_id}",...$})}getWebhook($){return($.client??this.client).get({url:"/webhook/webhooks/{webhook_id}",...$})}patchWebhook($){return($.client??this.client).patch({url:"/webhook/webhooks/{webhook_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}validateWebhook($){return($.client??this.client).post({url:"/webhook/webhooks/{webhook_id}/validate",...$})}}function J6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((W)=>setTimeout(W,V)));return{stream:async function*(){let V=K??3000,W=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;W++;let A=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)A.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:A,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",k);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let a of g){let i=a.split(`
`),F=[],y;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let C,v=!1;if(F.length){let R=F.join(`
-`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},qx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},fx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G4(x),X=Object.entries(S).map(([Y,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q4=/\{[^{}]+\}/g,J4=({path:$,url:O})=>{let j=O,x=O.match(Q4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,qx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,fx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},V6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function F1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var B6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var L6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=fx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},N6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},V4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U6($){for(let O of $.security??[]){if(V4($,O.name))continue;let j=await B6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var E1=($)=>V6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L6($.querySerializer),url:$.url}),w1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=kx($.headers,O.headers),j},B4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},kx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class bx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var z6=()=>({error:new bx,request:new bx,response:new bx}),W4=L6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L4={"Content-Type":"application/json"},Bj=($={})=>({...W6,headers:L4,parseAs:"auto",querySerializer:W4,...$});var q1=($={})=>{let O=w1(Bj(),$),j=()=>({...O}),x=(Q)=>{return O=w1(O,Q),j()},S=z6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:kx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await U6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=E1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:F1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?N6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return J6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:F1(I),url:z})};return{buildUrl:(Q)=>E1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var I6=q1(Bj());class T6{client;constructor($){this.client=$?.client??I6}}class H6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class gx extends T6{static __registry=new H6;constructor($){super($);gx.__registry.set(this,$?.key)}proxyRequestHandler($){return($.client??this.client).get({url:"/proxy",...$})}getUnfurl($){return($.client??this.client).get({url:"/unfurl",...$})}getUnfurlBulk($){return($.client??this.client).post({url:"/unfurl/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var R6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},f1={dev:{"agent-harness":"https://dev-gateway.macro.com/agent-harness",storage:"https://dev-gateway.macro.com/dss",auth:"https://dev-gateway.macro.com/auth",email:"https://dev-gateway.macro.com/email",calendar:"https://dev-gateway.macro.com/calendar",cognition:"https://dev-gateway.macro.com/cognition",notification:"https://dev-gateway.macro.com/notification",properties:"https://dev-gateway.macro.com/dss",search:"https://dev-gateway.macro.com/dss","scheduled-action":"https://dev-gateway.macro.com/scheduled-action","static-files":"https://static-file-service-dev.macro.com",connection:"https://dev-gateway.macro.com/connection-gateway",contacts:"https://dev-gateway.macro.com/contacts",unfurl:"https://dev-gateway.macro.com/unfurl"},prod:{"agent-harness":"https://gateway.macro.com/agent-harness",storage:"https://gateway.macro.com/dss",auth:"https://gateway.macro.com/auth",email:"https://gateway.macro.com/email",calendar:"https://gateway.macro.com/calendar",cognition:"https://gateway.macro.com/cognition",notification:"https://gateway.macro.com/notification",properties:"https://gateway.macro.com/dss",search:"https://gateway.macro.com/dss","scheduled-action":"https://gateway.macro.com/scheduled-action","static-files":"https://static-file-service.macro.com",connection:"https://gateway.macro.com/connection-gateway",contacts:"https://gateway.macro.com/contacts",unfurl:"https://gateway.macro.com/unfurl"},local:{"agent-harness":"http://localhost:8101",storage:"http://localhost:8086",auth:"http://localhost:8080",email:"http://localhost:8087",calendar:"http://localhost:8088/calendar",cognition:"http://localhost:8101/cognition",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8101/scheduled-action","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function N4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:M.byId($,O.owner_id),...N4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?M.byId($,O):void 0}function D6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>M.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var _6="macro|";function M$($,O){return O.startsWith(_6)&&O.length>_6.length?M.byId($,O.toLowerCase()):void 0}function C6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:M$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function M6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:w.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:w.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:w.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:w.byId($,j.document_id),sourceDocument:w.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:w.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function cO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:u$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:w.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function P6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:cO($,j,j.mentions),sender:M$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:cO($,j),sender:M$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:cO($,j),actor:M$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function A6($){let O=new TextEncoder,j=await crypto.subtle.importKey("raw",O.encode($.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),x=await crypto.subtle.sign("HMAC",j,O.encode(`${$.timestamp}.${$.rawBody}`));return`v1=${new Uint8Array(x).toHex()}`===$.signature}var U4="webhook.validation.test";function z4($,O){return c(O).with({event_type:Z$.string.startsWith("document.")},(j)=>M6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>P6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>D6($,j)).otherwise(()=>{return})}class b1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await A6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===U4)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");return async($)=>{return await this.handle(await $.text(),{event:$.headers.get("x-macro-event")??void 0,eventId:$.headers.get("x-macro-event-id")??void 0,timestamp:$.headers.get("x-macro-timestamp")??void 0,signature:$.headers.get("x-macro-signature")??void 0}),new Response("ok")}}filtersFromHandlers(){let $=[...this.handlers.entries()].filter(([,O])=>O.size>0).map(([O])=>O);return $.length>0?[{events:$}]:[]}async dispatchEvent($){let O=typeof $==="string"?JSON.parse($):$;if(O===null||typeof O!=="object"||!("event_type"in O))return;let j=O,x=this.handlers.get(j.event_type);if(!x||x.size===0)return;let S=z4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function F6(){return}var I4=0,k1;function T4($){k1=$}function z$($,O,j){if(!j&&!k1)return $;let x=(S)=>{for(let K of[k1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...Y)=>{let L={id:++I4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,Y),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var w6="x-macro-user-api-key",H4="mak_",g1="mbot_";function R4($){return c($).with(Z$.string.startsWith(g1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(H4),(O)=>[w6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function E6($){return typeof $==="function"?await $():$}async function D4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await E6(x.token);if(!S.startsWith(g1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:Z$.string},({apiKey:x})=>{if(x.startsWith(g1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[w6,x]]}).with({type:"user"},async({token:x})=>{return[R4(await E6(x))]}).exhaustive()}class y1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=_4($),j=O==="local"?F6():void 0,x={...f1[O],...j?.hosts,...$.hosts};this.hosts=x,this.localPortmap=j;let S=typeof process<"u"?{}.MACRO_WEB_URL:void 0;if(this.webAppUrl=$.webAppUrl??S??j?.webAppUrl??R6[O],this.authConfig=C4($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=z$(new Hx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=z$(new gx({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=z$(new kj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=z$(new mj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=z$(new rj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=z$(new sj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=z$(new Ox({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=z$(new Xx({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=z$(new Jx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=z$(new Nx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=z$(new Mx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=z$(new wx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new b1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):M.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await D4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function _4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in f1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function C4($){if($.auth)return $.auth;if($.token)return{type:"user",token:$.token};let O=typeof process<"u"?{}.MACRO_API_KEY:void 0,j=typeof process<"u"?{}.MACRO_BOT_TOKEN:void 0;if(O&&j)throw Error("both MACRO_API_KEY and MACRO_BOT_TOKEN are set — pass auth to new Macro() to pick one");if(j)return{type:"bot",token:j};return{type:"user",token:O??(()=>{throw Error("no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().")})}}class v1{id;constructor($){this.id=$}static byId($){return new v1($)}toJSON(){return{id:this.id}}}class q6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new y1($);this._client=O,this.routines=new M0(O),this.unfurls=new F0(O),this.agents=new cx(O),this.initiatives=new U0(O),this.apiKeys=new dx(O),this.harnesses=new N0(O),this.meetings=new z0(O),this.githubPullRequests=new L0(O),this.entityMentions=new Q0(O),this.agentSessions=new mx(O),this.ai=new ux(O),this.bots=new rO(O),this.calendar=new lx(O),this.calls=new rx(O),this.channels=new ax(O),this.whatsapp=new f0(O),this.chats=new ix(O),this.crm=new sx(O),this.databases=new X0(O),this.documents=new K0(O),this.email=new G0(O),this.favorites=new J0(O),this.foreignEntities=new V0(O),this.forms=new B0(O),this.notifications=new I0(O),this.pins=new T0(O),this.projects=new H0(O),this.properties=new R0(O),this.tasks=new P0(O),this.teams=new A0(O),this.users=new E0(O),this.webhooks=new w0(O),this.workspace=new y0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new q6({...this.opts,requestedAs:$.id})}}export{a$ as wrapXml,O$ as toBody,T4 as observeRequests,g6 as msg,k6 as here,YO as WhatsAppUpload,GO as WhatsAppSend,KO as WhatsAppParticipant,C$ as WhatsAppMessage,v$ as WhatsAppGroup,IO as WhatsAppChat,MO as WhatsAppAccount,n$ as UserApiKey,lO as ToolApproval,N$ as SessionReview,_0 as RoutineExecution,ZO as Routine,hx as ReviewItem,W0 as PullRequestChangeset,zj as PipelineTable,BO as PipelineRow,Ij as PipelineColumn,L$ as MessageThread,R$ as Meeting,Z0 as MacroOpRefusedError,q6 as Macro,xO as Initiative,_O as HarnessPairing,W$ as Harness,DO as GithubPullRequest,p$ as FormSection,RO as FormResponse,Aj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,HO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,s$ as CrmPipeline,vx as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,v1 as ChannelPicture,JO as ChannelActivity,q$ as CalendarNote,Lj as AgentConversation,T$ as Agent,TO as AccessRequest};
+`);try{C=JSON.parse(R),v=!0}catch{C=R}}if(v){if(S)await S(C);if(x)C=await x(C)}if(j?.({data:C,event:y,id:J,retry:V}),F.length)yield C}}}finally{T.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&W>=Z)break;let _=Math.min(V*2**(W-1),X??30000);await I(_)}}}()}}var K4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},G4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},qx=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(Y4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=K4(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return vO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},vO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},fx=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=G4(x),X=Object.entries(S).map(([Y,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Q4=/\{[^{}]+\}/g,J4=({path:$,url:O})=>{let j=O,x=O.match(Q4);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,qx({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,fx({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},V6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=J4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function F1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var B6=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var L6=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=qx({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=fx({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=vO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},N6=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},V4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function U6($){for(let O of $.security??[]){if(V4($,O.name))continue;let j=await B6(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var E1=($)=>V6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:L6($.querySerializer),url:$.url}),w1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=kx($.headers,O.headers),j},B4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},kx=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?B4(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class bx{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var z6=()=>({error:new bx,request:new bx,response:new bx}),W4=L6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),L4={"Content-Type":"application/json"},Bj=($={})=>({...W6,headers:L4,parseAs:"auto",querySerializer:W4,...$});var q1=($={})=>{let O=w1(Bj(),$),j=()=>({...O}),x=(Q)=>{return O=w1(O,Q),j()},S=z6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:kx(O.headers,Q.headers),serializedBody:void 0};if(J.security)await U6(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=E1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,B;try{let{opts:V,url:W}=await K(Q),T={redirect:"follow",...V,body:F1(V)};z=new Request(W,T);for(let N of S.request.fns)if(N)z=await N(z,V);let A=V.fetch;B=await A(z);for(let N of S.response.fns)if(N)B=await N(B,z,V);let D={request:z,response:B};if(B.ok){let N=(V.parseAs==="auto"?N6(B.headers.get("Content-Type")):V.parseAs)??"json";if(B.status===204||B.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await B[N]();break;case"formData":U=new FormData;break;case"stream":U=B.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await B[N]();break;case"json":{let U=await B.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?B.body:{data:B.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await B.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let W=V;for(let T of S.error.fns)if(T)W=await T(W,B,z,Q);if(W=W||{},J)throw W;return I==="data"?void 0:{error:W,request:z,response:B}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return J6({...I,body:I.body,method:Q,onRequest:async(B,V)=>{let W=new Request(B,V);for(let T of S.request.fns)if(T)W=await T(W,I);return W},serializedBody:F1(I),url:z})};return{buildUrl:(Q)=>E1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var I6=q1(Bj());class T6{client;constructor($){this.client=$?.client??I6}}class H6{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class gx extends T6{static __registry=new H6;constructor($){super($);gx.__registry.set(this,$?.key)}proxyRequestHandler($){return($.client??this.client).get({url:"/proxy",...$})}getUnfurl($){return($.client??this.client).get({url:"/unfurl",...$})}getUnfurlBulk($){return($.client??this.client).post({url:"/unfurl/bulk",...$,headers:{"Content-Type":"application/json",...$.headers}})}}var R6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},f1={dev:{"agent-harness":"https://dev-gateway.macro.com/agent-harness",storage:"https://dev-gateway.macro.com/dss",auth:"https://dev-gateway.macro.com/auth",email:"https://dev-gateway.macro.com/email",calendar:"https://dev-gateway.macro.com/calendar",cognition:"https://dev-gateway.macro.com/cognition",notification:"https://dev-gateway.macro.com/notification",properties:"https://dev-gateway.macro.com/dss",search:"https://dev-gateway.macro.com/dss","scheduled-action":"https://dev-gateway.macro.com/scheduled-action","static-files":"https://static-file-service-dev.macro.com",connection:"https://dev-gateway.macro.com/connection-gateway",contacts:"https://dev-gateway.macro.com/contacts",unfurl:"https://dev-gateway.macro.com/unfurl"},prod:{"agent-harness":"https://gateway.macro.com/agent-harness",storage:"https://gateway.macro.com/dss",auth:"https://gateway.macro.com/auth",email:"https://gateway.macro.com/email",calendar:"https://gateway.macro.com/calendar",cognition:"https://gateway.macro.com/cognition",notification:"https://gateway.macro.com/notification",properties:"https://gateway.macro.com/dss",search:"https://gateway.macro.com/dss","scheduled-action":"https://gateway.macro.com/scheduled-action","static-files":"https://static-file-service.macro.com",connection:"https://gateway.macro.com/connection-gateway",contacts:"https://gateway.macro.com/contacts",unfurl:"https://gateway.macro.com/unfurl"},local:{"agent-harness":"http://localhost:8101",storage:"http://localhost:8086",auth:"http://localhost:8080",email:"http://localhost:8087",calendar:"http://localhost:8088/calendar",cognition:"http://localhost:8101/cognition",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8101/scheduled-action","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function N4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new h$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:M.byId($,O.owner_id),...N4($,O.origin)}}function hO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function mO($,O){return O?M.byId($,O):void 0}function D6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...E$($,j.identity),actor:mO($,j.actor),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...E$($,j.identity),actor:mO($,j.last_turn?.actor),announcement:hO($,j.identity,j.last_turn?.announcement_message_id)})).with({event_type:"agent_session.waiting_for_input"},({metadata:j})=>({event_type:"agent_session.waiting_for_input",metadata:j,...E$($,j.identity),announcement:hO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...E$($,j.identity),mentionedBy:mO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>M.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:mO($,j.turn_in_flight?.actor),announcement:hO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...E$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...E$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var _6="macro|";function M$($,O){return O.startsWith(_6)&&O.length>_6.length?M.byId($,O.toLowerCase()):void 0}function C6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:M$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:M$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function M6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function cO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:Q$.byId($,x.id),message:u$.byId($,x.id,O.message_id),threadId:x.id};if(x.type==="channel")return{type:"channel",channel:b.byId($,x.id),message:e.byId($,x.id,O.message_id,j),thread:O.thread_id?new h$($,x.id,O.thread_id):void 0};return{type:"document",document:q.byId($,x.id),comment:c$.byId($,x.id,O.message_id),threadId:O.root_id}}function P6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:cO($,j,j.mentions),sender:M$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:cO($,j),sender:M$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:cO($,j),actor:M$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:cO($,j),actor:M$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function A6($){let O=new TextEncoder,j=await crypto.subtle.importKey("raw",O.encode($.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),x=await crypto.subtle.sign("HMAC",j,O.encode(`${$.timestamp}.${$.rawBody}`));return`v1=${new Uint8Array(x).toHex()}`===$.signature}var U4="webhook.validation.test";function z4($,O){return c(O).with({event_type:Z$.string.startsWith("document.")},(j)=>M6($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>C6($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>P6($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>D6($,j)).otherwise(()=>{return})}class b1{client;secret;handlers=new Map;constructor($,O){this.client=$;this.secret=O}on($,O){let j=this.handlers.get($)??new Set;return j.add(O),this.handlers.set($,j),()=>j.delete(O)}onSelfMention($){return this.on("message.mentioned",async(O)=>{if(O.metadata.mentioned.entity_id.toLowerCase()!==(await this.client.myPrincipalId()).toLowerCase())return;await $(O)})}async listen($={}){let O=$.filters??this.filtersFromHandlers();if(O.length===0||O.every((K)=>K.events.length===0))throw new f("listen() needs filters — pass filters or register handlers with .on() first");let j=new AbortController;if($.signal)if($.signal.aborted)j.abort();else $.signal.addEventListener("abort",()=>j.abort(),{once:!0});let{stream:x}=await this.client.storage.streamEvents({query:{scope:$.scope??"user",filters:JSON.stringify(O)},signal:j.signal});return(async()=>{try{for await(let K of x)await this.dispatchEvent(K)}catch{if(j.signal.aborted)return;throw new f("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");if(!await A6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===U4)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new f("webhookSecret is required to verify incoming webhook deliveries");return async($)=>{return await this.handle(await $.text(),{event:$.headers.get("x-macro-event")??void 0,eventId:$.headers.get("x-macro-event-id")??void 0,timestamp:$.headers.get("x-macro-timestamp")??void 0,signature:$.headers.get("x-macro-signature")??void 0}),new Response("ok")}}filtersFromHandlers(){let $=[...this.handlers.entries()].filter(([,O])=>O.size>0).map(([O])=>O);return $.length>0?[{events:$}]:[]}async dispatchEvent($){let O=typeof $==="string"?JSON.parse($):$;if(O===null||typeof O!=="object"||!("event_type"in O))return;let j=O,x=this.handlers.get(j.event_type);if(!x||x.size===0)return;let S=z4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function F6(){return}var I4=0,k1;function T4($){k1=$}function z$($,O,j){if(!j&&!k1)return $;let x=(S)=>{for(let K of[k1,j])try{Promise.resolve(K?.(S)).catch(()=>{})}catch{}};return new Proxy($,{get(S,K,Z){let X=Reflect.get(S,K,Z);if(typeof K!=="string"||typeof X!=="function")return X;return async(...Y)=>{let L={id:++I4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,Y),J=Q!==null&&typeof Q==="object"&&"error"in Q&&Q.error!=null;return x({...L,status:J?"failed":"completed"}),Q}catch(Q){throw x({...L,status:"failed"}),Q}}}})}var w6="x-macro-user-api-key",H4="mak_",g1="mbot_";function R4($){return c($).with(Z$.string.startsWith(g1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(H4),(O)=>[w6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function E6($){return typeof $==="function"?await $():$}async function D4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await E6(x.token);if(!S.startsWith(g1))throw Error("user API key passed as a bot token. Use auth: { type: 'user', apiKey } or MACRO_API_KEY.");let K=[["x-macro-bot-token",S]];if(!j?.hasBotScope)K.push(["x-macro-bot-scope",x.scope??(O?"user":"team")]);if(O)K.push(["x-macro-bot-for-macro-user-id",O]);return K}).with({type:"user",apiKey:Z$.string},({apiKey:x})=>{if(x.startsWith(g1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[w6,x]]}).with({type:"user"},async({token:x})=>{return[R4(await E6(x))]}).exhaustive()}class y1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=_4($),j=O==="local"?F6():void 0,x={...f1[O],...j?.hosts,...$.hosts};this.hosts=x,this.localPortmap=j;let S=typeof process<"u"?{}.MACRO_WEB_URL:void 0;if(this.webAppUrl=$.webAppUrl??S??j?.webAppUrl??R6[O],this.authConfig=C4($),this.requestedAs=$.requestedAs,this.requestedAs&&this.authConfig.type!=="bot")throw Error("requestedAs() requires bot auth — a user token always acts as its own user");this.wsVerify=$.wsVerify,this.scheduledAction=z$(new Hx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=z$(new gx({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=z$(new kj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=z$(new mj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=z$(new rj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=z$(new sj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=z$(new Ox({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=z$(new Xx({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=z$(new Jx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=z$(new Nx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=z$(new Mx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=z$(new wx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new b1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new rO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):M.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Vj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await D4(this.authConfig,this.requestedAs,{hasBotScope:j.headers.has("x-macro-bot-scope")});for(let[S,K]of x)j.headers.set(S,K);return j}),O}}function _4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in f1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function C4($){if($.auth)return $.auth;if($.token)return{type:"user",token:$.token};let O=typeof process<"u"?{}.MACRO_API_KEY:void 0,j=typeof process<"u"?{}.MACRO_BOT_TOKEN:void 0;if(O&&j)throw Error("both MACRO_API_KEY and MACRO_BOT_TOKEN are set — pass auth to new Macro() to pick one");if(j)return{type:"bot",token:j};return{type:"user",token:O??(()=>{throw Error("no Macro credential. Set MACRO_API_KEY (API key or bearer token) or MACRO_BOT_TOKEN, or pass token/auth to new Macro().")})}}class v1{id;constructor($){this.id=$}static byId($){return new v1($)}toJSON(){return{id:this.id}}}class q6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new y1($);this._client=O,this.routines=new M0(O),this.unfurls=new F0(O),this.agents=new cx(O),this.initiatives=new U0(O),this.apiKeys=new dx(O),this.harnesses=new N0(O),this.meetings=new z0(O),this.githubPullRequests=new L0(O),this.entityMentions=new Q0(O),this.agentSessions=new mx(O),this.ai=new ux(O),this.bots=new rO(O),this.calendar=new lx(O),this.calls=new rx(O),this.channels=new ax(O),this.whatsapp=new f0(O),this.chats=new ix(O),this.crm=new sx(O),this.databases=new X0(O),this.documents=new K0(O),this.email=new G0(O),this.favorites=new J0(O),this.foreignEntities=new V0(O),this.forms=new B0(O),this.notifications=new I0(O),this.pins=new T0(O),this.projects=new H0(O),this.properties=new R0(O),this.tasks=new P0(O),this.teams=new A0(O),this.users=new E0(O),this.webhooks=new w0(O),this.workspace=new y0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new q6({...this.opts,requestedAs:$.id})}}export{a$ as wrapXml,O$ as toBody,T4 as observeRequests,g6 as msg,k6 as here,YO as WhatsAppUpload,GO as WhatsAppSend,KO as WhatsAppParticipant,C$ as WhatsAppMessage,v$ as WhatsAppGroup,IO as WhatsAppChat,MO as WhatsAppAccount,n$ as UserApiKey,lO as ToolApproval,N$ as SessionReview,_0 as RoutineExecution,ZO as Routine,hx as ReviewItem,W0 as PullRequestChangeset,zj as PipelineTable,BO as PipelineRow,Ij as PipelineColumn,L$ as MessageThread,R$ as Meeting,Z0 as MacroOpRefusedError,q6 as Macro,xO as Initiative,_O as HarnessPairing,W$ as Harness,DO as GithubPullRequest,p$ as FormSection,RO as FormResponse,Aj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,HO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,s$ as CrmPipeline,vx as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,v1 as ChannelPicture,JO as ChannelActivity,q$ as CalendarNote,Lj as AgentConversation,T$ as Agent,TO as AccessRequest};
diff --git a/crates/entity_access/AGENTS.md b/crates/entity_access/AGENTS.md
index 97374fe07a..4123a7d3ba 100644
--- a/crates/entity_access/AGENTS.md
+++ b/crates/entity_access/AGENTS.md
@@ -64,7 +64,7 @@ the entity-access domain service.
checked access at the right level; domain code downstream (e.g.
`entity_mutation`) takes a receipt, not a raw boolean/level.
-- `WhatsAppGroup` resolves ordinary entity-access/link/team grants; its extractor reads `group_id`. Imported WhatsApp attachments inherit current group view access.
+- `WhatsAppGroup` resolves ordinary entity-access/link/team grants; its extractor reads `group_id`.
## Related
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
index 92414704ba..a57a081dda 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs
@@ -78,17 +78,6 @@ pub async fn get_document_access(
AND entity_type = 'document'
AND source_id = ANY($2)
- UNION ALL
- -- A WhatsApp attachment's document is viewable by whoever can view
- -- a chat whose live message holds it, through the chat's one access
- -- rule (whatsapp_group_access_level).
- SELECT 'view'::text AS access_level
- FROM whatsapp_group_attachment wa
- JOIN whatsapp_group_message wm
- ON wm.binding_id = wa.binding_id AND wm.person_id = wa.person_id AND wm.source_id = wa.source_id
- WHERE wa.document_id = $1 AND wa.state = 'ready' AND wm.deleted_at IS NULL
- AND whatsapp_group_access_level(wm.binding_id, $2) IS NOT NULL
-
UNION ALL
-- Source 2: document link share permission
SELECT
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
index c845b1c9fa..1b71ce2ee1 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs
@@ -712,143 +712,3 @@ async fn explain_team_link_matches_access_level(pool: PgPool) -> anyhow::Result<
)));
Ok(())
}
-
-/// A ready WhatsApp attachment document in a chat owned by `owner`; returns
-/// (chat id, attachment document id).
-async fn whatsapp_attachment(pool: &PgPool, owner: &str) -> anyhow::Result<(Uuid, Uuid)> {
- let permission = Uuid::now_v7().to_string();
- sqlx::query!(
- r#"INSERT INTO "SharePermission" (id) VALUES ($1)"#,
- permission
- )
- .execute(pool)
- .await?;
- let group = Uuid::now_v7();
- sqlx::query!(
- r#"INSERT INTO whatsapp_group (id, group_jid, name, share_permission_id, user_id, state)
- VALUES ($1, '[email protected]', 'Chat', $2, $3, 'active')"#,
- group,
- permission,
- owner
- )
- .execute(pool)
- .await?;
- let person = Uuid::now_v7();
- sqlx::query!(
- "INSERT INTO whatsapp_external_person (id, binding_id) VALUES ($1, $2)",
- person,
- group
- )
- .execute(pool)
- .await?;
- sqlx::query!(
- r#"INSERT INTO whatsapp_group_message (id, binding_id, person_id, source_id, message_id, origin, source_at)
- VALUES ($1, $2, $3, 'SOURCE', $1, 'whatsapp', now())"#,
- Uuid::now_v7(),
- group,
- person
- )
- .execute(pool)
- .await?;
- let document = Uuid::now_v7();
- sqlx::query!(
- r#"INSERT INTO whatsapp_group_attachment (binding_id, person_id, source_id, ordinal, document_id, sha256, state)
- VALUES ($1, $2, 'SOURCE', 0, $3, $4, 'ready')"#,
- group,
- person,
- document,
- &[0_u8; 32][..]
- )
- .execute(pool)
- .await?;
- Ok((group, document))
-}
-
-/// The attachment is readable exactly when its chat is, for any sources.
-async fn attachment_follows_chat(
- pool: &PgPool,
- group: Uuid,
- document: Uuid,
- sources: &[&str],
-) -> anyhow::Result<Option<AccessLevel>> {
- let sources = SourceIds(sources.iter().map(|source| (*source).to_owned()).collect());
- let attachment = get_document_access(pool, &document, &sources, None).await?;
- let chat =
- super::super::whatsapp_group_access::get_whatsapp_group_access(pool, &group, &sources)
- .await?;
- assert_eq!(attachment.is_some(), chat.is_some(), "{:?}", sources.0);
- Ok(attachment)
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn a_whatsapp_attachment_is_viewable_through_its_chats_grants(
- pool: PgPool,
-) -> anyhow::Result<()> {
- const VIEWER: &str = "macro|[email protected]";
- insert_user(&pool, OWNER_WITH_TEAM).await?;
- let team = Uuid::now_v7();
- add_owner_to_team(&pool, OWNER_WITH_TEAM, team).await?;
- let (group, document) = whatsapp_attachment(&pool, OWNER_WITH_TEAM).await?;
- let channel = Uuid::now_v7().to_string();
- let team = team.to_string();
-
- for sources in [&[VIEWER][..], &[channel.as_str()], &[team.as_str()]] {
- assert_eq!(
- attachment_follows_chat(&pool, group, document, sources).await?,
- None
- );
- }
-
- sqlx::query!(
- r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, 'whatsapp_group', $2, 'channel', 'view')"#,
- group,
- channel
- )
- .execute(&pool)
- .await?;
- // A bot or person reaching the chat through a channel reads the file.
- assert_eq!(
- attachment_follows_chat(&pool, group, document, &[channel.as_str()]).await?,
- Some(AccessLevel::View)
- );
-
- sqlx::query!(
- r#"UPDATE "SharePermission" SET "linkShare" = 'TEAM', "linkShareAccessLevel" = 'view'
- WHERE id = (SELECT share_permission_id FROM whatsapp_group WHERE id = $1)"#,
- group
- )
- .execute(&pool)
- .await?;
- assert_eq!(
- attachment_follows_chat(&pool, group, document, &[VIEWER, team.as_str()]).await?,
- Some(AccessLevel::View)
- );
- assert_eq!(
- attachment_follows_chat(&pool, group, document, &[VIEWER]).await?,
- None
- );
-
- sqlx::query!(
- r#"UPDATE "SharePermission" SET "linkShare" = 'PUBLIC'
- WHERE id = (SELECT share_permission_id FROM whatsapp_group WHERE id = $1)"#,
- group
- )
- .execute(&pool)
- .await?;
- assert_eq!(
- attachment_follows_chat(&pool, group, document, &[VIEWER]).await?,
- Some(AccessLevel::View)
- );
-
- sqlx::query!(
- "UPDATE whatsapp_group_message SET deleted_at = now() WHERE binding_id = $1",
- group
- )
- .execute(&pool)
- .await?;
- let deleted =
- get_document_access(&pool, &document, &SourceIds(vec![VIEWER.to_owned()]), None).await?;
- assert_eq!(deleted, None, "a deleted message's file is not shared");
- Ok(())
-}
diff --git a/crates/macro_db_client/migrations/20261027194950_whatsapp_attachments_as_static_files.sql b/crates/macro_db_client/migrations/20261027194950_whatsapp_attachments_as_static_files.sql
new file mode 100644
index 0000000000..52a719c22b
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261027194950_whatsapp_attachments_as_static_files.sql
@@ -0,0 +1,34 @@
+-- WhatsApp attachments are stored as static files, like channel images, not
+-- as private documents. The id reserved per attachment (and returned for an
+-- upload) only keys its staged bytes now; the static file id is recorded once
+-- the bytes are stored. The tables hold no rows yet: the session service has
+-- never run in a deployed environment.
+SET LOCAL lock_timeout = '5s';
+
+ALTER TABLE whatsapp_group_attachment RENAME COLUMN document_id TO blob_id;
+ALTER INDEX whatsapp_group_attachment_document_id_key RENAME TO whatsapp_group_attachment_blob_id_key;
+ALTER TABLE whatsapp_group_attachment
+ ADD COLUMN file_id uuid UNIQUE,
+ ADD CONSTRAINT whatsapp_group_attachment_ready_file CHECK (state <> 'ready' OR file_id IS NOT NULL);
+
+ALTER TABLE whatsapp_media_blob RENAME COLUMN document_id TO id;
+
+-- Static files no attachment references any more (the message was deleted,
+-- or its chat or owner went away), until DSS deletes them from the static
+-- file service.
+CREATE TABLE whatsapp_file_deletion (
+ file_id uuid PRIMARY KEY,
+ retry_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX whatsapp_file_deletion_retry ON whatsapp_file_deletion(retry_at);
+
+CREATE FUNCTION whatsapp_attachment_release_file() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF OLD.file_id IS NOT NULL AND (TG_OP = 'DELETE' OR NEW.file_id IS DISTINCT FROM OLD.file_id) THEN
+ INSERT INTO whatsapp_file_deletion (file_id) VALUES (OLD.file_id) ON CONFLICT DO NOTHING;
+ END IF;
+ RETURN NULL;
+END;
+$$;
+CREATE TRIGGER whatsapp_attachment_release_file AFTER DELETE OR UPDATE OF file_id ON whatsapp_group_attachment
+FOR EACH ROW EXECUTE FUNCTION whatsapp_attachment_release_file();
diff --git a/crates/static_file_service_client/src/put_file.rs b/crates/static_file_service_client/src/put_file.rs
index ef7515a2cd..5d3d85e9ea 100644
--- a/crates/static_file_service_client/src/put_file.rs
+++ b/crates/static_file_service_client/src/put_file.rs
@@ -52,6 +52,7 @@ impl StaticFileServiceClient {
content_type: String,
) -> Result<PutFileResponse> {
self.upload(
+ None,
PutFileRequest {
file_name: file_url.to_string(),
content_type: Some(content_type.clone()),
@@ -77,6 +78,28 @@ impl StaticFileServiceClient {
content_type: &str,
) -> Result<PutFileResponse> {
self.upload(
+ None,
+ PutFileRequest {
+ file_name: file_name.to_string(),
+ content_type: Some(content_type.to_string()),
+ extension_data: None,
+ },
+ bytes,
+ content_type,
+ )
+ .await
+ }
+
+ /// [`Self::put_named_bytes`] for a file owned by `owner_id`.
+ pub async fn put_named_bytes_for_user(
+ &self,
+ owner_id: &str,
+ file_name: &str,
+ bytes: Bytes,
+ content_type: &str,
+ ) -> Result<PutFileResponse> {
+ self.upload(
+ Some(owner_id),
PutFileRequest {
file_name: file_name.to_string(),
content_type: Some(content_type.to_string()),
@@ -125,15 +148,21 @@ impl StaticFileServiceClient {
Ok(res.json().await?)
}
- /// Reserve a file and PUT its bytes to the upload URL that comes back.
+ /// Reserve a file (owned by `owner_id`, when given) and PUT its bytes to
+ /// the upload URL that comes back.
async fn upload(
&self,
+ owner_id: Option<&str>,
body: PutFileRequest,
bytes: Bytes,
content_type: &str,
) -> Result<PutFileResponse> {
let full_url = format!("{}/internal/file", self.url);
- let res = self.client.put(&full_url).json(&body).send().await?;
+ let mut request = self.client.put(&full_url).json(&body);
+ if let Some(owner_id) = owner_id {
+ request = request.header(crate::INTERNAL_MACRO_USER_ID_HEADER, owner_id);
+ }
+ let res = request.send().await?;
let status_code = res.status();
diff --git a/crates/whatsapp_e2e/src/test.rs b/crates/whatsapp_e2e/src/test.rs
index 00e6b80553..a6330df74f 100644
--- a/crates/whatsapp_e2e/src/test.rs
+++ b/crates/whatsapp_e2e/src/test.rs
@@ -724,7 +724,7 @@ async fn a_phone_image_is_downloaded_for_import(pool: PgPool) {
let downloaded = wait_for_rows(&world.pool, TIMEOUT, || async {
sqlx::query_scalar!(
"SELECT b.bytes FROM whatsapp_group_attachment a
- JOIN whatsapp_media_blob b ON b.document_id = a.document_id
+ JOIN whatsapp_media_blob b ON b.id = a.blob_id
WHERE a.binding_id = $1 AND a.source_id = $2 AND a.state = 'downloaded'",
binding.id,
&source
diff --git a/crates/whatsapp_e2e/src/test/message_types.rs b/crates/whatsapp_e2e/src/test/message_types.rs
index 570fc3c240..aecd13a382 100644
--- a/crates/whatsapp_e2e/src/test/message_types.rs
+++ b/crates/whatsapp_e2e/src/test/message_types.rs
@@ -356,7 +356,7 @@ async fn media_keeps_its_shape_and_a_media_reply_keeps_its_quote(pool: PgPool) {
let downloaded = wait_for_rows(&world.pool, TIMEOUT, || async {
sqlx::query_scalar!(
"SELECT b.bytes FROM whatsapp_group_attachment a
- JOIN whatsapp_media_blob b ON b.document_id = a.document_id
+ JOIN whatsapp_media_blob b ON b.id = a.blob_id
WHERE a.binding_id = $1 AND a.source_id = $2 AND a.state = 'downloaded'",
binding.id,
&view_once
diff --git a/crates/whatsapp_linked/AGENTS.md b/crates/whatsapp_linked/AGENTS.md
index bbdc3d6f72..7c4dd283bf 100644
--- a/crates/whatsapp_linked/AGENTS.md
+++ b/crates/whatsapp_linked/AGENTS.md
@@ -54,7 +54,9 @@ rows and `NOTIFY` (the `outbound::pg` notify helper).
final schema, including the one view rule `whatsapp_group_access_level`, which
entity_access also calls) and
`20261027061311_validate_entity_whatsapp_group_type.sql` (validates the entity
- type check in its own transaction). Deleting a user cascades to their account,
+ type check in its own transaction), then
+ `20261027194950_whatsapp_attachments_as_static_files.sql` (attachments keep a
+ static `file_id`; released files queue in `whatsapp_file_deletion`). Deleting a user cascades to their account,
chats (with their grants, entity record and sharing settings) and sends;
aliases outlive the account that saw them.
## Boundaries
@@ -90,7 +92,10 @@ rows and `NOTIFY` (the `outbound::pg` notify helper).
`whatsapp_group_reaction`, `whatsapp_group_attachment` and
`whatsapp_group_poll_vote`; never native comms tables.
- Attachment bytes cross Postgres (`whatsapp_media_blob`, ≤ 32 MiB) because the
- session service has no document storage; DSS imports and deletes them.
+ session service has no file storage; DSS stores them as static files (like
+ Chat's media, readable by id) through the `FileStore` port and deletes the
+ blob. A file no attachment references is queued in `whatsapp_file_deletion`
+ (trigger) and deleted by `MediaService::delete_released`.
`events::Media::locator` is sealed by the session service; never read it.
- `src/domain/media.rs` + `src/outbound/pg/media.rs`: download claims, import
queue. `src/domain/shape.rs` reads a staged upload's pixel size and length
diff --git a/crates/whatsapp_linked/src/domain.rs b/crates/whatsapp_linked/src/domain.rs
index 85085c3f15..c084108294 100644
--- a/crates/whatsapp_linked/src/domain.rs
+++ b/crates/whatsapp_linked/src/domain.rs
@@ -10,7 +10,7 @@ pub mod rich;
/// Native notification outbox.
#[cfg(feature = "ports")]
pub mod effects;
-/// Attachment import into private documents.
+/// Attachment import into static files.
#[cfg(feature = "ports")]
pub mod media;
/// Port traits.
diff --git a/crates/whatsapp_linked/src/domain/media.rs b/crates/whatsapp_linked/src/domain/media.rs
index 8d377ed1ef..8fe07e3d7a 100644
--- a/crates/whatsapp_linked/src/domain/media.rs
+++ b/crates/whatsapp_linked/src/domain/media.rs
@@ -1,5 +1,5 @@
-//! Turns downloaded and uploaded attachment bytes into private documents. Runs
-//! in DSS, which owns document storage.
+//! Turns downloaded and uploaded attachment bytes into static files, and
+//! deletes the static files no attachment references any more. Runs in DSS.
use super::ports::*;
use std::sync::Arc;
@@ -7,20 +7,17 @@ use std::sync::Arc;
/// Failed imports before the attachment is shown as unavailable.
const MAX_IMPORT_ATTEMPTS: i32 = 5;
-/// Drains the import queue.
+/// Drains the import and deletion queues.
#[derive(Clone)]
pub struct MediaService {
repository: Arc<dyn MediaRepository>,
- documents: Arc<dyn DocumentStore>,
+ files: Arc<dyn FileStore>,
}
impl MediaService {
- /// Wire the queue and document storage.
- pub fn new(repository: Arc<dyn MediaRepository>, documents: Arc<dyn DocumentStore>) -> Self {
- Self {
- repository,
- documents,
- }
+ /// Wire the queues and static file storage.
+ pub fn new(repository: Arc<dyn MediaRepository>, files: Arc<dyn FileStore>) -> Self {
+ Self { repository, files }
}
/// Import one batch; one failing file never blocks the others. Returns how
@@ -40,17 +37,17 @@ impl MediaService {
let Some(bytes) = self.repository.import_bytes(import).await? else {
continue;
};
- match self.documents.store(import, bytes).await {
- Ok(()) => {
- self.repository.import_stored(import).await?;
+ match self.files.store(import, bytes).await {
+ Ok(file_id) => {
+ self.repository.import_stored(import, file_id).await?;
imported += 1;
}
Err(error) => {
tracing::warn!(
- document_id = %import.document_id,
+ blob_id = %import.blob_id,
attempts = import.attempts,
code = error.current_context().code(),
- error = %error,
+ error = %error,
"WhatsApp attachment import will retry"
);
self.repository
@@ -63,6 +60,35 @@ impl MediaService {
Ok(imported)
}
+ /// Delete one batch of static files no attachment references any more; a
+ /// file that fails stays queued and is retried later. Returns how many
+ /// were deleted.
+ #[tracing::instrument(
+ name = "whatsapp.linked.delete_files",
+ skip_all,
+ err,
+ fields(due, deleted)
+ )]
+ pub async fn delete_released(&self) -> LinkedResult<usize> {
+ let due = self.repository.due_file_deletions(25).await?;
+ tracing::Span::current().record("due", due.len());
+ let mut deleted = vec![];
+ for file_id in due {
+ match self.files.delete(file_id).await {
+ Ok(()) => deleted.push(file_id),
+ Err(error) => tracing::warn!(
+ file_id = %file_id,
+ code = error.current_context().code(),
+ error = %error,
+ "Deleting a WhatsApp attachment file will retry"
+ ),
+ }
+ }
+ self.repository.files_deleted(&deleted).await?;
+ tracing::Span::current().record("deleted", deleted.len());
+ Ok(deleted.len())
+ }
+
/// Delete staged uploads that were never sent, old participant receipts
/// and old consumed pairings.
pub async fn expire_retained(&self) -> LinkedResult<u64> {
diff --git a/crates/whatsapp_linked/src/domain/models.rs b/crates/whatsapp_linked/src/domain/models.rs
index 24ce985400..e9386d3f0a 100644
--- a/crates/whatsapp_linked/src/domain/models.rs
+++ b/crates/whatsapp_linked/src/domain/models.rs
@@ -588,7 +588,7 @@ pub enum ReplyContent {
},
/// One attachment staged through the attachments route.
Media {
- /// The staged upload, which becomes the message's private document.
+ /// The staged upload, imported as the message's static file.
#[serde(rename = "uploadId")]
upload_id: Uuid,
/// Optional caption; audio has none.
@@ -773,7 +773,7 @@ pub const MEDIA_LIMIT_BYTES: usize = 32 * 1024 * 1024;
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schema", schema(as = LinkedUploadedAttachment))]
pub struct UploadedAttachment {
- /// Use as `upload_id` in a media send; also the future document id.
+ /// Use as `upload_id` in a media send.
pub upload_id: Uuid,
/// Display filename.
pub filename: String,
@@ -789,7 +789,7 @@ pub struct UploadedAttachment {
pub enum AttachmentState {
/// Downloading or importing.
Loading,
- /// Imported; `document_id` is set.
+ /// Imported; `file_id` is set.
Ready,
/// Download or import failed for good.
Unavailable,
@@ -813,8 +813,8 @@ pub struct LinkedAttachment {
pub mime: String,
/// Declared size in bytes.
pub size: u64,
- /// The private document, once ready.
- pub document_id: Option<Uuid>,
+ /// The static file holding it, once ready.
+ pub file_id: Option<Uuid>,
/// Pixel width of an image, sticker or video, when WhatsApp declared it.
pub width: Option<u32>,
/// Pixel height, when declared.
diff --git a/crates/whatsapp_linked/src/domain/ports.rs b/crates/whatsapp_linked/src/domain/ports.rs
index 632b682c2c..ce2d11f4ed 100644
--- a/crates/whatsapp_linked/src/domain/ports.rs
+++ b/crates/whatsapp_linked/src/domain/ports.rs
@@ -219,7 +219,7 @@ pub struct SendIntent<'a> {
/// A validated attachment upload.
pub struct StagedUpload<'a> {
- /// Uploader, who will own the document.
+ /// Uploader, who will own the static file.
pub user: &'a MacroUserIdStr<'a>,
/// Group it may be sent to.
pub group_id: Uuid,
@@ -318,7 +318,7 @@ pub trait SessionRepository: Send + Sync {
scope: SessionScope,
limit: i64,
) -> LinkedResult<Vec<MediaImport>>;
- /// Keep downloaded bytes for import into a private document. The bytes must
+ /// Keep downloaded bytes for import into a static file. The bytes must
/// match the expected hash; a ready attachment is never rewritten.
async fn complete_media_import(
&self,
@@ -507,49 +507,55 @@ pub trait GroupPublisher: Send + Sync {
async fn publish(&self, effect: &GroupEffect) -> LinkedResult<()>;
}
-/// Downloaded or uploaded bytes waiting to become a private document.
+/// Downloaded or uploaded bytes waiting to become a static file.
#[derive(Clone)]
-pub struct DocumentImport {
+pub struct FileImport {
/// Which attachment.
pub attachment: AttachmentRef,
- /// Reserved document id.
- pub document_id: Uuid,
- /// The chat whose viewers inherit access to the document.
+ /// The staged bytes' id (the upload id of a file sent from Macro).
+ pub blob_id: Uuid,
+ /// The chat the attachment belongs to.
pub group_id: Uuid,
- /// Owner of the document.
+ /// Owner of the static file: the uploader, or the chat's owner.
pub owner: String,
/// Display filename.
pub filename: String,
/// MIME type.
pub mime: String,
- /// SHA-256 of the bytes.
- pub sha256: [u8; 32],
/// Earlier failed imports.
pub attempts: i32,
}
-/// The import queue between blobs and documents.
+/// The import queue between blobs and static files, and the static files no
+/// attachment references any more.
#[async_trait]
pub trait MediaRepository: Send + Sync {
/// Imports whose retry time has come, claimed, without their bytes.
- async fn due_imports(&self, limit: i64) -> LinkedResult<Vec<DocumentImport>>;
+ async fn due_imports(&self, limit: i64) -> LinkedResult<Vec<FileImport>>;
/// One claimed import's plaintext bytes; `None` once the blob is gone.
- async fn import_bytes(&self, import: &DocumentImport) -> LinkedResult<Option<Vec<u8>>>;
- /// The document holds the bytes: attach it to the message, drop the blob and
- /// queue publication.
- async fn import_stored(&self, import: &DocumentImport) -> LinkedResult<()>;
+ async fn import_bytes(&self, import: &FileImport) -> LinkedResult<Option<Vec<u8>>>;
+ /// `file_id` holds the bytes: attach it to the message, drop the blob and
+ /// queue publication. A file the attachment no longer takes (deleted, or
+ /// imported meanwhile) is queued for deletion instead.
+ async fn import_stored(&self, import: &FileImport, file_id: Uuid) -> LinkedResult<()>;
/// Retry later, or give up and show a notice on the message.
- async fn import_failed(&self, import: &DocumentImport, permanent: bool) -> LinkedResult<()>;
+ async fn import_failed(&self, import: &FileImport, permanent: bool) -> LinkedResult<()>;
/// Delete staged uploads nobody sent, participant receipts older than
/// [`RECEIPT_RETENTION_DAYS`](crate::domain::models::RECEIPT_RETENTION_DAYS)
/// and pairings consumed over a day ago (they keep the expected identity).
async fn expire_retained(&self) -> LinkedResult<u64>;
+ /// Static files no attachment references any more, claimed for deletion.
+ async fn due_file_deletions(&self, limit: i64) -> LinkedResult<Vec<Uuid>>;
+ /// The static file service no longer holds these files.
+ async fn files_deleted(&self, files: &[Uuid]) -> LinkedResult<()>;
}
-/// Private document storage owned by the documents domain.
+/// Static file storage, the same as channel media's.
#[async_trait]
-pub trait DocumentStore: Send + Sync {
- /// Create the document with the reserved id, owned by `owner`, holding the
- /// bytes; group viewers inherit attachment access. Never rewrites uploaded bytes.
- async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()>;
+pub trait FileStore: Send + Sync {
+ /// Store the bytes as a new static file owned by `import.owner`; returns
+ /// its id.
+ async fn store(&self, import: &FileImport, bytes: Vec<u8>) -> LinkedResult<Uuid>;
+ /// Delete one static file; one that is already gone counts as deleted.
+ async fn delete(&self, file_id: Uuid) -> LinkedResult<()>;
}
diff --git a/crates/whatsapp_linked/src/domain/session.rs b/crates/whatsapp_linked/src/domain/session.rs
index 795fd708b8..d486fa212a 100644
--- a/crates/whatsapp_linked/src/domain/session.rs
+++ b/crates/whatsapp_linked/src/domain/session.rs
@@ -147,8 +147,8 @@ impl SessionService {
Ok(claimed)
}
- /// Hand over decrypted bytes for an import. DSS turns them into a private
- /// document whose access inherits the group.
+ /// Hand over decrypted bytes for an import. DSS stores them as a static
+ /// file.
#[tracing::instrument(name = "whatsapp.session.complete_media", skip_all, err, fields(account_id = %scope.account_id, size = bytes.len()))]
pub async fn complete_media_import(
&self,
diff --git a/crates/whatsapp_linked/src/outbound/pg/bindings.rs b/crates/whatsapp_linked/src/outbound/pg/bindings.rs
index 163c952ad8..3e80bddbfb 100644
--- a/crates/whatsapp_linked/src/outbound/pg/bindings.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/bindings.rs
@@ -125,7 +125,7 @@ impl BindingRepository for PgLinkedRepository {
messages: &[Uuid],
) -> LinkedResult<Vec<MessageAttachments>> {
let rows = sqlx::query!(
- r#"SELECT m.message_id AS "message_id!", a.ordinal, a.state, a.filename, a.mime, a.size, a.document_id,
+ r#"SELECT m.message_id AS "message_id!", a.ordinal, a.state, a.filename, a.mime, a.size, a.file_id,
a.width, a.height, a.duration_seconds, a.presentation
FROM whatsapp_group_attachment a
JOIN whatsapp_group_message m ON m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id
@@ -152,7 +152,7 @@ impl BindingRepository for PgLinkedRepository {
file_name: row.filename.unwrap_or_default(),
mime,
size: row.size.unwrap_or(0).max(0) as u64,
- document_id: (state == AttachmentState::Ready).then_some(row.document_id),
+ file_id: row.file_id,
width: row.width.map(|value| value.max(0) as u32),
height: row.height.map(|value| value.max(0) as u32),
duration_seconds: row.duration_seconds.map(|value| value.max(0) as u32),
diff --git a/crates/whatsapp_linked/src/outbound/pg/ingest.rs b/crates/whatsapp_linked/src/outbound/pg/ingest.rs
index 013339a872..f0ed19ef40 100644
--- a/crates/whatsapp_linked/src/outbound/pg/ingest.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/ingest.rs
@@ -369,7 +369,7 @@ async fn reserve_attachments_in(
"failed"
};
sqlx::query!(
- r#"INSERT INTO whatsapp_group_attachment (binding_id, person_id, source_id, ordinal, document_id, sha256, state, account_id, locator, mime, filename, size,
+ r#"INSERT INTO whatsapp_group_attachment (binding_id, person_id, source_id, ordinal, blob_id, sha256, state, account_id, locator, mime, filename, size,
width, height, duration_seconds, presentation)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
ON CONFLICT (binding_id, person_id, source_id, ordinal) DO UPDATE SET account_id = excluded.account_id, locator = excluded.locator
@@ -477,7 +477,7 @@ pub(super) async fn persist_in(
reserve_attachments_in(tx, r, message).await?;
}
if r.deleted_at.is_some() {
- sqlx::query!("UPDATE whatsapp_group_attachment SET state = 'deleted' WHERE binding_id = $1 AND person_id = $2 AND source_id = $3",r.binding.id,r.person,r.source)
+ sqlx::query!("UPDATE whatsapp_group_attachment SET state = 'deleted', file_id = NULL WHERE binding_id = $1 AND person_id = $2 AND source_id = $3",r.binding.id,r.person,r.source)
.execute(&mut **tx).await.map_err(failure)?;
}
Ok(r.create || changed || matches!(message.kind, MessageKind::Edit | MessageKind::Delete))
diff --git a/crates/whatsapp_linked/src/outbound/pg/media.rs b/crates/whatsapp_linked/src/outbound/pg/media.rs
index d148ea68cc..666dde11a5 100644
--- a/crates/whatsapp_linked/src/outbound/pg/media.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/media.rs
@@ -1,11 +1,12 @@
-//! Attachment downloads (session service) and their import into private
-//! documents (DSS). States: `pending` → `downloaded` (bytes in
-//! `whatsapp_media_blob`) → `ready`, or `failed`; `deleted` follows the message.
+//! Attachment downloads (session service) and their import into static files
+//! (DSS). States: `pending` → `downloaded` (bytes in `whatsapp_media_blob`) →
+//! `ready` (`file_id` set), or `failed`; `deleted` follows the message. A file
+//! an attachment lets go of is queued in `whatsapp_file_deletion` by a trigger.
use super::*;
use crate::domain::{
events::*,
- ports::{DocumentImport, MediaRepository},
+ ports::{FileImport, MediaRepository},
};
use async_trait::async_trait;
use sha2::{Digest, Sha256};
@@ -25,7 +26,7 @@ async fn fail_in(
AND a.state IN ('pending', 'downloaded')
AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id
AND b.id = a.binding_id
- RETURNING a.document_id, a.filename, m.message_id, b.id AS group_id"#,
+ RETURNING a.blob_id, a.filename, m.message_id, b.id AS group_id"#,
attachment.binding_id,
attachment.person_id,
attachment.source_id,
@@ -35,13 +36,10 @@ async fn fail_in(
.await
.map_err(failure)?;
let Some(row) = row else { return Ok(()) };
- sqlx::query!(
- "DELETE FROM whatsapp_media_blob WHERE document_id = $1",
- row.document_id
- )
- .execute(&mut **tx)
- .await
- .map_err(failure)?;
+ sqlx::query!("DELETE FROM whatsapp_media_blob WHERE id = $1", row.blob_id)
+ .execute(&mut **tx)
+ .await
+ .map_err(failure)?;
if let Some(message) = row.message_id {
bump_in(tx, attachment, message).await?;
}
@@ -133,7 +131,7 @@ impl PgLinkedRepository {
let account = fence_in(&mut tx, scope).await?;
lock_group_in(&mut tx, attachment.binding_id).await?;
let row = sqlx::query!(
- r#"SELECT a.document_id, a.sha256, a.state, a.mime AS "mime!", a.filename AS "filename!", b.id AS group_id, b.user_id
+ r#"SELECT a.blob_id, a.sha256, a.state, a.mime AS "mime!", a.filename AS "filename!", b.id AS group_id, b.user_id
FROM whatsapp_group_attachment a JOIN whatsapp_group b ON b.id = a.binding_id
WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.account_id = $5
FOR UPDATE OF a"#,
@@ -158,9 +156,9 @@ impl PgLinkedRepository {
return Err(LinkedError::Invalid("attachment bytes do not match their hash").into());
}
sqlx::query!(
- r#"INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes)
- VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (document_id) DO NOTHING"#,
- row.document_id,
+ r#"INSERT INTO whatsapp_media_blob (id, group_id, user_id, mime, filename, sha256, bytes)
+ VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO NOTHING"#,
+ row.blob_id,
row.group_id,
row.user_id,
row.mime,
@@ -182,7 +180,7 @@ impl PgLinkedRepository {
.execute(&mut *tx)
.await
.map_err(failure)?;
- notify(&mut tx, signals::MEDIA_READY, row.document_id).await?;
+ notify(&mut tx, signals::MEDIA_READY, row.blob_id).await?;
tx.commit().await.map_err(failure)
}
@@ -220,7 +218,7 @@ impl PgLinkedRepository {
#[async_trait]
impl MediaRepository for PgLinkedRepository {
- async fn due_imports(&self, limit: i64) -> LinkedResult<Vec<DocumentImport>> {
+ async fn due_imports(&self, limit: i64) -> LinkedResult<Vec<FileImport>> {
// Claiming pushes retry_at forward, so DSS replicas don't import twice.
let rows = sqlx::query!(
r#"UPDATE whatsapp_group_attachment a SET retry_at = now() + interval '5 minutes'
@@ -229,54 +227,49 @@ impl MediaRepository for PgLinkedRepository {
SELECT binding_id, person_id, source_id, ordinal FROM whatsapp_group_attachment
WHERE state = 'downloaded' AND retry_at <= now()
ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)
- AND blob.document_id = a.document_id
- RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.document_id, a.attempts,
- blob.group_id, blob.user_id, blob.filename, blob.mime, blob.sha256"#,
+ AND blob.id = a.blob_id
+ RETURNING a.binding_id, a.person_id, a.source_id, a.ordinal, a.blob_id, a.attempts,
+ blob.group_id, blob.user_id, blob.filename, blob.mime"#,
limit
)
.fetch_all(&self.pool)
.await
.map_err(failure)?;
- rows.into_iter()
- .map(|row| {
- Ok(DocumentImport {
- attachment: AttachmentRef {
- binding_id: row.binding_id,
- person_id: row.person_id,
- source_id: row.source_id,
- ordinal: row.ordinal,
- },
- document_id: row.document_id,
- group_id: row.group_id,
- owner: row.user_id,
- filename: row.filename,
- mime: row.mime,
- sha256: row
- .sha256
- .try_into()
- .map_err(|_| corrupt("sha256 is not 32 bytes"))?,
- attempts: row.attempts,
- })
+ Ok(rows
+ .into_iter()
+ .map(|row| FileImport {
+ attachment: AttachmentRef {
+ binding_id: row.binding_id,
+ person_id: row.person_id,
+ source_id: row.source_id,
+ ordinal: row.ordinal,
+ },
+ blob_id: row.blob_id,
+ group_id: row.group_id,
+ owner: row.user_id,
+ filename: row.filename,
+ mime: row.mime,
+ attempts: row.attempts,
})
- .collect()
+ .collect())
}
- async fn import_bytes(&self, import: &DocumentImport) -> LinkedResult<Option<Vec<u8>>> {
+ async fn import_bytes(&self, import: &FileImport) -> LinkedResult<Option<Vec<u8>>> {
sqlx::query_scalar!(
- "SELECT bytes FROM whatsapp_media_blob WHERE document_id = $1",
- import.document_id
+ "SELECT bytes FROM whatsapp_media_blob WHERE id = $1",
+ import.blob_id
)
.fetch_optional(&self.pool)
.await
.map_err(failure)
}
- async fn import_stored(&self, import: &DocumentImport) -> LinkedResult<()> {
+ async fn import_stored(&self, import: &FileImport, file_id: Uuid) -> LinkedResult<()> {
let attachment = &import.attachment;
let mut tx = self.pool.begin().await.map_err(failure)?;
lock_group_in(&mut tx, import.attachment.binding_id).await?;
let row = sqlx::query!(
- r#"UPDATE whatsapp_group_attachment a SET state = 'ready'
+ r#"UPDATE whatsapp_group_attachment a SET state = 'ready', file_id = $5
FROM whatsapp_group_message m
WHERE a.binding_id = $1 AND a.person_id = $2 AND a.source_id = $3 AND a.ordinal = $4 AND a.state = 'downloaded'
AND m.binding_id = a.binding_id AND m.person_id = a.person_id AND m.source_id = a.source_id
@@ -284,25 +277,40 @@ impl MediaRepository for PgLinkedRepository {
attachment.binding_id,
attachment.person_id,
attachment.source_id,
- attachment.ordinal
+ attachment.ordinal,
+ file_id
)
.fetch_optional(&mut *tx)
.await
.map_err(failure)?;
+ match row {
+ Some(row) => {
+ if let Some(message) = row.message_id {
+ bump_in(&mut tx, attachment, message).await?;
+ }
+ }
+ // Deleted or imported meanwhile: nothing will reference the file.
+ None => {
+ sqlx::query!(
+ "INSERT INTO whatsapp_file_deletion (file_id) VALUES ($1) ON CONFLICT DO NOTHING",
+ file_id
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(failure)?;
+ }
+ }
sqlx::query!(
- "DELETE FROM whatsapp_media_blob WHERE document_id = $1",
- import.document_id
+ "DELETE FROM whatsapp_media_blob WHERE id = $1",
+ import.blob_id
)
.execute(&mut *tx)
.await
.map_err(failure)?;
- if let Some(message) = row.and_then(|row| row.message_id) {
- bump_in(&mut tx, attachment, message).await?;
- }
tx.commit().await.map_err(failure)
}
- async fn import_failed(&self, import: &DocumentImport, permanent: bool) -> LinkedResult<()> {
+ async fn import_failed(&self, import: &FileImport, permanent: bool) -> LinkedResult<()> {
let mut tx = self.pool.begin().await.map_err(failure)?;
lock_group_in(&mut tx, import.attachment.binding_id).await?;
if permanent {
@@ -328,7 +336,7 @@ impl MediaRepository for PgLinkedRepository {
async fn expire_retained(&self) -> LinkedResult<u64> {
let uploads = sqlx::query!(
r#"DELETE FROM whatsapp_media_blob b WHERE b.created_at < now() - interval '1 day'
- AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)"#
+ AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.blob_id = b.id)"#
)
.execute(&self.pool)
.await
@@ -351,4 +359,31 @@ impl MediaRepository for PgLinkedRepository {
.rows_affected();
Ok(uploads + receipts + pairings)
}
+
+ async fn due_file_deletions(&self, limit: i64) -> LinkedResult<Vec<Uuid>> {
+ // Claiming pushes retry_at forward, so DSS replicas don't delete twice
+ // and a failing file waits before it is tried again.
+ sqlx::query_scalar!(
+ r#"UPDATE whatsapp_file_deletion SET retry_at = now() + interval '5 minutes'
+ WHERE file_id IN (
+ SELECT file_id FROM whatsapp_file_deletion WHERE retry_at <= now()
+ ORDER BY retry_at LIMIT $1 FOR UPDATE SKIP LOCKED)
+ RETURNING file_id"#,
+ limit
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(failure)
+ }
+
+ async fn files_deleted(&self, files: &[Uuid]) -> LinkedResult<()> {
+ sqlx::query!(
+ "DELETE FROM whatsapp_file_deletion WHERE file_id = ANY($1)",
+ files
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(failure)?;
+ Ok(())
+ }
}
diff --git a/crates/whatsapp_linked/src/outbound/pg/sends.rs b/crates/whatsapp_linked/src/outbound/pg/sends.rs
index b3795695a0..275606d26d 100644
--- a/crates/whatsapp_linked/src/outbound/pg/sends.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/sends.rs
@@ -51,7 +51,7 @@ impl SendRepository for PgLinkedRepository {
async fn stage_upload(&self, upload: StagedUpload<'_>) -> LinkedResult<Uuid> {
let id = Uuid::now_v7();
sqlx::query!(
- r#"INSERT INTO whatsapp_media_blob (document_id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)
+ r#"INSERT INTO whatsapp_media_blob (id, group_id, user_id, mime, filename, sha256, bytes, width, height, duration_seconds)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,
id,
upload.group_id,
@@ -79,8 +79,8 @@ impl SendRepository for PgLinkedRepository {
let user = user.as_ref();
sqlx::query_scalar!(
r#"SELECT mime FROM whatsapp_media_blob b
- WHERE document_id = $1 AND group_id = $2 AND user_id = $3
- AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.document_id = b.document_id)"#,
+ WHERE id = $1 AND group_id = $2 AND user_id = $3
+ AND NOT EXISTS (SELECT 1 FROM whatsapp_group_attachment a WHERE a.blob_id = b.id)"#,
upload,
group_id,
user
@@ -384,7 +384,7 @@ async fn content_in(
Ok(match &request.message {
ReplyContent::Media { upload_id, caption } => {
let Some(blob) = sqlx::query!(
- "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",
+ "SELECT mime, filename, width, height, duration_seconds FROM whatsapp_media_blob WHERE id = $1",
upload_id
)
.fetch_optional(&mut **tx)
@@ -653,7 +653,7 @@ impl PgLinkedRepository {
let (kind, text, target) = match &request.message {
ReplyContent::Media { upload_id, caption } => {
let blob = sqlx::query!(
- "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE document_id = $1",
+ "SELECT mime, filename, sha256, octet_length(bytes) AS \"size!\", width, height, duration_seconds FROM whatsapp_media_blob WHERE id = $1",
upload_id
)
.fetch_one(&mut *tx)
@@ -775,10 +775,10 @@ impl PgLinkedRepository {
let changed =
ingest::persist_in(&mut tx, &event, message, &reservation).await?;
ingest::finish_in(&mut tx, &reservation, changed).await?;
- // The staged upload becomes the attachment's document.
+ // The staged upload is imported as the attachment's static file.
if let Some(upload) = upload {
sqlx::query!(
- r#"UPDATE whatsapp_group_attachment SET document_id = $4, state = 'downloaded', retry_at = now()
+ r#"UPDATE whatsapp_group_attachment SET blob_id = $4, state = 'downloaded', retry_at = now()
WHERE binding_id = $1 AND person_id = $2 AND source_id = $3 AND ordinal = 0 AND state = 'pending'"#,
reservation.binding.id,
reservation.person,
@@ -806,7 +806,7 @@ impl PgLinkedRepository {
let account = fence_in(&mut tx, scope).await?;
let row = sqlx::query!(
r#"SELECT b.mime, b.filename, b.sha256, b.bytes FROM whatsapp_send s
- JOIN whatsapp_media_blob b ON b.document_id = (s.payload->'message'->>'uploadId')::uuid
+ JOIN whatsapp_media_blob b ON b.id = (s.payload->'message'->>'uploadId')::uuid
AND b.user_id = s.user_id AND b.group_id = s.group_id
WHERE s.id = $1 AND s.account_id = $2 AND s.claimed_epoch = $3 AND s.state = 'sending'
AND s.payload->'message'->>'type' = 'media'"#,
diff --git a/crates/whatsapp_linked/src/outbound/pg/test/media.rs b/crates/whatsapp_linked/src/outbound/pg/test/media.rs
index 9ce8258e6d..86ff391a89 100644
--- a/crates/whatsapp_linked/src/outbound/pg/test/media.rs
+++ b/crates/whatsapp_linked/src/outbound/pg/test/media.rs
@@ -1,34 +1,59 @@
use super::*;
use crate::domain::{
media::MediaService,
- ports::{DocumentImport, DocumentStore},
+ ports::{FileImport, FileStore, MediaRepository},
};
use sha2::{Digest, Sha256};
use std::sync::Mutex;
-/// Records what would become documents; fails the first `fail` imports.
+/// A stored static file: its id, the blob it came from, its owner and bytes.
+#[derive(Clone)]
+struct StoredFile {
+ file_id: Uuid,
+ blob_id: Uuid,
+ owner: String,
+ bytes: Vec<u8>,
+}
+
+/// Records the static files stored and deleted; fails the first `fail` stores.
#[derive(Default)]
-struct Documents {
- stored: Mutex<Vec<(Uuid, String, Vec<u8>)>>,
+struct Files {
+ stored: Mutex<Vec<StoredFile>>,
+ deleted: Mutex<Vec<Uuid>>,
fail: Mutex<u32>,
}
#[async_trait]
-impl DocumentStore for Documents {
- async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()> {
+impl FileStore for Files {
+ async fn store(&self, import: &FileImport, bytes: Vec<u8>) -> LinkedResult<Uuid> {
let mut fail = self.fail.lock().unwrap();
if *fail > 0 {
*fail -= 1;
return Err(LinkedError::Unavailable.into());
}
- self.stored
- .lock()
- .unwrap()
- .push((import.document_id, import.owner.clone(), bytes));
+ let file_id = Uuid::now_v7();
+ self.stored.lock().unwrap().push(StoredFile {
+ file_id,
+ blob_id: import.blob_id,
+ owner: import.owner.clone(),
+ bytes,
+ });
+ Ok(file_id)
+ }
+
+ async fn delete(&self, file_id: Uuid) -> LinkedResult<()> {
+ self.deleted.lock().unwrap().push(file_id);
Ok(())
}
}
+async fn released_files(pool: &PgPool) -> Vec<Uuid> {
+ sqlx::query_scalar!("SELECT file_id FROM whatsapp_file_deletion ORDER BY file_id")
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
fn photo(event: u128, sender: &str, source: &str, bytes: &[u8]) -> InboundEvent {
let mut event = text(event, sender, source, "");
if let InboundKind::Message(message) = &mut event.kind {
@@ -58,7 +83,7 @@ async fn content(pool: &PgPool, group_id: Uuid) -> Vec<String> {
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn an_inbound_photo_is_downloaded_once_and_becomes_a_private_document(pool: PgPool) {
+async fn an_inbound_photo_is_downloaded_once_and_becomes_a_static_file(pool: PgPool) {
let (linked, session, repository, binding, alice, bob) = adopted(&pool).await;
let bytes = b"jpeg bytes".to_vec();
session
@@ -115,7 +140,7 @@ async fn an_inbound_photo_is_downloaded_once_and_becomes_a_private_document(pool
);
assert_eq!(states[0].linked_attachments[0].file_name, "receipt.jpg");
- // A fresh message imports cleanly, surviving one failed document write.
+ // A fresh message imports cleanly, surviving one failed file write.
session
.ingest_event(alice, &photo(3, CUSTOMER_JID, "3EB0PIC2", &bytes))
.await
@@ -125,9 +150,9 @@ async fn an_inbound_photo_is_downloaded_once_and_becomes_a_private_document(pool
.complete_media_import(alice, &claimed[0].attachment, &bytes)
.await
.unwrap();
- let documents = Arc::new(Documents::default());
- *documents.fail.lock().unwrap() = 1;
- let media = MediaService::new(repository.clone(), documents.clone());
+ let files = Arc::new(Files::default());
+ *files.fail.lock().unwrap() = 1;
+ let media = MediaService::new(repository.clone(), files.clone());
assert_eq!(media.import_pending().await.unwrap(), 0);
sqlx::query!(
"UPDATE whatsapp_group_attachment SET retry_at = now() WHERE state = 'downloaded'"
@@ -137,20 +162,19 @@ async fn an_inbound_photo_is_downloaded_once_and_becomes_a_private_document(pool
.unwrap();
assert_eq!(media.import_pending().await.unwrap(), 1);
assert_eq!(media.import_pending().await.unwrap(), 0);
- let stored = documents.stored.lock().unwrap().clone();
+ let stored = files.stored.lock().unwrap().clone();
assert_eq!(stored.len(), 1);
assert_eq!(
- stored[0].1, binding.user_id,
+ stored[0].owner, binding.user_id,
"the content owner owns imports"
);
- assert_eq!(stored[0].2, bytes);
- let attached = sqlx::query_scalar!(
- "SELECT document_id FROM whatsapp_group_attachment WHERE state = 'ready'"
- )
- .fetch_all(&pool)
- .await
- .unwrap();
- assert_eq!(attached, vec![stored[0].0]);
+ assert_eq!(stored[0].bytes, bytes);
+ let attached =
+ sqlx::query_scalar!("SELECT file_id FROM whatsapp_group_attachment WHERE state = 'ready'")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert_eq!(attached, vec![Some(stored[0].file_id)]);
assert_eq!(
content(&pool, binding.id).await[1],
"",
@@ -174,129 +198,102 @@ async fn an_inbound_photo_is_downloaded_once_and_becomes_a_private_document(pool
file_name: "receipt.jpg".into(),
mime: "image/jpeg".into(),
size: bytes.len() as u64,
- document_id: Some(stored[0].0),
+ file_id: Some(stored[0].file_id),
width: Some(800),
height: Some(600),
duration_seconds: None,
presentation: None,
}
);
- // Imported documents inherit ordinary group shares dynamically.
- sqlx::query!(
- r#"INSERT INTO "Document" (id,name,owner) VALUES ($1,'receipt',$2)"#,
- stored[0].0.to_string(),
- ALICE
- )
- .execute(&pool)
- .await
- .unwrap();
- let mut tx = pool.begin().await.unwrap();
- entity_access_db_utils::direct_share::set(
- &mut tx,
- &binding.id,
- EntityType::WhatsAppGroup,
- &CAROL.to_owned().try_into().unwrap(),
- Some(AccessLevel::View),
- false,
- )
- .await
- .unwrap();
- tx.commit().await.unwrap();
- let access = entity_access::domain::service::EntityAccessServiceImpl::new(
- entity_access::outbound::PgAccessRepository::new(pool.clone()),
- );
- use entity_access::domain::ports::EntityAccessService;
- let viewer = macro_user_id::user_id::MacroUserIdStr::try_from(CAROL.to_owned()).unwrap();
- assert_eq!(
- access
- .get_access_level(
- Some(&viewer.0),
- &stored[0].0.to_string(),
- EntityType::Document
- )
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- let mut tx = pool.begin().await.unwrap();
- entity_access_db_utils::direct_share::set(
- &mut tx,
- &binding.id,
- EntityType::WhatsAppGroup,
- &viewer,
- None,
- false,
- )
- .await
- .unwrap();
- tx.commit().await.unwrap();
- assert_eq!(
- access
- .get_access_level(
- Some(&viewer.0),
- &stored[0].0.to_string(),
- EntityType::Document
- )
- .await
- .unwrap(),
- None
- );
- // A bot in team scope inherits the group's explicit team share, without
- // impersonating the adopter or receiving a separate document grant.
- let bot = entity_access::domain::models::BotId::new_from_uuid(Uuid::from_u128(0xb07));
- let team = sqlx::query_scalar!("SELECT team_id FROM team_user WHERE user_id = $1", ALICE)
+ let blobs = sqlx::query_scalar!(r#"SELECT count(*) AS "count!" FROM whatsapp_media_blob"#)
.fetch_one(&pool)
.await
.unwrap();
- sqlx::query!("INSERT INTO bots (id,kind,team_id,name,handle) VALUES ($1,'owned',$2,'Group reader','wa-reader')",
- bot.as_uuid(), team).execute(&pool).await.unwrap();
- let team_share = models_permissions::share_permission::UpdateSharePermissionRequestV2 {
- link_share: None,
- link_share_access_level: None,
- team_share_access_level: Some(Some(AccessLevel::View)),
- channel_share_permissions: None,
- };
- let owner = receipt::<MessageView>(ALICE, binding.id);
- linked
- .update_permissions(&owner, &team_share, SendAuthority::Human)
+ assert_eq!(blobs, 0);
+
+ // Deleting the message in WhatsApp deletes its file.
+ let mut delete = text(4, CUSTOMER_JID, "3EB0DEL", "");
+ if let InboundKind::Message(message) = &mut delete.kind {
+ message.kind = MessageKind::Delete;
+ message.target = Some(Target {
+ source_id: "3EB0PIC2".into(),
+ sender_jid: CUSTOMER_JID.into(),
+ });
+ }
+ session.ingest_event(alice, &delete).await.unwrap();
+ assert_eq!(released_files(&pool).await, vec![stored[0].file_id]);
+ assert_eq!(media.delete_released().await.unwrap(), 1);
+ assert_eq!(*files.deleted.lock().unwrap(), vec![stored[0].file_id]);
+ assert!(released_files(&pool).await.is_empty());
+ assert_eq!(media.delete_released().await.unwrap(), 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deleting_a_chats_owner_deletes_its_files(pool: PgPool) {
+ let (_, session, repository, binding, alice, _) = adopted(&pool).await;
+ let bytes = b"jpeg bytes".to_vec();
+ session
+ .ingest_event(alice, &photo(1, CUSTOMER_JID, "3EB0PIC", &bytes))
.await
.unwrap();
- use entity_access::domain::ports::AccessRepository;
- let permissions = entity_access::outbound::PgAccessRepository::new(pool.clone());
- assert_eq!(
- permissions
- .get_team_entity_access(bot, team, &stored[0].0.to_string(), EntityType::Document)
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- linked
- .update_permissions(
- &owner,
- &models_permissions::share_permission::UpdateSharePermissionRequestV2 {
- team_share_access_level: Some(None),
- ..team_share
- },
- SendAuthority::Human,
- )
+ let claimed = session.claim_media_imports(alice, 8).await.unwrap();
+ session
+ .complete_media_import(alice, &claimed[0].attachment, &bytes)
.await
.unwrap();
- assert_eq!(
- permissions
- .get_team_entity_access(bot, team, &stored[0].0.to_string(), EntityType::Document)
- .await
- .unwrap(),
- None
- );
- let blobs = sqlx::query_scalar!(r#"SELECT count(*) AS "count!" FROM whatsapp_media_blob"#)
- .fetch_one(&pool)
+ let files = Arc::new(Files::default());
+ let media = MediaService::new(repository, files.clone());
+ assert_eq!(media.import_pending().await.unwrap(), 1);
+ let file_id = files.stored.lock().unwrap()[0].file_id;
+ assert!(released_files(&pool).await.is_empty());
+
+ sqlx::query!(r#"DELETE FROM "User" WHERE id = $1"#, binding.user_id)
+ .execute(&pool)
.await
.unwrap();
- assert_eq!(blobs, 0);
+ assert_eq!(released_files(&pool).await, vec![file_id]);
+ assert_eq!(media.delete_released().await.unwrap(), 1);
+ assert_eq!(*files.deleted.lock().unwrap(), vec![file_id]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_file_stored_after_its_message_was_deleted_is_deleted(pool: PgPool) {
+ let (_, session, repository, _, alice, _) = adopted(&pool).await;
+ let bytes = b"jpeg bytes".to_vec();
+ session
+ .ingest_event(alice, &photo(1, CUSTOMER_JID, "3EB0PIC", &bytes))
+ .await
+ .unwrap();
+ let claimed = session.claim_media_imports(alice, 8).await.unwrap();
+ session
+ .complete_media_import(alice, &claimed[0].attachment, &bytes)
+ .await
+ .unwrap();
+ let imports = repository.due_imports(8).await.unwrap();
+ let mut delete = text(2, CUSTOMER_JID, "3EB0DEL", "");
+ if let InboundKind::Message(message) = &mut delete.kind {
+ message.kind = MessageKind::Delete;
+ message.target = Some(Target {
+ source_id: "3EB0PIC".into(),
+ sender_jid: CUSTOMER_JID.into(),
+ });
+ }
+ session.ingest_event(alice, &delete).await.unwrap();
+ // The import was already under way: its file has no attachment to go to.
+ let late = Uuid::now_v7();
+ repository.import_stored(&imports[0], late).await.unwrap();
+ assert_eq!(released_files(&pool).await, vec![late]);
+ let ready = sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM whatsapp_group_attachment WHERE file_id IS NOT NULL"#
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(ready, 0);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn an_uploaded_attachment_is_sent_once_and_becomes_the_messages_document(pool: PgPool) {
+async fn an_uploaded_attachment_is_sent_once_and_becomes_the_messages_file(pool: PgPool) {
let (linked, session, repository, binding, alice, _) = adopted(&pool).await;
let bytes = b"%PDF-1.7 quote".to_vec();
let uploaded = linked
@@ -382,16 +379,16 @@ async fn an_uploaded_attachment_is_sent_once_and_becomes_the_messages_document(p
vec!["Signed quote"],
"attachment state is separate from the plain caption"
);
- let documents = Arc::new(Documents::default());
- MediaService::new(repository, documents.clone())
+ let files = Arc::new(Files::default());
+ MediaService::new(repository, files.clone())
.import_pending()
.await
.unwrap();
assert_eq!(content(&pool, binding.id).await, vec!["Signed quote"]);
- let stored = documents.stored.lock().unwrap().clone();
+ let stored = files.stored.lock().unwrap().clone();
assert_eq!(stored.len(), 1);
- assert_eq!(stored[0].0, uploaded.upload_id);
- assert_eq!(stored[0].1, ALICE, "the uploader owns what they sent");
+ assert_eq!(stored[0].blob_id, uploaded.upload_id);
+ assert_eq!(stored[0].owner, ALICE, "the uploader owns what they sent");
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
diff --git a/crates/whatsapp_linked/src/signals.rs b/crates/whatsapp_linked/src/signals.rs
index 0392cf1928..a36bad0c13 100644
--- a/crates/whatsapp_linked/src/signals.rs
+++ b/crates/whatsapp_linked/src/signals.rs
@@ -16,7 +16,7 @@ pub const GROUPS_REQUESTED: &str = "whatsapp_groups_requested";
pub const ACCOUNT_CHANGED: &str = "whatsapp_account_changed";
/// `<account_id>`: a replica released the account (session service only).
pub const ACCOUNT_RELEASED: &str = "whatsapp_account_released";
-/// `<document_id>`: attachment bytes are ready to import (DSS listens).
+/// `<blob_id>`: attachment bytes are ready to import (DSS listens).
pub const MEDIA_READY: &str = "whatsapp_media_ready";
/// `<message_id>`: a standalone message notification is ready (DSS listens).
pub const GROUP_EFFECTS: &str = "whatsapp_group_effects";
diff --git a/docs/agent-guide/external.md b/docs/agent-guide/external.md
index b6120d1717..6ff07ce8b0 100644
--- a/docs/agent-guide/external.md
+++ b/docs/agent-guide/external.md
@@ -88,8 +88,9 @@ Ready images and videos show inline in Chat's media grid (click opens the
viewer), sized from WhatsApp's declared width/height before they load so the
timeline opens at the bottom. Stickers show small and unframed, GIFs loop muted
in place, voice notes read **Voice note · 0:42** above an inline player; bytes
-come from the imported document's presigned URL. Other ready files show as
-document chips; other states show loading, unavailable or unsupported. Senders
+come from the attachment's static file, like Chat's media. Other ready files
+(PDF, text) show as file chips that open the stored file in a new tab; other
+states show loading, unavailable or unsupported. Senders
show their WhatsApp name. `@<number>` in a body shows the person: a verified
Macro user as Chat's mention chip, anyone else their WhatsApp name in bold.
Bare URLs are links with Chat's hover preview. **Forwarded** marks forwarded
diff --git a/docs/architecture/whatsapp-linked-devices.md b/docs/architecture/whatsapp-linked-devices.md
index a4cc7ef304..d38acb4931 100644
--- a/docs/architecture/whatsapp-linked-devices.md
+++ b/docs/architecture/whatsapp-linked-devices.md
@@ -31,7 +31,7 @@ Every payload is JSON `{"id": "<uuid>", "traceparent": "…"}` (`whatsapp_change
| `whatsapp_account_changed` | account | DSS → session | consent or adopted groups changed; re-read |
| `whatsapp_account_released` | account | session ↔ session | lease handed over |
| `whatsapp_group_effects` | message | session → DSS | a group notification revision is ready |
-| `whatsapp_media_ready` | document | session → DSS | attachment bytes are ready to import |
+| `whatsapp_media_ready` | blob | session → DSS | attachment bytes are ready to import |
| `whatsapp_changed` | scope | session/DSS → DSS | something a page shows changed; DSS pushes it |
## Ownership and fencing
@@ -220,15 +220,24 @@ Inbound attachments are reserved per ordinal at ingest, with the download
locator sealed by the session service under the observing account's key. That
account's replica claims the download (`claim_media_imports`), checks the
SHA-256 and hands over the bytes (`complete_media_import`), which wait in
-`whatsapp_media_blob`. DSS (signal `whatsapp_media_ready`) creates a private
-document owned by the group owner. Attachment documents inherit current group
-view access; sharing and revocation apply to previously imported files too. Ready
-bytes are never rewritten. Failures retry with backoff and then expose an
-`unavailable` attachment state; message bodies remain plain WhatsApp text.
+`whatsapp_media_blob`. DSS (signal `whatsapp_media_ready`) stores them as a
+static file owned by the group owner, the same storage as Chat's images, and
+records its id in `whatsapp_group_attachment.file_id`. Like Chat's media, a
+static file is readable by anyone who has its unguessable id: sharing the chat
+lets people see its files, and unsharing doesn't take back a file id someone
+already has. Ready bytes are never rewritten. Failures retry with backoff and
+then expose an `unavailable` attachment state; message bodies remain plain
+WhatsApp text.
+
+A file no attachment references any more (its message deleted in WhatsApp, or
+its chat removed with its owner) is queued in `whatsapp_file_deletion` by a
+trigger on `whatsapp_group_attachment`; DSS's drain deletes it from the static
+file service, retrying every 5 minutes until it does.
Outbound: the attachments route stages one file per send in the blob table;
`ReplyContent::Media` names it, the replica fetches it with `outbound_media`,
-and on acceptance it becomes the message's document, owned by the sender.
+and on acceptance it is imported as the message's static file, owned by the
+sender.
Staging reads the file's pixel size and length from its headers
(`domain::shape`: image headers, MP4 `tkhd`/`mvhd`, Ogg/Opus granule); the
sent WhatsApp message and the stored attachment carry them like received ones.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
index 3da7210bb3..4b826074a1 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedAttachment.md
@@ -1,6 +1,6 @@
# Type Alias: LinkedAttachment
-> **LinkedAttachment** = \{ `documentId?`: `string` \| `null`; `durationSeconds?`: `number` \| `null`; `fileName`: `string`; `height?`: `number` \| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \| `null`; \}
+> **LinkedAttachment** = \{ `durationSeconds?`: `number` \| `null`; `fileId?`: `string` \| `null`; `fileName`: `string`; `height?`: `number` \| `null`; `mime`: `string`; `ordinal`: `number`; `presentation?`: `null` \| [`LinkedMediaPresentation`](LinkedMediaPresentation.md); `size`: `number`; `state`: [`LinkedAttachmentState`](LinkedAttachmentState.md); `width?`: `number` \| `null`; \}
One attachment of a linked message.
@@ -8,8 +8,8 @@ One attachment of a linked message.
| Property | Type | Description |
| ------ | ------ | ------ |
-| <a id="property-documentid"></a> `documentId?` | `string` \| `null` | The private document, once ready. |
| <a id="property-durationseconds"></a> `durationSeconds?` | `number` \| `null` | Length of audio or video in whole seconds, when declared. |
+| <a id="property-fileid"></a> `fileId?` | `string` \| `null` | The static file holding it, once ready. |
| <a id="property-filename"></a> `fileName` | `string` | Display filename. |
| <a id="property-height"></a> `height?` | `number` \| `null` | Pixel height, when declared. |
| <a id="property-mime"></a> `mime` | `string` | Declared MIME type. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
index d28d0108a5..9ce52ab204 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedReplyContent.md
@@ -26,7 +26,7 @@ Content of a deliberate send.
| ------ | ------ | ------ |
| `caption?` | `string` \| `null` | Optional caption; audio has none. |
| `type` | `"media"` | - |
-| `uploadId` | `string` | The staged upload, which becomes the message's private document. |
+| `uploadId` | `string` | The staged upload, imported as the message's static file. |
***
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
index c074a43985..b3966ef714 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/LinkedUploadedAttachment.md
@@ -10,4 +10,4 @@ A staged attachment, sent only by a later deliberate send.
| ------ | ------ | ------ |
| <a id="property-filename"></a> `filename` | `string` | Display filename. |
| <a id="property-kind"></a> `kind` | [`LinkedMediaKind`](LinkedMediaKind.md) | Category. |
-| <a id="property-uploadid"></a> `uploadId` | `string` | Use as `upload_id` in a media send; also the future document id. |
+| <a id="property-uploadid"></a> `uploadId` | `string` | Use as `upload_id` in a media send. |
diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
index 9ca19fa8c1..1d60cbef34 100644
--- a/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
+++ b/packages/sdk-docs/reference/src/entities/whatsapp/group/classes/WhatsAppGroup.md
@@ -96,7 +96,7 @@ Advance the caller's own read cursor.
### messageAttachments()
-> **messageAttachments**(`messages`): `Promise`\<\{ `attachments`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md) \| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \}[]\>
+> **messageAttachments**(`messages`): `Promise`\<\{ `attachments`: \{ `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `url`: `string` \| `undefined`; \}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \}[]\>
Read attachment states for selected messages.
@@ -108,7 +108,7 @@ Read attachment states for selected messages.
#### Returns
-`Promise`\<\{ `attachments`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md) \| `undefined`; `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); \}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \}[]\>
+`Promise`\<\{ `attachments`: \{ `fileName`: `string`; `mime`: `string`; `ordinal`: `number`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `url`: `string` \| `undefined`; \}[]; `message`: [`WhatsAppMessage`](../../message/classes/WhatsAppMessage.md); \}[]\>
***
diff --git a/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md b/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md
index 3334d707a8..ede3f4bf8b 100644
--- a/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md
+++ b/packages/sdk-docs/reference/src/entities/whatsapp/message/classes/WhatsAppMessage.md
@@ -10,7 +10,7 @@ Message in an independently shared WhatsApp group.
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
-| <a id="property-attachments"></a> `attachments` | `readonly` | () => `Promise`\<\{ `document`: [`Document`](../../../documents/document/classes/Document.md) \| `undefined`; `durationSeconds`: `number` \| `undefined`; `fileName`: `string`; `height`: `number` \| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `width`: `number` \| `undefined`; \}[]\> | Attachment state and imported document handles. | - |
+| <a id="property-attachments"></a> `attachments` | `readonly` | () => `Promise`\<\{ `durationSeconds`: `number` \| `undefined`; `fileName`: `string`; `height`: `number` \| `undefined`; `mime`: `string`; `ordinal`: `number`; `presentation`: [`LinkedMediaPresentation`](../../../../../generated/storage/types.gen/type-aliases/LinkedMediaPresentation.md) \| `undefined`; `size`: `number`; `state`: [`LinkedAttachmentState`](../../../../../generated/storage/types.gen/type-aliases/LinkedAttachmentState.md); `url`: `string` \| `undefined`; `width`: `number` \| `undefined`; \}[]\> | Attachment states, with the stored file's URL once ready. | - |
| <a id="property-body"></a> `body` | `readonly` | () => `Promise`\<`string`\> | Plain WhatsApp text. | - |
| <a id="property-deleted"></a> `deleted` | `readonly` | () => `Promise`\<`boolean`\> | Deleted for everyone. | - |
| <a id="property-deliverystate"></a> `deliveryState` | `readonly` | () => `Promise`\<`NonNullable`\<LinkedDeliveryState \| null \| undefined\> \| `undefined`\> | Caller-owned send's delivery state, when present. | - |
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index da507fa27f..5b18df799e 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -9036,14 +9036,14 @@ export type LinkedAdoptGroup = {
* One attachment of a linked message.
*/
export type LinkedAttachment = {
- /**
- * The private document, once ready.
- */
- documentId?: string | null;
/**
* Length of audio or video in whole seconds, when declared.
*/
durationSeconds?: number | null;
+ /**
+ * The static file holding it, once ready.
+ */
+ fileId?: string | null;
/**
* Display filename.
*/
@@ -9394,7 +9394,7 @@ export type LinkedReplyContent = {
caption?: string | null;
type: 'media';
/**
- * The staged upload, which becomes the message's private document.
+ * The staged upload, imported as the message's static file.
*/
uploadId: string;
} | {
@@ -9510,7 +9510,7 @@ export type LinkedUploadedAttachment = {
*/
kind: LinkedMediaKind;
/**
- * Use as `upload_id` in a media send; also the future document id.
+ * Use as `upload_id` in a media send.
*/
uploadId: string;
};
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index ec23b9d8fa..89d8e213c3 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -33467,17 +33467,17 @@
"description": "One attachment of a linked message.",
"required": ["ordinal", "state", "fileName", "mime", "size"],
"properties": {
- "documentId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "The private document, once ready."
- },
"durationSeconds": {
"type": ["integer", "null"],
"format": "int32",
"description": "Length of audio or video in whole seconds, when declared.",
"minimum": 0
},
+ "fileId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The static file holding it, once ready."
+ },
"fileName": {
"type": "string",
"description": "Display filename."
@@ -33965,7 +33965,7 @@
"uploadId": {
"type": "string",
"format": "uuid",
- "description": "The staged upload, which becomes the message's private document."
+ "description": "The staged upload, imported as the message's static file."
}
}
},
@@ -34115,7 +34115,7 @@
"uploadId": {
"type": "string",
"format": "uuid",
- "description": "Use as `upload_id` in a media send; also the future document id."
+ "description": "Use as `upload_id` in a media send."
}
}
},
diff --git a/packages/sdk/src/entities/whatsapp/group.ts b/packages/sdk/src/entities/whatsapp/group.ts
index 0243d48a92..c034f8e787 100644
--- a/packages/sdk/src/entities/whatsapp/group.ts
+++ b/packages/sdk/src/entities/whatsapp/group.ts
@@ -6,7 +6,6 @@ import type {
} from '../../../generated/storage/types.gen';
import { paginate, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import { Document } from '../documents/document';
import { FavoritableEntity } from '../entity';
import { User } from '../users/user';
import { communityOf } from './chat';
@@ -241,8 +240,8 @@ export class WhatsAppGroup extends FavoritableEntity<WhatsAppGroupDetail> {
fileName: attachment.fileName,
mime: attachment.mime,
size: attachment.size,
- document: attachment.documentId
- ? Document.byId(this.client, attachment.documentId)
+ url: attachment.fileId
+ ? `${this.client.hosts['static-files']}/file/${attachment.fileId}`
: undefined,
})),
}));
diff --git a/packages/sdk/src/entities/whatsapp/message.ts b/packages/sdk/src/entities/whatsapp/message.ts
index f213f11b98..b460b33409 100644
--- a/packages/sdk/src/entities/whatsapp/message.ts
+++ b/packages/sdk/src/entities/whatsapp/message.ts
@@ -1,7 +1,6 @@
import type { WhatsAppGroupMessage } from '../../../generated/storage/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import { Document } from '../documents/document';
import { MacroEntity } from '../entity';
import type { WhatsAppGroup } from './group';
@@ -72,7 +71,7 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {
this.mappedField('replyTo', (id) =>
id ? WhatsAppMessage.byId(this.client, this.group, id) : undefined,
);
- /** Attachment state and imported document handles. */
+ /** Attachment states, with the stored file's URL once ready. */
readonly attachments = this.mappedField('attachments', (records) =>
records.map((record) => ({
ordinal: record.ordinal,
@@ -84,8 +83,8 @@ export class WhatsAppMessage extends MacroEntity<WhatsAppGroupMessage> {
height: record.height ?? undefined,
durationSeconds: record.durationSeconds ?? undefined,
presentation: record.presentation ?? undefined,
- document: record.documentId
- ? Document.byId(this.client, record.documentId)
+ url: record.fileId
+ ? `${this.client.hosts['static-files']}/file/${record.fileId}`
: undefined,
})),
);
diff --git a/packages/sdk/tests/whatsapp.test.ts b/packages/sdk/tests/whatsapp.test.ts
index 2f050226fd..ce4248bf49 100644
--- a/packages/sdk/tests/whatsapp.test.ts
+++ b/packages/sdk/tests/whatsapp.test.ts
@@ -102,7 +102,10 @@ function fixture(handler: (request: Request) => Response | Promise<Response>) {
}) as typeof fetch;
const macro = new Macro({
token: 'owner-api-token',
- hosts: { storage: 'https://storage.example.test' },
+ hosts: {
+ storage: 'https://storage.example.test',
+ 'static-files': 'https://files.example.test',
+ },
});
return { macro, requests, group: macro.whatsapp.byId('group') };
}
@@ -435,7 +438,7 @@ test('sends, delivery and attachment states stay scoped to the chat', async () =
fileName: 'note.txt',
mime: 'text/plain',
size: 5,
- documentId: 'document',
+ fileId: 'file',
},
],
},
@@ -450,7 +453,9 @@ test('sends, delivery and attachment states stay scoped to the chat', async () =
expect(await requests[1].json()).toEqual(['intent', 'message']);
const [states] = await group.messageAttachments([target]);
expect(states.message.id).toBe('message');
- expect(states.attachments[0].document?.id).toBe('document');
+ expect(states.attachments[0].url).toBe(
+ 'https://files.example.test/file/file',
+ );
const other = macro.whatsapp.byId('other');
await expect(
group.messageAttachments([
diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.md
index 18e1ba6c41..87066ab57a 100644
--- a/services/document_storage_service/AGENTS.md
+++ b/services/document_storage_service/AGENTS.md
@@ -25,7 +25,8 @@ threads, pins, recents, notifications, folders, activity.
notification/withdrawal/realtime ports. Policy lives in `crates/access_requests`.
- `src/whatsapp_linked.rs`: mounts `/meta/linked` from `crates/whatsapp_linked`
and runs the group notification/import worker (LISTEN `whatsapp_group_effects`,
- `whatsapp_media_ready`) and the `whatsapp_changed` pusher (bare
+ `whatsapp_media_ready`; attachments become static files through the static
+ file service, which also deletes released ones) and the `whatsapp_changed` pusher (bare
connection-gateway events to the account owner or a group's viewers);
enforces a Redis-shared one-send-request-per-second budget per user;
switches `WHATSAPP_LINKED_{PAIRING,ADOPTION,SENDING}_ENABLED` default off.
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index cb137b8dce..4326a9c64f 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1483,9 +1483,10 @@ pub async fn run() -> anyhow::Result<()> {
let whatsapp_linked_state =
crate::whatsapp_linked::build(crate::whatsapp_linked::Dependencies {
redis: redis_client.clone(),
- documents: document_service.clone(),
- s3: macro_aws_config::s3_client().await,
- document_bucket: config.document_storage_bucket.as_ref().to_owned(),
+ static_files: static_file_service_client::StaticFileServiceClient::new(
+ config.internal_api_key.to_string(),
+ StaticFileServiceUrl::new()?.to_string(),
+ ),
features: whatsapp_linked::domain::models::Features {
pairing: config.whatsapp_linked_pairing_enabled,
adoption: config.whatsapp_linked_adoption_enabled,
diff --git a/services/document_storage_service/src/whatsapp_linked.rs b/services/document_storage_service/src/whatsapp_linked.rs
index 13c9440d2b..d8e5079557 100644
--- a/services/document_storage_service/src/whatsapp_linked.rs
+++ b/services/document_storage_service/src/whatsapp_linked.rs
@@ -1,5 +1,5 @@
//! Personal WhatsApp linked devices: composition of the `whatsapp_linked` domain
-//! crate with DSS's entity access, notification and document clients, the
+//! crate with DSS's entity access, notification and static file clients, the
//! notification outbox worker, and the `whatsapp_changed` pushes to open pages.
//! The session service runs the WhatsApp sockets; it reaches DSS only through
//! MacroDB rows and `NOTIFY`.
@@ -7,29 +7,24 @@
use crate::api::context::{AuthorizationService, EntityAccessService, NotificationIngressType};
use async_trait::async_trait;
use connection_gateway_client::client::ConnectionGatewayClient;
-use documents_hex::domain::{
- models::{InitialLinkShare, NewDocument},
- ports::DocumentService as _,
-};
use entity_access::domain::ports::EntityAccessService as _;
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::FileType;
use model_entity::EntityType;
-use model_owner::CreationPrincipal;
-use models_permissions::share_permission::LinkShareState;
use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};
use sqlx::PgPool;
+use static_file_service_client::StaticFileServiceClient;
use std::{collections::HashSet, sync::Arc, time::Duration};
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use tracing::Instrument as _;
+use uuid::Uuid;
use whatsapp_linked::{
domain::{
effects::EffectsService,
media::MediaService,
models::{Features, LinkedError},
ports::{
- AudienceRepository, DocumentImport, DocumentStore, GroupEffect, GroupPublisher,
- LinkedResult, Origin, SendRateLimiter,
+ AudienceRepository, FileImport, FileStore, GroupEffect, GroupPublisher, LinkedResult,
+ Origin, SendRateLimiter,
},
service::LinkedService,
},
@@ -44,9 +39,7 @@ pub(crate) type State = LinkedRouterState<EntityAccessService, AuthorizationServ
/// Clients the linked composition needs from DSS.
pub(crate) struct Dependencies {
pub features: Features,
- pub documents: Arc<crate::api::context::DocumentService>,
- pub s3: aws_sdk_s3::Client,
- pub document_bucket: String,
+ pub static_files: StaticFileServiceClient,
pub pool: PgPool,
pub redis: redis::Client,
pub access: Arc<EntityAccessService>,
@@ -61,9 +54,7 @@ pub(crate) struct Dependencies {
pub(crate) fn build(dependencies: Dependencies) -> State {
let Dependencies {
features,
- documents,
- s3,
- document_bucket,
+ static_files,
pool,
redis,
access,
@@ -79,15 +70,7 @@ pub(crate) fn build(dependencies: Dependencies) -> State {
access: access.clone(),
notifications,
});
- let media = MediaService::new(
- repository.clone(),
- Arc::new(DssDocumentStore {
- pool: pool.clone(),
- documents,
- s3,
- bucket: document_bucket,
- }),
- );
+ let media = MediaService::new(repository.clone(), Arc::new(StaticFiles(static_files)));
let service = LinkedService::new(
features,
repository.clone(),
@@ -184,7 +167,8 @@ async fn listen(
}
}
-/// Import ready attachments, expire unsent uploads and publish notifications.
+/// Import ready attachments, delete released files, expire unsent uploads and
+/// publish notifications.
async fn drain(effects: &EffectsService, media: &MediaService) {
loop {
match media.import_pending().await {
@@ -199,6 +183,19 @@ async fn drain(effects: &EffectsService, media: &MediaService) {
}
}
}
+ loop {
+ match media.delete_released().await {
+ Ok(0) => break,
+ Ok(_) => {}
+ Err(error) => {
+ tracing::warn!(
+ code = error.current_context().code(),
+ "Deleting WhatsApp attachment files will retry"
+ );
+ break;
+ }
+ }
+ }
if let Err(error) = media.expire_retained().await {
tracing::warn!(
code = error.current_context().code(),
@@ -411,93 +408,42 @@ impl GroupPublisher for DssGroupPublisher {
}
}
-/// Creates private documents for imported and sent attachments, owned by the
-/// group owner or uploader; document access inherits the group's current grants.
-struct DssDocumentStore {
- pool: PgPool,
- documents: Arc<crate::api::context::DocumentService>,
- s3: aws_sdk_s3::Client,
- bucket: String,
-}
+/// Stores imported and sent attachments as static files, like channel media,
+/// owned by the uploader or the chat's owner.
+struct StaticFiles(StaticFileServiceClient);
#[async_trait]
-impl DocumentStore for DssDocumentStore {
+impl FileStore for StaticFiles {
#[tracing::instrument(
- name = "whatsapp.linked.store_document",
+ name = "whatsapp.linked.store_file",
skip_all,
err,
- fields(document_id = %import.document_id, group_id = %import.group_id, size = bytes.len())
+ fields(blob_id = %import.blob_id, group_id = %import.group_id, size = bytes.len(), file_id)
)]
- async fn store(&self, import: &DocumentImport, bytes: Vec<u8>) -> LinkedResult<()> {
- let id = import.document_id.to_string();
- let owner = MacroUserIdStr::try_from(import.owner.clone()).map_err(unavailable)?;
- let file_type = FileType::all()
- .iter()
- .copied()
- .find(|kind| kind.mime_type() == import.mime)
- .ok_or_else(|| unavailable(format!("unsupported attachment type {}", import.mime)))?;
- let exists = match macro_db_client::document::get_basic_document(&self.pool, &id).await {
- Ok(_) => true,
- Err(sqlx::Error::RowNotFound) => false,
- Err(error) => return Err(unavailable(error)),
- };
- if !exists {
- let name = std::path::Path::new(&import.filename)
- .file_stem()
- .and_then(|stem| stem.to_str())
- .filter(|stem| !stem.trim().is_empty())
- .unwrap_or("Attachment")
- .to_owned();
- self.documents
- .create_document(
- &CreationPrincipal::BotForUser {
- bot: bot_id::MACRO_SYSTEM_BOT_ID,
- user: owner.clone(),
- },
- NewDocument {
- id: Some(import.document_id),
- sha: hex::encode(import.sha256),
- document_name: name,
- file_type: Some(file_type),
- project_id: None,
- team_id: None,
- share_with_team: false,
- created_at: None,
- sub_type: None,
- skip_history: true,
- initial_link_share: InitialLinkShare::Exact(LinkShareState::Off),
- },
- None,
- )
- .await
- .map_err(unavailable)?;
- }
- let document = macro_db_client::document::get_basic_document(&self.pool, &id)
+ async fn store(&self, import: &FileImport, bytes: Vec<u8>) -> LinkedResult<Uuid> {
+ let stored = self
+ .0
+ .put_named_bytes_for_user(&import.owner, &import.filename, bytes.into(), &import.mime)
.await
- .map_err(unavailable)?;
- let (version, uploaded) =
- macro_db_client::document::get_latest_document_version_id(&self.pool, &id)
- .await
- .map_err(unavailable)?;
- // Ready bytes are never rewritten; an interrupted upload is retried.
- if !uploaded {
- use base64::Engine as _;
- self.s3
- .put_object()
- .bucket(&self.bucket)
- .key(s3_key::build_cloud_storage_bucket_document_key(
- &document.owner,
- &id,
- version,
- ))
- .content_type(file_type.mime_type())
- .checksum_sha256(base64::engine::general_purpose::STANDARD.encode(import.sha256))
- .body(aws_sdk_s3::primitives::ByteStream::from(bytes))
- .send()
- .await
- .map_err(unavailable)?;
+ .map_err(|error| unavailable(format!("{error:#}")))?;
+ tracing::Span::current().record("file_id", &stored.id);
+ Uuid::parse_str(&stored.id).map_err(unavailable)
+ }
+
+ #[tracing::instrument(name = "whatsapp.linked.delete_file", skip(self), err)]
+ async fn delete(&self, file_id: Uuid) -> LinkedResult<()> {
+ match self.0.delete_file(&file_id.to_string()).await {
+ Ok(_) => Ok(()),
+ Err(error)
+ if error
+ .downcast_ref::<reqwest::Error>()
+ .and_then(reqwest::Error::status)
+ == Some(reqwest::StatusCode::NOT_FOUND) =>
+ {
+ Ok(())
+ }
+ Err(error) => Err(unavailable(format!("{error:#}"))),
}
- Ok(())
}
}