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.

chore(calendar): remove meeting notes linked to events (#9372)

gbirman0b1d6a83d7fe
diff --git a/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json b/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json
deleted file mode 100644
index d0d41844ce..0000000000
--- a/.sqlx/query-136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT team.id, team.name FROM team\n JOIN team_user member ON member.team_id = team.id WHERE member.user_id = $1\n ORDER BY team.name, team.id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "136e7b98319003c7f61aff7fbdb4aa8b693f9e0d2b0662b1f93068689e200206"
-}
diff --git a/.sqlx/query-3f0661915621c25f5bf5d3e5eb78c9e0a854c45a3b724820be55853a0eee4740.json b/.sqlx/query-3f0661915621c25f5bf5d3e5eb78c9e0a854c45a3b724820be55853a0eee4740.json
deleted file mode 100644
index 625b55f8d3..0000000000
--- a/.sqlx/query-3f0661915621c25f5bf5d3e5eb78c9e0a854c45a3b724820be55853a0eee4740.json
+++ /dev/null
@@ -1,59 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT note.event_id, note.occurrence_key, document.name AS document_name,\n calendar_note_event_visible($1, note.event_id, note.occurrence_key) AS \"can_view_meeting!\",\n CASE WHEN calendar_note_event_visible($1, note.event_id, note.occurrence_key)\n THEN CASE WHEN event.owner_id = $1 OR EXISTS (\n SELECT 1 FROM macro_user_links delegate\n WHERE delegate.link_id = event.source_link_id AND delegate.primary_macro_id = $1\n ) THEN event.title ELSE 'Shared meeting' END\n ELSE 'Unavailable meeting' END AS \"event_title!\",\n team.id AS \"team_id?\", team.name AS \"team_name?\"\n FROM calendar_event_notes note\n JOIN \"Document\" document ON document.id = note.document_id AND document.\"deletedAt\" IS NULL\n JOIN calendar_events event ON event.id = note.event_id\n LEFT JOIN team ON team.id = note.team_id\n WHERE note.document_id = $2\n AND (document.owner = $1 OR calendar_note_event_visible($1, note.event_id, note.occurrence_key))\n ORDER BY note.created_at, note.event_id, note.occurrence_key\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "event_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "occurrence_key",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "document_name",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "can_view_meeting!",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "event_title!",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "team_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 6,
- "name": "team_name?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- null,
- null,
- false,
- false
- ]
- },
- "hash": "3f0661915621c25f5bf5d3e5eb78c9e0a854c45a3b724820be55853a0eee4740"
-}
diff --git a/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json b/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json
deleted file mode 100644
index ebf5753340..0000000000
--- a/.sqlx/query-4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS \"exists!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4da94c34c66bcc713e6d09116d41ec0c297dba6b1baac2364fd65fe0fb38dd04"
-}
diff --git a/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json b/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json
deleted file mode 100644
index 060cbe2781..0000000000
--- a/.sqlx/query-57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT EXISTS (SELECT 1 FROM calendar_event_occurrences WHERE event_id = $1 AND calendar_note_link_key($1, occurrence_key) = calendar_note_link_key($1, $2) AND NOT is_cancelled) AS \"exists!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "57318c4dce85fa85b0de1c2e0f885dc26f0daf4eab3e1fadd393409b9f3261af"
-}
diff --git a/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json b/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json
deleted file mode 100644
index 8082335509..0000000000
--- a/.sqlx/query-718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047.json
+++ /dev/null
@@ -1,48 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT d.id, d.name, team.id AS \"team_id?\", team.name AS \"team_name?\",\n d.owner = $1 AS \"can_manage!\"\n FROM calendar_event_notes note\n JOIN calendar_events event ON event.id = note.event_id\n JOIN calendar_events requested ON requested.id = $2\n AND requested.ical_uid = event.ical_uid\n AND lower(requested.organizer_email) IS NOT DISTINCT FROM lower(event.organizer_email)\n JOIN \"Document\" d ON d.id = note.document_id AND d.\"deletedAt\" IS NULL AND d.\"fileType\" = 'md'\n LEFT JOIN team ON team.id = note.team_id\n WHERE note.occurrence_key = calendar_note_link_key($2, $3) AND event.status <> 'cancelled'\n AND calendar_note_event_visible($1, note.event_id, note.occurrence_key)\n AND calendar_note_copies_match(requested.id, note.event_id, calendar_note_link_key($2, $3))\n ORDER BY note.created_at, d.id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "team_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "team_name?",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "can_manage!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- null
- ]
- },
- "hash": "718a734ca1b531d26b2ff84915e9633359af1b17a7b0c3fc5026a61fd0549047"
-}
diff --git a/.sqlx/query-7bb507dd28fef3044b651c51295532001b6f9dac01144191c41577752ba2cbf3.json b/.sqlx/query-7bb507dd28fef3044b651c51295532001b6f9dac01144191c41577752ba2cbf3.json
deleted file mode 100644
index 9bf822df59..0000000000
--- a/.sqlx/query-7bb507dd28fef3044b651c51295532001b6f9dac01144191c41577752ba2cbf3.json
+++ /dev/null
@@ -1,92 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH reference_targets AS MATERIALIZED (\n SELECT candidate.id AS event_id, note.event_id AS reference_event_id,\n note.occurrence_key AS reference_occurrence_key\n FROM calendar_event_notes note\n JOIN calendar_events linked ON linked.id = note.event_id\n JOIN calendar_events candidate ON candidate.ical_uid = linked.ical_uid\n AND lower(candidate.organizer_email) IS NOT DISTINCT FROM lower(linked.organizer_email)\n WHERE note.document_id = $11\n AND calendar_note_copies_match(note.event_id, candidate.id, note.occurrence_key)\n ), eligible AS (\n SELECT teammate.user_id, COALESCE(policy.sharing, 'busy_only') AS sharing FROM team_user viewer\n JOIN team_user teammate ON teammate.team_id = viewer.team_id\n LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id\n WHERE viewer.user_id = $1 AND teammate.user_id <> $1\n AND COALESCE(policy.sharing, 'busy_only') <> 'none'\n UNION SELECT $1::text, 'all'\n ), visible_accounts AS MATERIALIZED (\n SELECT eligible.user_id, eligible.sharing, account.id AS account_id\n FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id\n WHERE ($11::text IS NOT NULL OR eligible.user_id = ANY($2::text[]))\n UNION\n SELECT eligible.user_id, eligible.sharing, account.id AS account_id\n FROM eligible\n JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id\n JOIN calendar_accounts account ON account.email_link_id = link.link_id\n WHERE ($11::text IS NOT NULL OR eligible.user_id = ANY($2::text[]))\n ), authorized_sources AS MATERIALIZED (\n SELECT eligible.user_id AS shared_by, source.id AS source_id,\n calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,\n COALESCE(preference.contributes_to_availability,\n account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,\n source.normalized_payload, reference.reference_event_id,\n reference.reference_occurrence_key\n FROM visible_accounts eligible\n JOIN calendar_accounts account ON account.id = eligible.account_id\n AND account.sync_status IN ('ready', 'syncing')\n AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted\n AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id\n AND source.provider_access_role IS NOT NULL\n AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role\n LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id\n LEFT JOIN reference_targets reference ON reference.event_id = source.event_id\n WHERE ($11::text IS NULL OR (eligible.sharing = 'all' AND reference.event_id IS NOT NULL))\n AND ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))\n )\n SELECT shared_by AS \"shared_by!\", source_id AS \"source_id!\",\n calendar_id AS \"calendar_id!\", calendar_name AS \"calendar_name!\", time_zone,\n contributes AS \"contributes!\", reference_event_id AS \"reference_event_id?\",\n reference_occurrence_key AS \"reference_occurrence_key?\",\n ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS \"owner_emails!\",\n (normalized_payload - 'occurrences') AS \"snapshot!\", occurrence.value AS \"occurrence!\"\n FROM authorized_sources\n CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)\n WHERE (normalized_payload->'event'->>'status') <> 'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)\n AND ($11::text IS NOT NULL OR (\n ((occurrence.value->'time'->>'kind') = 'timed'\n AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4\n AND ((occurrence.value->'time'->>'endsAt')::timestamptz > $3\n OR ((occurrence.value->'time'->>'startsAt')::timestamptz = (occurrence.value->'time'->>'endsAt')::timestamptz\n AND (occurrence.value->'time'->>'startsAt')::timestamptz >= $3)))\n OR ((occurrence.value->'time'->>'kind') = 'allDay'\n AND (occurrence.value->'time'->>'startDate')::date < $6\n AND (occurrence.value->'time'->>'endDate')::date > $5)\n ))\n AND ($11::text IS NULL OR occurrence.value->>'occurrenceKey' = reference_occurrence_key\n OR (reference_occurrence_key = 'single' AND jsonb_array_length(normalized_payload->'event'->'recurrenceLines') = 0))\n AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))\n ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'\n LIMIT $10\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "shared_by!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "source_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "calendar_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "calendar_name!",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "time_zone",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "contributes!",
- "type_info": "Bool"
- },
- {
- "ordinal": 6,
- "name": "reference_event_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 7,
- "name": "reference_occurrence_key?",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "owner_emails!",
- "type_info": "TextArray"
- },
- {
- "ordinal": 9,
- "name": "snapshot!",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 10,
- "name": "occurrence!",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "TextArray",
- "Timestamptz",
- "Timestamptz",
- "Date",
- "Date",
- "Text",
- "Uuid",
- "Text",
- "Int8",
- "Text"
- ]
- },
- "nullable": [
- null,
- false,
- false,
- false,
- true,
- null,
- false,
- false,
- null,
- null,
- null
- ]
- },
- "hash": "7bb507dd28fef3044b651c51295532001b6f9dac01144191c41577752ba2cbf3"
-}
diff --git a/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json b/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json
deleted file mode 100644
index 92d7e21ffc..0000000000
--- a/.sqlx/query-90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT calendar_note_event_visible($1, $2, calendar_note_link_key($2, $3)) AS \"visible!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "visible!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "90f303813158f4ec3b39e4457a7623b1a982f4916f93f6ecf3e9c047cfbf232a"
-}
diff --git a/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json b/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json
deleted file mode 100644
index 1ad6e48fa8..0000000000
--- a/.sqlx/query-ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested\n WHERE note.event_id = event.id AND requested.id = $1\n AND event.ical_uid = requested.ical_uid\n AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)\n AND (note.occurrence_key = $2 OR note.occurrence_key = calendar_note_link_key($1, $2)) AND note.document_id = $3\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "ada5231f3d25c542337e68f115f8cc3f13a1340ab17e04bc9d8a5e2ed2f30754"
-}
diff --git a/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json b/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json
deleted file mode 100644
index 096357e02f..0000000000
--- a/.sqlx/query-bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1 FROM calendar_event_notes note\n JOIN \"Document\" d ON d.id = note.document_id\n AND d.\"deletedAt\" IS NULL AND d.\"fileType\" = 'md'\n WHERE note.document_id = $1 AND (\n calendar_note_event_visible($2, note.event_id, note.occurrence_key)\n OR EXISTS (\n SELECT 1 FROM team_user member\n WHERE member.team_id = note.team_id AND member.user_id = $2\n )\n )\n ) AS \"visible!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "visible!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "bb02b8092869f8b1d8a3233316bc98c94ba244e37e31957ad33c2297fc671652"
-}
diff --git a/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json b/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json
deleted file mode 100644
index 009cac6ece..0000000000
--- a/.sqlx/query-bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested\n WHERE note.event_id = event.id AND requested.id = $1\n AND event.ical_uid = requested.ical_uid\n AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)\n AND note.occurrence_key = calendar_note_link_key($1, $2) AND note.document_id = $3 AND note.event_id <> $1\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "bd3d358ba1c3902d295476a49edd77fd7022d66a70a89342ab4cda3f2c43f989"
-}
diff --git a/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json b/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json
deleted file mode 100644
index 0776c3a04d..0000000000
--- a/.sqlx/query-bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT EXISTS (SELECT 1 FROM \"Document\" WHERE id = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL) AS \"exists!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "bf7af6db65b2268e241ce154c32729ffdcb80ecd395827fe003e4bdde55ca349"
-}
diff --git a/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json b/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json
deleted file mode 100644
index 3d1ea8de54..0000000000
--- a/.sqlx/query-f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO calendar_event_notes (event_id, occurrence_key, document_id, team_id, user_id)\n VALUES ($1, calendar_note_link_key($1, $2), $3, $4, $5)\n ON CONFLICT (event_id, occurrence_key, document_id) DO UPDATE SET team_id = EXCLUDED.team_id, user_id = EXCLUDED.user_id\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "f496ee6f2c6552827ce68aae06f35d662c2c0228d2b80493090c3aa1e3730828"
-}
diff --git a/.sqlx/query-fedcb133dd9ba625014a0aee5129c3e3cfd470cc4f0c008cb1a670e6333535b7.json b/.sqlx/query-fedcb133dd9ba625014a0aee5129c3e3cfd470cc4f0c008cb1a670e6333535b7.json
new file mode 100644
index 0000000000..96663c8fb2
--- /dev/null
+++ b/.sqlx/query-fedcb133dd9ba625014a0aee5129c3e3cfd470cc4f0c008cb1a670e6333535b7.json
@@ -0,0 +1,79 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH eligible AS (\n SELECT teammate.user_id FROM team_user viewer\n JOIN team_user teammate ON teammate.team_id = viewer.team_id\n LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id\n WHERE viewer.user_id = $1 AND COALESCE(policy.sharing, 'busy_only') <> 'none'\n UNION SELECT $1::text\n ), visible_accounts AS MATERIALIZED (\n SELECT eligible.user_id, account.id AS account_id\n FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id\n WHERE eligible.user_id = ANY($2::text[])\n UNION\n SELECT eligible.user_id, account.id AS account_id\n FROM eligible\n JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id\n JOIN calendar_accounts account ON account.email_link_id = link.link_id\n WHERE eligible.user_id = ANY($2::text[])\n ), authorized_sources AS MATERIALIZED (\n SELECT eligible.user_id AS shared_by, source.id AS source_id,\n calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,\n COALESCE(preference.contributes_to_availability,\n account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,\n source.normalized_payload\n FROM visible_accounts eligible\n JOIN calendar_accounts account ON account.id = eligible.account_id\n AND account.sync_status IN ('ready', 'syncing')\n AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted\n AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id\n AND source.provider_access_role IS NOT NULL\n AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role\n LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id\n WHERE ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))\n )\n SELECT shared_by AS \"shared_by!\", source_id AS \"source_id!\",\n calendar_id AS \"calendar_id!\", calendar_name AS \"calendar_name!\", time_zone,\n contributes AS \"contributes!\",\n ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS \"owner_emails!\",\n (normalized_payload - 'occurrences') AS \"snapshot!\", occurrence.value AS \"occurrence!\"\n FROM authorized_sources\n CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)\n WHERE (normalized_payload->'event'->>'status') <> 'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)\n AND (\n ((occurrence.value->'time'->>'kind') = 'timed'\n AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4\n AND ((occurrence.value->'time'->>'endsAt')::timestamptz > $3\n OR ((occurrence.value->'time'->>'startsAt')::timestamptz = (occurrence.value->'time'->>'endsAt')::timestamptz\n AND (occurrence.value->'time'->>'startsAt')::timestamptz >= $3)))\n OR ((occurrence.value->'time'->>'kind') = 'allDay'\n AND (occurrence.value->'time'->>'startDate')::date < $6\n AND (occurrence.value->'time'->>'endDate')::date > $5)\n )\n AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))\n ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'\n LIMIT $10\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "shared_by!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "source_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "calendar_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "calendar_name!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "time_zone",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "contributes!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "owner_emails!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 7,
+ "name": "snapshot!",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 8,
+ "name": "occurrence!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "Timestamptz",
+ "Timestamptz",
+ "Date",
+ "Date",
+ "Text",
+ "Uuid",
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ false,
+ false,
+ true,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "fedcb133dd9ba625014a0aee5129c3e3cfd470cc4f0c008cb1a670e6333535b7"
+}
diff --git a/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json b/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json
deleted file mode 100644
index 1e0156233e..0000000000
--- a/.sqlx/query-fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id AS document_id, name FROM \"Document\"\n WHERE owner = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL\n AND name ILIKE '%' || $2 || '%'\n ORDER BY \"updatedAt\" DESC, id LIMIT 30\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "document_id",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "fee0bf0248959985bdea594b2a3b2c569d8e6db9620d99a8ca7774f4b1bbaa84"
-}
diff --git a/Cargo.lock b/Cargo.lock
index 626668ad9a..33c9ed76ba 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3812,7 +3812,6 @@ dependencies = [
"chrono",
"chrono-tz",
"email_utils",
- "entity_access",
"futures",
"macro_authorization",
"macro_db_migrator",
@@ -3886,7 +3885,6 @@ dependencies = [
"email_api_client",
"email_db_client",
"email_utils",
- "entity_access",
"futures",
"google_token",
"macro_auth",
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 322132f5a4..c653806974 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -122,30 +122,6 @@ agent, retry, open a session) has a backend-free browser regression over a
scripted runtime:
`bunx playwright test --config src/features/local-runtime/browser-test/playwright.config.ts`.
-Meeting-note creation, linking, optional team access, retry, and unlinking have desktop and
-phone browser coverage in `features/calendar-notes`:
-`bunx playwright test --config src/features/calendar-notes/browser-test/playwright.config.ts`.
-The browser fixture uses the real event details popover and mobile drawer over
-sample data; keep notes aligned with those existing surfaces and preserve their
-dialog open guards. Open the existing document Share dialog for note access,
-keep labeled Options controls visible beside truncated titles without redundant
-hover tooltips, and use existing team memberships for optional note sharing.
-Keep meeting-note reads cached across event opens, show cached Quick Access
-matches while note searches refresh, and keep event actions usable while notes
-load. Show meeting-derived team viewing in the document's Team access summary;
-keep it distinct from additional direct sharing and keep Unlink stable while
-team access saves.
-Include linked meetings in Markdown side-panel References, behind the same flag;
-reuse the shared single-line ReferenceRow with the title and date inline, and
-resolve meeting details and opening targets through authorized calendar previews.
-Treat missing reference projection fields during backend rollout as unresolved,
-not denied; offer Retry on the links query without bypassing the server's
-reference authorization.
-Gate event notes and document Share meeting-link controls with
-`enable-calendar-meeting-notes` before mounting their query sources; it defaults
-on in dev and uses PostHog in production.
-See `docs/agent-guide/calendar.md` at the repo root.
-
Share message image paste, drop, removal during upload, and
upload failure have desktop, phone, and tablet browser coverage:
`bunx playwright test --config src/lib/core/component/ForwardMessageComposer/browser-test/playwright.config.ts`.
diff --git a/apps/web/src/components/ui/components/Dialog.tsx b/apps/web/src/components/ui/components/Dialog.tsx
index 8cf1fd526f..b3485afd92 100644
--- a/apps/web/src/components/ui/components/Dialog.tsx
+++ b/apps/web/src/components/ui/components/Dialog.tsx
@@ -38,8 +38,6 @@ export type DialogProps = {
visibleScrim?: boolean /* if the scrim is visible */;
/** Desktop opening animation; mobile drawers own their transitions. */
animate?: boolean;
- /** Constrain children on mobile so their own scroll regions can resize. */
- contentOwnsScroll?: boolean;
};
export function Dialog(props: DialogProps) {
@@ -85,22 +83,13 @@ function DialogDrawer(props: DialogProps) {
class={cn('mx-auto max-w-[calc(100vw-16px)]', props.class)}
>
<MobileDrawer.Handle aria-hidden="true" />
- <Show
- when={props.contentOwnsScroll}
- fallback={
- <MobileDrawer.ScrollBody>
- {/* Give desktop surfaces their natural height so their size-full
+ <MobileDrawer.ScrollBody>
+ {/* Give desktop surfaces their natural height so their size-full
and overflow-clip styles cannot clip the drawer's scroll body. */}
- <div class="shrink-0 [&>[data-layer]>[data-surface]]:border-0! [&>[data-layer]>[data-surface]]:rounded-none [&>[data-layer]>[data-surface]]:bg-transparent">
- {props.children}
- </div>
- </MobileDrawer.ScrollBody>
- }
- >
- <div class="flex min-h-0 flex-auto flex-col">
+ <div class="shrink-0 [&>[data-layer]>[data-surface]]:border-0! [&>[data-layer]>[data-surface]]:rounded-none [&>[data-layer]>[data-surface]]:bg-transparent">
{props.children}
</div>
- </Show>
+ </MobileDrawer.ScrollBody>
</MobileDrawer.Content>
</MobileDrawer.Portal>
</MobileDrawer>
diff --git a/apps/web/src/features/block-md/component/sidepanel/MarkdownReferencesSection.tsx b/apps/web/src/features/block-md/component/sidepanel/MarkdownReferencesSection.tsx
deleted file mode 100644
index 139b81a710..0000000000
--- a/apps/web/src/features/block-md/component/sidepanel/MarkdownReferencesSection.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { MeetingReference } from '@app/features/calendar-notes/meeting-reference';
-import type { DocumentReference } from '@app/features/calendar-notes/queries/notes-source';
-import { documentLinksOptions } from '@app/features/calendar-notes/queries/notes-source';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import { SidePanel, useSidePanel } from '@components/app/side-panel';
-import { References } from '@core/component/References';
-import { enableCalendarMeetingNotes } from '@core/constant/featureFlags';
-import { useUserId } from '@core/context/user';
-import { isMobile } from '@core/mobile/isMobile';
-import { fireAndForget } from '@core/util/fireAndForget';
-import { queryReadyGate } from '@queries/gate';
-import { useAttachmentReferencesQuery } from '@queries/storage/attachment-references';
-import { useQuery } from '@tanstack/solid-query';
-import { Button } from '@ui';
-import { For, Show, Suspense } from 'solid-js';
-
-/** Keep the meeting source unmounted while its rollout flag is off. */
-export function MarkdownReferencesSection(props: { documentId: string }) {
- const flag = useFeatureFlag(enableCalendarMeetingNotes);
- const userId = useUserId();
- return (
- <Show
- when={flag().enabled && userId()}
- fallback={<ReferencesSection documentId={props.documentId} />}
- >
- <Suspense fallback={<ReferencesSection documentId={props.documentId} />}>
- <ReferencesWithMeetings documentId={props.documentId} />
- </Suspense>
- </Show>
- );
-}
-
-function ReferencesWithMeetings(props: { documentId: string }) {
- const userId = useUserId();
- const links = useQuery(() =>
- documentLinksOptions(userId(), props.documentId)
- );
- return (
- <ReferencesSection
- documentId={props.documentId}
- meetings={queryReadyGate(links) ? links.data : []}
- meetingError={links.isError}
- onRetry={() =>
- fireAndForget(links.refetch(), 'calendar.notes.references.retry')
- }
- />
- );
-}
-
-function ReferencesSection(props: {
- documentId: string;
- meetings?: DocumentReference[];
- meetingError?: boolean;
- onRetry?: () => void;
-}) {
- const sidePanel = useSidePanel();
- const references = useAttachmentReferencesQuery(
- () => props.documentId,
- () => 'document'
- );
- const attachmentCount = () =>
- queryReadyGate(references) ? references.data.length : 0;
- const count = () => attachmentCount() + (props.meetings?.length ?? 0);
- return (
- <Show when={count() > 0 || props.meetingError}>
- <SidePanel.Section
- id="references"
- title={<SidePanel.CountTitle label="References" count={count()} />}
- order={33}
- >
- <div class="text-xs">
- <Show when={props.meetingError}>
- <div
- role="alert"
- class="flex items-center justify-between gap-2 py-2 text-ink-muted"
- >
- Couldn’t load meeting references.
- <Button variant="ghost" size="sm" onClick={props.onRetry}>
- Retry
- </Button>
- </div>
- </Show>
- <For each={props.meetings}>
- {(link) => (
- <MeetingReference
- documentId={props.documentId}
- link={link}
- onRetry={props.onRetry}
- onOpenCalendar={() => {
- if (isMobile()) sidePanel?.setIsOpen(false);
- }}
- />
- )}
- </For>
- <Show when={attachmentCount() > 0}>
- <References documentId={props.documentId} />
- </Show>
- </div>
- </SidePanel.Section>
- </Show>
- );
-}
diff --git a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index 9f5d2287e3..588e693fc2 100644
--- a/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/apps/web/src/features/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -20,6 +20,7 @@ import { useSplitLayout } from '@components/app/split-layout/layout';
import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
import { Wordcount } from '@core/component/LexicalMarkdown/component/status/Wordcount';
import { Notifications } from '@core/component/Notifications';
+import { References } from '@core/component/References';
import {
enableProjects,
USE_MACRO_PR_SUMMARY_BLOCK,
@@ -36,6 +37,8 @@ import {
getDefaultPinnedProperties,
SYSTEM_PROPERTY_IDS,
} from '@property/constants';
+import { queryReadyGate } from '@queries/gate';
+import { useAttachmentReferencesQuery } from '@queries/storage/attachment-references';
import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';
import {
type GithubPullRequestWithDetails,
@@ -50,7 +53,6 @@ import { createPinnedProperties } from '../../primitives/create-pinned-propertie
import { DispatchAgentButton } from '../DispatchAgentMenu';
import { useMarkdownName } from '../MarkdownNameProvider';
import { TaskDuplicateMatchesSidePanelSection } from '../TaskDuplicateMatches';
-import { MarkdownReferencesSection } from './MarkdownReferencesSection';
/** Registers markdown header actions, panel sections, and shared metadata. */
export function MarkdownSidePanelSections() {
@@ -119,7 +121,7 @@ export function MarkdownSidePanelSections() {
/>
<GithubSectionConditional documentId={documentId()} isTask={isTask()} />
<NotificationsSectionConditional entity={entity()} />
- <MarkdownReferencesSection documentId={documentId()} />
+ <ReferencesSectionConditional documentId={documentId()} />
<Show when={isTask()}>
<TaskDuplicateMatchesSidePanelSection />
</Show>
@@ -318,6 +320,33 @@ function NotificationsSectionConditional(props: { entity: Entity }) {
);
}
+// ─────────────────────────────────────────────────────────────────────────────
+// References Section (conditional)
+// ─────────────────────────────────────────────────────────────────────────────
+
+function ReferencesSectionConditional(props: { documentId: string }) {
+ const references = useAttachmentReferencesQuery(
+ () => props.documentId,
+ () => 'document'
+ );
+
+ const count = () => (queryReadyGate(references) ? references.data.length : 0);
+
+ return (
+ <Show when={count() > 0}>
+ <SidePanel.Section
+ id="references"
+ title={<SidePanel.CountTitle label="References" count={count()} />}
+ order={33}
+ >
+ <div class="text-xs">
+ <References documentId={props.documentId} />
+ </div>
+ </SidePanel.Section>
+ </Show>
+ );
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// GitHub Section (conditional)
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/apps/web/src/features/calendar-notes/browser-test/fixture.tsx b/apps/web/src/features/calendar-notes/browser-test/fixture.tsx
deleted file mode 100644
index cb7e9b2cf3..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/fixture.tsx
+++ /dev/null
@@ -1,220 +0,0 @@
-import '@fontsource-variable/inter';
-import '../../../index.css';
-import { fireAndForget } from '@core/util/fireAndForget';
-import CalendarIcon from '@icon/system/regular/calendar-blank.svg';
-import { Button, ImperativeDialogHost } from '@ui';
-import { ok } from 'neverthrow';
-import { createSignal, onCleanup, Show } from 'solid-js';
-import { render } from 'solid-js/web';
-import type { CalendarEvent } from '../../calendar/types';
-import { SelectedEventDetails } from '../../calendar-view/components/SelectedEventDetails';
-import { macroDarkTheme } from '../../theme/themes/macro-dark';
-import { macroLightTheme } from '../../theme/themes/macro-light';
-import type { DocumentNoteLink } from '../core/types';
-import { createFakeNotesSource } from '../tests/fake-source';
-import { DocumentNotesView } from '../views/document-notes';
-import { PreviewNotesProvider } from './preview-adapters';
-
-const params = new URLSearchParams(location.search);
-document.documentElement.dataset.themeLight = String(
- params.get('theme') !== 'dark'
-);
-const theme = params.get('theme') === 'dark' ? macroDarkTheme : macroLightTheme;
-for (const [token, value] of Object.entries(theme.colorTokens)) {
- document.documentElement.style.setProperty(`--color-${token}`, value);
-}
-
-const calendar = { id: 'calendar-1', name: 'Calendar', color: '#609fe2' };
-const sampleEvent: CalendarEvent = {
- id: 'weekly-sync',
- eventId: 'event-1',
- occurrenceKey: '2026-10-23T14:00:00Z',
- title: 'Weekly product sync',
- start: '2026-10-23T14:00:00Z',
- end: '2026-10-23T14:30:00Z',
- allDay: false,
- isCancelled: false,
- isReadOnly: false,
- description: 'Review progress, decisions, and next steps.',
- recurrenceLines: ['RRULE:FREQ=WEEKLY;BYDAY=FR'],
- guestPolicy: {
- canModify: false,
- canInviteOthers: true,
- canSeeOtherGuests: true,
- },
- viewerCan: {
- editDetails: false,
- inviteGuests: true,
- removeGuests: false,
- setGuestPolicy: false,
- rsvp: true,
- organize: false,
- },
- attendees: [
- {
- email: '[email protected]',
- isOptional: false,
- isOrganizer: true,
- isSelf: false,
- responseStatus: 'accepted',
- },
- {
- email: '[email protected]',
- isOptional: false,
- isOrganizer: false,
- isSelf: false,
- responseStatus: 'accepted',
- },
- {
- email: '[email protected]',
- isOptional: false,
- isOrganizer: false,
- isSelf: true,
- responseStatus: 'accepted',
- },
- ],
- organizerEmail: '[email protected]',
- sourceCalendarIds: [calendar.id],
- calendarId: calendar.id,
- calendar,
- visibleCalendars: [calendar],
-};
-
-function Fixture() {
- const [links, setLinks] = createSignal<DocumentNoteLink[]>([
- {
- eventId: 'unavailable',
- occurrenceKey: '2026-10-23T14:00:00Z',
- eventTitle: 'Unavailable meeting',
- team: { id: 'macro', name: 'Macro' },
- },
- ]);
- if (params.has('document'))
- return (
- <main class="min-h-dvh bg-page px-3 py-10 text-ink">
- <div class="mx-auto max-w-[480px]">
- <h1 class="mb-4 text-lg font-semibold">
- Share: Weekly product notes
- </h1>
- <DocumentNotesView
- source={{
- links: () => ({ data: links(), pending: false }),
- team: () => ({ data: null, pending: false }),
- setTeam: async () => {
- setLinks((current) =>
- current.map((link) => ({ ...link, team: undefined }))
- );
- return ok(undefined);
- },
- retry: async () => {},
- unlink: async () => {
- setLinks([]);
- return ok(undefined);
- },
- }}
- />
- <p class="mt-4 text-sm">Your document is saved.</p>
- </div>
- </main>
- );
- const fake = createFakeNotesSource({
- fail: params.has('fail'),
- });
- const teamProjectionKind = params.get('team');
- const [event, setEvent] = createSignal<CalendarEvent>({
- ...sampleEvent,
- teamProjection:
- teamProjectionKind === 'details' || teamProjectionKind === 'busy'
- ? { kind: teamProjectionKind, ownerId: 'macro|[email protected]' }
- : undefined,
- guestPolicy: {
- ...sampleEvent.guestPolicy,
- canSeeOtherGuests: !params.has('hidden'),
- },
- });
- const [selected, setSelected] = createSignal(true);
- const [boundary, setBoundary] = createSignal<HTMLDivElement>();
- const [anchor, setAnchor] = createSignal<HTMLButtonElement>();
- const [message, setMessage] = createSignal('');
- const onMessage = (event: Event) => {
- if (event instanceof CustomEvent && typeof event.detail === 'string')
- setMessage(event.detail);
- };
- const onRsvp = (event: Event) => {
- if (!(event instanceof CustomEvent)) return;
- const response = event.detail;
- if (
- response !== 'accepted' &&
- response !== 'tentative' &&
- response !== 'declined'
- )
- return;
- setEvent((current) => ({
- ...current,
- attendees: current.attendees.map((attendee) =>
- attendee.isSelf ? { ...attendee, responseStatus: response } : attendee
- ),
- }));
- };
- const onRemoteUnlink = (event: Event) => {
- if (event instanceof CustomEvent && typeof event.detail === 'string') {
- fireAndForget(
- fake.source.unlink(event.detail),
- 'calendar.preview.unlink'
- );
- }
- };
- document.addEventListener('calendar-preview-message', onMessage);
- document.addEventListener('calendar-preview-rsvp', onRsvp);
- document.addEventListener('calendar-preview-unlink', onRemoteUnlink);
- onCleanup(() => {
- document.removeEventListener('calendar-preview-message', onMessage);
- document.removeEventListener('calendar-preview-rsvp', onRsvp);
- document.removeEventListener('calendar-preview-unlink', onRemoteUnlink);
- });
- return (
- <PreviewNotesProvider source={fake.source}>
- <main
- ref={setBoundary}
- class="relative min-h-dvh bg-page p-4 text-ink sm:p-8"
- >
- <div class="flex items-center gap-2 text-sm text-ink-muted">
- <CalendarIcon class="size-4" /> Friday, October 23
- </div>
- <Button
- ref={setAnchor}
- variant="secondary"
- size="md"
- class="mt-5"
- onClick={() => setSelected(true)}
- >
- Weekly product sync
- </Button>
- <Show when={message()}>
- <p
- role="status"
- aria-label="Preview action"
- class="mt-4 text-sm text-ink-muted"
- >
- {message()}
- </p>
- </Show>
- <Show when={boundary()}>
- {(element) => (
- <SelectedEventDetails
- boundary={element()}
- anchor={anchor}
- event={() => (selected() ? event() : undefined)}
- timeFormat={() => '12-hour'}
- onClose={() => setSelected(false)}
- />
- )}
- </Show>
- <ImperativeDialogHost />
- </main>
- </PreviewNotesProvider>
- );
-}
-
-const root = document.getElementById('root');
-if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/calendar-notes/browser-test/index.html b/apps/web/src/features/calendar-notes/browser-test/index.html
deleted file mode 100644
index 7109c4b797..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/index.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<!doctype html>
-<html lang="en" data-modality="keyboard">
- <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Meeting notes</title></head>
- <body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body>
-</html>
diff --git a/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts b/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts
deleted file mode 100644
index b98e0a3e8f..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/notes.browser.e2e.ts
+++ /dev/null
@@ -1,420 +0,0 @@
-import { expect, test } from '@playwright/test';
-
-test('full-detail team viewers can link and open notes without provider actions', async ({
- page,
-}) => {
- await page.goto('/?team=details');
- const notes = page.getByRole('region', { name: 'Meeting notes' });
- await notes
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- await dialog
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await notes
- .getByRole('button', { name: 'Open Weekly product sync', exact: true })
- .click();
- await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
- 'Opened Weekly product sync'
- );
-
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(notes).toBeVisible();
- await expect(
- page.getByRole('button', { name: 'Yes', exact: true })
- ).toHaveCount(0);
- await expect(
- page.getByRole('button', { name: 'Edit event', exact: true })
- ).toHaveCount(0);
-
- await page.goto('/?team=busy');
- await expect(
- page.getByRole('button', { name: 'Close event details', exact: true })
- ).toBeVisible();
- await expect(notes).toHaveCount(0);
-});
-
-test('long note titles keep their options accessible without horizontal scrolling', async ({
- page,
-}) => {
- await page.goto('/');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- const title =
- 'Agent: offers to add a meeting to another calendar after the organizer updates a recurring event';
- await dialog.getByRole('button', { name: title, exact: true }).click();
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await expect(dialog).not.toBeVisible();
- const notes = page.getByRole('region', { name: 'Meeting notes' });
- expect(await notes.evaluate((element) => element.scrollWidth)).toBe(
- await notes.evaluate((element) => element.clientWidth)
- );
- const options = notes.getByRole('button', {
- name: `Options for ${title}`,
- exact: true,
- });
- await expect(options).toBeInViewport({ ratio: 1 });
- await options.click();
- await page.getByRole('menuitem', { name: 'Unlink from meeting' }).click();
- await page
- .getByRole('dialog', { name: 'Unlink meeting notes?' })
- .getByRole('button', { name: 'Unlink note', exact: true })
- .click();
- await expect(
- notes.getByRole('button', { name: `Open ${title}` })
- ).toHaveCount(0);
-});
-
-test('create and open multiple notes with meeting access and no team sharing', async ({
- page,
-}) => {
- await page.goto('/');
- const notes = page.getByRole('region', { name: 'Meeting notes' });
- await notes
- .getByRole('button', { name: 'Create notes', exact: true })
- .click();
- await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
- 'Opened Weekly product sync notes'
- );
- await expect(notes).not.toBeVisible();
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(
- notes.getByRole('button', {
- name: 'Open Weekly product sync notes',
- exact: true,
- })
- ).toHaveCount(1);
- await expect(notes).not.toContainText('Also shared with Macro');
- await notes
- .getByRole('button', { name: 'Create notes', exact: true })
- .click();
- await expect(notes).not.toBeVisible();
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(
- notes.getByRole('button', {
- name: 'Open Weekly product sync notes',
- exact: true,
- })
- ).toHaveCount(2);
- await expect(
- notes.getByRole('button', { name: 'Options for Weekly product sync notes' })
- ).toHaveCount(2);
-});
-
-test('retry linking a newly created note without duplicating the document', async ({
- page,
-}) => {
- await page.goto('/?fail=1');
- const notes = page.getByRole('region', { name: 'Meeting notes' });
- await notes
- .getByRole('button', { name: 'Create notes', exact: true })
- .click();
- await expect(notes.getByRole('alert')).toContainText('Your note was saved');
- await expect(
- notes.getByRole('button', { name: 'Open saved note' })
- ).toBeVisible();
- await notes
- .getByRole('button', { name: 'Retry linking', exact: true })
- .click();
- await expect(notes).not.toBeVisible();
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(
- notes.getByRole('button', {
- name: 'Open Weekly product sync notes',
- exact: true,
- })
- ).toHaveCount(1);
- await notes.getByRole('button', { name: 'Link existing' }).click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- await expect(
- dialog.getByRole('button', {
- name: 'Weekly product sync notes',
- exact: true,
- })
- ).toHaveCount(1);
- await expect(
- dialog.getByRole('button', {
- name: 'Weekly product sync notes',
- exact: true,
- })
- ).toBeDisabled();
-});
-
-test('an owner can revoke a missing meeting’s team grant from document sharing', async ({
- page,
-}) => {
- await page.goto('/?document=1');
- const links = page.getByRole('region', { name: 'Meeting links' });
- await expect(links).toContainText('Unavailable meeting');
- await expect(links).toContainText('Macro');
- await links.getByRole('button', { name: 'Unlink', exact: true }).click();
- await links.getByRole('button', { name: 'Keep link' }).click();
- await expect(links).toBeVisible();
- await links.getByRole('button', { name: 'Unlink', exact: true }).click();
- await links
- .getByRole('button', { name: 'Unlink meeting', exact: true })
- .click();
- await expect(links).not.toBeVisible();
- await expect(page.getByText('Your document is saved.')).toBeVisible();
-});
-
-test('link a note, optionally share with a team, open it, and unlink it', async ({
- page,
-}, testInfo) => {
- await page.goto('/');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', {
- name: /Link meeting notes|Unlink meeting notes/,
- });
- await expect(
- dialog.getByRole('button', { name: 'Link note', exact: true })
- ).toBeDisabled();
- await dialog
- .getByRole('textbox', { name: 'Find a markdown document' })
- .fill('weekly');
- await dialog
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(
- dialog.getByRole('checkbox', { name: /Also share with Macro/ })
- ).not.toBeChecked();
- await expect(
- dialog.getByRole('button', { name: 'Link note', exact: true })
- ).toBeInViewport();
- await page.screenshot({ path: testInfo.outputPath('link-note.png') });
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await expect(dialog).not.toBeVisible();
- await page
- .getByRole('button', { name: 'Options for Weekly product sync' })
- .click();
- await page.getByRole('menuitem', { name: 'Share', exact: true }).click();
- const share = page.getByRole('dialog', {
- name: 'Share: Weekly product sync',
- exact: true,
- });
- await share.getByText('Also share with Macro').click();
- await expect(share.getByRole('checkbox')).toBeChecked();
- await share.getByRole('button', { name: 'Done', exact: true }).click();
- await expect(share).not.toBeVisible();
- await expect(
- page.getByRole('region', { name: 'Meeting notes' })
- ).toContainText('Also shared with Macro');
- await page.screenshot({ path: testInfo.outputPath('linked-note.png') });
- await page
- .getByRole('region', { name: 'Meeting notes' })
- .getByRole('button', { name: 'Open Weekly product sync', exact: true })
- .click();
- await expect(page.getByRole('status', { name: 'Preview action' })).toHaveText(
- 'Opened Weekly product sync'
- );
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await page
- .getByRole('button', { name: 'Options for Weekly product sync' })
- .click();
- await page.getByRole('menuitem', { name: 'Unlink from meeting' }).click();
- await dialog
- .getByRole('button', { name: 'Unlink note', exact: true })
- .click();
- await expect(
- page.getByRole('button', { name: 'Link existing', exact: true })
- ).toBeVisible();
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- await expect(
- dialog.getByRole('button', { name: 'Weekly product sync', exact: true })
- ).toBeEnabled();
-});
-
-test('a failed link preserves the selected document and sharing choice for retry', async ({
- page,
-}) => {
- await page.goto('/?fail=1');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', {
- name: /Link meeting notes|Unlink meeting notes/,
- });
- await dialog
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await dialog.getByText('Also share with Macro').click();
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await expect(dialog.getByRole('alert')).toBeVisible();
- await expect(
- dialog.getByRole('button', { name: 'Weekly product sync', exact: true })
- ).toHaveAttribute('aria-pressed', 'true');
- await expect(
- dialog.getByRole('checkbox', { name: /Also share with Macro/ })
- ).toBeChecked();
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await expect(dialog).not.toBeVisible();
- await expect(
- page.getByRole('region', { name: 'Meeting notes' })
- ).toContainText('Also shared with Macro');
-});
-
-test('removing a note during an open options menu does not block event dismissal', async ({
- page,
-}) => {
- await page.goto('/');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- await dialog
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await dialog.getByRole('button', { name: 'Link note', exact: true }).click();
- await page
- .getByRole('button', { name: 'Options for Weekly product sync' })
- .click();
- await expect(
- page.getByRole('menuitem', { name: 'Share', exact: true })
- ).toBeVisible();
- await page.evaluate(() =>
- document.dispatchEvent(
- new CustomEvent('calendar-preview-unlink', { detail: 'weekly' })
- )
- );
- await expect(
- page.getByRole('menuitem', { name: 'Share', exact: true })
- ).not.toBeVisible();
- await page.keyboard.press('Escape');
- await expect(
- page.getByRole('region', { name: 'Meeting notes' })
- ).not.toBeVisible();
- await page
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await expect(
- page.getByRole('region', { name: 'Meeting notes' })
- ).toBeVisible();
-});
-
-test('short dialogs scroll only the note results and keep context, sharing, and actions visible', async ({
- page,
-}) => {
- await page.setViewportSize({
- width: page.viewportSize()?.width ?? 400,
- height: 520,
- });
- await page.goto('/');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- const title = dialog.getByRole('heading', { name: 'Link meeting notes' });
- const sharing = dialog.getByRole('region', { name: 'Note sharing' });
- const submit = dialog.getByRole('button', { name: 'Link note', exact: true });
- const results = dialog.getByRole('region', {
- name: 'Your markdown documents',
- });
- await expect(sharing).toBeInViewport({ ratio: 1 });
- await expect(submit).toBeInViewport({ ratio: 1 });
- await dialog.evaluate(async (element) => {
- await Promise.all(
- element
- .getAnimations({ subtree: true })
- .map((animation) => animation.finished)
- );
- });
- const titleBefore = await title.boundingBox();
- const sharingBefore = await sharing.boundingBox();
- await results
- .getByRole('button', { name: 'Team retrospective', exact: true })
- .scrollIntoViewIfNeeded();
- await expect(title).toBeInViewport({ ratio: 1 });
- await expect(
- dialog.getByText('Weekly product sync', { exact: true }).first()
- ).toBeInViewport({ ratio: 1 });
- expect(await title.boundingBox()).toEqual(titleBefore);
- expect(await sharing.boundingBox()).toEqual(sharingBefore);
- await results
- .getByRole('button', { name: 'Team retrospective', exact: true })
- .click();
- await submit.click();
- await expect(dialog).not.toBeVisible();
- await expect(
- page.getByRole('button', { name: 'Open Team retrospective', exact: true })
- ).toBeVisible();
-});
-
-test('search, dismiss, and reopen reset the unfinished choice', async ({
- page,
-}) => {
- await page.goto('/?theme=dark');
- const trigger = page.getByRole('button', {
- name: 'Link existing',
- exact: true,
- });
- await trigger.click();
- const dialog = page.getByRole('dialog', {
- name: /Link meeting notes|Unlink meeting notes/,
- });
- await dialog.getByRole('textbox').fill('no matching note');
- await expect(dialog.getByText('No notes match this name.')).toBeVisible();
- await dialog.getByRole('button', { name: 'Cancel' }).click();
- await expect(dialog).not.toBeVisible();
- await trigger.click();
- await expect(dialog.getByRole('textbox')).toHaveValue('');
- await expect(
- dialog.getByRole('button', { name: 'Link note', exact: true })
- ).toBeDisabled();
- await expect(dialog.getByRole('checkbox')).not.toBeChecked();
- await expect(page.locator('body')).toHaveJSProperty(
- 'scrollWidth',
- await page.locator('body').evaluate((body) => body.clientWidth)
- );
-});
-
-test('team selection and failure recovery stay visible in a short viewport', async ({
- page,
-}) => {
- await page.setViewportSize({
- width: page.viewportSize()?.width ?? 400,
- height: 520,
- });
- await page.goto('/?hidden=1&fail=1');
- await page
- .getByRole('button', { name: 'Link existing', exact: true })
- .click();
- const dialog = page.getByRole('dialog', { name: 'Link meeting notes' });
- await expect(
- dialog.getByText(/This meeting hides its guest list/)
- ).toBeInViewport({ ratio: 1 });
- await dialog
- .getByRole('button', { name: 'Weekly product sync', exact: true })
- .click();
- await dialog.getByText('Also share with Macro').click();
- const submit = dialog.getByRole('button', { name: 'Link note', exact: true });
- await expect(submit).toBeInViewport({ ratio: 1 });
- await submit.click();
- await expect(dialog.getByRole('alert')).toBeInViewport({ ratio: 1 });
- await expect(
- dialog.getByRole('region', { name: 'Note sharing' })
- ).toBeInViewport({ ratio: 1 });
- await expect(submit).toBeInViewport({ ratio: 1 });
- await submit.click();
- await expect(dialog).not.toBeVisible();
- await expect(
- page.getByRole('region', { name: 'Meeting notes' })
- ).toContainText('Also shared with Macro');
-});
diff --git a/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts b/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts
deleted file mode 100644
index 6306e366ac..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/playwright.config.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { fileURLToPath } from 'node:url';
-import { defineConfig, devices } from '@playwright/test';
-
-const directory = fileURLToPath(new URL('.', import.meta.url));
-const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
-const port = Number(process.env.CALENDAR_NOTES_BROWSER_PORT ?? 3097);
-export default defineConfig({
- testDir: directory,
- testMatch: '*.browser.e2e.ts',
- outputDir: `${directory}/test-results`,
- timeout: 45_000,
- fullyParallel: true,
- use: {
- baseURL: `http://127.0.0.1:${port}`,
- trace: 'retain-on-failure',
- screenshot: 'only-on-failure',
- contextOptions: { reducedMotion: 'reduce' },
- },
- webServer: {
- command: `bunx vite --config src/features/calendar-notes/browser-test/vite.config.ts --port ${port}`,
- cwd: webDirectory,
- url: `http://127.0.0.1:${port}`,
- reuseExistingServer: false,
- timeout: 120_000,
- },
- projects: [
- {
- name: 'desktop',
- use: {
- ...devices['Desktop Chrome'],
- launchOptions: {
- executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
- },
- },
- },
- {
- name: 'phone',
- use: {
- ...devices['iPhone 13'],
- defaultBrowserType: 'chromium',
- launchOptions: {
- executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
- },
- },
- },
- ],
-});
diff --git a/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx b/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx
deleted file mode 100644
index 5368048a4e..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/preview-adapters.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-import { Avatar, Button, Dialog } from '@ui';
-import { createContext, type ParentProps, useContext } from 'solid-js';
-import { EventAttendeesSection } from '../../calendar/components/EventDetails';
-import type { CalendarEvent } from '../../calendar/types';
-import type { NotesSource } from '../context/notes-source';
-import { DocumentNotesView } from '../views/document-notes';
-import { MeetingNotesView } from '../views/meeting-notes';
-
-export { sanitizeCalendarDescription } from '../../calendar/utils/calendar-description-sanitizer';
-export const parseMacroAppLink = () => undefined;
-export const recipientEntityMapper = () => () => undefined;
-
-// Sample sources, identities, and placeholders for unrelated calendar actions.
-// Event details, its popover/drawer, and the notes controls render their real UI.
-const NotesContext = createContext<NotesSource>();
-export function PreviewNotesProvider(
- props: ParentProps<{ source: NotesSource }>
-) {
- return (
- <NotesContext.Provider value={props.source}>
- {props.children}
- </NotesContext.Provider>
- );
-}
-
-function announce(message: string) {
- document.dispatchEvent(
- new CustomEvent('calendar-preview-message', { detail: message })
- );
-}
-
-export function CalendarMeetingNotes(props: {
- event: CalendarEvent;
- onOpenDocument: (id: string) => void;
- onDialogChange: (open: boolean) => void;
-}) {
- const source = useContext(NotesContext);
- if (!source) throw new Error('The calendar preview needs a notes source');
- return (
- <MeetingNotesView
- source={source}
- eventTitle={props.event.title}
- recurring={props.event.recurrenceLines.length > 0}
- guestListHidden={!props.event.guestPolicy.canSeeOtherGuests}
- onOpen={(note) => {
- announce(`Opened ${note.name}`);
- props.onOpenDocument(note.documentId);
- }}
- onDialogChange={props.onDialogChange}
- shareDialog={(note, onClose) => (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onClose();
- }}
- position="center"
- class="w-[720px]"
- >
- <div class="p-4">
- <Dialog.Title>Share: {note.name}</Dialog.Title>
- <Dialog.Description class="my-3 text-xs text-ink-muted">
- Preview of meeting access controls. The app opens the full
- document Share dialog.
- </Dialog.Description>
- <DocumentNotesView
- source={{
- links: () => ({
- pending: false,
- data: source
- .notes()
- .data?.filter((item) => item.documentId === note.documentId)
- .map((item) => ({
- eventId: props.event.eventId,
- occurrenceKey: props.event.occurrenceKey,
- eventTitle: props.event.title,
- team: item.team,
- })),
- }),
- team: () => ({
- pending: false,
- data: { id: 'macro', name: 'Macro' },
- }),
- retry: source.retry,
- setTeam: (_target, teamId) =>
- source.link(note.documentId, teamId),
- unlink: () => source.unlink(note.documentId),
- }}
- />
- <div class="mt-4 flex justify-end">
- <Button variant="ghost" onClick={onClose}>
- Done
- </Button>
- </div>
- </div>
- </Dialog>
- )}
- />
- );
-}
-
-export const useVisibleCalendarsQuery = () => ({ isSuccess: true, data: [] });
-export const useDeleteCalendarEventMutation = () => ({
- isPending: false,
- mutate: () => announce('Delete event · Preview only'),
-});
-export const useSplitLayout = () => ({ openWithSplit: () => {} });
-export const useOpenEventComposer = () => () =>
- announce('Edit event · Preview only');
-export const useForwardEventEmail = () => () =>
- announce('Forward event · Preview only');
-export const createGuestInviteController = () => ({
- editorOpen: () => false,
- forwardEditorOpen: () => false,
-});
-export const useCalendarGuestInvitesFlag = () => () => false;
-export const useCalendarInvitationForwardFlag = () => () => false;
-export const useCalendarMeetingNotesFlag = () => () =>
- new URLSearchParams(location.search).get('notes') !== 'off';
-export const EventGuests = (props: { event: CalendarEvent }) => (
- <EventAttendeesSection attendees={props.event.attendees} />
-);
-export const EventJoinRequests = () => null;
-export const TeamEventDetails = () => null;
-export const OutlookRsvpAction = () => null;
-export const copyCalendarEventMention = () =>
- announce('Copy event · Preview only');
-export const downloadCalendarEventIcs = () =>
- announce('Download event · Preview only');
-export const openDocument = () => announce('Open document · Preview only');
-export const toast = { success: announce, failure: announce };
-
-export const createCalendarRsvpController = () => ({
- pending: () => false,
- error: () => undefined,
- scopeOpen: () => false,
- scope: () => 'this_event',
- setScope: () => {},
- closeScope: () => {},
- confirmScope: () => {},
- respond: (response: string) =>
- document.dispatchEvent(
- new CustomEvent('calendar-preview-rsvp', { detail: response })
- ),
-});
-
-const names: Record<string, string> = {
- '[email protected]': 'Alex Morgan',
- '[email protected]': 'Sam Lee',
- '[email protected]': 'You',
-};
-export const emailToMacroId = (email: string) => email;
-export const getDisplayName = (id?: string) => names[id ?? ''] ?? '';
-export const getInitialsFromName = (name: string) =>
- name
- .split(' ')
- .map((part) => part[0])
- .join('');
-export function UserIcon(props: { id?: string; email?: string; size?: 'md' }) {
- return (
- <Avatar size={props.size ?? 'md'}>
- <Avatar.Fallback>
- {getInitialsFromName(getDisplayName(props.id ?? props.email))}
- </Avatar.Fallback>
- </Avatar>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/browser-test/vite.config.ts b/apps/web/src/features/calendar-notes/browser-test/vite.config.ts
deleted file mode 100644
index 1ab4471b9d..0000000000
--- a/apps/web/src/features/calendar-notes/browser-test/vite.config.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { fileURLToPath } from 'node:url';
-import tailwind from '@tailwindcss/vite';
-import { defineConfig } from 'vite';
-import solidPlugin from 'vite-plugin-solid';
-import solidSvg from 'vite-plugin-solid-svg';
-import tsconfigPaths from 'vite-tsconfig-paths';
-
-const directory = fileURLToPath(new URL('.', import.meta.url));
-const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
-const workspaceDirectory = fileURLToPath(
- new URL('../../../../../../', import.meta.url)
-);
-
-const previewAdapters = `${directory}/preview-adapters.tsx`;
-const previewImports = [
- '@queries/calendar/calendars',
- '@queries/calendar/mutations',
- '@components/app/split-layout/layout',
- '@app/features/calendar-view/components/use-open-event-composer',
- '@app/features/calendar-view/components/use-forward-event-email',
- '@app/features/calendar/hooks/create-guest-invite-controller',
- '@app/features/calendar/hooks/use-calendar-ui-flag',
- '@app/features/calendar-notes/calendar-meeting-notes',
- '@app/features/calendar-view/components/EventGuests',
- '@app/features/calendar-view/components/EventJoinRequests',
- '@app/features/calendar-team/components/team-event-details',
- '@app/features/calendar/views/event-replacement',
- '@app/features/calendar-view/copy-event-mention',
- '@app/features/calendar-view/download-event-ics',
- '@core/component/LexicalMarkdown/component/core/BlockLink',
- '@core/component/UserIcon',
- '@core/component/Toast/Toast',
- '@core/user/combinedRecipient',
- '@core/user',
- '../utils/calendar-description',
- '../../calendar/hooks/create-calendar-rsvp-controller',
-];
-
-/** Real event overlays and notes views, with sample data and preview services. */
-export default defineConfig({
- root: directory,
- cacheDir: `${directory}/.vite`,
- plugins: [
- solidPlugin(),
- solidSvg({ defaultAsComponent: true }),
- tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),
- tailwind(),
- ],
- resolve: {
- dedupe: ['solid-js'],
- alias: previewImports.map((find) => ({
- find,
- replacement: previewAdapters,
- })),
- },
- server: {
- host: '127.0.0.1',
- port: 3097,
- strictPort: true,
- fs: { allow: [workspaceDirectory] },
- },
-});
diff --git a/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx b/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx
deleted file mode 100644
index e3e23aa677..0000000000
--- a/apps/web/src/features/calendar-notes/calendar-meeting-notes.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { Permissions } from '@core/component/SharePermissions';
-import { useQuickAccess } from '@core/context/quickAccess';
-import { useUserId } from '@core/context/user';
-import { lazy, Show, Suspense } from 'solid-js';
-import type { CalendarEvent } from '../calendar/types';
-import { createLocalNoteSearch } from './queries/local-note-search';
-import { createNotesSource } from './queries/notes-source';
-import { MeetingNotesView } from './views/meeting-notes';
-
-const ShareModal = lazy(async () => ({
- default: (await import('@core/component/TopBar/ShareButton')).ShareModal,
-}));
-
-/** App composition; the view and controller also mount without calendar chrome. */
-export function CalendarMeetingNotes(props: {
- event: CalendarEvent;
- onOpenDocument: (documentId: string) => void;
- onDialogChange: (open: boolean) => void;
-}) {
- const userId = useUserId();
- const localSearch = createLocalNoteSearch(useQuickAccess(), userId);
- const source = createNotesSource(
- userId,
- () => ({
- eventId: props.event.eventId,
- occurrenceKey: props.event.occurrenceKey,
- }),
- localSearch
- );
- return (
- <Suspense>
- <Show
- when={JSON.stringify([
- userId(),
- props.event.eventId,
- props.event.occurrenceKey,
- ])}
- keyed
- >
- {(_identity) => (
- <MeetingNotesView
- source={source}
- eventTitle={props.event.title}
- recurring={props.event.recurrenceLines.length > 0}
- guestListHidden={!props.event.guestPolicy.canSeeOtherGuests}
- onOpen={(note) => props.onOpenDocument(note.documentId)}
- shareDialog={(note, onClose) => (
- <Suspense>
- <ShareModal
- open
- onOpenChange={(open) => {
- if (!open) onClose();
- }}
- id={note.documentId}
- itemType="document"
- blockAlias="md"
- name={note.name}
- owner={userId()}
- userPermissions={Permissions.OWNER}
- />
- </Suspense>
- )}
- onDialogChange={props.onDialogChange}
- />
- )}
- </Show>
- </Suspense>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/components/document-notes-section.tsx b/apps/web/src/features/calendar-notes/components/document-notes-section.tsx
deleted file mode 100644
index bf51ef7f5e..0000000000
--- a/apps/web/src/features/calendar-notes/components/document-notes-section.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import CalendarIcon from '@icon/system/regular/calendar-blank.svg';
-import { Key } from '@solid-primitives/keyed';
-import { Button, Checkbox } from '@ui';
-import { Show } from 'solid-js';
-import type { DocumentNoteLink, NoteRead, NoteTeam } from '../core/types';
-
-export function DocumentNotesSection(props: {
- state: NoteRead<DocumentNoteLink[]>;
- team: NoteRead<NoteTeam | null>;
- selected?: DocumentNoteLink;
- saving: boolean;
- removing: boolean;
- error?: string;
- onSelect: (link: DocumentNoteLink | undefined) => void;
- onRemove: () => void;
- onTeam: (link: DocumentNoteLink, teamId?: string) => void;
- onRetry: () => void;
-}) {
- return (
- <Show
- when={
- props.state.pending || props.state.error || props.state.data?.length
- }
- >
- <section
- aria-label="Meeting links"
- class="rounded-3xl bg-dialog p-4 text-sm text-ink"
- >
- <h3 class="font-medium">Meeting links</h3>
- <p class="mt-1 text-xs leading-relaxed text-ink-muted">
- People who can see a meeting’s details can read this note.
- </p>
- <Show when={props.state.pending}>
- <p role="status" class="mt-3 text-xs text-ink-muted">
- Loading meeting access…
- </p>
- </Show>
- <Show when={props.state.error || props.team.error}>
- <div
- role="alert"
- class="mt-3 flex items-center justify-between gap-3 text-xs text-failure"
- >
- {props.state.error || props.team.error}
- <Button size="sm" variant="ghost" onClick={props.onRetry}>
- Retry
- </Button>
- </div>
- </Show>
- <Show when={props.error}>
- <p role="alert" class="mt-3 text-xs text-failure">
- {props.error}
- </p>
- </Show>
- <Key
- each={props.state.data}
- by={(link) => JSON.stringify([link.eventId, link.occurrenceKey])}
- >
- {(link) => (
- <div class="mt-3 rounded-xl border border-edge-muted p-3">
- <div class="flex items-start gap-3">
- <CalendarIcon class="mt-0.5 size-4 shrink-0 text-ink-muted" />
- <div class="min-w-0 flex-1">
- <p class="truncate font-medium">{link().eventTitle}</p>
- <p class="mt-1 text-xs text-ink-muted">
- {link().occurrenceKey === 'single'
- ? 'One-time meeting'
- : link().occurrenceKey.slice(0, 10)}{' '}
- · Can view
- </p>
- </div>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.removing}
- onClick={() => props.onSelect(link())}
- >
- Unlink
- </Button>
- </div>
- <Show when={props.team.data}>
- {(team) => (
- <Checkbox
- checked={link().team?.id === team().id}
- disabled={props.saving}
- onChange={(checked) =>
- props.onTeam(link(), checked ? team().id : undefined)
- }
- class="mt-3 gap-2"
- >
- <Checkbox.Control />
- <Checkbox.Label class="text-xs font-normal text-ink-muted">
- Also share with {team().name}
- </Checkbox.Label>
- </Checkbox>
- )}
- </Show>
- <Show
- when={
- link().team &&
- props.team.data !== undefined &&
- link().team?.id !== props.team.data?.id
- }
- >
- <div class="mt-3 flex items-center justify-between gap-3 text-xs text-ink-muted">
- <span>{link().team?.name} can also view this note.</span>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.saving}
- onClick={() => props.onTeam(link(), undefined)}
- >
- Remove team access
- </Button>
- </div>
- </Show>
- <Show
- when={
- props.selected?.eventId === link().eventId &&
- props.selected?.occurrenceKey === link().occurrenceKey
- }
- >
- <div class="mt-3 border-t border-edge-muted pt-3">
- <p class="text-xs text-ink-muted">
- Remove this meeting link and its team access? The document
- and its other sharing stay the same.
- </p>
- <div class="mt-3 flex justify-end gap-2">
- <Button
- variant="ghost"
- size="sm"
- disabled={props.saving}
- onClick={() => props.onSelect(undefined)}
- >
- Keep link
- </Button>
- <Button
- variant="danger"
- size="sm"
- disabled={props.saving}
- onClick={props.onRemove}
- >
- {props.removing ? 'Removing…' : 'Unlink meeting'}
- </Button>
- </div>
- </div>
- </Show>
- </div>
- )}
- </Key>
- </section>
- </Show>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/components/note-dialog.tsx b/apps/web/src/features/calendar-notes/components/note-dialog.tsx
deleted file mode 100644
index a23f92ac19..0000000000
--- a/apps/web/src/features/calendar-notes/components/note-dialog.tsx
+++ /dev/null
@@ -1,254 +0,0 @@
-import CheckIcon from '@icon/system/regular/check.svg';
-import FileTextIcon from '@icon/system/regular/file-text.svg';
-import LinkIcon from '@icon/system/regular/link.svg';
-import MagnifyingGlassIcon from '@icon/system/regular/magnifying-glass.svg';
-import XIcon from '@icon/system/regular/x.svg';
-import { Button, Checkbox, Dialog, InputGroup } from '@ui';
-import { For, Show } from 'solid-js';
-import type { NoteDocument, NotePicker, NoteRead } from '../core/types';
-
-export function NoteDialog(props: {
- kind: 'link' | 'unlink';
- eventTitle: string;
- recurring: boolean;
- guestListHidden?: boolean;
- picker: NoteRead<NotePicker>;
- query: string;
- onQuery: (query: string) => void;
- selected?: NoteDocument;
- onSelect: (document: NoteDocument) => void;
- linkedIds: string[];
- linksReady: boolean;
- teamId?: string;
- onTeam: (id: string | undefined) => void;
- saving: boolean;
- error?: string;
- onSave: () => void;
- onClose: () => void;
-}) {
- const title = () =>
- props.kind === 'unlink' ? 'Unlink meeting notes?' : 'Link meeting notes';
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) props.onClose();
- }}
- position="center"
- class={props.kind === 'link' ? 'w-[720px]' : 'w-[400px]'}
- contentOwnsScroll
- animate
- >
- <div
- class="relative flex min-h-0 max-h-[calc(100dvh-var(--virtual-keyboard-height,0px)-2rem)] flex-col p-4 sm:p-6"
- classList={{ 'h-[680px]': props.kind === 'link' }}
- >
- <div class="flex min-h-8 shrink-0 items-center justify-between gap-3 pr-8">
- <Dialog.Title class="text-base font-medium text-ink sm:text-sm">
- {title()}
- </Dialog.Title>
- </div>
- <Dialog.Description class="mt-1 shrink-0 text-sm leading-relaxed text-ink-muted sm:text-xs">
- <Show
- when={props.kind !== 'unlink'}
- fallback="The document stays in your files. Access granted by this meeting link will be removed; other sharing stays the same."
- >
- <span class="flex min-w-0 items-center gap-2">
- <span class="min-w-0 truncate">{props.eventTitle}</span>
- <Show when={props.recurring}>
- <span class="shrink-0 text-xs text-ink-extra-muted">
- · This occurrence
- </span>
- </Show>
- </span>
- </Show>
- </Dialog.Description>
-
- <Show when={props.kind === 'link'}>
- <div class="mt-3 shrink-0">
- <InputGroup size="md">
- <InputGroup.Addon>
- <MagnifyingGlassIcon class="size-4 text-ink-muted" />
- </InputGroup.Addon>
- <InputGroup.Input
- aria-label="Find a markdown document"
- placeholder="Find a note…"
- value={props.query}
- onInput={(event) => props.onQuery(event.currentTarget.value)}
- disabled={props.saving}
- />
- </InputGroup>
- </div>
- <div
- class="mt-3 flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto overscroll-contain"
- role="region"
- aria-label="Your markdown documents"
- aria-busy={props.picker.pending}
- >
- <Show
- when={
- props.picker.pending && !props.picker.data?.documents.length
- }
- >
- <p role="status" class="px-3 py-5 text-sm text-ink-muted">
- Searching notes…
- </p>
- </Show>
- <Show when={props.picker.error}>
- <p role="alert" class="py-4 text-sm text-failure">
- {props.picker.error}
- </p>
- </Show>
- <For each={props.picker.data?.documents}>
- {(document) => {
- const linked = () =>
- props.linkedIds.includes(document.documentId);
- return (
- <Button
- variant="ghost"
- size="md"
- fullWidth
- aria-label={document.name}
- tooltip={document.name}
- aria-pressed={
- props.selected?.documentId === document.documentId
- }
- disabled={linked() || props.saving}
- onClick={() => props.onSelect(document)}
- >
- <FileTextIcon class="size-4 text-ink-extra-muted" />
- <span class="min-w-0 flex-1 truncate text-left">
- {document.name}
- </span>
- <Show when={linked()}>
- <span class="text-xs text-ink-extra-muted">Linked</span>
- </Show>
- <Show
- when={props.selected?.documentId === document.documentId}
- >
- <CheckIcon class="size-4" />
- </Show>
- </Button>
- );
- }}
- </For>
- <Show
- when={
- props.picker.data?.documents.length === 0 &&
- !props.picker.pending
- }
- >
- <p class="px-3 py-5 text-center text-sm text-ink-muted">
- {props.query
- ? 'No notes match this name.'
- : 'No markdown documents yet.'}
- <span class="mt-1 block text-xs text-ink-extra-muted">
- Only notes you own can be shared with a meeting.
- </span>
- </p>
- </Show>
- </div>
- </Show>
-
- <Show when={props.kind !== 'link' && props.selected}>
- {(document) => (
- <div class="mt-3 flex shrink-0 items-center gap-2 rounded-lg bg-ink/4 p-3 text-sm text-ink">
- <FileTextIcon class="size-4 text-accent" />
- <span class="min-w-0 flex-1 truncate">{document().name}</span>
- </div>
- )}
- </Show>
-
- <Show when={props.kind !== 'unlink'}>
- <div
- role="region"
- aria-label="Note sharing"
- class="mt-3 shrink-0 border-t border-edge-muted pt-3"
- >
- <p class="text-xs leading-relaxed text-ink-muted">
- Anyone who can see this meeting’s details can read this note.
- </p>
- <Show when={props.picker.data?.teams.length}>
- <div class="mt-3 flex flex-col gap-2">
- <For each={props.picker.data?.teams}>
- {(team) => (
- <Checkbox
- checked={props.teamId === team.id}
- onChange={(checked) =>
- props.onTeam(checked ? team.id : undefined)
- }
- disabled={props.saving}
- class="min-h-9 justify-between gap-3"
- >
- <Checkbox.Control />
- <Checkbox.Label class="flex-1 text-sm text-ink sm:text-xs">
- Also share with {team.name}
- <span class="mt-0.5 block text-xs font-normal text-ink-extra-muted">
- Your team can read this note
- </span>
- </Checkbox.Label>
- </Checkbox>
- )}
- </For>
- </div>
- </Show>
- <Show when={props.guestListHidden}>
- <p class="mt-2 text-xs leading-relaxed text-ink-extra-muted">
- This meeting hides its guest list. Some guests may need a direct
- document share.
- </p>
- </Show>
- </div>
- </Show>
-
- <Show when={props.error}>
- <p role="alert" class="mt-3 shrink-0 text-sm text-failure">
- {props.error}
- </p>
- </Show>
- <div class="mt-4 flex shrink-0 justify-end gap-2">
- <Button
- variant="ghost"
- size="md"
- onClick={props.onClose}
- disabled={props.saving}
- >
- Cancel
- </Button>
- <Button
- variant={props.kind === 'unlink' ? 'danger' : 'primary'}
- size="md"
- onClick={props.onSave}
- disabled={
- !props.selected ||
- props.saving ||
- (props.kind === 'link' &&
- (!props.linksReady ||
- props.linkedIds.includes(props.selected.documentId)))
- }
- >
- <Show when={props.kind === 'link'}>
- <LinkIcon class="size-4 shrink-0 touch:size-6" />
- </Show>
- {props.saving
- ? 'Saving…'
- : props.kind === 'unlink'
- ? 'Unlink note'
- : 'Link note'}
- </Button>
- </div>
- <Dialog.CloseButton
- as={Button}
- variant="ghost"
- size="icon-sm"
- aria-label="Close"
- tooltip="Close"
- disabled={props.saving}
- class="absolute right-4 top-4 sm:right-6 sm:top-6"
- >
- <XIcon class="size-3.5 shrink-0 touch:size-6" />
- </Dialog.CloseButton>
- </div>
- </Dialog>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/components/notes-section.tsx b/apps/web/src/features/calendar-notes/components/notes-section.tsx
deleted file mode 100644
index 55cc303091..0000000000
--- a/apps/web/src/features/calendar-notes/components/notes-section.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import CaretDownIcon from '@icon/system/regular/caret-down.svg';
-import FileTextIcon from '@icon/system/regular/file-text.svg';
-import SpinnerIcon from '@icon/system/regular/spinner.svg';
-import { Button, Dropdown } from '@ui';
-import { For, onCleanup, Show } from 'solid-js';
-import type { MeetingNote, NoteRead } from '../core/types';
-
-export function NotesSection(props: {
- state: NoteRead<MeetingNote[]>;
- creating: boolean;
- createdUnlinked: boolean;
- createError?: string;
- onCreate: () => void;
- onOpenSaved: () => void;
- dialogOpen: boolean;
- onMenuChange: (documentId: string, open: boolean) => void;
- onLink: () => void;
- onOpen: (note: MeetingNote) => void;
- onSharing: (note: MeetingNote) => void;
- onUnlink: (note: MeetingNote) => void;
- onRetry: () => void;
-}) {
- const createLabel = () =>
- props.creating
- ? props.createdUnlinked
- ? 'Linking…'
- : 'Creating…'
- : props.createdUnlinked
- ? 'Retry linking'
- : 'Create notes';
-
- return (
- <section
- aria-label="Meeting notes"
- class="grid grid-cols-[1.25rem_minmax(0,1fr)] gap-x-4 border-t border-edge-muted px-4 py-3 text-sm text-ink-muted sm:grid-cols-[1rem_minmax(0,1fr)] sm:gap-x-3 sm:text-xs"
- >
- <FileTextIcon class="mt-2 size-5 text-ink-extra-muted sm:mt-1.5 sm:size-4" />
- <div class="min-w-0">
- <div class="mb-1 flex min-h-7 items-center justify-between gap-2">
- <div class="flex min-w-0 items-center gap-2">
- <h3 class="whitespace-nowrap font-medium text-ink">
- Meeting notes
- </h3>
- <Show when={props.state.data?.length}>
- <span class="text-xs text-ink-extra-muted">
- {props.state.data?.length}
- </span>
- </Show>
- <Show when={props.state.pending && !props.state.data}>
- <span role="status" aria-label="Loading meeting notes">
- <SpinnerIcon class="size-3 animate-spin text-ink-extra-muted" />
- </span>
- </Show>
- </div>
- <div class="flex shrink-0 items-center gap-1">
- <Button
- variant="ghost"
- size="xs"
- aria-label={createLabel()}
- tooltip={createLabel()}
- disabled={props.creating}
- onClick={props.onCreate}
- >
- {props.creating || props.createdUnlinked
- ? createLabel()
- : 'Create'}
- </Button>
- <Button
- variant="ghost"
- size="xs"
- aria-label="Link existing"
- tooltip="Link existing"
- disabled={props.creating}
- onClick={props.onLink}
- >
- Link
- </Button>
- </div>
- </div>
- <Show when={props.state.error}>
- <div
- role="alert"
- class="flex items-center justify-between gap-2 py-2 text-xs text-ink-muted"
- >
- <span>{props.state.error}</span>
- <Button size="sm" variant="secondary" onClick={props.onRetry}>
- Retry
- </Button>
- </div>
- </Show>
- <div class="flex flex-col gap-2">
- <For each={props.state.data}>
- {(note) => {
- onCleanup(() => props.onMenuChange(note.documentId, false));
- return (
- <div class="min-w-0">
- <div class="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2">
- <Button
- variant="ghost"
- size="sm"
- class="min-w-0 justify-start"
- aria-label={`Open ${note.name}`}
- tooltip={`Open ${note.name}`}
- onClick={() => props.onOpen(note)}
- >
- <span class="min-w-0 flex-1 truncate text-left">
- {note.name}
- </span>
- </Button>
- <Show when={note.canManage}>
- <Dropdown
- modal={false}
- placement="bottom-end"
- onOpenChange={(open) =>
- props.onMenuChange(note.documentId, open)
- }
- >
- <Dropdown.Trigger
- variant="secondary"
- size="xs"
- aria-label={`Options for ${note.name}`}
- tooltip={`Options for ${note.name}`}
- disabled={props.creating}
- >
- Options
- <CaretDownIcon class="size-3 shrink-0 touch:size-6" />
- </Dropdown.Trigger>
- <Dropdown.Content
- portalScope="local"
- class="z-nested-action-menu min-w-44"
- onCloseAutoFocus={(event) => {
- if (props.dialogOpen) event.preventDefault();
- }}
- >
- <Dropdown.Group>
- <Dropdown.Item
- onSelect={() => props.onSharing(note)}
- >
- Share
- </Dropdown.Item>
- <Dropdown.Item
- onSelect={() => props.onUnlink(note)}
- >
- Unlink from meeting
- </Dropdown.Item>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- </Show>
- </div>
- <Show when={note.team}>
- {(team) => (
- <p class="px-2 text-xs text-ink-extra-muted sm:text-xxs">
- Also shared with {team().name}
- </p>
- )}
- </Show>
- </div>
- );
- }}
- </For>
- </div>
- <Show when={props.createError}>
- <div role="alert" class="my-2 text-xs text-ink-muted">
- <p>{props.createError}</p>
- <Show when={props.createdUnlinked}>
- <Button
- variant="ghost"
- size="sm"
- disabled={props.creating}
- onClick={props.onOpenSaved}
- >
- Open saved note
- </Button>
- </Show>
- </div>
- </Show>
- </div>
- </section>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/context/notes-source.ts b/apps/web/src/features/calendar-notes/context/notes-source.ts
deleted file mode 100644
index 31887100c9..0000000000
--- a/apps/web/src/features/calendar-notes/context/notes-source.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { Result } from 'neverthrow';
-import type { Accessor } from 'solid-js';
-import type {
- DocumentNoteLink,
- MeetingNote,
- NoteCreateFailure,
- NoteDocument,
- NoteFailure,
- NotePicker,
- NoteRead,
- NoteTarget,
- NoteTeam,
-} from '../core/types';
-
-/** Reactive reads and writes owned by the calendar-note feature. */
-export type NotesSource = {
- notes: Accessor<NoteRead<MeetingNote[]>>;
- create: (name: string) => Promise<Result<NoteDocument, NoteCreateFailure>>;
- picker: (
- query: Accessor<string>,
- enabled: Accessor<boolean>
- ) => Accessor<NoteRead<NotePicker>>;
- retry: () => Promise<unknown>;
- link: (
- documentId: string,
- teamId?: string
- ) => Promise<Result<void, NoteFailure>>;
- unlink: (documentId: string) => Promise<Result<void, NoteFailure>>;
-};
-
-/** Already cached, owned Markdown candidates from the app's Quick Access source. */
-export type NoteDocumentSearch = (
- query: Accessor<string>,
- enabled: Accessor<boolean>
-) => Accessor<NoteDocument[]>;
-
-export type DocumentNotesSource = {
- links: Accessor<NoteRead<DocumentNoteLink[]>>;
- team: Accessor<NoteRead<NoteTeam | null>>;
- retry: () => Promise<unknown>;
- setTeam: (
- target: NoteTarget,
- teamId?: string
- ) => Promise<Result<void, NoteFailure>>;
- unlink: (target: NoteTarget) => Promise<Result<void, NoteFailure>>;
-};
diff --git a/apps/web/src/features/calendar-notes/core/types.ts b/apps/web/src/features/calendar-notes/core/types.ts
deleted file mode 100644
index 654eea28a8..0000000000
--- a/apps/web/src/features/calendar-notes/core/types.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-export type NoteDocument = { documentId: string; name: string };
-export type NoteTeam = { id: string; name: string };
-export type MeetingNote = NoteDocument & {
- team?: NoteTeam;
- canManage: boolean;
-};
-export type NotePicker = { documents: NoteDocument[]; teams: NoteTeam[] };
-export type NoteTarget = { eventId: string; occurrenceKey: string };
-export type DocumentNoteLink = NoteTarget & {
- eventTitle: string;
- team?: NoteTeam;
-};
-export type MeetingAccessState = 'loading' | 'shared' | 'none' | 'error';
-export type NoteFailure =
- | { kind: 'link_failed'; message: string }
- | { kind: 'unlink_failed'; message: string };
-
-export type NoteCreateFailure =
- | { kind: 'create_failed'; message: string }
- | { kind: 'created_unlinked'; message: string; document: NoteDocument };
-
-export type NoteRead<T> = {
- data?: T;
- pending: boolean;
- error?: string;
-};
diff --git a/apps/web/src/features/calendar-notes/document-meeting-notes.test.tsx b/apps/web/src/features/calendar-notes/document-meeting-notes.test.tsx
deleted file mode 100644
index 1e1ca05282..0000000000
--- a/apps/web/src/features/calendar-notes/document-meeting-notes.test.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { queryClient } from '@queries/client';
-import { calendarNotesClient } from '@service-calendar/notes';
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { QueryClientProvider } from '@tanstack/solid-query';
-import { err, ok } from 'neverthrow';
-import { afterEach, expect, it, vi } from 'vitest';
-import { DocumentMeetingNotes } from './document-meeting-notes';
-import { notesKeys } from './queries/keys';
-
-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'owner' }));
-vi.mock('@queries/team/teams', () => ({
- useCurrentTeamQuery: () => ({ isPending: false, isError: false, data: null }),
-}));
-vi.mock('@core/util/create', () => ({ createMarkdownFile: vi.fn() }));
-vi.mock('@service-calendar/notes', () => ({
- calendarNotesClient: { documentLinks: vi.fn() },
-}));
-vi.mock('@queries/client', async () => {
- const { QueryClient } = await import('@tanstack/solid-query');
- return {
- queryClient: new QueryClient({
- defaultOptions: { queries: { retry: false } },
- }),
- };
-});
-afterEach(() => {
- cleanup();
- queryClient.clear();
- vi.resetAllMocks();
-});
-
-it('retains cached links after a failed refresh without reporting their grants as confirmed', async () => {
- vi.mocked(calendarNotesClient.documentLinks).mockResolvedValue(
- ok([
- {
- documentName: 'Notes',
- eventId: 'event',
- eventTitle: 'Planning',
- occurrenceKey: 'single',
- canViewMeeting: true,
- team: { id: 'team', name: 'Macro' },
- },
- ])
- );
- const onAccessState = vi.fn();
- render(() => (
- <QueryClientProvider client={queryClient}>
- <DocumentMeetingNotes documentId="note" onAccessState={onAccessState} />
- </QueryClientProvider>
- ));
- await vi.waitFor(() =>
- expect(onAccessState).toHaveBeenLastCalledWith('shared', ['team'])
- );
- const unlink = screen.getByRole('button', { name: 'Unlink' });
- vi.mocked(calendarNotesClient.documentLinks).mockResolvedValue(
- err([{ code: 'NETWORK_ERROR', message: 'Network unavailable' }])
- );
- await queryClient.refetchQueries({
- queryKey: notesKeys.documentLinks('owner', 'note').queryKey,
- });
- await vi.waitFor(() =>
- expect(onAccessState).toHaveBeenLastCalledWith('error', [])
- );
- expect(screen.getByRole('button', { name: 'Unlink' })).toBe(unlink);
-});
diff --git a/apps/web/src/features/calendar-notes/document-meeting-notes.tsx b/apps/web/src/features/calendar-notes/document-meeting-notes.tsx
deleted file mode 100644
index 18c44f8a10..0000000000
--- a/apps/web/src/features/calendar-notes/document-meeting-notes.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useUserId } from '@core/context/user';
-import { createEffect, Show, Suspense } from 'solid-js';
-import type { MeetingAccessState } from './core/types';
-import { createDocumentNotesSource } from './queries/notes-source';
-import { DocumentNotesView } from './views/document-notes';
-
-/** Owner-only meeting grants within the document share panel. */
-export function DocumentMeetingNotes(props: {
- documentId: string;
- onAccessState?: (state: MeetingAccessState, teamIds: string[]) => void;
-}) {
- const userId = useUserId();
- const source = createDocumentNotesSource(userId, () => props.documentId);
- createEffect(() => {
- const state = source.links();
- props.onAccessState?.(
- state.error
- ? 'error'
- : !state.data
- ? 'loading'
- : state.data.length
- ? 'shared'
- : 'none',
- state.error
- ? []
- : (state.data?.flatMap((link) => (link.team ? [link.team.id] : [])) ??
- [])
- );
- });
- return (
- <Suspense>
- <Show when={JSON.stringify([userId(), props.documentId])} keyed>
- {(_identity) => <DocumentNotesView source={source} />}
- </Show>
- </Suspense>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/meeting-reference.tsx b/apps/web/src/features/calendar-notes/meeting-reference.tsx
deleted file mode 100644
index 5c77793148..0000000000
--- a/apps/web/src/features/calendar-notes/meeting-reference.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { openCalendarEventSplit } from '@app/features/calendar-view/open-calendar-event';
-import { CalendarEventPreviewDetails } from '@core/component/DocumentPreview';
-import { ReferenceRow } from '@core/component/References';
-import { fireAndForget } from '@core/util/fireAndForget';
-import { parseLocalDate } from '@core/util/local-date';
-import { Telemetry } from '@macro-inc/observability';
-import CalendarIcon from '@phosphor/calendar-blank.svg';
-import { Button, Dialog } from '@ui';
-import { createSignal, onCleanup, Show } from 'solid-js';
-import type { DocumentReference } from './queries/notes-source';
-import { resolveReferencePreview } from './queries/reference-preview';
-
-/** A linked occurrence, resolved through the document-link access checks. */
-export function MeetingReference(props: {
- link: DocumentReference;
- documentId: string;
- onOpenCalendar?: () => void;
- onRetry?: () => void;
-}) {
- const occurrenceKey = () =>
- props.link.occurrenceKey === 'single'
- ? undefined
- : props.link.occurrenceKey;
- const resolved = () => resolveReferencePreview(props.link);
- const event = () => resolved()?.event;
- const unresolved = () => typeof props.link.canViewMeeting !== 'boolean';
- const [detailsOpen, setDetailsOpen] = createSignal(false);
- const title = () => event()?.title || props.link.eventTitle;
- const date = () => {
- const time = event()?.time;
- if (!time) return undefined;
- const start =
- time.kind === 'allDay'
- ? parseLocalDate(time.startDate)
- : new Date(time.startsAt);
- if (!start || !Number.isFinite(start.getTime())) return undefined;
- return start.toLocaleDateString(undefined, {
- month: 'short',
- day: 'numeric',
- year:
- start.getFullYear() === new Date().getFullYear()
- ? undefined
- : 'numeric',
- });
- };
- let active = true;
- onCleanup(() => {
- active = false;
- });
- function open() {
- fireAndForget(
- Telemetry.span('calendar.notes.reference.open', async (span) => {
- span.setAttr('event.id', props.link.eventId);
- span.setAttr('document.id', props.documentId);
- const current = event();
- if (!current?.viewerEventId) {
- span.setAttr(
- 'calendar.notes.reference.outcome',
- unresolved()
- ? 'unresolved'
- : current
- ? 'shared_preview'
- : 'unavailable'
- );
- setDetailsOpen(true);
- return;
- }
- setDetailsOpen(false);
- const opened = await openCalendarEventSplit({
- eventId: current.viewerEventId,
- occurrenceKey: current.occurrenceKey ?? occurrenceKey(),
- time: current.time,
- openInNewSplit: true,
- });
- span.setAttr(
- 'calendar.notes.reference.outcome',
- opened ? 'calendar' : 'preview'
- );
- if (!active) return;
- if (opened) props.onOpenCalendar?.();
- else setDetailsOpen(true);
- }),
- 'calendar.notes.reference'
- );
- }
-
- return (
- <>
- <ReferenceRow
- source={
- <span class="inline-flex min-w-0 max-w-full items-baseline gap-1 align-baseline">
- <CalendarIcon class="relative top-[0.125em] size-[1em] shrink-0" />
- <span class="min-w-0 truncate underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
- {title()}
- </span>
- </span>
- }
- timestampLabel={date()}
- onClick={open}
- ariaLabel={`Open meeting ${title()}`}
- />
- <Show when={detailsOpen()}>
- <Dialog
- open
- onOpenChange={setDetailsOpen}
- position="center"
- class="w-[400px]"
- >
- <Dialog.Title class="px-4 pt-4 text-sm font-medium">
- {title()}
- </Dialog.Title>
- <Dialog.Description class="sr-only">
- Details of the meeting linked to this note.
- </Dialog.Description>
- <Show
- when={event()}
- fallback={
- <p class="p-4 text-sm text-ink-muted">
- {unresolved()
- ? 'Meeting details are temporarily unavailable. Please try again.'
- : 'This meeting is no longer available to you.'}
- </p>
- }
- >
- {(current) => (
- <CalendarEventPreviewDetails
- event={current()}
- mentionedEventId={props.link.eventId}
- onJoin={() => setDetailsOpen(false)}
- sharedActions={resolved()?.sharedActions}
- />
- )}
- </Show>
- <div class="flex justify-end gap-2 p-3">
- <Show when={unresolved() && props.onRetry}>
- <Button variant="ghost" onClick={props.onRetry}>
- Retry
- </Button>
- </Show>
- <Button variant="ghost" onClick={() => setDetailsOpen(false)}>
- Close
- </Button>
- </div>
- </Dialog>
- </Show>
- </>
- );
-}
diff --git a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts
deleted file mode 100644
index 38100e6b20..0000000000
--- a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import { err, ok, type Result } from 'neverthrow';
-import { createRoot } from 'solid-js';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { NoteCreateFailure, NoteDocument } from '../core/types';
-import { createFakeNotesSource } from '../tests/fake-source';
-import { createMeetingNoteAction } from './create-meeting-note';
-
-let dispose = () => {};
-afterEach(() => dispose());
-
-function fixture(fail = false) {
- return createRoot((cleanup) => {
- dispose = cleanup;
- const fake = createFakeNotesSource({ fail });
- const create = vi.spyOn(fake.source, 'create');
- const link = vi.spyOn(fake.source, 'link');
- const onOpen = vi.fn();
- const action = createMeetingNoteAction({
- source: fake.source,
- title: () => 'Weekly product sync',
- onOpen,
- });
- return { ...fake, create, link, onOpen, action };
- });
-}
-
-describe('creating meeting notes', () => {
- it('waits for linking before opening and suppresses duplicate clicks', async () => {
- const { action, create, onOpen } = fixture();
- let finish = (_result: Result<NoteDocument, NoteCreateFailure>) => {};
- create.mockReturnValueOnce(
- new Promise((resolve) => {
- finish = resolve;
- })
- );
- const creating = action.run();
- await action.run();
- expect(create).toHaveBeenCalledExactlyOnceWith('Weekly product sync notes');
- expect(action.pending()).toBe(true);
- expect(onOpen).not.toHaveBeenCalled();
- const document = { documentId: 'saved', name: 'Weekly product sync notes' };
- finish(ok(document));
- await creating;
- expect(onOpen).toHaveBeenCalledExactlyOnceWith(document);
- expect(action.pending()).toBe(false);
- });
-
- it('retries linking the saved document without creating another one', async () => {
- const { action, create, link, notes, onOpen } = fixture(true);
- await action.run();
- expect(action.saved()?.documentId).toBe('created-1');
- expect(action.error()).toBeDefined();
- expect(action.pending()).toBe(false);
- expect(notes()).toEqual([]);
- expect(onOpen).not.toHaveBeenCalled();
- await action.run();
- expect(create).toHaveBeenCalledOnce();
- expect(link).toHaveBeenNthCalledWith(1, 'created-1');
- expect(link).toHaveBeenNthCalledWith(2, 'created-1');
- expect(notes()).toEqual([
- {
- documentId: 'created-1',
- name: 'Weekly product sync notes',
- canManage: true,
- },
- ]);
- expect(action.saved()).toBeUndefined();
- expect(action.error()).toBeUndefined();
- expect(onOpen).toHaveBeenCalledExactlyOnceWith({
- documentId: 'created-1',
- name: 'Weekly product sync notes',
- });
- });
-
- it('can open the saved note after linking fails', async () => {
- const { action, create, onOpen } = fixture(true);
- await action.run();
- action.openSaved();
- expect(create).toHaveBeenCalledOnce();
- expect(onOpen).toHaveBeenCalledExactlyOnceWith({
- documentId: 'created-1',
- name: 'Weekly product sync notes',
- });
- });
-
- it('allows retry after document creation fails without navigating', async () => {
- const { action, create, link, onOpen } = fixture();
- create.mockResolvedValueOnce(
- err({ kind: 'create_failed', message: 'Offline' })
- );
- await action.run();
- expect(action.pending()).toBe(false);
- expect(action.saved()).toBeUndefined();
- expect(link).not.toHaveBeenCalled();
- expect(onOpen).not.toHaveBeenCalled();
- await action.run();
- expect(create).toHaveBeenCalledTimes(2);
- expect(onOpen).toHaveBeenCalledOnce();
- });
-
- it('does not navigate after the meeting or account changes', async () => {
- const { action, create, onOpen } = fixture();
- let finish = (_result: Result<NoteDocument, NoteCreateFailure>) => {};
- create.mockReturnValueOnce(
- new Promise((resolve) => {
- finish = resolve;
- })
- );
- const creating = action.run();
- dispose();
- finish(ok({ documentId: 'saved', name: 'Weekly product sync notes' }));
- await creating;
- expect(onOpen).not.toHaveBeenCalled();
- await action.run();
- expect(create).toHaveBeenCalledOnce();
- });
-});
diff --git a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts b/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts
deleted file mode 100644
index e346486e0b..0000000000
--- a/apps/web/src/features/calendar-notes/primitives/create-meeting-note.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { type Accessor, createSignal, onCleanup } from 'solid-js';
-import type { NotesSource } from '../context/notes-source';
-import type { NoteCreateFailure, NoteDocument } from '../core/types';
-
-/** Create once, retain a saved note if linking fails, and navigate after linking. */
-export function createMeetingNoteAction(options: {
- source: NotesSource;
- title: Accessor<string>;
- onOpen: (document: NoteDocument) => void;
-}) {
- const [pending, setPending] = createSignal(false);
- const [saved, setSaved] = createSignal<NoteDocument>();
- const [error, setError] = createSignal<string>();
- let disposed = false;
- onCleanup(() => {
- disposed = true;
- });
-
- async function run() {
- if (pending() || disposed) return;
- setPending(true);
- setError(undefined);
- const document = saved();
- const result = document
- ? (await options.source.link(document.documentId))
- .map(() => document)
- .mapErr(
- (failure): NoteCreateFailure => ({
- kind: 'created_unlinked',
- document,
- message: failure.message,
- })
- )
- : await options.source.create(`${options.title()} notes`);
- if (disposed) return;
- setPending(false);
- if (result.isErr()) {
- setError(result.error.message);
- if (result.error.kind === 'created_unlinked')
- setSaved(result.error.document);
- return;
- }
- setSaved(undefined);
- options.onOpen(result.value);
- }
-
- return {
- pending,
- saved,
- error,
- run,
- openSaved: () => {
- const document = saved();
- if (document && !pending() && !disposed) options.onOpen(document);
- },
- };
-}
diff --git a/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts b/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts
deleted file mode 100644
index 1ffaa141b2..0000000000
--- a/apps/web/src/features/calendar-notes/primitives/document-notes-controller.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { createSignal, onCleanup } from 'solid-js';
-import type { DocumentNotesSource } from '../context/notes-source';
-import type { DocumentNoteLink } from '../core/types';
-
-export function createDocumentNotesController(source: DocumentNotesSource) {
- const [selected, setSelected] = createSignal<DocumentNoteLink>();
- const [saving, setSaving] = createSignal(false);
- const [removing, setRemoving] = createSignal(false);
- const [error, setError] = createSignal<string>();
- let disposed = false;
- onCleanup(() => {
- disposed = true;
- });
- function select(link: DocumentNoteLink | undefined) {
- if (removing()) return;
- setSelected(link);
- setError(undefined);
- }
- async function remove() {
- const link = selected();
- if (!link || saving()) return;
- setSaving(true);
- setRemoving(true);
- const result = await source.unlink(link);
- if (disposed) return;
- setSaving(false);
- setRemoving(false);
- if (result.isErr()) setError(result.error.message);
- else select(undefined);
- }
- async function setTeam(link: DocumentNoteLink, teamId?: string) {
- if (saving()) return;
- setSaving(true);
- setError(undefined);
- const result = await source.setTeam(link, teamId);
- if (disposed) return;
- setSaving(false);
- if (result.isErr()) setError(result.error.message);
- }
- return { selected, saving, removing, error, select, remove, setTeam };
-}
diff --git a/apps/web/src/features/calendar-notes/primitives/notes-controller.test.ts b/apps/web/src/features/calendar-notes/primitives/notes-controller.test.ts
deleted file mode 100644
index 672961e268..0000000000
--- a/apps/web/src/features/calendar-notes/primitives/notes-controller.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { ok } from 'neverthrow';
-import { createRoot, createSignal } from 'solid-js';
-import { expect, it, vi } from 'vitest';
-import type { NotesSource } from '../context/notes-source';
-import type { MeetingNote } from '../core/types';
-import { createNotesController } from './notes-controller';
-
-it('does not overwrite an existing team grant when its link arrives after selection', async () => {
- const document = { documentId: 'note', name: 'Notes' };
- const [notes, setNotes] = createSignal<MeetingNote[]>();
- const source: NotesSource = {
- notes: () => ({ pending: !notes(), data: notes() }),
- picker: () => () => ({
- pending: false,
- data: { documents: [document], teams: [] },
- }),
- create: async () => ok(document),
- retry: async () => {},
- link: vi.fn(async () => ok(undefined)),
- unlink: async () => ok(undefined),
- };
- const { controller, dispose } = createRoot((dispose) => ({
- controller: createNotesController(source, () => {}),
- dispose,
- }));
- try {
- controller.openLink();
- controller.setSelected(document);
- await controller.save();
- expect(source.link).not.toHaveBeenCalled();
- setNotes([
- { ...document, canManage: true, team: { id: 'team', name: 'Macro' } },
- ]);
- await controller.save();
- expect(source.link).not.toHaveBeenCalled();
- expect(controller.dialog()?.kind).toBe('link');
- controller.setSelected({ documentId: 'new-note', name: 'Another note' });
- await controller.save();
- expect(source.link).toHaveBeenCalledExactlyOnceWith('new-note', undefined);
- expect(controller.dialog()).toBeUndefined();
- } finally {
- dispose();
- }
-});
diff --git a/apps/web/src/features/calendar-notes/primitives/notes-controller.ts b/apps/web/src/features/calendar-notes/primitives/notes-controller.ts
deleted file mode 100644
index b9d4b37c5e..0000000000
--- a/apps/web/src/features/calendar-notes/primitives/notes-controller.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { createSignal, onCleanup } from 'solid-js';
-import type { NotesSource } from '../context/notes-source';
-import type { MeetingNote, NoteDocument } from '../core/types';
-
-type NoteDialog =
- | { kind: 'link' }
- | { kind: 'sharing' | 'unlink'; note: MeetingNote };
-
-export function createNotesController(
- source: NotesSource,
- onDialogChange: (open: boolean) => void
-) {
- const [dialog, setDialog] = createSignal<NoteDialog>();
- const [query, setQuery] = createSignal('');
- const [selected, setSelected] = createSignal<NoteDocument>();
- const [teamId, setTeamId] = createSignal<string>();
- const [saving, setSaving] = createSignal(false);
- const [error, setError] = createSignal<string>();
- let menuDocumentId: string | undefined;
- let disposed = false;
- onCleanup(() => {
- disposed = true;
- onDialogChange(false);
- });
- const picker = source.picker(query, () => dialog()?.kind === 'link');
-
- function reportOpen() {
- if (disposed) return;
- onDialogChange(!!menuDocumentId || !!dialog());
- }
-
- function open(next: NoteDialog) {
- if (saving()) return;
- setQuery('');
- setError(undefined);
- setSelected(next.kind === 'link' ? undefined : next.note);
- setTeamId(next.kind === 'link' ? undefined : next.note.team?.id);
- setDialog(next);
- reportOpen();
- }
-
- function close() {
- if (saving()) return;
- setDialog(undefined);
- reportOpen();
- }
-
- async function save() {
- const active = dialog();
- const document = selected();
- if (!active || active.kind === 'sharing' || !document || saving()) return;
- if (active.kind === 'link') {
- const linkedNotes = source.notes().data;
- // PUT also changes an existing link's team grant. An early or stale
- // selection must never turn "link" into an unintended sharing update.
- if (!linkedNotes) return;
- if (linkedNotes.some((note) => note.documentId === document.documentId)) {
- setError('This note is already linked to the meeting.');
- return;
- }
- }
- setSaving(true);
- setError(undefined);
- const result =
- active.kind === 'unlink'
- ? await source.unlink(document.documentId)
- : await source.link(document.documentId, teamId());
- if (disposed || dialog() !== active) return;
- setSaving(false);
- if (result.isErr()) {
- setError(result.error.message);
- return;
- }
- close();
- }
-
- return {
- dialog,
- query,
- setQuery,
- selected,
- setSelected,
- teamId,
- setTeamId,
- saving,
- error,
- picker,
- setMenuOpen: (documentId: string, open: boolean) => {
- if (open) menuDocumentId = documentId;
- else if (menuDocumentId === documentId) menuDocumentId = undefined;
- reportOpen();
- },
- close,
- save,
- openLink: () => open({ kind: 'link' }),
- openSharing: (note: MeetingNote) => open({ kind: 'sharing', note }),
- openUnlink: (note: MeetingNote) => open({ kind: 'unlink', note }),
- };
-}
-
-export type NotesController = ReturnType<typeof createNotesController>;
diff --git a/apps/web/src/features/calendar-notes/queries/keys.ts b/apps/web/src/features/calendar-notes/queries/keys.ts
deleted file mode 100644
index f38d7b9157..0000000000
--- a/apps/web/src/features/calendar-notes/queries/keys.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { createQueryKeys } from '@lukemorales/query-key-factory';
-import type { NoteTarget } from '../core/types';
-
-export const notesKeys = createQueryKeys('calendar-notes', {
- notes: (userId: string | undefined, target: NoteTarget) => [userId, target],
- documents: (userId: string | undefined, query: string) => [userId, query],
- documentLinks: (userId: string | undefined, documentId: string) => [
- userId,
- documentId,
- ],
-});
diff --git a/apps/web/src/features/calendar-notes/queries/local-note-search.ts b/apps/web/src/features/calendar-notes/queries/local-note-search.ts
deleted file mode 100644
index e770d250a9..0000000000
--- a/apps/web/src/features/calendar-notes/queries/local-note-search.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import type { QuickAccessContextValue } from '@core/context/quickAccess/types';
-import { type Accessor, createMemo } from 'solid-js';
-import type { NoteDocumentSearch } from '../context/notes-source';
-
-export function createLocalNoteSearch(
- quickAccess: QuickAccessContextValue,
- userId: Accessor<string | undefined>
-): NoteDocumentSearch {
- return (query, enabled) => {
- const list = quickAccess.useList({
- buckets: ['note', 'task', 'snippet', 'skill'],
- searchTerm: query,
- enabled,
- });
- return createMemo(() => {
- const owner = userId();
- if (!owner || !enabled()) return [];
- return list
- .items()
- .flatMap(({ data }) =>
- data.ownerId === owner
- ? [{ documentId: data.id, name: data.name }]
- : []
- );
- });
- };
-}
diff --git a/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx b/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx
deleted file mode 100644
index 9b02d7a2e4..0000000000
--- a/apps/web/src/features/calendar-notes/queries/notes-source.test.tsx
+++ /dev/null
@@ -1,212 +0,0 @@
-import { createMarkdownFile } from '@core/util/create';
-import { queryClient } from '@queries/client';
-import { calendarNotesClient } from '@service-calendar/notes';
-import { QueryClientProvider } from '@tanstack/solid-query';
-import { err, ok } from 'neverthrow';
-import {
- type Accessor,
- createComponent,
- createRoot,
- createSignal,
-} from 'solid-js';
-import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import type { NoteDocumentSearch, NotesSource } from '../context/notes-source';
-import type { NotePicker, NoteRead } from '../core/types';
-import { notesKeys } from './keys';
-import { createNotesSource } from './notes-source';
-
-vi.mock('@core/util/create', () => ({ createMarkdownFile: vi.fn() }));
-vi.mock('@service-calendar/notes', () => ({
- calendarNotesClient: { list: vi.fn(), link: vi.fn(), documents: vi.fn() },
-}));
-vi.mock('@queries/client', async () => {
- const { QueryClient } = await import('@tanstack/solid-query');
- return {
- queryClient: new QueryClient({
- defaultOptions: { queries: { retry: false } },
- }),
- };
-});
-
-let dispose = () => {};
-beforeEach(() => {
- vi.mocked(calendarNotesClient.list).mockResolvedValue(ok([]));
- vi.mocked(calendarNotesClient.link).mockResolvedValue(ok({}));
- vi.mocked(calendarNotesClient.documents).mockResolvedValue(
- ok({ documents: [], teams: [] })
- );
-});
-afterEach(() => {
- dispose();
- queryClient.clear();
- vi.resetAllMocks();
- vi.useRealTimers();
-});
-
-function mountSource(localSearch: NoteDocumentSearch = () => () => []) {
- const [user, setUser] = createSignal<string | undefined>('owner');
- const [target, setTarget] = createSignal({
- eventId: 'event-a',
- occurrenceKey: '2026-10-23T14:00:00Z',
- });
- let source: NotesSource | undefined;
- const [query, setQuery] = createSignal('');
- const [enabled, setEnabled] = createSignal(false);
- let picker: Accessor<NoteRead<NotePicker>> | undefined;
- function Probe() {
- source = createNotesSource(user, target, localSearch);
- picker = source.picker(query, enabled);
- return null;
- }
- createRoot((cleanup) => {
- dispose = cleanup;
- createComponent(QueryClientProvider, {
- client: queryClient,
- get children() {
- return createComponent(Probe, {});
- },
- });
- });
- if (!source || !picker) throw new Error('Notes source did not mount');
- return { source, setUser, setTarget, picker, setQuery, setEnabled };
-}
-
-it('reopens a recently viewed meeting from cache without another request', async () => {
- const notes = [
- { documentId: 'note-a', name: 'Notes', team: null, canManage: true },
- ];
- vi.mocked(calendarNotesClient.list).mockResolvedValue(ok(notes));
- const first = mountSource();
- await vi.waitFor(() => expect(first.source.notes().data).toHaveLength(1));
- dispose();
- const reopened = mountSource();
- expect(reopened.source.notes().data?.[0].documentId).toBe('note-a');
- expect(reopened.source.notes().pending).toBe(false);
- expect(calendarNotesClient.list).toHaveBeenCalledOnce();
- reopened.setTarget({ eventId: 'different-event', occurrenceKey: 'single' });
- expect(reopened.source.notes().data).toBeUndefined();
-});
-
-it('keeps matching candidates while a new search is pending and reuses earlier queries', async () => {
- vi.useFakeTimers();
- const initial = {
- documents: [
- { documentId: 'alpha', name: 'Alpha sync' },
- { documentId: 'beta', name: 'Beta sync' },
- ],
- teams: [{ id: 'team', name: 'Macro' }],
- };
- queryClient.setQueryData(notesKeys.documents('owner', '').queryKey, initial);
- const response =
- Promise.withResolvers<
- Awaited<ReturnType<typeof calendarNotesClient.documents>>
- >();
- vi.mocked(calendarNotesClient.documents).mockReturnValue(response.promise);
- const mounted = mountSource();
- mounted.setEnabled(true);
- mounted.setQuery('alp');
- expect(mounted.picker().data?.documents).toEqual([initial.documents[0]]);
- await vi.advanceTimersByTimeAsync(180);
- expect(mounted.picker().data?.documents).toEqual([initial.documents[0]]);
- expect(mounted.picker().data?.teams).toEqual(initial.teams);
- expect(mounted.picker().pending).toBe(true);
- response.resolve(
- ok({ documents: [initial.documents[0]], teams: initial.teams })
- );
- await vi.advanceTimersByTimeAsync(0);
- mounted.setQuery('');
- await vi.advanceTimersByTimeAsync(180);
- expect(mounted.picker().data?.documents).toEqual(initial.documents);
- expect(calendarNotesClient.documents).toHaveBeenCalledOnce();
-});
-
-it('shows local candidates before the server responds and deduplicates remote matches', async () => {
- const local = { documentId: 'cached', name: 'Cached note' };
- const response =
- Promise.withResolvers<
- Awaited<ReturnType<typeof calendarNotesClient.documents>>
- >();
- vi.mocked(calendarNotesClient.documents).mockReturnValue(response.promise);
- const mounted = mountSource(() => () => [local]);
- mounted.setEnabled(true);
- expect(mounted.picker().data?.documents).toEqual([local]);
- response.resolve(
- ok({
- documents: [local, { documentId: 'server', name: 'Server note' }],
- teams: [],
- })
- );
- await vi.waitFor(() =>
- expect(mounted.picker().data?.documents).toHaveLength(2)
- );
-});
-
-it('does not keep another account’s notes or teams as placeholder results', () => {
- queryClient.setQueryData(notesKeys.documents('owner', '').queryKey, {
- documents: [{ documentId: 'private', name: 'Private note' }],
- teams: [{ id: 'private-team', name: 'Previous team' }],
- });
- const mounted = mountSource();
- mounted.setEnabled(true);
- expect(mounted.picker().data?.documents).toHaveLength(1);
- mounted.setUser('another-owner');
- expect(mounted.picker().data?.documents).toEqual([]);
- expect(mounted.picker().data?.teams).toEqual([]);
-});
-
-it('links to the original occurrence when selection changes during creation', async () => {
- let finish = (_id: string) => {};
- vi.mocked(createMarkdownFile).mockReturnValueOnce(
- new Promise((resolve) => {
- finish = resolve;
- })
- );
- const { source, setTarget } = mountSource();
- const creating = source.create('Weekly sync notes');
- expect(createMarkdownFile).toHaveBeenCalledOnce();
- setTarget({ eventId: 'event-b', occurrenceKey: '2026-10-30T14:00:00Z' });
- finish('created-document');
- expect((await creating).isOk()).toBe(true);
- expect(calendarNotesClient.link).toHaveBeenCalledExactlyOnceWith(
- 'event-a',
- '2026-10-23T14:00:00Z',
- 'created-document',
- { teamId: null }
- );
-});
-
-it('does not link a newly created document under a different account', async () => {
- let finish = (_id: string) => {};
- vi.mocked(createMarkdownFile).mockReturnValueOnce(
- new Promise((resolve) => {
- finish = resolve;
- })
- );
- const { source, setUser } = mountSource();
- const creating = source.create('Weekly sync notes');
- setUser('another-owner');
- finish('created-document');
- const result = await creating;
- expect(result.isErr()).toBe(true);
- if (result.isErr())
- expect(result.error).toMatchObject({
- kind: 'created_unlinked',
- document: { documentId: 'created-document' },
- });
- expect(calendarNotesClient.link).not.toHaveBeenCalled();
-});
-
-it('preserves the created document when the server rejects linking', async () => {
- vi.mocked(createMarkdownFile).mockResolvedValueOnce('created-document');
- vi.mocked(calendarNotesClient.link).mockResolvedValueOnce(
- err([{ code: 'FORBIDDEN', message: 'Meeting access changed' }])
- );
- const { source } = mountSource();
- const result = await source.create('Weekly sync notes');
- expect(result.isErr()).toBe(true);
- if (result.isErr())
- expect(result.error).toMatchObject({
- kind: 'created_unlinked',
- document: { documentId: 'created-document', name: 'Weekly sync notes' },
- });
-});
diff --git a/apps/web/src/features/calendar-notes/queries/notes-source.ts b/apps/web/src/features/calendar-notes/queries/notes-source.ts
deleted file mode 100644
index 52eca807b6..0000000000
--- a/apps/web/src/features/calendar-notes/queries/notes-source.ts
+++ /dev/null
@@ -1,341 +0,0 @@
-import { catchToResult, throwOnErr } from '@core/util/result';
-import { matchesTokenSubsequences } from '@core/util/string';
-import { Telemetry } from '@macro-inc/observability';
-import { queryClient } from '@queries/client';
-import { queryReadyGate } from '@queries/gate';
-import { useCurrentTeamQuery } from '@queries/team/teams';
-import type { DocumentNoteLink as CalendarDocumentLink } from '@service-calendar/generated/schemas/documentNoteLink';
-import { calendarNotesClient } from '@service-calendar/notes';
-import { createDebouncedMemo } from '@solid-primitives/memo';
-import { useMutation, useQuery } from '@tanstack/solid-query';
-import { err, ok } from 'neverthrow';
-import { type Accessor, createMemo } from 'solid-js';
-import type {
- DocumentNotesSource,
- NoteDocumentSearch,
- NotesSource,
-} from '../context/notes-source';
-import type {
- DocumentNoteLink,
- MeetingNote,
- NoteCreateFailure,
- NoteFailure,
- NotePicker,
- NoteTarget,
-} from '../core/types';
-import { notesKeys } from './keys';
-
-function notesOptions(userId: string | undefined, target: NoteTarget) {
- return {
- queryKey: notesKeys.notes(userId, target).queryKey,
- queryFn: async ({
- signal,
- }: {
- signal: AbortSignal;
- }): Promise<MeetingNote[]> => {
- const notes = await throwOnErr(() =>
- calendarNotesClient.list(target.eventId, target.occurrenceKey, signal)
- );
- return notes.map((note) => ({ ...note, team: note.team ?? undefined }));
- },
- enabled: !!userId,
- staleTime: 30_000,
- gcTime: 5 * 60_000,
- refetchInterval: 30_000,
- refetchOnWindowFocus: true,
- };
-}
-
-function pickerOptions(
- userId: string | undefined,
- query: string,
- enabled: boolean,
- eventId: string,
- localCount: number
-) {
- return {
- queryKey: notesKeys.documents(userId, query).queryKey,
- queryFn: ({ signal }: { signal: AbortSignal }) =>
- Telemetry.span('calendar.notes.search', async (span) => {
- span.setAttr('event.id', eventId);
- span.setAttr('search.query_length', query.length);
- span.setAttr('search.debounce_ms', 180);
- span.setAttr('search.local_result_count', localCount);
- const result = await span.span(
- 'calendar.notes.search.server',
- async (server) => {
- const result = await calendarNotesClient.documents(query, signal);
- if (result.isOk()) {
- server.setAttr(
- 'search.result_count',
- result.value.documents.length
- );
- } else if (!signal.aborted) {
- server.error('Meeting note search failed');
- }
- return result;
- }
- );
- span.setAttr(
- 'search.outcome',
- signal.aborted ? 'cancelled' : result.isOk() ? 'success' : 'error'
- );
- if (result.isErr() && !signal.aborted)
- span.error('Meeting note search failed');
- return throwOnErr(async () => result);
- }),
- enabled: !!userId && enabled,
- staleTime: 60_000,
- gcTime: 5 * 60_000,
- // Keep matching results while typing, but never carry them across accounts.
- placeholderData: (
- previous: NotePicker | undefined,
- previousQuery: { queryKey: readonly unknown[] } | undefined
- ) => (previousQuery?.queryKey[2] === userId ? previous : undefined),
- };
-}
-
-type NoteWrite = NoteTarget & { documentId: string; teamId?: string };
-
-function linkNote(input: NoteWrite) {
- return Telemetry.span('calendar.notes.link', async (span) => {
- span.setAttr('event.id', input.eventId);
- span.setAttr('document.id', input.documentId);
- await throwOnErr(() =>
- calendarNotesClient.link(
- input.eventId,
- input.occurrenceKey,
- input.documentId,
- { teamId: input.teamId ?? null }
- )
- );
- });
-}
-
-function unlinkNote(input: NoteWrite) {
- return Telemetry.span('calendar.notes.unlink', async (span) => {
- span.setAttr('event.id', input.eventId);
- span.setAttr('document.id', input.documentId);
- await throwOnErr(() =>
- calendarNotesClient.unlink(
- input.eventId,
- input.occurrenceKey,
- input.documentId
- )
- );
- });
-}
-
-function refreshNotes() {
- // The same meeting can be open through several inbox copies with distinct IDs.
- return Promise.all([
- queryClient.invalidateQueries({ queryKey: notesKeys.notes._def }),
- queryClient.invalidateQueries({ queryKey: notesKeys.documentLinks._def }),
- ]);
-}
-
-export function createNotesSource(
- userId: Accessor<string | undefined>,
- target: Accessor<NoteTarget>,
- localSearch: NoteDocumentSearch
-): NotesSource {
- const notes = useQuery(() => notesOptions(userId(), target()));
- const link = useMutation(() => ({
- mutationFn: linkNote,
- onSuccess: refreshNotes,
- }));
- const unlink = useMutation(() => ({
- mutationFn: unlinkNote,
- onSuccess: refreshNotes,
- }));
- return {
- notes: () => ({
- data: queryReadyGate(notes) ? notes.data : undefined,
- pending: notes.isPending,
- error: notes.isError ? 'Couldn’t load meeting notes.' : undefined,
- }),
- async create(name) {
- // Capture the occurrence and account before document creation yields.
- const destination = { ...target() };
- const owner = userId();
- return Telemetry.span('calendar.notes.create', async (span) => {
- span.setAttr('event.id', destination.eventId);
- const created = await catchToResult(() =>
- createMarkdownFile({
- title: name,
- source: 'calendar_notes',
- })
- );
- if (created.isErr() || !created.value) {
- span.setAttr('calendar.notes.outcome', 'create_failed');
- span.error('Meeting note creation failed');
- return err({
- kind: 'create_failed',
- message: 'Couldn’t create the note. Please try again.',
- } satisfies NoteCreateFailure);
- }
- const document = { documentId: created.value, name };
- span.setAttr('document.id', document.documentId);
- if (userId() !== owner) {
- span.setAttr('calendar.notes.outcome', 'account_changed');
- span.error('Account changed before meeting note linking');
- return err({
- kind: 'created_unlinked',
- document,
- message:
- 'Your note was saved, but your account changed before it could be linked.',
- } satisfies NoteCreateFailure);
- }
- const linked = await catchToResult(() =>
- link.mutateAsync({ ...destination, documentId: document.documentId })
- );
- if (linked.isErr()) {
- span.setAttr('calendar.notes.outcome', 'created_unlinked');
- span.error('Created meeting note could not be linked');
- return err({
- kind: 'created_unlinked',
- document,
- message:
- 'Your note was saved, but couldn’t be linked to this meeting. Retry linking or open the saved note.',
- } satisfies NoteCreateFailure);
- }
- span.setAttr('calendar.notes.outcome', 'linked');
- return ok(document);
- });
- },
- picker(query, enabled) {
- const normalized = () => query().trim();
- const debounced = createDebouncedMemo(normalized, 180);
- const local = localSearch(normalized, enabled);
- const picker = useQuery(() =>
- pickerOptions(
- userId(),
- debounced(),
- enabled(),
- target().eventId,
- local().length
- )
- );
- const data = createMemo(() => {
- const remote = queryReadyGate(picker) ? picker.data : undefined;
- const documents = new Map(
- local().map((document) => [document.documentId, document])
- );
- for (const document of remote?.documents ?? []) {
- if (matchesTokenSubsequences(document.name, normalized())) {
- documents.set(document.documentId, document);
- }
- }
- return {
- documents: [...documents.values()],
- teams: remote?.teams ?? [],
- };
- });
- return () => ({
- data: data(),
- pending: picker.isFetching || normalized() !== debounced(),
- error: picker.isError
- ? 'Couldn’t load your notes. Try again.'
- : undefined,
- });
- },
- retry: () => notes.refetch(),
- async link(documentId, teamId) {
- const input = { ...target(), documentId, teamId };
- return (await catchToResult(() => link.mutateAsync(input))).mapErr(
- (): NoteFailure => ({
- kind: 'link_failed',
- message:
- 'Couldn’t save this link. Check that you still own the note and can view the meeting, then try again.',
- })
- );
- },
- async unlink(documentId) {
- const input = { ...target(), documentId };
- return (await catchToResult(() => unlink.mutateAsync(input))).mapErr(
- (): NoteFailure => ({
- kind: 'unlink_failed',
- message:
- 'Couldn’t unlink this note. Your document is safe. Please try again.',
- })
- );
- },
- };
-}
-
-/** Reference previews are adapted at the calendar API boundary. */
-export type DocumentReference = DocumentNoteLink &
- Partial<Pick<CalendarDocumentLink, 'teamEvent' | 'event' | 'canViewMeeting'>>;
-
-export function documentLinksOptions(
- userId: string | undefined,
- documentId: string
-) {
- return {
- queryKey: notesKeys.documentLinks(userId, documentId).queryKey,
- queryFn: async ({ signal }: { signal: AbortSignal }) => {
- const links = await throwOnErr(() =>
- calendarNotesClient.documentLinks(documentId, signal)
- );
- return links.map((link) => ({ ...link, team: link.team ?? undefined }));
- },
- enabled: !!userId,
- staleTime: 30_000,
- gcTime: 5 * 60_000,
- refetchInterval: 30_000,
- refetchOnWindowFocus: true,
- };
-}
-
-export function createDocumentNotesSource(
- userId: Accessor<string | undefined>,
- documentId: Accessor<string>
-): DocumentNotesSource {
- const links = useQuery(() => documentLinksOptions(userId(), documentId()));
- const team = useCurrentTeamQuery();
- const link = useMutation(() => ({
- mutationFn: linkNote,
- onSuccess: refreshNotes,
- }));
- const unlink = useMutation(() => ({
- mutationFn: unlinkNote,
- onSuccess: refreshNotes,
- }));
- return {
- links: () => ({
- data: queryReadyGate(links) ? links.data : undefined,
- pending: links.isPending,
- error: links.isError ? 'Couldn’t load meeting access.' : undefined,
- }),
- team: () => ({
- data: queryReadyGate(team) ? (team.data?.team ?? null) : undefined,
- pending: team.isPending,
- error: team.isError ? 'Couldn’t load your team.' : undefined,
- }),
- retry: () => Promise.all([links.refetch(), team.refetch()]),
- async setTeam(target, teamId) {
- const input = { ...target, documentId: documentId(), teamId };
- return (await catchToResult(() => link.mutateAsync(input))).mapErr(
- (): NoteFailure => ({
- kind: 'link_failed',
- message:
- 'Couldn’t update team access. Check that you can still view the meeting, then try again.',
- })
- );
- },
- async unlink(target) {
- return (
- await catchToResult(() =>
- unlink.mutateAsync({ ...target, documentId: documentId() })
- )
- ).mapErr(
- (): NoteFailure => ({
- kind: 'unlink_failed',
- message: 'Couldn’t remove this meeting link. Please try again.',
- })
- );
- },
- };
-}
-
-import { createMarkdownFile } from '@core/util/create';
diff --git a/apps/web/src/features/calendar-notes/queries/reference-preview.test.ts b/apps/web/src/features/calendar-notes/queries/reference-preview.test.ts
deleted file mode 100644
index e56129a177..0000000000
--- a/apps/web/src/features/calendar-notes/queries/reference-preview.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import type { CalendarMentionEvent } from '@service-calendar/generated/schemas/calendarMentionEvent';
-import { describe, expect, it } from 'vitest';
-import type { DocumentReference } from './notes-source';
-import { resolveReferencePreview } from './reference-preview';
-
-const link: DocumentReference = {
- eventId: 'linked-copy',
- canViewMeeting: true,
- eventTitle: 'Planning',
- occurrenceKey: '2026-10-26T14:00:00+00:00',
-};
-const preview: CalendarMentionEvent = {
- title: 'Planning',
- viewerEventId: 'viewer-copy',
- time: {
- kind: 'timed',
- startsAt: '2026-10-26T14:00:00Z',
- endsAt: '2026-10-26T15:00:00Z',
- },
- occurrenceKey: link.occurrenceKey,
- isRecurring: true,
- description: null,
- location: null,
- organizerEmail: null,
- organizerName: null,
- attendeeCount: 2,
- updatedAt: '2026-10-25T12:00:00Z',
- canRequestToJoin: false,
-};
-
-describe('meeting reference resolution', () => {
- it('never recovers details for an unavailable owner link from a retained preview', () => {
- expect(
- resolveReferencePreview({
- ...link,
- canViewMeeting: false,
- event: preview,
- })
- ).toBeUndefined();
- });
- it('never substitutes another instance for a cancelled linked occurrence', () => {
- expect(
- resolveReferencePreview({ ...link, event: preview })?.event.viewerEventId
- ).toBe('viewer-copy');
- expect(
- resolveReferencePreview({
- ...link,
- event: {
- ...preview,
- occurrenceKey: '2026-10-27T14:00:00+00:00',
- },
- })
- ).toBeUndefined();
- expect(
- resolveReferencePreview({
- ...link,
- event: { ...preview, occurrenceKey: null },
- })
- ).toBeUndefined();
- });
-
- it('follows a rescheduled one-time meeting but not a conversion into a series', () => {
- const moved = {
- ...preview,
- isRecurring: false,
- occurrenceKey: '2026-10-28T16:00:00+00:00',
- };
- expect(
- resolveReferencePreview({
- ...link,
- occurrenceKey: 'single',
- event: moved,
- })?.event
- ).toBe(moved);
- expect(
- resolveReferencePreview({
- ...link,
- occurrenceKey: 'single',
- event: { ...moved, isRecurring: true },
- })
- ).toBeUndefined();
- });
-
- it('uses authorized team details without channel-sharing actions or a calendar copy', () => {
- const result = resolveReferencePreview({
- ...link,
- teamEvent: {
- id: 'opaque-team-projection',
- ownerId: 'macro|[email protected]',
- time: preview.time,
- contributesToAvailability: true,
- kind: 'details',
- details: {
- title: 'Source-scoped planning',
- description: null,
- location: null,
- conferenceUrl: null,
- organizerEmail: null,
- organizerName: null,
- attendees: [],
- calendarName: 'Work',
- },
- },
- });
- expect(result?.event.title).toBe('Source-scoped planning');
- expect(result?.event.viewerEventId).toBeNull();
- expect(result?.sharedActions).toBe(false);
- });
-});
diff --git a/apps/web/src/features/calendar-notes/queries/reference-preview.ts b/apps/web/src/features/calendar-notes/queries/reference-preview.ts
deleted file mode 100644
index aeaf835ea2..0000000000
--- a/apps/web/src/features/calendar-notes/queries/reference-preview.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import type { CalendarMentionEvent } from '@service-calendar/generated/schemas/calendarMentionEvent';
-import type { DocumentReference } from './notes-source';
-
-/** Mentions may fall forward to another instance; durable note links never do. */
-export function resolveReferencePreview(link: DocumentReference) {
- if (!link.canViewMeeting) return undefined;
- const preview = link.event;
- const exact =
- preview &&
- (link.occurrenceKey === 'single'
- ? !preview.isRecurring
- : preview.occurrenceKey === link.occurrenceKey);
- if (exact) return { event: preview, sharedActions: false };
- const team = link.teamEvent;
- if (team?.kind !== 'details') return undefined;
- return {
- event: {
- ...team.details,
- time: team.time,
- viewerEventId: null,
- occurrenceKey:
- link.occurrenceKey === 'single' ? undefined : link.occurrenceKey,
- isRecurring: link.occurrenceKey !== 'single',
- attendeeCount: team.details.attendees.length,
- } satisfies Omit<CalendarMentionEvent, 'updatedAt'>,
- sharedActions: false,
- };
-}
diff --git a/apps/web/src/features/calendar-notes/tests/fake-source.ts b/apps/web/src/features/calendar-notes/tests/fake-source.ts
deleted file mode 100644
index 386185c3c9..0000000000
--- a/apps/web/src/features/calendar-notes/tests/fake-source.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { err, ok } from 'neverthrow';
-import { createSignal } from 'solid-js';
-import type { NotesSource } from '../context/notes-source';
-import type { MeetingNote, NoteDocument } from '../core/types';
-
-export function createFakeNotesSource(options: { fail?: boolean } = {}) {
- const documents: NoteDocument[] = [
- { documentId: 'weekly', name: 'Weekly product sync' },
- { documentId: 'roadmap', name: 'Q4 product roadmap' },
- { documentId: 'research', name: 'Customer research · October' },
- { documentId: 'retro', name: 'Team retrospective' },
- {
- documentId: 'long',
- name: 'Agent: offers to add a meeting to another calendar after the organizer updates a recurring event',
- },
- ];
- const team = { id: 'macro', name: 'Macro' };
- const [notes, setNotes] = createSignal<MeetingNote[]>([]);
- const [fail, setFail] = createSignal(options.fail ?? false);
- let createdCount = 0;
- const source: NotesSource = {
- notes: () => ({ data: notes(), pending: false }),
- picker: (query) => () => ({
- data: {
- documents: documents.filter((doc) =>
- doc.name.toLowerCase().includes(query().toLowerCase())
- ),
- teams: [team],
- },
- pending: false,
- }),
- retry: async () => {},
- async create(name) {
- const document = { documentId: `created-${++createdCount}`, name };
- documents.push(document);
- const linked = await source.link(document.documentId);
- if (linked.isErr()) {
- return err({
- kind: 'created_unlinked',
- document,
- message:
- 'Your note was saved, but couldn’t be linked to this meeting. Retry linking or open the saved note.',
- });
- }
- return ok(document);
- },
- async link(documentId, teamId) {
- if (fail()) {
- setFail(false);
- return err({
- kind: 'link_failed',
- message: 'Couldn’t save this link. Please try again.',
- });
- }
- const document = documents.find((doc) => doc.documentId === documentId);
- if (!document)
- return err({ kind: 'link_failed', message: 'Document not found' });
- setNotes((current) => [
- ...current.filter((note) => note.documentId !== documentId),
- {
- ...document,
- team: teamId ? team : undefined,
- canManage: true,
- },
- ]);
- return ok(undefined);
- },
- async unlink(documentId) {
- setNotes((current) =>
- current.filter((note) => note.documentId !== documentId)
- );
- return ok(undefined);
- },
- };
- return { source, notes };
-}
diff --git a/apps/web/src/features/calendar-notes/views/document-notes.test.tsx b/apps/web/src/features/calendar-notes/views/document-notes.test.tsx
deleted file mode 100644
index 38a3bbd07d..0000000000
--- a/apps/web/src/features/calendar-notes/views/document-notes.test.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { ok } from 'neverthrow';
-import { createSignal } from 'solid-js';
-import { afterEach, expect, it, vi } from 'vitest';
-import type { DocumentNotesSource } from '../context/notes-source';
-import type { DocumentNoteLink } from '../core/types';
-import { DocumentNotesView } from './document-notes';
-
-afterEach(cleanup);
-
-it('keeps Unlink mounted and usable while team access saves, without allowing concurrent writes', async () => {
- const link = {
- eventId: 'event',
- occurrenceKey: 'single',
- eventTitle: 'Sync',
- };
- const team = { id: 'team', name: 'Macro' };
- const [links, setLinks] = createSignal<DocumentNoteLink[]>([link]);
- const saved = Promise.withResolvers<void>();
- const source: DocumentNotesSource = {
- links: () => ({ data: links(), pending: false }),
- team: () => ({ data: team, pending: false }),
- retry: async () => {},
- setTeam: async () => {
- await saved.promise;
- setLinks([{ ...link, team }]);
- return ok(undefined);
- },
- unlink: vi.fn(async () => ok(undefined)),
- };
- render(() => <DocumentNotesView source={source} />);
- const unlink = screen.getByRole('button', { name: 'Unlink' });
- const checkbox = screen.getByRole('checkbox');
- await fireEvent.click(checkbox);
- expect(unlink.hasAttribute('disabled')).toBe(false);
- await fireEvent.click(unlink);
- const confirm = screen.getByRole('button', { name: 'Unlink meeting' });
- expect(confirm.hasAttribute('disabled')).toBe(true);
- await fireEvent.click(confirm);
- expect(source.unlink).not.toHaveBeenCalled();
-
- saved.resolve();
- await vi.waitFor(() => expect(confirm.hasAttribute('disabled')).toBe(false));
- expect(screen.getByRole('button', { name: 'Unlink' })).toBe(unlink);
- expect(screen.getByRole('checkbox')).toBe(checkbox);
- await fireEvent.click(confirm);
- expect(source.unlink).toHaveBeenCalledOnce();
-});
diff --git a/apps/web/src/features/calendar-notes/views/document-notes.tsx b/apps/web/src/features/calendar-notes/views/document-notes.tsx
deleted file mode 100644
index b73a121e71..0000000000
--- a/apps/web/src/features/calendar-notes/views/document-notes.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { fireAndForget } from '@core/util/fireAndForget';
-import { DocumentNotesSection } from '../components/document-notes-section';
-import type { DocumentNotesSource } from '../context/notes-source';
-import { createDocumentNotesController } from '../primitives/document-notes-controller';
-
-export function DocumentNotesView(props: { source: DocumentNotesSource }) {
- const controller = createDocumentNotesController(props.source);
- return (
- <DocumentNotesSection
- state={props.source.links()}
- team={props.source.team()}
- selected={controller.selected()}
- saving={controller.saving()}
- removing={controller.removing()}
- error={controller.error()}
- onSelect={controller.select}
- onTeam={(link, teamId) =>
- fireAndForget(controller.setTeam(link, teamId), 'calendar.notes.team')
- }
- onRemove={() =>
- fireAndForget(controller.remove(), 'calendar.notes.revoke')
- }
- onRetry={() =>
- fireAndForget(props.source.retry(), 'calendar.notes.retry')
- }
- />
- );
-}
diff --git a/apps/web/src/features/calendar-notes/views/meeting-notes.tsx b/apps/web/src/features/calendar-notes/views/meeting-notes.tsx
deleted file mode 100644
index 0d9e67e046..0000000000
--- a/apps/web/src/features/calendar-notes/views/meeting-notes.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { fireAndForget } from '@core/util/fireAndForget';
-import { type JSX, Show } from 'solid-js';
-import { NoteDialog } from '../components/note-dialog';
-import { NotesSection } from '../components/notes-section';
-import type { NotesSource } from '../context/notes-source';
-import type { MeetingNote } from '../core/types';
-import { createMeetingNoteAction } from '../primitives/create-meeting-note';
-import { createNotesController } from '../primitives/notes-controller';
-
-export function MeetingNotesView(props: {
- source: NotesSource;
- eventTitle: string;
- recurring: boolean;
- guestListHidden?: boolean;
- onOpen: (note: MeetingNote) => void;
- shareDialog: (note: MeetingNote, onClose: () => void) => JSX.Element;
- onDialogChange: (open: boolean) => void;
-}) {
- const controller = createNotesController(props.source, props.onDialogChange);
- const creation = createMeetingNoteAction({
- source: props.source,
- title: () => props.eventTitle,
- onOpen: (document) => props.onOpen({ ...document, canManage: true }),
- });
- return (
- <>
- <NotesSection
- state={props.source.notes()}
- creating={creation.pending()}
- createdUnlinked={!!creation.saved()}
- createError={creation.error()}
- onCreate={() => fireAndForget(creation.run(), 'calendar.notes.create')}
- onOpenSaved={creation.openSaved}
- dialogOpen={!!controller.dialog()}
- onMenuChange={controller.setMenuOpen}
- onLink={controller.openLink}
- onOpen={props.onOpen}
- onSharing={controller.openSharing}
- onUnlink={controller.openUnlink}
- onRetry={() =>
- fireAndForget(props.source.retry(), 'calendar.notes.retry')
- }
- />
- <Show
- when={controller.dialog()?.kind === 'sharing' && controller.dialog()}
- >
- {(dialog) => {
- const active = dialog();
- return active.kind === 'sharing'
- ? props.shareDialog(active.note, controller.close)
- : undefined;
- }}
- </Show>
- <Show
- when={controller.dialog()?.kind !== 'sharing' && controller.dialog()}
- >
- {(dialog) => (
- <NoteDialog
- kind={dialog().kind === 'unlink' ? 'unlink' : 'link'}
- eventTitle={props.eventTitle}
- recurring={props.recurring}
- guestListHidden={props.guestListHidden}
- picker={controller.picker()}
- query={controller.query()}
- onQuery={controller.setQuery}
- selected={controller.selected()}
- onSelect={controller.setSelected}
- linkedIds={
- props.source.notes().data?.map((note) => note.documentId) ?? []
- }
- linksReady={props.source.notes().data !== undefined}
- teamId={controller.teamId()}
- onTeam={controller.setTeamId}
- saving={controller.saving()}
- error={controller.error() ?? props.source.notes().error}
- onSave={() =>
- fireAndForget(controller.save(), 'calendar.notes.save')
- }
- onClose={controller.close}
- />
- )}
- </Show>
- </>
- );
-}
diff --git a/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx b/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx
index cb69d8080e..518e47d5cb 100644
--- a/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx
+++ b/apps/web/src/features/calendar-view/browser-test/preview-adapters.tsx
@@ -153,8 +153,6 @@ export function createGuestInviteController() {
}
export const useCalendarGuestInvitesFlag = () => () => false;
export const useCalendarInvitationForwardFlag = () => () => false;
-export const useCalendarMeetingNotesFlag = () => () => false;
-export const CalendarMeetingNotes = () => null;
export const TeamEventDetails = () => null;
export const OutlookRsvpAction = () => null;
export const copyCalendarEventMention = () =>
diff --git a/apps/web/src/features/calendar-view/browser-test/vite.config.ts b/apps/web/src/features/calendar-view/browser-test/vite.config.ts
index 47ca32fa28..90494baf51 100644
--- a/apps/web/src/features/calendar-view/browser-test/vite.config.ts
+++ b/apps/web/src/features/calendar-view/browser-test/vite.config.ts
@@ -21,7 +21,6 @@ const previewImports = [
'@app/features/calendar-view/components/use-forward-event-email',
'@app/features/calendar/hooks/create-guest-invite-controller',
'@app/features/calendar/hooks/use-calendar-ui-flag',
- '@app/features/calendar-notes/calendar-meeting-notes',
'@app/features/calendar-view/components/use-open-event-email',
'@app/features/calendar-view/copy-guest-emails',
'@property/editors/selectors/PropertyEntitySelector',
diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
index 4682a5f885..7d0bb39294 100644
--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.test.tsx
@@ -3,7 +3,6 @@
*/
import type { CalendarEvent } from '@app/features/calendar/types';
-import { createSplitAutofocus } from '@components/app/split-layout/utils/createSplitAutofocus';
import { cleanup, render, screen } from '@solidjs/testing-library';
import userEvent from '@testing-library/user-event';
import { ImperativeDialogHost } from '@ui';
@@ -53,17 +52,9 @@ vi.mock('@app/features/calendar/hooks/create-guest-invite-controller', () => ({
vi.mock('@app/features/calendar/hooks/use-calendar-ui-flag', () => ({
useCalendarGuestInvitesFlag: () => () => false,
useCalendarInvitationForwardFlag: () => () => false,
- useCalendarMeetingNotesFlag: () => () => true,
}));
// The sections have their own tests; exercise the overlay's actions and
// navigation/focus handoff here.
-vi.mock('@app/features/calendar-notes/calendar-meeting-notes', () => ({
- CalendarMeetingNotes: (props: { onOpenDocument: (id: string) => void }) => (
- <button onClick={() => props.onOpenDocument('note-1')}>
- Open linked note
- </button>
- ),
-}));
vi.mock('@app/features/calendar/components/EventDetails', () => ({
EventDetails: () => null,
}));
@@ -179,36 +170,6 @@ describe('desktop focus handoff', () => {
mocks.mobile = false;
});
- it('lets a note that finishes mounting after dismissal claim focus', async () => {
- const user = userEvent.setup();
- const anchor = showDetails(event());
- const [noteElement, setNoteElement] = createSignal<HTMLElement | null>(
- null
- );
- render(() => {
- createSplitAutofocus({ element: noteElement, enabled: () => true });
- return null;
- });
-
- for (let attempt = 0; attempt < 2; attempt++) {
- if (attempt > 0) await user.click(anchor);
- await user.click(
- screen.getByRole('button', { name: 'Open linked note' })
- );
- expect(mocks.openDocument).toHaveBeenCalledWith(
- { type: 'md', id: 'note-1' },
- { preferNewSplit: true }
- );
-
- const note = document.createElement('div');
- note.tabIndex = -1;
- document.body.append(note);
- setNoteElement(note);
- await Promise.resolve();
- expect(document.activeElement).toBe(note);
- }
- });
-
it('returns focus to the event on ordinary dismissal and reopening', async () => {
const user = userEvent.setup();
const anchor = showDetails(event());
diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
index 4fc7c550a4..87f18194ac 100644
--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
@@ -4,7 +4,6 @@ import { createGuestInviteController } from '@app/features/calendar/hooks/create
import {
useCalendarGuestInvitesFlag,
useCalendarInvitationForwardFlag,
- useCalendarMeetingNotesFlag,
} from '@app/features/calendar/hooks/use-calendar-ui-flag';
import {
type CalendarEvent,
@@ -17,7 +16,6 @@ import {
} from '@app/features/calendar/utils/event-interaction';
import { eventEmailRecipients } from '@app/features/calendar/utils/guest-emails';
import { handleOpenEventOutsidePress } from '@app/features/calendar/utils/open-event-outside-press';
-import { CalendarMeetingNotes } from '@app/features/calendar-notes/calendar-meeting-notes';
import { TeamEventDetails } from '@app/features/calendar-team/components/team-event-details';
import { EventGuests } from '@app/features/calendar-view/components/EventGuests';
import { EventJoinRequests } from '@app/features/calendar-view/components/EventJoinRequests';
@@ -27,7 +25,6 @@ import { useOpenEventComposer } from '@app/features/calendar-view/components/use
import { copyCalendarEventMention } from '@app/features/calendar-view/copy-event-mention';
import { downloadCalendarEventIcs } from '@app/features/calendar-view/download-event-ics';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
-import { useSplitLayout } from '@components/app/split-layout/layout';
import { toast } from '@core/component/Toast/Toast';
import { isMobile } from '@core/mobile/isMobile';
import { openExternalUrl } from '@core/util/url';
@@ -183,10 +180,6 @@ function EveryoneElseDeclinedNotice(props: {
}
function EventDetailsDrawer(props: EventDetailsOverlayProps) {
- const meetingNotesEnabled = useCalendarMeetingNotesFlag();
- const [notesOpen, setNotesOpen] = createSignal(false);
- let content: HTMLDivElement | undefined;
- const { openWithSplit } = useSplitLayout();
const openEventComposer = useOpenEventComposer();
const deleteDialog = useDeleteEventDialog({
event: () => props.event,
@@ -219,24 +212,17 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {
!open &&
(deleteDialog.isOpen() ||
invites.editorOpen() ||
- invites.forwardEditorOpen() ||
- notesOpen())
+ invites.forwardEditorOpen())
)
return;
props.onOpenChange(open);
}}
preventScroll={false}
preventScrollbarShift={false}
- trapFocus={!notesOpen()}
- onInitialFocus={(event) => {
- if (notesOpen() || content?.contains(document.activeElement))
- event.preventDefault();
- }}
>
<MobileDrawer.Portal>
<MobileDrawer.Overlay />
<MobileDrawer.Content
- ref={content}
aria-label={props.event.title}
class="overflow-hidden"
>
@@ -339,23 +325,6 @@ function EventDetailsDrawer(props: EventDetailsOverlayProps) {
/>
</Show>
</div>
- <Show
- when={
- meetingNotesEnabled() &&
- props.event.teamProjection?.kind !== 'busy' &&
- !props.event.isCancelled &&
- !props.event.isSnapshot
- }
- >
- <CalendarMeetingNotes
- event={props.event}
- onDialogChange={setNotesOpen}
- onOpenDocument={(id) => {
- openWithSplit({ type: 'md', id }, { preferNewSplit: false });
- props.onOpenChange(false);
- }}
- />
- </Show>
<Show when={!props.event.teamProjection}>
<EventGuests
event={props.event}
@@ -490,10 +459,6 @@ function DeleteEventDialog(
* scroll within 32rem or the available height; the RSVP row stays pinned.
*/
function EventDetailsPopover(props: EventDetailsPopoverProps) {
- const meetingNotesEnabled = useCalendarMeetingNotesFlag();
- const [notesOpen, setNotesOpen] = createSignal(false);
- let openingDocument = false;
- const { openWithSplit } = useSplitLayout();
const openEventComposer = useOpenEventComposer();
const deleteDialog = useDeleteEventDialog({
event: () => props.event,
@@ -529,8 +494,7 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
!open &&
(deleteDialog.isOpen() ||
invites.editorOpen() ||
- invites.forwardEditorOpen() ||
- notesOpen())
+ invites.forwardEditorOpen())
)
return;
props.onOpenChange(open);
@@ -538,7 +502,7 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
placement="right-start"
gutter={8}
// Flip only to the other side, never to an end alignment: sections
- // that arrive after opening (join requests, meeting notes) change the
+ // that arrive after opening (join requests) change the
// height, and an end fallback would re-place the popover from below
// the event to above it. Slide keeps a tall popover in view instead.
flip="left-start"
@@ -568,8 +532,7 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
event.preventDefault();
}}
onCloseAutoFocus={(event) => {
- const shouldRestoreFocus =
- !openingDocument && !event.defaultPrevented;
+ const shouldRestoreFocus = !event.defaultPrevented;
event.preventDefault();
if (shouldRestoreFocus && props.anchor.isConnected) {
props.anchor.focus();
@@ -677,27 +640,6 @@ function EventDetailsPopover(props: EventDetailsPopoverProps) {
/>
</Show>
</div>
- <Show
- when={
- meetingNotesEnabled() &&
- props.event.teamProjection?.kind !== 'busy' &&
- !props.event.isCancelled &&
- !props.event.isSnapshot
- }
- >
- <CalendarMeetingNotes
- event={props.event}
- onDialogChange={setNotesOpen}
- onOpenDocument={(id) => {
- openingDocument = true;
- openWithSplit(
- { type: 'md', id },
- { preferNewSplit: true }
- );
- props.onOpenChange(false);
- }}
- />
- </Show>
<Show when={!props.event.teamProjection}>
<EventGuests
event={props.event}
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
index 4c670385c2..90a6d21017 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-ui-flag.ts
@@ -3,7 +3,6 @@ import {
enableCalendarAddSharedEvent,
enableCalendarGuestInvites,
enableCalendarInvitationForward,
- enableCalendarMeetingNotes,
enableCalendarPromptMobile,
enableCalendarPromptWeb,
enableCalendarSearchUi,
@@ -19,11 +18,6 @@ export function useCalendarUiFlag(): Accessor<boolean> {
return () => flag().enabled;
}
-export function useCalendarMeetingNotesFlag(): Accessor<boolean> {
- const flag = useFeatureFlag(enableCalendarMeetingNotes);
- return () => flag().enabled;
-}
-
/**
* Whether the calendar search UI (Search-view calendar type/rows and the
* in-calendar keyword search) is enabled. A sub-feature of the calendar UI, so
diff --git a/apps/web/src/lib/core/component/DocumentPreview.tsx b/apps/web/src/lib/core/component/DocumentPreview.tsx
index 78cf178cef..cb77474858 100644
--- a/apps/web/src/lib/core/component/DocumentPreview.tsx
+++ b/apps/web/src/lib/core/component/DocumentPreview.tsx
@@ -337,7 +337,7 @@ const calendarTimeFormat = new Intl.DateTimeFormat(undefined, {
/** One compact local-time schedule line for a calendar mention preview. */
export function calendarPreviewSchedule(
- event: Pick<PreviewCalendarEventAccess['event'], 'time'>
+ event: PreviewCalendarEventAccess['event']
): string | undefined {
if (event.time.kind === 'allDay') {
const start = parseLocalDate(event.time.startDate);
@@ -372,16 +372,14 @@ function heldOnCalendarLabel(
}
/** Meeting-level rows of the calendar mention hover card. */
-export function CalendarEventPreviewDetails(props: {
- event: Omit<PreviewCalendarEventAccess['event'], 'updatedAt'>;
+function CalendarEventPreviewDetails(props: {
+ event: PreviewCalendarEventAccess['event'];
/** The mentioned event, which a read-only share copies from. */
mentionedEventId: string;
/** Opens the viewer's own copy; absent where the card cannot open it. */
onOpen?: (event: MouseEvent) => void;
/** Runs once Join has left the card; native apps join in-app, behind it. */
onJoin?: () => void;
- /** Team-calendar projections have no channel-share mutation capabilities. */
- sharedActions?: boolean;
}) {
const organizer = () =>
props.event.organizerName ?? props.event.organizerEmail;
@@ -492,9 +490,7 @@ export function CalendarEventPreviewDetails(props: {
</MetadataInfo>
</Show>
<Switch>
- <Match
- when={!props.event.viewerEventId && props.sharedActions !== false}
- >
+ <Match when={!props.event.viewerEventId}>
<SharedEventActions
eventId={props.mentionedEventId}
title={props.event.title}
diff --git a/apps/web/src/lib/core/component/References.tsx b/apps/web/src/lib/core/component/References.tsx
index 2649448ffe..a8440ca9ba 100644
--- a/apps/web/src/lib/core/component/References.tsx
+++ b/apps/web/src/lib/core/component/References.tsx
@@ -97,25 +97,19 @@ interface ReferenceRowProps {
source: JSX.Element;
senderAvatar?: JSX.Element;
senderName?: string;
- timestamp?: DateValue;
- timestampLabel?: string;
- ariaLabel?: string;
+ timestamp: DateValue;
body?: JSX.Element;
onClick?: (e: KeyboardEvent | MouseEvent) => void;
}
-export function ReferenceRow(props: ReferenceRowProps) {
+function ReferenceRow(props: ReferenceRowProps) {
const navHandlers = useSplitNavigationHandler<HTMLDivElement>((e) => {
props.onClick?.(e);
});
- const timestamp = () =>
- props.timestampLabel ??
- (props.timestamp ? formatRelativeTimestamp(props.timestamp) : undefined);
return (
<div
role="button"
- aria-label={props.ariaLabel}
tabIndex={0}
class="group/ref-row flex min-w-0 flex-col overflow-hidden rounded-lg py-1 hover:bg-hover/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/40"
onMouseDown={navHandlers.onMouseDown}
@@ -140,18 +134,12 @@ export function ReferenceRow(props: ReferenceRowProps) {
{props.source}
</div>
</div>
- <Show when={timestamp()}>
- {(label) => (
- <>
- <span aria-hidden class="shrink-0 text-ink-extra-muted">
- ·
- </span>
- <span class="shrink-0 text-ink-extra-muted tabular-nums">
- {label()}
- </span>
- </>
- )}
- </Show>
+ <span aria-hidden class="shrink-0 text-ink-extra-muted">
+ ·
+ </span>
+ <span class="shrink-0 text-ink-extra-muted tabular-nums">
+ {formatRelativeTimestamp(props.timestamp)}
+ </span>
</div>
<Show when={props.body}>
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index 2968c1d766..e5cddb3c2c 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -7,7 +7,7 @@ import {
} from '@solidjs/testing-library';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { err, ok } from 'neverthrow';
-import { createSignal, For, type JSX, onCleanup } from 'solid-js';
+import { createSignal, For, type JSX } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Permissions } from '../SharePermissions';
import {
@@ -17,29 +17,6 @@ import {
shareLevelsFor,
} from './ShareButton';
-vi.mock('@app/features/calendar-notes/document-meeting-notes', () => ({
- DocumentMeetingNotes: (props: {
- documentId: string;
- onAccessState?: (state: 'shared' | 'none', teamIds: string[]) => void;
- }) => {
- mocks.mountMeetingNotes(props.documentId);
- onCleanup(mocks.unmountMeetingNotes);
- props.onAccessState?.(
- props.documentId === 'meeting-note' ? 'shared' : 'none',
- []
- );
- return (
- <section aria-label="Meeting links">
- Meeting links for {props.documentId}
- </section>
- );
- },
-}));
-
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => mocks.meetingNotesFlag(),
-}));
-
// Share's request workflow has its own source and lifecycle suites. Keep these
// existing sharing tests independent of a live QueryClient and backend.
vi.mock('@app/features/access-requests/access-requests', async (original) => ({
@@ -88,9 +65,6 @@ const ME = 'macro|[email protected]';
const SOMEONE_ELSE = 'macro|[email protected]';
const mocks = vi.hoisted(() => ({
- meetingNotesFlag: () => ({ enabled: true, loading: false }),
- mountMeetingNotes: vi.fn(),
- unmountMeetingNotes: vi.fn(),
sendToChannel: vi.fn(),
sendToUsers: vi.fn(),
graphql: false,
@@ -449,7 +423,6 @@ beforeEach(() => {
defaultOptions: { queries: { retry: false } },
});
vi.clearAllMocks();
- mocks.meetingNotesFlag = () => ({ enabled: true, loading: false });
mocks.inBlock = true;
mocks.blockId = 'launcher-placeholder';
mocks.getDocumentPermissions.mockResolvedValue(
@@ -491,8 +464,8 @@ beforeEach(() => {
});
afterEach(cleanup);
-describe('document meeting-link management', () => {
- it('loads the linked note’s permissions instead of its enclosing calendar block', async () => {
+describe('document permissions source', () => {
+ it('loads a document’s own permissions instead of its enclosing block’s', async () => {
mocks.blockId = 'calendar';
mocks.blockEditPermissionEnabled = false;
mocks.getDocumentPermissions.mockResolvedValue(
@@ -504,8 +477,8 @@ describe('document meeting-link management', () => {
);
render(() => (
<ShareModal
- id="linked-note"
- name="Linked note"
+ id="shared-doc"
+ name="Shared doc"
owner={ME}
itemType="document"
blockAlias="md"
@@ -516,7 +489,7 @@ describe('document meeting-link management', () => {
));
await vi.waitFor(() =>
expect(mocks.getDocumentPermissions).toHaveBeenCalledWith({
- document_id: 'linked-note',
+ document_id: 'shared-doc',
})
);
expect(
@@ -527,97 +500,6 @@ describe('document meeting-link management', () => {
await screen.findByRole('button', { name: 'Set option edit' })
).toBeTruthy();
});
- it.each([false, true])(
- 'gates the meeting source without implying grants were revoked (mobile: %s)',
- async (mobile) => {
- mocks.mobile = mobile;
- mocks.blockId = 'meeting-note';
- const [flag, setFlag] = createSignal({ enabled: false, loading: true });
- const [documentId, setDocumentId] = createSignal('meeting-note');
- mocks.meetingNotesFlag = flag;
- render(() => (
- <ShareModal
- id={documentId()}
- name="Notes"
- owner={ME}
- itemType="document"
- blockAlias="md"
- userPermissions={Permissions.OWNER}
- open
- onOpenChange={vi.fn()}
- />
- ));
- if (mobile)
- await fireEvent.click(screen.getByRole('tab', { name: /^Link$/ }));
- expect(mocks.mountMeetingNotes).not.toHaveBeenCalled();
- expect(screen.getByText('Checking access…')).toBeDefined();
- expect(screen.queryByText('Just me')).toBeNull();
-
- setFlag({ enabled: false, loading: false });
- expect(mocks.mountMeetingNotes).not.toHaveBeenCalled();
- expect(screen.getByText('Restricted')).toBeDefined();
- expect(screen.queryByText('Just me')).toBeNull();
-
- setFlag({ enabled: true, loading: false });
- expect(mocks.mountMeetingNotes).toHaveBeenCalledExactlyOnceWith(
- 'meeting-note'
- );
- expect(screen.getByText('Shared')).toBeDefined();
-
- setFlag({ enabled: false, loading: false });
- expect(mocks.unmountMeetingNotes).toHaveBeenCalledOnce();
- expect(screen.getByText('Shared')).toBeDefined();
- expect(screen.queryByText('Just me')).toBeNull();
-
- setDocumentId('another-note');
- expect(screen.queryByText('Shared')).toBeNull();
- expect(await screen.findByText('Restricted')).toBeDefined();
- expect(mocks.mountMeetingNotes).toHaveBeenCalledTimes(1);
- setFlag({ enabled: true, loading: false });
- expect(mocks.mountMeetingNotes).toHaveBeenLastCalledWith('another-note');
- expect(screen.getByText('Just me')).toBeDefined();
- }
- );
- it.each([false, true])(
- 'is reachable by the document owner (mobile: %s)',
- async (mobile) => {
- mocks.mobile = mobile;
- render(() => (
- <ShareModal
- id="meeting-note"
- name="Notes"
- owner={ME}
- itemType="document"
- blockAlias="md"
- userPermissions={Permissions.OWNER}
- open
- onOpenChange={vi.fn()}
- />
- ));
- if (mobile)
- await fireEvent.click(screen.getByRole('tab', { name: /^Link$/ }));
- expect(
- (await screen.findByRole('region', { name: 'Meeting links' }))
- .textContent
- ).toContain('meeting-note');
- expect(screen.queryByText('Just me')).toBeNull();
- }
- );
- it('does not request another owner’s meeting links', () => {
- render(() => (
- <ShareModal
- id="meeting-note"
- name="Notes"
- owner={SOMEONE_ELSE}
- itemType="document"
- blockAlias="md"
- userPermissions={Permissions.CAN_VIEW}
- open
- onOpenChange={vi.fn()}
- />
- ));
- expect(screen.queryByRole('region', { name: 'Meeting links' })).toBeNull();
- });
});
function mountShare(isOwner: boolean) {
const onOpenChange = vi.fn();
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 8a4f6be2d3..b3625d0d8b 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -13,14 +13,11 @@ import {
useShareRequestTrigger,
} from '@app/features/access-requests/share-request-trigger';
import { DirectAccessInvite } from '@app/features/access-requests/views/DirectAccessInvite';
-import type { MeetingAccessState } from '@app/features/calendar-notes/core/types';
-import { DocumentMeetingNotes } from '@app/features/calendar-notes/document-meeting-notes';
import {
updatePipelineSharePermissions,
updatePipelineTeamShare,
} from '@app/features/crm/sharing-adapter';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useChannelParticipants } from '@channel/use-channel-participants';
import { HeaderActionButton } from '@components/app/HeaderActionButton';
import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
@@ -49,7 +46,6 @@ import { resolveBlockAlias } from '@core/constant/allBlocks';
import {
ENABLE_MARKDOWN_COMMENTS,
ENABLE_MARKDOWN_LIVE_COLLABORATION,
- enableCalendarMeetingNotes,
} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import clickOutside from '@core/directive/clickOutside';
@@ -418,7 +414,6 @@ interface LinkSharingControlsProps {
linkShare: LinkShare | null | undefined;
linkShareAccessLevel: AccessLevel | null | undefined;
hasExplicitShares: boolean;
- meetingAccess?: MeetingAccessState | 'unknown';
setLinkShareScope: (scope: LinkShareScope) => void;
setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;
copyLink: () => void;
@@ -430,9 +425,6 @@ interface LinkSharingControlsProps {
/** Owner-only explicit team sharing, present only for entity types that support it. */
interface TeamShareControls {
accessLevel: AccessLevel | null | undefined;
- /** An independent view grant that is managed under Meeting links. */
- meetingViewAccess?: boolean;
- meetingAccess?: MeetingAccessState | 'unknown';
setAccessLevel: (scope: TeamShareScope) => void;
/** Noun for the copy, e.g. "document" or "chat". */
itemNoun: string;
@@ -450,33 +442,13 @@ function teamShareOnOwnCard(
function TeamAccessSection(props: { teamShare: TeamShareControls }) {
const teamShareScope = () => getTeamShareScope(props.teamShare.accessLevel);
- const label = () => {
- const scope = teamShareScope();
- if (scope !== 'NONE') return getTeamShareScopeCopy(scope);
- if (props.teamShare.meetingViewAccess) return 'View via meeting';
- if (props.teamShare.meetingAccess === 'loading') return 'Checking…';
- if (props.teamShare.meetingAccess === 'error')
- return 'Check meeting access';
- if (props.teamShare.meetingAccess === 'unknown') return 'Direct: None';
- return getTeamShareScopeCopy(scope);
- };
return (
<div class="flex flex-wrap items-center justify-between gap-3">
<div class="flex flex-col gap-1">
<span class="font-medium">Team access</span>
<p class="text-sm text-ink-muted">
- <Show
- when={props.teamShare.meetingViewAccess}
- fallback={
- <>
- Share this {props.teamShare.itemNoun} directly with the owner's
- team.
- </>
- }
- >
- Your team can view through meeting links.
- </Show>
+ Share this {props.teamShare.itemNoun} directly with the owner's team.
</p>
</div>
<Dropdown>
@@ -485,7 +457,7 @@ function TeamAccessSection(props: { teamShare: TeamShareControls }) {
aria-label="Team access"
class="min-w-16.75 py-1 pl-2 pr-1 flex items-center gap-1"
>
- {label()}
+ {getTeamShareScopeCopy(teamShareScope())}
<ChevronDownIcon class="size-4 text-ink-extra-muted" />
</Dropdown.Trigger>
<Dropdown.Content portalScope="local">
@@ -499,12 +471,7 @@ function TeamAccessSection(props: { teamShare: TeamShareControls }) {
<For each={props.teamShare.scopeOptions}>
{(option) => (
<Dropdown.RadioItem value={option.value}>
- <span class="flex-1 truncate">
- {option.value === 'NONE' &&
- props.teamShare.meetingViewAccess
- ? 'Use meeting access'
- : option.label}
- </span>
+ <span class="flex-1 truncate">{option.label}</span>
<Dropdown.ItemIndicator>
<CheckIcon class="size-3.5 text-accent" />
</Dropdown.ItemIndicator>
@@ -521,54 +488,12 @@ function TeamAccessSection(props: { teamShare: TeamShareControls }) {
function LinkSharingControls(props: LinkSharingControlsProps) {
const scope = () => getLinkShareScope(props.linkShare);
const scopeCopy = () => getLinkShareScopeCopy(scope());
- const shareStatus = () => {
- const status = getShareStatus(
+ const shareStatus = () =>
+ getShareStatus(
props.linkShare,
- props.hasExplicitShares || props.meetingAccess === 'shared',
- props.teamShare?.accessLevel ??
- (props.teamShare?.meetingViewAccess ? 'view' : undefined)
+ props.hasExplicitShares,
+ props.teamShare?.accessLevel
);
- if (
- status.label === 'Team' &&
- props.teamShare?.meetingViewAccess &&
- !props.teamShare.accessLevel &&
- !props.linkShare
- ) {
- return {
- ...status,
- tooltip: 'Your team can view through meeting links.',
- };
- }
- if (status.label === 'Shared' && props.meetingAccess === 'shared') {
- return {
- ...status,
- tooltip: props.hasExplicitShares
- ? 'Shared with specific people or channels and through meeting links.'
- : 'Shared through meeting links with meeting viewers and any teams selected there.',
- };
- }
- if (status.label !== 'Just me') return status;
- if (props.meetingAccess === 'unknown') {
- return {
- label: 'Restricted',
- tooltip: 'Only people with access can open this link.',
- };
- }
- if (props.meetingAccess === 'loading') {
- return {
- label: 'Checking access…',
- tooltip: 'Meeting links may grant additional access.',
- };
- }
- if (props.meetingAccess === 'error') {
- return {
- label: 'Check meeting access',
- tooltip:
- 'Meeting links may grant additional access. See Meeting links.',
- };
- }
- return status;
- };
return (
<Show when={!props.loading} fallback={<LinkSharingSkeleton />}>
@@ -705,9 +630,6 @@ function RecipientsSkeleton() {
}
interface MobileShareDrawerProps {
- meetingNotesEnabled: boolean;
- meetingAccess?: MeetingAccessState | 'unknown';
- onMeetingAccessState: (state: MeetingAccessState, teamIds: string[]) => void;
requests: SharingSource;
requestLevels: readonly AccessLevel[];
editPermissionEnabled?: boolean;
@@ -742,7 +664,6 @@ interface MobileShareDrawerProps {
}
function MobileShareDrawer(props: MobileShareDrawerProps) {
- const userId = useUserId();
const [activeTab, setActiveTab] = createSignal<string>();
const wrappedSetOpen = (open: boolean) => {
@@ -1005,7 +926,6 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
props.blockAlias
)}
loading={props.permissionsLoading}
- meetingAccess={props.meetingAccess}
editPermissionEnabled={props.editPermissionEnabled}
linkShare={props.linkShare}
linkShareAccessLevel={props.linkShareAccessLevel}
@@ -1024,20 +944,6 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
<Dynamic component={props.linkSharing} />
</div>
</Show>
- <Show
- when={
- props.meetingNotesEnabled &&
- props.blockAlias === 'md' &&
- props.itemType === 'document' &&
- !!userId() &&
- props.owner === userId()
- }
- >
- <DocumentMeetingNotes
- documentId={props.id}
- onAccessState={props.onMeetingAccessState}
- />
- </Show>
</Show>
<Show
when={
@@ -1059,7 +965,6 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {
}
export function ShareModal(props: ShareModalProps) {
- const meetingNotesFlag = useFeatureFlag(enableCalendarMeetingNotes);
const requests = useShareRequests(
() => shareEntity(props.itemType, props.id),
() => props.open
@@ -1080,8 +985,8 @@ export function ShareModal(props: ShareModalProps) {
const callRecordQuery = useCallRecordQuery(() =>
props.itemType === 'call' ? props.id : ''
);
- // A calendar can open Share for a linked note. Only reuse the enclosing
- // block's permissions when the dialog is sharing that same entity.
+ // A block can open Share for another entity it shows. Only reuse the
+ // enclosing block's permissions when the dialog is sharing that same entity.
const enclosingBlockId = useMaybeBlockId();
const isBlockContext = () =>
!!enclosingBlockId &&
@@ -1127,51 +1032,6 @@ export function ShareModal(props: ShareModalProps) {
await fallbackPermissionsQuery.refetch();
};
const userId = useUserId();
- const [meetingAccessSnapshot, setMeetingAccessSnapshot] = createSignal<{
- documentId: string;
- userId: string | undefined;
- state: MeetingAccessState;
- teamIds: string[];
- }>();
- const setMeetingAccess = (state: MeetingAccessState, teamIds: string[]) =>
- setMeetingAccessSnapshot({
- documentId: props.id,
- userId: userId(),
- state,
- teamIds,
- });
- const meetingTeamAccess = () => {
- const snapshot = meetingAccessSnapshot();
- if (snapshot?.documentId !== props.id || snapshot.userId !== userId())
- return false;
- const teamId = currentTeamQuery.isSuccess
- ? currentTeamQuery.data?.team?.id
- : undefined;
- return !!teamId && snapshot.teamIds.includes(teamId);
- };
- const meetingAccess = (): MeetingAccessState => {
- const snapshot = meetingAccessSnapshot();
- return snapshot?.documentId === props.id && snapshot.userId === userId()
- ? snapshot.state
- : 'loading';
- };
- const canManageMeetingLinks = () =>
- props.blockAlias === 'md' &&
- props.itemType === 'document' &&
- !!userId() &&
- (props.owner ?? requests.state()?.owner) === userId();
- const meetingAccessForSharing = ():
- | MeetingAccessState
- | 'unknown'
- | undefined => {
- if (!canManageMeetingLinks()) return undefined;
- // Turning off the UI does not revoke grants. Keep known sharing visible and
- // avoid claiming privacy when the gated source cannot check saved links.
- if (meetingAccess() === 'shared') return 'shared';
- const flag = meetingNotesFlag();
- if (flag.loading) return 'loading';
- return flag.enabled ? meetingAccess() : 'unknown';
- };
// Like a document, a pipeline is shared by anyone who can edit it. Only its
// owner changes team access, which `teamShareControls` still requires.
const canSharePipeline = () =>
@@ -1661,11 +1521,7 @@ export function ShareModal(props: ShareModalProps) {
setCallRecordTeamShareCache(props.id, shared);
}
if (scope === 'NONE') {
- toast.success(
- canManageMeetingLinks()
- ? `Removed direct team access for this ${itemNoun}`
- : `Removed team access for this ${itemNoun}`
- );
+ toast.success(`Removed team access for this ${itemNoun}`);
return;
}
@@ -1700,8 +1556,6 @@ export function ShareModal(props: ShareModalProps) {
currentTeamQuery.data
? {
accessLevel: teamShareAccessLevel(),
- meetingViewAccess: canManageMeetingLinks() && meetingTeamAccess(),
- meetingAccess: meetingAccessForSharing(),
setAccessLevel: setTeamShareAccessLevel,
itemNoun:
props.blockAlias === 'snippet'
@@ -1815,9 +1669,6 @@ export function ShareModal(props: ShareModalProps) {
when={!isMobile()}
fallback={
<MobileShareDrawer
- meetingNotesEnabled={meetingNotesFlag().enabled}
- meetingAccess={meetingAccessForSharing()}
- onMeetingAccessState={setMeetingAccess}
requests={requests}
requestLevels={requestLevels()}
directPeopleIds={props.directPeopleIds}
@@ -2105,21 +1956,6 @@ export function ShareModal(props: ShareModalProps) {
</Show>
{/* Card 3: Link sharing — plain border */}
- <Show
- when={
- props.open &&
- meetingNotesFlag().enabled &&
- props.blockAlias === 'md' &&
- props.itemType === 'document' &&
- !!userId() &&
- (props.owner ?? requests.state()?.owner) === userId()
- }
- >
- <DocumentMeetingNotes
- documentId={props.id}
- onAccessState={setMeetingAccess}
- />
- </Show>
<Show
when={
props.linkSharing ||
@@ -2142,7 +1978,6 @@ export function ShareModal(props: ShareModalProps) {
props.blockAlias
)}
loading={permissionsLoading()}
- meetingAccess={meetingAccessForSharing()}
editPermissionEnabled={editPermissionEnabled()}
linkShare={linkShare()}
linkShareAccessLevel={linkShareAccessLevel()}
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index b0a7bc8296..4ed4803428 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -664,15 +664,6 @@ export const enableCalendarUi = defineFlag({
default: onInDev,
});
-// Calendar meeting notes and document-side meeting-link management. On in dev;
-// production uses PostHog's internal-user rollout. This is a UI rollout, not
-// an authorization check: saved meeting grants remain enforced by the service.
-export const enableCalendarMeetingNotes = defineFlag({
- key: 'enable-calendar-meeting-notes',
- env: 'ENABLE_CALENDAR_MEETING_NOTES',
- default: onInDev,
-});
-
// Calendar event search UI: the Search view's Calendar type (and calendar
// rows) plus the in-calendar keyword search. A sub-feature of the calendar UI
// — opening a hit needs the calendar block — so it only takes effect where
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts b/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
index 46582ed843..318a7dd61e 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/client.ts
@@ -16,20 +16,12 @@ import type {
CopyCalendarEventRequest,
CreateCalendarEventRequest,
DeleteCalendarEventParams,
- DocumentNoteLink,
- EventNotesParams,
InviteCalendarEventGuestsRequest,
- LinkEventNoteParams,
- LinkNoteRequest,
ListCalendarsResponse,
- MeetingNote,
- NoteDocumentsParams,
- NotePicker,
PrepareCalendarReplacementRequest,
RespondToJoinRequestRequest,
RsvpCalendarEventRequest,
TeamCalendarSharingBody,
- UnlinkEventNoteParams,
UpdateCalendarEventRequest,
} from './schemas';
@@ -601,169 +593,6 @@ export const inviteCalendarEventGuests = async (
} as inviteCalendarEventGuestsResponse;
};
-/**
- * @summary List notes visible through this meeting occurrence.
- */
-export type eventNotesResponse200 = {
- data: MeetingNote[];
- status: 200;
-};
-
-export type eventNotesResponseSuccess = eventNotesResponse200 & {
- headers: Headers;
-};
-
-export type eventNotesResponse = eventNotesResponseSuccess;
-
-export const getEventNotesUrl = (eventId: string, params: EventNotesParams) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString());
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0
- ? `/events/${eventId}/notes?${stringifiedParams}`
- : `/events/${eventId}/notes`;
-};
-
-export const eventNotes = async (
- eventId: string,
- params: EventNotesParams,
- options?: RequestInit
-): Promise<eventNotesResponse> => {
- const res = await fetch(getEventNotesUrl(eventId, params), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: eventNotesResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as eventNotesResponse;
-};
-
-/**
- * @summary Idempotently link a markdown document and its optional team audience.
- */
-export type linkEventNoteResponse204 = {
- data: void;
- status: 204;
-};
-
-export type linkEventNoteResponseSuccess = linkEventNoteResponse204 & {
- headers: Headers;
-};
-
-export type linkEventNoteResponse = linkEventNoteResponseSuccess;
-
-export const getLinkEventNoteUrl = (
- eventId: string,
- documentId: string,
- params: LinkEventNoteParams
-) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString());
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0
- ? `/events/${eventId}/notes/${documentId}?${stringifiedParams}`
- : `/events/${eventId}/notes/${documentId}`;
-};
-
-export const linkEventNote = async (
- eventId: string,
- documentId: string,
- linkNoteRequest: LinkNoteRequest,
- params: LinkEventNoteParams,
- options?: RequestInit
-): Promise<linkEventNoteResponse> => {
- const res = await fetch(getLinkEventNoteUrl(eventId, documentId, params), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(linkNoteRequest),
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: linkEventNoteResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as linkEventNoteResponse;
-};
-
-/**
- * @summary Remove this meeting's grant without deleting the document.
- */
-export type unlinkEventNoteResponse204 = {
- data: void;
- status: 204;
-};
-
-export type unlinkEventNoteResponseSuccess = unlinkEventNoteResponse204 & {
- headers: Headers;
-};
-
-export type unlinkEventNoteResponse = unlinkEventNoteResponseSuccess;
-
-export const getUnlinkEventNoteUrl = (
- eventId: string,
- documentId: string,
- params: UnlinkEventNoteParams
-) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString());
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0
- ? `/events/${eventId}/notes/${documentId}?${stringifiedParams}`
- : `/events/${eventId}/notes/${documentId}`;
-};
-
-export const unlinkEventNote = async (
- eventId: string,
- documentId: string,
- params: UnlinkEventNoteParams,
- options?: RequestInit
-): Promise<unlinkEventNoteResponse> => {
- const res = await fetch(getUnlinkEventNoteUrl(eventId, documentId, params), {
- ...options,
- method: 'DELETE',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: unlinkEventNoteResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as unlinkEventNoteResponse;
-};
-
/**
* @summary Resolve an authorized event's provider link for Outlook-only actions.
*/
@@ -1078,92 +907,6 @@ export const respondToJoinRequest = async (
} as respondToJoinRequestResponse;
};
-/**
- * @summary Suggest the caller's markdown documents and extra team audiences.
- */
-export type noteDocumentsResponse200 = {
- data: NotePicker;
- status: 200;
-};
-
-export type noteDocumentsResponseSuccess = noteDocumentsResponse200 & {
- headers: Headers;
-};
-
-export type noteDocumentsResponse = noteDocumentsResponseSuccess;
-
-export const getNoteDocumentsUrl = (params?: NoteDocumentsParams) => {
- const normalizedParams = new URLSearchParams();
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString());
- }
- });
-
- const stringifiedParams = normalizedParams.toString();
-
- return stringifiedParams.length > 0
- ? `/meeting-notes/documents?${stringifiedParams}`
- : `/meeting-notes/documents`;
-};
-
-export const noteDocuments = async (
- params?: NoteDocumentsParams,
- options?: RequestInit
-): Promise<noteDocumentsResponse> => {
- const res = await fetch(getNoteDocumentsUrl(params), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: noteDocumentsResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as noteDocumentsResponse;
-};
-
-/**
- * @summary List a document's visible meeting links; owners also see unavailable grants.
- */
-export type documentNoteLinksResponse200 = {
- data: DocumentNoteLink[];
- status: 200;
-};
-
-export type documentNoteLinksResponseSuccess = documentNoteLinksResponse200 & {
- headers: Headers;
-};
-
-export type documentNoteLinksResponse = documentNoteLinksResponseSuccess;
-
-export const getDocumentNoteLinksUrl = (documentId: string) => {
- return `/meeting-notes/documents/${documentId}/links`;
-};
-
-export const documentNoteLinks = async (
- documentId: string,
- options?: RequestInit
-): Promise<documentNoteLinksResponse> => {
- const res = await fetch(getDocumentNoteLinksUrl(documentId), {
- ...options,
- method: 'GET',
- });
-
- const body = [204, 205, 304].includes(res.status) ? null : await res.text();
-
- const data: documentNoteLinksResponse['data'] = body ? JSON.parse(body) : {};
- return {
- data,
- status: res.status,
- headers: res.headers,
- } as documentNoteLinksResponse;
-};
-
/**
* @summary Read saved progress without performing a provider mutation.
*/
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEvent.ts
deleted file mode 100644
index ac187507d1..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEvent.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { CalendarMentionEventDescription } from './calendarMentionEventDescription';
-import type { CalendarMentionEventJoinRequestStatus } from './calendarMentionEventJoinRequestStatus';
-import type { CalendarMentionEventLocation } from './calendarMentionEventLocation';
-import type { CalendarMentionEventOccurrenceKey } from './calendarMentionEventOccurrenceKey';
-import type { CalendarMentionEventOrganizerEmail } from './calendarMentionEventOrganizerEmail';
-import type { CalendarMentionEventOrganizerName } from './calendarMentionEventOrganizerName';
-import type { CalendarMentionEventViewerCopy } from './calendarMentionEventViewerCopy';
-import type { CalendarMentionEventViewerEventId } from './calendarMentionEventViewerEventId';
-import type { EventTime } from './eventTime';
-
-/**
- * Meeting-level fields shown in a calendar event mention preview, taken from
-the requester's own projection of the meeting, or — when the requester has
-none — from the mentioned projection a channel they belong to was given.
- */
-export interface CalendarMentionEvent {
- /**
- * Number of attendees on the previewed copy.
- * @minimum 0
- */
- attendeeCount: number;
- /** For a channel-shared preview, whether the person who shared it can
-add the requester as a guest. Always false for the requester's own
-copy. */
- canRequestToJoin?: boolean;
- /** Provider description, plain text or HTML, truncated for the preview.
-Clients must sanitize it before rendering. */
- description?: CalendarMentionEventDescription;
- /** Whether the event repeats. */
- isRecurring: boolean;
- joinRequestStatus?: CalendarMentionEventJoinRequestStatus;
- /** Location label, when set. */
- location?: CalendarMentionEventLocation;
- /** Key of the previewed instance, absent when no occurrence is
-materialized. */
- occurrenceKey?: CalendarMentionEventOccurrenceKey;
- /** Organizer email. */
- organizerEmail?: CalendarMentionEventOrganizerEmail;
- /** Organizer display name. */
- organizerName?: CalendarMentionEventOrganizerName;
- /** Time of the previewed instance: the requested occurrence when it
-exists, else the next upcoming one, else the latest past one, else the
-series start. */
- time: EventTime;
- /** Display title. */
- title: string;
- /** Entity update time of the previewed copy. */
- updatedAt: string;
- /** The calendars holding `viewer_event_id`, the canonical copy's first. */
- viewerCalendarIds?: string[];
- viewerCopy?: CalendarMentionEventViewerCopy;
- /** The requester's own event entity for the mentioned meeting. Differs
-from the mentioned id when the mention came from another attendee.
-Absent when the meeting is on none of the requester's calendars and
-they see it only because it was shared with one of their channels:
-that preview is read-only and there is no event of theirs to open. */
- viewerEventId?: CalendarMentionEventViewerEventId;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventDescription.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventDescription.ts
deleted file mode 100644
index 9a1c557eb9..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventDescription.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Provider description, plain text or HTML, truncated for the preview.
-Clients must sanitize it before rendering.
- */
-export type CalendarMentionEventDescription = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventJoinRequestStatus.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventJoinRequestStatus.ts
deleted file mode 100644
index 27b82d8f2e..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventJoinRequestStatus.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { CalendarJoinRequestStatus } from './calendarJoinRequestStatus';
-
-export type CalendarMentionEventJoinRequestStatus =
- null | CalendarJoinRequestStatus;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventLocation.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventLocation.ts
deleted file mode 100644
index 505e0e0073..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventLocation.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Location label, when set.
- */
-export type CalendarMentionEventLocation = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOccurrenceKey.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOccurrenceKey.ts
deleted file mode 100644
index 46c50a8fb6..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOccurrenceKey.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Key of the previewed instance, absent when no occurrence is
-materialized.
- */
-export type CalendarMentionEventOccurrenceKey = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerEmail.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerEmail.ts
deleted file mode 100644
index 815fb1f57b..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerEmail.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Organizer email.
- */
-export type CalendarMentionEventOrganizerEmail = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerName.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerName.ts
deleted file mode 100644
index 051a6f9091..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventOrganizerName.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Organizer display name.
- */
-export type CalendarMentionEventOrganizerName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerCopy.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerCopy.ts
deleted file mode 100644
index 8b9cddde1a..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerCopy.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { CalendarMentionViewerCopy } from './calendarMentionViewerCopy';
-
-export type CalendarMentionEventViewerCopy = null | CalendarMentionViewerCopy;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerEventId.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerEventId.ts
deleted file mode 100644
index 5ad1f4d7cc..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionEventViewerEventId.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * The requester's own event entity for the mentioned meeting. Differs
-from the mentioned id when the mention came from another attendee.
-Absent when the meeting is on none of the requester's calendars and
-they see it only because it was shared with one of their channels:
-that preview is read-only and there is no event of theirs to open.
- */
-export type CalendarMentionEventViewerEventId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionViewerCopy.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionViewerCopy.ts
deleted file mode 100644
index cea91a4ec8..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/calendarMentionViewerCopy.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * How a requester holds a mentioned meeting on their own calendar, decided
-by the copy's own inbox, the way viewer capabilities decide organizer and
-guest.
- */
-export type CalendarMentionViewerCopy =
- (typeof CalendarMentionViewerCopy)[keyof typeof CalendarMentionViewerCopy];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const CalendarMentionViewerCopy = {
- snapshot: 'snapshot',
- invitation: 'invitation',
- event: 'event',
-} as const;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts
deleted file mode 100644
index f408ec9987..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLink.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { DocumentNoteLinkEvent } from './documentNoteLinkEvent';
-import type { DocumentNoteLinkTeam } from './documentNoteLinkTeam';
-import type { DocumentNoteLinkTeamEvent } from './documentNoteLinkTeamEvent';
-
-/**
- * A visible meeting link, or an owner's durable grant they can no longer open.
- */
-export interface DocumentNoteLink {
- /** Whether the reader may resolve this exact meeting's details right now. */
- canViewMeeting: boolean;
- /** Current name of the markdown document. */
- documentName: string;
- event?: DocumentNoteLinkEvent;
- /** Linked calendar copy. */
- eventId: string;
- /** Current title, or a safe placeholder when meeting details are unavailable. */
- eventTitle: string;
- /** Original occurrence start, or `single` for a one-time meeting. */
- occurrenceKey: string;
- team?: DocumentNoteLinkTeam;
- teamEvent?: DocumentNoteLinkTeamEvent;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkEvent.ts
deleted file mode 100644
index 4a8996e2f7..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkEvent.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { CalendarMentionEvent } from './calendarMentionEvent';
-
-export type DocumentNoteLinkEvent = null | CalendarMentionEvent;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts
deleted file mode 100644
index 09e2a6a074..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeam.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { NoteTeam } from './noteTeam';
-
-export type DocumentNoteLinkTeam = null | NoteTeam;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeamEvent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeamEvent.ts
deleted file mode 100644
index 756ad2d5e8..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/documentNoteLinkTeamEvent.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamCalendarItem } from './teamCalendarItem';
-
-export type DocumentNoteLinkTeamEvent = null | TeamCalendarItem;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts
deleted file mode 100644
index 6aa872b90f..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/eventNotesParams.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type EventNotesParams = {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
index 2b00a49e8b..f752cfcad1 100644
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/index.ts
@@ -38,16 +38,6 @@ export * from './calendarGuestInputBody';
export * from './calendarJoinRequest';
export * from './calendarJoinRequestDecision';
export * from './calendarJoinRequestStatus';
-export * from './calendarMentionEvent';
-export * from './calendarMentionEventDescription';
-export * from './calendarMentionEventJoinRequestStatus';
-export * from './calendarMentionEventLocation';
-export * from './calendarMentionEventOccurrenceKey';
-export * from './calendarMentionEventOrganizerEmail';
-export * from './calendarMentionEventOrganizerName';
-export * from './calendarMentionEventViewerCopy';
-export * from './calendarMentionEventViewerEventId';
-export * from './calendarMentionViewerCopy';
export * from './calendarMutationApiError';
export * from './calendarMutationErrorCode';
export * from './calendarProvider';
@@ -74,11 +64,6 @@ export * from './createCalendarEventRequestReminders';
export * from './createCalendarEventRequestTransparency';
export * from './createCalendarEventRequestVisibility';
export * from './deleteCalendarEventParams';
-export * from './documentNoteLink';
-export * from './documentNoteLinkEvent';
-export * from './documentNoteLinkTeam';
-export * from './documentNoteLinkTeamEvent';
-export * from './eventNotesParams';
export * from './eventReminderOverride';
export * from './eventReminders';
export * from './eventStatus';
@@ -97,16 +82,7 @@ export * from './inviteCalendarEventGuestsRequestCalendarId';
export * from './inviteCalendarEventGuestsRequestInbox';
export * from './inviteCalendarEventGuestsRequestRecurrenceId';
export * from './inviteCalendarEventGuestsRequestScope';
-export * from './linkEventNoteParams';
-export * from './linkNoteRequest';
-export * from './linkNoteRequestTeamId';
export * from './listCalendarsResponse';
-export * from './meetingNote';
-export * from './meetingNoteTeam';
-export * from './noteDocument';
-export * from './noteDocumentsParams';
-export * from './notePicker';
-export * from './noteTeam';
export * from './outOfOfficeAutoDeclineMode';
export * from './outOfOfficeProperties';
export * from './outOfOfficePropertiesDeclineMessage';
@@ -127,22 +103,8 @@ export * from './rsvpCalendarEventRequestCalendarId';
export * from './rsvpCalendarEventRequestRecurrenceId';
export * from './rsvpCalendarEventRequestRespondingEmail';
export * from './rsvpCalendarEventRequestScope';
-export * from './teamCalendarContent';
-export * from './teamCalendarContentOneOf';
-export * from './teamCalendarContentOneOfKind';
-export * from './teamCalendarContentOneOfThree';
-export * from './teamCalendarContentOneOfThreeKind';
-export * from './teamCalendarDetails';
-export * from './teamCalendarDetailsConferenceUrl';
-export * from './teamCalendarDetailsDescription';
-export * from './teamCalendarDetailsLocation';
-export * from './teamCalendarDetailsOrganizerEmail';
-export * from './teamCalendarDetailsOrganizerName';
-export * from './teamCalendarItem';
-export * from './teamCalendarItemAllOf';
export * from './teamCalendarSharing';
export * from './teamCalendarSharingBody';
-export * from './unlinkEventNoteParams';
export * from './updateCalendarEventRequest';
export * from './updateCalendarEventRequestAttendees';
export * from './updateCalendarEventRequestCalendarId';
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts
deleted file mode 100644
index 8ed305d0da..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkEventNoteParams.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type LinkEventNoteParams = {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts
deleted file mode 100644
index 0aef5bab5b..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequest.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { LinkNoteRequestTeamId } from './linkNoteRequestTeamId';
-
-/**
- * Optional additional view access for one team.
- */
-export interface LinkNoteRequest {
- /** Null means the meeting audience only. */
- teamId?: LinkNoteRequestTeamId;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts
deleted file mode 100644
index 228647427b..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/linkNoteRequestTeamId.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Null means the meeting audience only.
- */
-export type LinkNoteRequestTeamId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts
deleted file mode 100644
index 0b512301e7..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNote.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { MeetingNoteTeam } from './meetingNoteTeam';
-
-/**
- * One linked document and the extra access this link grants.
- */
-export interface MeetingNote {
- /** Whether this viewer can change this document's sharing. */
- canManage: boolean;
- /** Markdown document identity. */
- documentId: string;
- /** Current document name. */
- name: string;
- team?: MeetingNoteTeam;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts
deleted file mode 100644
index 67e210f94c..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/meetingNoteTeam.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { NoteTeam } from './noteTeam';
-
-export type MeetingNoteTeam = null | NoteTeam;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts
deleted file mode 100644
index e532b93f98..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocument.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * A document available in the note picker.
- */
-export interface NoteDocument {
- /** Markdown document identity. */
- documentId: string;
- /** Current document name, never a copied title. */
- name: string;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts
deleted file mode 100644
index 150efcf598..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteDocumentsParams.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type NoteDocumentsParams = {
- /**
- * Empty returns recent documents.
- */
- query?: string;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts
deleted file mode 100644
index a5b94c1750..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/notePicker.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { NoteDocument } from './noteDocument';
-import type { NoteTeam } from './noteTeam';
-
-/**
- * Picker results; only documents whose owner is the caller are suggested.
- */
-export interface NotePicker {
- /** At most 30 matching markdown documents, most recently updated first. */
- documents: NoteDocument[];
- /** Teams the caller currently belongs to. */
- teams: NoteTeam[];
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts
deleted file mode 100644
index dc55becc9a..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/noteTeam.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * An additional team audience, separate from the meeting's audience.
- */
-export interface NoteTeam {
- /** Team identity. */
- id: string;
- /** Display name. */
- name: string;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContent.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContent.ts
deleted file mode 100644
index 9a168034d4..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContent.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamCalendarContentOneOf } from './teamCalendarContentOneOf';
-import type { TeamCalendarContentOneOfThree } from './teamCalendarContentOneOfThree';
-
-/**
- * Disjoint busy/detail shapes prevent new event fields leaking by default.
- */
-export type TeamCalendarContent =
- | TeamCalendarContentOneOf
- | TeamCalendarContentOneOfThree;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOf.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOf.ts
deleted file mode 100644
index 8b004d25b5..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOf.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamCalendarContentOneOfKind } from './teamCalendarContentOneOfKind';
-
-/**
- * No provider or event metadata.
- */
-export type TeamCalendarContentOneOf = {
- kind: TeamCalendarContentOneOfKind;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfKind.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfKind.ts
deleted file mode 100644
index 4b88ffe980..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfKind.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type TeamCalendarContentOneOfKind =
- (typeof TeamCalendarContentOneOfKind)[keyof typeof TeamCalendarContentOneOfKind];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const TeamCalendarContentOneOfKind = {
- busy: 'busy',
-} as const;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThree.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThree.ts
deleted file mode 100644
index b5b41491c3..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThree.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-import type { TeamCalendarContentOneOfThreeKind } from './teamCalendarContentOneOfThreeKind';
-import type { TeamCalendarDetails } from './teamCalendarDetails';
-
-/**
- * Explicitly authorized source content.
- */
-export type TeamCalendarContentOneOfThree = {
- /** Detail projection. */
- details: TeamCalendarDetails;
- kind: TeamCalendarContentOneOfThreeKind;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThreeKind.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThreeKind.ts
deleted file mode 100644
index 88187f095b..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarContentOneOfThreeKind.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type TeamCalendarContentOneOfThreeKind =
- (typeof TeamCalendarContentOneOfThreeKind)[keyof typeof TeamCalendarContentOneOfThreeKind];
-
-// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const TeamCalendarContentOneOfThreeKind = {
- details: 'details',
-} as const;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetails.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetails.ts
deleted file mode 100644
index b5012306a8..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetails.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { CalendarAttendee } from './calendarAttendee';
-import type { TeamCalendarDetailsConferenceUrl } from './teamCalendarDetailsConferenceUrl';
-import type { TeamCalendarDetailsDescription } from './teamCalendarDetailsDescription';
-import type { TeamCalendarDetailsLocation } from './teamCalendarDetailsLocation';
-import type { TeamCalendarDetailsOrganizerEmail } from './teamCalendarDetailsOrganizerEmail';
-import type { TeamCalendarDetailsOrganizerName } from './teamCalendarDetailsOrganizerName';
-
-/**
- * Safe details from a single authorized source.
- */
-export interface TeamCalendarDetails {
- /** Attendees; self flags are relative to the requesting viewer. */
- attendees: CalendarAttendee[];
- /** Source calendar name, shown only with details. */
- calendarName: string;
- /** Join URL, if supplied by this source. */
- conferenceUrl?: TeamCalendarDetailsConferenceUrl;
- /** Body, if supplied by this source. */
- description?: TeamCalendarDetailsDescription;
- /** Location, if supplied by this source. */
- location?: TeamCalendarDetailsLocation;
- /** Organizer address from this source. */
- organizerEmail?: TeamCalendarDetailsOrganizerEmail;
- /** Organizer name from this source. */
- organizerName?: TeamCalendarDetailsOrganizerName;
- /** Display title. */
- title: string;
-}
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsConferenceUrl.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsConferenceUrl.ts
deleted file mode 100644
index 59d3891b3c..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsConferenceUrl.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Join URL, if supplied by this source.
- */
-export type TeamCalendarDetailsConferenceUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsDescription.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsDescription.ts
deleted file mode 100644
index 74465a13c6..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsDescription.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Body, if supplied by this source.
- */
-export type TeamCalendarDetailsDescription = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsLocation.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsLocation.ts
deleted file mode 100644
index c5fc6f8b99..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsLocation.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Location, if supplied by this source.
- */
-export type TeamCalendarDetailsLocation = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerEmail.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerEmail.ts
deleted file mode 100644
index debd5b0a08..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerEmail.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Organizer address from this source.
- */
-export type TeamCalendarDetailsOrganizerEmail = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerName.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerName.ts
deleted file mode 100644
index 8053194907..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarDetailsOrganizerName.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Organizer name from this source.
- */
-export type TeamCalendarDetailsOrganizerName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItem.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItem.ts
deleted file mode 100644
index bbb14fba76..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItem.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { TeamCalendarContent } from './teamCalendarContent';
-import type { TeamCalendarItemAllOf } from './teamCalendarItemAllOf';
-
-/**
- * A read-only team calendar occurrence.
- */
-export type TeamCalendarItem = TeamCalendarContent & TeamCalendarItemAllOf;
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItemAllOf.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItemAllOf.ts
deleted file mode 100644
index 533689e4c1..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/teamCalendarItemAllOf.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-import type { EventTime } from './eventTime';
-
-export type TeamCalendarItemAllOf = {
- /** Whether this occurrence blocks the sharer's personal availability.
-A subscribed calendar's block can be shared without occupying the sharer. */
- contributesToAvailability: boolean;
- /** Stable opaque projection identity, never an event entity id. */
- id: string;
- /** The person sharing access to the source. */
- ownerId: string;
- /** Occurrence interval. */
- time: EventTime;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts b/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts
deleted file mode 100644
index 96ee8fedaa..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/generated/schemas/unlinkEventNoteParams.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * calendar_service
- * OpenAPI spec version: 0.1.0
- */
-
-export type UnlinkEventNoteParams = {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/notes.ts b/apps/web/src/lib/service-clients/service-calendar/notes.ts
deleted file mode 100644
index 4458d56f84..0000000000
--- a/apps/web/src/lib/service-clients/service-calendar/notes.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { SERVER_HOSTS } from '@core/constant/servers';
-import { fetchWithToken } from '@core/util/fetchWithToken';
-import type {
- DocumentNoteLink,
- LinkNoteRequest,
- MeetingNote,
- NotePicker,
-} from './generated/schemas';
-
-const host = SERVER_HOSTS['calendar-service'];
-
-export const calendarNotesClient = {
- documentLinks(documentId: string, signal?: AbortSignal) {
- return fetchWithToken<DocumentNoteLink[]>(
- `${host}/meeting-notes/documents/${encodeURIComponent(documentId)}/links`,
- { signal }
- );
- },
- list(eventId: string, occurrenceKey: string, signal?: AbortSignal) {
- const query = new URLSearchParams({ occurrenceKey });
- return fetchWithToken<MeetingNote[]>(
- `${host}/events/${encodeURIComponent(eventId)}/notes?${query}`,
- { signal }
- );
- },
- documents(query: string, signal?: AbortSignal) {
- return fetchWithToken<NotePicker>(
- `${host}/meeting-notes/documents?${new URLSearchParams({ query })}`,
- { signal }
- );
- },
- link(
- eventId: string,
- occurrenceKey: string,
- documentId: string,
- body: LinkNoteRequest
- ) {
- return fetchWithToken<Record<string, never>>(
- `${host}/events/${encodeURIComponent(eventId)}/notes/${encodeURIComponent(documentId)}?${new URLSearchParams({ occurrenceKey })}`,
- { method: 'PUT', body: JSON.stringify(body) }
- );
- },
- unlink(eventId: string, occurrenceKey: string, documentId: string) {
- return fetchWithToken<Record<string, never>>(
- `${host}/events/${encodeURIComponent(eventId)}/notes/${encodeURIComponent(documentId)}?${new URLSearchParams({ occurrenceKey })}`,
- { method: 'DELETE' }
- );
- },
-};
diff --git a/apps/web/src/lib/service-clients/service-calendar/openapi.json b/apps/web/src/lib/service-clients/service-calendar/openapi.json
index 52cf717875..35838d1e78 100644
--- a/apps/web/src/lib/service-clients/service-calendar/openapi.json
+++ b/apps/web/src/lib/service-clients/service-calendar/openapi.json
@@ -549,136 +549,6 @@
}
}
},
- "/events/{event_id}/notes": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "List notes visible through this meeting occurrence.",
- "operationId": "event_notes",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/MeetingNote"
- }
- }
- }
- }
- }
- }
- }
- },
- "/events/{event_id}/notes/{document_id}": {
- "put": {
- "tags": ["calendar_events"],
- "summary": "Idempotently link a markdown document and its optional team audience.",
- "operationId": "link_event_note",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/LinkNoteRequest"
- }
- }
- },
- "required": true
- },
- "responses": {
- "204": {
- "description": ""
- }
- }
- },
- "delete": {
- "tags": ["calendar_events"],
- "summary": "Remove this meeting's grant without deleting the document.",
- "operationId": "unlink_event_note",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "204": {
- "description": ""
- }
- }
- }
- },
"/events/{event_id}/provider-url": {
"get": {
"tags": ["calendar_events"],
@@ -975,68 +845,6 @@
}
}
},
- "/meeting-notes/documents": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "Suggest the caller's markdown documents and extra team audiences.",
- "operationId": "note_documents",
- "parameters": [
- {
- "name": "query",
- "in": "query",
- "description": "Empty returns recent documents.",
- "required": false,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NotePicker"
- }
- }
- }
- }
- }
- }
- },
- "/meeting-notes/documents/{document_id}/links": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "List a document's visible meeting links; owners also see unavailable grants.",
- "operationId": "document_note_links",
- "parameters": [
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/DocumentNoteLink"
- }
- }
- }
- }
- }
- }
- }
- },
"/replacements/{operation_id}": {
"get": {
"tags": ["calendar_events"],
@@ -1665,105 +1473,6 @@
"description": "Lifecycle of a request to be added as a guest of a shared event.",
"enum": ["pending", "accepted", "declined"]
},
- "CalendarMentionEvent": {
- "type": "object",
- "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given.",
- "required": [
- "title",
- "time",
- "isRecurring",
- "attendeeCount",
- "updatedAt"
- ],
- "properties": {
- "attendeeCount": {
- "type": "integer",
- "description": "Number of attendees on the previewed copy.",
- "minimum": 0
- },
- "canRequestToJoin": {
- "type": "boolean",
- "description": "For a channel-shared preview, whether the person who shared it can\nadd the requester as a guest. Always false for the requester's own\ncopy."
- },
- "description": {
- "type": ["string", "null"],
- "description": "Provider description, plain text or HTML, truncated for the preview.\nClients must sanitize it before rendering."
- },
- "isRecurring": {
- "type": "boolean",
- "description": "Whether the event repeats."
- },
- "joinRequestStatus": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarJoinRequestStatus",
- "description": "For a channel-shared preview, the requester's request to join, if any."
- }
- ]
- },
- "location": {
- "type": ["string", "null"],
- "description": "Location label, when set."
- },
- "occurrenceKey": {
- "type": ["string", "null"],
- "description": "Key of the previewed instance, absent when no occurrence is\nmaterialized."
- },
- "organizerEmail": {
- "type": ["string", "null"],
- "description": "Organizer email."
- },
- "organizerName": {
- "type": ["string", "null"],
- "description": "Organizer display name."
- },
- "time": {
- "$ref": "#/components/schemas/EventTime",
- "description": "Time of the previewed instance: the requested occurrence when it\nexists, else the next upcoming one, else the latest past one, else the\nseries start."
- },
- "title": {
- "type": "string",
- "description": "Display title."
- },
- "updatedAt": {
- "type": "string",
- "format": "date-time",
- "description": "Entity update time of the previewed copy."
- },
- "viewerCalendarIds": {
- "type": "array",
- "items": {
- "type": "string",
- "format": "uuid"
- },
- "description": "The calendars holding `viewer_event_id`, the canonical copy's first."
- },
- "viewerCopy": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarMentionViewerCopy",
- "description": "How the requester holds the meeting through `viewer_event_id`; absent\nexactly when that is."
- }
- ]
- },
- "viewerEventId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee.\nAbsent when the meeting is on none of the requester's calendars and\nthey see it only because it was shared with one of their channels:\nthat preview is read-only and there is no event of theirs to open."
- }
- }
- },
- "CalendarMentionViewerCopy": {
- "type": "string",
- "description": "How a requester holds a mentioned meeting on their own calendar, decided\nby the copy's own inbox, the way viewer capabilities decide organizer and\nguest.",
- "enum": ["snapshot", "invitation", "event"]
- },
"CalendarMutationApiError": {
"type": "object",
"description": "HTTP error body returned by calendar mutation endpoints.",
@@ -2039,73 +1748,6 @@
}
}
},
- "DocumentNoteLink": {
- "type": "object",
- "description": "A visible meeting link, or an owner's durable grant they can no longer open.",
- "required": [
- "documentName",
- "eventId",
- "occurrenceKey",
- "eventTitle",
- "canViewMeeting"
- ],
- "properties": {
- "canViewMeeting": {
- "type": "boolean",
- "description": "Whether the reader may resolve this exact meeting's details right now."
- },
- "documentName": {
- "type": "string",
- "description": "Current name of the markdown document."
- },
- "event": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarMentionEvent",
- "description": "Exact accessible calendar preview, resolved with this link's authorization snapshot."
- }
- ]
- },
- "eventId": {
- "type": "string",
- "format": "uuid",
- "description": "Linked calendar copy."
- },
- "eventTitle": {
- "type": "string",
- "description": "Current title, or a safe placeholder when meeting details are unavailable."
- },
- "occurrenceKey": {
- "type": "string",
- "description": "Original occurrence start, or `single` for a one-time meeting."
- },
- "team": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/NoteTeam",
- "description": "Independent optional team audience."
- }
- ]
- },
- "teamEvent": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/TeamCalendarItem",
- "description": "Exact, sanitized team-calendar details when the meeting is shared through a team."
- }
- ]
- }
- }
- },
"EventReminderOverride": {
"type": "object",
"description": "One reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.",
@@ -2276,17 +1918,6 @@
}
}
},
- "LinkNoteRequest": {
- "type": "object",
- "description": "Optional additional view access for one team.",
- "properties": {
- "teamId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "Null means the meeting audience only."
- }
- }
- },
"ListCalendarsResponse": {
"type": "object",
"description": "Calendars visible to the requester across connected and delegated inboxes.",
@@ -2301,88 +1932,6 @@
}
}
},
- "MeetingNote": {
- "type": "object",
- "description": "One linked document and the extra access this link grants.",
- "required": ["documentId", "name", "canManage"],
- "properties": {
- "canManage": {
- "type": "boolean",
- "description": "Whether this viewer can change this document's sharing."
- },
- "documentId": {
- "type": "string",
- "description": "Markdown document identity."
- },
- "name": {
- "type": "string",
- "description": "Current document name."
- },
- "team": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/NoteTeam",
- "description": "Optional extra team view grant."
- }
- ]
- }
- }
- },
- "NoteDocument": {
- "type": "object",
- "description": "A document available in the note picker.",
- "required": ["documentId", "name"],
- "properties": {
- "documentId": {
- "type": "string",
- "description": "Markdown document identity."
- },
- "name": {
- "type": "string",
- "description": "Current document name, never a copied title."
- }
- }
- },
- "NotePicker": {
- "type": "object",
- "description": "Picker results; only documents whose owner is the caller are suggested.",
- "required": ["documents", "teams"],
- "properties": {
- "documents": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/NoteDocument"
- },
- "description": "At most 30 matching markdown documents, most recently updated first."
- },
- "teams": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/NoteTeam"
- },
- "description": "Teams the caller currently belongs to."
- }
- }
- },
- "NoteTeam": {
- "type": "object",
- "description": "An additional team audience, separate from the meeting's audience.",
- "required": ["id", "name"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "Team identity."
- },
- "name": {
- "type": "string",
- "description": "Display name."
- }
- }
- },
"OutOfOfficeAutoDeclineMode": {
"type": "string",
"description": "How an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
@@ -2533,110 +2082,6 @@
}
}
},
- "TeamCalendarContent": {
- "oneOf": [
- {
- "type": "object",
- "description": "No provider or event metadata.",
- "required": ["kind"],
- "properties": {
- "kind": {
- "type": "string",
- "enum": ["busy"]
- }
- }
- },
- {
- "type": "object",
- "description": "Explicitly authorized source content.",
- "required": ["details", "kind"],
- "properties": {
- "details": {
- "$ref": "#/components/schemas/TeamCalendarDetails",
- "description": "Detail projection."
- },
- "kind": {
- "type": "string",
- "enum": ["details"]
- }
- }
- }
- ],
- "description": "Disjoint busy/detail shapes prevent new event fields leaking by default."
- },
- "TeamCalendarDetails": {
- "type": "object",
- "description": "Safe details from a single authorized source.",
- "required": ["title", "attendees", "calendarName"],
- "properties": {
- "attendees": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/CalendarAttendee"
- },
- "description": "Attendees; self flags are relative to the requesting viewer."
- },
- "calendarName": {
- "type": "string",
- "description": "Source calendar name, shown only with details."
- },
- "conferenceUrl": {
- "type": ["string", "null"],
- "description": "Join URL, if supplied by this source."
- },
- "description": {
- "type": ["string", "null"],
- "description": "Body, if supplied by this source."
- },
- "location": {
- "type": ["string", "null"],
- "description": "Location, if supplied by this source."
- },
- "organizerEmail": {
- "type": ["string", "null"],
- "description": "Organizer address from this source."
- },
- "organizerName": {
- "type": ["string", "null"],
- "description": "Organizer name from this source."
- },
- "title": {
- "type": "string",
- "description": "Display title."
- }
- }
- },
- "TeamCalendarItem": {
- "allOf": [
- {
- "$ref": "#/components/schemas/TeamCalendarContent",
- "description": "Authorized content variant."
- },
- {
- "type": "object",
- "required": ["id", "ownerId", "time", "contributesToAvailability"],
- "properties": {
- "contributesToAvailability": {
- "type": "boolean",
- "description": "Whether this occurrence blocks the sharer's personal availability.\nA subscribed calendar's block can be shared without occupying the sharer."
- },
- "id": {
- "type": "string",
- "description": "Stable opaque projection identity, never an event entity id."
- },
- "ownerId": {
- "type": "string",
- "description": "The person sharing access to the source."
- },
- "time": {
- "$ref": "#/components/schemas/EventTime",
- "description": "Occurrence interval."
- }
- }
- }
- ],
- "description": "A read-only team calendar occurrence."
- },
"TeamCalendarSharing": {
"type": "string",
"description": "What a user exposes through their team membership.",
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 16feb2bf66..9da033169e 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -16,7 +16,6 @@ interface ImportMetaEnv {
readonly VITE_ENABLE_REMINDERS?: string;
readonly VITE_ENABLE_ROUTINE_SHARING?: string;
readonly VITE_ENABLE_CHAT_SIDEBAR_SECTIONS?: string;
- readonly VITE_ENABLE_CALENDAR_MEETING_NOTES?: string;
readonly VITE_DISABLE_BROWSER_TURSO_CACHE?: string;
readonly VITE_ENABLE_WHATSAPP_LINKED?: string;
}
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index bac5ef9c8e..f853a83c90 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -58,7 +58,7 @@
{
"name": "calendar",
"description": "Find and manage calendar events.",
- "index": "## calendar\nFind and manage calendar events.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Calendar\nA calendar visible to the requester across their connected inboxes: a free-to-construct handle whose detail resolves from the caller's calendar list.\nExtends `MacroEntity`.\nFields: color, contributesToAvailability, emailAddress, emailLink, id, isPrimary, isSubscription, isWritable, name, syncError\n- `Calendar.setContributesToAvailability`: setContributesToAvailability(contributesToAvailability): Promise<void> — Set whether this calendar contributes to the caller's availability.\n- `Calendar.byId`: static byId(client, id): Calendar — A handle to a calendar by id.\n- `Calendar.list`: static list(client): Promise<Calendar[]> — The caller's visible calendars, primaries and writable first.\n\n### CalendarEvent\nA Macro calendar event: a handle exposing the event's synced fields and the mutations that act on it ([CalendarEvent.update](#update), [CalendarEvent.delete]...\nExtends `MacroEntity`.\nFields: attendees, calendar, description, guestPolicy, id, isReadOnly, location, recurrenceLines, status, time, title, transparency, viewerCan\n- `CalendarEvent.addToCalendar`: addToCalendar(options?): Promise<CalendarEvent> — Add a snapshot of an event shared with one of the requester's channels to one of their Google calendars, and return a handle to the synced snapshot.\n- `CalendarEvent.delete`: delete(options?): Promise<void> — Delete the event (or a scoped part of a recurring series) at its provider.\n- `CalendarEvent.ics`: ics(): Promise<string> — The event as an iCalendar (.ics) document: its series, title, description, location and organizer, never its guests or join link.\n- `CalendarEvent.inviteGuests`: inviteGuests(options): Promise<CalendarEvent> — Add guests without touching anyone already invited, and return a handle to the synced record.\n- `CalendarEvent.linkNote`: linkNote(document, occurrence, options?): Promise<CalendarNote> — Link a markdown document you own.\n- `CalendarEvent.notes`: notes(occurrence): Promise<CalendarNote[]> — Notes linked to a specific occurrence returned by calendar.occurrences().\n- `CalendarEvent.prepareReplacement`: prepareReplacement(options): Promise<CalendarReplacement> — Preview an organizer replacement without cancelling or sending invitations.\n- `CalendarEvent.providerUrl`: providerUrl(options?): Promise<string | undefined> — Open this calendar copy in its provider for actions unavailable through its API.\n- `CalendarEvent.record`: record(): Promise<calendar.CalendarEvent> — The full synced event record.\n- `CalendarEvent.rsvp`: rsvp(options): Promise<CalendarEvent> — Record the requester's RSVP and return a handle to the synced record.\n- `CalendarEvent.update`: update(options): Promise<CalendarEvent> — Update the event and return a handle to its synced record.\n- `CalendarEvent.byId`: static byId(client, id): CalendarEvent — A handle to a calendar event by id, for driving mutations.\n- `CalendarEvent.fromRecord`: static fromRecord(client, record): CalendarEvent — A handle seeded with a synced event record; reads resolve without a fetch.\n\n### CalendarNamespace (`macro.calendar`)\nThe calendar surface: every calendar the caller can see (not all of them theirs), event creation, and handles to individual events and calendars.\n- `CalendarNamespace.availabilityCalendars`: availabilityCalendars(): Promise<{ calendar: Calendar; contributesToAvailability: boolean; isPrimary: boolean; name: string; }[]> — Calendar availability settings, each referring to a typed calendar.\n- `CalendarNamespace.calendar`: calendar(id): Calendar — A handle to a calendar by id.\n- `CalendarNamespace.calendars`: calendars(): Promise<Calendar[]> — The calendars the caller can see, some possibly not theirs, primaries and writable first.\n- `CalendarNamespace.createEvent`: createEvent(options): Promise<CalendarEvent> — Create a calendar event and return a handle to its synced record.\n- `CalendarNamespace.event`: event(id): CalendarEvent — A handle to a calendar event by id, for driving mutations.\n- `CalendarNamespace.noteDocuments`: noteDocuments(query?): Promise<{ documents: { document: Document; name: string; }[]; teams: { name: string; team: Team; }[]; }> — Find up to 30 owned markdown documents for meeting notes, plus available extra team audiences.\n- `CalendarNamespace.occurrences`: occurrences(options): AsyncGenerator<{ calendarName: string | undefined; contributesToAvailability: boolean | undefined; event: CalendarEvent; inbox: string | undefined; occurrence: storage.CalendarOccurrence; role: CalendarEventRole | undefined; }, any, any> — Occurrences on every calendar the user can see: their schedule is only contributesToAvailability rows and meetings they attend; call the rest by calendarName.\n- `CalendarNamespace.replacement`: replacement(operationId): CalendarReplacement — Recover a saved replacement, including after its original event was retired.\n- `CalendarNamespace.setTeamSharing`: setTeamSharing(sharing): Promise<calendar.TeamCalendarSharing> — Replace the team calendar sharing preference.\n- `CalendarNamespace.teamOutOfOffice`: teamOutOfOffice(options): Promise<{ hasMore: boolean; items: { event: CalendarEvent; occurrenceKey: string; owner: User; time: storage.EventTime; title: string | undefined; }[]; }> — Teammates' out-of-office occurrences in a bounded viewport.\n- `CalendarNamespace.teamPage`: teamPage(options): Promise<{ items: ({ contributesToAvailability: boolean; id: string; kind: \"busy\"; owner: User; time: storage.EventTime; } | { contributesToAvailability: boolean; details: storage.TeamCalendarDetails; id: string; kind: \"details\"; owner: User; time: storage.EventTime; })[]; members: { coverage: TeamCalendarCoverage; sharing: storage.TeamCalendarSharing; user: User; }[]; nextCursor: string | undefined; }> — A page of team availability, including its roster and continuation cursor.\n- `CalendarNamespace.teamSharing`: teamSharing(): Promise<calendar.TeamCalendarSharing> — Current sharing preference for the team calendar.\n\n### CalendarNote\nA markdown document linked to one meeting occurrence, with view-only access.\nExtends `MacroEntity`.\nFields: canManage, document, event, id, name, occurrence, team\n- `CalendarNote.setTeam`: setTeam(team?): Promise<void> — Change the extra team view grant; omit the team to remove it.\n- `CalendarNote.unlink`: unlink(): Promise<void> — Remove this occurrence's link and view grants, preserving the document and other sharing.\n- `CalendarNote.forDocument`: static forDocument(client, event, occurrence, document): CalendarNote — Construct a handle for a document already linked to this occurrence.\n- `CalendarNote.fromDocumentLink`: static fromDocumentLink(client, document, link): CalendarNote — Seed an owner-visible link that can be revoked even if the meeting is unavailable.\n- `CalendarNote.fromRecord`: static fromRecord(client, event, occurrence, record): CalendarNote — Seed a handle with a record returned by the meeting-note API.\n\n### CalendarReplacement\nDurable organizer replacement, recoverable even after the original event is retired.\nFields: id\n- `CalendarReplacement.confirm`: confirm(): Promise<CalendarReplacementView> — Confirm the reviewed cancellation and reinvitation, or resume that same operation.\n- `CalendarReplacement.discard`: discard(): Promise<void> — Discard an unconfirmed preview.\n- `CalendarReplacement.status`: status(): Promise<CalendarReplacementView> — Read progress without initiating provider writes.\n\nTypes: `DeleteEventOptions`, `InviteGuestsOptions`, `RsvpEventOptions`, `UpdateEventOptions`, `CreateEventOptions`, `CalendarEventRole`\n"
+ "index": "## calendar\nFind and manage calendar events.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### Calendar\nA calendar visible to the requester across their connected inboxes: a free-to-construct handle whose detail resolves from the caller's calendar list.\nExtends `MacroEntity`.\nFields: color, contributesToAvailability, emailAddress, emailLink, id, isPrimary, isSubscription, isWritable, name, syncError\n- `Calendar.setContributesToAvailability`: setContributesToAvailability(contributesToAvailability): Promise<void> — Set whether this calendar contributes to the caller's availability.\n- `Calendar.byId`: static byId(client, id): Calendar — A handle to a calendar by id.\n- `Calendar.list`: static list(client): Promise<Calendar[]> — The caller's visible calendars, primaries and writable first.\n\n### CalendarEvent\nA Macro calendar event: a handle exposing the event's synced fields and the mutations that act on it ([CalendarEvent.update](#update), [CalendarEvent.delete]...\nExtends `MacroEntity`.\nFields: attendees, calendar, description, guestPolicy, id, isReadOnly, location, recurrenceLines, status, time, title, transparency, viewerCan\n- `CalendarEvent.addToCalendar`: addToCalendar(options?): Promise<CalendarEvent> — Add a snapshot of an event shared with one of the requester's channels to one of their Google calendars, and return a handle to the synced snapshot.\n- `CalendarEvent.delete`: delete(options?): Promise<void> — Delete the event (or a scoped part of a recurring series) at its provider.\n- `CalendarEvent.ics`: ics(): Promise<string> — The event as an iCalendar (.ics) document: its series, title, description, location and organizer, never its guests or join link.\n- `CalendarEvent.inviteGuests`: inviteGuests(options): Promise<CalendarEvent> — Add guests without touching anyone already invited, and return a handle to the synced record.\n- `CalendarEvent.prepareReplacement`: prepareReplacement(options): Promise<CalendarReplacement> — Preview an organizer replacement without cancelling or sending invitations.\n- `CalendarEvent.providerUrl`: providerUrl(options?): Promise<string | undefined> — Open this calendar copy in its provider for actions unavailable through its API.\n- `CalendarEvent.record`: record(): Promise<calendar.CalendarEvent> — The full synced event record.\n- `CalendarEvent.rsvp`: rsvp(options): Promise<CalendarEvent> — Record the requester's RSVP and return a handle to the synced record.\n- `CalendarEvent.update`: update(options): Promise<CalendarEvent> — Update the event and return a handle to its synced record.\n- `CalendarEvent.byId`: static byId(client, id): CalendarEvent — A handle to a calendar event by id, for driving mutations.\n- `CalendarEvent.fromRecord`: static fromRecord(client, record): CalendarEvent — A handle seeded with a synced event record; reads resolve without a fetch.\n\n### CalendarNamespace (`macro.calendar`)\nThe calendar surface: every calendar the caller can see (not all of them theirs), event creation, and handles to individual events and calendars.\n- `CalendarNamespace.availabilityCalendars`: availabilityCalendars(): Promise<{ calendar: Calendar; contributesToAvailability: boolean; isPrimary: boolean; name: string; }[]> — Calendar availability settings, each referring to a typed calendar.\n- `CalendarNamespace.calendar`: calendar(id): Calendar — A handle to a calendar by id.\n- `CalendarNamespace.calendars`: calendars(): Promise<Calendar[]> — The calendars the caller can see, some possibly not theirs, primaries and writable first.\n- `CalendarNamespace.createEvent`: createEvent(options): Promise<CalendarEvent> — Create a calendar event and return a handle to its synced record.\n- `CalendarNamespace.event`: event(id): CalendarEvent — A handle to a calendar event by id, for driving mutations.\n- `CalendarNamespace.occurrences`: occurrences(options): AsyncGenerator<{ calendarName: string | undefined; contributesToAvailability: boolean | undefined; event: CalendarEvent; inbox: string | undefined; occurrence: storage.CalendarOccurrence; role: CalendarEventRole | undefined; }, any, any> — Occurrences on every calendar the user can see: their schedule is only contributesToAvailability rows and meetings they attend; call the rest by calendarName.\n- `CalendarNamespace.replacement`: replacement(operationId): CalendarReplacement — Recover a saved replacement, including after its original event was retired.\n- `CalendarNamespace.setTeamSharing`: setTeamSharing(sharing): Promise<calendar.TeamCalendarSharing> — Replace the team calendar sharing preference.\n- `CalendarNamespace.teamOutOfOffice`: teamOutOfOffice(options): Promise<{ hasMore: boolean; items: { event: CalendarEvent; occurrenceKey: string; owner: User; time: storage.EventTime; title: string | undefined; }[]; }> — Teammates' out-of-office occurrences in a bounded viewport.\n- `CalendarNamespace.teamPage`: teamPage(options): Promise<{ items: ({ contributesToAvailability: boolean; id: string; kind: \"busy\"; owner: User; time: storage.EventTime; } | { contributesToAvailability: boolean; details: TeamCalendarDetails; id: string; kind: \"details\"; owner: User; time: storage.EventTime; })[]; members: { coverage: TeamCalendarCoverage; sharing: storage.TeamCalendarSharing; user: User; }[]; nextCursor: string | undefined; }> — A page of team availability, including its roster and continuation cursor.\n- `CalendarNamespace.teamSharing`: teamSharing(): Promise<calendar.TeamCalendarSharing> — Current sharing preference for the team calendar.\n\n### CalendarReplacement\nDurable organizer replacement, recoverable even after the original event is retired.\nFields: id\n- `CalendarReplacement.confirm`: confirm(): Promise<CalendarReplacementView> — Confirm the reviewed cancellation and reinvitation, or resume that same operation.\n- `CalendarReplacement.discard`: discard(): Promise<void> — Discard an unconfirmed preview.\n- `CalendarReplacement.status`: status(): Promise<CalendarReplacementView> — Read progress without initiating provider writes.\n\nTypes: `DeleteEventOptions`, `InviteGuestsOptions`, `RsvpEventOptions`, `UpdateEventOptions`, `CreateEventOptions`, `CalendarEventRole`\n"
},
{
"name": "calls",
@@ -83,7 +83,7 @@
{
"name": "documents",
"description": "Search, read, create, and manage documents and tasks.",
- "index": "## documents\nSearch, read, create, and manage documents and tasks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DocumentAnchor\nA PDF annotation scoped to its document.\nExtends `MacroEntity`.\nFields: document, id, kind, page\n- `DocumentAnchor.delete`: delete(): Promise<void> — Delete a standalone highlight annotation.\n- `DocumentAnchor.edit`: edit(options): Promise<void> — Edit a placeable comment's position and display settings.\n- `DocumentAnchor.toJSON`: toJSON(): { detail?: PdfAnchor; documentId: string; id: string; } — Serialize identity with its owning resource.\n- `DocumentAnchor.byId`: static byId(client, document, id): DocumentAnchor — Construct a document scoped annotation handle.\n- `DocumentAnchor.from`: static from(client, document, record): DocumentAnchor — Seed an annotation from a document annotation listing.\n\n### Comment\nA comment on a document: a document-parent message, addressed by its document and message UUID.\nExtends `MacroEntity`.\nFields: createdAt, documentId, id, text, updatedAt\n- `Comment.author`: author(): Promise<User> — The user who wrote this comment.\n- `Comment.delete`: delete(): Promise<void> — Delete this comment.\n- `Comment.document`: document(): Document — The document this comment is on.\n- `Comment.edit`: edit(body): Promise<Comment> — Replace the comment's text.\n- `Comment.reply`: reply(body): Promise<Comment> — Reply in this comment's thread.\n- `Comment.threadId`: threadId(): Promise<string> — The id of the thread this comment belongs to: its root, or itself for a root.\n- `Comment.byId`: static byId(client, documentId, id): Comment — A handle to a comment by id.\n- `Comment.from`: static from(client, documentId, record): Comment — Build a comment from a message record (pre-seeded, no fetch).\n\n### Document\nA Macro document.\nExtends `PropertiedEntity`.\nFields: access, branchedFrom, createdAt, deletedAt, entityType, fileType, id, name, owner, project, updatedAt, search\n- `Document.anchors`: anchors(): Promise<DocumentAnchor[]> — PDF annotations in this document.\n- `Document.branchName`: branchName(): Promise<string> — The git branch name derived for the document (task documents).\n- `Document.comment`: comment(body, opts?): Promise<Comment> — Add a comment.\n- `Document.comments`: comments(): Promise<CommentThread[]> — The document's live comment threads, each with its comments, newest thread first.\n- `Document.content`: content(): Promise<string> — Current Markdown for native documents, extracted text for PDF/Word, or raw file content for other formats.\n- `Document.copy`: copy(opts): Promise<Document> — Copy the document under a new name, optionally from a specific version.\n- `Document.createHighlight`: createHighlight(options): Promise<DocumentAnchor> — Create a standalone PDF highlight.\n- `Document.delete`: delete(opts?): Promise<void> — Delete the document.\n- `Document.githubPullRequests`: githubPullRequests(): Promise<storage.GithubPullRequest[]> — GitHub pull requests associated with the document.\n- `Document.meetingNotes`: meetingNotes(): Promise<{ eventTitle: string; note: CalendarNote; }[]> — Meeting links visible to the reader.\n- `Document.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Document.move`: move(project): Promise<void> — Move the document into a project (or out of one, with null).\n- `Document.permissionsToken`: permissionsToken(): Promise<string> — Mint a scoped permissions token.\n- `Document.prepareSave`: prepareSave(parts): Promise<PreSaveDocumentResponseData> — Prepare multipart content saving and return the service's upload instructions.\n- `Document.rename`: rename(name): Promise<void> — Rename the document.\n- `Document.restore`: restore(): Promise<void> — Restore a soft-deleted document.\n- `Document.save`: save(options): Promise<SaveDocumentResponseData> — Commit uploaded content.\n- `Document.setTeamShare`: setTeamShare(shared): Promise<void> — Share the document with the owner's team, or unshare it.\n- `Document.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Sharing configuration.\n- `Document.shortId`: shortId(): Promise<string> — The document's short id (used in compact links and branch names).\n- `Document.simpleSave`: simpleSave(): Promise<SaveDocumentResponseData> — Commit a simple document save.\n- `Document.teamShare`: teamShare(): Promise<DocumentTeamShareResponse> — Whether the document is shared with the owner's team, and which team.\n- `Document.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: Comment; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Document.toMention`: toMention(): MentionPart — MentionPart\n- `Document.version`: version(version): DocumentVersion — A handle to an immutable version.\n- `Document.webUrl`: webUrl(): string — The document's URL in the Macro web app.\n- `Document.byId`: static byId(client, id): Document — A handle to a document by id.\n- `Document.create`: static create(client, opts): Promise<Document> — Create a markdown document.\n- `Document.createSkill`: static createSkill(client, opts): Promise<Document> — Create a skill: a markdown document containing instructions that AI reads and follows when the skill is referenced in an AI input.\n- `Document.createSnippet`: static createSnippet(client, opts): Promise<Document> — Create a snippet: a reusable markdown document that can be inserted into any markdown area.\n- `Document.recent`: static recent(client, opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `Document.recentlyDeleted`: static recentlyDeleted(client): Promise<Document[]> — The user's recently soft-deleted documents.\n\n### DocumentNamespace (`macro.documents`)\n- `DocumentNamespace.byId`: byId(id): Document — A handle to a document by id.\n- `DocumentNamespace.byTeamSlug`: byTeamSlug(slug): Promise<Document> — Resolve a team task reference such as ENG-42.\n- `DocumentNamespace.create`: create(opts): Promise<Document> — Create a markdown document.\n- `DocumentNamespace.createCanvas`: createCanvas(opts): Promise<Document> — Create a native Canvas with shared content ready for reading and editing.\n- `DocumentNamespace.createSkill`: createSkill(opts): Promise<Document> — Create a skill: markdown instructions that AI reads and follows.\n- `DocumentNamespace.createSnippet`: createSnippet(opts): Promise<Document> — Create a snippet: a reusable markdown document.\n- `DocumentNamespace.createUpload`: createUpload(options): Promise<{ content: DocumentContent; contentType: string; document: Document; uploadUrl: string | undefined; }> — Reserve a binary document and return upload instructions.\n- `DocumentNamespace.recent`: recent(opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `DocumentNamespace.recentlyDeleted`: recentlyDeleted(): Promise<Document[]> — The user's recently soft-deleted documents.\n- `DocumentNamespace.search`: search(query, opts?): AsyncGenerator<Document> — Search documents by name and content, most relevant first, auto-paginated.\n- `DocumentNamespace.systemSkills`: systemSkills(): Promise<SystemSkill[]> — The built-in system skills: static AI instructions with no document behind them.\n- `DocumentNamespace.validatePermissionsToken`: validatePermissionsToken(token): Promise<{ accessLevel: storage.AccessLevel; document: Document; expiresAt: number; issuer: string; user: User | undefined; }> — Validate a permissions token, returning its document and optional user handles.\n\n### SystemSkill\nA built-in system skill: static, code-defined AI instructions that surface to AI like skill documents but have no document behind them.\nFields: id, name\n- `SystemSkill.list`: static list(client): Promise<SystemSkill[]> — The built-in system skills, in display order.\n\n### DocumentVersion\nAn immutable document version, scoped to its document.\nFields: document, id\n- `DocumentVersion.read`: read(): Promise<GetDocumentResponseData> — Version metadata and the caller's access.\n- `DocumentVersion.toJSON`: toJSON(): { documentId: string; id: number; } — Serialize only scoped identity.\n- `DocumentVersion.byId`: static byId(client, document, id): DocumentVersion — Construct a version handle.\n\nTypes: `CommentThread`\n"
+ "index": "## documents\nSearch, read, create, and manage documents and tasks.\nRead any symbol below, or one a reference names, with ReadCodeDocs.\n\n### DocumentAnchor\nA PDF annotation scoped to its document.\nExtends `MacroEntity`.\nFields: document, id, kind, page\n- `DocumentAnchor.delete`: delete(): Promise<void> — Delete a standalone highlight annotation.\n- `DocumentAnchor.edit`: edit(options): Promise<void> — Edit a placeable comment's position and display settings.\n- `DocumentAnchor.toJSON`: toJSON(): { detail?: PdfAnchor; documentId: string; id: string; } — Serialize identity with its owning resource.\n- `DocumentAnchor.byId`: static byId(client, document, id): DocumentAnchor — Construct a document scoped annotation handle.\n- `DocumentAnchor.from`: static from(client, document, record): DocumentAnchor — Seed an annotation from a document annotation listing.\n\n### Comment\nA comment on a document: a document-parent message, addressed by its document and message UUID.\nExtends `MacroEntity`.\nFields: createdAt, documentId, id, text, updatedAt\n- `Comment.author`: author(): Promise<User> — The user who wrote this comment.\n- `Comment.delete`: delete(): Promise<void> — Delete this comment.\n- `Comment.document`: document(): Document — The document this comment is on.\n- `Comment.edit`: edit(body): Promise<Comment> — Replace the comment's text.\n- `Comment.reply`: reply(body): Promise<Comment> — Reply in this comment's thread.\n- `Comment.threadId`: threadId(): Promise<string> — The id of the thread this comment belongs to: its root, or itself for a root.\n- `Comment.byId`: static byId(client, documentId, id): Comment — A handle to a comment by id.\n- `Comment.from`: static from(client, documentId, record): Comment — Build a comment from a message record (pre-seeded, no fetch).\n\n### Document\nA Macro document.\nExtends `PropertiedEntity`.\nFields: access, branchedFrom, createdAt, deletedAt, entityType, fileType, id, name, owner, project, updatedAt, search\n- `Document.anchors`: anchors(): Promise<DocumentAnchor[]> — PDF annotations in this document.\n- `Document.branchName`: branchName(): Promise<string> — The git branch name derived for the document (task documents).\n- `Document.comment`: comment(body, opts?): Promise<Comment> — Add a comment.\n- `Document.comments`: comments(): Promise<CommentThread[]> — The document's live comment threads, each with its comments, newest thread first.\n- `Document.content`: content(): Promise<string> — Current Markdown for native documents, extracted text for PDF/Word, or raw file content for other formats.\n- `Document.copy`: copy(opts): Promise<Document> — Copy the document under a new name, optionally from a specific version.\n- `Document.createHighlight`: createHighlight(options): Promise<DocumentAnchor> — Create a standalone PDF highlight.\n- `Document.delete`: delete(opts?): Promise<void> — Delete the document.\n- `Document.githubPullRequests`: githubPullRequests(): Promise<storage.GithubPullRequest[]> — GitHub pull requests associated with the document.\n- `Document.messageThreadById`: messageThreadById(id): MessageThread — A shared message thread scoped to this resource.\n- `Document.move`: move(project): Promise<void> — Move the document into a project (or out of one, with null).\n- `Document.permissionsToken`: permissionsToken(): Promise<string> — Mint a scoped permissions token.\n- `Document.prepareSave`: prepareSave(parts): Promise<PreSaveDocumentResponseData> — Prepare multipart content saving and return the service's upload instructions.\n- `Document.rename`: rename(name): Promise<void> — Rename the document.\n- `Document.restore`: restore(): Promise<void> — Restore a soft-deleted document.\n- `Document.save`: save(options): Promise<SaveDocumentResponseData> — Commit uploaded content.\n- `Document.setTeamShare`: setTeamShare(shared): Promise<void> — Share the document with the owner's team, or unshare it.\n- `Document.sharePermissions`: sharePermissions(): Promise<storage.SharePermissionV2> — Sharing configuration.\n- `Document.shortId`: shortId(): Promise<string> — The document's short id (used in compact links and branch names).\n- `Document.simpleSave`: simpleSave(): Promise<SaveDocumentResponseData> — Commit a simple document save.\n- `Document.teamShare`: teamShare(): Promise<DocumentTeamShareResponse> — Whether the document is shared with the owner's team, and which team.\n- `Document.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: Comment; type: \"message\"; })[]; nextCursor: MessageCursor | undefined; previousCursor: MessageCursor | undefined; }> — A mixed message and activity timeline page.\n- `Document.toMention`: toMention(): MentionPart — MentionPart\n- `Document.version`: version(version): DocumentVersion — A handle to an immutable version.\n- `Document.webUrl`: webUrl(): string — The document's URL in the Macro web app.\n- `Document.byId`: static byId(client, id): Document — A handle to a document by id.\n- `Document.create`: static create(client, opts): Promise<Document> — Create a markdown document.\n- `Document.createSkill`: static createSkill(client, opts): Promise<Document> — Create a skill: a markdown document containing instructions that AI reads and follows when the skill is referenced in an AI input.\n- `Document.createSnippet`: static createSnippet(client, opts): Promise<Document> — Create a snippet: a reusable markdown document that can be inserted into any markdown area.\n- `Document.recent`: static recent(client, opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `Document.recentlyDeleted`: static recentlyDeleted(client): Promise<Document[]> — The user's recently soft-deleted documents.\n\n### DocumentNamespace (`macro.documents`)\n- `DocumentNamespace.byId`: byId(id): Document — A handle to a document by id.\n- `DocumentNamespace.byTeamSlug`: byTeamSlug(slug): Promise<Document> — Resolve a team task reference such as ENG-42.\n- `DocumentNamespace.create`: create(opts): Promise<Document> — Create a markdown document.\n- `DocumentNamespace.createCanvas`: createCanvas(opts): Promise<Document> — Create a native Canvas with shared content ready for reading and editing.\n- `DocumentNamespace.createSkill`: createSkill(opts): Promise<Document> — Create a skill: markdown instructions that AI reads and follows.\n- `DocumentNamespace.createSnippet`: createSnippet(opts): Promise<Document> — Create a snippet: a reusable markdown document.\n- `DocumentNamespace.createUpload`: createUpload(options): Promise<{ content: DocumentContent; contentType: string; document: Document; uploadUrl: string | undefined; }> — Reserve a binary document and return upload instructions.\n- `DocumentNamespace.recent`: recent(opts?): AsyncGenerator<Document> — The user's recent documents, most recent first, auto-paginated.\n- `DocumentNamespace.recentlyDeleted`: recentlyDeleted(): Promise<Document[]> — The user's recently soft-deleted documents.\n- `DocumentNamespace.search`: search(query, opts?): AsyncGenerator<Document> — Search documents by name and content, most relevant first, auto-paginated.\n- `DocumentNamespace.systemSkills`: systemSkills(): Promise<SystemSkill[]> — The built-in system skills: static AI instructions with no document behind them.\n- `DocumentNamespace.validatePermissionsToken`: validatePermissionsToken(token): Promise<{ accessLevel: storage.AccessLevel; document: Document; expiresAt: number; issuer: string; user: User | undefined; }> — Validate a permissions token, returning its document and optional user handles.\n\n### SystemSkill\nA built-in system skill: static, code-defined AI instructions that surface to AI like skill documents but have no document behind them.\nFields: id, name\n- `SystemSkill.list`: static list(client): Promise<SystemSkill[]> — The built-in system skills, in display order.\n\n### DocumentVersion\nAn immutable document version, scoped to its document.\nFields: document, id\n- `DocumentVersion.read`: read(): Promise<GetDocumentResponseData> — Version metadata and the caller's access.\n- `DocumentVersion.toJSON`: toJSON(): { documentId: string; id: number; } — Serialize only scoped identity.\n- `DocumentVersion.byId`: static byId(client, document, id): DocumentVersion — Construct a version handle.\n\nTypes: `CommentThread`\n"
},
{
"name": "email",
@@ -230,16 +230,12 @@
"calendar.CalendarEvent": "# Type Alias: CalendarEvent\n\n> **CalendarEvent** = \\{ `attendees`: `calendar.CalendarAttendee`[]; `calendarId?`: `string` \\| `null`; `conferenceProvider?`: `null` \\| `calendar.ConferenceProvider`; `conferenceUrl?`: `string` \\| `null`; `createdAt`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `calendar.EventType`; `guestPolicy`: `calendar.GuestPolicy`; `icalUid`: `string`; `id`: `string`; `isReadOnly`: `boolean`; `isSnapshot`: `boolean`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `ownerId`: `string`; `recurrenceLines`: `string`[]; `reminders?`: `calendar.EventReminders`; `sequence`: `number`; `sources?`: `calendar.CalendarEventSourceContent`[]; `status`: `calendar.EventStatus`; `time`: `calendar.EventTime`; `title`: `string`; `transparency`: `calendar.EventTransparency`; `updatedAt`: `string`; `viewerCan`: `calendar.ViewerCapabilities`; `visibility`: `calendar.EventVisibility`; \\}\n\nA stable, first-class Macro calendar event entity.\n\nContent fields hold the canonical source's values: the account's primary\ncalendar copy when one is synced, else the freshest remaining copy.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `calendar.CalendarAttendee`[] | Attendees, keyed by email during persistence. |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` | Calendar the canonical source belongs to, when known. Absent only in projections stored before calendars were attributed. |\n| <a id=\"property-conferenceprovider\"></a> `conferenceProvider?` | `null` \\| `calendar.ConferenceProvider` | - |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Direct join URL when known. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | Entity creation time. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. Distinct from the organizer when someone writes onto a calendar they do not own. Omitted from stored projections when unknown so events ingested before this field still compare equal. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType?` | `calendar.EventType` | Provider event type. Skipped when it is the regular type so projections stored before event types were modeled still compare equal. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy` | `calendar.GuestPolicy` | What the organizer lets guests do: the canonical copy's values, or Google's defaults for an event synced before the policy was modeled. |\n| <a id=\"property-icaluid\"></a> `icalUid` | `string` | RFC 5545 UID used to reconcile provider and email sources. |\n| <a id=\"property-id\"></a> `id` | `string` | Macro entity identifier. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the canonical source's calendar prohibits editing it. |\n| <a id=\"property-issnapshot\"></a> `isSnapshot` | `boolean` | Whether this is a snapshot of a meeting shared with the owner, which Macro added to their calendar as a private copy: the meeting's changes never reach it, and nothing done to it reaches the meeting. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer email. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer display name. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | Macro user who owns this event entity. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | `calendar.EventReminders` | Per-user reminder configuration. Skipped when it is the provider default so projections stored before reminders were modeled still compare equal. |\n| <a id=\"property-sequence\"></a> `sequence` | `number` | Provider/iCalendar sequence number. |\n| <a id=\"property-sources\"></a> `sources?` | `calendar.CalendarEventSourceContent`[] | Content of every active copy of this event, canonical first: the primary calendar's copy, then the freshest. A client picks the copy whose calendar it is showing and falls back to the first. Populated only on the read path, so stored projections omit it. |\n| <a id=\"property-status\"></a> `status` | `calendar.EventStatus` | Event status. |\n| <a id=\"property-time\"></a> `time` | `calendar.EventTime` | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | `calendar.EventTransparency` | Availability behavior. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Entity update time. |\n| <a id=\"property-viewercan\"></a> `viewerCan` | `calendar.ViewerCapabilities` | What the viewing requester may do with the event. Resolved only on the read path, alongside each attendee's `is_self`; nothing when no viewer is known. Source projections never store it. |\n| <a id=\"property-visibility\"></a> `visibility` | `calendar.EventVisibility` | Event visibility. |",
"calendar.CalendarEventSourceContent": "# Type Alias: CalendarEventSourceContent\n\n> **CalendarEventSourceContent** = \\{ `calendarId`: `string`; `creatorEmail?`: `string` \\| `null`; `creatorName?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType`: `calendar.EventType`; `isReadOnly`: `boolean`; `location?`: `string` \\| `null`; `reminders`: `calendar.EventReminders`; `title`: `string`; `transparency`: `calendar.EventTransparency`; `visibility`: `calendar.EventVisibility`; \\}\n\nThe content one provider copy of an event carries.\n\nGoogle keeps these fields per calendar copy: a shared calendar's copy of a\nmember's event can have its own title, type, reminders, and access role.\nThe entity holds its canonical source's values. Every other copy's values\nare read from here so a client can show the copy that belongs to the\ncalendar being viewed.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-calendarid\"></a> `calendarId` | `string` | Calendar this copy lives on. |\n| <a id=\"property-creatoremail\"></a> `creatorEmail?` | `string` \\| `null` | Provider-reported creator email. |\n| <a id=\"property-creatorname\"></a> `creatorName?` | `string` \\| `null` | Provider-reported creator display name. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Optional event body. |\n| <a id=\"property-eventtype\"></a> `eventType` | `calendar.EventType` | Provider event type. |\n| <a id=\"property-isreadonly\"></a> `isReadOnly` | `boolean` | Whether the calendar's access role prohibits editing this copy. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Optional physical or virtual location label. |\n| <a id=\"property-reminders\"></a> `reminders` | `calendar.EventReminders` | Reminder configuration of this copy. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency` | `calendar.EventTransparency` | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility` | `calendar.EventVisibility` | Event visibility. |",
"CalendarGuestInputBody": "# Type Alias: CalendarGuestInputBody\n\n> **CalendarGuestInputBody** = \\{ `email`: `string`; `optional?`: `boolean`; \\}\n\nA guest added to an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-email\"></a> `email` | `string` | Guest email address. |\n| <a id=\"property-optional\"></a> `optional?` | `boolean` | Whether attendance is optional. |",
- "CalendarJoinRequestStatus": "# Type Alias: CalendarJoinRequestStatus\n\n> **CalendarJoinRequestStatus** = `\"pending\"` \\| `\"accepted\"` \\| `\"declined\"`\n\nLifecycle of a request to be added as a guest of a shared event.",
- "CalendarMentionEvent": "# Type Alias: CalendarMentionEvent\n\n> **CalendarMentionEvent** = \\{ `attendeeCount`: `number`; `canRequestToJoin?`: `boolean`; `description?`: `string` \\| `null`; `isRecurring`: `boolean`; `joinRequestStatus?`: `null` \\| `CalendarJoinRequestStatus`; `location?`: `string` \\| `null`; `occurrenceKey?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `time`: `calendar.EventTime`; `title`: `string`; `updatedAt`: `string`; `viewerCalendarIds?`: `string`[]; `viewerCopy?`: `null` \\| `CalendarMentionViewerCopy`; `viewerEventId?`: `string` \\| `null`; \\}\n\nMeeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendeecount\"></a> `attendeeCount` | `number` | Number of attendees on the previewed copy. |\n| <a id=\"property-canrequesttojoin\"></a> `canRequestToJoin?` | `boolean` | For a channel-shared preview, whether the person who shared it can add the requester as a guest. Always false for the requester's own copy. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Provider description, plain text or HTML, truncated for the preview. Clients must sanitize it before rendering. |\n| <a id=\"property-isrecurring\"></a> `isRecurring` | `boolean` | Whether the event repeats. |\n| <a id=\"property-joinrequeststatus\"></a> `joinRequestStatus?` | `null` \\| `CalendarJoinRequestStatus` | - |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location label, when set. |\n| <a id=\"property-occurrencekey\"></a> `occurrenceKey?` | `string` \\| `null` | Key of the previewed instance, absent when no occurrence is materialized. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer email. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer display name. |\n| <a id=\"property-time\"></a> `time` | `calendar.EventTime` | Time of the previewed instance: the requested occurrence when it exists, else the next upcoming one, else the latest past one, else the series start. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `string` | Entity update time of the previewed copy. |\n| <a id=\"property-viewercalendarids\"></a> `viewerCalendarIds?` | `string`[] | The calendars holding `viewer_event_id`, the canonical copy's first. |\n| <a id=\"property-viewercopy\"></a> `viewerCopy?` | `null` \\| `CalendarMentionViewerCopy` | - |\n| <a id=\"property-viewereventid\"></a> `viewerEventId?` | `string` \\| `null` | The requester's own event entity for the mentioned meeting. Differs from the mentioned id when the mention came from another attendee. Absent when the meeting is on none of the requester's calendars and they see it only because it was shared with one of their channels: that preview is read-only and there is no event of theirs to open. |",
- "CalendarMentionViewerCopy": "# Type Alias: CalendarMentionViewerCopy\n\n> **CalendarMentionViewerCopy** = `\"snapshot\"` \\| `\"invitation\"` \\| `\"event\"`\n\nHow a requester holds a mentioned meeting on their own calendar, decided\nby the copy's own inbox, the way viewer capabilities decide organizer and\nguest.",
"CalendarProvider": "# Type Alias: CalendarProvider\n\n> **CalendarProvider** = `\"google\"` \\| `\"outlook\"`\n\nProvider selected from the persisted calendar account and email binding.",
"CalendarReplacementView": "# Type Alias: CalendarReplacementView\n\n> **CalendarReplacementView** = \\{ `attendeeCount`: `number`; `completedSteps`: `number`; `event?`: `null` \\| `calendar.CalendarEvent`; `isSeries`: `boolean`; `operationId`: `string`; `providerUrl?`: `string` \\| `null`; `removeConference`: `boolean`; `replacementUrl?`: `string` \\| `null`; `status`: `ReplacementStatus`; `time`: `calendar.EventTime`; `title`: `string`; `totalSteps`: `number`; \\}\n\nSafe preview and recovery response; never exposes the opaque provider snapshot.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendeecount\"></a> `attendeeCount` | `number` | Guest count for cancellation and reinvitation confirmation. |\n| <a id=\"property-completedsteps\"></a> `completedSteps` | `number` | Number of completed provider steps. |\n| <a id=\"property-event\"></a> `event?` | `null` \\| `calendar.CalendarEvent` | - |\n| <a id=\"property-isseries\"></a> `isSeries` | `boolean` | Entire recurring series, including exceptions, is replaced. |\n| <a id=\"property-operationid\"></a> `operationId` | `string` | Use this identity when confirming or checking progress. |\n| <a id=\"property-providerurl\"></a> `providerUrl?` | `string` \\| `null` | Original event for manual review. |\n| <a id=\"property-removeconference\"></a> `removeConference` | `boolean` | The provider conference is removed. |\n| <a id=\"property-replacementurl\"></a> `replacementUrl?` | `string` \\| `null` | New provider event, when creation was confirmed. |\n| <a id=\"property-status\"></a> `status` | `ReplacementStatus` | Current durable state. |\n| <a id=\"property-time\"></a> `time` | `calendar.EventTime` | Frozen time. |\n| <a id=\"property-title\"></a> `title` | `string` | Frozen title. |\n| <a id=\"property-totalsteps\"></a> `totalSteps` | `number` | Number of provider steps in this operation. |",
"CalendarRsvpScopeParam": "# Type Alias: CalendarRsvpScopeParam\n\n> **CalendarRsvpScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an RSVP applies to.\n\nUnlike deletion there is no this-and-following variant: the provider\ncannot express a forward-scoped response, so offering one would be a\npromise sync could not keep.",
"CalendarUpdateScopeParam": "# Type Alias: CalendarUpdateScopeParam\n\n> **CalendarUpdateScopeParam** = `\"all\"` \\| `\"this_event\"`\n\nHow much of a recurring series an update applies to.\n\nLike RSVPs there is no this-and-following variant: the provider cannot\nexpress a forward-scoped edit as one write, and emulating it (truncate\nthe series, insert an edited clone) is non-atomic and re-invites the\nattendees of the clone. Compose it from a this-and-following deletion\nand a create when that shape is wanted.",
"ConferenceChange": "# Type Alias: ConferenceChange\n\n> **ConferenceChange** = `\"provider_default\"` \\| `\"microsoft_teams\"` \\| `\"google_meet\"` \\| `\"none\"`\n\nA requested change to an event's conferencing. Omitting the field leaves\nthe existing conference untouched; only these values change it.",
"calendar.ConferenceProvider": "# Type Alias: ConferenceProvider\n\n> **ConferenceProvider** = `\"microsoft_teams\"` \\| `\"google_meet\"` \\| `\"other\"`\n\nThe conferencing system backing an event's join URL.\n\nCalendars can create Google Meet or Microsoft Teams according to their\ncapabilities. Imported third-party conferences are labeled separately.\nOmitting a conference change preserves the current conference; explicit\nchanges still require provider and calendar capability validation.",
- "DocumentNoteLink": "# Type Alias: DocumentNoteLink\n\n> **DocumentNoteLink** = \\{ `canViewMeeting`: `boolean`; `documentName`: `string`; `event?`: `null` \\| `CalendarMentionEvent`; `eventId`: `string`; `eventTitle`: `string`; `occurrenceKey`: `string`; `team?`: `null` \\| `NoteTeam`; `teamEvent?`: `null` \\| `TeamCalendarItem`; \\}\n\nA visible meeting link, or an owner's durable grant they can no longer open.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canviewmeeting\"></a> `canViewMeeting` | `boolean` | Whether the reader may resolve this exact meeting's details right now. |\n| <a id=\"property-documentname\"></a> `documentName` | `string` | Current name of the markdown document. |\n| <a id=\"property-event\"></a> `event?` | `null` \\| `CalendarMentionEvent` | - |\n| <a id=\"property-eventid\"></a> `eventId` | `string` | Linked calendar copy. |\n| <a id=\"property-eventtitle\"></a> `eventTitle` | `string` | Current title, or a safe placeholder when meeting details are unavailable. |\n| <a id=\"property-occurrencekey\"></a> `occurrenceKey` | `string` | Original occurrence start, or `single` for a one-time meeting. |\n| <a id=\"property-team\"></a> `team?` | `null` \\| `NoteTeam` | - |\n| <a id=\"property-teamevent\"></a> `teamEvent?` | `null` \\| `TeamCalendarItem` | - |",
"calendar.EventReminderOverride": "# Type Alias: EventReminderOverride\n\n> **EventReminderOverride** = \\{ `method`: `string`; `minutes`: `number`; \\}\n\nOne reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-method\"></a> `method` | `string` | Provider method, stored verbatim; only `popup` fires Macro notifications. |\n| <a id=\"property-minutes\"></a> `minutes` | `number` | Minutes before the event start. |",
"calendar.EventReminders": "# Type Alias: EventReminders\n\n> **EventReminders** = \\{ `overrides?`: `calendar.EventReminderOverride`[]; `useDefault`: `boolean`; \\}\n\nPer-user reminder configuration for an event, mirroring Google's model:\neither the calendar's default reminders apply, or the explicit overrides\nreplace them entirely.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-overrides\"></a> `overrides?` | `calendar.EventReminderOverride`[] | Explicit reminders replacing the defaults when `use_default` is off. |\n| <a id=\"property-usedefault\"></a> `useDefault` | `boolean` | Whether the calendar's default reminders apply. |",
"calendar.EventStatus": "# Type Alias: EventStatus\n\n> **EventStatus** = `\"confirmed\"` \\| `\"tentative\"` \\| `\"cancelled\"`\n\nCanonical event status.",
@@ -248,14 +244,9 @@
"calendar.EventType": "# Type Alias: EventType\n\n> **EventType** = `\"default\"` \\| `\"out_of_office\"` \\| `\"focus_time\"` \\| `\"working_location\"` \\| `\"birthday\"` \\| `\"from_gmail\"`\n\nGoogle's event type: ordinary meetings versus the status-style entries\n(working location, out of office, focus time, birthdays) Google renders\nand notifies differently. Immutable at the provider after creation.",
"calendar.EventVisibility": "# Type Alias: EventVisibility\n\n> **EventVisibility** = `\"default\"` \\| `\"public\"` \\| `\"private\"` \\| `\"confidential\"`\n\nVisibility of event details.",
"calendar.GuestPolicy": "# Type Alias: GuestPolicy\n\n> **GuestPolicy** = \\{ `canInviteOthers`: `boolean`; `canModify`: `boolean`; `canSeeOtherGuests`: `boolean`; \\}\n\nThe switches an organizer sets on an event to bound what its guests may\ndo. Google omits a switch from the payload while it holds its default.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-caninviteothers\"></a> `canInviteOthers` | `boolean` | Whether guests may invite others. |\n| <a id=\"property-canmodify\"></a> `canModify` | `boolean` | Whether guests may change the event, including its guest list. |\n| <a id=\"property-canseeotherguests\"></a> `canSeeOtherGuests` | `boolean` | Whether guests may see the guest list. |",
- "MeetingNote": "# Type Alias: MeetingNote\n\n> **MeetingNote** = \\{ `canManage`: `boolean`; `documentId`: `string`; `name`: `string`; `team?`: `null` \\| `NoteTeam`; \\}\n\nOne linked document and the extra access this link grants.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-canmanage\"></a> `canManage` | `boolean` | Whether this viewer can change this document's sharing. |\n| <a id=\"property-documentid\"></a> `documentId` | `string` | Markdown document identity. |\n| <a id=\"property-name\"></a> `name` | `string` | Current document name. |\n| <a id=\"property-team\"></a> `team?` | `null` \\| `NoteTeam` | - |",
- "NoteTeam": "# Type Alias: NoteTeam\n\n> **NoteTeam** = \\{ `id`: `string`; `name`: `string`; \\}\n\nAn additional team audience, separate from the meeting's audience.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `string` | Team identity. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |",
"OutOfOfficeAutoDeclineMode": "# Type Alias: OutOfOfficeAutoDeclineMode\n\n> **OutOfOfficeAutoDeclineMode** = `\"decline_none\"` \\| `\"decline_all_conflicting_invitations\"` \\| `\"decline_only_new_conflicting_invitations\"`\n\nHow an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
"OutOfOfficeProperties": "# Type Alias: OutOfOfficeProperties\n\n> **OutOfOfficeProperties** = \\{ `autoDeclineMode?`: `OutOfOfficeAutoDeclineMode`; `declineMessage?`: `string` \\| `null`; \\}\n\nThe extra properties Google requires on an out-of-office event, mirroring\nits `outOfOfficeProperties` block. Their presence on a draft or patch is\nwhat marks the mutation as out-of-office.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-autodeclinemode\"></a> `autoDeclineMode?` | `OutOfOfficeAutoDeclineMode` | How conflicting invitations are handled while the user is out. |\n| <a id=\"property-declinemessage\"></a> `declineMessage?` | `string` \\| `null` | Message returned to organizers whose invitations are auto-declined. |",
"ReplacementStatus": "# Type Alias: ReplacementStatus\n\n> **ReplacementStatus** = `\"needs_confirmation\"` \\| `\"in_progress\"` \\| `\"complete\"`\n\nUser-visible workflow state.",
- "TeamCalendarContent": "# Type Alias: TeamCalendarContent\n\n> **TeamCalendarContent** = \\{ `kind`: `\"busy\"`; \\} \\| \\{ `details`: `calendar.TeamCalendarDetails`; `kind`: `\"details\"`; \\}\n\nDisjoint busy/detail shapes prevent new event fields leaking by default.\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"busy\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `details`: `calendar.TeamCalendarDetails`; `kind`: `\"details\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `details` | `calendar.TeamCalendarDetails` | Detail projection. |\n| `kind` | `\"details\"` | - |",
- "calendar.TeamCalendarDetails": "# Type Alias: TeamCalendarDetails\n\n> **TeamCalendarDetails** = \\{ `attendees`: `calendar.CalendarAttendee`[]; `calendarName`: `string`; `conferenceUrl?`: `string` \\| `null`; `description?`: `string` \\| `null`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `title`: `string`; \\}\n\nSafe details from a single authorized source.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `calendar.CalendarAttendee`[] | Attendees; self flags are relative to the requesting viewer. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` | Source calendar name, shown only with details. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Join URL, if supplied by this source. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Body, if supplied by this source. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location, if supplied by this source. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer address from this source. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer name from this source. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |",
- "TeamCalendarItem": "# Type Alias: TeamCalendarItem\n\n> **TeamCalendarItem** = `TeamCalendarContent` & \\{ `contributesToAvailability`: `boolean`; `id`: `string`; `ownerId`: `string`; `time`: `calendar.EventTime`; \\}\n\nA read-only team calendar occurrence.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `contributesToAvailability` | `boolean` | Whether this occurrence blocks the sharer's personal availability. A subscribed calendar's block can be shared without occupying the sharer. |\n| `id` | `string` | Stable opaque projection identity, never an event entity id. |\n| `ownerId` | `string` | The person sharing access to the source. |\n| `time` | `calendar.EventTime` | Occurrence interval. |",
"calendar.TeamCalendarSharing": "# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.",
"calendar.ViewerCapabilities": "# Type Alias: ViewerCapabilities\n\n> **ViewerCapabilities** = \\{ `editDetails`: `boolean`; `inviteGuests`: `boolean`; `organize`: `boolean`; `removeGuests`: `boolean`; `rsvp`: `boolean`; `setGuestPolicy`: `boolean`; \\}\n\nWhat the viewing requester may do with an event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-editdetails\"></a> `editDetails` | `boolean` | Change the event's details (title, time, description, conference). |\n| <a id=\"property-inviteguests\"></a> `inviteGuests` | `boolean` | Add guests. |\n| <a id=\"property-organize\"></a> `organize` | `boolean` | Act as the event's organizer: replace its whole guest list and manage its conferencing. |\n| <a id=\"property-removeguests\"></a> `removeGuests` | `boolean` | Remove guests. |\n| <a id=\"property-rsvp\"></a> `rsvp` | `boolean` | Answer the invitation. |\n| <a id=\"property-setguestpolicy\"></a> `setGuestPolicy` | `boolean` | Change the event's guest policy, which only Google calendars have. |",
"VisibleCalendar": "# Type Alias: VisibleCalendar\n\n> **VisibleCalendar** = \\{ `capabilities`: `CalendarCapabilities`; `color?`: `string` \\| `null`; `contributesToAvailability?`: `boolean`; `defaultReminders`: `calendar.EventReminderOverride`[]; `emailAddress`: `string`; `emailLinkId`: `string`; `id`: `string`; `isPrimary`: `boolean`; `isSubscription`: `boolean`; `isWritable`: `boolean`; `name`: `string`; `provider`: `CalendarProvider`; `syncError?`: `string` \\| `null`; \\}\n\nA calendar visible to a requester, listed for pickers and filters.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-capabilities\"></a> `capabilities` | `CalendarCapabilities` | Provider features available on this actual calendar. |\n| <a id=\"property-color\"></a> `color?` | `string` \\| `null` | Provider color. |\n| <a id=\"property-contributestoavailability\"></a> `contributesToAvailability?` | `boolean` | Whether this calendar counts toward the requester's busy time: their setting, by default only the primary calendars of inboxes they own. The nearest thing to \"this is the requester's own\": a provider's access role only says what they may do, on a colleague's calendar too. |\n| <a id=\"property-defaultreminders\"></a> `defaultReminders` | `calendar.EventReminderOverride`[] | Default reminders applied to events that keep `useDefault`. |\n| <a id=\"property-emailaddress\"></a> `emailAddress` | `string` | Connected inbox address, for grouping in multi-inbox pickers. |\n| <a id=\"property-emaillinkid\"></a> `emailLinkId` | `string` | Connected inbox that syncs this calendar. |\n| <a id=\"property-id\"></a> `id` | `string` | Persisted Macro calendar identifier. |\n| <a id=\"property-isprimary\"></a> `isPrimary` | `boolean` | Whether this is its account's primary calendar. |\n| <a id=\"property-issubscription\"></a> `isSubscription` | `boolean` | Whether this is one of Google's shared system calendars (holidays, birthdays) the account subscribes to rather than one a person maintains. |\n| <a id=\"property-iswritable\"></a> `isWritable` | `boolean` | Whether the grant can create and modify events on this calendar. |\n| <a id=\"property-name\"></a> `name` | `string` | Provider display name. |\n| <a id=\"property-provider\"></a> `provider` | `CalendarProvider` | Calendar provider, for display and reconnect routing. |\n| <a id=\"property-syncerror\"></a> `syncError?` | `string` \\| `null` | A persistent sync failure isolated to this calendar, surfaced so the settings row can badge it. `None` while the calendar is syncing normally or a failure has not yet crossed the persistence threshold. |",
@@ -761,7 +752,7 @@
"TableVersion": "# Type Alias: TableVersion\n\n> **TableVersion** = `number`\n\nMonotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one.",
"TakenId": "# Type Alias: TakenId\n\n> **TakenId** = \\{ `id`: `string`; `kind`: `\"table\"`; \\} \\| \\{ `id`: `string`; `kind`: `\"column\"`; \\} \\| \\{ `id`: `string`; `kind`: `\"option\"`; \\} \\| \\{ `id`: `string`; `kind`: `\"view\"`; \\}\n\nAn id a request minted for something new that already names something,\nwhich refuses the request: a retried request whose first attempt\ncommitted, or an id minted twice.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `kind`: `\"table\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A table's. |\n| `kind` | `\"table\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `kind`: `\"column\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A column's. |\n| `kind` | `\"column\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `kind`: `\"option\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An option's. |\n| `kind` | `\"option\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `kind`: `\"view\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A view's. |\n| `kind` | `\"view\"` | - |",
"TeamCalendarCoverage": "# Type Alias: TeamCalendarCoverage\n\n> **TeamCalendarCoverage** = `\"ready\"` \\| `\"unavailable\"` \\| `\"hidden\"`\n\nWhether a member's calendar projection can establish availability.",
- "storage.TeamCalendarDetails": "# Type Alias: TeamCalendarDetails\n\n> **TeamCalendarDetails** = \\{ `attendees`: `storage.CalendarAttendee`[]; `calendarName`: `string`; `conferenceUrl?`: `string` \\| `null`; `description?`: `string` \\| `null`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `title`: `string`; \\}\n\nSafe details from a single authorized source.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `storage.CalendarAttendee`[] | Attendees; self flags are relative to the requesting viewer. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` | Source calendar name, shown only with details. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Join URL, if supplied by this source. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Body, if supplied by this source. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location, if supplied by this source. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer address from this source. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer name from this source. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |",
+ "TeamCalendarDetails": "# Type Alias: TeamCalendarDetails\n\n> **TeamCalendarDetails** = \\{ `attendees`: `storage.CalendarAttendee`[]; `calendarName`: `string`; `conferenceUrl?`: `string` \\| `null`; `description?`: `string` \\| `null`; `location?`: `string` \\| `null`; `organizerEmail?`: `string` \\| `null`; `organizerName?`: `string` \\| `null`; `title`: `string`; \\}\n\nSafe details from a single authorized source.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees` | `storage.CalendarAttendee`[] | Attendees; self flags are relative to the requesting viewer. |\n| <a id=\"property-calendarname\"></a> `calendarName` | `string` | Source calendar name, shown only with details. |\n| <a id=\"property-conferenceurl\"></a> `conferenceUrl?` | `string` \\| `null` | Join URL, if supplied by this source. |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` | Body, if supplied by this source. |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` | Location, if supplied by this source. |\n| <a id=\"property-organizeremail\"></a> `organizerEmail?` | `string` \\| `null` | Organizer address from this source. |\n| <a id=\"property-organizername\"></a> `organizerName?` | `string` \\| `null` | Organizer name from this source. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |",
"storage.TeamCalendarSharing": "# Type Alias: TeamCalendarSharing\n\n> **TeamCalendarSharing** = `\"all\"` \\| `\"busy_only\"` \\| `\"none\"`\n\nWhat a user exposes through their team membership.",
"storage.TeamRole": "# Type Alias: TeamRole\n\n> **TeamRole** = `\"member\"` \\| `\"admin\"` \\| `\"owner\"`\n\nThe role a user has within a team.\n\nOrdered least to most privileged so comparisons reflect access strength.",
"TextOperator": "# Type Alias: TextOperator\n\n> **TextOperator** = `\"is\"` \\| `\"isNot\"` \\| `\"contains\"` \\| `\"doesNotContain\"` \\| `\"startsWith\"` \\| `\"endsWith\"`\n\nHow a text cell compares to a text.",
@@ -939,8 +930,6 @@
"CalendarEvent.delete": "### delete()\n\n> **delete**(`options?`): `Promise`\\<`void`\\>\n\nDelete the event (or a scoped part of a recurring series) at its provider.\n\nA meeting on more than one of the user's inboxes is one event per inbox.\nBefore deleting any of them, ask the user which inbox's copy to delete,\nthen pass that copy's `inbox`. Never choose between the user's inboxes\nyourself, whatever they look like: a test, secondary or unfamiliar address\nis still the user's own inbox. Skip the question only when the user\nalready named the inbox, or when only one copy can be deleted; then delete\nthat copy and say why. Without `inbox` the call is refused with\n`copy_choice_required`, listing each copy and the question to ask.\n\nDeleting the copy the user organizes cancels the meeting for every guest.\nDeleting a copy where they are a guest takes the meeting off that inbox's\ncalendar: on Google it also declines the invitation and tells the\norganizer, while on Outlook the organizer is not told and still sees the\ninvitation unanswered.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | `DeleteEventOptions` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"CalendarEvent.ics": "### ics()\n\n> **ics**(): `Promise`\\<`string`\\>\n\nThe event as an iCalendar (`.ics`) document: its series, title,\ndescription, location and organizer, never its guests or join link.\nAvailable for the requester's own events and ones shared with a channel\nthey belong to.\n\n#### Returns\n\n`Promise`\\<`string`\\>",
"CalendarEvent.inviteGuests": "### inviteGuests()\n\n> **inviteGuests**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nAdd guests without touching anyone already invited, and return a handle\nto the synced record.\n\nWhen the meeting is on more than one of the user's inboxes, add from the\ncopy the user organizes when there is one (it invites directly, while a\nguest's copy invites only as far as the organizer allows) and say why;\notherwise ask the user which inbox's copy to add them from. Never choose\nbetween the user's inboxes any other way, whatever they look like. Pass\nthat copy's `inbox`; without it the call is refused with\n`copy_choice_required`, listing each copy and the question to ask.\n\nThe organizer may add guests, and so may a guest the organizer lets\ninvite others (see [CalendarEvent.viewerCan](#property-viewercan)); Google emails the\nnew guests.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `InviteGuestsOptions` |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>",
- "CalendarEvent.linkNote": "### linkNote()\n\n> **linkNote**(`document`, `occurrence`, `options?`): `Promise`\\<`CalendarNote`\\>\n\nLink a markdown document you own. Meeting-detail viewers gain read access;\nan optional team gains read access too. Editing and other sharing are preserved.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `document` | `Document` |\n| `occurrence` | `storage.CalendarOccurrence` |\n| `options?` | \\{ `team?`: `Team`; \\} |\n| `options.team?` | `Team` |\n\n#### Returns\n\n`Promise`\\<`CalendarNote`\\>",
- "CalendarEvent.notes": "### notes()\n\n> **notes**(`occurrence`): `Promise`\\<`CalendarNote`[]\\>\n\nNotes linked to a specific occurrence returned by `calendar.occurrences()`.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `occurrence` | `storage.CalendarOccurrence` |\n\n#### Returns\n\n`Promise`\\<`CalendarNote`[]\\>",
"CalendarEvent.prepareReplacement": "### prepareReplacement()\n\n> **prepareReplacement**(`options`): `Promise`\\<`CalendarReplacement`\\>\n\nPreview an organizer replacement without cancelling or sending invitations.\nReview replacement.status() before explicitly calling replacement.confirm().\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | \\{ `calendar?`: `Calendar`; `recurrenceId?`: `string`; `removeConference`: `boolean`; \\} |\n| `options.calendar?` | `Calendar` |\n| `options.recurrenceId?` | `string` |\n| `options.removeConference` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`CalendarReplacement`\\>",
"CalendarEvent.providerUrl": "### providerUrl()\n\n> **providerUrl**(`options?`): `Promise`\\<`string` \\| `undefined`\\>\n\nOpen this calendar copy in its provider for actions unavailable through its API.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `calendar?`: `Calendar`; `recurrenceId?`: `string`; \\} |\n| `options.calendar?` | `Calendar` |\n| `options.recurrenceId?` | `string` |\n\n#### Returns\n\n`Promise`\\<`string` \\| `undefined`\\>",
"CalendarEvent.record": "### record()\n\n> **record**(): `Promise`\\<`calendar.CalendarEvent`\\>\n\nThe full synced event record. Available on a seeded handle (from create /\nupdate / rsvp); a bare `byId` handle throws (no fetch-by-id endpoint).\n\n#### Returns\n\n`Promise`\\<`calendar.CalendarEvent`\\>",
@@ -959,22 +948,14 @@
"CalendarNamespace.calendars": "### calendars()\n\n> **calendars**(): `Promise`\\<`Calendar`[]\\>\n\nThe calendars the caller can see, some possibly not theirs, primaries and writable first.\n\n#### Returns\n\n`Promise`\\<`Calendar`[]\\>",
"CalendarNamespace.createEvent": "### createEvent()\n\n> **createEvent**(`options`): `Promise`\\<`CalendarEvent`\\>\n\nCreate a calendar event and return a handle to its synced record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `CreateEventOptions` |\n\n#### Returns\n\n`Promise`\\<`CalendarEvent`\\>",
"CalendarNamespace.event": "### event()\n\n> **event**(`id`): `CalendarEvent`\n\nA handle to a calendar event by id, for driving mutations.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`CalendarEvent`",
- "CalendarNamespace.noteDocuments": "### noteDocuments()\n\n> **noteDocuments**(`query?`): `Promise`\\<\\{ `documents`: \\{ `document`: `Document`; `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: `Team`; \\}[]; \\}\\>\n\nFind up to 30 owned markdown documents for meeting notes, plus available extra team audiences.\n\n#### Parameters\n\n| Parameter | Type | Default value |\n| ------ | ------ | ------ |\n| `query?` | `string` | `''` |\n\n#### Returns\n\n`Promise`\\<\\{ `documents`: \\{ `document`: `Document`; `name`: `string`; \\}[]; `teams`: \\{ `name`: `string`; `team`: `Team`; \\}[]; \\}\\>",
"CalendarNamespace.occurrences": "### occurrences()\n\n> **occurrences**(`options`): `AsyncGenerator`\\<\\{ `calendarName`: `string` \\| `undefined`; `contributesToAvailability`: `boolean` \\| `undefined`; `event`: `CalendarEvent`; `inbox`: `string` \\| `undefined`; `occurrence`: `storage.CalendarOccurrence`; `role`: `CalendarEventRole` \\| `undefined`; \\}, `any`, `any`\\>\n\nOccurrences on every calendar the user can see: their schedule is only\n`contributesToAvailability` rows and meetings they attend; call the rest\nby `calendarName`. Automatically paginated within the viewport. Each names\nits calendar (`calendarName`), whether a calendar holding it is on the\nuser's schedule (`contributesToAvailability`), the address of the\nconnected inbox holding that copy of the event (`inbox`) and whether the\nuser organizes it or is a guest there (`role`, absent when neither, when\nthey can only write that calendar, or when a read-only calendar names\nthem organizer).\n\n`inbox` is the account syncing the calendar, so a colleague's calendar\nreports the user's own address; it never says whose calendar it is, and\nneither does `role`, since writing someone's calendar lets the user act\nas its organizer. Say \"your calendar\", and count a conflict or busy time,\nonly for `contributesToAvailability` rows and meetings the user attends\n(`role`), the way team availability does. Any other row is what that\ncalendar shows, not where the user is or what they are doing: \"the\nOffsites calendar has...\", or \"[email protected]'s calendar has...\" when\nthe name shows whose it is. If it does not, say you cannot tell rather\nthan guess. When one overlaps a time you suggest, mention it so the user\ncan decide, since their own other calendars read the same way.\n\nA meeting on several of the user's inboxes appears once per inbox, each\nwith its own event; describe them by inbox and role, never by id.\n\nBefore changing or deleting such a meeting, ask the user which inbox's\ncopy to change, unless they named it, only one copy can make the change,\nor you add guests from the copy they organize. Never choose between the\nuser's inboxes yourself, whatever they look like. Pass the chosen copy's\n`inbox` to its `update`, `inviteGuests` or `delete`; without it the call\nis refused with `copy_choice_required`, which names each copy's inbox and\nevent and gives the question to ask. An occurrence whose calendar is no\nlonger listed has no `inbox`; take it from that refusal.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | `Omit`\\<`ListOccurrencesData`\\[`\"query\"`\\], `\"cursor\"`\\> |\n\n#### Returns\n\n`AsyncGenerator`\\<\\{ `calendarName`: `string` \\| `undefined`; `contributesToAvailability`: `boolean` \\| `undefined`; `event`: `CalendarEvent`; `inbox`: `string` \\| `undefined`; `occurrence`: `storage.CalendarOccurrence`; `role`: `CalendarEventRole` \\| `undefined`; \\}, `any`, `any`\\>",
"CalendarNamespace.replacement": "### replacement()\n\n> **replacement**(`operationId`): `CalendarReplacement`\n\nRecover a saved replacement, including after its original event was retired.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `operationId` | `string` |\n\n#### Returns\n\n`CalendarReplacement`",
"CalendarNamespace.setTeamSharing": "### setTeamSharing()\n\n> **setTeamSharing**(`sharing`): `Promise`\\<`calendar.TeamCalendarSharing`\\>\n\nReplace the team calendar sharing preference.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `sharing` | `calendar.TeamCalendarSharing` |\n\n#### Returns\n\n`Promise`\\<`calendar.TeamCalendarSharing`\\>",
"CalendarNamespace.teamOutOfOffice": "### teamOutOfOffice()\n\n> **teamOutOfOffice**(`options`): `Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: `CalendarEvent`; `occurrenceKey`: `string`; `owner`: `User`; `time`: `storage.EventTime`; `title`: `string` \\| `undefined`; \\}[]; \\}\\>\n\nTeammates' out-of-office occurrences in a bounded viewport. Check hasMore for truncation.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `end`: `string`; `endDate?`: `string`; `limit?`: `number`; `start`: `string`; `startDate?`: `string`; \\} | - |\n| `options.end` | `string` | Exclusive UTC viewport end. |\n| `options.endDate?` | `string` | Exclusive local date boundary for all-day events. |\n| `options.limit?` | `number` | Maximum number of occurrences, from 1 through 2,000. |\n| `options.start` | `string` | Inclusive UTC viewport start. |\n| `options.startDate?` | `string` | Inclusive local date boundary for all-day events. |\n\n#### Returns\n\n`Promise`\\<\\{ `hasMore`: `boolean`; `items`: \\{ `event`: `CalendarEvent`; `occurrenceKey`: `string`; `owner`: `User`; `time`: `storage.EventTime`; `title`: `string` \\| `undefined`; \\}[]; \\}\\>",
- "CalendarNamespace.teamPage": "### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: `User`; `time`: `storage.EventTime`; \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: `storage.TeamCalendarDetails`; `id`: `string`; `kind`: `\"details\"`; `owner`: `User`; `time`: `storage.EventTime`; \\})[]; `members`: \\{ `coverage`: `TeamCalendarCoverage`; `sharing`: `storage.TeamCalendarSharing`; `user`: `User`; \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: `User`; `time`: `storage.EventTime`; \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: `storage.TeamCalendarDetails`; `id`: `string`; `kind`: `\"details\"`; `owner`: `User`; `time`: `storage.EventTime`; \\})[]; `members`: \\{ `coverage`: `TeamCalendarCoverage`; `sharing`: `storage.TeamCalendarSharing`; `user`: `User`; \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>",
+ "CalendarNamespace.teamPage": "### teamPage()\n\n> **teamPage**(`options`): `Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: `User`; `time`: `storage.EventTime`; \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: `TeamCalendarDetails`; `id`: `string`; `kind`: `\"details\"`; `owner`: `User`; `time`: `storage.EventTime`; \\})[]; `members`: \\{ `coverage`: `TeamCalendarCoverage`; `sharing`: `storage.TeamCalendarSharing`; `user`: `User`; \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>\n\nA page of team availability, including its roster and continuation cursor.\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `options` | \\{ `cursor?`: `string` \\| `null`; `end`: `string`; `limit?`: `number` \\| `null`; `start`: `string`; \\} | - |\n| `options.cursor?` | `string` \\| `null` | Continuation returned by the preceding page. |\n| `options.end` | `string` | Exclusive instant. |\n| `options.limit?` | `number` \\| `null` | Maximum source occurrences, at most 2,000. Zero returns the roster only. |\n| `options.start` | `string` | Inclusive instant. |\n\n#### Returns\n\n`Promise`\\<\\{ `items`: (\\{ `contributesToAvailability`: `boolean`; `id`: `string`; `kind`: `\"busy\"`; `owner`: `User`; `time`: `storage.EventTime`; \\} \\| \\{ `contributesToAvailability`: `boolean`; `details`: `TeamCalendarDetails`; `id`: `string`; `kind`: `\"details\"`; `owner`: `User`; `time`: `storage.EventTime`; \\})[]; `members`: \\{ `coverage`: `TeamCalendarCoverage`; `sharing`: `storage.TeamCalendarSharing`; `user`: `User`; \\}[]; `nextCursor`: `string` \\| `undefined`; \\}\\>",
"CalendarNamespace.teamSharing": "### teamSharing()\n\n> **teamSharing**(): `Promise`\\<`calendar.TeamCalendarSharing`\\>\n\nCurrent sharing preference for the team calendar.\n\n#### Returns\n\n`Promise`\\<`calendar.TeamCalendarSharing`\\>",
"CreateEventOptions": "# Interface: CreateEventOptions\n\nFields for a new calendar event.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attendees\"></a> `attendees?` | `CalendarAttendeeInputBody`[] | Invited attendees. |\n| <a id=\"property-calendar\"></a> `calendar?` | `Calendar` | Exact calendar to create the event on; takes precedence over the inbox default. |\n| <a id=\"property-conference\"></a> `conference?` | `ConferenceChange` | Conference to attach; omit to create the event without one. |\n| <a id=\"property-description\"></a> `description?` | `string` | Optional event body. |\n| <a id=\"property-emaillink\"></a> `emailLink?` | `Link` | Connected inbox whose primary calendar receives the event; defaults to the requester's primary inbox. |\n| <a id=\"property-guestpolicy\"></a> `guestPolicy?` | `calendar.GuestPolicy` | What guests may do; omit for Google's defaults. Google calendars only. |\n| <a id=\"property-location\"></a> `location?` | `string` | Optional location label. |\n| <a id=\"property-macrocall\"></a> `macroCall?` | `boolean` | Mint a Macro call with the event; its join link lands in the description and location. Cannot be combined with `conference`. |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | `OutOfOfficeProperties` | Out-of-office properties; present to create an out-of-office event. |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] | Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). |\n| <a id=\"property-reminders\"></a> `reminders?` | `calendar.EventReminders` | Reminder configuration; omit to keep the calendar defaults. |\n| <a id=\"property-time\"></a> `time` | `calendar.EventTime` | Timed or all-day shape. |\n| <a id=\"property-title\"></a> `title` | `string` | Display title. |\n| <a id=\"property-transparency\"></a> `transparency?` | `calendar.EventTransparency` | Availability behavior. |\n| <a id=\"property-visibility\"></a> `visibility?` | `calendar.EventVisibility` | Event visibility. |",
"CalendarEventRole": "# Type Alias: CalendarEventRole\n\n> **CalendarEventRole** = `\"organizer\"` \\| `\"guest\"`\n\nWhat the user is on one copy of an event, through the inbox holding it:\nits organizer (or the owner of an event without guests), or a guest. Being\nable to write someone else's calendar makes them neither, and neither does\na read-only calendar naming them organizer; `viewerCan` says what they may\ndo there.",
- "CalendarNote": "# Class: CalendarNote\n\nA markdown document linked to one meeting occurrence, with view-only access.\n\n## Extends\n\n- `MacroEntity`\\<`MeetingNote`\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-canmanage\"></a> `canManage` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the caller may change this link's sharing. | - |\n| <a id=\"property-document\"></a> `document` | `readonly` | () => `Promise`\\<`Document`\\> | The original markdown document; unlinking never deletes it. | - |\n| <a id=\"property-event\"></a> `event` | `readonly` | `CalendarEvent` | - | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `MacroEntity.id` |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Current document name. | - |\n| <a id=\"property-occurrence\"></a> `occurrence` | `readonly` | `Pick`\\<`storage.CalendarOccurrence`, `\"eventId\"` \\| `\"occurrenceKey\"`\\> | - | - |\n| <a id=\"property-team\"></a> `team` | `readonly` | () => `Promise`\\<`Team` \\| `undefined`\\> | Optional extra team audience. Meeting-detail viewers already have view access. | - |",
- "CalendarNote.setTeam": "### setTeam()\n\n> **setTeam**(`team?`): `Promise`\\<`void`\\>\n\nChange the extra team view grant; omit the team to remove it. Requires document ownership.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `team?` | `Team` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "CalendarNote.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `MeetingNote`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `MeetingNote`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `MeetingNote` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
- "CalendarNote.unlink": "### unlink()\n\n> **unlink**(): `Promise`\\<`void`\\>\n\nRemove this occurrence's link and view grants, preserving the document and other sharing.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
- "CalendarNote.forDocument": "### forDocument()\n\n> `static` **forDocument**(`client`, `event`, `occurrence`, `document`): `CalendarNote`\n\nConstruct a handle for a document already linked to this occurrence.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `event` | `CalendarEvent` |\n| `occurrence` | `storage.CalendarOccurrence` |\n| `document` | `Document` |\n\n#### Returns\n\n`CalendarNote`",
- "CalendarNote.fromDocumentLink": "### fromDocumentLink()\n\n> `static` **fromDocumentLink**(`client`, `document`, `link`): `CalendarNote`\n\nSeed an owner-visible link that can be revoked even if the meeting is unavailable.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `document` | `Document` |\n| `link` | `DocumentNoteLink` |\n\n#### Returns\n\n`CalendarNote`",
- "CalendarNote.fromRecord": "### fromRecord()\n\n> `static` **fromRecord**(`client`, `event`, `occurrence`, `record`): `CalendarNote`\n\nSeed a handle with a record returned by the meeting-note API.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `event` | `CalendarEvent` |\n| `occurrence` | `storage.CalendarOccurrence` |\n| `record` | `MeetingNote` |\n\n#### Returns\n\n`CalendarNote`",
"CalendarReplacement": "# Class: CalendarReplacement\n\nDurable organizer replacement, recoverable even after the original event is retired.\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` |",
"CalendarReplacement.confirm": "### confirm()\n\n> **confirm**(): `Promise`\\<`CalendarReplacementView`\\>\n\nConfirm the reviewed cancellation and reinvitation, or resume that same operation.\nPresent the preview and obtain the organizer's confirmation before the first call.\n\n#### Returns\n\n`Promise`\\<`CalendarReplacementView`\\>",
"CalendarReplacement.discard": "### discard()\n\n> **discard**(): `Promise`\\<`void`\\>\n\nDiscard an unconfirmed preview. Confirmed operations must be recovered, not discarded.\n\n#### Returns\n\n`Promise`\\<`void`\\>",
@@ -1315,7 +1296,6 @@
"Document.deleteProperty": "### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | `EntityPropertyWithDefinition` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`PropertiedEntity.deleteProperty`",
"Document.favorite": "### favorite()\n\n> **favorite**(): `Promise`\\<`Document`\\>\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`\\<`Document`\\>\n\n#### Inherited from\n\n`PropertiedEntity.favorite`",
"Document.githubPullRequests": "### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<`storage.GithubPullRequest`[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<`storage.GithubPullRequest`[]\\>",
- "Document.meetingNotes": "### meetingNotes()\n\n> **meetingNotes**(): `Promise`\\<\\{ `eventTitle`: `string`; `note`: `CalendarNote`; \\}[]\\>\n\nMeeting links visible to the reader. Owners also receive unavailable grants and may unlink them to revoke meeting/team access.\n\n#### Returns\n\n`Promise`\\<\\{ `eventTitle`: `string`; `note`: `CalendarNote`; \\}[]\\>",
"Document.messageThreadById": "### messageThreadById()\n\n> **messageThreadById**(`id`): `MessageThread`\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`MessageThread`",
"Document.move": "### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | `Project` \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>",
"Document.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`PropertiedEntity.permission`",
@@ -1503,7 +1483,7 @@
"FavoritableEntity.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\"`; \\}\\>",
"FavoritableEntity.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |\n\n#### Inherited from\n\n`MacroEntity.toJSON`",
"FavoritableEntity.unfavorite": "### unfavorite()\n\n> **unfavorite**(): `Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\nRemove this entity from the user's favorites. Returns this handle for chaining.\n\n#### Returns\n\n`Promise`\\<`FavoritableEntity`\\<`Detail`\\>\\>\n\n#### Implementation of\n\n`Favoritable.unfavorite`",
- "MacroEntity": "# Abstract Class: MacroEntity\\<Detail\\>\n\nBase for entity handles: a free-to-construct `(client, id)` pair whose\ndetail record loads lazily on first field access and is dropped after any\nmutation. Subclasses implement fetch and build their surface from\nfield and mutate.\n\n## Extended by\n\n- `AgentSession`\n- `CodeExecution`\n- `SessionReview`\n- `Agent`\n- `UserApiKey`\n- `Calendar`\n- `CalendarEvent`\n- `CalendarNote`\n- `CallMessage`\n- `ChatMessage`\n- `CrmComment`\n- `CrmPipeline`\n- `PipelineTable`\n- `PipelineRow`\n- `PipelineColumn`\n- `Database`\n- `DocumentAnchor`\n- `Comment`\n- `EmailAttachment`\n- `EmailFilter`\n- `Label`\n- `Link`\n- `EmailMessage`\n- `FavoritableEntity`\n- `ExternalChatMessage`\n- `ExternalChatSend`\n- `Form`\n- `GithubPullRequest`\n- `Harness`\n- `HarnessPairing`\n- `Initiative`\n- `Meeting`\n- `MessageThread`\n- `Notification`\n- `Routine`\n- `AccessRequest`\n- `Team`\n- `Webhook`\n- `WhatsAppAccount`\n- `WhatsAppChat`\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` |",
+ "MacroEntity": "# Abstract Class: MacroEntity\\<Detail\\>\n\nBase for entity handles: a free-to-construct `(client, id)` pair whose\ndetail record loads lazily on first field access and is dropped after any\nmutation. Subclasses implement fetch and build their surface from\nfield and mutate.\n\n## Extended by\n\n- `AgentSession`\n- `CodeExecution`\n- `SessionReview`\n- `Agent`\n- `UserApiKey`\n- `Calendar`\n- `CalendarEvent`\n- `CallMessage`\n- `ChatMessage`\n- `CrmComment`\n- `CrmPipeline`\n- `PipelineTable`\n- `PipelineRow`\n- `PipelineColumn`\n- `Database`\n- `DocumentAnchor`\n- `Comment`\n- `EmailAttachment`\n- `EmailFilter`\n- `Label`\n- `Link`\n- `EmailMessage`\n- `FavoritableEntity`\n- `ExternalChatMessage`\n- `ExternalChatSend`\n- `Form`\n- `GithubPullRequest`\n- `Harness`\n- `HarnessPairing`\n- `Initiative`\n- `Meeting`\n- `MessageThread`\n- `Notification`\n- `Routine`\n- `AccessRequest`\n- `Team`\n- `Webhook`\n- `WhatsAppAccount`\n- `WhatsAppChat`\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Properties\n\n| Property | Modifier | Type |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` |",
"MacroEntity.toJSON": "### toJSON()\n\n> **toJSON**(): \\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: `Detail`; `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | `Detail` |\n| `id` | `string` |",
"PropertiedEntity": "# Abstract Class: PropertiedEntity\\<Detail\\>\n\nA favoritable entity that also carries user-defined properties.\n\n## Extends\n\n- `FavoritableEntity`\\<`Detail`\\>\n\n## Extended by\n\n- `Channel`\n- `Chat`\n- `Company`\n- `Document`\n- `EmailThread`\n- `Project`\n- `User`\n\n## Type Parameters\n\n| Type Parameter |\n| ------ |\n| <a id=\"type-parameter-detail\"></a> `Detail` |\n\n## Implements\n\n- `Propertied`\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-entitytype\"></a> `entityType` | `abstract readonly` | `\"project\"` \\| `\"user\"` \\| `\"team\"` \\| `\"chat\"` \\| `\"channel\"` \\| `\"channel_message\"` \\| `\"document\"` \\| `\"email_thread\"` \\| `\"calendar_event\"` \\| `\"call\"` \\| `\"foreign_entity\"` \\| `\"static_file\"` \\| `\"crm_company\"` \\| `\"crm_contact\"` \\| `\"crm_pipeline\"` \\| `\"reminder\"` \\| `\"skill\"` \\| `\"agent_session\"` \\| `\"scheduled_action\"` \\| `\"initiative\"` \\| `\"database\"` \\| `\"database_row\"` \\| `\"form\"` \\| `\"external_chat\"` | How the entity-addressed APIs (favorites) identify this entity's type. | `FavoritableEntity.entityType` |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | `FavoritableEntity.id` |",
"PropertiedEntity.deleteProperty": "### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | `EntityPropertyWithDefinition` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Implementation of\n\n`Propertied.deleteProperty`",
@@ -1856,7 +1836,6 @@
"Task.deleteProperty": "### deleteProperty()\n\n> **deleteProperty**(`assignment`): `Promise`\\<`void`\\>\n\nRemove a property from this entity, given its [properties](#properties) entry.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `assignment` | `EntityPropertyWithDefinition` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`Document.deleteProperty`",
"Task.favorite": "### favorite()\n\n> **favorite**(): `Promise`\\<`Task`\\>\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`\\<`Task`\\>\n\n#### Inherited from\n\n`Document.favorite`",
"Task.githubPullRequests": "### githubPullRequests()\n\n> **githubPullRequests**(): `Promise`\\<`storage.GithubPullRequest`[]\\>\n\nGitHub pull requests associated with the document.\n\n#### Returns\n\n`Promise`\\<`storage.GithubPullRequest`[]\\>\n\n#### Inherited from\n\n`Document.githubPullRequests`",
- "Task.meetingNotes": "### meetingNotes()\n\n> **meetingNotes**(): `Promise`\\<\\{ `eventTitle`: `string`; `note`: `CalendarNote`; \\}[]\\>\n\nMeeting links visible to the reader. Owners also receive unavailable grants and may unlink them to revoke meeting/team access.\n\n#### Returns\n\n`Promise`\\<\\{ `eventTitle`: `string`; `note`: `CalendarNote`; \\}[]\\>\n\n#### Inherited from\n\n`Document.meetingNotes`",
"Task.messageThreadById": "### messageThreadById()\n\n> **messageThreadById**(`id`): `MessageThread`\n\nA shared message thread scoped to this resource.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n`MessageThread`\n\n#### Inherited from\n\n`Document.messageThreadById`",
"Task.move": "### move()\n\n> **move**(`project`): `Promise`\\<`void`\\>\n\nMove the document into a project (or out of one, with `null`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `project` | `Project` \\| `null` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n#### Inherited from\n\n`Document.move`",
"Task.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`Document.permission`",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 741251bf27..6966f8fca7 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -164,16 +164,11 @@
"calendar.updateCalendarEvent": "Update Calendar Event",
"calendar.copyCalendarEvent": "Copy Calendar Event",
"calendar.inviteCalendarEventGuests": "Invite Calendar Event Guests",
- "calendar.eventNotes": "Event Notes",
- "calendar.unlinkEventNote": "Unlink Event Note",
- "calendar.linkEventNote": "Link Event Note",
"calendar.calendarEventProviderUrl": "Calendar Event Provider Url",
"calendar.prepareCalendarReplacement": "Prepare Calendar Replacement",
"calendar.rsvpCalendarEvent": "Rsvp Calendar Event",
"calendar.healthHandler": "Health",
"calendar.respondToJoinRequest": "Respond To Join Request",
- "calendar.noteDocuments": "Note Documents",
- "calendar.documentNoteLinks": "Document Note Links",
"calendar.discardCalendarReplacement": "Discard Calendar Replacement",
"calendar.calendarReplacementStatus": "Calendar Replacement Status",
"calendar.confirmCalendarReplacement": "Confirm Calendar Replacement",
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 13afeaab3d..00571a1d8a 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -15,8 +15,6 @@ reminder dispatch, team availability, and provider/Postgres persistence.
- `src/domain/capabilities.rs`: Google's organizer-set `GuestPolicy` and the
`ViewerCapabilities` every read surface exposes as `viewerCan`.
- `src/domain/team_availability.rs` + `src/domain/team.rs`: team sharing/availability.
-- `src/domain/notes.rs`, `src/outbound/pg_notes.rs`, `src/inbound/notes_router.rs`:
- occurrence-scoped markdown links and optional team view access (feature `notes`).
- `src/outbound/google.rs`, `src/outbound/pg.rs`: Google Calendar and Postgres adapters.
- `src/outbound/pg/outlook.rs`: durable Outlook synchronization; preserve
provider-specific coverage on discovery.
@@ -52,17 +50,9 @@ reminder dispatch, team availability, and provider/Postgres persistence.
## Checks
- `cargo test -p calendar_events` (`SQLX_OFFLINE` unset).
-- `cargo test -p calendar_events --features notes,postgres` covers meeting-note
- policy and its document-access integration against a migrated local MacroDB.
## Gotchas
-- Keep note links separate from sync-owned occurrence rows; require a live
- occurrence and corroborated inbox copies for inherited view access. A document
- owner can unlink after losing meeting access. Document readers can discover
- only links whose meeting details they can currently see; owners also retain
- unavailable links for revocation. See
- [meeting-note access](../../docs/architecture/calendar-meeting-notes.md).
- `CalendarEvent` is the stable Macro entity; external calendars and email
invitations are sources feeding it, and recurrence instances are queryable
occurrence projections, not separate events — don't model them as new entities.
@@ -236,8 +226,7 @@ reminder dispatch, team availability, and provider/Postgres persistence.
`ReadCalendarEvent` (`src/inbound/toolset/read_calendar_event.rs`), which goes
through `mention_previews`: the hover card's visibility and fields. A preview
that falls back to a channel share loses its Macro call there, in the
- repository so that meeting-note references (`reference_previews`) get the
- same, and before the description cap, since the join line closes the
+ repository and before the description cap, since the join line closes the
description. Whoever resolves to their own copy keeps it: the card's Join
button reads the link from the preview. Only the generated Macro call goes;
join text a provider wrote into the body, as a Teams invitation's, stays, as
diff --git a/crates/calendar_events/Cargo.toml b/crates/calendar_events/Cargo.toml
index 9c9c3cff6f..16178e5bde 100644
--- a/crates/calendar_events/Cargo.toml
+++ b/crates/calendar_events/Cargo.toml
@@ -6,7 +6,6 @@ version = "0.1.0"
[features]
default = []
-notes = ["dep:entity_access"]
outlook = ["dep:tokio"]
# The AI toolset adapter exposing calendar CRUD to agents.
ai_tools = ["dep:ai_toolset", "dep:anyhow", "dep:async-trait", "dep:schemars"]
@@ -46,7 +45,6 @@ call = { path = "../call", default-features = false, features = [
chrono = { workspace = true }
chrono-tz = { workspace = true }
email_utils = { path = "../email_utils" }
-entity_access = { path = "../entity_access", default-features = false, features = ["ports"], optional = true }
futures = { workspace = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
@@ -75,7 +73,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
wiremock = { workspace = true }
-entity_access = { path = "../entity_access", default-features = false, features = ["outbound", "ports"] }
macro_db_migrator = { path = "../macro_db_migrator" }
macro_user_id = { path = "../macro_user_id" }
tokio = { workspace = true }
diff --git a/crates/calendar_events/src/domain/mod.rs b/crates/calendar_events/src/domain/mod.rs
index 8a92e4fe7e..84df8fa550 100644
--- a/crates/calendar_events/src/domain/mod.rs
+++ b/crates/calendar_events/src/domain/mod.rs
@@ -25,9 +25,6 @@ pub mod meeting_links;
pub mod models;
/// User-initiated calendar mutation policy.
pub mod mutations;
-/// Markdown documents linked to a meeting occurrence.
-#[cfg(feature = "notes")]
-pub mod notes;
/// Domain ports.
pub mod ports;
/// Calendar reminder dispatch policy.
diff --git a/crates/calendar_events/src/domain/notes.rs b/crates/calendar_events/src/domain/notes.rs
deleted file mode 100644
index e8e87d4dde..0000000000
--- a/crates/calendar_events/src/domain/notes.rs
+++ /dev/null
@@ -1,416 +0,0 @@
-//! Meeting-note links and their view-only, live audience.
-
-use super::models::{CalendarMentionEvent, CalendarMentionPreview};
-use super::team::{
- TeamCalendarContent, TeamCalendarItem, TeamCalendarSharing, TeamSourceOccurrence,
- project_team_source,
-};
-use entity_access::domain::models::{
- EntityAccessReceipt, EntityType, OwnerAccessLevel, ViewAccessLevel,
-};
-use serde::{Deserialize, Serialize};
-use uuid::Uuid;
-
-/// One occurrence, shared across the calendar copies of the same meeting.
-#[derive(Clone, Debug)]
-pub struct NoteTarget {
- /// A calendar copy the caller can see.
- pub event_id: Uuid,
- /// Calendar occurrence key; one-time meetings normalize to a stable event key.
- pub occurrence_key: String,
-}
-
-/// An additional team audience, separate from the meeting's audience.
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct NoteTeam {
- /// Team identity.
- pub id: Uuid,
- /// Display name.
- pub name: String,
-}
-
-/// A document available in the note picker.
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct NoteDocument {
- /// Markdown document identity.
- pub document_id: String,
- /// Current document name, never a copied title.
- pub name: String,
-}
-
-/// One linked document and the extra access this link grants.
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct MeetingNote {
- /// Markdown document identity.
- pub document_id: String,
- /// Current document name.
- pub name: String,
- /// Optional extra team view grant.
- pub team: Option<NoteTeam>,
- /// Whether this viewer can change this document's sharing.
- pub can_manage: bool,
-}
-
-/// Picker results; only documents whose owner is the caller are suggested.
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct NotePicker {
- /// At most 30 matching markdown documents, most recently updated first.
- pub documents: Vec<NoteDocument>,
- /// Teams the caller currently belongs to.
- pub teams: Vec<NoteTeam>,
-}
-
-/// A visible meeting link, or an owner's durable grant they can no longer open.
-#[derive(Clone, Debug, Serialize, Deserialize)]
-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentNoteLink {
- /// Current name of the markdown document.
- pub document_name: String,
- /// Linked calendar copy.
- pub event_id: Uuid,
- /// Original occurrence start, or `single` for a one-time meeting.
- pub occurrence_key: String,
- /// Current title, or a safe placeholder when meeting details are unavailable.
- pub event_title: String,
- /// Whether the reader may resolve this exact meeting's details right now.
- pub can_view_meeting: bool,
- /// Exact accessible calendar preview, resolved with this link's authorization snapshot.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub event: Option<CalendarMentionEvent>,
- /// Independent optional team audience.
- pub team: Option<NoteTeam>,
- /// Exact, sanitized team-calendar details when the meeting is shared through a team.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub team_event: Option<TeamCalendarItem>,
-}
-
-/// An exact linked occurrence from a currently authorized full-detail team source.
-pub struct NoteReferenceSource {
- /// Durable link this source resolves.
- pub target: NoteTarget,
- /// Source-scoped event and occurrence; never borrowed from another calendar.
- pub source: TeamSourceOccurrence,
- /// Addresses owned by the reader, for requester-relative attendee fields.
- pub viewer_emails: Vec<String>,
-}
-
-/// Failures with safe, user-facing semantics.
-#[derive(Debug, thiserror::Error)]
-pub enum NoteError {
- /// The meeting is missing, cancelled, or not visible in detail.
- #[error("This meeting is no longer available")]
- NotFound,
- /// Sharing requires document ownership and current team membership.
- #[error("You do not have permission to share these notes")]
- Forbidden,
- /// Only live markdown documents can be linked.
- #[error("Choose a markdown document")]
- NotMarkdown,
- /// Invalid or excessive input.
- #[error("Invalid meeting notes request")]
- InvalidInput,
- /// An infrastructure operation failed.
- #[error("Meeting notes could not be saved")]
- Internal(rootcause::Report),
-}
-
-/// Persistence facts and atomic link writes.
-pub trait NoteRepository: Send + Sync + 'static {
- /// Adapter error.
- type Err: std::error::Error + Send + Sync + 'static;
- /// Visible meeting links; document owners also retain unavailable grants.
- fn document_links(
- &self,
- user: &str,
- document: &str,
- ) -> impl Future<Output = Result<Vec<DocumentNoteLink>, Self::Err>> + Send;
- /// Exact linked sources with live full-detail team policy and source access.
- fn team_reference_sources(
- &self,
- user: &str,
- document: &str,
- ) -> impl Future<Output = Result<Vec<NoteReferenceSource>, rootcause::Report>> + Send;
- /// Resolve visible link targets through the existing own/channel preview reader.
- fn reference_previews(
- &self,
- user: &str,
- targets: Vec<NoteTarget>,
- ) -> impl Future<Output = Result<Vec<CalendarMentionPreview>, rootcause::Report>> + Send;
- /// Current full-detail access; busy-only projections never qualify.
- fn visible(
- &self,
- user: &str,
- target: &NoteTarget,
- ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Whether a live, materialized occurrence exists for a new link.
- fn occurrence_exists(
- &self,
- target: &NoteTarget,
- ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Whether the document exists, is live, and is markdown.
- fn is_markdown(&self, document: &str) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Current membership in the optional extra audience.
- fn team_member(
- &self,
- user: &str,
- team: Uuid,
- ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Notes from every copy of the same meeting and occurrence.
- fn list(
- &self,
- user: &str,
- target: &NoteTarget,
- ) -> impl Future<Output = Result<Vec<MeetingNote>, Self::Err>> + Send;
- /// Owned markdown suggestions and current teams.
- fn picker(
- &self,
- user: &str,
- query: &str,
- ) -> impl Future<Output = Result<NotePicker, Self::Err>> + Send;
- /// Replace this document's link atomically, including across calendar copies.
- fn link(
- &self,
- user: &str,
- target: &NoteTarget,
- document: &str,
- team: Option<Uuid>,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Remove this document's link from all copies; leave the document intact.
- fn unlink(
- &self,
- target: &NoteTarget,
- document: &str,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
-}
-
-/// Inbound contract; mutation receipts prove ownership before granting access.
-pub trait MeetingNotesService: Send + Sync + 'static {
- /// List visible meeting links; owners also receive unavailable durable grants.
- fn document_links(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> impl Future<Output = Result<Vec<DocumentNoteLink>, NoteError>> + Send;
- /// Read notes using the current meeting audience.
- fn list(
- &self,
- user: &str,
- target: NoteTarget,
- ) -> impl Future<Output = Result<Vec<MeetingNote>, NoteError>> + Send;
- /// Find documents the user can share.
- fn picker(
- &self,
- user: &str,
- query: &str,
- ) -> impl Future<Output = Result<NotePicker, NoteError>> + Send;
- /// Link notes, or update their optional team audience.
- fn link(
- &self,
- receipt: EntityAccessReceipt<OwnerAccessLevel>,
- target: NoteTarget,
- team: Option<Uuid>,
- ) -> impl Future<Output = Result<(), NoteError>> + Send;
- /// Unlink without deleting the notes or touching other grants.
- fn unlink(
- &self,
- receipt: EntityAccessReceipt<OwnerAccessLevel>,
- target: NoteTarget,
- ) -> impl Future<Output = Result<(), NoteError>> + Send;
-}
-
-/// Calendar note policy, independent from transport and storage.
-pub struct MeetingNotes<R> {
- repo: R,
-}
-
-impl<R: NoteRepository> MeetingNotes<R> {
- /// Compose the repository with meeting-note policy.
- pub fn new(repo: R) -> Self {
- Self { repo }
- }
-
- async fn authorize(&self, user: &str, target: &NoteTarget) -> Result<(), NoteError> {
- validate_target(target)?;
- if !self.repo.visible(user, target).await.map_err(internal)? {
- return Err(NoteError::NotFound);
- }
- Ok(())
- }
-}
-
-fn validate_target(target: &NoteTarget) -> Result<(), NoteError> {
- if target.occurrence_key.is_empty() || target.occurrence_key.len() > 100 {
- return Err(NoteError::InvalidInput);
- }
- Ok(())
-}
-
-fn internal(error: impl std::error::Error + Send + Sync + 'static) -> NoteError {
- NoteError::Internal(rootcause::Report::new(error).into_dynamic())
-}
-
-impl<R: NoteRepository> MeetingNotesService for MeetingNotes<R> {
- #[tracing::instrument(name = "calendar.notes.document_links", skip_all, fields(document_id = %receipt.entity().entity_id), err)]
- async fn document_links(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> Result<Vec<DocumentNoteLink>, NoteError> {
- let user = receipt
- .get_authenticated_user()
- .map_err(|_| NoteError::Forbidden)?;
- if receipt.entity().entity_type != EntityType::Document {
- return Err(NoteError::Forbidden);
- }
- let mut links = self
- .repo
- .document_links(user.as_ref(), &receipt.entity().entity_id)
- .await
- .map_err(internal)?;
- if links.is_empty() {
- return Ok(links);
- }
- let visible_targets = links
- .iter()
- .filter(|link| link.can_view_meeting)
- .map(|link| NoteTarget {
- event_id: link.event_id,
- occurrence_key: link.occurrence_key.clone(),
- })
- .collect::<Vec<_>>();
- if !visible_targets.is_empty() {
- let previews = self
- .repo
- .reference_previews(user.as_ref(), visible_targets)
- .await
- .map_err(NoteError::Internal)?;
- for (link, preview) in links
- .iter_mut()
- .filter(|link| link.can_view_meeting)
- .zip(previews)
- {
- if let CalendarMentionPreview::Accessible(event) = preview {
- let exact = if link.occurrence_key == "single" {
- !event.is_recurring
- } else {
- event.occurrence_key.as_deref() == Some(link.occurrence_key.as_str())
- };
- if exact {
- link.event = Some(*event);
- }
- }
- }
- }
- let sources = self
- .repo
- .team_reference_sources(user.as_ref(), &receipt.entity().entity_id)
- .await
- .map_err(NoteError::Internal)?;
- for reference in sources {
- let Some(projected) = project_team_source(
- &reference.source,
- TeamCalendarSharing::All,
- &reference.viewer_emails,
- ) else {
- continue;
- };
- if !matches!(projected.content, TeamCalendarContent::Details { .. }) {
- continue;
- }
- if let Some(link) = links.iter_mut().find(|link| {
- link.event_id == reference.target.event_id
- && link.occurrence_key == reference.target.occurrence_key
- && link.can_view_meeting
- && link.team_event.is_none()
- }) {
- link.team_event = Some(projected);
- }
- }
- Ok(links)
- }
- #[tracing::instrument(name = "calendar.notes.list", skip_all, fields(event_id = %target.event_id), err)]
- async fn list(&self, user: &str, target: NoteTarget) -> Result<Vec<MeetingNote>, NoteError> {
- self.authorize(user, &target).await?;
- self.repo.list(user, &target).await.map_err(internal)
- }
-
- #[tracing::instrument(name = "calendar.notes.picker", skip_all, err)]
- async fn picker(&self, user: &str, query: &str) -> Result<NotePicker, NoteError> {
- if query.len() > 200 {
- return Err(NoteError::InvalidInput);
- }
- self.repo.picker(user, query.trim()).await.map_err(internal)
- }
-
- #[tracing::instrument(name = "calendar.notes.link", skip_all, fields(event_id = %target.event_id, document_id = %receipt.entity().entity_id), err)]
- async fn link(
- &self,
- receipt: EntityAccessReceipt<OwnerAccessLevel>,
- target: NoteTarget,
- team: Option<Uuid>,
- ) -> Result<(), NoteError> {
- let user = receipt
- .get_authenticated_user()
- .map_err(|_| NoteError::Forbidden)?;
- if receipt.entity().entity_type != EntityType::Document {
- return Err(NoteError::Forbidden);
- }
- self.authorize(user.as_ref(), &target).await?;
- if !self
- .repo
- .occurrence_exists(&target)
- .await
- .map_err(internal)?
- {
- return Err(NoteError::NotFound);
- }
- let document = &receipt.entity().entity_id;
- if !self.repo.is_markdown(document).await.map_err(internal)? {
- return Err(NoteError::NotMarkdown);
- }
- if let Some(team) = team
- && !self
- .repo
- .team_member(user.as_ref(), team)
- .await
- .map_err(internal)?
- {
- return Err(NoteError::Forbidden);
- }
- self.repo
- .link(user.as_ref(), &target, document, team)
- .await
- .map_err(internal)
- }
-
- #[tracing::instrument(name = "calendar.notes.unlink", skip_all, fields(event_id = %target.event_id, document_id = %receipt.entity().entity_id), err)]
- async fn unlink(
- &self,
- receipt: EntityAccessReceipt<OwnerAccessLevel>,
- target: NoteTarget,
- ) -> Result<(), NoteError> {
- receipt
- .get_authenticated_user()
- .map_err(|_| NoteError::Forbidden)?;
- if receipt.entity().entity_type != EntityType::Document {
- return Err(NoteError::Forbidden);
- }
- // A document owner must still be able to revoke sharing after the
- // meeting is cancelled or they lose access to its calendar.
- validate_target(&target)?;
- self.repo
- .unlink(&target, &receipt.entity().entity_id)
- .await
- .map_err(internal)
- }
-}
-
-#[cfg(test)]
-mod test;
diff --git a/crates/calendar_events/src/domain/notes/test.rs b/crates/calendar_events/src/domain/notes/test.rs
deleted file mode 100644
index 6a64c4206e..0000000000
--- a/crates/calendar_events/src/domain/notes/test.rs
+++ /dev/null
@@ -1,178 +0,0 @@
-use super::*;
-use macro_user_id::user_id::MacroUserIdStr;
-use std::sync::atomic::{AtomicUsize, Ordering};
-
-struct Repo {
- visible: bool,
- markdown: bool,
- member: bool,
- writes: AtomicUsize,
-}
-
-impl NoteRepository for Repo {
- type Err = std::io::Error;
- async fn document_links(&self, _: &str, _: &str) -> Result<Vec<DocumentNoteLink>, Self::Err> {
- Ok(vec![])
- }
- async fn team_reference_sources(
- &self,
- _: &str,
- _: &str,
- ) -> Result<Vec<NoteReferenceSource>, rootcause::Report> {
- Ok(vec![])
- }
- async fn reference_previews(
- &self,
- _: &str,
- _: Vec<NoteTarget>,
- ) -> Result<Vec<CalendarMentionPreview>, rootcause::Report> {
- Ok(vec![])
- }
- async fn visible(&self, _: &str, _: &NoteTarget) -> Result<bool, Self::Err> {
- Ok(self.visible)
- }
- async fn occurrence_exists(&self, _: &NoteTarget) -> Result<bool, Self::Err> {
- Ok(true)
- }
- async fn is_markdown(&self, _: &str) -> Result<bool, Self::Err> {
- Ok(self.markdown)
- }
- async fn team_member(&self, _: &str, _: Uuid) -> Result<bool, Self::Err> {
- Ok(self.member)
- }
- async fn list(&self, _: &str, _: &NoteTarget) -> Result<Vec<MeetingNote>, Self::Err> {
- Ok(vec![])
- }
- async fn picker(&self, _: &str, _: &str) -> Result<NotePicker, Self::Err> {
- Ok(NotePicker {
- documents: vec![],
- teams: vec![],
- })
- }
- async fn link(
- &self,
- _: &str,
- _: &NoteTarget,
- _: &str,
- _: Option<Uuid>,
- ) -> Result<(), Self::Err> {
- self.writes.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
- async fn unlink(&self, _: &NoteTarget, _: &str) -> Result<(), Self::Err> {
- self.writes.fetch_add(1, Ordering::SeqCst);
- Ok(())
- }
-}
-
-#[tokio::test]
-async fn sharing_requires_visible_meeting_markdown_and_membership_in_extra_team() {
- let target = NoteTarget {
- event_id: Uuid::now_v7(),
- occurrence_key: "2026-07-24T14:00:00+00:00".into(),
- };
- for (visible, markdown, member, extra_team, expected) in [
- (false, true, true, None, "meeting"),
- (true, false, true, None, "markdown"),
- (true, true, false, Some(Uuid::now_v7()), "team"),
- (true, true, false, None, "allowed"),
- (true, true, true, Some(Uuid::now_v7()), "allowed"),
- ] {
- let service = MeetingNotes::new(Repo {
- visible,
- markdown,
- member,
- writes: AtomicUsize::new(0),
- });
- let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- "019f85aa-984e-7022-a018-4a242bcafe23",
- EntityType::Document,
- );
- let result = service.link(receipt, target.clone(), extra_team).await;
- match expected {
- "meeting" => assert!(matches!(result, Err(NoteError::NotFound))),
- "markdown" => assert!(matches!(result, Err(NoteError::NotMarkdown))),
- "team" => assert!(matches!(result, Err(NoteError::Forbidden))),
- _ => assert!(result.is_ok()),
- }
- assert_eq!(
- service.repo.writes.load(Ordering::SeqCst),
- usize::from(expected == "allowed")
- );
- }
-}
-
-#[tokio::test]
-async fn unrelated_owner_receipt_cannot_share_a_document() {
- let service = MeetingNotes::new(Repo {
- visible: true,
- markdown: true,
- member: true,
- writes: AtomicUsize::new(0),
- });
- let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- "019f85aa-984e-7022-a018-4a242bcafe23",
- EntityType::Project,
- );
- assert!(matches!(
- service
- .link(
- receipt,
- NoteTarget {
- event_id: Uuid::now_v7(),
- occurrence_key: "2026-07-24".into()
- },
- None
- )
- .await,
- Err(NoteError::Forbidden)
- ));
- assert_eq!(service.repo.writes.load(Ordering::SeqCst), 0);
-}
-
-#[tokio::test]
-async fn an_owner_can_revoke_sharing_after_losing_meeting_access() {
- let service = MeetingNotes::new(Repo {
- visible: false,
- markdown: true,
- member: false,
- writes: AtomicUsize::new(0),
- });
- let receipt = EntityAccessReceipt::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- "019f85aa-984e-7022-a018-4a242bcafe23",
- EntityType::Document,
- );
- service
- .unlink(
- receipt,
- NoteTarget {
- event_id: Uuid::now_v7(),
- occurrence_key: "2026-07-24".into(),
- },
- )
- .await
- .unwrap();
- assert_eq!(service.repo.writes.load(Ordering::SeqCst), 1);
-}
-
-#[tokio::test]
-async fn document_references_require_a_document_view_receipt() {
- let service = MeetingNotes::new(Repo {
- visible: true,
- markdown: true,
- member: false,
- writes: AtomicUsize::new(0),
- });
- for (entity_type, allowed) in [(EntityType::Document, true), (EntityType::Project, false)] {
- let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
- "019f85aa-984e-7022-a018-4a242bcafe23",
- entity_type,
- );
- assert_eq!(service.document_links(receipt).await.is_ok(), allowed);
- }
- assert_eq!(service.repo.writes.load(Ordering::SeqCst), 0);
-}
diff --git a/crates/calendar_events/src/domain/team.rs b/crates/calendar_events/src/domain/team.rs
index 0440d57f75..ff5d218cd3 100644
--- a/crates/calendar_events/src/domain/team.rs
+++ b/crates/calendar_events/src/domain/team.rs
@@ -6,6 +6,4 @@ mod service;
pub use models::*;
pub use ports::*;
-#[cfg(feature = "notes")]
-pub(crate) use service::project as project_team_source;
pub use service::{CalendarTeamServiceImpl, TeamCalendarError};
diff --git a/crates/calendar_events/src/domain/team/service.rs b/crates/calendar_events/src/domain/team/service.rs
index 1a3a86997d..4f0a58647b 100644
--- a/crates/calendar_events/src/domain/team/service.rs
+++ b/crates/calendar_events/src/domain/team/service.rs
@@ -274,7 +274,7 @@ impl<R: CalendarTeamRepository, N: CalendarTeamNotifier> CalendarTeamService
}
}
-pub(crate) fn project(
+fn project(
source: &TeamSourceOccurrence,
sharing: TeamCalendarSharing,
viewer_emails: &[String],
diff --git a/crates/calendar_events/src/inbound/mod.rs b/crates/calendar_events/src/inbound/mod.rs
index 11e4c7be52..73a7ddf0e4 100644
--- a/crates/calendar_events/src/inbound/mod.rs
+++ b/crates/calendar_events/src/inbound/mod.rs
@@ -3,9 +3,6 @@
/// Axum routes for authenticated calendar queries.
#[cfg(feature = "inbound")]
pub mod axum_router;
-/// Markdown meeting-note links.
-#[cfg(all(feature = "inbound", feature = "notes"))]
-pub mod notes_router;
/// Queue worker driving calendar reminder dispatch.
#[cfg(feature = "dispatch")]
diff --git a/crates/calendar_events/src/inbound/notes_router.rs b/crates/calendar_events/src/inbound/notes_router.rs
deleted file mode 100644
index 8cbe6226ad..0000000000
--- a/crates/calendar_events/src/inbound/notes_router.rs
+++ /dev/null
@@ -1,305 +0,0 @@
-//! HTTP transport for meeting notes; policy lives in the domain service.
-
-use crate::domain::notes::{
- DocumentNoteLink, MeetingNote, MeetingNotesService, NoteError, NotePicker, NoteTarget,
-};
-use axum::{
- Json, Router,
- extract::{FromRef, Path, Query, State},
- http::{StatusCode, header},
- response::{IntoResponse, Response},
- routing::{get, put},
-};
-use entity_access::domain::{
- models::{AccessError, EntityType, OwnerAccessLevel, ViewAccessLevel},
- ports::EntityAccessService,
-};
-use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
-};
-use serde::Deserialize;
-use std::sync::Arc;
-use uuid::Uuid;
-
-/// Composed meeting-note, access, and authentication services.
-pub struct NotesRouterState<S, E, A> {
- service: Arc<S>,
- access: Arc<E>,
- auth: MacroAuthorizationState<A>,
-}
-
-impl<S, E, A> Clone for NotesRouterState<S, E, A> {
- fn clone(&self) -> Self {
- Self {
- service: self.service.clone(),
- access: self.access.clone(),
- auth: self.auth.clone(),
- }
- }
-}
-
-impl<S, E, A> NotesRouterState<S, E, A> {
- /// Supply concrete services at the composition root.
- pub fn new(service: Arc<S>, access: Arc<E>, auth: MacroAuthorizationState<A>) -> Self {
- Self {
- service,
- access,
- auth,
- }
- }
-}
-
-impl<S, E, A> FromRef<NotesRouterState<S, E, A>> for MacroAuthorizationState<A> {
- fn from_ref(state: &NotesRouterState<S, E, A>) -> Self {
- state.auth.clone()
- }
-}
-
-/// Authenticated note reads and owner-authorized link writes.
-pub fn notes_router<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
- T: Send + Sync + 'static,
->(
- state: NotesRouterState<S, E, A>,
-) -> Router<T> {
- Router::new()
- .route("/meeting-notes/documents", get(note_documents::<S, E, A>))
- .route(
- "/meeting-notes/documents/{document_id}/links",
- get(document_note_links::<S, E, A>),
- )
- .route("/events/{event_id}/notes", get(event_notes::<S, E, A>))
- .route(
- "/events/{event_id}/notes/{document_id}",
- put(link_event_note::<S, E, A>).delete(unlink_event_note::<S, E, A>),
- )
- .layer(axum::middleware::map_response(
- |mut response: Response| async move {
- response.headers_mut().insert(
- header::CACHE_CONTROL,
- header::HeaderValue::from_static("private, no-store"),
- );
- response
- },
- ))
- .with_state(state)
-}
-
-/// Original occurrence key; independent of a later reschedule.
-#[derive(Deserialize, utoipa::IntoParams)]
-#[serde(rename_all = "camelCase")]
-pub struct NotesQuery {
- /// Stable occurrence key returned by the calendar read API.
- pub occurrence_key: String,
-}
-
-/// Name fragment for owned markdown suggestions.
-#[derive(Deserialize, utoipa::IntoParams)]
-pub struct NoteDocumentsQuery {
- /// Empty returns recent documents.
- #[serde(default)]
- pub query: String,
-}
-
-/// Optional additional view access for one team.
-#[derive(Deserialize, utoipa::ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct LinkNoteRequest {
- /// Null means the meeting audience only.
- pub team_id: Option<Uuid>,
-}
-
-/// Safe HTTP error mapping for note policy failures.
-pub struct NotesApiError(NoteError);
-
-impl From<NoteError> for NotesApiError {
- fn from(error: NoteError) -> Self {
- Self(error)
- }
-}
-
-impl From<AccessError> for NotesApiError {
- fn from(error: AccessError) -> Self {
- Self(match error {
- AccessError::Unavailable(report) | AccessError::Internal(report) => {
- NoteError::Internal(report)
- }
- AccessError::BadRequest(_) => NoteError::InvalidInput,
- AccessError::NotFound(_) => NoteError::NotFound,
- AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
- NoteError::Forbidden
- }
- })
- }
-}
-
-impl IntoResponse for NotesApiError {
- fn into_response(self) -> Response {
- let status = match &self.0 {
- NoteError::NotFound => StatusCode::NOT_FOUND,
- NoteError::Forbidden => StatusCode::FORBIDDEN,
- NoteError::NotMarkdown | NoteError::InvalidInput => StatusCode::BAD_REQUEST,
- NoteError::Internal(error) => {
- tracing::error!(error=?error, "meeting notes request failed");
- StatusCode::INTERNAL_SERVER_ERROR
- }
- };
- (
- status,
- Json(serde_json::json!({"message": self.0.to_string()})),
- )
- .into_response()
- }
-}
-
-/// List notes visible through this meeting occurrence.
-#[utoipa::path(get, path="/events/{event_id}/notes", params(("event_id" = Uuid, Path), NotesQuery), responses((status=200, body=Vec<MeetingNote>)), tag="calendar_events")]
-pub async fn event_notes<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
->(
- State(state): State<NotesRouterState<S, E, A>>,
- user: MacroAuthorizationExtractor<A, UserOrInternal>,
- Path(event_id): Path<Uuid>,
- Query(query): Query<NotesQuery>,
-) -> Result<Json<Vec<MeetingNote>>, NotesApiError> {
- Ok(Json(
- state
- .service
- .list(
- user.authorization.user.macro_user_id.as_ref(),
- NoteTarget {
- event_id,
- occurrence_key: query.occurrence_key,
- },
- )
- .await?,
- ))
-}
-
-/// Suggest the caller's markdown documents and extra team audiences.
-#[utoipa::path(get, path="/meeting-notes/documents", params(NoteDocumentsQuery), responses((status=200, body=NotePicker)), tag="calendar_events")]
-pub async fn note_documents<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
->(
- State(state): State<NotesRouterState<S, E, A>>,
- user: MacroAuthorizationExtractor<A, UserOrInternal>,
- Query(query): Query<NoteDocumentsQuery>,
-) -> Result<Json<NotePicker>, NotesApiError> {
- Ok(Json(
- state
- .service
- .picker(user.authorization.user.macro_user_id.as_ref(), &query.query)
- .await?,
- ))
-}
-
-/// List a document's visible meeting links; owners also see unavailable grants.
-#[utoipa::path(get, path="/meeting-notes/documents/{document_id}/links", params(("document_id" = String, Path)), responses((status=200, body=Vec<DocumentNoteLink>)), tag="calendar_events")]
-pub async fn document_note_links<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
->(
- State(state): State<NotesRouterState<S, E, A>>,
- user: MacroAuthorizationExtractor<A, UserOrInternal>,
- Path(document_id): Path<String>,
-) -> Result<Json<Vec<DocumentNoteLink>>, NotesApiError> {
- let receipt = state
- .access
- .generate_entity_access_receipt::<ViewAccessLevel>(
- &user.authorization.user.macro_user_id,
- user.authorization
- .user
- .user_context
- .organization_id
- .map(i64::from),
- &document_id,
- EntityType::Document,
- )
- .await?;
- Ok(Json(state.service.document_links(receipt).await?))
-}
-
-/// Idempotently link a markdown document and its optional team audience.
-#[utoipa::path(put, path="/events/{event_id}/notes/{document_id}", params(("event_id" = Uuid, Path), ("document_id" = String, Path), NotesQuery), request_body=LinkNoteRequest, responses((status=204)), tag="calendar_events")]
-pub async fn link_event_note<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
->(
- State(state): State<NotesRouterState<S, E, A>>,
- user: MacroAuthorizationExtractor<A, UserOrInternal>,
- Path((event_id, document_id)): Path<(Uuid, String)>,
- Query(query): Query<NotesQuery>,
- Json(body): Json<LinkNoteRequest>,
-) -> Result<StatusCode, NotesApiError> {
- let receipt = state
- .access
- .generate_entity_access_receipt::<OwnerAccessLevel>(
- &user.authorization.user.macro_user_id,
- user.authorization
- .user
- .user_context
- .organization_id
- .map(i64::from),
- &document_id,
- EntityType::Document,
- )
- .await?;
- state
- .service
- .link(
- receipt,
- NoteTarget {
- event_id,
- occurrence_key: query.occurrence_key,
- },
- body.team_id,
- )
- .await?;
- Ok(StatusCode::NO_CONTENT)
-}
-
-/// Remove this meeting's grant without deleting the document.
-#[utoipa::path(delete, path="/events/{event_id}/notes/{document_id}", params(("event_id" = Uuid, Path), ("document_id" = String, Path), NotesQuery), responses((status=204)), tag="calendar_events")]
-pub async fn unlink_event_note<
- S: MeetingNotesService,
- E: EntityAccessService,
- A: MacroAuthorizationService,
->(
- State(state): State<NotesRouterState<S, E, A>>,
- user: MacroAuthorizationExtractor<A, UserOrInternal>,
- Path((event_id, document_id)): Path<(Uuid, String)>,
- Query(query): Query<NotesQuery>,
-) -> Result<StatusCode, NotesApiError> {
- let receipt = state
- .access
- .generate_entity_access_receipt::<OwnerAccessLevel>(
- &user.authorization.user.macro_user_id,
- user.authorization
- .user
- .user_context
- .organization_id
- .map(i64::from),
- &document_id,
- EntityType::Document,
- )
- .await?;
- state
- .service
- .unlink(
- receipt,
- NoteTarget {
- event_id,
- occurrence_key: query.occurrence_key,
- },
- )
- .await?;
- Ok(StatusCode::NO_CONTENT)
-}
diff --git a/crates/calendar_events/src/outbound/mod.rs b/crates/calendar_events/src/outbound/mod.rs
index d256e54f66..b9579573b7 100644
--- a/crates/calendar_events/src/outbound/mod.rs
+++ b/crates/calendar_events/src/outbound/mod.rs
@@ -15,9 +15,6 @@ pub mod notification_notifier;
/// PostgreSQL calendar repository.
#[cfg(feature = "postgres")]
pub mod pg;
-/// PostgreSQL meeting-note links and audience facts.
-#[cfg(all(feature = "postgres", feature = "notes"))]
-pub mod pg_notes;
/// PostgreSQL facts for team-calendar sharing.
#[cfg(feature = "postgres")]
pub mod pg_team;
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 1e050bec52..1586b2a417 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -7408,8 +7408,6 @@ mod join_requests;
mod meeting_copies;
mod meeting_uid;
mod mention_join_link;
-#[cfg(feature = "notes")]
-mod notes;
mod organizer_calendar;
mod source_access;
diff --git a/crates/calendar_events/src/outbound/pg/test/notes.rs b/crates/calendar_events/src/outbound/pg/test/notes.rs
deleted file mode 100644
index cafee6b704..0000000000
--- a/crates/calendar_events/src/outbound/pg/test/notes.rs
+++ /dev/null
@@ -1,673 +0,0 @@
-use super::*;
-use crate::domain::notes::{NoteRepository, NoteTarget};
-use crate::outbound::pg_notes::PgNoteRepository;
-use entity_access::{
- domain::{models::AccessLevel, ports::AccessRepository},
- outbound::PgAccessRepository,
-};
-use macro_user_id::user_id::MacroUserIdStr;
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn a_one_time_meeting_keeps_its_notes_after_a_provider_reschedule(pool: PgPool) {
- let owner = "macro|[email protected]";
- let viewer = "macro|[email protected]";
- for user in [owner, viewer] {
- insert_user(&pool, user).await;
- }
- let calendar = PgCalendarRepository::new(pool.clone());
- let link = insert_link(&pool, owner).await;
- let mut event = timed_upsert(
- owner,
- link,
- provider_ids(&calendar, link).await,
- "one-time-note",
- "Planning",
- 1,
- );
- event.event.recurrence_lines.clear();
- event.occurrences.truncate(1);
- let original = NoteTarget {
- event_id: event.event.id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event.clone()).await.unwrap();
- let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", original.event_id, channel.to_string()).execute(&pool).await.unwrap();
- let document = Uuid::now_v7().to_string();
- sqlx::query!(
- "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
- document,
- owner
- )
- .execute(&pool)
- .await
- .unwrap();
- let notes = PgNoteRepository::new(pool.clone());
- notes.link(owner, &original, &document, None).await.unwrap();
- // A reader who can see this meeting can discover it from the document.
- let references = notes.document_links(viewer, &document).await.unwrap();
- assert_eq!(references.len(), 1);
- assert_eq!(references[0].event_id, original.event_id);
-
- let starts_at = Utc.with_ymd_and_hms(2026, 7, 26, 16, 0, 0).unwrap();
- event.event.sequence += 1;
- event.event.updated_at += Duration::minutes(1);
- event.event.time = EventTime::Timed {
- starts_at,
- ends_at: starts_at + Duration::hours(1),
- time_zone: Some("UTC".into()),
- };
- event.occurrences[0].time = event.event.time.clone();
- event.occurrences[0].occurrence_key = starts_at.to_rfc3339();
- let moved = NoteTarget {
- event_id: original.event_id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event).await.unwrap();
-
- assert_eq!(notes.list(viewer, &moved).await.unwrap().len(), 1);
- let viewer_id = MacroUserIdStr::parse_from_str(viewer).unwrap();
- assert_eq!(
- PgAccessRepository::new(pool.clone())
- .get_document_access(&document, Some(&viewer_id))
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- assert_eq!(
- notes.document_links(owner, &document).await.unwrap()[0].occurrence_key,
- "single"
- );
- // Losing calendar access hides the reference from a reader, even if a
- // separate document grant remains. The owner retains the durable link.
- let document_uuid = Uuid::parse_str(&document).unwrap();
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'document', $2, 'user', 'view')", document_uuid, viewer)
- .execute(&pool).await.unwrap();
- sqlx::query!("UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2", channel, viewer)
- .execute(&pool).await.unwrap();
- assert_eq!(
- PgAccessRepository::new(pool.clone())
- .get_document_access(&document, Some(&viewer_id))
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- assert!(
- notes
- .document_links(viewer, &document)
- .await
- .unwrap()
- .is_empty()
- );
- assert_eq!(
- notes.document_links(owner, &document).await.unwrap().len(),
- 1
- );
- // A previously returned handle remains able to revoke after the move.
- notes.unlink(&original, &document).await.unwrap();
- assert!(notes.list(viewer, &moved).await.unwrap().is_empty());
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn converting_a_series_to_one_time_does_not_revive_another_instances_grants(pool: PgPool) {
- let owner = "macro|[email protected]";
- let viewer = "macro|[email protected]";
- for user in [owner, viewer] {
- insert_user(&pool, user).await;
- }
- let calendar = PgCalendarRepository::new(pool.clone());
- let link = insert_link(&pool, owner).await;
- let mut event = timed_upsert(
- owner,
- link,
- provider_ids(&calendar, link).await,
- "converted-note",
- "Planning",
- 1,
- );
- let original = NoteTarget {
- event_id: event.event.id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event.clone()).await.unwrap();
- let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", original.event_id, channel.to_string()).execute(&pool).await.unwrap();
- let document = Uuid::now_v7().to_string();
- sqlx::query!(
- "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
- document,
- owner
- )
- .execute(&pool)
- .await
- .unwrap();
- let notes = PgNoteRepository::new(pool.clone());
- notes.link(owner, &original, &document, None).await.unwrap();
- event.event.recurrence_lines.clear();
- event.occurrences.remove(0);
- event.event.time = event.occurrences[0].time.clone();
- event.event.sequence += 1;
- event.event.updated_at += Duration::minutes(1);
- calendar.upsert_event_fixture(event).await.unwrap();
- let viewer_id = MacroUserIdStr::parse_from_str(viewer).unwrap();
- assert_eq!(
- PgAccessRepository::new(pool.clone())
- .get_document_access(&document, Some(&viewer_id))
- .await
- .unwrap(),
- None
- );
- notes.unlink(&original, &document).await.unwrap();
- assert!(
- notes
- .document_links(owner, &document)
- .await
- .unwrap()
- .is_empty()
- );
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn notes_follow_real_guests_reject_forged_copies_and_revoke_without_deleting_documents(
- pool: PgPool,
-) {
- let owner = "macro|[email protected]";
- let guest = "macro|[email protected]";
- let stranger = "macro|[email protected]";
- for user in [owner, guest, stranger] {
- insert_user(&pool, user).await;
- }
- let calendar = PgCalendarRepository::new(pool.clone());
- let notes = PgNoteRepository::new(pool.clone());
- let access = PgAccessRepository::new(pool.clone());
- let owner_link = insert_link(&pool, owner).await;
- let guest_link = insert_link(&pool, guest).await;
- let stranger_link = insert_link(&pool, stranger).await;
- sqlx::query!(
- "UPDATE email_links SET email_address = '[email protected]' WHERE id = $1",
- owner_link
- )
- .execute(&pool)
- .await
- .unwrap();
- sqlx::query!(
- "UPDATE email_links SET email_address = '[email protected]' WHERE id = $1",
- guest_link
- )
- .execute(&pool)
- .await
- .unwrap();
- let original = timed_upsert(
- owner,
- owner_link,
- provider_ids(&calendar, owner_link).await,
- "notes-meeting",
- "Planning",
- 1,
- );
- let target = NoteTarget {
- event_id: original.event.id,
- occurrence_key: original.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(original).await.unwrap();
- let guest_copy = timed_upsert(
- guest,
- guest_link,
- provider_ids(&calendar, guest_link).await,
- "notes-meeting",
- "Planning",
- 1,
- );
- let guest_event = guest_copy.event.id;
- calendar.upsert_event_fixture(guest_copy).await.unwrap();
- let forged = timed_upsert(
- stranger,
- stranger_link,
- provider_ids(&calendar, stranger_link).await,
- "notes-meeting",
- "Forged",
- 1,
- );
- let forged_target = NoteTarget {
- event_id: forged.event.id,
- occurrence_key: target.occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(forged).await.unwrap();
- let document = Uuid::now_v7().to_string();
- sqlx::query!("INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Meeting notes', $2, 'md')", document, owner).execute(&pool).await.unwrap();
- notes.link(owner, &target, &document, None).await.unwrap();
- notes.link(owner, &target, &document, None).await.unwrap();
- assert_eq!(notes.list(guest, &target).await.unwrap().len(), 1);
- let guest_id = MacroUserIdStr::parse_from_str(guest).unwrap();
- let stranger_id = MacroUserIdStr::parse_from_str(stranger).unwrap();
- assert_eq!(
- access
- .get_document_access(&document, Some(&guest_id))
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- assert_eq!(
- access
- .get_document_access(&document, Some(&stranger_id))
- .await
- .unwrap(),
- None
- );
- assert!(
- notes
- .list(stranger, &forged_target)
- .await
- .unwrap()
- .is_empty()
- );
- assert_eq!(
- access.get_document_access(&document, None).await.unwrap(),
- None
- );
- let injected = Uuid::now_v7().to_string();
- sqlx::query!("INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Injected notes', $2, 'md')", injected, stranger).execute(&pool).await.unwrap();
- notes
- .link(stranger, &forged_target, &injected, None)
- .await
- .unwrap();
- let owner_id = MacroUserIdStr::parse_from_str(owner).unwrap();
- assert_eq!(
- access
- .get_document_access(&injected, Some(&owner_id))
- .await
- .unwrap(),
- None
- );
- assert_eq!(notes.list(owner, &target).await.unwrap().len(), 1);
- let fake_channel = insert_channel(&pool, stranger, &[stranger, owner]).await;
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", forged_target.event_id, fake_channel.to_string()).execute(&pool).await.unwrap();
- assert!(notes.visible(owner, &forged_target).await.unwrap());
- assert_eq!(notes.list(owner, &target).await.unwrap().len(), 1);
- let another = NoteTarget {
- event_id: target.event_id,
- occurrence_key: "2026-07-25T14:00:00+00:00".into(),
- };
- assert!(notes.list(guest, &another).await.unwrap().is_empty());
-
- sqlx::query!(
- "UPDATE calendar_events SET is_snapshot = true WHERE id = $1",
- guest_event
- )
- .execute(&pool)
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document, Some(&guest_id))
- .await
- .unwrap(),
- None
- );
- sqlx::query!(
- "UPDATE calendar_events SET is_snapshot = false WHERE id = $1",
- guest_event
- )
- .execute(&pool)
- .await
- .unwrap();
- sqlx::query!("INSERT INTO calendar_event_overrides (event_id, recurrence_id, original_starts_at, starts_at, ends_at, attendees_overridden) SELECT event_id, occurrence_key, starts_at, starts_at, ends_at, true FROM calendar_event_occurrences WHERE event_id = $1 AND occurrence_key = $2", target.event_id, target.occurrence_key).execute(&pool).await.unwrap();
- sqlx::query!("UPDATE calendar_event_occurrences SET recurrence_id = occurrence_key WHERE event_id = $1 AND occurrence_key = $2", target.event_id, target.occurrence_key).execute(&pool).await.unwrap();
- assert_eq!(
- access
- .get_document_access(&document, Some(&guest_id))
- .await
- .unwrap(),
- None
- );
- sqlx::query!(
- "UPDATE calendar_event_overrides SET attendees_overridden = false WHERE event_id = $1",
- target.event_id
- )
- .execute(&pool)
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document, Some(&guest_id))
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- sqlx::query!(
- "DELETE FROM calendar_event_attendees WHERE event_id = $1",
- target.event_id
- )
- .execute(&pool)
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document, Some(&guest_id))
- .await
- .unwrap(),
- None
- );
-
- // Provider sync removes cancelled instances instead of retaining tombstones.
- sqlx::query!(
- "DELETE FROM calendar_event_occurrences WHERE event_id = $1 AND occurrence_key = $2",
- target.event_id,
- target.occurrence_key
- )
- .execute(&pool)
- .await
- .unwrap();
- assert!(!notes.visible(owner, &target).await.unwrap());
- notes.unlink(&target, &document).await.unwrap();
- notes.unlink(&target, &document).await.unwrap();
- assert!(notes.list(owner, &target).await.unwrap().is_empty());
- assert!(notes.is_markdown(&document).await.unwrap());
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn channel_note_access_observes_membership_and_private_occurrences(pool: PgPool) {
- let owner = "macro|[email protected]";
- let viewer = "macro|[email protected]";
- for user in [owner, viewer] {
- insert_user(&pool, user).await;
- }
- let calendar = PgCalendarRepository::new(pool.clone());
- let link = insert_link(&pool, owner).await;
- let event = timed_upsert(
- owner,
- link,
- provider_ids(&calendar, link).await,
- "channel-note",
- "Planning",
- 1,
- );
- let target = NoteTarget {
- event_id: event.event.id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event).await.unwrap();
- let channel = insert_channel(&pool, owner, &[owner, viewer]).await;
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'calendar_event', $2, 'channel', 'view')", target.event_id, channel.to_string()).execute(&pool).await.unwrap();
- let notes = PgNoteRepository::new(pool.clone());
- assert!(notes.visible(viewer, &target).await.unwrap());
- let document = Uuid::now_v7().to_string();
- sqlx::query!("INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Channel notes', $2, 'md')", document, viewer).execute(&pool).await.unwrap();
- notes.link(viewer, &target, &document, None).await.unwrap();
- use crate::domain::notes::{MeetingNotes, MeetingNotesService};
- use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
- let service = MeetingNotes::new(PgNoteRepository::new(pool.clone()));
- let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str(viewer).unwrap(),
- &document,
- EntityType::Document,
- );
- let references = service.document_links(receipt.clone()).await.unwrap();
- assert!(references[0].can_view_meeting);
- assert_eq!(
- references[0]
- .event
- .as_ref()
- .unwrap()
- .occurrence_key
- .as_deref(),
- Some(target.occurrence_key.as_str())
- );
- let overrides =
- serde_json::json!([{ "recurrenceId": target.occurrence_key, "visibility": "private" }]);
- sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(jsonb_set(normalized_payload, '{occurrences,0,recurrenceId}', to_jsonb($2::text)), '{overrides}', $3) WHERE event_id = $1", target.event_id, target.occurrence_key, overrides).execute(&pool).await.unwrap();
- assert!(!notes.visible(viewer, &target).await.unwrap());
- let references = service.document_links(receipt).await.unwrap();
- assert!(!references[0].can_view_meeting);
- assert!(references[0].event.is_none());
- assert!(references[0].team_event.is_none());
- sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{overrides}', '[]') WHERE event_id = $1", target.event_id).execute(&pool).await.unwrap();
- assert!(notes.visible(viewer, &target).await.unwrap());
- sqlx::query!("UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2", channel, viewer).execute(&pool).await.unwrap();
- assert!(!notes.visible(viewer, &target).await.unwrap());
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn optional_team_grants_follow_membership_and_leave_other_document_permissions_intact(
- pool: PgPool,
-) {
- let owner = "macro|[email protected]";
- let teammate = "macro|[email protected]";
- let team = insert_team(&pool, owner, &[owner, teammate]).await;
- let link = insert_link(&pool, owner).await;
- let calendar = PgCalendarRepository::new(pool.clone());
- let event = timed_upsert(
- owner,
- link,
- provider_ids(&calendar, link).await,
- "team-note",
- "Planning",
- 1,
- );
- let target = NoteTarget {
- event_id: event.event.id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event).await.unwrap();
- let document = Uuid::now_v7();
- let document_id = document.to_string();
- sqlx::query!(
- "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
- document_id,
- owner
- )
- .execute(&pool)
- .await
- .unwrap();
- let notes = PgNoteRepository::new(pool.clone());
- let access = PgAccessRepository::new(pool.clone());
- let user = MacroUserIdStr::parse_from_str(teammate).unwrap();
- notes
- .link(owner, &target, &document_id, None)
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document_id, Some(&user))
- .await
- .unwrap(),
- None
- );
- notes
- .link(owner, &target, &document_id, Some(team))
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document_id, Some(&user))
- .await
- .unwrap(),
- Some(AccessLevel::View)
- );
- sqlx::query!(
- "UPDATE calendar_events SET status = 'cancelled' WHERE id = $1",
- target.event_id
- )
- .execute(&pool)
- .await
- .unwrap();
- let links = notes.document_links(owner, &document_id).await.unwrap();
- assert_eq!(links.len(), 1);
- assert_eq!(links[0].event_title, "Unavailable meeting");
- assert_eq!(links[0].team.as_ref().unwrap().id, team);
- assert!(
- notes
- .document_links(teammate, &document_id)
- .await
- .unwrap()
- .is_empty()
- );
- let service = crate::domain::notes::MeetingNotes::new(PgNoteRepository::new(pool.clone()));
- let receipt =
- entity_access::domain::models::EntityAccessReceipt::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str(owner).unwrap(),
- &document_id,
- entity_access::domain::models::EntityType::Document,
- );
- crate::domain::notes::MeetingNotesService::unlink(&service, receipt, target.clone())
- .await
- .unwrap();
- assert!(
- notes
- .document_links(owner, &document_id)
- .await
- .unwrap()
- .is_empty()
- );
- assert_eq!(
- access
- .get_document_access(&document_id, Some(&user))
- .await
- .unwrap(),
- None
- );
- sqlx::query!(
- "UPDATE calendar_events SET status = 'confirmed' WHERE id = $1",
- target.event_id
- )
- .execute(&pool)
- .await
- .unwrap();
- notes
- .link(owner, &target, &document_id, Some(team))
- .await
- .unwrap();
- sqlx::query!("DELETE FROM team_user WHERE user_id = $1", teammate)
- .execute(&pool)
- .await
- .unwrap();
- assert_eq!(
- access
- .get_document_access(&document_id, Some(&user))
- .await
- .unwrap(),
- None
- );
- sqlx::query!("INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES ($1, 'document', $2, 'user', 'edit')", document, teammate).execute(&pool).await.unwrap();
- notes.unlink(&target, &document_id).await.unwrap();
- assert_eq!(
- access
- .get_document_access(&document_id, Some(&user))
- .await
- .unwrap(),
- Some(AccessLevel::Edit)
- );
- assert!(notes.is_markdown(&document_id).await.unwrap());
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn team_detail_access_is_live_and_busy_only_never_reveals_notes(pool: PgPool) {
- let owner = "macro|[email protected]";
- let viewer = "macro|[email protected]";
- insert_team(&pool, owner, &[owner, viewer]).await;
- let calendar = PgCalendarRepository::new(pool.clone());
- let link = insert_link(&pool, owner).await;
- let (account, calendar_id) = provider_ids(&calendar, link).await;
- let event = timed_upsert(
- owner,
- link,
- (account, calendar_id),
- "detail-note",
- "Planning",
- 1,
- );
- let target = NoteTarget {
- event_id: event.event.id,
- occurrence_key: event.occurrences[0].occurrence_key.clone(),
- };
- calendar.upsert_event_fixture(event).await.unwrap();
- sqlx::query!(
- "UPDATE calendars SET synced_at=now(), snapshot_normalization_version=1 WHERE id=$1",
- calendar_id
- )
- .execute(&pool)
- .await
- .unwrap();
- sqlx::query!(
- "UPDATE calendars SET snapshot_normalization_version=1 WHERE id=$1",
- calendar_id
- )
- .execute(&pool)
- .await
- .unwrap();
- sqlx::query!(
- "UPDATE calendar_accounts SET sync_status='ready', last_synced_at=now() WHERE id=$1",
- account
- )
- .execute(&pool)
- .await
- .unwrap();
- let notes = PgNoteRepository::new(pool.clone());
- assert!(!notes.visible(viewer, &target).await.unwrap());
- sqlx::query!(
- "INSERT INTO calendar_team_sharing (user_id, sharing) VALUES ($1, 'all')",
- owner
- )
- .execute(&pool)
- .await
- .unwrap();
- assert!(notes.visible(viewer, &target).await.unwrap());
- let document = Uuid::now_v7().to_string();
- sqlx::query!(
- "INSERT INTO \"Document\" (id, name, owner, \"fileType\") VALUES ($1, 'Notes', $2, 'md')",
- document,
- viewer
- )
- .execute(&pool)
- .await
- .unwrap();
- notes.link(viewer, &target, &document, None).await.unwrap();
- assert_eq!(
- notes.document_links(viewer, &document).await.unwrap()[0].event_title,
- "Shared meeting"
- );
- use crate::domain::notes::{MeetingNotes, MeetingNotesService};
- use crate::domain::team::TeamCalendarContent;
- use entity_access::domain::models::{EntityAccessReceipt, EntityType, ViewAccessLevel};
- let service = MeetingNotes::new(PgNoteRepository::new(pool.clone()));
- let receipt = EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
- MacroUserIdStr::parse_from_str(viewer).unwrap(),
- &document,
- EntityType::Document,
- );
- let references = service.document_links(receipt.clone()).await.unwrap();
- let projection = references[0].team_event.as_ref().unwrap();
- assert!(
- matches!(&projection.content, TeamCalendarContent::Details { details } if details.title == "Planning")
- );
- assert_eq!(
- notes
- .team_reference_sources(viewer, &document)
- .await
- .unwrap()
- .len(),
- 1
- );
- sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{event,visibility}', '\"private\"') WHERE event_id=$1", target.event_id).execute(&pool).await.unwrap();
- assert!(!notes.visible(viewer, &target).await.unwrap());
- assert!(
- service.document_links(receipt.clone()).await.unwrap()[0]
- .team_event
- .is_none()
- );
- sqlx::query!("UPDATE calendar_event_sources SET normalized_payload = jsonb_set(normalized_payload, '{event,visibility}', '\"default\"') WHERE event_id=$1", target.event_id).execute(&pool).await.unwrap();
- assert!(notes.visible(viewer, &target).await.unwrap());
- sqlx::query!(
- "UPDATE calendar_accounts SET last_synced_at=now()-interval '16 minutes' WHERE id=$1",
- account
- )
- .execute(&pool)
- .await
- .unwrap();
- assert!(!notes.visible(viewer, &target).await.unwrap());
- assert!(
- service.document_links(receipt).await.unwrap()[0]
- .team_event
- .is_none()
- );
-}
diff --git a/crates/calendar_events/src/outbound/pg/test/team_sharing.rs b/crates/calendar_events/src/outbound/pg/test/team_sharing.rs
index 90e698fa73..0cee203b6c 100644
--- a/crates/calendar_events/src/outbound/pg/test/team_sharing.rs
+++ b/crates/calendar_events/src/outbound/pg/test/team_sharing.rs
@@ -361,14 +361,6 @@ async fn team_sources_require_current_membership_and_verified_source_entitlement
.await
.unwrap();
assert_eq!(rows.len(), 4, "all synced source calendars are included");
- assert_eq!(
- team.sources(owner, july_2026_range(), &owners, None, 100)
- .await
- .unwrap()
- .len(),
- 4,
- "the owner's busy-only policy must not duplicate their own sources"
- );
sqlx::query!(
"UPDATE calendars SET snapshot_normalization_version=0 WHERE account_id=$1",
account
diff --git a/crates/calendar_events/src/outbound/pg_notes.rs b/crates/calendar_events/src/outbound/pg_notes.rs
deleted file mode 100644
index 7a7c3cf439..0000000000
--- a/crates/calendar_events/src/outbound/pg_notes.rs
+++ /dev/null
@@ -1,226 +0,0 @@
-//! PostgreSQL adapter for durable meeting-note links.
-
-use crate::domain::notes::*;
-use sqlx::PgPool;
-use uuid::Uuid;
-
-/// Calendar-owned note-link storage.
-pub struct PgNoteRepository {
- pool: PgPool,
-}
-
-impl PgNoteRepository {
- /// Use the primary database so permission changes are immediately visible.
- pub fn new(pool: PgPool) -> Self {
- Self { pool }
- }
-}
-
-impl NoteRepository for PgNoteRepository {
- type Err = sqlx::Error;
-
- async fn document_links(
- &self,
- user: &str,
- document: &str,
- ) -> Result<Vec<DocumentNoteLink>, Self::Err> {
- let rows = sqlx::query!(r#"
- SELECT note.event_id, note.occurrence_key, document.name AS document_name,
- calendar_note_event_visible($1, note.event_id, note.occurrence_key) AS "can_view_meeting!",
- CASE WHEN calendar_note_event_visible($1, note.event_id, note.occurrence_key)
- THEN CASE WHEN event.owner_id = $1 OR EXISTS (
- SELECT 1 FROM macro_user_links delegate
- WHERE delegate.link_id = event.source_link_id AND delegate.primary_macro_id = $1
- ) THEN event.title ELSE 'Shared meeting' END
- ELSE 'Unavailable meeting' END AS "event_title!",
- team.id AS "team_id?", team.name AS "team_name?"
- FROM calendar_event_notes note
- JOIN "Document" document ON document.id = note.document_id AND document."deletedAt" IS NULL
- JOIN calendar_events event ON event.id = note.event_id
- LEFT JOIN team ON team.id = note.team_id
- WHERE note.document_id = $2
- AND (document.owner = $1 OR calendar_note_event_visible($1, note.event_id, note.occurrence_key))
- ORDER BY note.created_at, note.event_id, note.occurrence_key
- "#, user, document).fetch_all(&self.pool).await?;
- Ok(rows
- .into_iter()
- .map(|row| DocumentNoteLink {
- document_name: row.document_name,
- event_id: row.event_id,
- occurrence_key: row.occurrence_key,
- event_title: row.event_title,
- can_view_meeting: row.can_view_meeting,
- event: None,
- team_event: None,
- team: row
- .team_id
- .zip(row.team_name)
- .map(|(id, name)| NoteTeam { id, name }),
- })
- .collect())
- }
-
- async fn team_reference_sources(
- &self,
- user: &str,
- document: &str,
- ) -> Result<Vec<NoteReferenceSource>, rootcause::Report> {
- super::pg_team::PgCalendarTeamRepository::new(self.pool.clone())
- .note_reference_sources(user, document)
- .await
- }
-
- async fn reference_previews(
- &self,
- user: &str,
- targets: Vec<NoteTarget>,
- ) -> Result<Vec<crate::domain::models::CalendarMentionPreview>, rootcause::Report> {
- use crate::domain::ports::CalendarRepository;
- let items = targets
- .into_iter()
- .map(|target| crate::domain::models::CalendarMentionRequestItem {
- event_id: target.event_id,
- occurrence_key: (target.occurrence_key != "single")
- .then_some(target.occurrence_key),
- })
- .collect();
- super::pg::PgCalendarRepository::new(self.pool.clone())
- .mention_previews(user, items, chrono::Utc::now())
- .await
- }
-
- async fn visible(&self, user: &str, target: &NoteTarget) -> Result<bool, Self::Err> {
- sqlx::query_scalar!(
- "SELECT calendar_note_event_visible($1, $2, calendar_note_link_key($2, $3)) AS \"visible!\"",
- user, target.event_id, target.occurrence_key,
- ).fetch_one(&self.pool).await
- }
-
- async fn occurrence_exists(&self, target: &NoteTarget) -> Result<bool, Self::Err> {
- sqlx::query_scalar!(
- "SELECT EXISTS (SELECT 1 FROM calendar_event_occurrences WHERE event_id = $1 AND calendar_note_link_key($1, occurrence_key) = calendar_note_link_key($1, $2) AND NOT is_cancelled) AS \"exists!\"",
- target.event_id, target.occurrence_key,
- ).fetch_one(&self.pool).await
- }
-
- async fn is_markdown(&self, document: &str) -> Result<bool, Self::Err> {
- sqlx::query_scalar!(
- "SELECT EXISTS (SELECT 1 FROM \"Document\" WHERE id = $1 AND \"fileType\" = 'md' AND \"deletedAt\" IS NULL) AS \"exists!\"",
- document,
- ).fetch_one(&self.pool).await
- }
-
- async fn team_member(&self, user: &str, team: Uuid) -> Result<bool, Self::Err> {
- sqlx::query_scalar!(
- "SELECT EXISTS (SELECT 1 FROM team_user WHERE user_id = $1 AND team_id = $2) AS \"exists!\"",
- user, team,
- ).fetch_one(&self.pool).await
- }
-
- async fn list(&self, user: &str, target: &NoteTarget) -> Result<Vec<MeetingNote>, Self::Err> {
- let rows = sqlx::query!(r#"
- SELECT d.id, d.name, team.id AS "team_id?", team.name AS "team_name?",
- d.owner = $1 AS "can_manage!"
- FROM calendar_event_notes note
- JOIN calendar_events event ON event.id = note.event_id
- JOIN calendar_events requested ON requested.id = $2
- AND requested.ical_uid = event.ical_uid
- AND lower(requested.organizer_email) IS NOT DISTINCT FROM lower(event.organizer_email)
- JOIN "Document" d ON d.id = note.document_id AND d."deletedAt" IS NULL AND d."fileType" = 'md'
- LEFT JOIN team ON team.id = note.team_id
- WHERE note.occurrence_key = calendar_note_link_key($2, $3) AND event.status <> 'cancelled'
- AND calendar_note_event_visible($1, note.event_id, note.occurrence_key)
- AND calendar_note_copies_match(requested.id, note.event_id, calendar_note_link_key($2, $3))
- ORDER BY note.created_at, d.id
- "#, user, target.event_id, target.occurrence_key).fetch_all(&self.pool).await?;
- Ok(rows
- .into_iter()
- .map(|row| MeetingNote {
- document_id: row.id,
- name: row.name,
- team: row
- .team_id
- .zip(row.team_name)
- .map(|(id, name)| NoteTeam { id, name }),
- can_manage: row.can_manage,
- })
- .collect())
- }
-
- async fn picker(&self, user: &str, query: &str) -> Result<NotePicker, Self::Err> {
- let documents = sqlx::query_as!(
- NoteDocument,
- r#"
- SELECT id AS document_id, name FROM "Document"
- WHERE owner = $1 AND "fileType" = 'md' AND "deletedAt" IS NULL
- AND name ILIKE '%' || $2 || '%'
- ORDER BY "updatedAt" DESC, id LIMIT 30
- "#,
- user,
- query
- )
- .fetch_all(&self.pool)
- .await?;
- let teams = sqlx::query_as!(
- NoteTeam,
- r#"
- SELECT team.id, team.name FROM team
- JOIN team_user member ON member.team_id = team.id WHERE member.user_id = $1
- ORDER BY team.name, team.id
- "#,
- user
- )
- .fetch_all(&self.pool)
- .await?;
- Ok(NotePicker { documents, teams })
- }
-
- async fn link(
- &self,
- user: &str,
- target: &NoteTarget,
- document: &str,
- team: Option<Uuid>,
- ) -> Result<(), Self::Err> {
- let mut tx = self.pool.begin().await?;
- // A document can be linked from two inbox copies concurrently. Serialize
- // its link writes so retries never leave duplicate or conflicting grants.
- sqlx::query!(
- "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
- document
- )
- .execute(&mut *tx)
- .await?;
- sqlx::query!(r#"
- DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested
- WHERE note.event_id = event.id AND requested.id = $1
- AND event.ical_uid = requested.ical_uid
- AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
- AND note.occurrence_key = calendar_note_link_key($1, $2) AND note.document_id = $3 AND note.event_id <> $1
- "#, target.event_id, target.occurrence_key, document).execute(&mut *tx).await?;
- sqlx::query!(r#"
- INSERT INTO calendar_event_notes (event_id, occurrence_key, document_id, team_id, user_id)
- VALUES ($1, calendar_note_link_key($1, $2), $3, $4, $5)
- ON CONFLICT (event_id, occurrence_key, document_id) DO UPDATE SET team_id = EXCLUDED.team_id, user_id = EXCLUDED.user_id
- "#, target.event_id, target.occurrence_key, document, team, user).execute(&mut *tx).await?;
- tx.commit().await
- }
-
- async fn unlink(&self, target: &NoteTarget, document: &str) -> Result<(), Self::Err> {
- let mut tx = self.pool.begin().await?;
- sqlx::query!(
- "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
- document
- )
- .execute(&mut *tx)
- .await?;
- sqlx::query!(r#"
- DELETE FROM calendar_event_notes note USING calendar_events event, calendar_events requested
- WHERE note.event_id = event.id AND requested.id = $1
- AND event.ical_uid = requested.ical_uid
- AND lower(event.organizer_email) IS NOT DISTINCT FROM lower(requested.organizer_email)
- AND (note.occurrence_key = $2 OR note.occurrence_key = calendar_note_link_key($1, $2)) AND note.document_id = $3
- "#, target.event_id, target.occurrence_key, document).execute(&mut *tx).await?;
- tx.commit().await
- }
-}
diff --git a/crates/calendar_events/src/outbound/pg_team.rs b/crates/calendar_events/src/outbound/pg_team.rs
index 99732d4e85..363f2370f3 100644
--- a/crates/calendar_events/src/outbound/pg_team.rs
+++ b/crates/calendar_events/src/outbound/pg_team.rs
@@ -42,164 +42,6 @@ fn sharing(value: &str) -> Result<TeamCalendarSharing, Report> {
}
}
-struct SourceRead<'a> {
- range: Option<OccurrenceRange>,
- owners: &'a [String],
- cursor: Option<&'a TeamCalendarCursor>,
- limit: u32,
- document: Option<&'a str>,
-}
-
-impl PgCalendarTeamRepository {
- /// Read exact linked occurrences through the same source entitlement as team calendars.
- #[cfg(feature = "notes")]
- pub(super) async fn note_reference_sources(
- &self,
- requester: &str,
- document: &str,
- ) -> Result<Vec<crate::domain::notes::NoteReferenceSource>, Report> {
- let viewer_emails = self.owned_emails(requester).await?;
- let rows = self
- .read_sources(
- requester,
- SourceRead {
- range: None,
- owners: &[],
- cursor: None,
- limit: 2000,
- document: Some(document),
- },
- )
- .await?;
- Ok(rows
- .into_iter()
- .filter_map(|(source, target)| {
- target.map(
- |(event_id, occurrence_key)| crate::domain::notes::NoteReferenceSource {
- target: crate::domain::notes::NoteTarget {
- event_id,
- occurrence_key,
- },
- source,
- viewer_emails: viewer_emails.clone(),
- },
- )
- })
- .collect())
- }
-
- async fn read_sources(
- &self,
- requester: &str,
- request: SourceRead<'_>,
- ) -> Result<Vec<(TeamSourceOccurrence, Option<(Uuid, String)>)>, Report> {
- // The normalized source payload holds this source's schedule, guests,
- // conference, and exceptions. Joining canonical entity fields here would
- // borrow richer content from a different calendar's entitlement.
- let rows = sqlx::query!(r#"
- WITH reference_targets AS MATERIALIZED (
- SELECT candidate.id AS event_id, note.event_id AS reference_event_id,
- note.occurrence_key AS reference_occurrence_key
- FROM calendar_event_notes note
- JOIN calendar_events linked ON linked.id = note.event_id
- JOIN calendar_events candidate ON candidate.ical_uid = linked.ical_uid
- AND lower(candidate.organizer_email) IS NOT DISTINCT FROM lower(linked.organizer_email)
- WHERE note.document_id = $11
- AND calendar_note_copies_match(note.event_id, candidate.id, note.occurrence_key)
- ), eligible AS (
- SELECT teammate.user_id, COALESCE(policy.sharing, 'busy_only') AS sharing FROM team_user viewer
- JOIN team_user teammate ON teammate.team_id = viewer.team_id
- LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id
- WHERE viewer.user_id = $1 AND teammate.user_id <> $1
- AND COALESCE(policy.sharing, 'busy_only') <> 'none'
- UNION SELECT $1::text, 'all'
- ), visible_accounts AS MATERIALIZED (
- SELECT eligible.user_id, eligible.sharing, account.id AS account_id
- FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id
- WHERE ($11::text IS NOT NULL OR eligible.user_id = ANY($2::text[]))
- UNION
- SELECT eligible.user_id, eligible.sharing, account.id AS account_id
- FROM eligible
- JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id
- JOIN calendar_accounts account ON account.email_link_id = link.link_id
- WHERE ($11::text IS NOT NULL OR eligible.user_id = ANY($2::text[]))
- ), authorized_sources AS MATERIALIZED (
- SELECT eligible.user_id AS shared_by, source.id AS source_id,
- calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,
- COALESCE(preference.contributes_to_availability,
- account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,
- source.normalized_payload, reference.reference_event_id,
- reference.reference_occurrence_key
- FROM visible_accounts eligible
- JOIN calendar_accounts account ON account.id = eligible.account_id
- AND account.sync_status IN ('ready', 'syncing')
- AND account.last_sync_error IS NULL
- AND account.last_synced_at > now() - interval '15 minutes'
- JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted
- AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL
- AND calendar.snapshot_normalization_version >= 1
- JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id
- AND source.provider_access_role IS NOT NULL
- AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role
- LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id
- LEFT JOIN reference_targets reference ON reference.event_id = source.event_id
- WHERE ($11::text IS NULL OR (eligible.sharing = 'all' AND reference.event_id IS NOT NULL))
- AND ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))
- )
- SELECT shared_by AS "shared_by!", source_id AS "source_id!",
- calendar_id AS "calendar_id!", calendar_name AS "calendar_name!", time_zone,
- contributes AS "contributes!", reference_event_id AS "reference_event_id?",
- reference_occurrence_key AS "reference_occurrence_key?",
- ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS "owner_emails!",
- (normalized_payload - 'occurrences') AS "snapshot!", occurrence.value AS "occurrence!"
- FROM authorized_sources
- CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)
- WHERE (normalized_payload->'event'->>'status') <> 'cancelled'
- AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)
- AND ($11::text IS NOT NULL OR (
- ((occurrence.value->'time'->>'kind') = 'timed'
- AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4
- AND ((occurrence.value->'time'->>'endsAt')::timestamptz > $3
- OR ((occurrence.value->'time'->>'startsAt')::timestamptz = (occurrence.value->'time'->>'endsAt')::timestamptz
- AND (occurrence.value->'time'->>'startsAt')::timestamptz >= $3)))
- OR ((occurrence.value->'time'->>'kind') = 'allDay'
- AND (occurrence.value->'time'->>'startDate')::date < $6
- AND (occurrence.value->'time'->>'endDate')::date > $5)
- ))
- AND ($11::text IS NULL OR occurrence.value->>'occurrenceKey' = reference_occurrence_key
- OR (reference_occurrence_key = 'single' AND jsonb_array_length(normalized_payload->'event'->'recurrenceLines') = 0))
- AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))
- ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'
- LIMIT $10
- "#, requester, request.owners, request.range.as_ref().map(|r| r.starts_at), request.range.as_ref().map(|r| r.ends_at),
- request.range.as_ref().map(|r| r.start_date), request.range.as_ref().map(|r| r.end_date),
- request.cursor.map(|cursor| cursor.user_id.as_str()), request.cursor.map(|cursor| cursor.source_id), request.cursor.map(|cursor| cursor.occurrence_key.as_str()), i64::from(request.limit), request.document)
- .fetch_all(&self.pool).await.map_err(|error| rootcause::report!(error))?;
- rows.into_iter()
- .map(|row| {
- let snapshot: SourceSnapshot = serde_json::from_value(row.snapshot)
- .map_err(|error| rootcause::report!(error))?;
- Ok((
- TeamSourceOccurrence {
- shared_by: row.shared_by,
- source_id: row.source_id,
- calendar_id: row.calendar_id,
- calendar_name: row.calendar_name,
- calendar_time_zone: row.time_zone,
- contributes_to_availability: row.contributes,
- owner_emails: row.owner_emails,
- event: snapshot.event,
- overrides: snapshot.overrides,
- occurrence: serde_json::from_value(row.occurrence)
- .map_err(|error| rootcause::report!(error))?,
- },
- row.reference_event_id.zip(row.reference_occurrence_key),
- ))
- })
- .collect()
- }
-}
-
impl CalendarTeamRepository for PgCalendarTeamRepository {
async fn projection_revision(&self, requester: &str) -> Result<String, Report> {
sqlx::query_scalar!(r#"
@@ -299,21 +141,90 @@ impl CalendarTeamRepository for PgCalendarTeamRepository {
cursor: Option<&TeamCalendarCursor>,
limit: u32,
) -> Result<Vec<TeamSourceOccurrence>, Report> {
- Ok(self
- .read_sources(
- requester,
- SourceRead {
- range: Some(range),
- owners,
- cursor,
- limit,
- document: None,
- },
+ // The normalized source payload holds this source's schedule, guests,
+ // conference, and exceptions. Joining canonical entity fields here would
+ // borrow richer content from a different calendar's entitlement.
+ let rows = sqlx::query!(r#"
+ WITH eligible AS (
+ SELECT teammate.user_id FROM team_user viewer
+ JOIN team_user teammate ON teammate.team_id = viewer.team_id
+ LEFT JOIN calendar_team_sharing policy ON policy.user_id = teammate.user_id
+ WHERE viewer.user_id = $1 AND COALESCE(policy.sharing, 'busy_only') <> 'none'
+ UNION SELECT $1::text
+ ), visible_accounts AS MATERIALIZED (
+ SELECT eligible.user_id, account.id AS account_id
+ FROM eligible JOIN calendar_accounts account ON account.owner_id = eligible.user_id
+ WHERE eligible.user_id = ANY($2::text[])
+ UNION
+ SELECT eligible.user_id, account.id AS account_id
+ FROM eligible
+ JOIN macro_user_links link ON link.primary_macro_id = eligible.user_id
+ JOIN calendar_accounts account ON account.email_link_id = link.link_id
+ WHERE eligible.user_id = ANY($2::text[])
+ ), authorized_sources AS MATERIALIZED (
+ SELECT eligible.user_id AS shared_by, source.id AS source_id,
+ calendar.id AS calendar_id, calendar.name AS calendar_name, calendar.time_zone,
+ COALESCE(preference.contributes_to_availability,
+ account.owner_id = eligible.user_id AND calendar.is_primary) AS contributes,
+ source.normalized_payload
+ FROM visible_accounts eligible
+ JOIN calendar_accounts account ON account.id = eligible.account_id
+ AND account.sync_status IN ('ready', 'syncing')
+ AND account.last_sync_error IS NULL
+ AND account.last_synced_at > now() - interval '15 minutes'
+ JOIN calendars calendar ON calendar.account_id = account.id AND NOT calendar.is_deleted
+ AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL
+ AND calendar.snapshot_normalization_version >= 1
+ JOIN calendar_event_sources source ON source.calendar_id = calendar.id AND source.account_id = account.id
+ AND source.provider_access_role IS NOT NULL
+ AND source.provider_access_role IS NOT DISTINCT FROM calendar.access_role
+ LEFT JOIN calendar_availability_preferences preference ON preference.user_id = eligible.user_id AND preference.calendar_id = calendar.id
+ WHERE ($7::text IS NULL OR (eligible.user_id, source.id) >= ($7,$8))
)
- .await?
- .into_iter()
- .map(|(source, _)| source)
- .collect())
+ SELECT shared_by AS "shared_by!", source_id AS "source_id!",
+ calendar_id AS "calendar_id!", calendar_name AS "calendar_name!", time_zone,
+ contributes AS "contributes!",
+ ARRAY(SELECT owned.email_address::text FROM email_links owned WHERE owned.macro_id = shared_by) AS "owner_emails!",
+ (normalized_payload - 'occurrences') AS "snapshot!", occurrence.value AS "occurrence!"
+ FROM authorized_sources
+ CROSS JOIN LATERAL jsonb_array_elements(normalized_payload->'occurrences') occurrence(value)
+ WHERE (normalized_payload->'event'->>'status') <> 'cancelled'
+ AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean, false)
+ AND (
+ ((occurrence.value->'time'->>'kind') = 'timed'
+ AND (occurrence.value->'time'->>'startsAt')::timestamptz < $4
+ AND ((occurrence.value->'time'->>'endsAt')::timestamptz > $3
+ OR ((occurrence.value->'time'->>'startsAt')::timestamptz = (occurrence.value->'time'->>'endsAt')::timestamptz
+ AND (occurrence.value->'time'->>'startsAt')::timestamptz >= $3)))
+ OR ((occurrence.value->'time'->>'kind') = 'allDay'
+ AND (occurrence.value->'time'->>'startDate')::date < $6
+ AND (occurrence.value->'time'->>'endDate')::date > $5)
+ )
+ AND ($7::text IS NULL OR (shared_by, source_id, occurrence.value->>'occurrenceKey') > ($7,$8,$9))
+ ORDER BY shared_by, source_id, occurrence.value->>'occurrenceKey'
+ LIMIT $10
+ "#, requester, owners, range.starts_at, range.ends_at, range.start_date, range.end_date,
+ cursor.map(|cursor| cursor.user_id.as_str()), cursor.map(|cursor| cursor.source_id), cursor.map(|cursor| cursor.occurrence_key.as_str()), i64::from(limit))
+ .fetch_all(&self.pool).await.map_err(|error| rootcause::report!(error))?;
+ rows.into_iter()
+ .map(|row| {
+ let snapshot: SourceSnapshot = serde_json::from_value(row.snapshot)
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(TeamSourceOccurrence {
+ shared_by: row.shared_by,
+ source_id: row.source_id,
+ calendar_id: row.calendar_id,
+ calendar_name: row.calendar_name,
+ calendar_time_zone: row.time_zone,
+ contributes_to_availability: row.contributes,
+ owner_emails: row.owner_emails,
+ event: snapshot.event,
+ overrides: snapshot.overrides,
+ occurrence: serde_json::from_value(row.occurrence)
+ .map_err(|error| rootcause::report!(error))?,
+ })
+ })
+ .collect()
}
async fn owned_emails(&self, requester: &str) -> Result<Vec<String>, Report> {
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index ce00e399c1..a84e9e8f67 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 cO($,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*c($){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 Y($){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=Y(await $(this.client));return this.detail.clear(),O}}class T$ extends P{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class X$ extends T${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(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){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(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($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var m7={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function n$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>m7[x]??x);return`<${$}>${j}</${$}>`}function u7($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var c7={toMention:()=>({tag:n$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function d7($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(u7(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:l7(x)}}function l7($){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 L$ extends P{static byId($,O){return new L$($,O)}static from($,O){return new L$($,O.id,O)}async fetch(){let $=Y(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 R$ extends P{static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.bot.id,O)}async fetch(){let $=Y(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",($)=>$?L$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:m0($)}))}}function m0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...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:G}}async function Bj($,O,j,x=[]){let{channelId:S,thread:K}=p7(O);if(await a7($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:r7,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new f("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)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:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var r7="static/image";function p7($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function a7($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class m${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:$}=Y(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($,O){let j=await Bj(this.client,this,O$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends T${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 Y(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 A.byId(this.client,(await this.detail.get()).sender_id)}channel(){return b.byId(this.client,this.channelId)}thread(){return new m$(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 R$.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 u0(this.client,this,$))}async startFresh($){Y(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 u0{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($){Y(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 N$ 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 N$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return Y(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 q$($,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=Y(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:A.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 i7=50;function x$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??i7;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),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 A.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new JO(this.client,this.channel,Y(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,Y(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 N$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return q$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Lj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(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}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new b($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new b($,j)}static async create($,O){let{id:j}=Y(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 Bj(this.client,O?.thread??this,O$($),O?.images);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 c(async(O)=>{let j=Y(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:$}=Y(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 Y(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){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(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 A extends X${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(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 A($,O)}static fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new A($,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:n$("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=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?A.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?HO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>HO.from(this.client,this,j))}}async submit($,O){return HO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(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 Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class HO extends P{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new HO($,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",($)=>A.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function s$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class U$ extends P{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new U$($,O,j)}static fromRecord($,O,j){return new U$($,O,j.id,j)}static async create($,O,j){return U$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return U$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>U$.fromRecord($,O.session(),x))}async fetch(){return Y(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 c0($,{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 c0{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 Y(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>U$.create(this.client,this,$),list:()=>U$.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 Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(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 Y(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 Y(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:s$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(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}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(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}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(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?A.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(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 Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(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:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Nj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(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}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>U$.createForSession(this.client,this,$),byId:($)=>U$.byId(this.client,this,$)};codeExecutions={byId:($)=>dO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class d0{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 l0{client;constructor($){this.client=$}byId($){return R$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>R$.from(this.client,$))}async create($){return R$.from(this.client,Y(await this.client.storage.createAgent({body:m0($)})))}}class r0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class t$ extends P{static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(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 p0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>t$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:t$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(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 Y(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 Y(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=Y(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=Y(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 Y(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",($)=>A.byId(this.client,$));async members(){let $=Y(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:A.byId(this.client,O.user_id),role:O.role}))}}class D$ extends P{async fetch(){let{links:$}=Y(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 D$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new D$($,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 Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class u$ extends P{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(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 u$($,O)}static async list($){let{calendars:O}=Y(await $.calendar.listCalendars());return O.map((j)=>new u$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>D$.byId(this.client,$))}class pO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class $$ extends P{async notes($){return this.requireOwnOccurrence($),Y(await this.client.calendar.eventNotes({path:{event_id:this.id},query:{occurrenceKey:$.occurrenceKey}})).map((j)=>w$.fromRecord(this.client,this,$,j))}async linkNote($,O,j={}){return this.requireOwnOccurrence(O),Y(await this.client.calendar.linkEventNote({path:{event_id:this.id,document_id:$.id},query:{occurrenceKey:O.occurrenceKey},body:{teamId:j.team?.id??null}})),w$.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",($)=>$?u$.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:n7($)}));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=Y(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 Y(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 Y(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 n7($){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 w$ 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 w$($,$$.byId($,j.eventId),j,O,{documentId:O.id,name:j.documentName,team:j.team,canManage:!0},!0)}static forDocument($,O,j,x){return new w$($,O,j,x)}static fromRecord($,O,j,x){return new w$($,O,j,q.byId($,x.documentId),x)}async fetch(){if(this.fromDocument){let x=Y(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=Y(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 Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(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}=Y(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:$}=Y(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 $=Y(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 Y(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 A.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()=>Y(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 s7=8;class q extends X${async meetingNotes(){return Y(await this.client.calendar.documentNoteLinks({path:{document_id:this.id}})).map((O)=>({note:w$.fromDocumentLink(this.client,this,O),eventTitle:O.eventTitle}))}async anchors(){return Y(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,Y(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 Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(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 N$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return q$(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:$}=Y(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}=Y(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}=Y(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}=Y(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 c(async(x)=>{let S=Y(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}=Y(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",($)=>A.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:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(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}=Y(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=c(async(x)=>{let S=Y(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 cO(j,s7,async(x)=>{let{state:S,root:K,replies:Z}=Y(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 Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(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:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(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:n$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class a0{client;async noteDocuments($=""){let O=Y(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 Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:u$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=e7(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:$$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:d1(K.event,S),inbox:Z?.emailAddress,role:o7(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:A.byId(this.client,j)})),members:O.members.map((j)=>({user:A.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:$$.byId(this.client,j.eventId),owner:A.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return u$.list(this.client)}calendar($){return u$.byId(this.client,$)}event($){return $$.byId(this.client,$)}replacement($){return new pO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:t7($)}));return $$.fromRecord(this.client,O)}}function t7($){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 e7($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function d1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function o7($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&d1($,O)&&!x)return"organizer";return j?"guest":void 0}class _$ extends P{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new _$($,O)}static from($,O){return new _$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(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",($)=>$?J$.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 Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(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 d$ 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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new d$($,O,j)}static from($,O,j){return new d$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return J$.byId(this.client,this.callId)}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...O$($),thread_id:this.callId}}));return d$.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 J$ extends T${messageThreadById($){return N$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return q$(this.client,{type:"call",entity:this},(O)=>d$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return _$.from(this.client,Y(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 Y(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new J$($,O)}message($){return d$.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",($)=>A.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 J$($,O.call_id)})}class i0{client;constructor($){this.client=$}byId($){return J$.byId(this.client,$)}search($,O){return J$.search(this.client,$,O)}}class n0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class s0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new JO(this.client,b.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new n0($)}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:$}=Y(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}=Y(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(){Y(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 $=Y(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:$}=Y(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}=Y(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:$}=Y(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:n$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class t0{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 $S=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 Y(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 A.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=c(async(K)=>{let Z=Y(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 cO(S,$S,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>P$.from($,O,L))}})}async function sO($,O,j,x){let S=Y(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 T${messageThreadById($){return N$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return q$(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 Y(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 N$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return q$(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 Y(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 Y(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 e$ extends P{tableDetail=new B$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new e$($,O)}static from($,O){return new e$($,O.id,O)}async fetch(){return Y(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",($)=>A.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 Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:s$($)}))}async table(){return zj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>WO.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 c(async(O)=>{let j=Y(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)=>WO.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 WO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class WO 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 WO($,O,j)}static from($,O,j){return new WO($,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 e0{client;constructor($){this.client=$}byId($){return e$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>e$.from(this.client,$))}async create($){return e$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class o0{client;pipelines;constructor($){this.client=$;this.pipelines=new e0($)}companyById($){return b$.byId(this.client,$)}contactById($){return f$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?f$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(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,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return b$.search(this.client,$)}}var Y$=Symbol.for("@ts-pattern/matcher"),r1=Symbol.for("@ts-pattern/isVariadic");var $x=($)=>Boolean($&&typeof $=="object"),Hj=($)=>$&&!!$[Y$],s=($,O,j)=>{if(Hj($)){let x=$[Y$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if($x($)){if(!$x(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Hj(X)&&X[r1]?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),G=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],G,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)||Hj(K=S)&&K[Y$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},G$=($)=>{var O,j,x;return $x($)?Hj($)?(O=(j=(x=$[Y$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?tO($,G$):tO(Object.values($),G$):[]},tO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function OS(...$){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:()=>xx($),and:(O)=>d($,O),or:(O)=>p1($,O),select:(O)=>O===void 0?eO($):eO(O,$)})}function Ox($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[r1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>Ox(xx($)),select:(O)=>Ox(O===void 0?eO($):eO(O,$))})}function xx($){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(G$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>G$($),matcherType:"optional"})})}var jS=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},xS=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},SS=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function d(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"and"})})}function p1(...$){return t({[Y$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return tO($,G$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>tO($,G$),matcherType:"or"})})}function u($){return{[Y$]:()=>({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({[Y$]:()=>({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?[]:G$(j))})})}function a1($){return!0}function k$($){return typeof $=="number"}function o$($){return typeof $=="string"}function $O($){return typeof $=="bigint"}var i1=t(u(a1)),ZS=t(u(a1)),XS=i1,OO=($)=>Object.assign(t($),{startsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.endsWith(j)))));var j},minLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length>=j))(O))),length:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length===j))(O))),maxLength:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x.length<=j))(O))),includes:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&x.includes(j)))));var j},regex:(O)=>{return OO(d($,(j=O,u((x)=>o$(x)&&Boolean(x.match(j))))));var j}}),l1=OO(u(o$)),g$=($)=>Object.assign(t($),{between:(O,j)=>g$(d($,((x,S)=>u((K)=>k$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<j))(O))),gt:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>j))(O))),lte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x<=j))(O))),gte:(O)=>g$(d($,((j)=>u((x)=>k$(x)&&x>=j))(O))),int:()=>g$(d($,u((O)=>k$(O)&&Number.isInteger(O)))),finite:()=>g$(d($,u((O)=>k$(O)&&Number.isFinite(O)))),positive:()=>g$(d($,u((O)=>k$(O)&&O>0))),negative:()=>g$(d($,u((O)=>k$(O)&&O<0)))}),KS=g$(u(k$)),jO=($)=>Object.assign(t($),{between:(O,j)=>jO(d($,((x,S)=>u((K)=>$O(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<j))(O))),gt:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>j))(O))),lte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x<=j))(O))),gte:(O)=>jO(d($,((j)=>u((x)=>$O(x)&&x>=j))(O))),positive:()=>jO(d($,u((O)=>$O(O)&&O>0))),negative:()=>jO(d($,u((O)=>$O(O)&&O<0)))}),GS=jO(u($O)),YS=t(u(function($){return typeof $=="boolean"})),QS=t(u(function($){return typeof $=="symbol"})),JS=t(u(function($){return $==null})),VS=t(u(function($){return $!=null})),Z$={__proto__:null,matcher:Y$,optional:xx,array:function(...$){return Ox({[Y$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return G$(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?[]:G$($[0])})})},set:function(...$){return t({[Y$]:()=>({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:jS(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:G$($[0])})})},map:function(...$){return t({[Y$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};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:xS(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},record:function(...$){return t({[Y$]:()=>({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,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[l1,$[0]]:$;return{matched:SS(O,(X,G)=>{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,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...G$($[0]),...G$($[1])]})})},intersection:d,union:p1,not:function($){return t({[Y$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:eO,any:i1,unknown:ZS,_:XS,string:l1,number:KS,bigint:GS,boolean:YS,symbol:QS,nullish:JS,nonNullable:VS,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(OS($)))}};class n1 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 jx={matched:!1,value:void 0};function k($){return new Tj($,jx)}class Tj{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=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?jx:{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 Tj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Tj(this.input,j?{matched:!0,value:O(this.input,this.input)}:jx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=WS){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function WS($){throw new n1($)}var Sx,BS=new Uint8Array(16);function Rj(){if(!Sx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sx=crypto.getRandomValues.bind(crypto)}return Sx(BS)}var j$=[];for(let $=0;$<256;++$)j$.push(($+256).toString(16).slice(1));function s1($,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 Zx={};function LS($,O,j){let x;if($)x=t1($.random??$.rng?.()??Rj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Rj();NS(Zx,S,K),x=t1(K,Zx.msecs,Zx.seq,O,j)}return O??s1(x)}function NS($,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 t1($,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 l$=LS;class C${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new C$($,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 V${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new V$($,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)=>C$.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=Y(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 V$.byId(Z(J),Q)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(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:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:C$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?US(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 US($,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 Mj{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 Mj($,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 Gx 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 Aj($){return k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:Z$.not("relation")},(O)=>O).exhaustive()}var zS={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 IS($){return k($).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})=>zS[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Xx($){return $.map((O)=>({id:l$(),label:O}))}function e1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Kx($){return k($).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 r$($,O,j){let[x]=$;if($.length!==1||!e1(x,O,j))throw new f(`expected one ${O}.${j} result, got ${$.map(Kx).join(", ")||"none"}`);return x}class W$ extends P{access=new o(this.client,"database",this);async fetch(){return Y(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 W$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new W$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new W$($,j.database.id))}query($,O){return _j(this.client,W$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>A.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)=>V$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?V$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=r$(await this.applyOps([{kind:"table",table:l$(),change:{kind:"create",name:$.name}}]),"table","created");return V$.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 Gx(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(Kx).join(", ")||"none"}`);return j.tables.map(({table:x})=>V$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),r$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(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}=Y(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}=Y(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 V$.byId(this,O.id)}webhookOf($){return Mj.fromRecord(V$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(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),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(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 r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:Aj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),Y(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:Aj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${IS(O.to)})`,S=l$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Aj(O.to),options:Xx(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:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!e1(Z,"column","created"))throw new f(`expected a column.created result, got ${Z?Kx(Z):"none"}`);return C$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=r$(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}=r$(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}=r$(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}=r$(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:Aj(O.type),...O.options!==void 0?{options:Xx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=r$(await this.applyOps([{kind:"column",table:$.id,column:l$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return C$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),r$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Xx(O)}}]),"column","options_added")}}class Yx{client;constructor($){this.client=$}query($,O){return _j(this.client,W$.byId,$,O)}byId($){return W$.byId(this.client,$)}create($){return W$.create(this.client,$)}list(){return W$.list(this.client)}}class Pj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Pj(j.id,j.name))}}class Qx{client;async byTeamSlug($){let O=Y(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=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?A.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=Y(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=Y(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 BO extends P{async fetch(){let{attachment:$}=Y(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new BO($,O)}static from($,O){return new BO($,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:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class I$ extends X${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(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 readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:z$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}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?s$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new I$($,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",($)=>D$.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 Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>z$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>BO.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?z$.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=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(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 I$($,O.thread_id)})}class z$ extends P{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new z$($,O)}static from($,O){return new z$($,O.db_id,O)}static async send($,O){let{message:j}=Y(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?z$.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",($)=>D$.byId(this.client,$));async operationStatus(){return Y(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 I$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class LO extends z${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:{...Jx($),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 Jx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...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:G?.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 $=Y(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 xO extends P{async fetch(){let{labels:$}=Y(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 xO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new xO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new f("created label has no id");return new xO($,j.id)}async delete(){Y(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 Vx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Jx($)},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=Y(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 Y(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,Y(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 Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(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:I$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return I$.byId(this.client,$)}message($){return z$.byId(this.client,$)}attachment($){return BO.byId(this.client,$)}link($){return D$.byId(this.client,$)}links(){return D$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return z$.send(this.client,$)}search($,O){return I$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(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)=>I$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return xO.byId(this.client,$)}labels(){return xO.list(this.client)}createLabel($){return xO.create(this.client,$)}archive($,O=!0){return I$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(await this.client.email.listBlockedSenders()).blocked_emails}}class TO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new TO($,O)}async delete(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Wx{client;constructor($){this.client=$}byId($){return TO.byId(this.client,$)}async create($,O){let j=Y(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 TO.byId(this.client,j.id)}}function Bx($,O){return{chat:UO.byId($,O.id),name:O.name,announcements:O.announcements}}class UO extends P{static byId($,O){return new UO($,O)}static from($,O){return new UO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),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");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Bx(this.client,$):void 0);added=this.mappedField("added",($)=>$?y$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?y$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return y$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.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",($)=>$?M$.byId(this.client,this.chat,$):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 SO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new SO($,O)}static from($,O){return new SO($,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,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class ZO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new ZO(O,$)}static from($,O){return new ZO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class XO extends P{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:ZO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>SO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class y$ extends T${entityType="external_chat";static byId($,O){return new y$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");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");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>SO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Bx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return ZO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return XO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>XO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>XO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.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}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Lx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>y$.byId(this.client,$.id))}byId($){return y$.byId(this.client,$)}}class Nx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class KO extends T${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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 o1({login:$,...O}){return{...O,login:$??void 0}}class Ux{client;constructor($){this.client=$}byId($){return KO.byId(this.client,$)}async bySource($,O){return KO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(o1),assignees:j.map(o1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class p${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new p$($,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 C$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>zO.byId(this,$.id))}}class zO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new zO($,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 a${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new a$($,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)=>p$.byId(this.form,O.id)):[]}}class Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class v$ extends P{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new v$($,O)}static async create($,O){let j=Y(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 v$($,j.form.id,j)}static async list($,O){if(!O)return Y(await $.storage.listAccessibleForms()).map(({form:S})=>new v$($,S.id));return Y(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new v$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>A.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>W$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>V$.byId(W$.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(($)=>a$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>p$.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)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.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??l$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??l$(),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=k(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:a$.byId(this,$.section)}:void 0}async outcome($,O){return k($).with({outcome:"stopped"},(j)=>({...j,section:a$.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(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=p$.byId(this,K.question),X=await k(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new f("stored form answers must reference options by id");return zO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new f("row answer requires a relation question");let Q=V$.byId(W$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:Z$.union("text","number","boolean","date","date_range","link","clear")},(G)=>G).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?a$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=Y(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:a$.byId(this,O.section),count:O.count}))}}async tally(){return Y(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=p$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>k(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:zO.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 Y(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 zx{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}create($){return v$.create(this.client,$)}list($){return v$.list(this.client,$)}}class DO extends P{static byId($,O){return new DO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new Ix(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class Ix{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Hx{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 Y(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 L$.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=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:L$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Tx{client;constructor($){this.client=$}byId($){return L$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>L$.from(this.client,$))}async me(){return L$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>R$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return _O.byId(this.client,$)}async createPairing($){let O=Y(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}}}class Fj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Fj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Ej extends Fj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Rx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(HS)}}));return new Ej(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function HS($){return $ instanceof q?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var TS="00000001-0000-0000-0000-000000000001",$2="00000001-0000-0000-0000-000000000002",RS="00000001-0000-0000-0000-000000000004",DS="00000001-0000-0000-0000-000000000014",_S="00000001-0000-0000-0002-000000000001",MS="00000001-0000-0000-0002-000000000004";function AS($){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 Q$ extends q{static byId($,O){return new Q$($,O)}static async create($,O){let{documentId:j}=Y(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,propertyValues:await PS($,O)}}));return new Q$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Q$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=AS(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Q$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===$2)?.value;return j?.type==="SelectOption"&&j.value.includes(MS)}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 Q$($,O.document_id)})}async function PS($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:$2,value:{type:"select_option",option_id:_S}}];if(j.length>0)x.push({propertyId:TS,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:DS,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:RS,value:{type:"date",value:O.dueDate.toISOString()}});return x}class i$ extends P{access=new o(this.client,"initiative",this);static byId($,O){return new i$($,O)}static from($,O){return new i$($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>A.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>A.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Q$.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?s$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Dx{client;constructor($){this.client=$}byId($){return i$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>i$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:i$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return i$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class _x{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}async create($){return _$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>_$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>_$.from(this.client,$))}async lookup($){return _$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class IO extends P{async fetch(){return Y(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new IO($,O)}static from($,O){return new IO($,O.id,O)}static list($,O){return c(async(j)=>{let x=Y(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)=>IO.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",($)=>A.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?A.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 Mx{client;constructor($){this.client=$}byId($){return IO.byId(this.client,$)}list($){return IO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Ax{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Px{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 MO{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 MO($,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=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class GO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new B$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new GO($,j.id,j)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,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 Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>MO.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return MO.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return MO.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(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 GO.fromRecord(this.client,x)})}create($){return GO.create(this.client,$)}definition($){return GO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(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 Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Fx($){return k($).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 CS($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Fx)})).with({type:"cron"},Fx).with({type:"events"},Fx).exhaustive()}class h$ extends P{static byId($,O){return new h$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new h$($,O.id,O)}async fetch(){return Y(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",($)=>A.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?h$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return h$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...qj($),enabled:$.enabled??!0}})))}toTemplate($){return new O2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:qj($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.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 Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Ex(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class O2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Ex{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 qj($){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:CS($.trigger),task:{...O}}}class qx{client;constructor($){this.client=$}byId($){return h$.byId(this.client,$)}async create($){return h$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...qj($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>h$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}summaries($){return Q$.summaries(this.client,$)}findSimilar($){return Q$.findSimilar(this.client,$)}forPullRequest($){return Q$.forPullRequest(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class fx{client;constructor($){this.client=$}byId($){return S$.byId(this.client,$)}current(){return S$.current(this.client)}list(){return S$.list(this.client)}}class bx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class kx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.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}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.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(A.fromName(this.client,J))}}return K}}class YO extends P{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(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 YO($,j.id,j,j.signing_secret)}static byId($,O){return new YO($,O)}static fromRecord($,O){return new YO($,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",($)=>A.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 gx{client;constructor($){this.client=$}create($){return YO.create(this.client,$)}byId($){return YO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>YO.fromRecord(this.client,O))}}class AO extends P{static byId($,O){return new AO($,O)}static from($,O){return new AO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());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",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class yx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?AO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>UO.from(this.client,$))}}function vx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function j2($,O,j){let x=[];for(let S of vx(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:I$.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 m$($,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:J$.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:KO.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 x2="00000000-0000-0000-0000-000000000000",hx={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"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),S2=($,O)=>$==null?O:{"&":[$,O]};function mx($,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==="!"){mx(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)=>{mx(Z,`${O}.${S}[${X}]`)})}class fj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),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(hx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(hx).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)mx($[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:x2}},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}=Y(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(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=S2(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(hx))if(!x.includes(S))O[K]={l:{[Z]:x2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=S2(O.propf,X)}return O}}class ux{client;constructor($){this.client=$}async page($={}){let O=new fj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new fj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>vx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>j2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function Z2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.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 W${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*c($){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 b extends Error{constructor($){super($);this.name="MacroError"}}class YO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class E extends b{constructor($){super($);this.name="MacroNotFoundError"}}function Y($){if($.error!==void 0)throw new YO($.response?.status??0,$.error);return $.data}class C{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>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=Y(await $(this.client));return this.detail.clear(),O}}class H$ extends C{async permission(){return Y(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return Y(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class Z$ extends H${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=Y(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){Y(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return Y(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($){Y(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}var h7={"<":"\\u003c",">":"\\u003e","&":"\\u0026"};function i$($,O){let j=JSON.stringify(O).replace(/[<>&]/g,(x)=>h7[x]??x);return`<${$}>${j}</${$}>`}function m7($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var u7={toMention:()=>({tag:i$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function c7($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(m7(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:d7(x)}}function d7($){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 $$($){return typeof $==="string"?{content:$,mentions:[]}:$}class B$ extends C{static byId($,O){return new B$($,O)}static from($,O){return new B$($,O.id,O)}async fetch(){let $=Y(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 C{static byId($,O){return new T$($,O)}static from($,O){return new T$($,O.bot.id,O)}async fetch(){let $=Y(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)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?B$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:h0($)}))}}function h0($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...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:G}}async function Wj($,O,j,x=[]){let{channelId:S,thread:K}=r7(O);if(await p7($)){let{id:X}=Y(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:S},body:{content:j.content,mentions:j.mentions,attachments:x.map((G)=>({entity_type:l7,entity_id:G.id,width:G.width??null,height:G.height??null})),thread_id:K?.rootId??null,nonce:crypto.randomUUID()}}));return X}if(x.length>0)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support images — use a team-owned bot, or requestedAs(user), "+"to attach images");if(K)throw new b("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:Z}=Y(await $.storage.postChannelBotWebhook({path:{channel_id:S},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return Z}var l7="static/image";function r7($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function p7($){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 f.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=Y(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($,O){let j=await Wj(this.client,this,$$($),O?.images);return e.byId(this.client,this.channelId,j)}}class e extends H${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 Y(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 A.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.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}=$$($);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 Bj{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 m0(this.client,this,$))}async startFresh($){Y(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 m0{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($){Y(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 C{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 Y(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=Y(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:A.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 a7=50;function j$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??a7;return c(async(Q)=>{let{results:J,next_cursor:I}=Y(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Q?{cursor:Q}:{}}}));return{items:J.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:I}})}}class QO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return A.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new QO(this.client,this.channel,Y(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends Z${async recordActivity($){return new QO(this.client,this,Y(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 Y(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Bj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return Y(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=Y(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=Y(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=Y(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 f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Wj(this.client,O?.thread??this,$$($),O?.images);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 c(async(O)=>{let j=Y(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:$}=Y(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 Y(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){Y(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return c(async(O)=>{let j=Y(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=j$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class A extends Z${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=Y(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 A($,O)}static fromName($,O){return new A($,O.id,O)}static async me($){let{user_id:O}=Y(await $.auth.getUserInfo());return new A($,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 f.dm(this.client,this)}toMention(){return{tag:i$("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=Y(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?A.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?IO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>IO.from(this.client,this,j))}}async submit($,O){return IO.from(this.client,this,Y(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){Y(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return Y(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:A.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){Y(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){Y(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 Y(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class IO extends C{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new IO($,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",($)=>A.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function n$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class N$ extends C{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=Y(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return N$.fromRecord($,O,S)}static async list($,O){return Y(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>N$.fromRecord($,O.session(),x))}async fetch(){return Y(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 u0($,{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 u0{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 cO extends C{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new cO($,j,O)}async fetch(){return Y(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 Lj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Lj($,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 Y(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){Y(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){Y(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class dO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new dO($,O,j)}async answer($){return Y(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 C{access=new o(this.client,"agent_session",this);toolApprovalById($){return dO.byId(this.client,this,$)}async sharePermissions(){return Y(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:n$($)}))}static byId($,O){return new l($,O)}static async createManaged($,O){let{session:j}=Y(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}=Y(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=Y(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}static async chooseMode($,O){let{mode:j}=Y(await $.agentHarness.chooseAgentMode({body:{prompt:O}}));return j}async fetch(){return Y(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}=Y(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>l.byId($,x))}async pullRequests(){let{pullRequests:$}=Y(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?A.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){Y(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){Y(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 Y(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return Y(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return Y(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return Y(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:$}=Y(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Lj.from(this.client,this.id,O))}async changes(){return Y(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return Y(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}=Y(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return Y(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:($)=>cO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class c0{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 d0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}async list(){return Y(await this.client.storage.listAgents()).map(($)=>T$.from(this.client,$))}async create($){return T$.from(this.client,Y(await this.client.storage.createAgent({body:h0($)})))}}class l0{client;async usage($={}){let{users:O,...j}=$;return Y(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return Y(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return Y(await this.client.cognition.decisions({body:$}))}}class s$ extends C{static byId($,O){return new s$($,O)}static from($,O){return new s$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=Y(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 r0{client;constructor($){this.client=$}byId($){return s$.byId(this.client,$)}async list(){return Y(await this.client.storage.listUserApiKeys()).keys.map(($)=>s$.from(this.client,$))}async create($){let O=Y(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:s$.from(this.client,O),secret:O.key}}async tokenForEmail($){return Y(await this.client.auth.macroApiToken({query:{email:$}}))}}class lO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return Y(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return Y(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class R$ extends C{async fetch(){let{links:$}=Y(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 R$($,O)}static async list($){let{links:O}=Y(await $.email.listLinks());return O.map((j)=>new R$($,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 Y(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class m$ extends C{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=Y(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}=Y(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");contributesToAvailability=this.field("contributesToAvailability");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>R$.byId(this.client,$))}class rO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return Y(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return Y(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){Y(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class x$ extends C{async fetch(){throw new b(`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 x$($,O)}static fromRecord($,O){return new x$($,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:i7($)}));return x$.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=Y(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new rO(this.client,O.operationId)}async providerUrl($={}){return Y(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 x$.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 x$.fromRecord(this.client,O)}async ics(){return Y(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 x$.fromRecord(this.client,O)}}function i7($){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 p0{client;async availabilityCalendars(){return Y(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:m$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return Y(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return Y(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){let O;return c(async(j)=>{let x=Y(await this.client.storage.listOccurrences({query:{...$,cursor:j}}));O??=s7(this.client);let S=await O;return{items:x.items.map((K)=>{let Z=K.event.calendarId?S.get(K.event.calendarId):void 0;return{event:x$.fromRecord(this.client,K.event),occurrence:K.occurrence,calendarName:Z?.name,contributesToAvailability:c1(K.event,S),inbox:Z?.emailAddress,role:t7(K.event,S)}}),nextCursor:x.nextCursor}})}async teamPage($){let O=Y(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:A.byId(this.client,j)})),members:O.members.map((j)=>({user:A.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=Y(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:x$.byId(this.client,j.eventId),owner:A.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 x$.byId(this.client,$)}replacement($){return new rO(this.client,$)}async createEvent($){let O=Y(await this.client.calendar.createCalendarEvent({body:n7($)}));return x$.fromRecord(this.client,O)}}function n7($){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 s7($){let{calendars:O}=Y(await $.calendar.listCalendars());return new Map(O.map((j)=>[j.id,j]))}function c1($,O){let j=[$.calendarId,...($.sources??[]).map((x)=>x.calendarId)].flatMap((x)=>{let S=x?O.get(x):void 0;return S?[S.contributesToAvailability]:[]});if(j.some(Boolean))return!0;return j.length>0&&j.every((x)=>x===!1)?!1:void 0}function t7($,O){let j=$.attendees.find((S)=>S.isSelf);if(j?.isOrganizer)return $.isReadOnly?void 0:"organizer";let x=$.attendees.some((S)=>S.isOrganizer);if($.viewerCan.organize&&c1($,O)&&!x)return"organizer";return j?"guest":void 0}class D$ extends C{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new D$($,O)}static from($,O){return new D$($,O.id,O)}async fetch(){if(this.lookupToken)return Y(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=Y(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",($)=>$?f.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 Y(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){Y(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){Y(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 C{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 Y(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 A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=Y(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return u$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=$$($);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 H${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 D$.from(this.client,Y(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 Y(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",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>A.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=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new Q$($,O.call_id)})}class a0{client;constructor($){this.client=$}byId($){return Q$.byId(this.client,$)}search($,O){return Q$.search(this.client,$,O)}}class i0{client;constructor($){this.client=$}async list(){let{labels:$}=Y(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return Y(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return Y(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return Y(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return Y(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){Y(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){Y(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class n0{client;async activity(){return Y(await this.client.storage.getActivity()).map(($)=>new QO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new i0($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=Y(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=Y(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends Z${async sharePermissions(){return Y(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return Y(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=Y(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}=Y(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:$}=Y(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=j$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class pO{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 pO($,O,j,x)}async stop(){Y(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 aO extends C{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new aO($,O,j)}async fetch(){let $=Y(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 X$ extends Z${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=X$.byId(this.client,S.chat_id);return pO.byId(this.client,K,S.stream_id,aO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=Y(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new X$($,O)}static async create($,O){let{id:j}=Y(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new X$($,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 X$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=Y(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=j$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new X$($,O.chat_id)});toMention(){return{tag:i$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class s0{client;constructor($){this.client=$}byId($){return X$.byId(this.client,$)}create($){return X$.create(this.client,$)}search($,O){return X$.search(this.client,$,O)}}class _$ extends C{async fetch(){let O=Y(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 _$($,O)}static async current($){let O=Y(await $.auth.getTeam());if(!O)throw new E("caller has no current team");return new _$($,O.team.id,O.team)}static async list($){return Y(await $.auth.getUserTeams()).map((j)=>new _$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>A.byId(this.client,$));async members(){let $=Y(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:A.byId(this.client,O.user_id),role:O.role}))}}var e7=8;class C$ extends C{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 Y(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");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return A.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return iO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);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 Nj($,O){let j={parent_type:O.type,parent_id:O.id},x=c(async(K)=>{let Z=Y(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,e7,async(K)=>{let{state:Z,root:X,replies:G}=Y(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>C$.from($,O,L))}})}async function iO($,O,j,x){let S=Y(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return C$.from($,O,S)}class q$ extends H${messageThreadById($){return L$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_contact",entity:this},(O)=>C$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return Y(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>f$.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 Nj(this.client,this.commentParent)}async comment($,O){return iO(this.client,this.commentParent,$,O)}commentById($){return C$.byId(this.client,this.commentParent,$)}}class f$ extends Z${messageThreadById($){return L$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return w$(this.client,{type:"crm_company",entity:this},(O)=>C$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return Y(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new f$($,O)}static from($,O){return new f$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>_$.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 Y(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>q$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new f$($,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 q$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Nj(this.client,this.commentParent)}async comment($,O){return iO(this.client,this.commentParent,$,O)}commentById($){return C$.byId(this.client,this.commentParent,$)}}class t$ extends C{tableDetail=new W$(async()=>Y(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new t$($,O)}static from($,O){return new t$($,O.id,O)}async fetch(){return Y(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",($)=>A.byId(this.client,$));team=this.mappedField("teamId",($)=>_$.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 Y(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:n$($)}))}async table(){return Uj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return c(async($)=>{let O=Y(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>JO.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 c(async(O)=>{let j=Y(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)=>JO.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 Uj extends C{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 Uj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>zj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return JO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class JO extends C{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 JO($,O,j)}static from($,O,j){return new JO($,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 zj extends C{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 zj($,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 t0{client;constructor($){this.client=$}byId($){return t$.byId(this.client,$)}async list(){return Y(await this.client.storage.listCrmPipelines()).map(($)=>t$.from(this.client,$))}async create($){return t$.from(this.client,Y(await this.client.storage.createCrmPipeline({body:$})))}}class e0{client;pipelines;constructor($){this.client=$;this.pipelines=new t0($)}companyById($){return f$.byId(this.client,$)}contactById($){return q$.byId(this.client,$)}async contactByEmail($){let{contact:O}=Y(await this.client.storage.getContactByEmail({query:{email:$}}));return O?q$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=Y(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>q$.from(this.client,x))}async createCompany($){return f$.from(this.client,Y(await this.client.storage.createCrmCompany({body:$})))}async settings(){return Y(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return Y(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return Y(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){Y(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return f$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),l1=Symbol.for("@ts-pattern/isVariadic");var o0=($)=>Boolean($&&typeof $=="object"),Ij=($)=>$&&!!$[G$],s=($,O,j)=>{if(Ij($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(o0($)){if(!o0(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Ij(X)&&X[l1]?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),G=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],G,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)||Ij(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},K$=($)=>{var O,j,x;return o0($)?Ij($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?nO($,K$):nO(Object.values($),K$):[]},nO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function o7(...$){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:()=>jx($),and:(O)=>d($,O),or:(O)=>r1($,O),select:(O)=>O===void 0?sO($):sO(O,$)})}function $x($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[l1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>$x(jx($)),select:(O)=>$x(O===void 0?sO($):sO(O,$))})}function jx($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(K$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>K$($),matcherType:"optional"})})}var $S=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},OS=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},jS=($,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:()=>nO($,K$),matcherType:"and"})})}function r1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return nO($,K$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>nO($,K$),matcherType:"or"})})}function u($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function sO(...$){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?[]:K$(j))})})}function p1($){return!0}function b$($){return typeof $=="number"}function e$($){return typeof $=="string"}function o$($){return typeof $=="bigint"}var a1=t(u(p1)),xS=t(u(p1)),SS=a1,$O=($)=>Object.assign(t($),{startsWith:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.endsWith(j)))));var j},minLength:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length>=j))(O))),length:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length===j))(O))),maxLength:(O)=>$O(d($,((j)=>u((x)=>e$(x)&&x.length<=j))(O))),includes:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&x.includes(j)))));var j},regex:(O)=>{return $O(d($,(j=O,u((x)=>e$(x)&&Boolean(x.match(j))))));var j}}),d1=$O(u(e$)),k$=($)=>Object.assign(t($),{between:(O,j)=>k$(d($,((x,S)=>u((K)=>b$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>k$(d($,((j)=>u((x)=>b$(x)&&x<j))(O))),gt:(O)=>k$(d($,((j)=>u((x)=>b$(x)&&x>j))(O))),lte:(O)=>k$(d($,((j)=>u((x)=>b$(x)&&x<=j))(O))),gte:(O)=>k$(d($,((j)=>u((x)=>b$(x)&&x>=j))(O))),int:()=>k$(d($,u((O)=>b$(O)&&Number.isInteger(O)))),finite:()=>k$(d($,u((O)=>b$(O)&&Number.isFinite(O)))),positive:()=>k$(d($,u((O)=>b$(O)&&O>0))),negative:()=>k$(d($,u((O)=>b$(O)&&O<0)))}),ZS=k$(u(b$)),OO=($)=>Object.assign(t($),{between:(O,j)=>OO(d($,((x,S)=>u((K)=>o$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x<j))(O))),gt:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x>j))(O))),lte:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x<=j))(O))),gte:(O)=>OO(d($,((j)=>u((x)=>o$(x)&&x>=j))(O))),positive:()=>OO(d($,u((O)=>o$(O)&&O>0))),negative:()=>OO(d($,u((O)=>o$(O)&&O<0)))}),XS=OO(u(o$)),KS=t(u(function($){return typeof $=="boolean"})),GS=t(u(function($){return typeof $=="symbol"})),YS=t(u(function($){return $==null})),QS=t(u(function($){return $!=null})),S$={__proto__:null,matcher:G$,optional:jx,array:function(...$){return $x({[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 K$(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?[]:K$($[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:$S(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:K$($[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,G)=>{j[X]=(j[X]||[]).concat([G])};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:OS(O,(X,G)=>{let L=s(K,G,x),Q=s(Z,X,x);return L&&Q}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[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,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[d1,$[0]]:$;return{matched:jS(O,(X,G)=>{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,G,S);return(J||Q)&&I}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...K$($[0]),...K$($[1])]})})},intersection:d,union:r1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:u,select:sO,any:a1,unknown:xS,_:SS,string:d1,number:ZS,bigint:XS,boolean:KS,symbol:GS,nullish:YS,nonNullable:QS,instanceOf:function($){return t(u(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(u(o7($)))}};class i1 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 k($){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=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,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($=JS){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function JS($){throw new i1($)}var xx,VS=new Uint8Array(16);function Tj(){if(!xx){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");xx=crypto.getRandomValues.bind(crypto)}return xx(VS)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function n1($,O=0){return(O$[$[O+0]]+O$[$[O+1]]+O$[$[O+2]]+O$[$[O+3]]+"-"+O$[$[O+4]]+O$[$[O+5]]+"-"+O$[$[O+6]]+O$[$[O+7]]+"-"+O$[$[O+8]]+O$[$[O+9]]+"-"+O$[$[O+10]]+O$[$[O+11]]+O$[$[O+12]]+O$[$[O+13]]+O$[$[O+14]]+O$[$[O+15]]).toLowerCase()}var Sx={};function WS($,O,j){let x;if($)x=s1($.random??$.rng?.()??Tj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Tj();BS(Sx,S,K),x=s1(K,Sx.msecs,Sx.seq,O,j)}return O??n1(x)}function BS($,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 s1($,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 c$=WS;class P${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new P$($,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 Rj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Rj($,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)=>P$.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)=>Rj.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 Dj($,O,j,x={}){let S=Y(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)},G=new Set(Object.keys(S.newVersions).map((Q)=>X(Q).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Q of G)for(let J of K.get(Q)??[])J.invalidateSchema();let L=k(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:W})=>{let V=X(Q);return{kind:"alterColumnType",table:V,tableName:J,column:P$.byId(V,I),columnName:z,to:W}}).exhaustive();return{result:S.result?LS(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 LS($,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 _j{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 _j($,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 Kx extends YO{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 k($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:S$.not("relation")},(O)=>O).exhaustive()}var NS={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 US($){return k($).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})=>NS[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function Zx($){return $.map((O)=>({id:c$(),label:O}))}function t1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function Xx($){return k($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:S$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function d$($,O,j){let[x]=$;if($.length!==1||!t1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(Xx).join(", ")||"none"}`);return x}class V$ extends C{access=new o(this.client,"database",this);async fetch(){return Y(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new V$($,O)}static async create($,O){let j=Y(await $.storage.createDatabase({body:{name:O.name}}));return new V$($,j.id)}static async list($){return Y(await $.storage.listDatabases()).map((j)=>new V$($,j.database.id))}query($,O){return Dj(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",($)=>A.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}=d$(await this.applyOps([{kind:"table",table:c$(),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 Kx(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 b(`expected one reorder_tables result, got ${O.map(Xx).join(", ")||"none"}`);return j.tables.map(({table:x})=>J$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),Y(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}=Y(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}=Y(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 _j.fromRecord(J$.byId(this,$.tableId),A.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=Y(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=Y(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),Y(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return Y(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 d$(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),Y(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()} (${US(O.to)})`,S=c$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:Mj(O.to),options:Zx(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:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!t1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?Xx(Z):"none"}`);return P$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=d$(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 b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=d$(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 b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=d$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=d$(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 b(`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:Zx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=d$(await this.applyOps([{kind:"column",table:$.id,column:c$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return P$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),d$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:Zx(O)}}]),"column","options_added")}}class Gx{client;constructor($){this.client=$}query($,O){return Dj(this.client,V$.byId,$,O)}byId($){return V$.byId(this.client,$)}create($){return V$.create(this.client,$)}list(){return V$.list(this.client)}}class VO extends C{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 $=Y(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 l$ extends C{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 Y(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new l$($,O,j)}static from($,O,j){return new l$($,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 A.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}=$$($);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 tO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new W$(async()=>Y(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new tO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var zS=8;class q extends Z${async anchors(){return Y(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,Y(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return tO.byId(this.client,this,$)}async sharePermissions(){return Y(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return Y(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return Y(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)=>l$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=Y(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}=Y(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}=Y(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}=Y(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 c(async(x)=>{let S=Y(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}=Y(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",($)=>A.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:$}=Y(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=Y(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new YO(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}=Y(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=c(async(x)=>{let S=Y(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,zS,async(x)=>{let{state:S,root:K,replies:Z}=Y(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>l$.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:{...$$($),thread_id:O?.threadId??null}}));return l$.from(this.client,this.id,j)}async shortId(){return Y(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return Y(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:$}=Y(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=Y(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=j$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:i$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Aj{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=Y(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Aj(j.id,j.name))}}class Yx{client;async byTeamSlug($){let O=Y(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=Y(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?A.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=Y(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=Y(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 Aj.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 C{async fetch(){let{attachment:$}=Y(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:$}=Y(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class z$ extends Z${access=new o(this.client,"email_thread",this);async followup(){return Y(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return Y(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return Y(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async addEventToCalendar($,O,j={}){let x=Y(await this.client.email.copyThreadCalendarInvitation({path:{thread_id:this.id,message_id:$.id,invitation_id:O.id},body:{calendarId:j.calendar?.id}}));return x$.fromRecord(this.client,x)}async readReceipts(){let{receipts:$}=Y(await this.client.email.getThreadReadReceipts({path:{thread_id:this.id}}));return $.map((O)=>({message:U$.byId(this.client,O.message_id),openCount:O.open_count,firstOpenedAt:O.first_opened_at??void 0,lastOpenedAt:O.last_opened_at??void 0}))}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?n$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=Y(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new z$($,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",($)=>R$.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 Y(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>U$.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?U$.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=Y(await $.email.archiveThreads({body:{thread_ids:K.map((G)=>G.id),value:j}})),X=new Set(Z.failed_thread_ids);for(let G of K)if(G.detail.clear(),X.has(G.id))x.push(G)}return x}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return Y(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=j$({filters:{email_filters:{}},type:"email",make:($,O)=>new z$($,O.thread_id)})}class U$ extends C{async fetch(){return Y(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new U$($,O)}static from($,O){return new U$($,O.db_id,O)}static async send($,O){let{message:j}=Y(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?U$.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",($)=>R$.byId(this.client,$));async operationStatus(){return Y(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 z$.byId(this.client,(await this.detail.get()).thread_db_id)}async downloadEml(){return Y(await this.client.email.getMessageEml({path:{id:this.id},parseAs:"blob"}))}}class BO extends U${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 BO($,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:{...Qx($),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:eO.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 eO.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 eO{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 eO(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 Qx($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,draftGeneration:Z,thread:X,replyingTo:G,...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:G?.id}}class LO extends C{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 LO($,O,void 0,j)}static from($,O,j){return new LO($,O.id,O,j)}async fetch(){let $=Y(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 jO extends C{async fetch(){let{labels:$}=Y(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 jO($,O)}static async list($){let{labels:O}=Y(await $.email.listLabels());return O.map((j)=>new jO($,j.id,j))}static async create($,O){let{label:j}=Y(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new jO($,j.id)}async delete(){Y(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 Jx{client;async createDraft($,O){let j=Y(await this.client.email.createDraft({body:{draft:Qx($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return BO.byId(this.client,j.draft.db_id)}draftById($){return BO.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=Y(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 BO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return Y(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>LO.from(this.client,O,$))}async upsertFilter($,O){return LO.from(this.client,Y(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 Y(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return c(async(x)=>{let S=Y(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:z$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return z$.byId(this.client,$)}message($){return U$.byId(this.client,$)}attachment($){return WO.byId(this.client,$)}link($){return R$.byId(this.client,$)}links(){return R$.list(this.client)}async connectionProviders(){return Y(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return Y(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return U$.send(this.client,$)}search($,O){return z$.search(this.client,$,O)}inbox($){return c(async(O)=>{let j=Y(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)=>z$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return jO.byId(this.client,$)}labels(){return jO.list(this.client)}createLabel($){return jO.create(this.client,$)}archive($,O=!0){return z$.archiveMany(this.client,$,O)}async deleteLabel($){Y(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){Y(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){Y(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return Y(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(){Y(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class Vx{client;constructor($){this.client=$}byId($){return HO.byId(this.client,$)}async create($,O){let j=Y(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)}}function Wx($,O){return{chat:NO.byId($,O.id),name:O.name,announcements:O.announcements}}class NO extends C{static byId($,O){return new NO($,O)}static from($,O){return new NO($,O.jid,O)}async fetch(){let{chats:$}=Y(await this.client.storage.whatsappChats()),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");phoneNumber=this.field("phoneNumber");lastActivityAt=this.field("lastActivityAt");archived=this.field("archived");pinned=this.field("pinned");canAdd=this.field("canAdd");cannotAddReason=this.field("cannotAddReason");community=this.mappedField("community",($)=>$?Wx(this.client,$):void 0);added=this.mappedField("added",($)=>$?g$.byId(this.client,$.id):void 0);shared=this.mappedField("shared",($)=>$?g$.byId(this.client,$.id):void 0);async add(){let $=await this.kind(),O=await this.mutate((j)=>j.storage.externalChatAdd({body:{provider:"whatsapp",remoteId:this.id,kind:$}}));return g$.byId(this.client,O.chatId)}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class M$ extends C{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new M$($,O,j)}static from($,O,j){return new M$($,O,j.id,j)}async fetch(){return Y(await this.client.storage.externalChatMessage({path:{chat_id:this.chat.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",($)=>$?M$.byId(this.client,this.chat,$):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 xO{chat;id;record;constructor($,O,j){this.chat=$;this.id=O;this.record=j}static byId($,O){return new xO($,O)}static from($,O){return new xO($,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,chat:this.chat.id,displayName:this.displayName,admin:this.admin}}}class SO{id;chat;filename;kind;constructor($,O,j,x){this.id=$;this.chat=O;this.filename=j;this.kind=x}static byId($,O){return new SO(O,$)}static from($,O){return new SO(O.uploadId,$,O.filename,O.kind)}toJSON(){return{id:this.id,chat:this.chat.id,filename:this.filename,kind:this.kind}}}class ZO extends C{chat;constructor($,O,j,x){super($,j,x);this.chat=O}static byId($,O,j){return new ZO($,O,j)}static from($,O,j){return new ZO($,O,j.id,j)}async fetch(){let O=Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.chat.id},body:[this.id]})).find((j)=>j.id===this.id);if(!O)throw new E("External chat send is not available");return O}state=this.field("state");errorCode=this.field("errorCode");createdAt=this.field("createdAt");message=this.mappedField("messageId",($)=>$?M$.byId(this.client,this.chat,$):void 0);async request(){let{payload:$}=await this.detail.get(),O=$.message,j=k(O).returnType().with({type:"media"},(x)=>({type:"media",upload:SO.byId(this.chat,x.uploadId),caption:x.caption??void 0})).with({type:"mutation"},(x)=>({type:"mutation",message:M$.byId(this.client,this.chat,x.messageId),operation:x.operation,text:x.text??void 0})).with({type:"text"},(x)=>({type:"text",text:x.text,mentions:(x.mentions??[]).map((S)=>xO.byId(this.chat,S))})).exhaustive();return{idempotencyKey:$.idempotencyKey,message:j,replyTo:$.replyTo?M$.byId(this.client,this.chat,$.replyTo):void 0}}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class g$ extends H${entityType="external_chat";static byId($,O){return new g$($,O)}async fetch(){return Y(await this.client.storage.externalChat({path:{chat_id:this.id}}))}provider=this.field("provider");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");members=this.field("members");participants=this.mappedField("members",($)=>($?.participants??[]).map((O)=>xO.from(this,O)));disappearingSeconds=this.field("disappearingSeconds");owner=this.mappedField("userId",($)=>A.byId(this.client,$));async community(){let{provider:$,community:O}=await this.detail.get();if(!O)return;return k($).with("whatsapp",()=>Wx(this.client,O)).exhaustive()}async*messages($={}){yield*c(async(O)=>{let j=Y(await this.client.storage.externalChatMessages({path:{chat_id:this.id},query:{before:O,limit:$.limit}}));return{items:j.messages.map((x)=>M$.from(this.client,this,x)),nextCursor:j.nextCursor}})}async markRead($){this.assertChat($.chat),await this.mutate((O)=>O.storage.externalChatRead({path:{chat_id:this.id},body:{messageId:$.id}}))}async permissions(){return Y(await this.client.storage.externalChatPermissions({path:{chat_id:this.id}}))}async updatePermissions($){await this.mutate((O)=>O.storage.externalChatUpdatePermissions({path:{chat_id:this.id},body:$}))}async remove(){await this.mutate(($)=>$.storage.externalChatRemove({path:{chat_id:this.id}}))}async upload($){let O=Y(await this.client.storage.externalChatUpload({path:{chat_id:this.id},body:{file:$}}));return SO.from(this,O)}async send($,O){if(O.replyTo)this.assertChat(O.replyTo.chat);let j=k($).returnType().with({type:"text"},(S)=>{let K=S.mentions??[];for(let Z of K)this.assertChat(Z.chat);return{type:"text",text:S.text,mentions:K.map((Z)=>Z.id)}}).with({type:"media"},(S)=>{return this.assertChat(S.upload.chat),{type:"media",uploadId:S.upload.id,caption:S.caption}}).with({type:"mutation"},(S)=>{return this.assertChat(S.message.chat),{type:"mutation",messageId:S.message.id,operation:S.operation,text:S.text}}).exhaustive(),x=await this.mutate((S)=>S.storage.externalChatSend({path:{chat_id:this.id},body:{idempotencyKey:O.idempotencyKey,message:j,replyTo:O.replyTo?.id}}));return ZO.from(this.client,this,x)}async sends(){return Y(await this.client.storage.externalChatSends({path:{chat_id:this.id}})).map(($)=>ZO.from(this.client,this,$))}async delivery($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatDelivery({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>ZO.from(this.client,this,O))}async messageAttachments($){for(let O of $)this.assertChat(O.chat);return Y(await this.client.storage.externalChatMessageAttachments({path:{chat_id:this.id},body:$.map((O)=>O.id)})).map((O)=>({message:M$.byId(this.client,this,O.messageId),attachments:O.attachments.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}assertChat($){if($.id!==this.id)throw Error("External chat reference belongs to another chat")}}class Bx{client;constructor($){this.client=$}async list(){return Y(await this.client.storage.externalChats()).map(($)=>g$.byId(this.client,$.id))}byId($){return g$.byId(this.client,$)}}class Lx{client;constructor($){this.client=$}async list($={}){let{favorites:O}=Y(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return Y(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){Y(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){Y(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class XO extends H${entityType="foreign_entity";async fetch(){return Y(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new XO($,O)}static fromRecord($,O){return new XO($,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 e1({login:$,...O}){return{...O,login:$??void 0}}class Nx{client;constructor($){this.client=$}byId($){return XO.byId(this.client,$)}async bySource($,O){return XO.fromRecord(this.client,Y(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=Y(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(e1),assignees:j.map(e1),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 P$.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 TO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new W$(()=>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 TO($,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 W$(()=>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 Cj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Cj($,O)}}class y$ extends C{async fetch(){return Y(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new y$($,O)}static async create($,O){let j=Y(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 Y(await $.storage.listAccessibleForms()).map(({form:S})=>new y$($,S.id));return Y(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",($)=>A.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 b(`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 b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>k(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:k(G.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:S$.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??c$(),title:Z.title,description:Z.description??""};return k(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??c$(),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=k(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 b("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:S$.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 k($).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:TO.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(Y(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(Y(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=Y(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 k(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return UO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Cj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Q=J$.byId(V$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((J)=>F$.byId(Q,J))}}).with({type:S$.union("text","number","boolean","date","date_range","link","clear")},(G)=>G).exhaustive(()=>{throw new b(`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:TO.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 $=Y(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 Y(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)=>k(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 Y(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 Ux{client;constructor($){this.client=$}byId($){return y$.byId(this.client,$)}create($){return y$.create(this.client,$)}list($){return y$.list(this.client,$)}}class RO extends C{static byId($,O){return new RO($,O)}async fetch(){return Y(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=Y(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new zx(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class zx{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return Y(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class Ix{client;constructor($){this.client=$}byId($){return RO.byId(this.client,$)}forEntity($){return RO.byId(this.client,$.id)}}class DO extends C{static byId($,O){return new DO($,O)}async fetch(){return Y(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 B$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class oO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new oO($,O)}async claim($){let O=Y(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:B$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class Hx{client;constructor($){this.client=$}byId($){return B$.byId(this.client,$)}async list(){return Y(await this.client.storage.listHarnesses()).map(($)=>B$.from(this.client,$))}async me(){return B$.from(this.client,Y(await this.client.storage.getSelfHarness()))}async deleteSelf(){Y(await this.client.storage.deleteSelfHarness())}async agents(){return Y(await this.client.storage.listHarnessAgents()).map(($)=>T$.byId(this.client,$.bot_id))}async sessions(){return Y(await this.client.storage.listHarnessSessions()).map(($)=>l.byId(this.client,$.session_id))}pairing($){return DO.byId(this.client,$)}async createPairing($){let O=Y(await this.client.storage.createHarnessPairing({body:$}));return{pairing:DO.byId(this.client,O.code),device:oO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}class Pj{id;url;width;height;constructor($,O,j,x){this.id=$;this.url=O;this.width=j;this.height=x}static byId($,O,j){return new Pj(O,`${$.hosts["static-files"]}/file/${O}`,j?.width,j?.height)}toJSON(){return{id:this.id,url:this.url,width:this.width,height:this.height}}}class Fj extends Pj{width;height;mimeType;sizeBytes;note;constructor($,O,j,x,S,K,Z){super($,O,j,x);this.width=j;this.height=x;this.mimeType=S;this.sizeBytes=K;this.note=Z}toJSON(){return{...super.toJSON(),mimeType:this.mimeType,sizeBytes:this.sizeBytes,note:this.note}}}class Tx{client;constructor($){this.client=$}async generate($){let O=Y(await this.client.cognition.generateImage({body:{prompt:$.prompt,aspectRatio:$.aspectRatio??null,referenceImages:($.referenceImages??[]).map(IS)}}));return new Fj(O.staticFileId,O.url,O.width,O.height,O.mimeType,O.sizeBytes,O.note??void 0)}}function IS($){return $ instanceof q?{type:"document",id:$.id}:{type:"staticFile",id:$.id}}var HS="00000001-0000-0000-0000-000000000001",o1="00000001-0000-0000-0000-000000000002",TS="00000001-0000-0000-0000-000000000004",RS="00000001-0000-0000-0000-000000000014",DS="00000001-0000-0000-0002-000000000001",_S="00000001-0000-0000-0002-000000000004";function MS($){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 Y$ extends q{static byId($,O){return new Y$($,O)}static async create($,O){let{documentId:j}=Y(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,propertyValues:await AS($,O)}}));return new Y$($,j)}static async summaries($,O){if(O.length===0)return[];let{previews:j}=Y(await $.storage.getBatchPreviewHandler({body:{document_ids:O.map((S)=>S.id)}})),x=new Map(j.flatMap((S)=>S.type==="access"?[[S.document_id,S]]:[]));return O.flatMap((S)=>{let K=x.get(S.id);if(!K)return[];return[{task:S,name:K.document_name,owner:A.byId($,K.owner),updatedAt:K.updated_at??void 0,completed:K.sub_type?.type==="task"&&K.sub_type.is_completed}]})}static async findSimilar($,O){let{results:j}=Y(await $.storage.taskSimilaritySearchHandler({body:{taskName:O.title,markdown:O.body??null}}));return j.map((x)=>({task:new Y$($,x.taskId),name:x.taskName,similarity:x.vectorScore}))}static async forPullRequest($,O){let j=MS(O),{pullRequests:x}=Y(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new Y$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===o1)?.value;return j?.type==="SelectOption"&&j.value.includes(_S)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=j$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new Y$($,O.document_id)})}async function AS($,O){if(!O.initiative&&!O.assignees&&!O.dueDate)return null;let j=O.assignees??[await A.me($)],x=[{propertyId:o1,value:{type:"select_option",option_id:DS}}];if(j.length>0)x.push({propertyId:HS,value:{type:"multi_entity_reference",references:j.map((S)=>({entity_id:S.id,entity_type:"USER"}))}});if(O.initiative)x.push({propertyId:RS,value:{type:"entity_reference",reference:{entity_id:O.initiative.id,entity_type:"INITIATIVE"}}});if(O.dueDate)x.push({propertyId:TS,value:{type:"date",value:O.dueDate.toISOString()}});return x}class a$ extends C{access=new o(this.client,"initiative",this);static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return Y(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>A.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>A.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>Y$.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?n$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Rx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>a$.byId(this.client,$.id))}async summaries(){return Y(await this.client.storage.listInitiatives()).initiatives.map(($)=>({initiative:a$.byId(this.client,$.id),name:$.name,updatedAt:$.updatedAt}))}async create($){return a$.from(this.client,Y(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Dx{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}async create($){return D$.from(this.client,Y(await this.client.storage.meetingCreate({body:$})))}async list(){return Y(await this.client.storage.meetingList()).meetings.map(($)=>D$.from(this.client,$))}async active(){return Y(await this.client.storage.meetingListActive()).meetings.map(($)=>D$.from(this.client,$))}async lookup($){return D$.from(this.client,Y(await this.client.storage.meetingLookup({path:{token:$}})))}}class zO extends C{async fetch(){return Y(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 c(async(j)=>{let x=Y(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",($)=>A.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?A.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 _x{client;constructor($){this.client=$}byId($){return zO.byId(this.client,$)}list($){return zO.list(this.client,$)}async markSeen($){Y(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){Y(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){Y(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return Y(await this.client.notification.getNotificationTypePreferences())}async enableType($){Y(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){Y(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class Mx{client;constructor($){this.client=$}async list(){let{data:$}=Y(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){Y(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){Y(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){Y(await this.client.storage.reorderPinsHandler({body:$}))}}class Ax{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 _O{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 _O($,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=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class KO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new W$(()=>this.fetch(),j)}async fetch(){return Y(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=Y(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new KO($,j.id,j)}static byId($,O){return new KO($,O)}static fromRecord($,O){return new KO($,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 Y(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return Y(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>_O.from(this.client,this.id,O))}async addOption($){let O=Y(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return _O.from(this.client,this.id,O)}async updateOption($,O){let j=Y(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return _O.from(this.client,this.id,j)}async deleteOption($){return Y(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class Cx{client;constructor($){this.client=$}async list($){return Y(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 KO.fromRecord(this.client,x)})}create($){return KO.create(this.client,$)}definition($){return KO.byId(this.client,$)}async bulkEntityProperties($){return Y(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return Y(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 Y(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return Y(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return Y(await this.client.properties.listTags({}))}}function Px($){return k($).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 CS($){return k($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(Px)})).with({type:"cron"},Px).with({type:"events"},Px).exhaustive()}class v$ extends C{static byId($,O){return new v$($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new v$($,O.id,O)}async fetch(){return Y(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",($)=>A.byId(this.client,$));sourceTemplate=this.mappedField("template_id",($)=>$?v$.byId(this.client,$):void 0);async template(){let $=await this.client.scheduledAction.getScheduledActionTemplate({path:{id:this.id}});if($.response?.status===404)return;return this.toTemplate(Y($))}async shareAsTemplate($){return this.toTemplate(Y(await this.client.scheduledAction.shareScheduledActionTemplate({path:{id:this.id},body:$})))}async activateTemplate($){return v$.from(this.client,Y(await this.client.scheduledAction.activateScheduledActionTemplate({path:{id:this.id},body:{...Ej($),enabled:$.enabled??!0}})))}toTemplate($){return new $2(this,A.byId(this.client,$.author),$)}async stopSharingTemplate(){Y(await this.client.scheduledAction.unshareScheduledActionTemplate({path:{id:this.id}}))}async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:Ej($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=Y(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return k($.resource).with({type:"agent"},(O)=>l.byId(this.client,O.id)).with({type:"chat"},(O)=>X$.byId(this.client,O.id)).exhaustive();return $.chat_id?X$.byId(this.client,$.chat_id):void 0}async history(){return Y(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new Fx(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class $2{routine;author;record;constructor($,O,j){this.routine=$;this.author=O;this.record=j}activate($){return this.routine.activateTemplate($)}toJSON(){return this.record}}class Fx{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 Ej($){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:CS($.trigger),task:{...O}}}class Ex{client;constructor($){this.client=$}byId($){return v$.byId(this.client,$)}async create($){return v$.from(this.client,Y(await this.client.scheduledAction.createScheduledAction({body:{...Ej($),enabled:$.enabled??!0}})))}async list($){return Y(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>v$.from(this.client,O))}}class wx{client;constructor($){this.client=$}byId($){return Y$.byId(this.client,$)}create($){return Y$.create(this.client,$)}summaries($){return Y$.summaries(this.client,$)}findSimilar($){return Y$.findSimilar(this.client,$)}forPullRequest($){return Y$.forPullRequest(this.client,$)}search($,O){return Y$.search(this.client,$,O)}}class qx{client;constructor($){this.client=$}byId($){return _$.byId(this.client,$)}current(){return _$.current(this.client)}list(){return _$.list(this.client)}}class fx{client;constructor($){this.client=$}async get($){return Y(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return Y(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class bx{client;constructor($){this.client=$}byId($){return A.byId(this.client,$)}me(){return A.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}=Y(j),S=[...new Set(x)],K=[];for(let Z=0;Z<S.length;Z+=100){let X=S.slice(Z,Z+100),{names:G}=Y(await this.client.auth.getUserNamesWithEmail({body:{user_ids:X}})),L=new Map(G.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(A.fromName(this.client,J))}}return K}}class GO extends C{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return Y(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=Y(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 GO($,j.id,j,j.signing_secret)}static byId($,O){return new GO($,O)}static fromRecord($,O){return new GO($,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",($)=>A.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 kx{client;constructor($){this.client=$}create($){return GO.create(this.client,$)}byId($){return GO.byId(this.client,$)}async list(){let{webhooks:$}=Y(await this.client.storage.listWebhooks());return $.map((O)=>GO.fromRecord(this.client,O))}}class MO extends C{static byId($,O){return new MO($,O)}static from($,O){return new MO($,O.id,O)}async fetch(){let{account:$}=Y(await this.client.storage.whatsappAccount());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",($)=>A.byId(this.client,$));async refresh(){return this.detail.clear(),await this.detail.get(),this}}class gx{client;constructor($){this.client=$}async account(){let{account:$}=Y(await this.client.storage.whatsappAccount());return $?MO.from(this.client,$):void 0}async chats(){return Y(await this.client.storage.whatsappChats()).chats.map(($)=>NO.from(this.client,$))}}function yx($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function O2($,O,j){let x=[];for(let S of yx(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:X$.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:z$.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:f.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:x$.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:XO.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 j2="00000000-0000-0000-0000-000000000000",vx={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"]},wj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),x2=($,O)=>$==null?O:{"&":[$,O]};function hx($,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==="!"){hx(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)=>{hx(Z,`${O}.${S}[${X}]`)})}class qj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(Y),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(vx,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(vx).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)hx($[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:j2}},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}=Y(await this.client.email.listLinks()),K=S.filter((X)=>wj(X.email_address)===wj(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=x2(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(vx))if(!x.includes(S))O[K]={l:{[Z]:j2}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Q)=>Q.value.type==="string"?[{id:Q.id,definitionId:L.id,label:Q.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Q)=>wj(Q.label)===wj(G.label.trim())&&(!G.scope||Q.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Q)=>`${Q.label} (${Q.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Q of L)K.set(Q.id,Q)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=x2(O.propf,X)}return O}}class mx{client;constructor($){this.client=$}async page($={}){let O=new qj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new qj(this.client),j=await O.body($);yield*c((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=Y(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>yx(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>O2(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function S2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var FS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ES=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},qS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},bj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(ES(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=FS(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)}`},kj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=qS(x),X=Object.entries(S).map(([G,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var wS=/\{[^{}]+\}/g,fS=({path:$,url:O})=>{let j=O,x=O.match(wS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,bj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,kj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},X2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=fS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function cx($){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 K2=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 G2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Y2=({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 G=bj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=kj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=PO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},Q2=($)=>{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},bS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function J2($){for(let O of $.security??[]){if(bS($,O.name))continue;let j=await K2(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 dx=($)=>X2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Y2($.querySerializer),url:$.url}),lx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=yj($.headers,O.headers),j},kS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},yj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?kS(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 gj{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 gj,request:new gj,response:new gj}),gS=Y2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),yS={"Content-Type":"application/json"},Oj=($={})=>({...G2,headers:yS,parseAs:"auto",querySerializer:gS,...$});var rx=($={})=>{let O=lx(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=lx(O,Q),j()},S=V2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:yj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await J2(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=dx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:cx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Q2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return Z2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:cx(I),url:z})};return{buildUrl:(Q)=>dx({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var W2=rx(Oj());class B2{client;constructor($){this.client=$?.client??W2}}class L2{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 vj extends B2{static __registry=new L2;constructor($){super($);vj.__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 N2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var PS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},FS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},ES=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},fj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(FS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=PS(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)}`},bj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=ES(x),X=Object.entries(S).map(([G,L])=>AO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var wS=/\{[^{}]+\}/g,qS=({path:$,url:O})=>{let j=O,x=O.match(wS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,fj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,bj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${AO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},Z2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=qS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ux($){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 X2=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 K2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var G2=({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 G=fj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=bj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=AO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},Y2=($)=>{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},fS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function Q2($){for(let O of $.security??[]){if(fS($,O.name))continue;let j=await X2(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 cx=($)=>Z2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:G2($.querySerializer),url:$.url}),dx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=gj($.headers,O.headers),j},bS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},gj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?bS(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 kj{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 J2=()=>({error:new kj,request:new kj,response:new kj}),kS=G2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),gS={"Content-Type":"application/json"},$j=($={})=>({...K2,headers:gS,parseAs:"auto",querySerializer:kS,...$});var lx=($={})=>{let O=dx($j(),$),j=()=>({...O}),x=(Q)=>{return O=dx(O,Q),j()},S=J2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:gj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await Q2(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=cx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:ux(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Y2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return S2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ux(I),url:z})};return{buildUrl:(Q)=>cx({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var V2=lx($j());class W2{client;constructor($){this.client=$?.client??V2}}class B2{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 yj extends W2{static __registry=new B2;constructor($){super($);yj.__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 L2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var vS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},mS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},hj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(hS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=vS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({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)}`},mj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=mS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var uS=/\{[^{}]+\}/g,cS=({path:$,url:O})=>{let j=O,x=O.match(uS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,mj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=cS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function px($){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 z2=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 I2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H2=({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 G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=mj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T2=($)=>{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},dS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R2($){for(let O of $.security??[]){if(dS($,O.name))continue;let j=await z2(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 ax=($)=>U2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H2($.querySerializer),url:$.url}),ix=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=cj($.headers,O.headers),j},lS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},cj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?lS(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 uj{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 D2=()=>({error:new uj,request:new uj,response:new uj}),rS=H2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pS={"Content-Type":"application/json"},jj=($={})=>({...I2,headers:pS,parseAs:"auto",querySerializer:rS,...$});var nx=($={})=>{let O=ix(jj(),$),j=()=>({...O}),x=(Q)=>{return O=ix(O,Q),j()},S=D2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:cj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R2(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=ax(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:px(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:px(I),url:z})};return{buildUrl:(Q)=>ax({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _2=nx(jj());class M2{client;constructor($){this.client=$?.client??_2}}class A2{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 dj extends M2{static __registry=new A2;constructor($){super($);dj.__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}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,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}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,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}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}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}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}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 P2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var yS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},vS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},hS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},vj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(vS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=yS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},CO=({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)}`},hj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=hS(x),X=Object.entries(S).map(([G,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var mS=/\{[^{}]+\}/g,uS=({path:$,url:O})=>{let j=O,x=O.match(mS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,vj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,hj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},N2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=uS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function rx($){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 U2=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 z2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var I2=({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 G=vj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=hj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=CO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},H2=($)=>{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},cS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function T2($){for(let O of $.security??[]){if(cS($,O.name))continue;let j=await U2(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 px=($)=>N2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:I2($.querySerializer),url:$.url}),ax=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=uj($.headers,O.headers),j},dS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},uj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?dS(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 mj{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 R2=()=>({error:new mj,request:new mj,response:new mj}),lS=I2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),rS={"Content-Type":"application/json"},Oj=($={})=>({...z2,headers:rS,parseAs:"auto",querySerializer:lS,...$});var ix=($={})=>{let O=ax(Oj(),$),j=()=>({...O}),x=(Q)=>{return O=ax(O,Q),j()},S=R2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:uj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await T2(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=px(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:rx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?H2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return L2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:rx(I),url:z})};return{buildUrl:(Q)=>px({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var D2=ix(Oj());class _2{client;constructor($){this.client=$?.client??D2}}class M2{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 cj extends _2{static __registry=new M2;constructor($){super($);cj.__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}})}purchaseAiCredits($){return($.client??this.client).post({url:"/ai-billing/credits/purchase",...$,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}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,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}",...$})}getSystemStatus($){return($?.client??this.client).get({url:"/system-status",...$})}setSystemStatus($){return($.client??this.client).post({url:"/system-status",...$,headers:{"Content-Type":"application/json",...$.headers}})}listSystemStatusHistory($){return($?.client??this.client).get({url:"/system-status/history",...$})}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}})}sendTeamDomainNotice($){return($?.client??this.client).post({url:"/team/domain-notice",...$})}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 A2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var aS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},iS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},nS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},lj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(iS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=aS(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)}`},rj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=nS(x),X=Object.entries(S).map(([G,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var sS=/\{[^{}]+\}/g,tS=({path:$,url:O})=>{let j=O,x=O.match(sS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,lj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,rj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},C2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=tS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function sx($){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 E2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var q2=({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 G=lj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=rj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=FO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}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},eS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function f2($){for(let O of $.security??[]){if(eS($,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 tx=($)=>C2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:q2($.querySerializer),url:$.url}),ex=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=aj($.headers,O.headers),j},oS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},aj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?oS(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 pj{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 b2=()=>({error:new pj,request:new pj,response:new pj}),$5=q2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),O5={"Content-Type":"application/json"},xj=($={})=>({...E2,headers:O5,parseAs:"auto",querySerializer:$5,...$});var ox=($={})=>{let O=ex(xj(),$),j=()=>({...O}),x=(Q)=>{return O=ex(O,Q),j()},S=b2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:aj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await f2(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=tx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:sx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?w2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return P2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:sx(I),url:z})};return{buildUrl:(Q)=>tx({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var k2=ox(xj());class g2{client;constructor($){this.client=$?.client??k2}}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 ij extends g2{static __registry=new y2;constructor($){super($);ij.__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 v2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var pS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},aS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},iS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(aS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=pS(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)}`},lj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=iS(x),X=Object.entries(S).map(([G,L])=>PO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var nS=/\{[^{}]+\}/g,sS=({path:$,url:O})=>{let j=O,x=O.match(nS);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,lj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${PO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},C2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=sS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function nx($){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 P2=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 F2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var E2=({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 G=dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=lj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=PO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}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},tS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function q2($){for(let O of $.security??[]){if(tS($,O.name))continue;let j=await P2(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 sx=($)=>C2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:E2($.querySerializer),url:$.url}),tx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=pj($.headers,O.headers),j},eS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},pj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?eS(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 rj{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 f2=()=>({error:new rj,request:new rj,response:new rj}),oS=E2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$5={"Content-Type":"application/json"},jj=($={})=>({...F2,headers:$5,parseAs:"auto",querySerializer:oS,...$});var ex=($={})=>{let O=tx(jj(),$),j=()=>({...O}),x=(Q)=>{return O=tx(O,Q),j()},S=f2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:pj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await q2(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=sx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:nx(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?w2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return A2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:nx(I),url:z})};return{buildUrl:(Q)=>sx({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var b2=ex(jj());class k2{client;constructor($){this.client=$?.client??b2}}class g2{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 aj extends k2{static __registry=new g2;constructor($){super($);aj.__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}})}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}})}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 y2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var j5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},S5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},nj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(x5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=j5(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)}`},sj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=S5(x),X=Object.entries(S).map(([G,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Z5=/\{[^{}]+\}/g,X5=({path:$,url:O})=>{let j=O,x=O.match(Z5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,nj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,sj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);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=X5({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 m2=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 u2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var c2=({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 G=nj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=EO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},d2=($)=>{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},K5=($,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(K5($,O.name))continue;let j=await m2(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=($)=>h2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:c2($.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=ej($.headers,O.headers),j},G5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},ej=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G5(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 tj{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 r2=()=>({error:new tj,request:new tj,response:new tj}),Y5=c2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Q5={"Content-Type":"application/json"},Sj=($={})=>({...u2,headers:Q5,parseAs:"auto",querySerializer:Y5,...$});var x1=($={})=>{let O=j1(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=j1(O,Q),j()},S=r2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:ej(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=O1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:$1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?d2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return v2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var p2=x1(Sj());class a2{client;constructor($){this.client=$?.client??p2}}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 oj extends a2{static __registry=new i2;constructor($){super($);oj.__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}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}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 n2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var O5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ij=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O5(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)}`},nj=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x5(x),X=Object.entries(S).map(([G,L])=>FO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S5=/\{[^{}]+\}/g,Z5=({path:$,url:O})=>{let j=O,x=O.match(S5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,ij({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,nj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${FO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},v2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function ox($){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 h2=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 m2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var u2=({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 G=ij({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=nj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=FO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}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},X5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function d2($){for(let O of $.security??[]){if(X5($,O.name))continue;let j=await h2(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 $1=($)=>v2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:u2($.querySerializer),url:$.url}),O1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=tj($.headers,O.headers),j},K5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},tj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?K5(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 sj{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 l2=()=>({error:new sj,request:new sj,response:new sj}),G5=u2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y5={"Content-Type":"application/json"},xj=($={})=>({...m2,headers:Y5,parseAs:"auto",querySerializer:G5,...$});var j1=($={})=>{let O=O1(xj(),$),j=()=>({...O}),x=(Q)=>{return O=O1(O,Q),j()},S=l2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:tj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await d2(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=$1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:ox(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?c2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return y2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:ox(I),url:z})};return{buildUrl:(Q)=>$1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var r2=j1(xj());class p2{client;constructor($){this.client=$?.client??r2}}class a2{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 ej extends p2{static __registry=new a2;constructor($){super($);ej.__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}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}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 i2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var J5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},W5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},$0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(V5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=J5(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)}`},O0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=W5(x),X=Object.entries(S).map(([G,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var B5=/\{[^{}]+\}/g,L5=({path:$,url:O})=>{let j=O,x=O.match(B5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,$0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,O0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},s2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=L5({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 t2=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 e2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var o2=({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 G=$0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=O0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=qO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},$6=($)=>{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},N5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function O6($){for(let O of $.security??[]){if(N5($,O.name))continue;let j=await t2(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=($)=>s2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:o2($.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=x0($.headers,O.headers),j},U5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},x0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?U5(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 j0{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 j6=()=>({error:new j0,request:new j0,response:new j0}),z5=o2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),I5={"Content-Type":"application/json"},Zj=($={})=>({...e2,headers:I5,parseAs:"auto",querySerializer:z5,...$});var K1=($={})=>{let O=X1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=X1(O,Q),j()},S=j6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:x0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await O6(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:S1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?$6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return n2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var x6=K1(Zj());class S6{client;constructor($){this.client=$?.client??x6}}class Z6{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 S0 extends S6{static __registry=new Z6;constructor($){super($);S0.__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 X6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},oj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q5(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)}`},$0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V5(x),X=Object.entries(S).map(([G,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W5=/\{[^{}]+\}/g,B5=({path:$,url:O})=>{let j=O,x=O.match(W5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,oj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,$0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},n2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function x1($){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 s2=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 t2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var e2=({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 G=oj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=$0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=EO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},o2=($)=>{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},L5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function $6($){for(let O of $.security??[]){if(L5($,O.name))continue;let j=await s2(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 S1=($)=>n2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:e2($.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=j0($.headers,O.headers),j},N5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},j0=(...$)=>{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 O0{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 O6=()=>({error:new O0,request:new O0,response:new O0}),U5=e2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z5={"Content-Type":"application/json"},Sj=($={})=>({...t2,headers:z5,parseAs:"auto",querySerializer:U5,...$});var X1=($={})=>{let O=Z1(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=Z1(O,Q),j()},S=O6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:j0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await $6(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=S1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:x1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?o2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return i2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:x1(I),url:z})};return{buildUrl:(Q)=>S1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var j6=X1(Sj());class x6{client;constructor($){this.client=$?.client??j6}}class S6{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 x0 extends x6{static __registry=new S6;constructor($){super($);x0.__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 Z6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T5=($)=>{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"&"}},Z0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=H5(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)}`},X0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.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(([G,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D5=/\{[^{}]+\}/g,_5=({path:$,url:O})=>{let j=O,x=O.match(D5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Z0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,X0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},K6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function G1($){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 G6=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 Y6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Q6=({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 G=Z0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=X0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=wO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},J6=($)=>{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},M5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function V6($){for(let O of $.security??[]){if(M5($,O.name))continue;let j=await G6(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 Y1=($)=>K6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Q6($.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=G0($.headers,O.headers),j},A5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},G0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A5(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 K0{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 W6=()=>({error:new K0,request:new K0,response:new K0}),P5=Q6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C5={"Content-Type":"application/json"},Xj=($={})=>({...Y6,headers:C5,parseAs:"auto",querySerializer:P5,...$});var J1=($={})=>{let O=Q1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=Q1(O,Q),j()},S=W6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:G0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await V6(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=Y1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:G1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?J6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return X6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:G1(I),url:z})};return{buildUrl:(Q)=>Y1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var B6=J1(Xj());class L6{client;constructor($){this.client=$?.client??B6}}class N6{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 Y0 extends L6{static __registry=new N6;constructor($){super($);Y0.__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}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}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}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function U6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var I5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},T5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},S0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(H5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=I5(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)}`},Z0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=T5(x),X=Object.entries(S).map(([G,L])=>wO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var R5=/\{[^{}]+\}/g,D5=({path:$,url:O})=>{let j=O,x=O.match(R5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,S0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Z0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${wO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},X6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=D5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function K1($){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 K6=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 G6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var Y6=({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 G=S0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Z0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=wO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},Q6=($)=>{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},_5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function J6($){for(let O of $.security??[]){if(_5($,O.name))continue;let j=await K6(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=($)=>X6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Y6($.querySerializer),url:$.url}),Y1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=K0($.headers,O.headers),j},M5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},K0=(...$)=>{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 X0{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 V6=()=>({error:new X0,request:new X0,response:new X0}),A5=Y6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C5={"Content-Type":"application/json"},Zj=($={})=>({...G6,headers:C5,parseAs:"auto",querySerializer:A5,...$});var Q1=($={})=>{let O=Y1(Zj(),$),j=()=>({...O}),x=(Q)=>{return O=Y1(O,Q),j()},S=V6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:K0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await J6(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:K1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?Q6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return Z6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:K1(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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var W6=Q1(Zj());class B6{client;constructor($){this.client=$?.client??W6}}class L6{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 G0 extends B6{static __registry=new L6;constructor($){super($);G0.__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}",...$})}forwardCalendarEvent($){return($.client??this.client).post({url:"/email/calendar-events/{event_id}/forward",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}",...$})}getMessageEml($){return($.client??this.client).get({url:"/email/messages/{id}/eml",...$})}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}})}getThreadReadReceipts($){return($.client??this.client).get({url:"/email/threads/{thread_id}/read-receipts",...$})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}getReadReceiptPixel($){return($.client??this.client).get({url:"/opens/{token}",...$})}}function N6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var F5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},q5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Q0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(E5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=F5(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)}`},J0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=q5(x),X=Object.entries(S).map(([G,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var w5=/\{[^{}]+\}/g,f5=({path:$,url:O})=>{let j=O,x=O.match(w5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Q0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,J0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},z6=({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 I6=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 H6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var T6=({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 G=Q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=J0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=fO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},R6=($)=>{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},b5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function D6($){for(let O of $.security??[]){if(b5($,O.name))continue;let j=await I6(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 W1=($)=>z6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:T6($.querySerializer),url:$.url}),B1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=W0($.headers,O.headers),j},k5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},W0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?k5(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 V0{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 _6=()=>({error:new V0,request:new V0,response:new V0}),g5=T6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),y5={"Content-Type":"application/json"},Kj=($={})=>({...H6,headers:y5,parseAs:"auto",querySerializer:g5,...$});var L1=($={})=>{let O=B1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=B1(O,Q),j()},S=_6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:W0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await D6(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=W1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:V1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?R6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return U6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:V1(I),url:z})};return{buildUrl:(Q)=>W1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var M6=L1(Kj());class A6{client;constructor($){this.client=$?.client??M6}}class P6{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 B0 extends A6{static __registry=new P6;constructor($){super($);B0.__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 C6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},F5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},E5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Y0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(F5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=P5(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)}`},Q0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=E5(x),X=Object.entries(S).map(([G,L])=>qO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var w5=/\{[^{}]+\}/g,q5=({path:$,url:O})=>{let j=O,x=O.match(w5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Y0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Q0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${qO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},U6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=q5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function J1($){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 z6=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 I6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var H6=({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 G=Y0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=qO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},T6=($)=>{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},f5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function R6($){for(let O of $.security??[]){if(f5($,O.name))continue;let j=await z6(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 V1=($)=>U6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:H6($.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=V0($.headers,O.headers),j},b5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},V0=(...$)=>{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 J0{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 D6=()=>({error:new J0,request:new J0,response:new J0}),k5=H6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),g5={"Content-Type":"application/json"},Xj=($={})=>({...I6,headers:g5,parseAs:"auto",querySerializer:k5,...$});var B1=($={})=>{let O=W1(Xj(),$),j=()=>({...O}),x=(Q)=>{return O=W1(O,Q),j()},S=D6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:V0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await R6(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=V1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:J1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?T6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return N6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:J1(I),url:z})};return{buildUrl:(Q)=>V1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var _6=B1(Xj());class M6{client;constructor($){this.client=$?.client??_6}}class A6{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 W0 extends M6{static __registry=new A6;constructor($){super($);W0.__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 C6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var v5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},h5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},m5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(h5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=v5(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)}`},N0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=m5(x),X=Object.entries(S).map(([G,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var u5=/\{[^{}]+\}/g,c5=({path:$,url:O})=>{let j=O,x=O.match(u5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,L0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,N0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},F6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=c5({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 E6=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 q6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var w6=({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 G=L0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=N0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=bO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},f6=($)=>{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},d5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function b6($){for(let O of $.security??[]){if(d5($,O.name))continue;let j=await E6(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=($)=>F6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:w6($.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=z0($.headers,O.headers),j},l5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},z0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?l5(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 U0{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 U0,request:new U0,response:new U0}),r5=w6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),p5={"Content-Type":"application/json"},Gj=($={})=>({...q6,headers:p5,parseAs:"auto",querySerializer:r5,...$});var I1=($={})=>{let O=z1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=z1(O,Q),j()},S=k6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:z0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await b6(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:N1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?f6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return C6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var g6=I1(Gj());class y6{client;constructor($){this.client=$?.client??g6}}class v6{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 I0 extends y6{static __registry=new v6;constructor($){super($);I0.__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 h6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var y5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},v5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},h5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},B0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(v5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=y5(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)}`},L0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=h5(x),X=Object.entries(S).map(([G,L])=>fO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var m5=/\{[^{}]+\}/g,u5=({path:$,url:O})=>{let j=O,x=O.match(m5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,B0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,L0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${fO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},P6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=u5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function L1($){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 F6=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 E6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var w6=({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 G=B0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=L0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=fO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},q6=($)=>{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},c5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function f6($){for(let O of $.security??[]){if(c5($,O.name))continue;let j=await F6(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 N1=($)=>P6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:w6($.querySerializer),url:$.url}),U1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=U0($.headers,O.headers),j},d5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},U0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?d5(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 N0{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 b6=()=>({error:new N0,request:new N0,response:new N0}),l5=w6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),r5={"Content-Type":"application/json"},Kj=($={})=>({...E6,headers:r5,parseAs:"auto",querySerializer:l5,...$});var z1=($={})=>{let O=U1(Kj(),$),j=()=>({...O}),x=(Q)=>{return O=U1(O,Q),j()},S=b6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:U0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await f6(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=N1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:L1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?q6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return C6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:L1(I),url:z})};return{buildUrl:(Q)=>N1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var k6=z1(Kj());class g6{client;constructor($){this.client=$?.client??k6}}class y6{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 z0 extends g6{static __registry=new y6;constructor($){super($);z0.__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 v6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var a5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},i5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},n5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(i5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=a5(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)}`},T0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=n5(x),X=Object.entries(S).map(([G,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var s5=/\{[^{}]+\}/g,t5=({path:$,url:O})=>{let j=O,x=O.match(s5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,H0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,T0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},m6=({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 H1($){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 u6=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 c6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var d6=({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 G=H0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=T0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=kO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},l6=($)=>{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 r6($){for(let O of $.security??[]){if(e5($,O.name))continue;let j=await u6(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 T1=($)=>m6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:d6($.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=D0($.headers,O.headers),j},o5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},D0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?o5(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 R0{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 p6=()=>({error:new R0,request:new R0,response:new R0}),$4=d6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),O4={"Content-Type":"application/json"},Yj=($={})=>({...c6,headers:O4,parseAs:"auto",querySerializer:$4,...$});var D1=($={})=>{let O=R1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=R1(O,Q),j()},S=p6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:D0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await r6(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=T1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:H1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?l6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return h6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:H1(I),url:z})};return{buildUrl:(Q)=>T1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var a6=D1(Yj());class i6{client;constructor($){this.client=$?.client??a6}}class n6{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 _0 extends i6{static __registry=new n6;constructor($){super($);_0.__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",...$})}unshareScheduledActionTemplate($){return($.client??this.client).delete({url:"/scheduled-actions/{id}/template",...$})}getScheduledActionTemplate($){return($.client??this.client).get({url:"/scheduled-actions/{id}/template",...$})}shareScheduledActionTemplate($){return($.client??this.client).put({url:"/scheduled-actions/{id}/template",...$,headers:{"Content-Type":"application/json",...$.headers}})}activateScheduledActionTemplate($){return($.client??this.client).post({url:"/scheduled-actions/{id}/template/activate",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function s6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var p5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},a5=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},i5=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},I0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(a5(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=p5(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)}`},H0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=i5(x),X=Object.entries(S).map(([G,L])=>bO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var n5=/\{[^{}]+\}/g,s5=({path:$,url:O})=>{let j=O,x=O.match(n5);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,I0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,H0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${bO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},h6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=s5({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function I1($){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 m6=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 u6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var c6=({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 G=I0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=H0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=bO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},d6=($)=>{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},t5=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function l6($){for(let O of $.security??[]){if(t5($,O.name))continue;let j=await m6(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=($)=>h6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:c6($.querySerializer),url:$.url}),T1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=R0($.headers,O.headers),j},e5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},R0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?e5(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 T0{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 r6=()=>({error:new T0,request:new T0,response:new T0}),o5=c6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$4={"Content-Type":"application/json"},Gj=($={})=>({...u6,headers:$4,parseAs:"auto",querySerializer:o5,...$});var R1=($={})=>{let O=T1(Gj(),$),j=()=>({...O}),x=(Q)=>{return O=T1(O,Q),j()},S=r6(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:R0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await l6(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:I1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?d6(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return v6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:I1(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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var p6=R1(Gj());class a6{client;constructor($){this.client=$?.client??p6}}class i6{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 D0 extends a6{static __registry=new i6;constructor($){super($);D0.__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",...$})}unshareScheduledActionTemplate($){return($.client??this.client).delete({url:"/scheduled-actions/{id}/template",...$})}getScheduledActionTemplate($){return($.client??this.client).get({url:"/scheduled-actions/{id}/template",...$})}shareScheduledActionTemplate($){return($.client??this.client).put({url:"/scheduled-actions/{id}/template",...$,headers:{"Content-Type":"application/json",...$.headers}})}activateScheduledActionTemplate($){return($.client??this.client).post({url:"/scheduled-actions/{id}/template/activate",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function n6({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var j4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},x4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},S4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},M0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(x4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=j4(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)}`},A0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=S4(x),X=Object.entries(S).map(([G,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var Z4=/\{[^{}]+\}/g,X4=({path:$,url:O})=>{let j=O,x=O.match(Z4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,M0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,A0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},t6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=X4({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 e6=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 o6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var $7=({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 G=M0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=A0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=gO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},O7=($)=>{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},K4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function j7($){for(let O of $.security??[]){if(K4($,O.name))continue;let j=await e6(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 M1=($)=>t6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:$7($.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=C0($.headers,O.headers),j},G4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},C0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G4(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 P0{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 x7=()=>({error:new P0,request:new P0,response:new P0}),Y4=$7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Q4={"Content-Type":"application/json"},Qj=($={})=>({...o6,headers:Q4,parseAs:"auto",querySerializer:Y4,...$});var P1=($={})=>{let O=A1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=A1(O,Q),j()},S=x7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:C0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await j7(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=M1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:_1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?O7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return s6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:_1(I),url:z})};return{buildUrl:(Q)=>M1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var S7=P1(Qj());class Z7{client;constructor($){this.client=$?.client??S7}}class X7{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 F0 extends Z7{static __registry=new X7;constructor($){super($);F0.__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 K7=($,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 C1={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)=>K7(O,j,S));else K7(O,j,x)}),O}},F1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function G7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var O4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},_0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O4(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)}`},M0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x4(x),X=Object.entries(S).map(([G,L])=>kO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S4=/\{[^{}]+\}/g,Z4=({path:$,url:O})=>{let j=O,x=O.match(S4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,_0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,M0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${kO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},s6=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function D1($){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 t6=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 e6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var o6=({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 G=_0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=M0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=kO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},$7=($)=>{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 O7($){for(let O of $.security??[]){if(X4($,O.name))continue;let j=await t6(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 _1=($)=>s6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:o6($.querySerializer),url:$.url}),M1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=C0($.headers,O.headers),j},K4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},C0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?K4(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 A0{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 j7=()=>({error:new A0,request:new A0,response:new A0}),G4=o6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y4={"Content-Type":"application/json"},Yj=($={})=>({...e6,headers:Y4,parseAs:"auto",querySerializer:G4,...$});var A1=($={})=>{let O=M1(Yj(),$),j=()=>({...O}),x=(Q)=>{return O=M1(O,Q),j()},S=j7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:C0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await O7(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=_1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:D1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?$7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return n6({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:D1(I),url:z})};return{buildUrl:(Q)=>_1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var x7=A1(Yj());class S7{client;constructor($){this.client=$?.client??x7}}class Z7{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 P0 extends S7{static __registry=new Z7;constructor($){super($);P0.__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 X7=($,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 C1={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)=>X7(O,j,S));else X7(O,j,x)}),O}},P1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};function K7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var J4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},V4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},W4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},E0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(V4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=J4(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)}`},q0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=W4(x),X=Object.entries(S).map(([G,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var B4=/\{[^{}]+\}/g,L4=({path:$,url:O})=>{let j=O,x=O.match(B4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,E0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,q0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},Y7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=L4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function E1($){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 Q7=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 J7=({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 G=E0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=q0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=yO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},V7=($)=>{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},N4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function W7($){for(let O of $.security??[]){if(N4($,O.name))continue;let j=await Q7(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 q1=($)=>Y7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:J7($.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=f0($.headers,O.headers),j},U4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},f0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?U4(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 w0{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 B7=()=>({error:new w0,request:new w0,response:new w0}),z4=J7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),I4={"Content-Type":"application/json"},Jj=($={})=>({...F1,headers:I4,parseAs:"auto",querySerializer:z4,...$});var Vj=($={})=>{let O=w1(Jj(),$),j=()=>({...O}),x=(Q)=>{return O=w1(O,Q),j()},S=B7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:f0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await W7(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=q1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:E1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?V7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return G7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:E1(I),url:z})};return{buildUrl:(Q)=>q1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var L7=Vj(Jj());class N7{client;constructor($){this.client=$?.client??L7}}class U7{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 b0 extends N7{static __registry=new U7;constructor($){super($);b0.__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}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,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",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...C1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}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",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function z7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var Q4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},J4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},V4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},F0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(J4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=Q4(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)}`},E0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=V4(x),X=Object.entries(S).map(([G,L])=>gO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var W4=/\{[^{}]+\}/g,B4=({path:$,url:O})=>{let j=O,x=O.match(W4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,F0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,E0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${gO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},G7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=B4({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 Y7=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 Q7=({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 G=F0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=E0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=gO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},J7=($)=>{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},L4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function V7($){for(let O of $.security??[]){if(L4($,O.name))continue;let j=await Y7(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=($)=>G7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:Q7($.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=q0($.headers,O.headers),j},N4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},q0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?N4(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 w0{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 W7=()=>({error:new w0,request:new w0,response:new w0}),U4=Q7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),z4={"Content-Type":"application/json"},Qj=($={})=>({...P1,headers:z4,parseAs:"auto",querySerializer:U4,...$});var Jj=($={})=>{let O=w1(Qj(),$),j=()=>({...O}),x=(Q)=>{return O=w1(O,Q),j()},S=W7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:q0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await V7(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:F1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?J7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return K7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var B7=Jj(Qj());class L7{client;constructor($){this.client=$?.client??B7}}class N7{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 f0 extends L7{static __registry=new N7;constructor($){super($);f0.__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}})}taskSimilaritySearchHandler($){return($.client??this.client).post({url:"/documents/similarity_search",...$,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",...$})}externalChats($){return($?.client??this.client).get({url:"/external-chats",...$})}externalChatAdd($){return($.client??this.client).post({url:"/external-chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRemove($){return($.client??this.client).delete({url:"/external-chats/{chat_id}",...$})}externalChat($){return($.client??this.client).get({url:"/external-chats/{chat_id}",...$})}externalChatUpload($){return($.client??this.client).post({...C1,url:"/external-chats/{chat_id}/attachments",...$,headers:{"Content-Type":null,...$.headers}})}externalChatDelivery($){return($.client??this.client).post({url:"/external-chats/{chat_id}/delivery",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessages($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages",...$})}externalChatMessageAttachments($){return($.client??this.client).post({url:"/external-chats/{chat_id}/messages/attachments",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatMessage($){return($.client??this.client).get({url:"/external-chats/{chat_id}/messages/{message_id}",...$})}externalChatPermissions($){return($.client??this.client).get({url:"/external-chats/{chat_id}/permissions",...$})}externalChatUpdatePermissions($){return($.client??this.client).patch({url:"/external-chats/{chat_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatRead($){return($.client??this.client).post({url:"/external-chats/{chat_id}/read",...$,headers:{"Content-Type":"application/json",...$.headers}})}externalChatSends($){return($.client??this.client).get({url:"/external-chats/{chat_id}/sends",...$})}externalChatSend($){return($.client??this.client).post({url:"/external-chats/{chat_id}/sends",...$,headers:{"Content-Type":"application/json",...$.headers}})}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}})}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",...$})}whatsappAccount($){return($?.client??this.client).get({url:"/whatsapp/account",...$})}whatsappChats($){return($?.client??this.client).get({url:"/whatsapp/chats",...$})}whatsappConnect($){return($.client??this.client).post({url:"/whatsapp/connect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappDisconnect($){return($.client??this.client).post({url:"/whatsapp/disconnect",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappImportHistory($){return($?.client??this.client).post({url:"/whatsapp/history-import",...$})}whatsappStartLookup($){return($.client??this.client).post({url:"/whatsapp/lookups",...$,headers:{"Content-Type":"application/json",...$.headers}})}whatsappLookup($){return($.client??this.client).get({url:"/whatsapp/lookups/{id}",...$})}whatsappCancelPairing($){return($.client??this.client).delete({url:"/whatsapp/pairing/{id}",...$})}whatsappPairing($){return($.client??this.client).get({url:"/whatsapp/pairing/{id}",...$})}whatsappPasskey($){return($.client??this.client).post({url:"/whatsapp/pairing/{id}/passkey",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function U7({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Q}){let J,I=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=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 T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`
`);let y=U.split(`
`);U=y.pop()??"";for(let a of y){let i=a.split(`
`),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`
-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var H4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},T4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},R4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},k0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(T4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=H4(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)}`},g0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=R4(x),X=Object.entries(S).map(([G,L])=>vO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var D4=/\{[^{}]+\}/g,_4=({path:$,url:O})=>{let j=O,x=O.match(D4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,k0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,g0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${vO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},I7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=_4({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 H7=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 T7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var R7=({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 G=k0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=g0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=vO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},D7=($)=>{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},M4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function _7($){for(let O of $.security??[]){if(M4($,O.name))continue;let j=await H7(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=($)=>I7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:R7($.querySerializer),url:$.url}),k1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=v0($.headers,O.headers),j},A4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},v0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?A4(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 y0{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 M7=()=>({error:new y0,request:new y0,response:new y0}),P4=R7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C4={"Content-Type":"application/json"},Wj=($={})=>({...T7,headers:C4,parseAs:"auto",querySerializer:P4,...$});var g1=($={})=>{let O=k1(Wj(),$),j=()=>({...O}),x=(Q)=>{return O=k1(O,Q),j()},S=M7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:v0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await _7(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,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:f1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?D7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return z7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:f1(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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var A7=g1(Wj());class P7{client;constructor($){this.client=$?.client??A7}}class C7{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 h0 extends P7{static __registry=new C7;constructor($){super($);h0.__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 F7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},y1={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 F4($,O){let j=O?.channel_id;return O&&j?{channel:b.byId($,j),thread:new m$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function E$($,O){return{session:l.byId($,O.session_id),owner:A.byId($,O.owner_id),...F4($,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?A.byId($,O):void 0}function E7($,O){return k(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)=>A.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 q7="macro|";function A$($,O){return O.startsWith(q7)&&O.length>q7.length?A.byId($,O.toLowerCase()):void 0}function w7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor),participants:j.participant_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:b.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:b.byId($,j.channel_id),addedBy:A$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:b.byId($,j.channel_id),removedBy:A.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>A.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function f7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:A.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:A.byId($,j.owner),actor:j.actor_user_id?A.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?A.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:A.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:A.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 uO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:J$.byId($,x.id),message:d$.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 m$($,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 b7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:uO($,j,j.mentions),sender:A$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:uO($,j),sender:A$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:uO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:uO($,j),actor:A$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function k7($){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 E4="webhook.validation.test";function q4($,O){return k(O).with({event_type:Z$.string.startsWith("document.")},(j)=>f7($,j)).with({event_type:Z$.string.startsWith("channel.")},(j)=>w7($,j)).with({event_type:Z$.string.startsWith("message.")},(j)=>b7($,j)).with({event_type:Z$.string.startsWith("agent_session.")},(j)=>E7($,j)).otherwise(()=>{return})}class v1{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 k7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new f("invalid webhook signature");if(O.event===E4)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=q4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function g7(){return}var w4=0,h1;function f4($){h1=$}function H$($,O,j){if(!j&&!h1)return $;let x=(S)=>{for(let K of[h1,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(...G)=>{let L={id:++w4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,G),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 v7="x-macro-user-api-key",b4="mak_",m1="mbot_";function k4($){return k($).with(Z$.string.startsWith(m1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(Z$.string.startsWith(b4),(O)=>[v7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function y7($){return typeof $==="function"?await $():$}async function g4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await y7(x.token);if(!S.startsWith(m1))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(m1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[v7,x]]}).with({type:"user"},async({token:x})=>{return[k4(await y7(x))]}).exhaustive()}class u1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=y4($),j=O==="local"?g7():void 0,x={...y1[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??F7[O],this.authConfig=v4($),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=H$(new _0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=H$(new h0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=H$(new vj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=H$(new dj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=H$(new ij({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=H$(new oj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=H$(new S0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=H$(new Y0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=H$(new B0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=H$(new I0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=H$(new F0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=H$(new b0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new v1(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}`):A.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 g4(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 y4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in y1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function v4($){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 c1{id;constructor($){this.id=$}static byId($){return new c1($)}toJSON(){return{id:this.id}}}class h7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new u1($);this._client=O,this.routines=new qx(O),this.unfurls=new bx(O),this.agents=new l0(O),this.initiatives=new Dx(O),this.apiKeys=new p0(O),this.harnesses=new Tx(O),this.meetings=new _x(O),this.githubPullRequests=new Hx(O),this.entityMentions=new Wx(O),this.agentSessions=new d0(O),this.ai=new r0(O),this.bots=new rO(O),this.calendar=new a0(O),this.calls=new i0(O),this.channels=new s0(O),this.externalChats=new Lx(O),this.whatsapp=new yx(O),this.chats=new t0(O),this.crm=new o0(O),this.databases=new Yx(O),this.documents=new Qx(O),this.email=new Vx(O),this.favorites=new Nx(O),this.foreignEntities=new Ux(O),this.forms=new zx(O),this.images=new Rx(O),this.notifications=new Mx(O),this.pins=new Ax(O),this.projects=new Px(O),this.properties=new Cx(O),this.tasks=new wx(O),this.teams=new fx(O),this.users=new kx(O),this.webhooks=new gx(O),this.workspace=new ux(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new h7({...this.opts,requestedAs:$.id})}}export{n$ as wrapXml,O$ as toBody,f4 as observeRequests,d7 as msg,c7 as here,UO as WhatsAppChat,AO as WhatsAppAccount,t$ as UserApiKey,lO as ToolApproval,Fj as StaticImage,U$ as SessionReview,Ex as RoutineExecution,h$ as Routine,c0 as ReviewItem,Ix as PullRequestChangeset,zj as PipelineTable,WO as PipelineRow,Ij as PipelineColumn,N$ as MessageThread,_$ as Meeting,Gx as MacroOpRefusedError,h7 as Macro,i$ as Initiative,_O as HarnessPairing,L$ as Harness,DO as GithubPullRequest,Ej as GeneratedImage,a$ as FormSection,RO as FormResponse,Cj as FormReference,p$ as FormQuestion,zO as FormOption,v$ as Form,ZO as ExternalChatUpload,XO as ExternalChatSend,SO as ExternalChatParticipant,M$ as ExternalChatMessage,y$ as ExternalChat,TO as EntityMention,o as EntityAccess,NO as EmailFilter,LO as EmailDraft,oO as DraftAttachment,aO as DocumentVersion,VO as DocumentAnchor,$j as DevicePairing,e$ as CrmPipeline,u0 as ConversationTurn,dO as CodeExecution,nO as ChatMessage,iO as ChatGeneration,c1 as ChannelPicture,JO as ChannelActivity,w$ as CalendarNote,Lj as AgentConversation,R$ as Agent,HO as AccessRequest};
+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var I4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},H4=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},T4=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},b0=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(H4(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=I4(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)}`},k0=({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 G=[];Object.entries(S).forEach(([Q,J])=>{G=[...G,Q,$?J:encodeURIComponent(J)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=T4(x),X=Object.entries(S).map(([G,L])=>yO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var R4=/\{[^{}]+\}/g,D4=({path:$,url:O})=>{let j=O,x=O.match(R4);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 G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,b0({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,k0({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${yO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},z7=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=D4({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function q1($){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 I7=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 H7={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var T7=({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 G=b0({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=k0({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=yO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},R7=($)=>{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},_4=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function D7($){for(let O of $.security??[]){if(_4($,O.name))continue;let j=await I7(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 f1=($)=>z7({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:T7($.querySerializer),url:$.url}),b1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=y0($.headers,O.headers),j},M4=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},y0=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?M4(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 g0{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 _7=()=>({error:new g0,request:new g0,response:new g0}),A4=T7({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),C4={"Content-Type":"application/json"},Vj=($={})=>({...H7,headers:C4,parseAs:"auto",querySerializer:A4,...$});var k1=($={})=>{let O=b1(Vj(),$),j=()=>({...O}),x=(Q)=>{return O=b1(O,Q),j()},S=_7(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:y0(O.headers,Q.headers),serializedBody:void 0};if(J.security)await D7(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=f1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:q1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?R7(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),G=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return U7({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:q1(I),url:z})};return{buildUrl:(Q)=>f1({...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:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var M7=k1(Vj());class A7{client;constructor($){this.client=$?.client??M7}}class C7{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 v0 extends A7{static __registry=new C7;constructor($){super($);v0.__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 P7={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},g1={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 P4($,O){let j=O?.channel_id;return O&&j?{channel:f.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:A.byId($,O.owner_id),...P4($,O.origin)}}function vO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function hO($,O){return O?A.byId($,O):void 0}function F7($,O){return k(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:hO($,j.actor),announcement:vO($,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:hO($,j.actor),announcement:vO($,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:hO($,j.actor),announcement:vO($,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:hO($,j.last_turn?.actor),announcement:vO($,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:vO($,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:hO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>A.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...E$($,j.identity),actor:hO($,j.turn_in_flight?.actor),announcement:vO($,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 E7="macro|";function A$($,O){return O.startsWith(E7)&&O.length>E7.length?A.byId($,O.toLowerCase()):void 0}function w7($,O){return k(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:f.byId($,j.channel_id),actor:A$($,j.actor),participants:j.participant_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:f.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:f.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:f.byId($,j.channel_id),actor:A$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:f.byId($,j.channel_id),addedBy:A$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>A.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:f.byId($,j.channel_id),removedBy:A.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>A.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function q7($,O){return k(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:A.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:A.byId($,j.owner),actor:j.actor_user_id?A.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?A.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:A.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:A.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 mO($,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:f.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:l$.byId($,x.id,O.message_id),threadId:O.root_id}}function f7($,O){return k(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:mO($,j,j.mentions),sender:A$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:mO($,j),sender:A$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:mO($,j),actor:A$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:mO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:mO($,j),actor:A$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:mO($,j),actor:A$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function b7($){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 F4="webhook.validation.test";function E4($,O){return k(O).with({event_type:S$.string.startsWith("document.")},(j)=>q7($,j)).with({event_type:S$.string.startsWith("channel.")},(j)=>w7($,j)).with({event_type:S$.string.startsWith("message.")},(j)=>f7($,j)).with({event_type:S$.string.startsWith("agent_session.")},(j)=>F7($,j)).otherwise(()=>{return})}class y1{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 b("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 b("event stream failed")}})().catch(()=>{}),()=>{j.abort()}}async handle($,O){if(!this.secret)throw new b("webhookSecret is required to verify incoming webhook deliveries");if(!await b7({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new b("invalid webhook signature");if(O.event===F4)return;await this.dispatchEvent(JSON.parse($))}webhook(){if(!this.secret)throw new b("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=E4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function k7(){return}var w4=0,v1;function q4($){v1=$}function I$($,O,j){if(!j&&!v1)return $;let x=(S)=>{for(let K of[v1,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(...G)=>{let L={id:++w4,service:O,operation:K};x({...L,status:"started"});try{let Q=await Reflect.apply(X,S,G),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 y7="x-macro-user-api-key",f4="mak_",h1="mbot_";function b4($){return k($).with(S$.string.startsWith(h1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(S$.string.startsWith(f4),(O)=>[y7,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function g7($){return typeof $==="function"?await $():$}async function k4($,O,j){return k($).with({type:"bot"},async(x)=>{let S=await g7(x.token);if(!S.startsWith(h1))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:S$.string},({apiKey:x})=>{if(x.startsWith(h1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[y7,x]]}).with({type:"user"},async({token:x})=>{return[b4(await g7(x))]}).exhaustive()}class m1{scheduledAction;unfurl;agentHarness;auth;calendar;cognition;contacts;email;notification;properties;search;storage;webAppUrl;wsVerify;events;authConfig;hosts;localPortmap;requestedAs;selfBotRecord;selfPrincipal;constructor($){let O=g4($),j=O==="local"?k7():void 0,x={...g1[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??P7[O],this.authConfig=y4($),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=I$(new D0({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=I$(new v0({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=I$(new yj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=I$(new cj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=I$(new aj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=I$(new ej({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=I$(new x0({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=I$(new G0({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=I$(new W0({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=I$(new z0({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=I$(new P0({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=I$(new f0({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new y1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new lO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):A.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Jj({baseUrl:$});return O.interceptors.request.use(async(j)=>{let x=await k4(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 g4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in g1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function y4($){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 u1{id;constructor($){this.id=$}static byId($){return new u1($)}toJSON(){return{id:this.id}}}class v7{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;externalChats;whatsapp;chats;crm;databases;documents;email;favorites;foreignEntities;forms;images;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new m1($);this._client=O,this.routines=new Ex(O),this.unfurls=new fx(O),this.agents=new d0(O),this.initiatives=new Rx(O),this.apiKeys=new r0(O),this.harnesses=new Hx(O),this.meetings=new Dx(O),this.githubPullRequests=new Ix(O),this.entityMentions=new Vx(O),this.agentSessions=new c0(O),this.ai=new l0(O),this.bots=new lO(O),this.calendar=new p0(O),this.calls=new a0(O),this.channels=new n0(O),this.externalChats=new Bx(O),this.whatsapp=new gx(O),this.chats=new s0(O),this.crm=new e0(O),this.databases=new Gx(O),this.documents=new Yx(O),this.email=new Jx(O),this.favorites=new Lx(O),this.foreignEntities=new Nx(O),this.forms=new Ux(O),this.images=new Tx(O),this.notifications=new _x(O),this.pins=new Mx(O),this.projects=new Ax(O),this.properties=new Cx(O),this.tasks=new wx(O),this.teams=new qx(O),this.users=new bx(O),this.webhooks=new kx(O),this.workspace=new mx(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new v7({...this.opts,requestedAs:$.id})}}export{i$ as wrapXml,$$ as toBody,q4 as observeRequests,c7 as msg,u7 as here,NO as WhatsAppChat,MO as WhatsAppAccount,s$ as UserApiKey,dO as ToolApproval,Pj as StaticImage,N$ as SessionReview,Fx as RoutineExecution,v$ as Routine,u0 as ReviewItem,zx as PullRequestChangeset,Uj as PipelineTable,JO as PipelineRow,zj as PipelineColumn,L$ as MessageThread,D$ as Meeting,Kx as MacroOpRefusedError,v7 as Macro,a$ as Initiative,DO as HarnessPairing,B$ as Harness,RO as GithubPullRequest,Fj as GeneratedImage,p$ as FormSection,TO as FormResponse,Cj as FormReference,r$ as FormQuestion,UO as FormOption,y$ as Form,SO as ExternalChatUpload,ZO as ExternalChatSend,xO as ExternalChatParticipant,M$ as ExternalChatMessage,g$ as ExternalChat,HO as EntityMention,o as EntityAccess,LO as EmailFilter,BO as EmailDraft,eO as DraftAttachment,tO as DocumentVersion,VO as DocumentAnchor,oO as DevicePairing,t$ as CrmPipeline,m0 as ConversationTurn,cO as CodeExecution,aO as ChatMessage,pO as ChatGeneration,u1 as ChannelPicture,QO as ChannelActivity,Bj as AgentConversation,T$ as Agent,IO as AccessRequest};
diff --git a/crates/entity_access/AGENTS.md b/crates/entity_access/AGENTS.md
index 2e1064a983..c53a693b13 100644
--- a/crates/entity_access/AGENTS.md
+++ b/crates/entity_access/AGENTS.md
@@ -56,9 +56,6 @@ the entity-access domain service.
## Gotchas
-- Document checks fall back to live calendar-note or optional team grants only
- when ordinary document access is absent; these grants are authenticated and
- view-only. Keep the shared SQL visibility policy aligned with calendar note reads.
- `#![deny(missing_docs)]`.
- `EntityAccessReceipt<R: RequiredPermission>` is the only proof a caller
checked access at the right level; domain code downstream (e.g.
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index d5a81e3c1d..535b0528a1 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -70,47 +70,22 @@ impl AccessRepository for PgAccessRepository {
let source_ids = queries::get_user_source_ids(&self.pool, user_id)
.await
.map_err(anyhow_access_error)?;
- let access = if let Ok(document_uuid) = document_id.parse::<Uuid>() {
- queries::document_access::get_document_access(
- &self.pool,
- &document_uuid,
- &source_ids,
- user_id,
- )
- .await?
- } else {
- queries::document_access::get_legacy_document_access(
+ let Ok(document_uuid) = document_id.parse::<Uuid>() else {
+ return Ok(queries::document_access::get_legacy_document_access(
&self.pool,
document_id,
&source_ids,
user_id,
)
- .await?
+ .await?);
};
- if access.is_some() || user_id.is_none() {
- return Ok(access);
- }
- let has_note_access = sqlx::query_scalar!(
- r#"
- SELECT EXISTS (
- SELECT 1 FROM calendar_event_notes note
- JOIN "Document" d ON d.id = note.document_id
- AND d."deletedAt" IS NULL AND d."fileType" = 'md'
- WHERE note.document_id = $1 AND (
- calendar_note_event_visible($2, note.event_id, note.occurrence_key)
- OR EXISTS (
- SELECT 1 FROM team_user member
- WHERE member.team_id = note.team_id AND member.user_id = $2
- )
- )
- ) AS "visible!"
- "#,
- document_id,
- user_id.map(AsRef::as_ref)
+ Ok(queries::document_access::get_document_access(
+ &self.pool,
+ &document_uuid,
+ &source_ids,
+ user_id,
)
- .fetch_one(&self.pool)
- .await?;
- Ok(has_note_access.then_some(AccessLevel::View))
+ .await?)
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.md
index 1e9120e0d6..e5161d71f3 100644
--- a/crates/macro_db_client/AGENTS.md
+++ b/crates/macro_db_client/AGENTS.md
@@ -77,10 +77,6 @@ unreferenced replicas. These additive tables do not change agent-session claims.
## Gotchas
-- `calendar_event_notes` and `calendar_note_event_visible` are shared by calendar
- note reads and document authorization; keep both consumers on the same policy.
- The additive migration must precede their service rollout. See
- [meeting-note access](../../docs/architecture/calendar-meeting-notes.md).
- Migrations deploy before service code: never drop a column/table in the
same PR that removes its last usage (see `docs/development/database.md`).
- Never hand-edit `.sqlx/query-*.json` or invent a migration timestamp.
diff --git a/crates/macro_db_client/migrations/20261102120000_drop_calendar_event_notes.sql b/crates/macro_db_client/migrations/20261102120000_drop_calendar_event_notes.sql
new file mode 100644
index 0000000000..90ef9ec13a
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261102120000_drop_calendar_event_notes.sql
@@ -0,0 +1,5 @@
+-- Meeting notes linked to calendar events were removed with the feature.
+DROP FUNCTION IF EXISTS calendar_note_event_visible(text, uuid, text);
+DROP FUNCTION IF EXISTS calendar_note_copies_match(uuid, uuid, text);
+DROP FUNCTION IF EXISTS calendar_note_link_key(uuid, text);
+DROP TABLE IF EXISTS calendar_event_notes;
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
index fa5a1b146f..f5c9beafe6 100644
--- a/docs/agent-guide/calendar.md
+++ b/docs/agent-guide/calendar.md
@@ -1,102 +1,5 @@
# Calendar
-## Meeting notes
-
-Meeting notes require `enable-calendar-meeting-notes`. It is on automatically in
-dev; production uses PostHog, enabled for `@macro.com` users. `VITE_ENABLE_CALENDAR_MEETING_NOTES=true` or `false` overrides it locally.
-With the flag off, event notes and document Share meeting-link controls do not
-mount or request note data, on desktop or phone. The flag does not revoke saved
-meeting/team grants or change API permissions.
-
-Open a live meeting's details and choose **Create** beside **Meeting notes**.
-This creates a Markdown document named after the meeting, links it with meeting
-viewer access, and opens it immediately. Team access starts off. A meeting can
-have multiple notes; **Create** and **Link** remain on the section title row
-so you can keep creating notes or linking existing documents.
-Both actions are available while notes load. Reopening a recently viewed event
-uses cached notes immediately while stale data refreshes in the background.
-The picker can open while existing links load, but submission waits for that
-check so selecting an already-linked note cannot change its sharing.
-
-Choose **Link** to search the titles of Markdown documents you own, select one, review
-the sharing explanation, and optionally include your existing team before
-**Link note**. Team access starts off for each note. Recurring meetings link only
-the displayed occurrence. Notes on a
-one-time meeting follow it when its date or time changes.
-Existing document editors and other sharing keep their access.
-Notes use the event details' existing row layout and controls. Team choices come
-from current Macro team memberships; they do not introduce departments or subteams.
-
-Linked meetings also appear in the note’s side-panel **References** section.
-Only readers with meeting-detail access see those references; owners retain safe
-unavailable-meeting entries.
-Click a meeting reference to reopen that exact occurrence. If the calendar
-backend has not yet deployed embedded reference previews, the dialog reports
-that meeting details are temporarily unavailable and offers **Retry**. Missing
-fields must not be described as removed meeting access.
-
-Open the linked title to read the original document. On desktop it opens in a
-new split; on mobile it replaces the calendar pane and closes event details.
-Opening a note leaves focus available to the document as it mounts; dismissing
-desktop details normally returns focus to the calendar event.
-Meeting access and occurrence scope are explained in the linking dialog;
-each note shows any additional team audience. **Options → Share** opens the same
-document Share dialog as the note toolbar. Its **Meeting links** section lets the
-owner change each link’s optional team access. **Options → Unlink from meeting**
-removes this meeting’s grants without deleting the document. Keep the labeled
-Options button visible beside long titles; truncate the title without widening
-the event details. Labeled note controls do not need extra hover tooltips.
-The linking dialog uses a wider desktop layout and a phone sheet. Only the
-document results scroll. The picker starts with owned Markdown matches from
-Quick Access's local cache, then adds the calendar notes endpoint's title
-results (up to 30 per query), not full-text search. Matching results stay visible
-while typing and searches are cached across opens. The meeting context,
-sharing controls, and action buttons stay visible, including in a short viewport.
-A former team’s grant can be removed in Share while the meeting is still visible;
-unlinking remains available even if the meeting is no longer accessible.
-Failed saves retain the selection and audience for retry; dismissing starts fresh.
-If creation succeeds but linking fails, **Retry linking** reuses the saved document;
-**Open saved note** lets you continue editing before the link is confirmed. Closing
-details never deletes that document; it remains in Drive. Changing the selected
-meeting or account prevents a late creation result from navigating away from the
-new selection.
-
-Owners can also open the markdown document's **Share** panel and find **Meeting
-links** (inside **Link** on mobile). Every saved link remains removable here even
-if the meeting was cancelled, fell outside the sync window, or stopped being
-shared with the owner. **Unlink** asks before removing its meeting/team grants.
-Unavailable meetings use a safe label rather than revealing private details.
-Checking **Also share with Macro** also updates **Team access** to **View via
-meeting** when there is no direct team grant. The dropdown's **Use meeting
-access** option removes only additional direct sharing; uncheck the meeting's
-checkbox to remove its team grant. Unlink stays in place while a team save runs.
-
-Full-detail team events expose the same note controls; provider actions such as
-editing the event or RSVPing stay unavailable. Busy-only team entries and
-imported snapshots have no meeting-note controls.
-Inherited access follows current meeting details and requires a synced live
-occurrence. If the provider hides its guest list, some guests need a direct
-document share. Independent team sharing lasts until the link is removed or the
-viewer leaves that team; it does not make the calendar event visible to that team.
-
-Verify on desktop and phone: create and open notes, add a second note, retry a failed
-link without duplicating the new document, link an existing note with team unchecked,
-add/remove a team in Share, and unlink while keeping the document. Link a long
-title and verify its Options menu opens without horizontal scrolling. The
-backend-free browser suite mounts the real event popover and mobile drawer with
-sample data and preview service adapters. It previews the real meeting-access
-controls inside a sample Share shell; verify the full Share dialog in the app
-as well. It is
-`apps/web/src/features/calendar-notes/browser-test/playwright.config.ts`.
-API permission cases are covered in `crates/calendar_events/src/outbound/pg/test/notes.rs`.
-The fixture accepts `?notes=off` to check the event details without notes.
-Use `?team=details` or `?team=busy` to check team visibility boundaries.
-
-Browser fixture screenshots: [desktop](media/calendar-notes/desktop.png) ·
-[phone](media/calendar-notes/phone.png) ·
-[desktop picker](media/calendar-notes/link-desktop.png) ·
-[phone picker](media/calendar-notes/link-phone.png).
-
## Calendar — `/app/calendar/<month-or-week-or-day>`
Microsoft calendars use the same editor and calendar views after calendar consent.
@@ -585,7 +488,7 @@ shrink to fit the pane; long details scroll while the RSVP row stays visible.
As in Google Calendar, the popover opens beside the event, aligned with its top,
and switches only between the right and left side; when it doesn't fit below,
it slides up to stay in the window instead of opening above the event. Sections
-that load after it opens (join requests, meeting notes) therefore never move it
+that load after it opens (join requests) therefore never move it
from below the event to above it. Check placement with an event low in a tall
window, a short window, and a pending join request; the backend-free regression
is `apps/web/src/features/calendar-view/browser-test/playwright.config.ts`.
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 8d1b5d83d8..8472f6b703 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -26,38 +26,6 @@ horizontally and removal remains available without hover. Composer fixture
screenshots: [desktop](media/share-images/desktop.png) and
[phone](media/share-images/mobile.png).
-With `enable-calendar-meeting-notes` enabled, owned markdown documents' Share
-panel also lists **Meeting links** (under the **Link** tab on mobile).
-Each shows its occurrence and optional team view grant. Toggle **Also share with
-<team>** here to update that link’s team access; changes save immediately.
-Calendar notes’ **Options → Share** opens this same dialog.
-Use **Unlink** and confirm to remove that grant without deleting the document.
-This remains available when the meeting is cancelled or no longer shared with
-you; unavailable meeting details are hidden. See [Calendar meeting notes](calendar.md#meeting-notes).
-Turning the flag off does not revoke saved grants. If meeting access cannot be
-checked, the share status uses **Restricted** instead of claiming **Just me**;
-known public, team, or shared access still appears.
-This status follows the current document and account when navigating with Share open.
-
-When meeting notes are enabled, the document side panel’s **References** section
-also lists linked calendar events, including when there are no document or message
-references. Each row uses the same single-line style, with the meeting title and
-date inline. Open a row to jump to
-your calendar copy; meetings shared through a channel or team without a personal
-copy use a read-only event preview. The preview also works when the Calendar
-view is disabled. Readers see only
-meetings they can view in detail. Owners retain safe
-unavailable-meeting entries, which can be removed through Share. Linking or
-unlinking updates the References count.
-
-Verify a note linked to two meetings, a note with both message and calendar
-references, a rescheduled one-time event, and a recurring occurrence. A cancelled
-instance must never open a later instance. Check full-detail team sharing, a
-reader who can see both entities, a reader with document-only access, and the
-feature flag off. On phone, open References from the document side panel and
-follow a meeting without leaving a sheet over the calendar. Closing a read-only
-meeting preview must return to the document details sheet.
-
Verify **Public → View** links in a fresh signed-out browser context. The
`/app/drive/md/<id>` route (including folder/tab document links and legacy
`/app/md/<id>` redirects) must show the document without private Drive lists or
diff --git a/docs/agent-guide/media/calendar-notes/desktop.png b/docs/agent-guide/media/calendar-notes/desktop.png
deleted file mode 100644
index 9dc2233f89..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/desktop.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/link-desktop.png b/docs/agent-guide/media/calendar-notes/link-desktop.png
deleted file mode 100644
index f1846439a8..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/link-desktop.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/link-phone.png b/docs/agent-guide/media/calendar-notes/link-phone.png
deleted file mode 100644
index 7080b56e7f..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/link-phone.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/phone.png b/docs/agent-guide/media/calendar-notes/phone.png
deleted file mode 100644
index 0bf113e5ff..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/phone.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/references-desktop.png b/docs/agent-guide/media/calendar-notes/references-desktop.png
deleted file mode 100644
index 3b86d9b08d..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/references-desktop.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/search-cached-results.png b/docs/agent-guide/media/calendar-notes/search-cached-results.png
deleted file mode 100644
index c0298f7bdf..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/search-cached-results.png and /dev/null differ
diff --git a/docs/agent-guide/media/calendar-notes/sharing-team-access.png b/docs/agent-guide/media/calendar-notes/sharing-team-access.png
deleted file mode 100644
index 34f59708c8..0000000000
Binary files a/docs/agent-guide/media/calendar-notes/sharing-team-access.png and /dev/null differ
diff --git a/docs/architecture/calendar-meeting-notes.md b/docs/architecture/calendar-meeting-notes.md
deleted file mode 100644
index 0a0caf6d1b..0000000000
--- a/docs/architecture/calendar-meeting-notes.md
+++ /dev/null
@@ -1,153 +0,0 @@
-# Calendar meeting notes
-
-Meeting notes link Markdown documents to a one-time meeting or one occurrence of a
-recurring meeting. Each occurrence can have multiple notes, created from event
-details or linked from the owner's existing documents.
-They reuse the document's content, editor, collaboration, and ownership; calendar
-sync does not copy or own that content.
-
-## Access contract
-
-- The document owner explicitly links it and optionally chooses one current team.
-- Authenticated full-detail meeting viewers inherit **view** access. Busy-only
- visibility, snapshots, and anonymous links do not qualify.
-- The selected team's current members independently receive **view** access.
- Team access does not expose the calendar event itself.
-- `team_user_user_id_unique` restricts each account to one current team; the
- optional checkbox uses that membership, with no subteam picker.
-- Existing ownership, editor, public, and other document grants remain unchanged.
-- Unlinking removes only this occurrence's meeting/team grant, never the document.
- An owner can revoke it from the document's Share panel, SDK, or API even after
- losing meeting access.
-
-`calendar_event_notes` stores `(event_id, occurrence_key, document_id)`, an optional
-`team_id`, and the linking user. Recurring links use the original-start key, which
-survives rescheduling that occurrence. One-time meetings use the canonical key
-`single`, so moving their start time preserves notes and old API handles. The API
-accepts the current calendar occurrence key for either kind; owner link listings
-return `single` for a one-time meeting. Links intentionally have no occurrence foreign key: provider
-sync replaces occurrence projections. Event, document, and linking-user deletion
-cascade links; team deletion clears only the additional audience.
-
-## Shared authorization
-
-`calendar_note_event_visible` is used by both note reads and the ordinary document
-access boundary. It checks the primary database on every authorization. A caller
-must have a live full-detail copy through inbox ownership/delegation, a current
-channel grant, or current full-detail team calendar sharing. Team projections
-also require fresh, successful source snapshots and non-private event/override
-visibility. Existing document permissions are checked first; the fallback never
-elevates above view.
-
-Different inbox copies have different event IDs. Matching iCalendar UID and
-organizer alone is insufficient: each inbox must be corroborated by the other
-copy's organizer or effective occurrence guest list. This prevents both reading
-real notes from a fabricated event and injecting notes into a real meeting.
-`calendar_note_copies_match` also checks the requested event against the note
-anchor directly, even if the viewer separately has access to both meetings.
-Both copies must have a live materialized occurrence. Provider cancellation
-often removes an instance rather than storing a cancelled row; missing instances
-therefore fail closed. If an old occurrence leaves the sync window, its inherited
-grant stops until it is synced again. Durable links and independent document/team
-grants remain. Hidden guest lists may also require an explicit document share.
-
-Writes use an owner-level document receipt. Only live markdown is accepted;
-additional team sharing requires current membership. A document-scoped advisory
-transaction lock serializes link/unlink across equivalent inbox copies. Relinking
-updates the existing grant and removes duplicates across those copies.
-
-## Surface and API
-
-The remote web flag `enable-calendar-meeting-notes` gates both event-details
-surfaces and document Share meeting-link management before their query sources
-mount. It defaults on in development; production falls through to PostHog, with
-the initial rollout intended for `@macro.com` users. The local override is
-`VITE_ENABLE_CALENDAR_MEETING_NOTES`. This is a UI rollout, not an authorization
-boundary: backend/SDK operations and persisted grants retain the access contract
-above when the web flag is off.
-The Share panel retains known shared status and otherwise uses a neutral
-restricted-link label while meeting access cannot be checked with the flag off.
-
-The web feature lives in `apps/web/src/features/calendar-notes`, with an injected
-data source, query adapter, controller, and presentational view. It mounts within
-desktop and mobile event details. Its shared dialog becomes a phone sheet with
-`Dialog.contentOwnsScroll`: only document results scroll, while context, sharing,
-and actions stay visible. Choices survive failures. Note options use labeled menu
-actions; **Share** opens the existing document Share dialog, whose Meeting links
-section owns optional team access. The host dialog guard follows the menu and
-Share dialog, and clears
-when a note disappears during a live refresh.
-**Create** and **Link** stay beside the section title so additional notes can be
-added without leaving the meeting. **Create** uses the standard Markdown creation
-flow, links the resulting document with no team grant, then opens the editor. It
-captures the account and occurrence before creation starts, suppresses duplicate
-clicks, and retains the created document for retry if linking fails. A disposed
-view never navigates on a late result. There is no separate calendar-owned content
-store or create endpoint.
-
-The document References section lists meeting links alongside document and
-message references. Readers need document view access and current full-detail
-meeting access to discover a link. Owners also retain unavailable links; their
-labels stay safe. Calendar previews resolve titles and times through the viewer’s
-projection. Opening a reference uses the viewer’s own copy when available, or
-the existing read-only event preview otherwise. The note flag gates this query
-before it mounts.
-
-The links response includes `canViewMeeting` and an optional exact `event`
-preview, which References uses without another lookup. During a rolling deploy,
-an older calendar service can omit those fields. Missing projection fields mean
-the reference is unresolved, not that meeting access was denied; the dialog
-offers Retry on the links query. It never substitutes a broader mention lookup
-for the server's source-scoped authorization. An explicit `canViewMeeting: false`
-still means the linked meeting is unavailable to the reader.
-It also includes an optional `teamEvent` projection, resolved through
-the same source entitlement reader and sanitizer as the team calendar. It never
-borrows canonical details, includes busy-only content, or substitutes a nearby
-occurrence. References previews expose no channel-share actions. A `single` link
-can follow a moved one-time event, but cannot become a link to a new recurring
-series.
-
-The document Share panel also lists owner-only durable links, immediate optional
-team access controls, and inline unlink confirmation. That list does not require
-current meeting access. It uses
-generic labels for inaccessible or indirectly shared meetings, so it cannot reveal
-a richer canonical event title through a restricted provider projection.
-The standard Team access control includes the current team's meeting-derived
-view grant: it shows **View via meeting** when there is no direct team grant.
-**Use meeting access** removes only additional direct team sharing; the meeting
-checkbox still owns its independent grant. A team save does not disable or
-remount the Unlink trigger, and destructive writes remain serialized.
-
-Event notes and document links remain cached per account and target for five
-minutes, with a 30-second freshness window and mutation invalidation. Event
-Create and Link actions do not wait for the notes request. The picker immediately
-uses the app's owned Markdown Quick Access candidates, then adds server title
-matches. Matching previous results remain visible during the debounced request;
-search responses are fresh for a minute and cached for five minutes. Previous
-results never carry across accounts. This supplements the existing owned-note
-endpoint; it does not use the full-text search backend.
-Picker server reads emit `calendar.notes.search` and a server phase with meeting
-ID, query length, configured debounce, local/remote result counts, and outcome.
-Quick Access retains its existing search-page and materialization traces. Search
-text and document names are not recorded.
-
-The calendar service mounts these authenticated routes even when provider sync is
-disabled. Every response is private and non-cacheable:
-
-| Method | Path | Purpose |
-| --- | --- | --- |
-| GET | `/meeting-notes/documents?query=` | Up to 30 owned markdown suggestions and current teams |
-| GET | `/meeting-notes/documents/{document_id}/links` | Visible links for document readers; owners also receive unavailable grants |
-| GET | `/events/{event_id}/notes?occurrenceKey=` | Notes visible through this occurrence |
-| PUT | `/events/{event_id}/notes/{document_id}?occurrenceKey=` | Link/update with `{ "teamId": null }` or a team UUID |
-| DELETE | `/events/{event_id}/notes/{document_id}?occurrenceKey=` | Idempotently unlink the owned document |
-
-The gateway prefixes these paths with `/calendar`. The SDK exposes
-`calendar.noteDocuments`, `CalendarEvent.notes`, `CalendarEvent.linkNote`,
-`Document.meetingNotes`, `CalendarNote.setTeam`, and `CalendarNote.unlink`. Event methods accept the
-occurrence record returned by calendar reads and reject an event mismatch.
-
-Deploy the additive migration before the updated calendar/document services and
-web client. Operation spans use `calendar.notes.*`; the ordinary authenticated
-service client and HTTP middleware propagate trace context. Browser fixtures use
-an in-memory source, while SQLx tests exercise real authorization and migrations.
diff --git a/packages/code-mode-sdk/AGENTS.md b/packages/code-mode-sdk/AGENTS.md
index c7a0c5a4a8..cebc47fda0 100644
--- a/packages/code-mode-sdk/AGENTS.md
+++ b/packages/code-mode-sdk/AGENTS.md
@@ -33,5 +33,3 @@ Run from this directory after installing the root workspace and the standalone
must match the public SDK; edit source and regenerate them together.
Use the repository's pinned Bun version (via `nix develop`); different Bun
bundlers produce different checked-in output even from identical SDK source.
-Run SDK-docs and code-mode generated-output checks sequentially; both render into
-`packages/sdk-docs/dist/docs`.
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/README.md b/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
index baf03ed2be..1e76d416f8 100644
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/calendar/types.gen/README.md
@@ -22,8 +22,6 @@
- [CalendarJoinRequest](type-aliases/CalendarJoinRequest.md)
- [CalendarJoinRequestDecision](type-aliases/CalendarJoinRequestDecision.md)
- [CalendarJoinRequestStatus](type-aliases/CalendarJoinRequestStatus.md)
-- [CalendarMentionEvent](type-aliases/CalendarMentionEvent.md)
-- [CalendarMentionViewerCopy](type-aliases/CalendarMentionViewerCopy.md)
- [CalendarMutationApiError](type-aliases/CalendarMutationApiError.md)
- [CalendarMutationErrorCode](type-aliases/CalendarMutationErrorCode.md)
- [CalendarProvider](type-aliases/CalendarProvider.md)
@@ -65,13 +63,6 @@
- [DiscardCalendarReplacementErrors](type-aliases/DiscardCalendarReplacementErrors.md)
- [DiscardCalendarReplacementResponse](type-aliases/DiscardCalendarReplacementResponse.md)
- [DiscardCalendarReplacementResponses](type-aliases/DiscardCalendarReplacementResponses.md)
-- [DocumentNoteLink](type-aliases/DocumentNoteLink.md)
-- [DocumentNoteLinksData](type-aliases/DocumentNoteLinksData.md)
-- [DocumentNoteLinksResponse](type-aliases/DocumentNoteLinksResponse.md)
-- [DocumentNoteLinksResponses](type-aliases/DocumentNoteLinksResponses.md)
-- [EventNotesData](type-aliases/EventNotesData.md)
-- [EventNotesResponse](type-aliases/EventNotesResponse.md)
-- [EventNotesResponses](type-aliases/EventNotesResponses.md)
- [EventReminderOverride](type-aliases/EventReminderOverride.md)
- [EventReminders](type-aliases/EventReminders.md)
- [EventStatus](type-aliases/EventStatus.md)
@@ -95,23 +86,12 @@
- [InviteCalendarEventGuestsRequest](type-aliases/InviteCalendarEventGuestsRequest.md)
- [InviteCalendarEventGuestsResponse](type-aliases/InviteCalendarEventGuestsResponse.md)
- [InviteCalendarEventGuestsResponses](type-aliases/InviteCalendarEventGuestsResponses.md)
-- [LinkEventNoteData](type-aliases/LinkEventNoteData.md)
-- [LinkEventNoteResponse](type-aliases/LinkEventNoteResponse.md)
-- [LinkEventNoteResponses](type-aliases/LinkEventNoteResponses.md)
-- [LinkNoteRequest](type-aliases/LinkNoteRequest.md)
- [ListCalendarsData](type-aliases/ListCalendarsData.md)
- [ListCalendarsError](type-aliases/ListCalendarsError.md)
- [ListCalendarsErrors](type-aliases/ListCalendarsErrors.md)
- [ListCalendarsResponse](type-aliases/ListCalendarsResponse.md)
- [ListCalendarsResponse2](type-aliases/ListCalendarsResponse2.md)
- [ListCalendarsResponses](type-aliases/ListCalendarsResponses.md)
-- [MeetingNote](type-aliases/MeetingNote.md)
-- [NoteDocument](type-aliases/NoteDocument.md)
-- [NoteDocumentsData](type-aliases/NoteDocumentsData.md)
-- [NoteDocumentsResponse](type-aliases/NoteDocumentsResponse.md)
-- [NoteDocumentsResponses](type-aliases/NoteDocumentsResponses.md)
-- [NotePicker](type-aliases/NotePicker.md)
-- [NoteTeam](type-aliases/NoteTeam.md)
- [OutOfOfficeAutoDeclineMode](type-aliases/OutOfOfficeAutoDeclineMode.md)
- [OutOfOfficeProperties](type-aliases/OutOfOfficeProperties.md)
- [PrepareCalendarReplacementData](type-aliases/PrepareCalendarReplacementData.md)
@@ -140,14 +120,8 @@
- [SetTeamSharingData](type-aliases/SetTeamSharingData.md)
- [SetTeamSharingResponse](type-aliases/SetTeamSharingResponse.md)
- [SetTeamSharingResponses](type-aliases/SetTeamSharingResponses.md)
-- [TeamCalendarContent](type-aliases/TeamCalendarContent.md)
-- [TeamCalendarDetails](type-aliases/TeamCalendarDetails.md)
-- [TeamCalendarItem](type-aliases/TeamCalendarItem.md)
- [TeamCalendarSharing](type-aliases/TeamCalendarSharing.md)
- [TeamCalendarSharingBody](type-aliases/TeamCalendarSharingBody.md)
-- [UnlinkEventNoteData](type-aliases/UnlinkEventNoteData.md)
-- [UnlinkEventNoteResponse](type-aliases/UnlinkEventNoteResponse.md)
-- [UnlinkEventNoteResponses](type-aliases/UnlinkEventNoteResponses.md)
- [UpdateCalendarEventData](type-aliases/UpdateCalendarEventData.md)
- [UpdateCalendarEventError](type-aliases/UpdateCalendarEventError.md)
- [UpdateCalendarEventErrors](type-aliases/UpdateCalendarEventErrors.md)
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionEvent.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionEvent.md
deleted file mode 100644
index c00677c51b..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionEvent.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Type Alias: CalendarMentionEvent
-
-> **CalendarMentionEvent** = \{ `attendeeCount`: `number`; `canRequestToJoin?`: `boolean`; `description?`: `string` \| `null`; `isRecurring`: `boolean`; `joinRequestStatus?`: `null` \| [`CalendarJoinRequestStatus`](CalendarJoinRequestStatus.md); `location?`: `string` \| `null`; `occurrenceKey?`: `string` \| `null`; `organizerEmail?`: `string` \| `null`; `organizerName?`: `string` \| `null`; `time`: [`EventTime`](EventTime.md); `title`: `string`; `updatedAt`: `string`; `viewerCalendarIds?`: `string`[]; `viewerCopy?`: `null` \| [`CalendarMentionViewerCopy`](CalendarMentionViewerCopy.md); `viewerEventId?`: `string` \| `null`; \}
-
-Meeting-level fields shown in a calendar event mention preview, taken from
-the requester's own projection of the meeting, or — when the requester has
-none — from the mentioned projection a channel they belong to was given.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-attendeecount"></a> `attendeeCount` | `number` | Number of attendees on the previewed copy. |
-| <a id="property-canrequesttojoin"></a> `canRequestToJoin?` | `boolean` | For a channel-shared preview, whether the person who shared it can add the requester as a guest. Always false for the requester's own copy. |
-| <a id="property-description"></a> `description?` | `string` \| `null` | Provider description, plain text or HTML, truncated for the preview. Clients must sanitize it before rendering. |
-| <a id="property-isrecurring"></a> `isRecurring` | `boolean` | Whether the event repeats. |
-| <a id="property-joinrequeststatus"></a> `joinRequestStatus?` | `null` \| [`CalendarJoinRequestStatus`](CalendarJoinRequestStatus.md) | - |
-| <a id="property-location"></a> `location?` | `string` \| `null` | Location label, when set. |
-| <a id="property-occurrencekey"></a> `occurrenceKey?` | `string` \| `null` | Key of the previewed instance, absent when no occurrence is materialized. |
-| <a id="property-organizeremail"></a> `organizerEmail?` | `string` \| `null` | Organizer email. |
-| <a id="property-organizername"></a> `organizerName?` | `string` \| `null` | Organizer display name. |
-| <a id="property-time"></a> `time` | [`EventTime`](EventTime.md) | Time of the previewed instance: the requested occurrence when it exists, else the next upcoming one, else the latest past one, else the series start. |
-| <a id="property-title"></a> `title` | `string` | Display title. |
-| <a id="property-updatedat"></a> `updatedAt` | `string` | Entity update time of the previewed copy. |
-| <a id="property-viewercalendarids"></a> `viewerCalendarIds?` | `string`[] | The calendars holding `viewer_event_id`, the canonical copy's first. |
-| <a id="property-viewercopy"></a> `viewerCopy?` | `null` \| [`CalendarMentionViewerCopy`](CalendarMentionViewerCopy.md) | - |
-| <a id="property-viewereventid"></a> `viewerEventId?` | `string` \| `null` | The requester's own event entity for the mentioned meeting. Differs from the mentioned id when the mention came from another attendee. Absent when the meeting is on none of the requester's calendars and they see it only because it was shared with one of their channels: that preview is read-only and there is no event of theirs to open. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionViewerCopy.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionViewerCopy.md
deleted file mode 100644
index dc0167333d..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/CalendarMentionViewerCopy.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Type Alias: CalendarMentionViewerCopy
-
-> **CalendarMentionViewerCopy** = `"snapshot"` \| `"invitation"` \| `"event"`
-
-How a requester holds a mentioned meeting on their own calendar, decided
-by the copy's own inbox, the way viewer capabilities decide organizer and
-guest.
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md
deleted file mode 100644
index 12b09329e8..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLink.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Type Alias: DocumentNoteLink
-
-> **DocumentNoteLink** = \{ `canViewMeeting`: `boolean`; `documentName`: `string`; `event?`: `null` \| [`CalendarMentionEvent`](CalendarMentionEvent.md); `eventId`: `string`; `eventTitle`: `string`; `occurrenceKey`: `string`; `team?`: `null` \| [`NoteTeam`](NoteTeam.md); `teamEvent?`: `null` \| [`TeamCalendarItem`](TeamCalendarItem.md); \}
-
-A visible meeting link, or an owner's durable grant they can no longer open.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-canviewmeeting"></a> `canViewMeeting` | `boolean` | Whether the reader may resolve this exact meeting's details right now. |
-| <a id="property-documentname"></a> `documentName` | `string` | Current name of the markdown document. |
-| <a id="property-event"></a> `event?` | `null` \| [`CalendarMentionEvent`](CalendarMentionEvent.md) | - |
-| <a id="property-eventid"></a> `eventId` | `string` | Linked calendar copy. |
-| <a id="property-eventtitle"></a> `eventTitle` | `string` | Current title, or a safe placeholder when meeting details are unavailable. |
-| <a id="property-occurrencekey"></a> `occurrenceKey` | `string` | Original occurrence start, or `single` for a one-time meeting. |
-| <a id="property-team"></a> `team?` | `null` \| [`NoteTeam`](NoteTeam.md) | - |
-| <a id="property-teamevent"></a> `teamEvent?` | `null` \| [`TeamCalendarItem`](TeamCalendarItem.md) | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md
deleted file mode 100644
index 5fce9d2ded..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksData.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Type Alias: DocumentNoteLinksData
-
-> **DocumentNoteLinksData** = \{ `body?`: `never`; `path`: \{ `document_id`: `string`; \}; `query?`: `never`; `url`: `"/meeting-notes/documents/{document_id}/links"`; \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-body"></a> `body?` | `never` |
-| <a id="property-path"></a> `path` | \{ `document_id`: `string`; \} |
-| `path.document_id` | `string` |
-| <a id="property-query"></a> `query?` | `never` |
-| <a id="property-url"></a> `url` | `"/meeting-notes/documents/{document_id}/links"` |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md
deleted file mode 100644
index 46bb67808f..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponse.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Type Alias: DocumentNoteLinksResponse
-
-> **DocumentNoteLinksResponse** = [`DocumentNoteLinksResponses`](DocumentNoteLinksResponses.md)\[keyof [`DocumentNoteLinksResponses`](DocumentNoteLinksResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md
deleted file mode 100644
index c689fb87fb..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/DocumentNoteLinksResponses.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Type Alias: DocumentNoteLinksResponses
-
-> **DocumentNoteLinksResponses** = \{ `200`: [`DocumentNoteLink`](DocumentNoteLink.md)[]; \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-200"></a> `200` | [`DocumentNoteLink`](DocumentNoteLink.md)[] |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md
deleted file mode 100644
index 766f17f78a..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesData.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Type Alias: EventNotesData
-
-> **EventNotesData** = \{ `body?`: `never`; `path`: \{ `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes"`; \}
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-body"></a> `body?` | `never` | - |
-| <a id="property-path"></a> `path` | \{ `event_id`: `string`; \} | - |
-| `path.event_id` | `string` | - |
-| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
-| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
-| <a id="property-url"></a> `url` | `"/events/{event_id}/notes"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md
deleted file mode 100644
index 07ff73a220..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponse.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Type Alias: EventNotesResponse
-
-> **EventNotesResponse** = [`EventNotesResponses`](EventNotesResponses.md)\[keyof [`EventNotesResponses`](EventNotesResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md
deleted file mode 100644
index ab717451d6..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/EventNotesResponses.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Type Alias: EventNotesResponses
-
-> **EventNotesResponses** = \{ `200`: [`MeetingNote`](MeetingNote.md)[]; \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-200"></a> `200` | [`MeetingNote`](MeetingNote.md)[] |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md
deleted file mode 100644
index 48c3aeda8c..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteData.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Type Alias: LinkEventNoteData
-
-> **LinkEventNoteData** = \{ `body`: [`LinkNoteRequest`](LinkNoteRequest.md); `path`: \{ `document_id`: `string`; `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes/{document_id}"`; \}
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-body"></a> `body` | [`LinkNoteRequest`](LinkNoteRequest.md) | - |
-| <a id="property-path"></a> `path` | \{ `document_id`: `string`; `event_id`: `string`; \} | - |
-| `path.document_id` | `string` | - |
-| `path.event_id` | `string` | - |
-| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
-| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
-| <a id="property-url"></a> `url` | `"/events/{event_id}/notes/{document_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md
deleted file mode 100644
index cc386b249a..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponse.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Type Alias: LinkEventNoteResponse
-
-> **LinkEventNoteResponse** = [`LinkEventNoteResponses`](LinkEventNoteResponses.md)\[keyof [`LinkEventNoteResponses`](LinkEventNoteResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md
deleted file mode 100644
index 95d8459e3c..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkEventNoteResponses.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Type Alias: LinkEventNoteResponses
-
-> **LinkEventNoteResponses** = \{ `204`: `void`; \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-204"></a> `204` | `void` |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md
deleted file mode 100644
index 6d3fef55ef..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/LinkNoteRequest.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# Type Alias: LinkNoteRequest
-
-> **LinkNoteRequest** = \{ `teamId?`: `string` \| `null`; \}
-
-Optional additional view access for one team.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-teamid"></a> `teamId?` | `string` \| `null` | Null means the meeting audience only. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md
deleted file mode 100644
index 3284bbe960..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/MeetingNote.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Type Alias: MeetingNote
-
-> **MeetingNote** = \{ `canManage`: `boolean`; `documentId`: `string`; `name`: `string`; `team?`: `null` \| [`NoteTeam`](NoteTeam.md); \}
-
-One linked document and the extra access this link grants.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-canmanage"></a> `canManage` | `boolean` | Whether this viewer can change this document's sharing. |
-| <a id="property-documentid"></a> `documentId` | `string` | Markdown document identity. |
-| <a id="property-name"></a> `name` | `string` | Current document name. |
-| <a id="property-team"></a> `team?` | `null` \| [`NoteTeam`](NoteTeam.md) | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md
deleted file mode 100644
index ee48c54810..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocument.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Type Alias: NoteDocument
-
-> **NoteDocument** = \{ `documentId`: `string`; `name`: `string`; \}
-
-A document available in the note picker.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-documentid"></a> `documentId` | `string` | Markdown document identity. |
-| <a id="property-name"></a> `name` | `string` | Current document name, never a copied title. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md
deleted file mode 100644
index 46586ded89..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsData.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Type Alias: NoteDocumentsData
-
-> **NoteDocumentsData** = \{ `body?`: `never`; `path?`: `never`; `query?`: \{ `query?`: `string`; \}; `url`: `"/meeting-notes/documents"`; \}
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-body"></a> `body?` | `never` | - |
-| <a id="property-path"></a> `path?` | `never` | - |
-| <a id="property-query"></a> `query?` | \{ `query?`: `string`; \} | - |
-| `query.query?` | `string` | Empty returns recent documents. |
-| <a id="property-url"></a> `url` | `"/meeting-notes/documents"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md
deleted file mode 100644
index f03a5c91f7..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponse.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Type Alias: NoteDocumentsResponse
-
-> **NoteDocumentsResponse** = [`NoteDocumentsResponses`](NoteDocumentsResponses.md)\[keyof [`NoteDocumentsResponses`](NoteDocumentsResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md
deleted file mode 100644
index 3f45077451..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteDocumentsResponses.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Type Alias: NoteDocumentsResponses
-
-> **NoteDocumentsResponses** = \{ `200`: [`NotePicker`](NotePicker.md); \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-200"></a> `200` | [`NotePicker`](NotePicker.md) |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md
deleted file mode 100644
index 0c466a0f73..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NotePicker.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Type Alias: NotePicker
-
-> **NotePicker** = \{ `documents`: [`NoteDocument`](NoteDocument.md)[]; `teams`: [`NoteTeam`](NoteTeam.md)[]; \}
-
-Picker results; only documents whose owner is the caller are suggested.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-documents"></a> `documents` | [`NoteDocument`](NoteDocument.md)[] | At most 30 matching markdown documents, most recently updated first. |
-| <a id="property-teams"></a> `teams` | [`NoteTeam`](NoteTeam.md)[] | Teams the caller currently belongs to. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md
deleted file mode 100644
index 366a863367..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/NoteTeam.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Type Alias: NoteTeam
-
-> **NoteTeam** = \{ `id`: `string`; `name`: `string`; \}
-
-An additional team audience, separate from the meeting's audience.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-id"></a> `id` | `string` | Team identity. |
-| <a id="property-name"></a> `name` | `string` | Display name. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarContent.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarContent.md
deleted file mode 100644
index 3137706b9b..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarContent.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# Type Alias: TeamCalendarContent
-
-> **TeamCalendarContent** = \{ `kind`: `"busy"`; \} \| \{ `details`: [`TeamCalendarDetails`](TeamCalendarDetails.md); `kind`: `"details"`; \}
-
-Disjoint busy/detail shapes prevent new event fields leaking by default.
-
-## Union Members
-
-### Type Literal
-
-\{ `kind`: `"busy"`; \}
-
-***
-
-### Type Literal
-
-\{ `details`: [`TeamCalendarDetails`](TeamCalendarDetails.md); `kind`: `"details"`; \}
-
-| Name | Type | Description |
-| ------ | ------ | ------ |
-| `details` | [`TeamCalendarDetails`](TeamCalendarDetails.md) | Detail projection. |
-| `kind` | `"details"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarDetails.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarDetails.md
deleted file mode 100644
index 61b08a55e5..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarDetails.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# Type Alias: TeamCalendarDetails
-
-> **TeamCalendarDetails** = \{ `attendees`: [`CalendarAttendee`](CalendarAttendee.md)[]; `calendarName`: `string`; `conferenceUrl?`: `string` \| `null`; `description?`: `string` \| `null`; `location?`: `string` \| `null`; `organizerEmail?`: `string` \| `null`; `organizerName?`: `string` \| `null`; `title`: `string`; \}
-
-Safe details from a single authorized source.
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-attendees"></a> `attendees` | [`CalendarAttendee`](CalendarAttendee.md)[] | Attendees; self flags are relative to the requesting viewer. |
-| <a id="property-calendarname"></a> `calendarName` | `string` | Source calendar name, shown only with details. |
-| <a id="property-conferenceurl"></a> `conferenceUrl?` | `string` \| `null` | Join URL, if supplied by this source. |
-| <a id="property-description"></a> `description?` | `string` \| `null` | Body, if supplied by this source. |
-| <a id="property-location"></a> `location?` | `string` \| `null` | Location, if supplied by this source. |
-| <a id="property-organizeremail"></a> `organizerEmail?` | `string` \| `null` | Organizer address from this source. |
-| <a id="property-organizername"></a> `organizerName?` | `string` \| `null` | Organizer name from this source. |
-| <a id="property-title"></a> `title` | `string` | Display title. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarItem.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarItem.md
deleted file mode 100644
index 77afbf862d..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/TeamCalendarItem.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# Type Alias: TeamCalendarItem
-
-> **TeamCalendarItem** = [`TeamCalendarContent`](TeamCalendarContent.md) & \{ `contributesToAvailability`: `boolean`; `id`: `string`; `ownerId`: `string`; `time`: [`EventTime`](EventTime.md); \}
-
-A read-only team calendar occurrence.
-
-## Type Declaration
-
-| Name | Type | Description |
-| ------ | ------ | ------ |
-| `contributesToAvailability` | `boolean` | Whether this occurrence blocks the sharer's personal availability. A subscribed calendar's block can be shared without occupying the sharer. |
-| `id` | `string` | Stable opaque projection identity, never an event entity id. |
-| `ownerId` | `string` | The person sharing access to the source. |
-| `time` | [`EventTime`](EventTime.md) | Occurrence interval. |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md
deleted file mode 100644
index bd76bd4092..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteData.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# Type Alias: UnlinkEventNoteData
-
-> **UnlinkEventNoteData** = \{ `body?`: `never`; `path`: \{ `document_id`: `string`; `event_id`: `string`; \}; `query`: \{ `occurrenceKey`: `string`; \}; `url`: `"/events/{event_id}/notes/{document_id}"`; \}
-
-## Properties
-
-| Property | Type | Description |
-| ------ | ------ | ------ |
-| <a id="property-body"></a> `body?` | `never` | - |
-| <a id="property-path"></a> `path` | \{ `document_id`: `string`; `event_id`: `string`; \} | - |
-| `path.document_id` | `string` | - |
-| `path.event_id` | `string` | - |
-| <a id="property-query"></a> `query` | \{ `occurrenceKey`: `string`; \} | - |
-| `query.occurrenceKey` | `string` | Stable occurrence key returned by the calendar read API. |
-| <a id="property-url"></a> `url` | `"/events/{event_id}/notes/{document_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md
deleted file mode 100644
index d8a22c61f2..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponse.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# Type Alias: UnlinkEventNoteResponse
-
-> **UnlinkEventNoteResponse** = [`UnlinkEventNoteResponses`](UnlinkEventNoteResponses.md)\[keyof [`UnlinkEventNoteResponses`](UnlinkEventNoteResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md b/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md
deleted file mode 100644
index 1e267e7066..0000000000
--- a/packages/sdk-docs/reference/generated/calendar/types.gen/type-aliases/UnlinkEventNoteResponses.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# Type Alias: UnlinkEventNoteResponses
-
-> **UnlinkEventNoteResponses** = \{ `204`: `void`; \}
-
-## Properties
-
-| Property | Type |
-| ------ | ------ |
-| <a id="property-204"></a> `204` | `void` |
diff --git a/packages/sdk-docs/reference/modules.md b/packages/sdk-docs/reference/modules.md
index 44f4d4ef2f..7fd8e42c1a 100644
--- a/packages/sdk-docs/reference/modules.md
+++ b/packages/sdk-docs/reference/modules.md
@@ -33,7 +33,6 @@
- [src/entities/calendar/calendar](src/entities/calendar/calendar/README.md)
- [src/entities/calendar/event](src/entities/calendar/event/README.md)
- [src/entities/calendar/namespace](src/entities/calendar/namespace/README.md)
-- [src/entities/calendar/note](src/entities/calendar/note/README.md)
- [src/entities/calendar/replacement](src/entities/calendar/replacement/README.md)
- [src/entities/calls/call-record](src/entities/calls/call-record/README.md)
- [src/entities/calls/message](src/entities/calls/message/README.md)
diff --git a/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md b/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
index 739ff56cad..06aa7abc5b 100644
--- a/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
+++ b/packages/sdk-docs/reference/src/entities/calendar/event/classes/CalendarEvent.md
@@ -141,46 +141,6 @@ new guests.
***
-### linkNote()
-
-> **linkNote**(`document`, `occurrence`, `options?`): `Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)\>
-
-Link a markdown document you own. Meeting-detail viewers gain read access;
-an optional team gains read access too. Editing and other sharing are preserved.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `document` | [`Document`](../../../documents/document/classes/Document.md) |
-| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
-| `options?` | \{ `team?`: [`Team`](../../../teams/team/classes/Team.md); \} |
-| `options.team?` | [`Team`](../../../teams/team/classes/Team.md) |
-
-#### Returns
-
-`Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)\>
-
-***
-
-### notes()
-
-> **notes**(`occurrence`): `Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\>
-
-Notes linked to a specific occurrence returned by `calendar.occurrences()`.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
-
-#### Returns
-
-`Promise`\<[`CalendarNote`](../../note/classes/CalendarNote.md)[]\>
-
-***
-
### prepareReplacement()
> **prepareReplacement**(`options`): `Promise`\<[`CalendarReplacement`](../../replacement/classes/CalendarReplacement.md)\>
diff --git a/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md b/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
index 17cb5d0bfe..725d941f21 100644
--- a/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
+++ b/packages/sdk-docs/reference/src/entities/calendar/namespace/classes/CalendarNamespace.md
@@ -132,24 +132,6 @@ A handle to a calendar event by id, for driving mutations.
***
-### noteDocuments()
-
-> **noteDocuments**(`query?`): `Promise`\<\{ `documents`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \}[]; `teams`: \{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \}[]; \}\>
-
-Find up to 30 owned markdown documents for meeting notes, plus available extra team audiences.
-
-#### Parameters
-
-| Parameter | Type | Default value |
-| ------ | ------ | ------ |
-| `query?` | `string` | `''` |
-
-#### Returns
-
-`Promise`\<\{ `documents`: \{ `document`: [`Document`](../../../documents/document/classes/Document.md); `name`: `string`; \}[]; `teams`: \{ `name`: `string`; `team`: [`Team`](../../../teams/team/classes/Team.md); \}[]; \}\>
-
-***
-
### occurrences()
> **occurrences**(`options`): `AsyncGenerator`\<\{ `calendarName`: `string` \| `undefined`; `contributesToAvailability`: `boolean` \| `undefined`; `event`: [`CalendarEvent`](../../event/classes/CalendarEvent.md); `inbox`: `string` \| `undefined`; `occurrence`: [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md); `role`: [`CalendarEventRole`](../type-aliases/CalendarEventRole.md) \| `undefined`; \}, `any`, `any`\>
diff --git a/packages/sdk-docs/reference/src/entities/calendar/note/README.md b/packages/sdk-docs/reference/src/entities/calendar/note/README.md
deleted file mode 100644
index 808f54042f..0000000000
--- a/packages/sdk-docs/reference/src/entities/calendar/note/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# src/entities/calendar/note
-
-## Classes
-
-- [CalendarNote](classes/CalendarNote.md)
diff --git a/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md b/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md
deleted file mode 100644
index fb6e524b4c..0000000000
--- a/packages/sdk-docs/reference/src/entities/calendar/note/classes/CalendarNote.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# Class: CalendarNote
-
-A markdown document linked to one meeting occurrence, with view-only access.
-
-## Extends
-
-- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\<[`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md)\>
-
-## Properties
-
-| Property | Modifier | Type | Description | Inherited from |
-| ------ | ------ | ------ | ------ | ------ |
-| <a id="property-canmanage"></a> `canManage` | `readonly` | () => `Promise`\<`boolean`\> | Whether the caller may change this link's sharing. | - |
-| <a id="property-document"></a> `document` | `readonly` | () => `Promise`\<[`Document`](../../../documents/document/classes/Document.md)\> | The original markdown document; unlinking never deletes it. | - |
-| <a id="property-event"></a> `event` | `readonly` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) | - | - |
-| <a id="property-id"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |
-| <a id="property-name"></a> `name` | `readonly` | () => `Promise`\<`string`\> | Current document name. | - |
-| <a id="property-occurrence"></a> `occurrence` | `readonly` | `Pick`\<[`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md), `"eventId"` \| `"occurrenceKey"`\> | - | - |
-| <a id="property-team"></a> `team` | `readonly` | () => `Promise`\<[`Team`](../../../teams/team/classes/Team.md) \| `undefined`\> | Optional extra team audience. Meeting-detail viewers already have view access. | - |
-
-## Methods
-
-### setTeam()
-
-> **setTeam**(`team?`): `Promise`\<`void`\>
-
-Change the extra team view grant; omit the team to remove it. Requires document ownership.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `team?` | [`Team`](../../../teams/team/classes/Team.md) |
-
-#### Returns
-
-`Promise`\<`void`\>
-
-***
-
-### toJSON()
-
-> **toJSON**(): \{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \}
-
-#### Returns
-
-\{ `detail?`: [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md); `id`: `string`; \}
-
-| Name | Type |
-| ------ | ------ |
-| `detail?` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md) |
-| `id` | `string` |
-
-#### Inherited from
-
-[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)
-
-***
-
-### unlink()
-
-> **unlink**(): `Promise`\<`void`\>
-
-Remove this occurrence's link and view grants, preserving the document and other sharing.
-
-#### Returns
-
-`Promise`\<`void`\>
-
-***
-
-### forDocument()
-
-> `static` **forDocument**(`client`, `event`, `occurrence`, `document`): `CalendarNote`
-
-Construct a handle for a document already linked to this occurrence.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `client` | `MacroClient` |
-| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |
-| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
-| `document` | [`Document`](../../../documents/document/classes/Document.md) |
-
-#### Returns
-
-`CalendarNote`
-
-***
-
-### fromDocumentLink()
-
-> `static` **fromDocumentLink**(`client`, `document`, `link`): `CalendarNote`
-
-Seed an owner-visible link that can be revoked even if the meeting is unavailable.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `client` | `MacroClient` |
-| `document` | [`Document`](../../../documents/document/classes/Document.md) |
-| `link` | [`DocumentNoteLink`](../../../../../generated/calendar/types.gen/type-aliases/DocumentNoteLink.md) |
-
-#### Returns
-
-`CalendarNote`
-
-***
-
-### fromRecord()
-
-> `static` **fromRecord**(`client`, `event`, `occurrence`, `record`): `CalendarNote`
-
-Seed a handle with a record returned by the meeting-note API.
-
-#### Parameters
-
-| Parameter | Type |
-| ------ | ------ |
-| `client` | `MacroClient` |
-| `event` | [`CalendarEvent`](../../event/classes/CalendarEvent.md) |
-| `occurrence` | [`CalendarOccurrence`](../../../../../generated/storage/types.gen/type-aliases/CalendarOccurrence.md) |
-| `record` | [`MeetingNote`](../../../../../generated/calendar/types.gen/type-aliases/MeetingNote.md) |
-
-#### Returns
-
-`CalendarNote`
diff --git a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
index 78a99aee9f..e18c21a1b9 100644
--- a/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
+++ b/packages/sdk-docs/reference/src/entities/documents/document/classes/Document.md
@@ -217,18 +217,6 @@ GitHub pull requests associated with the document.
***
-### meetingNotes()
-
-> **meetingNotes**(): `Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
-
-Meeting links visible to the reader. Owners also receive unavailable grants and may unlink them to revoke meeting/team access.
-
-#### Returns
-
-`Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
-
-***
-
### messageThreadById()
> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)
diff --git a/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md b/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
index a61ceef3fc..a2dfeaa0ee 100644
--- a/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
+++ b/packages/sdk-docs/reference/src/entities/entity/classes/MacroEntity.md
@@ -14,7 +14,6 @@ field and mutate.
- [`UserApiKey`](../../api-keys/api-key/classes/UserApiKey.md)
- [`Calendar`](../../calendar/calendar/classes/Calendar.md)
- [`CalendarEvent`](../../calendar/event/classes/CalendarEvent.md)
-- [`CalendarNote`](../../calendar/note/classes/CalendarNote.md)
- [`CallMessage`](../../calls/message/classes/CallMessage.md)
- [`ChatMessage`](../../chats/generation/classes/ChatMessage.md)
- [`CrmComment`](../../crm/comment/classes/CrmComment.md)
diff --git a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
index d537aeae5f..b2f580a403 100644
--- a/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
+++ b/packages/sdk-docs/reference/src/entities/tasks/task/classes/Task.md
@@ -259,22 +259,6 @@ GitHub pull requests associated with the document.
***
-### meetingNotes()
-
-> **meetingNotes**(): `Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
-
-Meeting links visible to the reader. Owners also receive unavailable grants and may unlink them to revoke meeting/team access.
-
-#### Returns
-
-`Promise`\<\{ `eventTitle`: `string`; `note`: [`CalendarNote`](../../../calendar/note/classes/CalendarNote.md); \}[]\>
-
-#### Inherited from
-
-[`Document`](../../../documents/document/classes/Document.md).[`meetingNotes`](../../../documents/document/classes/Document.md#meetingnotes)
-
-***
-
### messageThreadById()
> **messageThreadById**(`id`): [`MessageThread`](../../../messages/thread/classes/MessageThread.md)
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index 1b4a4edaae..5f26c37c40 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -46,12 +46,6 @@ Re-exports [ApplyOpsOptions](../entities/databases/database/type-aliases/ApplyOp
***
-### CalendarNote
-
-Re-exports [CalendarNote](../entities/calendar/note/classes/CalendarNote.md)
-
-***
-
### CallMessage
Re-exports [CallMessage](../entities/calls/message/classes/CallMessage.md)
diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.md
index ba984062c1..facb0bd31a 100644
--- a/packages/sdk/AGENTS.md
+++ b/packages/sdk/AGENTS.md
@@ -74,19 +74,12 @@ the existing gateway prefixes.
(`isReadOnly` false): Outlook names the mailbox owner as organizer on every
event of a read-only calendar. `eventRole` and `EventRole::of` must stay
in step.
-- Calendar notes accept a document handle and the occurrence returned by calendar
- reads. `CalendarNote` owns optional team sharing and unlinking; clearing its team
- sends explicit null and never changes the document's other permissions.
- `Document.meetingNotes()` discovers visible meeting links for readers and
- durable grants for owners to revoke after losing
- meeting access.
- Regenerate Rust OpenAPI and web service clients before `bun run sync-specs &&
bun run generate`; do not copy deployed schemas over a local API change.
- Regenerate `../sdk-docs/reference` after SDK source or generated type changes;
run that package's checks because web CI verifies the reference is current.
-- Run `bun run generate` and the checks in `../code-mode-sdk` after SDK changes
- to keep the embedded Deno bundle, agent documentation, and operation catalog current.
- Commit `crates/agent_code_mode/src/domain/documentation.json`; CI's Typecheck
+ Also run `bun packages/code-mode-sdk/scripts/generate.ts` from the root and
+ commit `crates/agent_code_mode/src/domain/documentation.json`; CI's Typecheck
fails when it is stale.
- `generated/agent-fold/` is not from OpenAPI: `cargo run -p agent_fold --bin
export_types` writes it, and `foldedLog()` casts the opaque wire schema to it.
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index f92e41ee86..e778d07635 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -530,14 +530,6 @@ when mutations invalidate metadata. `update`, `cancel`, `invite(email)`,
`availabilityCalendars`, `calendar.setContributesToAvailability`, `teamSharing` and
`setTeamSharing` manage availability and sharing preferences.
-`calendar.noteDocuments(query)` suggests owned markdown and optional team handles.
-Use `event.linkNote(document, occurrence, { team })` to grant meeting viewers view
-access; omit `team` for meeting access only. One-time notes follow reschedules;
-recurring notes stay on the selected occurrence. `event.notes(occurrence)` returns
-`CalendarNote` handles with `setTeam(team?)` and `unlink()`. Existing editing and
-other document sharing stay unchanged. Owners can discover every durable grant
-through `document.meetingNotes()` and unlink it even when the meeting is unavailable.
-
### Document lifecycle and other resources
`documents.createUpload(options)` reserves a binary document and returns upload
diff --git a/packages/sdk/generated/calendar/index.ts b/packages/sdk/generated/calendar/index.ts
index c24732256d..7fbb761cb6 100644
--- a/packages/sdk/generated/calendar/index.ts
+++ b/packages/sdk/generated/calendar/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AttendeeResponseStatus, AvailabilityCalendar, AvailabilityCalendarBody, AvailabilityCalendarsResponse, CalendarAttendee, CalendarAttendeeInputBody, CalendarCapabilities, CalendarDeletionScopeParam, CalendarEvent, CalendarEventProviderUrl, CalendarEventProviderUrlData, CalendarEventProviderUrlError, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponse, CalendarEventProviderUrlResponses, CalendarEventSourceContent, CalendarGuestInputBody, CalendarJoinRequest, CalendarJoinRequestDecision, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionViewerCopy, CalendarMutationApiError, CalendarMutationErrorCode, CalendarProvider, CalendarReplacementStatusData, CalendarReplacementStatusError, CalendarReplacementStatusErrors, CalendarReplacementStatusResponse, CalendarReplacementStatusResponses, CalendarReplacementView, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, ConfirmCalendarReplacementData, ConfirmCalendarReplacementError, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponse, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventError, CopyCalendarEventErrors, CopyCalendarEventRequest, CopyCalendarEventResponse, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementError, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponse, DiscardCalendarReplacementResponses, DocumentNoteLink, DocumentNoteLinksData, DocumentNoteLinksResponse, DocumentNoteLinksResponses, EventNotesData, EventNotesResponse, EventNotesResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponse, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponse, GetTeamSharingResponses, GuestPolicy, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsError, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsRequest, InviteCalendarEventGuestsResponse, InviteCalendarEventGuestsResponses, LinkEventNoteData, LinkEventNoteResponse, LinkEventNoteResponses, LinkNoteRequest, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, MeetingNote, NoteDocument, NoteDocumentsData, NoteDocumentsResponse, NoteDocumentsResponses, NotePicker, NoteTeam, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, PrepareCalendarReplacementData, PrepareCalendarReplacementError, PrepareCalendarReplacementErrors, PrepareCalendarReplacementRequest, PrepareCalendarReplacementResponse, PrepareCalendarReplacementResponses, RefreshCalendarEvent, ReplacementStatus, RespondToJoinRequestData, RespondToJoinRequestError, RespondToJoinRequestErrors, RespondToJoinRequestRequest, RespondToJoinRequestResponse, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponse, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponse, SetTeamSharingResponses, TeamCalendarContent, TeamCalendarDetails, TeamCalendarItem, TeamCalendarSharing, TeamCalendarSharingBody, UnlinkEventNoteData, UnlinkEventNoteResponse, UnlinkEventNoteResponses, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, ViewerCapabilities, VisibleCalendar } from './types.gen';
+export type { AttendeeResponseStatus, AvailabilityCalendar, AvailabilityCalendarBody, AvailabilityCalendarsResponse, CalendarAttendee, CalendarAttendeeInputBody, CalendarCapabilities, CalendarDeletionScopeParam, CalendarEvent, CalendarEventProviderUrl, CalendarEventProviderUrlData, CalendarEventProviderUrlError, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponse, CalendarEventProviderUrlResponses, CalendarEventSourceContent, CalendarGuestInputBody, CalendarJoinRequest, CalendarJoinRequestDecision, CalendarJoinRequestStatus, CalendarMutationApiError, CalendarMutationErrorCode, CalendarProvider, CalendarReplacementStatusData, CalendarReplacementStatusError, CalendarReplacementStatusErrors, CalendarReplacementStatusResponse, CalendarReplacementStatusResponses, CalendarReplacementView, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, ConfirmCalendarReplacementData, ConfirmCalendarReplacementError, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponse, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventError, CopyCalendarEventErrors, CopyCalendarEventRequest, CopyCalendarEventResponse, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementError, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponse, DiscardCalendarReplacementResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponse, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponse, GetTeamSharingResponses, GuestPolicy, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsError, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsRequest, InviteCalendarEventGuestsResponse, InviteCalendarEventGuestsResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, PrepareCalendarReplacementData, PrepareCalendarReplacementError, PrepareCalendarReplacementErrors, PrepareCalendarReplacementRequest, PrepareCalendarReplacementResponse, PrepareCalendarReplacementResponses, RefreshCalendarEvent, ReplacementStatus, RespondToJoinRequestData, RespondToJoinRequestError, RespondToJoinRequestErrors, RespondToJoinRequestRequest, RespondToJoinRequestResponse, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponse, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponse, SetTeamSharingResponses, TeamCalendarSharing, TeamCalendarSharingBody, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, ViewerCapabilities, VisibleCalendar } from './types.gen';
diff --git a/packages/sdk/generated/calendar/sdk.gen.ts b/packages/sdk/generated/calendar/sdk.gen.ts
index 61719da738..b4910ef8ad 100644
--- a/packages/sdk/generated/calendar/sdk.gen.ts
+++ b/packages/sdk/generated/calendar/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { CalendarEventProviderUrlData, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponses, CalendarReplacementStatusData, CalendarReplacementStatusErrors, CalendarReplacementStatusResponses, ConfirmCalendarReplacementData, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventErrors, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponses, DocumentNoteLinksData, DocumentNoteLinksResponses, EventNotesData, EventNotesResponses, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsResponses, LinkEventNoteData, LinkEventNoteResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, NoteDocumentsData, NoteDocumentsResponses, PrepareCalendarReplacementData, PrepareCalendarReplacementErrors, PrepareCalendarReplacementResponses, RespondToJoinRequestData, RespondToJoinRequestErrors, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponses, UnlinkEventNoteData, UnlinkEventNoteResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';
+import type { CalendarEventProviderUrlData, CalendarEventProviderUrlErrors, CalendarEventProviderUrlResponses, CalendarReplacementStatusData, CalendarReplacementStatusErrors, CalendarReplacementStatusResponses, ConfirmCalendarReplacementData, ConfirmCalendarReplacementErrors, ConfirmCalendarReplacementResponses, CopyCalendarEventData, CopyCalendarEventErrors, CopyCalendarEventResponses, CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, DiscardCalendarReplacementData, DiscardCalendarReplacementErrors, DiscardCalendarReplacementResponses, GetAvailabilityCalendarsData, GetAvailabilityCalendarsResponses, GetTeamSharingData, GetTeamSharingResponses, HealthHandlerData, HealthHandlerResponses, InviteCalendarEventGuestsData, InviteCalendarEventGuestsErrors, InviteCalendarEventGuestsResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, PrepareCalendarReplacementData, PrepareCalendarReplacementErrors, PrepareCalendarReplacementResponses, RespondToJoinRequestData, RespondToJoinRequestErrors, RespondToJoinRequestResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, SetAvailabilityCalendarData, SetAvailabilityCalendarResponses, SetTeamSharingData, SetTeamSharingResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -156,34 +156,6 @@ export class Sdk extends HeyApiClient {
});
}
- /**
- * List notes visible through this meeting occurrence.
- */
- public eventNotes<ThrowOnError extends boolean = false>(options: Options<EventNotesData, ThrowOnError>): RequestResult<EventNotesResponses, unknown, ThrowOnError> {
- return (options.client ?? this.client).get<EventNotesResponses, unknown, ThrowOnError>({ url: '/events/{event_id}/notes', ...options });
- }
-
- /**
- * Remove this meeting's grant without deleting the document.
- */
- public unlinkEventNote<ThrowOnError extends boolean = false>(options: Options<UnlinkEventNoteData, ThrowOnError>): RequestResult<UnlinkEventNoteResponses, unknown, ThrowOnError> {
- return (options.client ?? this.client).delete<UnlinkEventNoteResponses, unknown, ThrowOnError>({ url: '/events/{event_id}/notes/{document_id}', ...options });
- }
-
- /**
- * Idempotently link a markdown document and its optional team audience.
- */
- public linkEventNote<ThrowOnError extends boolean = false>(options: Options<LinkEventNoteData, ThrowOnError>): RequestResult<LinkEventNoteResponses, unknown, ThrowOnError> {
- return (options.client ?? this.client).put<LinkEventNoteResponses, unknown, ThrowOnError>({
- url: '/events/{event_id}/notes/{document_id}',
- ...options,
- headers: {
- 'Content-Type': 'application/json',
- ...options.headers
- }
- });
- }
-
/**
* Resolve an authorized event's provider link for Outlook-only actions.
*/
@@ -242,20 +214,6 @@ export class Sdk extends HeyApiClient {
});
}
- /**
- * Suggest the caller's markdown documents and extra team audiences.
- */
- public noteDocuments<ThrowOnError extends boolean = false>(options?: Options<NoteDocumentsData, ThrowOnError>): RequestResult<NoteDocumentsResponses, unknown, ThrowOnError> {
- return (options?.client ?? this.client).get<NoteDocumentsResponses, unknown, ThrowOnError>({ url: '/meeting-notes/documents', ...options });
- }
-
- /**
- * List a document's visible meeting links; owners also see unavailable grants.
- */
- public documentNoteLinks<ThrowOnError extends boolean = false>(options: Options<DocumentNoteLinksData, ThrowOnError>): RequestResult<DocumentNoteLinksResponses, unknown, ThrowOnError> {
- return (options.client ?? this.client).get<DocumentNoteLinksResponses, unknown, ThrowOnError>({ url: '/meeting-notes/documents/{document_id}/links', ...options });
- }
-
/**
* Discard a preview only if no confirmation has been recorded.
*/
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
index 212098cccd..712ca0c605 100644
--- a/packages/sdk/generated/calendar/types.gen.ts
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -394,85 +394,6 @@ export type CalendarJoinRequestDecision = 'accept' | 'decline';
*/
export type CalendarJoinRequestStatus = 'pending' | 'accepted' | 'declined';
-/**
- * Meeting-level fields shown in a calendar event mention preview, taken from
- * the requester's own projection of the meeting, or — when the requester has
- * none — from the mentioned projection a channel they belong to was given.
- */
-export type CalendarMentionEvent = {
- /**
- * Number of attendees on the previewed copy.
- */
- attendeeCount: number;
- /**
- * For a channel-shared preview, whether the person who shared it can
- * add the requester as a guest. Always false for the requester's own
- * copy.
- */
- canRequestToJoin?: boolean;
- /**
- * Provider description, plain text or HTML, truncated for the preview.
- * Clients must sanitize it before rendering.
- */
- description?: string | null;
- /**
- * Whether the event repeats.
- */
- isRecurring: boolean;
- joinRequestStatus?: null | CalendarJoinRequestStatus;
- /**
- * Location label, when set.
- */
- location?: string | null;
- /**
- * Key of the previewed instance, absent when no occurrence is
- * materialized.
- */
- occurrenceKey?: string | null;
- /**
- * Organizer email.
- */
- organizerEmail?: string | null;
- /**
- * Organizer display name.
- */
- organizerName?: string | null;
- /**
- * Time of the previewed instance: the requested occurrence when it
- * exists, else the next upcoming one, else the latest past one, else the
- * series start.
- */
- time: EventTime;
- /**
- * Display title.
- */
- title: string;
- /**
- * Entity update time of the previewed copy.
- */
- updatedAt: string;
- /**
- * The calendars holding `viewer_event_id`, the canonical copy's first.
- */
- viewerCalendarIds?: Array<string>;
- viewerCopy?: null | CalendarMentionViewerCopy;
- /**
- * The requester's own event entity for the mentioned meeting. Differs
- * from the mentioned id when the mention came from another attendee.
- * Absent when the meeting is on none of the requester's calendars and
- * they see it only because it was shared with one of their channels:
- * that preview is read-only and there is no event of theirs to open.
- */
- viewerEventId?: string | null;
-};
-
-/**
- * How a requester holds a mentioned meeting on their own calendar, decided
- * by the copy's own inbox, the way viewer capabilities decide organizer and
- * guest.
- */
-export type CalendarMentionViewerCopy = 'snapshot' | 'invitation' | 'event';
-
/**
* HTTP error body returned by calendar mutation endpoints.
*/
@@ -651,35 +572,6 @@ export type CreateCalendarEventRequest = {
visibility?: null | EventVisibility;
};
-/**
- * A visible meeting link, or an owner's durable grant they can no longer open.
- */
-export type DocumentNoteLink = {
- /**
- * Whether the reader may resolve this exact meeting's details right now.
- */
- canViewMeeting: boolean;
- /**
- * Current name of the markdown document.
- */
- documentName: string;
- event?: null | CalendarMentionEvent;
- /**
- * Linked calendar copy.
- */
- eventId: string;
- /**
- * Current title, or a safe placeholder when meeting details are unavailable.
- */
- eventTitle: string;
- /**
- * Original occurrence start, or `single` for a one-time meeting.
- */
- occurrenceKey: string;
- team?: null | NoteTeam;
- teamEvent?: null | TeamCalendarItem;
-};
-
/**
* One reminder: how it alerts and how many minutes before the event start
* (before midnight in the calendar's zone for all-day events) it fires.
@@ -814,16 +706,6 @@ export type InviteCalendarEventGuestsRequest = {
scope?: null | CalendarUpdateScopeParam;
};
-/**
- * Optional additional view access for one team.
- */
-export type LinkNoteRequest = {
- /**
- * Null means the meeting audience only.
- */
- teamId?: string | null;
-};
-
/**
* Calendars visible to the requester across connected and delegated inboxes.
*/
@@ -834,67 +716,6 @@ export type ListCalendarsResponse = {
calendars: Array<VisibleCalendar>;
};
-/**
- * One linked document and the extra access this link grants.
- */
-export type MeetingNote = {
- /**
- * Whether this viewer can change this document's sharing.
- */
- canManage: boolean;
- /**
- * Markdown document identity.
- */
- documentId: string;
- /**
- * Current document name.
- */
- name: string;
- team?: null | NoteTeam;
-};
-
-/**
- * A document available in the note picker.
- */
-export type NoteDocument = {
- /**
- * Markdown document identity.
- */
- documentId: string;
- /**
- * Current document name, never a copied title.
- */
- name: string;
-};
-
-/**
- * Picker results; only documents whose owner is the caller are suggested.
- */
-export type NotePicker = {
- /**
- * At most 30 matching markdown documents, most recently updated first.
- */
- documents: Array<NoteDocument>;
- /**
- * Teams the caller currently belongs to.
- */
- teams: Array<NoteTeam>;
-};
-
-/**
- * An additional team audience, separate from the meeting's audience.
- */
-export type NoteTeam = {
- /**
- * Team identity.
- */
- id: string;
- /**
- * Display name.
- */
- name: string;
-};
-
/**
* How an out-of-office event responds to conflicting invitations, mirroring
* Google's `autoDeclineMode`.
@@ -1002,80 +823,6 @@ export type RsvpCalendarEventRequest = {
scope?: null | CalendarRsvpScopeParam;
};
-/**
- * Disjoint busy/detail shapes prevent new event fields leaking by default.
- */
-export type TeamCalendarContent = {
- kind: 'busy';
-} | {
- /**
- * Detail projection.
- */
- details: TeamCalendarDetails;
- kind: 'details';
-};
-
-/**
- * Safe details from a single authorized source.
- */
-export type TeamCalendarDetails = {
- /**
- * Attendees; self flags are relative to the requesting viewer.
- */
- attendees: Array<CalendarAttendee>;
- /**
- * Source calendar name, shown only with details.
- */
- calendarName: string;
- /**
- * Join URL, if supplied by this source.
- */
- conferenceUrl?: string | null;
- /**
- * Body, if supplied by this source.
- */
- description?: string | null;
- /**
- * Location, if supplied by this source.
- */
- location?: string | null;
- /**
- * Organizer address from this source.
- */
- organizerEmail?: string | null;
- /**
- * Organizer name from this source.
- */
- organizerName?: string | null;
- /**
- * Display title.
- */
- title: string;
-};
-
-/**
- * A read-only team calendar occurrence.
- */
-export type TeamCalendarItem = TeamCalendarContent & {
- /**
- * Whether this occurrence blocks the sharer's personal availability.
- * A subscribed calendar's block can be shared without occupying the sharer.
- */
- contributesToAvailability: boolean;
- /**
- * Stable opaque projection identity, never an event entity id.
- */
- id: string;
- /**
- * The person sharing access to the source.
- */
- ownerId: string;
- /**
- * Occurrence interval.
- */
- time: EventTime;
-};
-
/**
* What a user exposes through their team membership.
*/
@@ -1551,68 +1298,6 @@ export type InviteCalendarEventGuestsResponses = {
export type InviteCalendarEventGuestsResponse = InviteCalendarEventGuestsResponses[keyof InviteCalendarEventGuestsResponses];
-export type EventNotesData = {
- body?: never;
- path: {
- event_id: string;
- };
- query: {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
- };
- url: '/events/{event_id}/notes';
-};
-
-export type EventNotesResponses = {
- 200: Array<MeetingNote>;
-};
-
-export type EventNotesResponse = EventNotesResponses[keyof EventNotesResponses];
-
-export type UnlinkEventNoteData = {
- body?: never;
- path: {
- event_id: string;
- document_id: string;
- };
- query: {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
- };
- url: '/events/{event_id}/notes/{document_id}';
-};
-
-export type UnlinkEventNoteResponses = {
- 204: void;
-};
-
-export type UnlinkEventNoteResponse = UnlinkEventNoteResponses[keyof UnlinkEventNoteResponses];
-
-export type LinkEventNoteData = {
- body: LinkNoteRequest;
- path: {
- event_id: string;
- document_id: string;
- };
- query: {
- /**
- * Stable occurrence key returned by the calendar read API.
- */
- occurrenceKey: string;
- };
- url: '/events/{event_id}/notes/{document_id}';
-};
-
-export type LinkEventNoteResponses = {
- 204: void;
-};
-
-export type LinkEventNoteResponse = LinkEventNoteResponses[keyof LinkEventNoteResponses];
-
export type CalendarEventProviderUrlData = {
body?: never;
path: {
@@ -1772,39 +1457,6 @@ export type RespondToJoinRequestResponses = {
export type RespondToJoinRequestResponse = RespondToJoinRequestResponses[keyof RespondToJoinRequestResponses];
-export type NoteDocumentsData = {
- body?: never;
- path?: never;
- query?: {
- /**
- * Empty returns recent documents.
- */
- query?: string;
- };
- url: '/meeting-notes/documents';
-};
-
-export type NoteDocumentsResponses = {
- 200: NotePicker;
-};
-
-export type NoteDocumentsResponse = NoteDocumentsResponses[keyof NoteDocumentsResponses];
-
-export type DocumentNoteLinksData = {
- body?: never;
- path: {
- document_id: string;
- };
- query?: never;
- url: '/meeting-notes/documents/{document_id}/links';
-};
-
-export type DocumentNoteLinksResponses = {
- 200: Array<DocumentNoteLink>;
-};
-
-export type DocumentNoteLinksResponse = DocumentNoteLinksResponses[keyof DocumentNoteLinksResponses];
-
export type DiscardCalendarReplacementData = {
body?: never;
path: {
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
index 52cf717875..35838d1e78 100644
--- a/packages/sdk/specs/calendar.json
+++ b/packages/sdk/specs/calendar.json
@@ -549,136 +549,6 @@
}
}
},
- "/events/{event_id}/notes": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "List notes visible through this meeting occurrence.",
- "operationId": "event_notes",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/MeetingNote"
- }
- }
- }
- }
- }
- }
- }
- },
- "/events/{event_id}/notes/{document_id}": {
- "put": {
- "tags": ["calendar_events"],
- "summary": "Idempotently link a markdown document and its optional team audience.",
- "operationId": "link_event_note",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/LinkNoteRequest"
- }
- }
- },
- "required": true
- },
- "responses": {
- "204": {
- "description": ""
- }
- }
- },
- "delete": {
- "tags": ["calendar_events"],
- "summary": "Remove this meeting's grant without deleting the document.",
- "operationId": "unlink_event_note",
- "parameters": [
- {
- "name": "event_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "format": "uuid"
- }
- },
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- },
- {
- "name": "occurrenceKey",
- "in": "query",
- "description": "Stable occurrence key returned by the calendar read API.",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "204": {
- "description": ""
- }
- }
- }
- },
"/events/{event_id}/provider-url": {
"get": {
"tags": ["calendar_events"],
@@ -975,68 +845,6 @@
}
}
},
- "/meeting-notes/documents": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "Suggest the caller's markdown documents and extra team audiences.",
- "operationId": "note_documents",
- "parameters": [
- {
- "name": "query",
- "in": "query",
- "description": "Empty returns recent documents.",
- "required": false,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/NotePicker"
- }
- }
- }
- }
- }
- }
- },
- "/meeting-notes/documents/{document_id}/links": {
- "get": {
- "tags": ["calendar_events"],
- "summary": "List a document's visible meeting links; owners also see unavailable grants.",
- "operationId": "document_note_links",
- "parameters": [
- {
- "name": "document_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/DocumentNoteLink"
- }
- }
- }
- }
- }
- }
- }
- },
"/replacements/{operation_id}": {
"get": {
"tags": ["calendar_events"],
@@ -1665,105 +1473,6 @@
"description": "Lifecycle of a request to be added as a guest of a shared event.",
"enum": ["pending", "accepted", "declined"]
},
- "CalendarMentionEvent": {
- "type": "object",
- "description": "Meeting-level fields shown in a calendar event mention preview, taken from\nthe requester's own projection of the meeting, or — when the requester has\nnone — from the mentioned projection a channel they belong to was given.",
- "required": [
- "title",
- "time",
- "isRecurring",
- "attendeeCount",
- "updatedAt"
- ],
- "properties": {
- "attendeeCount": {
- "type": "integer",
- "description": "Number of attendees on the previewed copy.",
- "minimum": 0
- },
- "canRequestToJoin": {
- "type": "boolean",
- "description": "For a channel-shared preview, whether the person who shared it can\nadd the requester as a guest. Always false for the requester's own\ncopy."
- },
- "description": {
- "type": ["string", "null"],
- "description": "Provider description, plain text or HTML, truncated for the preview.\nClients must sanitize it before rendering."
- },
- "isRecurring": {
- "type": "boolean",
- "description": "Whether the event repeats."
- },
- "joinRequestStatus": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarJoinRequestStatus",
- "description": "For a channel-shared preview, the requester's request to join, if any."
- }
- ]
- },
- "location": {
- "type": ["string", "null"],
- "description": "Location label, when set."
- },
- "occurrenceKey": {
- "type": ["string", "null"],
- "description": "Key of the previewed instance, absent when no occurrence is\nmaterialized."
- },
- "organizerEmail": {
- "type": ["string", "null"],
- "description": "Organizer email."
- },
- "organizerName": {
- "type": ["string", "null"],
- "description": "Organizer display name."
- },
- "time": {
- "$ref": "#/components/schemas/EventTime",
- "description": "Time of the previewed instance: the requested occurrence when it\nexists, else the next upcoming one, else the latest past one, else the\nseries start."
- },
- "title": {
- "type": "string",
- "description": "Display title."
- },
- "updatedAt": {
- "type": "string",
- "format": "date-time",
- "description": "Entity update time of the previewed copy."
- },
- "viewerCalendarIds": {
- "type": "array",
- "items": {
- "type": "string",
- "format": "uuid"
- },
- "description": "The calendars holding `viewer_event_id`, the canonical copy's first."
- },
- "viewerCopy": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarMentionViewerCopy",
- "description": "How the requester holds the meeting through `viewer_event_id`; absent\nexactly when that is."
- }
- ]
- },
- "viewerEventId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "The requester's own event entity for the mentioned meeting. Differs\nfrom the mentioned id when the mention came from another attendee.\nAbsent when the meeting is on none of the requester's calendars and\nthey see it only because it was shared with one of their channels:\nthat preview is read-only and there is no event of theirs to open."
- }
- }
- },
- "CalendarMentionViewerCopy": {
- "type": "string",
- "description": "How a requester holds a mentioned meeting on their own calendar, decided\nby the copy's own inbox, the way viewer capabilities decide organizer and\nguest.",
- "enum": ["snapshot", "invitation", "event"]
- },
"CalendarMutationApiError": {
"type": "object",
"description": "HTTP error body returned by calendar mutation endpoints.",
@@ -2039,73 +1748,6 @@
}
}
},
- "DocumentNoteLink": {
- "type": "object",
- "description": "A visible meeting link, or an owner's durable grant they can no longer open.",
- "required": [
- "documentName",
- "eventId",
- "occurrenceKey",
- "eventTitle",
- "canViewMeeting"
- ],
- "properties": {
- "canViewMeeting": {
- "type": "boolean",
- "description": "Whether the reader may resolve this exact meeting's details right now."
- },
- "documentName": {
- "type": "string",
- "description": "Current name of the markdown document."
- },
- "event": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/CalendarMentionEvent",
- "description": "Exact accessible calendar preview, resolved with this link's authorization snapshot."
- }
- ]
- },
- "eventId": {
- "type": "string",
- "format": "uuid",
- "description": "Linked calendar copy."
- },
- "eventTitle": {
- "type": "string",
- "description": "Current title, or a safe placeholder when meeting details are unavailable."
- },
- "occurrenceKey": {
- "type": "string",
- "description": "Original occurrence start, or `single` for a one-time meeting."
- },
- "team": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/NoteTeam",
- "description": "Independent optional team audience."
- }
- ]
- },
- "teamEvent": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/TeamCalendarItem",
- "description": "Exact, sanitized team-calendar details when the meeting is shared through a team."
- }
- ]
- }
- }
- },
"EventReminderOverride": {
"type": "object",
"description": "One reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.",
@@ -2276,17 +1918,6 @@
}
}
},
- "LinkNoteRequest": {
- "type": "object",
- "description": "Optional additional view access for one team.",
- "properties": {
- "teamId": {
- "type": ["string", "null"],
- "format": "uuid",
- "description": "Null means the meeting audience only."
- }
- }
- },
"ListCalendarsResponse": {
"type": "object",
"description": "Calendars visible to the requester across connected and delegated inboxes.",
@@ -2301,88 +1932,6 @@
}
}
},
- "MeetingNote": {
- "type": "object",
- "description": "One linked document and the extra access this link grants.",
- "required": ["documentId", "name", "canManage"],
- "properties": {
- "canManage": {
- "type": "boolean",
- "description": "Whether this viewer can change this document's sharing."
- },
- "documentId": {
- "type": "string",
- "description": "Markdown document identity."
- },
- "name": {
- "type": "string",
- "description": "Current document name."
- },
- "team": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/NoteTeam",
- "description": "Optional extra team view grant."
- }
- ]
- }
- }
- },
- "NoteDocument": {
- "type": "object",
- "description": "A document available in the note picker.",
- "required": ["documentId", "name"],
- "properties": {
- "documentId": {
- "type": "string",
- "description": "Markdown document identity."
- },
- "name": {
- "type": "string",
- "description": "Current document name, never a copied title."
- }
- }
- },
- "NotePicker": {
- "type": "object",
- "description": "Picker results; only documents whose owner is the caller are suggested.",
- "required": ["documents", "teams"],
- "properties": {
- "documents": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/NoteDocument"
- },
- "description": "At most 30 matching markdown documents, most recently updated first."
- },
- "teams": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/NoteTeam"
- },
- "description": "Teams the caller currently belongs to."
- }
- }
- },
- "NoteTeam": {
- "type": "object",
- "description": "An additional team audience, separate from the meeting's audience.",
- "required": ["id", "name"],
- "properties": {
- "id": {
- "type": "string",
- "format": "uuid",
- "description": "Team identity."
- },
- "name": {
- "type": "string",
- "description": "Display name."
- }
- }
- },
"OutOfOfficeAutoDeclineMode": {
"type": "string",
"description": "How an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
@@ -2533,110 +2082,6 @@
}
}
},
- "TeamCalendarContent": {
- "oneOf": [
- {
- "type": "object",
- "description": "No provider or event metadata.",
- "required": ["kind"],
- "properties": {
- "kind": {
- "type": "string",
- "enum": ["busy"]
- }
- }
- },
- {
- "type": "object",
- "description": "Explicitly authorized source content.",
- "required": ["details", "kind"],
- "properties": {
- "details": {
- "$ref": "#/components/schemas/TeamCalendarDetails",
- "description": "Detail projection."
- },
- "kind": {
- "type": "string",
- "enum": ["details"]
- }
- }
- }
- ],
- "description": "Disjoint busy/detail shapes prevent new event fields leaking by default."
- },
- "TeamCalendarDetails": {
- "type": "object",
- "description": "Safe details from a single authorized source.",
- "required": ["title", "attendees", "calendarName"],
- "properties": {
- "attendees": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/CalendarAttendee"
- },
- "description": "Attendees; self flags are relative to the requesting viewer."
- },
- "calendarName": {
- "type": "string",
- "description": "Source calendar name, shown only with details."
- },
- "conferenceUrl": {
- "type": ["string", "null"],
- "description": "Join URL, if supplied by this source."
- },
- "description": {
- "type": ["string", "null"],
- "description": "Body, if supplied by this source."
- },
- "location": {
- "type": ["string", "null"],
- "description": "Location, if supplied by this source."
- },
- "organizerEmail": {
- "type": ["string", "null"],
- "description": "Organizer address from this source."
- },
- "organizerName": {
- "type": ["string", "null"],
- "description": "Organizer name from this source."
- },
- "title": {
- "type": "string",
- "description": "Display title."
- }
- }
- },
- "TeamCalendarItem": {
- "allOf": [
- {
- "$ref": "#/components/schemas/TeamCalendarContent",
- "description": "Authorized content variant."
- },
- {
- "type": "object",
- "required": ["id", "ownerId", "time", "contributesToAvailability"],
- "properties": {
- "contributesToAvailability": {
- "type": "boolean",
- "description": "Whether this occurrence blocks the sharer's personal availability.\nA subscribed calendar's block can be shared without occupying the sharer."
- },
- "id": {
- "type": "string",
- "description": "Stable opaque projection identity, never an event entity id."
- },
- "ownerId": {
- "type": "string",
- "description": "The person sharing access to the source."
- },
- "time": {
- "$ref": "#/components/schemas/EventTime",
- "description": "Occurrence interval."
- }
- }
- }
- ],
- "description": "A read-only team calendar occurrence."
- },
"TeamCalendarSharing": {
"type": "string",
"description": "What a user exposes through their team membership.",
diff --git a/packages/sdk/src/entities/calendar/event.ts b/packages/sdk/src/entities/calendar/event.ts
index f2d52790af..b0b876eda1 100644
--- a/packages/sdk/src/entities/calendar/event.ts
+++ b/packages/sdk/src/entities/calendar/event.ts
@@ -15,14 +15,10 @@ import type {
OutOfOfficeProperties,
UpdateCalendarEventRequest,
} from '../../../generated/calendar/types.gen';
-import type { CalendarOccurrence } from '../../../generated/storage/types.gen';
import { MacroError, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import type { Document } from '../documents/document';
import { MacroEntity } from '../entity';
-import type { Team } from '../teams/team';
import { Calendar } from './calendar';
-import { CalendarNote } from './note';
import { CalendarReplacement } from './replacement';
/** Fields to change on an event; omitted fields are left untouched. */
@@ -135,43 +131,6 @@ export interface RsvpEventOptions {
* mutations, but reading a field on it throws.
*/
export class CalendarEvent extends MacroEntity<CalendarEventRecord> {
- /** Notes linked to a specific occurrence returned by `calendar.occurrences()`. */
- async notes(occurrence: CalendarOccurrence): Promise<CalendarNote[]> {
- this.requireOwnOccurrence(occurrence);
- const notes = unwrap(
- await this.client.calendar.eventNotes({
- path: { event_id: this.id },
- query: { occurrenceKey: occurrence.occurrenceKey },
- }),
- );
- return notes.map((note) =>
- CalendarNote.fromRecord(this.client, this, occurrence, note),
- );
- }
-
- /** Link a markdown document you own. Meeting-detail viewers gain read access;
- * an optional team gains read access too. Editing and other sharing are preserved. */
- async linkNote(
- document: Document,
- occurrence: CalendarOccurrence,
- options: { team?: Team } = {},
- ): Promise<CalendarNote> {
- this.requireOwnOccurrence(occurrence);
- unwrap(
- await this.client.calendar.linkEventNote({
- path: { event_id: this.id, document_id: document.id },
- query: { occurrenceKey: occurrence.occurrenceKey },
- body: { teamId: options.team?.id ?? null },
- }),
- );
- return CalendarNote.forDocument(this.client, this, occurrence, document);
- }
-
- private requireOwnOccurrence(occurrence: CalendarOccurrence) {
- if (occurrence.eventId !== this.id)
- throw new MacroError('The occurrence belongs to a different event');
- }
-
protected async fetch(): Promise<CalendarEventRecord> {
throw new MacroError(
`calendar event ${this.id} has no fetch-by-id endpoint; read the record ` +
diff --git a/packages/sdk/src/entities/calendar/namespace.ts b/packages/sdk/src/entities/calendar/namespace.ts
index 498e430c0a..ee5e53c67c 100644
--- a/packages/sdk/src/entities/calendar/namespace.ts
+++ b/packages/sdk/src/entities/calendar/namespace.ts
@@ -19,9 +19,7 @@ import type {
} from '../../../generated/storage/types.gen';
import { paginate, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import { Document } from '../documents/document';
import type { Link } from '../email/link';
-import { Team } from '../teams/team';
import { User } from '../users/user';
import { Calendar } from './calendar';
import { CalendarEvent } from './event';
@@ -109,23 +107,6 @@ export type CalendarEventRole = 'organizer' | 'guest';
* calendar and never offer to add it to another one.
*/
export class CalendarNamespace {
- /** Find up to 30 owned markdown documents for meeting notes, plus available extra team audiences. */
- async noteDocuments(query = '') {
- const picker = unwrap(
- await this.client.calendar.noteDocuments({ query: { query } }),
- );
- return {
- documents: picker.documents.map((note) => ({
- document: Document.byId(this.client, note.documentId),
- name: note.name,
- })),
- teams: picker.teams.map((team) => ({
- team: Team.byId(this.client, team.id),
- name: team.name,
- })),
- };
- }
-
/** Calendar availability settings, each referring to a typed calendar. */
async availabilityCalendars() {
return unwrap(
diff --git a/packages/sdk/src/entities/calendar/note.ts b/packages/sdk/src/entities/calendar/note.ts
deleted file mode 100644
index fb4c405520..0000000000
--- a/packages/sdk/src/entities/calendar/note.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import type {
- DocumentNoteLink,
- MeetingNote,
-} from '../../../generated/calendar/types.gen';
-import type { CalendarOccurrence } from '../../../generated/storage/types.gen';
-import { MacroError, MacroNotFoundError, unwrap } from '../../utils';
-import type { MacroClient } from '../../utils/client';
-import { Document } from '../documents/document';
-import { MacroEntity } from '../entity';
-import { Team } from '../teams/team';
-import { CalendarEvent } from './event';
-
-/** A markdown document linked to one meeting occurrence, with view-only access. */
-export class CalendarNote extends MacroEntity<MeetingNote> {
- private constructor(
- client: MacroClient,
- readonly event: CalendarEvent,
- readonly occurrence: Pick<CalendarOccurrence, 'eventId' | 'occurrenceKey'>,
- document: Document,
- record?: MeetingNote,
- private readonly fromDocument = false,
- ) {
- super(client, document.id, record);
- if (occurrence.eventId !== event.id) {
- throw new MacroError('Choose an occurrence belonging to this event');
- }
- }
-
- /** Seed an owner-visible link that can be revoked even if the meeting is unavailable. */
- static fromDocumentLink(
- client: MacroClient,
- document: Document,
- link: DocumentNoteLink,
- ): CalendarNote {
- return new CalendarNote(
- client,
- CalendarEvent.byId(client, link.eventId),
- link,
- document,
- {
- documentId: document.id,
- name: link.documentName,
- team: link.team,
- canManage: true,
- },
- true,
- );
- }
-
- /** Construct a handle for a document already linked to this occurrence. */
- static forDocument(
- client: MacroClient,
- event: CalendarEvent,
- occurrence: CalendarOccurrence,
- document: Document,
- ): CalendarNote {
- return new CalendarNote(client, event, occurrence, document);
- }
-
- /** Seed a handle with a record returned by the meeting-note API. */
- static fromRecord(
- client: MacroClient,
- event: CalendarEvent,
- occurrence: CalendarOccurrence,
- record: MeetingNote,
- ): CalendarNote {
- return new CalendarNote(
- client,
- event,
- occurrence,
- Document.byId(client, record.documentId),
- record,
- );
- }
-
- protected async fetch(): Promise<MeetingNote> {
- if (this.fromDocument) {
- const links = unwrap(
- await this.client.calendar.documentNoteLinks({
- path: { document_id: this.id },
- }),
- );
- const link = links.find(
- (item) =>
- item.eventId === this.event.id &&
- item.occurrenceKey === this.occurrence.occurrenceKey,
- );
- if (!link)
- throw new MacroNotFoundError('This meeting link has been removed');
- return {
- documentId: this.id,
- name: link.documentName,
- team: link.team,
- canManage: true,
- };
- }
- const notes = unwrap(
- await this.client.calendar.eventNotes({
- path: { event_id: this.event.id },
- query: { occurrenceKey: this.occurrence.occurrenceKey },
- }),
- );
- const note = notes.find((item) => item.documentId === this.id);
- if (!note)
- throw new MacroNotFoundError(
- 'This document is no longer linked to the meeting',
- );
- return note;
- }
-
- /** The original markdown document; unlinking never deletes it. */
- readonly document = this.mappedField('documentId', (id) =>
- Document.byId(this.client, id),
- );
-
- /** Current document name. */
- readonly name = this.field('name');
-
- /** Optional extra team audience. Meeting-detail viewers already have view access. */
- readonly team = this.mappedField('team', (team) =>
- team ? Team.byId(this.client, team.id) : undefined,
- );
-
- /** Whether the caller may change this link's sharing. */
- readonly canManage = this.field('canManage');
-
- /** Change the extra team view grant; omit the team to remove it. Requires document ownership. */
- async setTeam(team?: Team): Promise<void> {
- await this.mutate((client) =>
- client.calendar.linkEventNote({
- path: { event_id: this.event.id, document_id: this.id },
- query: { occurrenceKey: this.occurrence.occurrenceKey },
- body: { teamId: team?.id ?? null },
- }),
- );
- }
-
- /** Remove this occurrence's link and view grants, preserving the document and other sharing. */
- async unlink(): Promise<void> {
- await this.mutate((client) =>
- client.calendar.unlinkEventNote({
- path: { event_id: this.event.id, document_id: this.id },
- query: { occurrenceKey: this.occurrence.occurrenceKey },
- }),
- );
- }
-}
diff --git a/packages/sdk/src/entities/documents/document.ts b/packages/sdk/src/entities/documents/document.ts
index ca12389a78..2677e36116 100644
--- a/packages/sdk/src/entities/documents/document.ts
+++ b/packages/sdk/src/entities/documents/document.ts
@@ -20,7 +20,6 @@ import {
} from '../../mentions';
import { MacroApiError, mapConcurrently, paginate, unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import { CalendarNote } from '../calendar/note';
import { PropertiedEntity } from '../entity';
import {
MessageThread,
@@ -56,20 +55,6 @@ export class Document
extends PropertiedEntity<DocumentDetail>
implements Mentionable
{
- /** Meeting links visible to the reader. Owners also receive unavailable grants and may unlink them to revoke meeting/team access. */
- async meetingNotes(): Promise<
- Array<{ note: CalendarNote; eventTitle: string }>
- > {
- const links = unwrap(
- await this.client.calendar.documentNoteLinks({
- path: { document_id: this.id },
- }),
- );
- return links.map((link) => ({
- note: CalendarNote.fromDocumentLink(this.client, this, link),
- eventTitle: link.eventTitle,
- }));
- }
/** PDF annotations in this document. */
async anchors(): Promise<DocumentAnchor[]> {
return unwrap(
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index b3da10b4be..3e772a6227 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -259,7 +259,6 @@ export { ReviewItem, SessionReview } from './entities/agent-sessions/review';
export { ToolApproval } from './entities/agent-sessions/tool-approval';
export { Agent, type AgentOptions } from './entities/agents/agent';
export { UserApiKey } from './entities/api-keys/api-key';
-export { CalendarNote } from './entities/calendar/note';
export { ChannelActivity } from './entities/channels/activity';
export { ChannelPicture } from './entities/channels/picture';
export { ChatGeneration, ChatMessage } from './entities/chats/generation';
diff --git a/packages/sdk/tests/calendar-notes.test.ts b/packages/sdk/tests/calendar-notes.test.ts
deleted file mode 100644
index 4aef6ca402..0000000000
--- a/packages/sdk/tests/calendar-notes.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { afterEach, expect, test } from 'bun:test';
-import type { CalendarOccurrence } from '../generated/storage/types.gen';
-import { Macro } from '../src/macro';
-
-const originalFetch = globalThis.fetch;
-afterEach(() => {
- globalThis.fetch = originalFetch;
-});
-
-const occurrence: CalendarOccurrence = {
- eventId: 'event-1',
- occurrenceKey: '2026-10-23T14:00:00+00:00',
- isCancelled: false,
- time: {
- kind: 'timed',
- startsAt: '2026-10-23T14:00:00Z',
- endsAt: '2026-10-23T15:00:00Z',
- },
-};
-
-function recordingMacro() {
- const requests: Request[] = [];
- let teamId: string | null = null;
- let linked = false;
- globalThis.fetch = (async (input, init) => {
- const request = input instanceof Request ? input : new Request(input, init);
- requests.push(request);
- if (new URL(request.url).pathname === '/meeting-notes/documents') {
- return Response.json({
- documents: [{ documentId: 'note-1', name: 'Design notes' }],
- teams: [{ id: 'team-1', name: 'Design' }],
- });
- }
- if (request.method === 'PUT') {
- const body = await request.clone().json();
- teamId = body.teamId;
- linked = true;
- return new Response(null, { status: 204 });
- }
- if (request.method === 'DELETE') {
- linked = false;
- return new Response(null, { status: 204 });
- }
- return Response.json(
- linked
- ? [
- {
- documentId: 'note-1',
- name: 'Design notes',
- canManage: true,
- team: teamId ? { id: teamId, name: 'Design' } : null,
- },
- ]
- : [],
- );
- }) as typeof fetch;
- return {
- requests,
- macro: new Macro({
- env: 'dev',
- token: 'test-token',
- hosts: { calendar: 'https://calendar.example.test' },
- }),
- };
-}
-
-test('meeting notes use occurrence-scoped handles and explicit optional team grants', async () => {
- const { macro, requests } = recordingMacro();
- const picker = await macro.calendar.noteDocuments('Design');
- const document = picker.documents[0].document;
- const team = picker.teams[0].team;
- expect(document.id).toBe('note-1');
- const event = macro.calendar.event(occurrence.eventId);
- const note = await event.linkNote(document, occurrence);
- expect(await requests[1].clone().json()).toEqual({ teamId: null });
- expect(new URL(requests[1].url).searchParams.get('occurrenceKey')).toBe(
- occurrence.occurrenceKey,
- );
- expect(await note.team()).toBeUndefined();
- await note.setTeam(team);
- expect((await note.team())?.id).toBe('team-1');
- await note.setTeam();
- expect(await note.team()).toBeUndefined();
- const listed = await event.notes(occurrence);
- expect((await listed[0].document()).id).toBe(document.id);
- const beforeSeededRead = requests.length;
- expect(await listed[0].name()).toBe('Design notes');
- expect(requests).toHaveLength(beforeSeededRead);
- await note.unlink();
- expect(await event.notes(occurrence)).toEqual([]);
- expect(
- requests
- .filter((request) => request.method === 'DELETE')
- .map((request) => new URL(request.url).pathname),
- ).toEqual(['/events/event-1/notes/note-1']);
-});
-
-test('a mismatched occurrence cannot share a document or issue a request', async () => {
- const { macro, requests } = recordingMacro();
- await expect(
- macro.calendar
- .event('different-event')
- .linkNote(macro.documents.byId('note-1'), occurrence),
- ).rejects.toThrow('different event');
- expect(requests).toHaveLength(0);
-});
-
-test('a document owner can discover and revoke an unavailable meeting grant', async () => {
- const { macro } = recordingMacro();
- const requests: Request[] = [];
- globalThis.fetch = (async (input, init) => {
- const request = input instanceof Request ? input : new Request(input, init);
- requests.push(request);
- if (request.method === 'DELETE') return new Response(null, { status: 204 });
- return Response.json([
- {
- eventId: occurrence.eventId,
- occurrenceKey: occurrence.occurrenceKey,
- eventTitle: 'Unavailable meeting',
- documentName: 'Design notes',
- team: { id: 'team-1', name: 'Design' },
- },
- ]);
- }) as typeof fetch;
- const links = await macro.documents.byId('note-1').meetingNotes();
- expect(links[0].eventTitle).toBe('Unavailable meeting');
- expect((await links[0].note.team())?.id).toBe('team-1');
- await links[0].note.unlink();
- expect(new URL(requests[1].url).pathname).toBe(
- '/events/event-1/notes/note-1',
- );
- expect(new URL(requests[1].url).searchParams.get('occurrenceKey')).toBe(
- occurrence.occurrenceKey,
- );
-});
-
-test('a rejected share surfaces the error without retrying or granting team access', async () => {
- const { macro, requests } = recordingMacro();
- const event = macro.calendar.event(occurrence.eventId);
- const note = await event.linkNote(macro.documents.byId('note-1'), occurrence);
- expect(await note.team()).toBeUndefined();
- let attempts = 0;
- globalThis.fetch = (async (_input) => {
- attempts++;
- return Response.json({ message: 'Forbidden' }, { status: 403 });
- }) as typeof fetch;
- await expect(note.setTeam(macro.teams.byId('team-1'))).rejects.toThrow();
- expect(attempts).toBe(1);
- expect(await note.team()).toBeUndefined();
- expect(requests).toHaveLength(2);
-});
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index bf9e5620e0..392c64e0cf 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -18,7 +18,6 @@ files:
- apps/web/src/features/task-composer/components/**
- apps/web/src/features/universal-input/components/**
- apps/web/src/features/saved-views/components/**
- - apps/web/src/features/calendar-notes/components/**
- apps/web/src/features/access-requests/components/**
- apps/web/src/features/agent-activity/components/**
- apps/web/src/features/agent-dms/components/**
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index a6ac4d295a..703d4f18a6 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -20,7 +20,6 @@ files:
- apps/web/src/features/task-composer/core/**
- apps/web/src/features/universal-input/core/**
- apps/web/src/features/saved-views/core/**
- - apps/web/src/features/calendar-notes/core/**
- apps/web/src/features/access-requests/core/**
- apps/web/src/features/agent-activity/core/**
- apps/web/src/features/agent-dms/core/**
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index b54231bb24..1b0d1f7bb3 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -23,8 +23,6 @@ files:
- apps/web/src/features/universal-input/context/**
- apps/web/src/features/saved-views/queries/**
- apps/web/src/features/saved-views/primitives/**
- - apps/web/src/features/calendar-notes/queries/**
- - apps/web/src/features/calendar-notes/primitives/**
- apps/web/src/features/access-requests/queries/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 0c2eb9fbba..11d7dbf941 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -40,10 +40,6 @@ files:
- apps/web/src/features/saved-views/primitives/**
- apps/web/src/features/saved-views/components/**
- apps/web/src/features/saved-views/views/**
- - apps/web/src/features/calendar-notes/queries/**
- - apps/web/src/features/calendar-notes/primitives/**
- - apps/web/src/features/calendar-notes/components/**
- - apps/web/src/features/calendar-notes/views/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/access-requests/views/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index e3211d4367..766b404947 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -18,7 +18,6 @@ files:
- apps/web/src/features/task-composer/components/**
- apps/web/src/features/universal-input/components/**
- apps/web/src/features/saved-views/components/**
- - apps/web/src/features/calendar-notes/components/**
- apps/web/src/features/access-requests/components/**
- apps/web/src/features/agent-activity/components/**
- apps/web/src/features/agent-dms/components/**
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index c80b39001f..c20fda7ab7 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -20,7 +20,6 @@ files:
- apps/web/src/features/task-composer/core/**
- apps/web/src/features/universal-input/core/**
- apps/web/src/features/saved-views/core/**
- - apps/web/src/features/calendar-notes/core/**
- apps/web/src/features/access-requests/core/**
- apps/web/src/features/agent-activity/core/**
- apps/web/src/features/agent-dms/core/**
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 2075b0b2df..3bb8e3d482 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -23,8 +23,6 @@ files:
- apps/web/src/features/universal-input/context/**
- apps/web/src/features/saved-views/queries/**
- apps/web/src/features/saved-views/primitives/**
- - apps/web/src/features/calendar-notes/queries/**
- - apps/web/src/features/calendar-notes/primitives/**
- apps/web/src/features/access-requests/queries/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index 0eeb60eeb4..bed06bd903 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -40,10 +40,6 @@ files:
- apps/web/src/features/saved-views/primitives/**
- apps/web/src/features/saved-views/components/**
- apps/web/src/features/saved-views/views/**
- - apps/web/src/features/calendar-notes/queries/**
- - apps/web/src/features/calendar-notes/primitives/**
- - apps/web/src/features/calendar-notes/components/**
- - apps/web/src/features/calendar-notes/views/**
- apps/web/src/features/access-requests/primitives/**
- apps/web/src/features/access-requests/views/**
- apps/web/src/features/agent-activity/queries/**
diff --git a/services/calendar_service/AGENTS.md b/services/calendar_service/AGENTS.md
index b62e914471..d88a3d21a0 100644
--- a/services/calendar_service/AGENTS.md
+++ b/services/calendar_service/AGENTS.md
@@ -16,7 +16,7 @@ gateway `/calendar` prefix.
## Scope
- Owns: the Google Calendar push webhook, calendar mutation routes, calendar
- sync scheduling/outbox, meeting-note link routes, and the backfill queue worker.
+ sync scheduling/outbox, and the backfill queue worker.
- Not here: calendar domain logic and the Postgres/Google adapters →
`crates/calendar_events`, `crates/calendar_scheduling`.
@@ -45,8 +45,6 @@ gateway `/calendar` prefix.
- The router is mounted at both `/` and `/calendar` (`GATEWAY_PATH_PREFIX` in
`src/api.rs`) because the gateway forwards the path unchanged.
-- Meeting-note routes remain mounted with calendar sync disabled; compose their
- repository and document access service from the primary database.
- Reauth-required notifications ride the shared `LinkManagerQueue`, consumed by
`email_service`; don't add a second calendar-specific reconnect notification.
- Forward `team_ooo_changed` to both inbox and teammate refresh notifications;
diff --git a/services/calendar_service/Cargo.toml b/services/calendar_service/Cargo.toml
index 4a445a035c..8623cc73b0 100644
--- a/services/calendar_service/Cargo.toml
+++ b/services/calendar_service/Cargo.toml
@@ -28,14 +28,12 @@ calendar_events = { path = "../../crates/calendar_events", features = [
"google",
"inbound",
"postgres",
- "notes",
] }
calendar_scheduling = { path = "../../crates/calendar_scheduling", features = ["calendar", "inbound", "postgres"] }
chrono = { workspace = true }
connection_gateway_client = { path = "../../crates/connection_gateway_client" }
email_db_client = { path = "../../crates/email_db_client" }
email_utils = { path = "../../crates/email_utils" }
-entity_access = { path = "../../crates/entity_access", default-features = false, features = ["outbound", "ports"] }
futures = { workspace = true }
google_token = { path = "../../crates/google_token" }
macro_auth = { path = "../../crates/macro_auth" }
diff --git a/services/calendar_service/src/api.rs b/services/calendar_service/src/api.rs
index 539eef8244..218952cff4 100644
--- a/services/calendar_service/src/api.rs
+++ b/services/calendar_service/src/api.rs
@@ -64,13 +64,6 @@ fn swagger_ui() -> Router {
}
fn api_router(state: ApiContext) -> Router<ApiContext> {
- let notes = calendar_events::inbound::notes_router::notes_router(
- calendar_events::inbound::notes_router::NotesRouterState::new(
- state.calendar_notes.clone(),
- state.note_access.clone(),
- state.authorization_state.clone(),
- ),
- );
let team_settings = calendar_events::inbound::team_router::team_calendar_settings_router(
calendar_events::inbound::team_router::CalendarTeamRouterState::new(
state.calendar_team_service.clone(),
@@ -81,7 +74,6 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
// provider write would never be reflected locally.
if state.config.calendar_sync_enabled {
calendar_watch::router()
- .merge(notes)
.merge(team_settings)
.nest(
"/scheduling",
@@ -104,6 +96,6 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {
state.authorization_state.clone(),
)))
} else {
- calendar_watch::router().merge(team_settings).merge(notes)
+ calendar_watch::router().merge(team_settings)
}
}
diff --git a/services/calendar_service/src/api/context.rs b/services/calendar_service/src/api/context.rs
index 0362772cd2..bb7a9d4d52 100644
--- a/services/calendar_service/src/api/context.rs
+++ b/services/calendar_service/src/api/context.rs
@@ -18,14 +18,6 @@ use crate::config::Config;
pub type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;
/// Calendar grant/watch service backing the push webhook.
pub type CalendarGrantService = CalendarService<PgCalendarRepository>;
-/// Meeting-note links with current meeting and team audiences.
-pub type CalendarNotesService = calendar_events::domain::notes::MeetingNotes<
- calendar_events::outbound::pg_notes::PgNoteRepository,
->;
-/// Shared document permission boundary.
-pub type NoteAccessService = entity_access::domain::service::EntityAccessServiceImpl<
- entity_access::outbound::PgAccessRepository,
->;
/// Team-sharing policy service with viewer refresh notifications.
pub type CalendarTeamSvc = calendar_events::domain::team::CalendarTeamServiceImpl<
calendar_events::outbound::pg_team::PgCalendarTeamRepository,
@@ -64,10 +56,6 @@ pub struct ApiContext {
pub authorization_state: MacroAuthorizationState<AuthorizationService>,
/// Calendar grant/watch service backing the push webhook.
pub calendar_service: Arc<CalendarGrantService>,
- /// Persistent meeting-note links.
- pub calendar_notes: Arc<CalendarNotesService>,
- /// Document ownership receipts required before sharing notes.
- pub note_access: Arc<NoteAccessService>,
/// User-initiated calendar mutation service.
pub calendar_mutation_service: Arc<CalendarMutationSvc>,
/// Read-only team-sharing preferences and personal availability inclusion.
diff --git a/services/calendar_service/src/api/swagger.rs b/services/calendar_service/src/api/swagger.rs
index 953a8dfd23..6ecf215e20 100644
--- a/services/calendar_service/src/api/swagger.rs
+++ b/services/calendar_service/src/api/swagger.rs
@@ -9,11 +9,6 @@ use utoipa::OpenApi;
#[openapi(
paths(
crate::health::health_handler,
- calendar_events::inbound::notes_router::event_notes,
- calendar_events::inbound::notes_router::note_documents,
- calendar_events::inbound::notes_router::document_note_links,
- calendar_events::inbound::notes_router::link_event_note,
- calendar_events::inbound::notes_router::unlink_event_note,
calendar_events::inbound::replacement_router::prepare_calendar_replacement,
calendar_events::inbound::replacement_router::confirm_calendar_replacement,
calendar_events::inbound::replacement_router::calendar_replacement_status,
diff --git a/services/calendar_service/src/main.rs b/services/calendar_service/src/main.rs
index 37abc57cb3..1dd1606a3b 100644
--- a/services/calendar_service/src/main.rs
+++ b/services/calendar_service/src/main.rs
@@ -321,14 +321,6 @@ async fn main() -> anyhow::Result<()> {
config: Arc::new(config),
authorization_state,
calendar_service,
- calendar_notes: Arc::new(calendar_events::domain::notes::MeetingNotes::new(
- calendar_events::outbound::pg_notes::PgNoteRepository::new(db.clone()),
- )),
- note_access: Arc::new(
- entity_access::domain::service::EntityAccessServiceImpl::new(
- entity_access::outbound::PgAccessRepository::new(db.clone()),
- ),
- ),
calendar_mutation_service,
calendar_team_service,
scheduling_service,