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.

fix(web): stop unknown service variants crashing exhaustive matches (#8221)

teo3c9be271001d
diff --git a/.agents/rules/web/architecture.md b/.agents/rules/web/architecture.md
index cf9e209b01..d28dc244b6 100644
--- a/.agents/rules/web/architecture.md
+++ b/.agents/rules/web/architecture.md
@@ -26,8 +26,13 @@ Module layout, layering, and TypeScript conventions.
- **FE-21** No `any` — proper types or `unknown` + type guards.
- **FE-31** Never cast a string to `ItemType` — parse it with `stringToItemType`
from `@service-storage/client`, the one owner of entity-type spellings (email
- threads alone are stored as `email`, `thread`, and `email_thread`). Enforced
- by ast-grep `ts-no-item-type-cast` + `tsx-no-item-type-cast`, CI error.
+ threads alone are stored as `email`, `thread`, and `email_thread`). The same
+ goes for a service's `EntityType`: each service has its own enum, so parse
+ with `parseEntityType` (properties) or type the source rather than casting
+ (`as EntityReference['entity_type']` let `AGENT_SESSION` crash the property
+ editor). Enforced by ast-grep `ts-no-item-type-cast` +
+ `tsx-no-item-type-cast` for `as ItemType`, `as EntityType`, and
+ `as EntityReference['entity_type']`, CI error.
- **FE-33** New features and feature restructures use the [layered feature
architecture](../../../docs/architecture/frontend-features.md), with
`features/activity` as the reference. Use `core/` for pure feature types and
diff --git a/.agents/rules/web/libraries.md b/.agents/rules/web/libraries.md
index fae8b6d49a..6b562c9d09 100644
--- a/.agents/rules/web/libraries.md
+++ b/.agents/rules/web/libraries.md
@@ -16,8 +16,21 @@ under `services/` throw and validate with zod; elsewhere in `apps/web` and
- **FE-35** Branch on unions and literal sets with ts-pattern:
`match(x).with(...).exhaustive()`. `.otherwise` only for open domains
- (arbitrary strings, error codes). Never hand-write `switch` on a discriminant;
- a `switch` over `event.key` in a keyboard handler is fine.
+ (arbitrary strings, error codes, and any payload from a Tauri plugin, worker,
+ or the network: the sender ships separately and `.exhaustive()` throws on a
+ shape it doesn't know). When such a payload is typed by a closed union you
+ still want checked (a generated service enum, a message union, persisted
+ data), use `.exhaustive((unknown) => fallback)` instead: it keeps the
+ compile-time check and returns the fallback rather than throwing. Read paths
+ fall back to an empty or unknown value; write paths and request handlers fail
+ the operation (`err`, a rejected mutation, an `ok: false` reply) instead of
+ sending or reporting a default. Bare `.exhaustive()` is for closed,
+ client-built values; parse anything else into one first
+ (`stringToItemType`, `parseEntityType`). Enforced in wire adapters,
+ service clients, transports, workers, and SDK event hydrators by ast-grep
+ `ts-exhaustive-boundary-fallback` + `tsx-exhaustive-boundary-fallback`, CI
+ error. Never hand-write `switch` on a discriminant; a `switch` over
+ `event.key` in a keyboard handler is fine.
- **FE-36** Fallible operations return neverthrow `Result` / `ResultAsync`. New
feature code types errors as `{ kind:... }` unions matched with ts-pattern;
transport code keeps `ResultError<Code>[]`. Guard with `if (r.isErr())
diff --git a/apps/web/src/features/access-requests/queries/source.ts b/apps/web/src/features/access-requests/queries/source.ts
index 628f2a34a4..34c8c17fa6 100644
--- a/apps/web/src/features/access-requests/queries/source.ts
+++ b/apps/web/src/features/access-requests/queries/source.ts
@@ -81,7 +81,9 @@ export function createSharingSource(
accessRequestsClient.setGrant(target, change.userId, change.level)
)
)
- .exhaustive();
+ .exhaustive(() =>
+ Promise.reject(new Error(`Unknown access change: ${change.kind}`))
+ );
},
onSuccess: (_result, change) => {
refreshSharedAccess(change.target);
diff --git a/apps/web/src/features/block-database/core/native-mentions.ts b/apps/web/src/features/block-database/core/native-mentions.ts
index eeb37ce3e6..acdd60fc41 100644
--- a/apps/web/src/features/block-database/core/native-mentions.ts
+++ b/apps/web/src/features/block-database/core/native-mentions.ts
@@ -74,5 +74,5 @@ export function databaseMentionScope(
'INITIATIVE',
() => ({ sources: [], documentBuckets: undefined })
)
- .exhaustive();
+ .exhaustive(() => ({ sources: [] }));
}
diff --git a/apps/web/src/features/block-database/core/webhook-example.ts b/apps/web/src/features/block-database/core/webhook-example.ts
index edc3244f02..ad7a655e56 100644
--- a/apps/web/src/features/block-database/core/webhook-example.ts
+++ b/apps/web/src/features/block-database/core/webhook-example.ts
@@ -34,7 +34,7 @@ function exampleValue(column: DatabaseViewColumn, today: string): ExampleValue {
: label;
})
.with('ENTITY', () => null)
- .exhaustive();
+ .exhaustive(() => null);
}
/** A `curl` that posts the payload to the webhook. */
diff --git a/apps/web/src/features/block-database/queries/column-casts.test.tsx b/apps/web/src/features/block-database/queries/column-casts.test.tsx
index 53c74fb902..0498bc0108 100644
--- a/apps/web/src/features/block-database/queries/column-casts.test.tsx
+++ b/apps/web/src/features/block-database/queries/column-casts.test.tsx
@@ -135,3 +135,55 @@ it('reads the dry run only once the menu opens, in the menu’s terms', async ()
columnId: 'price',
});
});
+
+it('offers a cast verdict from a newer server as never instead of throwing', async () => {
+ transport.columnCasts.mockResolvedValue(
+ ok([
+ {
+ data_type: 'NUMBER',
+ is_multi_select: false,
+ specific_entity_type: null,
+ relation: false,
+ cast: JSON.parse('"lossy"'),
+ reason: null,
+ failures: 0,
+ summary: null,
+ examples: [],
+ },
+ ])
+ );
+ let casts!: () => DatabaseColumnCasts;
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ render(() => (
+ <QueryClientProvider client={client}>
+ {(() => {
+ casts = createColumnCasts({
+ databaseId: 'db',
+ tableId: 'tasks',
+ version: () => 4,
+ })('price', () => true);
+ return null;
+ })()}
+ </QueryClientProvider>
+ ));
+
+ await waitFor(() =>
+ expect(casts()).toEqual({
+ status: 'ready',
+ version: 4,
+ casts: [
+ {
+ target: {
+ dataType: 'NUMBER',
+ isMultiSelect: false,
+ specificEntityType: undefined,
+ relation: false,
+ },
+ cast: { verdict: 'never', reason: '' },
+ },
+ ],
+ })
+ );
+});
diff --git a/apps/web/src/features/block-database/queries/column-casts.ts b/apps/web/src/features/block-database/queries/column-casts.ts
index 2edab59a7c..8dbab2bc54 100644
--- a/apps/web/src/features/block-database/queries/column-casts.ts
+++ b/apps/web/src/features/block-database/queries/column-casts.ts
@@ -70,6 +70,6 @@ function toMenuCast(cast: ServerColumnCast) {
examples: cast.examples,
}))
.with('never', () => ({ verdict: 'never', reason: cast.reason ?? '' }))
- .exhaustive(),
+ .exhaustive(() => ({ verdict: 'never', reason: cast.reason ?? '' })),
};
}
diff --git a/apps/web/src/features/block-database/queries/rename-database.test.ts b/apps/web/src/features/block-database/queries/rename-database.test.ts
index de6dae81ee..311d6eb9ea 100644
--- a/apps/web/src/features/block-database/queries/rename-database.test.ts
+++ b/apps/web/src/features/block-database/queries/rename-database.test.ts
@@ -100,6 +100,25 @@ describe('rename database', () => {
expect(cache.setQueryData).not.toHaveBeenCalled();
});
+ it('reports a result type from a newer server as unreachable', async () => {
+ const client: RenameDatabaseClient = {
+ mutation: () => ({
+ toPromise: async () => ({
+ data: {
+ renameEntities: {
+ results: [JSON.parse('{"__typename":"GraphqlMutationQueued"}')],
+ },
+ },
+ }),
+ }),
+ };
+
+ expect(await renameDatabase(client, 'db', 'Roadmap')).toEqual(
+ err({ kind: 'unreachable' })
+ );
+ expect(cache.setQueryData).not.toHaveBeenCalled();
+ });
+
it('refuses a blank name without sending it', async () => {
const mutation = vi.fn<RenameDatabaseClient['mutation']>();
diff --git a/apps/web/src/features/block-database/queries/rename-database.ts b/apps/web/src/features/block-database/queries/rename-database.ts
index b087f0f105..27a59fbed9 100644
--- a/apps/web/src/features/block-database/queries/rename-database.ts
+++ b/apps/web/src/features/block-database/queries/rename-database.ts
@@ -103,7 +103,7 @@ export function renameDatabase(
);
return ok(undefined);
})
- .exhaustive();
+ .exhaustive(async () => err({ kind: 'unreachable' }));
};
return new ResultAsync(renamed());
}
diff --git a/apps/web/src/features/block-database/queries/trash-database.test.ts b/apps/web/src/features/block-database/queries/trash-database.test.ts
index 9115ab8ee6..01d9c4e70d 100644
--- a/apps/web/src/features/block-database/queries/trash-database.test.ts
+++ b/apps/web/src/features/block-database/queries/trash-database.test.ts
@@ -89,4 +89,22 @@ describe('trash database', () => {
);
expect(cache.setQueryData).not.toHaveBeenCalled();
});
+
+ it('reports an outcome type from a newer server as unreachable', async () => {
+ const fromNewerServer = JSON.parse(
+ '{"__typename":"GraphqlMutationDeferred"}'
+ );
+ const client: TrashDatabaseClient = {
+ mutation: () => ({
+ toPromise: async () => ({
+ data: { trashEntities: { results: [fromNewerServer] } },
+ }),
+ }),
+ };
+
+ expect(await trashDatabase(client, 'db')).toEqual(
+ err({ kind: 'unreachable' })
+ );
+ expect(cache.setQueryData).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/web/src/features/block-database/queries/trash-database.ts b/apps/web/src/features/block-database/queries/trash-database.ts
index 182327aaee..0c8f60c7f0 100644
--- a/apps/web/src/features/block-database/queries/trash-database.ts
+++ b/apps/web/src/features/block-database/queries/trash-database.ts
@@ -58,7 +58,7 @@ export function trashDatabase(
});
return ok(undefined);
})
- .exhaustive();
+ .exhaustive(() => err({ kind: 'unreachable' }));
};
return new ResultAsync(trashed());
}
diff --git a/apps/web/src/features/block-fig/components/publish-dialog.tsx b/apps/web/src/features/block-fig/components/publish-dialog.tsx
index bcd3c512cc..7a09a2256a 100644
--- a/apps/web/src/features/block-fig/components/publish-dialog.tsx
+++ b/apps/web/src/features/block-fig/components/publish-dialog.tsx
@@ -35,7 +35,7 @@ function ChangeBadge(props: { change: AssetChange['change'] }) {
.with('NEW', () => 'New')
.with('CHANGED', () => 'Changed')
.with('REMOVED', () => 'Removed')
- .exhaustive()}
+ .exhaustive(() => 'Changed')}
</span>
);
}
diff --git a/apps/web/src/features/block-form/components/respond/respond-screens.tsx b/apps/web/src/features/block-form/components/respond/respond-screens.tsx
index 763d30070f..b0cd742444 100644
--- a/apps/web/src/features/block-form/components/respond/respond-screens.tsx
+++ b/apps/web/src/features/block-form/components/respond/respond-screens.tsx
@@ -215,7 +215,7 @@ export function AnswerValue(props: {
{rows.value.length === 1 ? '1 row' : `${rows.value.length} rows`}
</span>
))
- .exhaustive();
+ .exhaustive(() => null);
};
return <>{shown()}</>;
}
diff --git a/apps/web/src/features/block-form/core/answers.ts b/apps/web/src/features/block-form/core/answers.ts
index 2ea6278cad..528b1331f9 100644
--- a/apps/web/src/features/block-form/core/answers.ts
+++ b/apps/web/src/features/block-form/core/answers.ts
@@ -58,7 +58,7 @@ export function answerProblem(
{ type: 'relation' },
() => false
)
- .exhaustive();
+ .exhaustive(() => false);
return match(value)
.with({ type: 'number' }, ({ value: number }) =>
Number.isFinite(number) ? undefined : 'Enter a number.'
@@ -97,7 +97,7 @@ export function answerProblem(
{ type: 'clear' },
() => undefined
)
- .exhaustive();
+ .exhaustive(() => 'Update Macro to answer this question.');
}
/** Every problem with a section's answers, in question order. */
diff --git a/apps/web/src/features/block-form/core/gate-evaluation.ts b/apps/web/src/features/block-form/core/gate-evaluation.ts
index 40c30b5048..f0316d8440 100644
--- a/apps/web/src/features/block-form/core/gate-evaluation.ts
+++ b/apps/web/src/features/block-form/core/gate-evaluation.ts
@@ -54,7 +54,7 @@ export function presentValue(
{ type: 'date' },
(scalar) => scalar
)
- .exhaustive();
+ .exhaustive(() => undefined);
}
function conditionPasses(
@@ -80,7 +80,7 @@ function conditionPasses(
{ type: 'rows' },
() => undefined
)
- .exhaustive();
+ .exhaustive(() => undefined);
if (!texts) return false;
const needle = expected.toLowerCase();
const haystacks = texts.map((text) => text.toLowerCase());
@@ -96,7 +96,7 @@ function conditionPasses(
haystacks.some((text) => text.startsWith(needle))
)
.with('endsWith', () => haystacks.some((text) => text.endsWith(needle)))
- .exhaustive();
+ .exhaustive(() => false);
})
.with({ kind: 'number' }, ({ operator, value: expected }) => {
if (value.type !== 'number') return false;
@@ -108,7 +108,7 @@ function conditionPasses(
.with('greaterThanOrEqual', () => actual >= expected)
.with('lessThan', () => actual < expected)
.with('lessThanOrEqual', () => actual <= expected)
- .exhaustive();
+ .exhaustive(() => false);
})
.with({ kind: 'date' }, ({ operator, value: expected }) => {
if (value.type !== 'date') return false;
@@ -120,7 +120,7 @@ function conditionPasses(
.with('after', () => actual > bound)
.with('onOrBefore', () => actual <= bound)
.with('onOrAfter', () => actual >= bound)
- .exhaustive();
+ .exhaustive(() => false);
})
.with(
{ kind: 'checkbox' },
@@ -148,11 +148,11 @@ function conditionPasses(
{ type: 'options' },
() => undefined
)
- .exhaustive();
+ .exhaustive(() => undefined);
if (!held) return false;
return setPasses(operator, held, entities);
})
- .exhaustive();
+ .exhaustive(() => false);
}
function setPasses(
@@ -165,5 +165,5 @@ function setPasses(
.with('isAnyOf', 'hasAny', () => expected.some(holds))
.with('isNoneOf', 'hasNone', () => !expected.some(holds))
.with('hasAll', () => expected.every(holds))
- .exhaustive();
+ .exhaustive(() => false);
}
diff --git a/apps/web/src/features/block-form/core/question-types.ts b/apps/web/src/features/block-form/core/question-types.ts
index 29af8d5897..b805914123 100644
--- a/apps/web/src/features/block-form/core/question-types.ts
+++ b/apps/web/src/features/block-form/core/question-types.ts
@@ -163,7 +163,7 @@ export function widgetsFor(kind: FormColumnKind): QuestionWidget[] {
{ type: 'relation' },
() => []
)
- .exhaustive();
+ .exhaustive(() => []);
}
/** The widget a question shows with: its own, or its kind's default. */
@@ -226,7 +226,7 @@ export function questionTypeOf(
)
.with({ type: 'entity' }, () => 'entity')
.with({ type: 'relation' }, () => 'relation')
- .exhaustive();
+ .exhaustive(() => 'short');
}
/** The chip label of a question's type. */
@@ -256,7 +256,7 @@ export function questionTypeLabel(
{ type: 'relation' },
() => 'Question'
)
- .exhaustive()
+ .exhaustive(() => 'Question')
);
}
@@ -297,7 +297,7 @@ export function sameColumnKind(
right.database === one.database &&
right.table === one.table
)
- .exhaustive();
+ .exhaustive(() => false);
}
/** Whether a kind's answers are picked from options the column owns. */
diff --git a/apps/web/src/features/block-form/form-condition-editor.tsx b/apps/web/src/features/block-form/form-condition-editor.tsx
index c4aae573ed..a9a74c4408 100644
--- a/apps/web/src/features/block-form/form-condition-editor.tsx
+++ b/apps/web/src/features/block-form/form-condition-editor.tsx
@@ -70,7 +70,11 @@ export function toViewColumn(column: FormColumn): DatabaseViewColumn {
isMultiSelect: true,
relation: { databaseId: database, tableId: table },
}))
- .exhaustive();
+ .exhaustive(() => ({
+ ...base,
+ dataType: 'STRING',
+ isMultiSelect: false,
+ }));
}
/** Mounted once per open editor; its props are read live, so its draft survives saves. */
diff --git a/apps/web/src/features/block-form/form-pickers.tsx b/apps/web/src/features/block-form/form-pickers.tsx
index 64c341be63..0f4338fb58 100644
--- a/apps/web/src/features/block-form/form-pickers.tsx
+++ b/apps/web/src/features/block-form/form-pickers.tsx
@@ -40,7 +40,7 @@ function entityNoun(target: FormEntityKind): string {
.with('THREAD', () => 'email')
.with('CALENDAR_EVENT', () => 'event')
.with('INITIATIVE', () => 'initiative')
- .exhaustive();
+ .exhaustive(() => 'item');
}
export function FormEntityPicker(props: EntityPickerProps) {
diff --git a/apps/web/src/features/block-form/queries/form-collaboration.ts b/apps/web/src/features/block-form/queries/form-collaboration.ts
index 3e3cbe6af8..f3ecb65c6b 100644
--- a/apps/web/src/features/block-form/queries/form-collaboration.ts
+++ b/apps/web/src/features/block-form/queries/form-collaboration.ts
@@ -289,7 +289,7 @@ function decodeSections(value: unknown): FormSection[] | undefined {
const { rules } = gate;
return isFilterGroup(rules) ? { ...gate, rules } : undefined;
})
- .exhaustive();
+ .exhaustive(() => undefined);
if (!decoded) return undefined;
sections.push(decoded);
}
diff --git a/apps/web/src/features/block-form/queries/form-detail.test.ts b/apps/web/src/features/block-form/queries/form-detail.test.ts
index e0a33ba569..1c8cfd0f50 100644
--- a/apps/web/src/features/block-form/queries/form-detail.test.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.test.ts
@@ -183,6 +183,40 @@ describe('the booking step', () => {
);
});
+ it('reads a step kind from a newer server as a plain section instead of throwing', () => {
+ const fromNewerServer = JSON.parse(
+ '{"kind":"payment","id":"pay","title":"Pay the fee","description":"Ten dollars."}'
+ );
+ const detail = toFormDetail({
+ form,
+ access: 'view',
+ tableGone: false,
+ sections: [fromNewerServer],
+ });
+ expect(detail.layout.sections).toEqual([
+ {
+ id: 'pay',
+ title: 'Pay the fee',
+ description: 'Ten dollars.',
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ bookingTarget: null,
+ questions: [],
+ },
+ ]);
+ });
+
+ it('does not report an outcome from a newer server as a submission', () => {
+ const fromNewerServer = JSON.parse('{"outcome":"queued","response":"r-1"}');
+
+ expect(toSubmitOutcome(fromNewerServer)).toEqual({
+ kind: 'stopped',
+ sectionId: '',
+ message: 'Update Macro to see whether your response was submitted.',
+ });
+ });
+
it('unlocks the booking step only from an accepted submission or a passing saved response', () => {
expect(
toSubmitOutcome({
diff --git a/apps/web/src/features/block-form/queries/form-detail.ts b/apps/web/src/features/block-form/queries/form-detail.ts
index 4a9f81ab8f..f476ba22d8 100644
--- a/apps/web/src/features/block-form/queries/form-detail.ts
+++ b/apps/web/src/features/block-form/queries/form-detail.ts
@@ -78,7 +78,16 @@ function toSection(section: FormSectionDetail): FormSection {
bookingTarget: booking.target ? toBookingTarget(booking.target) : null,
questions: [],
}))
- .exhaustive();
+ .exhaustive(() => ({
+ id: section.id,
+ title: section.title,
+ description: section.description,
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ bookingTarget: null,
+ questions: [],
+ }));
}
function toBookingTarget(target: FormBookingTarget): FormBookingTarget {
@@ -174,7 +183,16 @@ export function toFormLayout(layout: WireFormLayout): FormLayout {
bookingTarget: toBookingTarget(booking.target),
questions: [],
}))
- .exhaustive()
+ .exhaustive(() => ({
+ id: section.id,
+ title: section.title,
+ description: section.description,
+ kind: 'questions',
+ gateRules: null,
+ gateMessage: '',
+ bookingTarget: null,
+ questions: [],
+ }))
),
};
}
@@ -213,7 +231,9 @@ export function toLayoutDocument(layout: FormLayout): WireFormLayout {
widget: question.widget,
})),
}))
- .exhaustive()
+ .exhaustive(() => {
+ throw new Error(`Section “${section.id}” has an unknown kind`);
+ })
),
};
}
@@ -243,7 +263,11 @@ export function toSubmitOutcome(outcome: SubmissionOutcome): SubmitOutcome {
sectionId: section,
message,
}))
- .exhaustive();
+ .exhaustive(() => ({
+ kind: 'stopped',
+ sectionId: '',
+ message: 'Update Macro to see whether your response was submitted.',
+ }));
}
export function toMyResponse(mine: WireMyResponse): MyResponse {
diff --git a/apps/web/src/features/block-form/queries/form-layout-collaboration.ts b/apps/web/src/features/block-form/queries/form-layout-collaboration.ts
index 81342e7adc..cfca717a50 100644
--- a/apps/web/src/features/block-form/queries/form-layout-collaboration.ts
+++ b/apps/web/src/features/block-form/queries/form-layout-collaboration.ts
@@ -66,7 +66,7 @@ export function flushFailureOf(error: unknown): FormWriteFailure {
.with({ kind: 'publish-failed' }, () => ({
message: 'The form couldn’t be published. Try again.',
}))
- .exhaustive();
+ .exhaustive(() => ({ message: 'The form couldn’t be saved.' }));
}
/** The form's shared layout for an editor; call under the editor's owner. */
@@ -109,7 +109,7 @@ export function createFormLayoutCollaboration(
.with({ kind: 'unsaved', reason: 'undelivered' }, () => 'unsaved')
.with({ kind: 'saving' }, () => 'saving')
.with({ kind: 'saved' }, () => 'saved')
- .exhaustive(),
+ .exhaustive(() => 'unsaved'),
connection: session.connection,
apply: (previous, next) =>
session.apply(toLayoutDocument(previous), toLayoutDocument(next)),
diff --git a/apps/web/src/features/block-form/queries/form-publication.test.ts b/apps/web/src/features/block-form/queries/form-publication.test.ts
index 64c55fc6fe..09be3f9dee 100644
--- a/apps/web/src/features/block-form/queries/form-publication.test.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.test.ts
@@ -78,4 +78,21 @@ describe('publicationMessage', () => {
);
expect(publicationMessage({ detail })).toBeUndefined();
});
+
+ it('gives generic copy for problems from a newer server instead of throwing', () => {
+ expect(
+ publicationMessage({
+ detail,
+ publicationError: JSON.parse('{"kind":"quotaExceeded"}'),
+ })
+ ).toBe('Your draft is saved, but it couldn’t be published yet.');
+ expect(
+ publicationMessage({
+ detail,
+ publicationError: JSON.parse(
+ '{"kind":"layout","problem":{"kind":"tooManySections"}}'
+ ),
+ })
+ ).toBe('Your draft is saved, but it couldn’t be published yet.');
+ });
});
diff --git a/apps/web/src/features/block-form/queries/form-publication.ts b/apps/web/src/features/block-form/queries/form-publication.ts
index 04af88e84d..801dd662b9 100644
--- a/apps/web/src/features/block-form/queries/form-publication.ts
+++ b/apps/web/src/features/block-form/queries/form-publication.ts
@@ -75,7 +75,9 @@ export function publicationMessage(
{ kind: 'textTooLong' },
({ max }) => `Shorten the text to ${max} characters or fewer.`
)
- .exhaustive()
+ .exhaustive(
+ () => 'Your draft is saved, but it couldn’t be published yet.'
+ )
)
- .exhaustive();
+ .exhaustive(() => 'Your draft is saved, but it couldn’t be published yet.');
}
diff --git a/apps/web/src/features/block-form/queries/form-sources.test.ts b/apps/web/src/features/block-form/queries/form-sources.test.ts
index e469f54418..d7cdb21329 100644
--- a/apps/web/src/features/block-form/queries/form-sources.test.ts
+++ b/apps/web/src/features/block-form/queries/form-sources.test.ts
@@ -2,7 +2,7 @@ import { ThrownResultError } from '@core/util/result';
import type { FormsError } from '@service-storage/forms';
import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createFormDetailSource } from './form-sources';
+import { createFormDetailSource, createTallySource } from './form-sources';
const sync = vi.hoisted(() => ({
formFollowed: [] as (() => string | undefined)[],
@@ -13,6 +13,7 @@ const sync = vi.hoisted(() => ({
formReads: 0,
databaseName: (): string => 'Offsite',
queryError: (): unknown => undefined,
+ tallyBuckets: [] as unknown[],
}));
vi.mock('@queries/storage/forms', () => ({
useFormDetailQuery: () => ({
@@ -51,6 +52,15 @@ vi.mock('@queries/storage/forms', () => ({
return { isError: false };
},
}),
+ useTallyQuery: () => ({
+ isSuccess: true,
+ isError: false,
+ data: {
+ questions: [
+ { question: 'question-1', responses: 2, buckets: sync.tallyBuckets },
+ ],
+ },
+ }),
}));
vi.mock('@queries/storage/databases', () => ({
useDatabaseDetailQuery: (databaseId: () => string | undefined) => {
@@ -209,3 +219,23 @@ describe('createFormDetailSource', () => {
expect(sync.databasesRead).toEqual(['database-1', undefined]);
});
});
+
+describe('createTallySource', () => {
+ it('skips a bucket kind from a newer service', () => {
+ sync.tallyBuckets = [
+ { value: { kind: 'option', option: 'option-1' }, count: 1 },
+ { value: JSON.parse('{"kind":"rating","stars":5}'), count: 1 },
+ ];
+ const source = createTallySource(
+ () => 'form-1',
+ () => true
+ );
+ expect(source.value()).toEqual([
+ {
+ questionId: 'question-1',
+ responses: 2,
+ buckets: [{ kind: 'option', optionId: 'option-1', count: 1 }],
+ },
+ ]);
+ });
+});
diff --git a/apps/web/src/features/block-form/queries/form-sources.ts b/apps/web/src/features/block-form/queries/form-sources.ts
index 9cfc454229..3f363aa8a1 100644
--- a/apps/web/src/features/block-form/queries/form-sources.ts
+++ b/apps/web/src/features/block-form/queries/form-sources.ts
@@ -101,7 +101,7 @@ function refusalOf(code: FormErrorCode): FormRefusal {
.with('tallyHidden', () => 'tally-hidden')
.with('conflict', () => 'conflict')
.with('internal', () => 'internal')
- .exhaustive();
+ .exhaustive(() => 'internal');
}
/** A refused write in the words the UI shows, naming the question it refused. */
@@ -277,20 +277,16 @@ export function createTallySource(
? query.data.questions.map((question) => ({
questionId: question.question,
responses: question.responses,
- buckets: question.buckets.map((bucket) =>
+ buckets: question.buckets.flatMap((bucket) =>
match(bucket.value)
- .returnType<QuestionTally['buckets'][number]>()
- .with({ kind: 'option' }, ({ option }) => ({
- kind: 'option',
- optionId: option,
- count: bucket.count,
- }))
- .with({ kind: 'checkbox' }, ({ checked }) => ({
- kind: 'checkbox',
- checked,
- count: bucket.count,
- }))
- .exhaustive()
+ .returnType<QuestionTally['buckets']>()
+ .with({ kind: 'option' }, ({ option }) => [
+ { kind: 'option', optionId: option, count: bucket.count },
+ ])
+ .with({ kind: 'checkbox' }, ({ checked }) => [
+ { kind: 'checkbox', checked, count: bucket.count },
+ ])
+ .exhaustive(() => [])
),
}))
: undefined,
diff --git a/apps/web/src/features/block-form/queries/table-columns.ts b/apps/web/src/features/block-form/queries/table-columns.ts
index 0a0a91bd5e..40b947e079 100644
--- a/apps/web/src/features/block-form/queries/table-columns.ts
+++ b/apps/web/src/features/block-form/queries/table-columns.ts
@@ -51,7 +51,7 @@ export function columnKindOf(column: ColumnDetail): FormColumnKind | undefined {
const target = entityKind(definition.specific_entity_type);
return target ? { type: 'entity', target, multi } : undefined;
})
- .exhaustive();
+ .exhaustive(() => undefined);
}
export function toFormColumn(column: ColumnDetail): FormColumn | undefined {
diff --git a/apps/web/src/features/block-md/queries/markdown-document.ts b/apps/web/src/features/block-md/queries/markdown-document.ts
index f8ddbe64cd..3e840c4efb 100644
--- a/apps/web/src/features/block-md/queries/markdown-document.ts
+++ b/apps/web/src/features/block-md/queries/markdown-document.ts
@@ -43,7 +43,11 @@ export async function loadMarkdownDocument(
canEdit: false,
isOwner: false,
}))
- .exhaustive();
+ .exhaustive(() => ({
+ canComment: false,
+ canEdit: false,
+ isOwner: false,
+ }));
return {
...createSyncServiceSource(documentId, token, authorization),
diff --git a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
index ea2f4e763c..673e8c4ca0 100644
--- a/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
+++ b/apps/web/src/features/block-spreadsheet/workers/calculation.worker.ts
@@ -184,7 +184,14 @@ self.onmessage = async (event: MessageEvent<CalculationRequest>) => {
message: 'Calculate the sheet before using Goal Seek.',
}),
}))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('calculation worker: unknown request', unknown);
+ return {
+ id: request.id,
+ type: 'error',
+ message: 'Unknown calculation request.',
+ };
+ });
} catch (error) {
response = {
id: request.id,
diff --git a/apps/web/src/features/channel/Call/native-call-lifecycle.ts b/apps/web/src/features/channel/Call/native-call-lifecycle.ts
index 10db328c21..cf27aa1c99 100644
--- a/apps/web/src/features/channel/Call/native-call-lifecycle.ts
+++ b/apps/web/src/features/channel/Call/native-call-lifecycle.ts
@@ -29,7 +29,9 @@ export function bindNativeCallLifecycle(
if (nativeSessionObserved) lifecycle.syncSession(undefined);
}
)
- .exhaustive();
+ .exhaustive((unknown) =>
+ console.warn('[callkit] unknown native call snapshot', unknown)
+ );
};
const unsubscribeState = lifecycle.subscribe((state) => {
if (state.t === 'joining') nativeSessionObserved = false;
diff --git a/apps/web/src/features/channel/use-message-participants.ts b/apps/web/src/features/channel/use-message-participants.ts
index 1bd16bf368..7a7f960ebd 100644
--- a/apps/web/src/features/channel/use-message-participants.ts
+++ b/apps/web/src/features/channel/use-message-participants.ts
@@ -41,6 +41,6 @@ export function useMessageParticipants(
.with('channel', () => channelParticipants.users())
.with(P.union('document', 'initiative', 'call'), () => contacts())
.with(P.union('crm_company', 'crm_contact'), () => teamMembers())
- .exhaustive()
+ .exhaustive(() => [])
);
}
diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.ts b/apps/web/src/features/channels-view/queries/channel-search-source.ts
index 1a7c091161..5e20569d2d 100644
--- a/apps/web/src/features/channels-view/queries/channel-search-source.ts
+++ b/apps/web/src/features/channels-view/queries/channel-search-source.ts
@@ -48,7 +48,7 @@ export function createChannelSearchSource(options: {
.with('direct_messages', () => ['direct_message'])
.with('channels', () => ['public', 'private', 'team'])
.with('recents', 'search', 'threads', () => undefined)
- .exhaustive(),
+ .exhaustive(() => undefined),
},
},
},
diff --git a/apps/web/src/features/crm/queries/pipeline-data.test.tsx b/apps/web/src/features/crm/queries/pipeline-data.test.tsx
index b965e0b5d3..942f92337a 100644
--- a/apps/web/src/features/crm/queries/pipeline-data.test.tsx
+++ b/apps/web/src/features/crm/queries/pipeline-data.test.tsx
@@ -244,6 +244,11 @@ it('maps single and multiple entity values without leaking transport objects int
expect(pipelineCell(undefined, column)).toBeNull();
});
+it('shows a value type from a newer server as an empty cell', () => {
+ const fromNewerServer = JSON.parse('{"type":"Rating","value":4}');
+ expect(pipelineCell(fromNewerServer, table.columns[0])).toBeNull();
+});
+
it('forwards the complete query and retained row request to the pipeline endpoint', async () => {
const host = setup();
const query = {
diff --git a/apps/web/src/features/crm/queries/pipeline-data.ts b/apps/web/src/features/crm/queries/pipeline-data.ts
index 0fcc9597a6..c6dbda37f7 100644
--- a/apps/web/src/features/crm/queries/pipeline-data.ts
+++ b/apps/web/src/features/crm/queries/pipeline-data.ts
@@ -41,7 +41,7 @@ export function pipelineCell(
})
)
)
- .exhaustive();
+ .exhaustive(() => null);
}
/** Transport adapter only; the shared provider owns queries and editing. */
diff --git a/apps/web/src/features/crm/queries/pipeline-entries.test.ts b/apps/web/src/features/crm/queries/pipeline-entries.test.ts
index 5d5e3335ef..54fba1cd03 100644
--- a/apps/web/src/features/crm/queries/pipeline-entries.test.ts
+++ b/apps/web/src/features/crm/queries/pipeline-entries.test.ts
@@ -136,6 +136,38 @@ it('reads stored values the way the pipeline table does', () => {
]);
});
+it('reads value kinds from a newer server as empty instead of throwing', () => {
+ const fromNewerServer = JSON.parse(
+ '{"__typename":"GraphqlColorPropertyValue","hex":"#ff0000"}'
+ );
+ const optionFromNewerServer = JSON.parse(
+ '{"__typename":"GraphqlColorPropertyOptionValue","hex":"#ff0000"}'
+ );
+ const mapped = toPipelineEntry(
+ entry([
+ {
+ __typename: 'GraphqlCrmPipelineCell',
+ column: column({
+ id: 'shade',
+ options: [
+ {
+ __typename: 'GraphqlPropertyOption',
+ id: 'red',
+ color: null,
+ value: optionFromNewerServer,
+ },
+ ],
+ }),
+ value: fromNewerServer,
+ },
+ ])
+ );
+ expect(mapped.cells[0].value).toBeNull();
+ expect(mapped.cells[0].column.options).toEqual([
+ { id: 'red', label: '', color: null },
+ ]);
+});
+
it('reads one company or one contact through soup', () => {
const company = pipelineEntriesInput({ type: 'company', id: 'acme' });
expect(company?.initial?.filters?.crmCompanyFilter).toEqual({
diff --git a/apps/web/src/features/crm/queries/pipeline-entries.ts b/apps/web/src/features/crm/queries/pipeline-entries.ts
index db22218494..5d48c7a223 100644
--- a/apps/web/src/features/crm/queries/pipeline-entries.ts
+++ b/apps/web/src/features/crm/queries/pipeline-entries.ts
@@ -37,7 +37,7 @@ function optionLabel(option: GraphqlCell['column']['options'][number]): string {
.with({ __typename: 'GraphqlNumberPropertyOptionValue' }, (value) =>
String(value.numberValue)
)
- .exhaustive();
+ .exhaustive(() => '');
}
function entryColumn(column: GraphqlCell['column']): DatabaseViewColumn {
@@ -92,7 +92,7 @@ export function entryCellValue(cell: GraphqlCell): DatabaseCellValue {
})
)
)
- .exhaustive();
+ .exhaustive(() => null);
}
export function toPipelineEntry(
diff --git a/apps/web/src/features/crm/queries/record-items.ts b/apps/web/src/features/crm/queries/record-items.ts
index 5566ae9fe2..22b2d49870 100644
--- a/apps/web/src/features/crm/queries/record-items.ts
+++ b/apps/web/src/features/crm/queries/record-items.ts
@@ -36,7 +36,7 @@ export function crmAssociation(scope: CrmRecordScope) {
return match(scope)
.with({ type: 'company' }, ({ id }) => ({ company: id }))
.with({ type: 'contact' }, ({ id }) => ({ contact: id }))
- .exhaustive();
+ .exhaustive(() => ({ company: NIL_UUID }));
}
/** Email addresses or domains of the people at the record. */
@@ -48,7 +48,7 @@ const participants = (scope: CrmRecordScope): AstNode[] =>
.with({ type: 'contact' }, ({ email }) => [
leaf({ eap: { Complete: email } }),
])
- .exhaustive();
+ .exhaustive(() => []);
/**
* Non-task documents associated with the record, plus attachments of emails
diff --git a/apps/web/src/features/database-query/core/answer-cell.ts b/apps/web/src/features/database-query/core/answer-cell.ts
index c1dfc339f1..34667531e5 100644
--- a/apps/web/src/features/database-query/core/answer-cell.ts
+++ b/apps/web/src/features/database-query/core/answer-cell.ts
@@ -189,6 +189,6 @@ function referenceCount(type: DatabaseEntityType, count: number): string {
.with('CALL_RECORD', () => ['call', 'calls'])
.with('CALENDAR_EVENT', () => ['event', 'events'])
.with('DATABASE_ROW', () => ['linked record', 'linked records'])
- .exhaustive();
+ .exhaustive(() => ['item', 'items']);
return `${count} ${count === 1 ? one : many}`;
}
diff --git a/apps/web/src/features/database-query/queries/app-query-source.ts b/apps/web/src/features/database-query/queries/app-query-source.ts
index 529a27014a..e5270d1438 100644
--- a/apps/web/src/features/database-query/queries/app-query-source.ts
+++ b/apps/web/src/features/database-query/queries/app-query-source.ts
@@ -70,7 +70,7 @@ function generateDatabaseQuery(
return serviceError(errors).message;
})
.with({ kind: 'interrupted' }, ({ reason }) => reason)
- .exhaustive()
+ .exhaustive(() => 'The query couldn’t be generated.')
)
)
)
diff --git a/apps/web/src/features/database/components/database-mention-label.tsx b/apps/web/src/features/database/components/database-mention-label.tsx
index 626d773065..a36a6bd04f 100644
--- a/apps/web/src/features/database/components/database-mention-label.tsx
+++ b/apps/web/src/features/database/components/database-mention-label.tsx
@@ -17,7 +17,7 @@ function mentionTypeLabel(type: DatabaseEntityType): string {
.with('CALL_RECORD', () => 'Call')
.with('CALENDAR_EVENT', () => 'Event')
.with('DATABASE_ROW', () => 'Row')
- .exhaustive();
+ .exhaustive(() => 'Item');
}
export function DatabaseMentionLabel(props: {
diff --git a/apps/web/src/features/database/core/board-input.ts b/apps/web/src/features/database/core/board-input.ts
index 38cce54487..31ddf07eab 100644
--- a/apps/web/src/features/database/core/board-input.ts
+++ b/apps/web/src/features/database/core/board-input.ts
@@ -36,7 +36,7 @@ function kind(column: DatabaseViewColumn): ColumnKind {
}
: { kind: 'text' }
)
- .exhaustive();
+ .exhaustive(() => ({ kind: 'text' }));
}
function cell(column: DatabaseViewColumn, row: DatabaseRow): Cell | null {
diff --git a/apps/web/src/features/database/core/cell-ops.ts b/apps/web/src/features/database/core/cell-ops.ts
index 911e78b861..5ed0a19a36 100644
--- a/apps/web/src/features/database/core/cell-ops.ts
+++ b/apps/web/src/features/database/core/cell-ops.ts
@@ -124,7 +124,7 @@ export function cellValue(
value: [{ entityType, entityId: String(value) }],
}))
)
- .exhaustive();
+ .exhaustive(() => err({ kind: 'read-only-column' }));
}
/**
diff --git a/apps/web/src/features/database/core/formula.ts b/apps/web/src/features/database/core/formula.ts
index c73988dc20..758c250b9d 100644
--- a/apps/web/src/features/database/core/formula.ts
+++ b/apps/web/src/features/database/core/formula.ts
@@ -95,7 +95,7 @@ function engineKind(column: DatabaseViewColumn): ColumnKind {
multi: column.isMultiSelect,
target: column.specificEntityType ?? 'USER',
}))
- .exhaustive();
+ .exhaustive(() => ({ kind: 'text' }));
}
/** Columns the name being typed at the caret could mean, and where it starts. */
diff --git a/apps/web/src/features/database/core/view-query.ts b/apps/web/src/features/database/core/view-query.ts
index 5ffa95ba3c..be59ed94b6 100644
--- a/apps/web/src/features/database/core/view-query.ts
+++ b/apps/web/src/features/database/core/view-query.ts
@@ -53,7 +53,7 @@ function columnValueKind(column: DatabaseViewColumn): ValueKind {
.with('BOOLEAN', () => 'checkbox')
.with('SELECT_STRING', 'SELECT_NUMBER', 'TAG', () => 'options')
.with('ENTITY', () => 'entities')
- .exhaustive();
+ .exhaustive(() => 'text');
}
function operatorId(test: FilterOperator | FilterTest): string {
diff --git a/apps/web/src/features/email-view/queries/email-query.ts b/apps/web/src/features/email-view/queries/email-query.ts
index 0bb6efe723..6103cebfb6 100644
--- a/apps/web/src/features/email-view/queries/email-query.ts
+++ b/apps/web/src/features/email-view/queries/email-query.ts
@@ -45,7 +45,7 @@ export const emailViewForTab = (tab: EmailTab): string =>
'archived',
() => 'all'
)
- .exhaustive();
+ .exhaustive(() => 'all');
const anyThread = (): TargetExpr => clause.not(clause.eq('threadId', NIL_UUID));
@@ -101,7 +101,7 @@ function tabClause(context: EmailQueryContext): TargetExpr {
'reminders',
anyThread
)
- .exhaustive()
+ .exhaustive(anyThread)
);
}
diff --git a/apps/web/src/features/email-view/queries/email-search.ts b/apps/web/src/features/email-view/queries/email-search.ts
index f3efa563e4..c81fafef2f 100644
--- a/apps/web/src/features/email-view/queries/email-search.ts
+++ b/apps/web/src/features/email-view/queries/email-search.ts
@@ -47,7 +47,7 @@ function tabFilters(tab: EmailTab): EmailFilters {
'all',
() => ({})
)
- .exhaustive();
+ .exhaustive(() => ({}));
}
const soleSelection = (selection: string[] | undefined) =>
diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.ts
index 2825811073..b5e15c50e3 100644
--- a/apps/web/src/features/email-view/queries/use-email-query.ts
+++ b/apps/web/src/features/email-view/queries/use-email-query.ts
@@ -85,7 +85,7 @@ function emailMatchesTab(
'all',
() => true
)
- .exhaustive()
+ .exhaustive(() => true)
);
}
diff --git a/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts b/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts
index 9f24dd107d..de0369759a 100644
--- a/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts
+++ b/apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts
@@ -129,7 +129,7 @@ export function getActionVerb(type: NotificationType): string {
.with('agent_session_settled', () => 'finished')
.with('agent_session_waiting_for_input', () => 'needs your answer')
.with('agent_session_mentioned', () => 'mentioned you')
- .exhaustive()
+ .exhaustive(() => 'updated')
);
}
@@ -192,7 +192,7 @@ export function getTypeNoun(type: NotificationType, count: number): string {
.with('agent_session_mentioned', () =>
count === 1 ? 'mention' : 'mentions'
)
- .exhaustive();
+ .exhaustive(() => (count === 1 ? 'notification' : 'notifications'));
}
export function getTypePreposition(type: NotificationType): string {
diff --git a/apps/web/src/features/entity/extractors-notification/notification-icon.tsx b/apps/web/src/features/entity/extractors-notification/notification-icon.tsx
index b2afa62301..44e8d6c5a7 100644
--- a/apps/web/src/features/entity/extractors-notification/notification-icon.tsx
+++ b/apps/web/src/features/entity/extractors-notification/notification-icon.tsx
@@ -75,7 +75,7 @@ function getNotificationIcon(
.with('agent_session_settled', () => AgentIcon)
.with('agent_session_waiting_for_input', () => QuestionIcon)
.with('agent_session_mentioned', () => AtIcon)
- .exhaustive();
+ .exhaustive(() => BellIcon);
}
/**
diff --git a/apps/web/src/features/entity/extractors/entity-title.tsx b/apps/web/src/features/entity/extractors/entity-title.tsx
index 5ae7387153..f77d5586cd 100644
--- a/apps/web/src/features/entity/extractors/entity-title.tsx
+++ b/apps/web/src/features/entity/extractors/entity-title.tsx
@@ -50,7 +50,7 @@ function extractRawTitle(entity: EntityData): JSX.Element {
{ type: 'form' },
(entity) => entity.name || blockNameToDefaultFile('form')
)
- .exhaustive();
+ .exhaustive(() => 'Untitled');
}
function extractSearchHighlight(entity: EntityData): string | undefined {
diff --git a/apps/web/src/features/entity/utils/notification.ts b/apps/web/src/features/entity/utils/notification.ts
index aa76229bda..127b410d7d 100644
--- a/apps/web/src/features/entity/utils/notification.ts
+++ b/apps/web/src/features/entity/utils/notification.ts
@@ -274,7 +274,7 @@ export function getNotificationActionText(n: Notification): string {
.with('agent_session_settled', () => 'finished')
.with('agent_session_waiting_for_input', () => 'asked')
.with('agent_session_mentioned', () => 'mentioned')
- .exhaustive();
+ .exhaustive(() => 'notified');
}
export function extractMessageContent(notification: Notification): string {
@@ -353,7 +353,7 @@ export function extractMessageContent(notification: Notification): string {
)
.with({ tag: 'agent_session_waiting_for_input' }, (m) => m.content.question)
.with({ tag: 'agent_session_mentioned' }, (m) => m.content.sessionName)
- .exhaustive();
+ .exhaustive(() => '');
}
/**
diff --git a/apps/web/src/features/entity/utils/shared.ts b/apps/web/src/features/entity/utils/shared.ts
index 45ded0fec9..794a8ba56e 100644
--- a/apps/web/src/features/entity/utils/shared.ts
+++ b/apps/web/src/features/entity/utils/shared.ts
@@ -34,7 +34,7 @@ export function isSharedWithViewer(
})
.with({ type: 'foreign' }, (row) => row.storedForId !== viewerId)
.with({ type: P.union(...UNSHARED_ROW) }, () => false)
- .exhaustive();
+ .exhaustive(() => false);
}
export function useIsShared(entity: EntityData) {
diff --git a/apps/web/src/features/gtm-invite/InviteWelcome.tsx b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
index a03117f00b..178a3afdf4 100644
--- a/apps/web/src/features/gtm-invite/InviteWelcome.tsx
+++ b/apps/web/src/features/gtm-invite/InviteWelcome.tsx
@@ -75,7 +75,7 @@ export function InviteWelcome() {
.with('expired', () => ({ kind: 'expired' }))
.with('revoked', () => ({ kind: 'revoked' }))
.with('redeemed', 'converted', () => ({ kind: 'used' }))
- .exhaustive();
+ .exhaustive(() => ({ kind: 'invalid' }));
});
const welcomeDetails = () => {
const current = view();
diff --git a/apps/web/src/features/gtm-invite/core/invite-link.ts b/apps/web/src/features/gtm-invite/core/invite-link.ts
index ab44c9e7b2..c8ec568eb2 100644
--- a/apps/web/src/features/gtm-invite/core/invite-link.ts
+++ b/apps/web/src/features/gtm-invite/core/invite-link.ts
@@ -96,7 +96,7 @@ export function describeInviteStatus(
label: 'Subscribed',
tone: 'success' as const,
}))
- .exhaustive();
+ .exhaustive(() => ({ label: 'Unknown', tone: 'muted' as const }));
}
const MINUTE_MS = 60_000;
diff --git a/apps/web/src/features/home/queries/home-item-filter.ts b/apps/web/src/features/home/queries/home-item-filter.ts
index fee6efd283..f2d5e2625a 100644
--- a/apps/web/src/features/home/queries/home-item-filter.ts
+++ b/apps/web/src/features/home/queries/home-item-filter.ts
@@ -27,5 +27,5 @@ export function soupItemMatchesHomeTab(
'noise',
() => item.tag === 'emailThread' && item.data.isSignal === false
)
- .exhaustive();
+ .exhaustive(() => false);
}
diff --git a/apps/web/src/features/home/queries/home-query.ts b/apps/web/src/features/home/queries/home-query.ts
index e1a7f6cdb9..815b2dcff9 100644
--- a/apps/web/src/features/home/queries/home-query.ts
+++ b/apps/web/src/features/home/queries/home-query.ts
@@ -107,7 +107,7 @@ function tabClause(
return match(tab)
.with('signal', () => signalClause(capabilities, now, userId))
.with('noise', noiseClause)
- .exhaustive();
+ .exhaustive(() => signalClause(capabilities, now, userId));
}
export type HomeViewContext = {
diff --git a/apps/web/src/features/home/queries/use-home-query.ts b/apps/web/src/features/home/queries/use-home-query.ts
index b8e704d2a2..adaec6a723 100644
--- a/apps/web/src/features/home/queries/use-home-query.ts
+++ b/apps/web/src/features/home/queries/use-home-query.ts
@@ -122,7 +122,7 @@ function matchesTab(
);
})
.with('noise', () => noiseFilter(entity) && notDone())
- .exhaustive();
+ .exhaustive(() => false);
}
// Cached query meta outlives the view; build the gate at module scope over the
diff --git a/apps/web/src/features/home/work-feed/queries/decode.test.ts b/apps/web/src/features/home/work-feed/queries/decode.test.ts
index e53b1f5f78..3d6334884c 100644
--- a/apps/web/src/features/home/work-feed/queries/decode.test.ts
+++ b/apps/web/src/features/home/work-feed/queries/decode.test.ts
@@ -63,6 +63,18 @@ describe('decodeWorkFeedEntry', () => {
);
expect(decoded?.entity.touchedAt).toBe('2026-02-01T10:30:00Z');
});
+
+ it('decodes an item state from a newer server as seen', () => {
+ const entry = documentEntry({
+ docId: 'doc-1',
+ sortAt: '2026-02-01T10:09:00Z',
+ });
+ const decoded = decodeWorkFeedEntry({
+ ...entry,
+ item: { ...entry.item, state: JSON.parse('"SNOOZED"') },
+ });
+ expect(decoded?.state).toBe('seen');
+ });
});
describe('encodeWorkFeedScope', () => {
diff --git a/apps/web/src/features/home/work-feed/queries/decode.ts b/apps/web/src/features/home/work-feed/queries/decode.ts
index cdaf574018..37c5441009 100644
--- a/apps/web/src/features/home/work-feed/queries/decode.ts
+++ b/apps/web/src/features/home/work-feed/queries/decode.ts
@@ -27,7 +27,7 @@ const decodeState = (state: GraphqlWorkFeedItemState): WorkFeedItemState =>
.with('UNSEEN', () => 'unseen' as const)
.with('SEEN', () => 'seen' as const)
.with('DONE', () => 'done' as const)
- .exhaustive();
+ .exhaustive(() => 'seen' as const);
const toTimestamp = (value: string | null | undefined) =>
value ? new Date(value).getTime() : undefined;
@@ -111,7 +111,9 @@ const toGraphqlItemType = (type: WorkFeedItemType): GraphqlWorkFeedItemType =>
.with('calendar_event', () => 'CALENDAR_EVENT' as const)
.with('pull_request', () => 'PULL_REQUEST' as const)
.with('agent_session', () => 'AGENT_SESSION' as const)
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error(`Unknown work feed item type: ${type}`);
+ });
/** Encode a feed scope for the wire. */
export function encodeWorkFeedScope(scope: WorkFeedScope): WorkFeedScopeInput {
diff --git a/apps/web/src/features/next-soup/filters/query-filters.ts b/apps/web/src/features/next-soup/filters/query-filters.ts
index de38a2438e..26cedc156c 100644
--- a/apps/web/src/features/next-soup/filters/query-filters.ts
+++ b/apps/web/src/features/next-soup/filters/query-filters.ts
@@ -198,7 +198,7 @@ export function filterSoupItemByRequestBody(
// These partitions are opt-in through the filter AST only.
return false;
})
- .exhaustive();
+ .exhaustive(() => false);
}
/**
diff --git a/apps/web/src/features/notifications/notification-metadata.ts b/apps/web/src/features/notifications/notification-metadata.ts
index 89f6d48bbf..ddd4106eaa 100644
--- a/apps/web/src/features/notifications/notification-metadata.ts
+++ b/apps/web/src/features/notifications/notification-metadata.ts
@@ -84,7 +84,7 @@ export function getNotificationAction(n: UnifiedNotification): string {
.with('agent_session_settled', () => 'finished')
.with('agent_session_waiting_for_input', () => 'needs your answer in')
.with('agent_session_mentioned', () => 'mentioned you in')
- .exhaustive()
+ .exhaustive(() => 'notified you about')
);
}
@@ -142,7 +142,7 @@ export function getNotificationTargetName(
},
(m) => m.content.sessionName
)
- .exhaustive()
+ .exhaustive(() => undefined)
);
}
@@ -215,7 +215,7 @@ export function getNotificationContent(
(m) => m.content.question
)
.with({ tag: 'agent_session_mentioned' }, () => undefined)
- .exhaustive()
+ .exhaustive(() => undefined)
);
}
@@ -289,6 +289,6 @@ export function shouldShowNotificationTarget(n: UnifiedNotification): boolean {
},
() => true
)
- .exhaustive()
+ .exhaustive(() => true)
);
}
diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.ts
index 1ea5feac31..dfa9eb4854 100644
--- a/apps/web/src/features/notifications/notification-navigation.ts
+++ b/apps/web/src/features/notifications/notification-navigation.ts
@@ -576,7 +576,7 @@ function getSupportedHandler(
};
})
.with('inbox_reauth_required', () => null)
- .exhaustive()
+ .exhaustive(() => null)
);
}
diff --git a/apps/web/src/features/notifications/notification-resolvers.ts b/apps/web/src/features/notifications/notification-resolvers.ts
index e6bd6df610..b4eaf2a05a 100644
--- a/apps/web/src/features/notifications/notification-resolvers.ts
+++ b/apps/web/src/features/notifications/notification-resolvers.ts
@@ -29,7 +29,7 @@ export const DefaultUserNameResolver: UserNameResolver = async (id: string) => {
return macroId ? macroIdToEmail(macroId) : id || undefined;
};
-const getPreview = async (id: string, type: EntityType) => {
+const getPreview = async (id: string, type: string) => {
const itemType = stringToItemType(type);
if (!itemType) return undefined;
return await raceTimeout(
@@ -42,7 +42,7 @@ export const DefaultDocumentNameResolver: DocumentNameResolver = async (
id: string,
type: string
) => {
- const preview = await getPreview(id, type as EntityType);
+ const preview = await getPreview(id, type);
if (!preview || !isAccessiblePreviewItem(preview)) return undefined;
return preview.name;
};
diff --git a/apps/web/src/features/notifications/notification-state.ts b/apps/web/src/features/notifications/notification-state.ts
index 3934a55a2f..902e04f1dd 100644
--- a/apps/web/src/features/notifications/notification-state.ts
+++ b/apps/web/src/features/notifications/notification-state.ts
@@ -23,7 +23,7 @@ export function notificationStateFromGraphql(
.with('UNSEEN', () => 'unseen' as const)
.with('SEEN', () => 'seen' as const)
.with('DONE', () => 'done' as const)
- .exhaustive();
+ .exhaustive(() => 'seen' as const);
}
/** Compile persisted UI filter intent into exact backend lifecycle states. */
diff --git a/apps/web/src/features/notifications/types.ts b/apps/web/src/features/notifications/types.ts
index e77de0a0ca..91d9d7ea87 100644
--- a/apps/web/src/features/notifications/types.ts
+++ b/apps/web/src/features/notifications/types.ts
@@ -1,5 +1,8 @@
import type { Entity, EntityType } from '@core/types';
-import type { ApiUserNotification } from '@service-notification/generated/schemas';
+import type {
+ ApiUserNotification,
+ EntityType as NotificationEntityType,
+} from '@service-notification/generated/schemas';
import { listTypedNotificationsResponse } from '@service-notification/generated/zod';
export type UnifiedNotification = Omit<ApiUserNotification, 'owner_id'>;
@@ -11,15 +14,22 @@ export const unifiedNotificationSchema = _entitySchema.and(
_allOfSchema.omit({ owner_id: true })
);
-export type CompositeEntity = `${EntityType}@${string}`;
+type NotificationEntity = { id: string; type: NotificationEntityType };
-export function compositeEntity(entity: Entity): CompositeEntity {
+export type CompositeEntity =
+ `${EntityType | NotificationEntityType}@${string}`;
+
+export function compositeEntity(
+ entity: Entity | NotificationEntity
+): CompositeEntity {
return `${entity.type}@${entity.id}`;
}
-export function notificationEntity(notification: UnifiedNotification): Entity {
+export function notificationEntity(
+ notification: UnifiedNotification
+): NotificationEntity {
return {
id: notification.entity_id,
- type: notification.entity_type as EntityType,
+ type: notification.entity_type,
};
}
diff --git a/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx b/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
index 2e8775855b..962bce164e 100644
--- a/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
+++ b/apps/web/src/features/property/component/modal/CreatePropertyModal.tsx
@@ -39,6 +39,7 @@ import { useMaybePropertiesContext } from '../../context/PropertiesContext';
import {
getPropertyDataTypeDropdownOptions,
PropertyDataTypeIcon,
+ parseEntityType,
usePropertyNameFocus,
} from '../../utils';
import { ERROR_MESSAGES } from '../../utils/errorHandling';
@@ -325,7 +326,7 @@ export const CreatePropertyModal: Component<CreatePropertyModalProps> = (
specificType?: EntityType | null;
} => {
if (value.startsWith('entity:')) {
- const specificType = value.split(':')[1] as EntityType;
+ const specificType = parseEntityType(value.split(':')[1]) ?? null;
return { type: 'entity', specificType };
}
if (value === 'entity') {
diff --git a/apps/web/src/features/property/editor/PropertyEditorModal.tsx b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
index 1b5ee5feb9..715e777abf 100644
--- a/apps/web/src/features/property/editor/PropertyEditorModal.tsx
+++ b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
@@ -1742,9 +1742,11 @@ function EntityPropertyEditor(props: {
});
const selectEntity = (entity: CombinedEntity) => {
+ const entityType = getEntityType(entity);
+ if (!entityType) return;
const entityRef: EntityReference = {
entity_id: entity.id,
- entity_type: getEntityType(entity),
+ entity_type: entityType,
};
props.onSubmit(entityRef);
};
@@ -1832,6 +1834,8 @@ function EntityPropertyEditor(props: {
return;
}
+ const entityType = getEntityType(entity);
+ if (!entityType) return;
const selectedIds = localSelectedIds();
setOpenOrderFrozen(true);
const nextRefs = selectedIds.has(entity.id)
@@ -1840,7 +1844,7 @@ function EntityPropertyEditor(props: {
...localSelectedRefs(),
{
entity_id: entity.id,
- entity_type: getEntityType(entity),
+ entity_type: entityType,
},
];
diff --git a/apps/web/src/features/property/editor/hooks/useEntitiesForProperty.ts b/apps/web/src/features/property/editor/hooks/useEntitiesForProperty.ts
index ab6b5c8eaa..511b79176b 100644
--- a/apps/web/src/features/property/editor/hooks/useEntitiesForProperty.ts
+++ b/apps/web/src/features/property/editor/hooks/useEntitiesForProperty.ts
@@ -125,13 +125,8 @@ export function useEntitiesForProperty(
converted.push(userToEntity(augmentedUser));
} else {
const entity = quickAccessItemToEntity(item);
- // Filter by specific entity type if needed
- if (entityType) {
- const type = getEntityType(entity);
- if (type === entityType) {
- converted.push(entity);
- }
- } else {
+ const type = getEntityType(entity);
+ if (type && (!entityType || type === entityType)) {
converted.push(entity);
}
}
diff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
index 9a52bc752e..151aa17770 100644
--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx
@@ -48,7 +48,7 @@ type EntityInputProps = {
selectedOptions: () => Set<string>;
setSelectedOptions: (
options: Set<string>,
- entityInfo?: { id: string; entity_type: string }[]
+ entityInfo?: { id: string; entity_type: EntityType }[]
) => void;
onClose?: () => void;
pinnedOptions?: PinnedOption[];
@@ -234,13 +234,11 @@ export function PropertyEntitySelector(props: EntityInputProps) {
converted.push(userToEntity(augmentedUser));
} else {
const entity = quickAccessItemToEntity(item);
- // Filter by specific entity type if needed
- if (specificEntityType) {
- const entityType = getEntityType(entity);
- if (entityType === specificEntityType) {
- converted.push(entity);
- }
- } else {
+ const entityType = getEntityType(entity);
+ if (
+ entityType &&
+ (!specificEntityType || entityType === specificEntityType)
+ ) {
converted.push(entity);
}
}
@@ -348,6 +346,8 @@ export function PropertyEntitySelector(props: EntityInputProps) {
index === selectedEntityCountAtOpen();
const toggleEntity = (entity: CombinedEntity) => {
+ const entityType = getEntityType(entity);
+ if (!entityType) return;
const newSelected = new Set(props.selectedOptions());
const isCurrentlySelected = newSelected.has(entity.id);
@@ -365,7 +365,7 @@ export function PropertyEntitySelector(props: EntityInputProps) {
props.setSelectedOptions(newSelected, [
{
id: entity.id,
- entity_type: getEntityType(entity),
+ entity_type: entityType,
},
]);
diff --git a/apps/web/src/features/property/editors/selectors/entityUtils.test.ts b/apps/web/src/features/property/editors/selectors/entityUtils.test.ts
index d51c1a034a..c1cdb56da5 100644
--- a/apps/web/src/features/property/editors/selectors/entityUtils.test.ts
+++ b/apps/web/src/features/property/editors/selectors/entityUtils.test.ts
@@ -23,9 +23,57 @@ import type { IUser } from '@core/user';
import type { CombinedEntity } from './entityUtils';
import {
createEntitySearchConfig,
+ getEntityType,
sortEntitiesWithSelfFirst,
+ useQuickAccessEntities,
} from './entityUtils';
+describe('getEntityType', () => {
+ it('has no properties-service type for an agent session', () => {
+ const agentSession: CombinedEntity = {
+ kind: 'entity',
+ id: 'session-1',
+ data: {
+ type: 'agent_session',
+ id: 'session-1',
+ name: 'Fix the build',
+ ownerId: 'owner-1',
+ botId: 'bot-1',
+ status: 'running',
+ },
+ };
+
+ expect(getEntityType(agentSession)).toBeUndefined();
+ });
+
+ it('maps a call to its call record', () => {
+ const call: CombinedEntity = {
+ kind: 'entity',
+ id: 'call-1',
+ data: {
+ type: 'call',
+ id: 'call-1',
+ name: 'Standup',
+ ownerId: 'owner-1',
+ isActive: false,
+ status: 'ATTENDED',
+ attended: true,
+ participantIds: [],
+ },
+ };
+
+ expect(getEntityType(call)).toBe('CALL_RECORD');
+ });
+});
+
+describe('useQuickAccessEntities', () => {
+ it('lists nothing for an entity type a newer service added', () => {
+ const fromNewerService = JSON.parse('"AGENT_SESSION"');
+
+ expect(useQuickAccessEntities(() => fromNewerService).items()).toEqual([]);
+ });
+});
+
describe('createEntitySearchConfig', () => {
it('should return correct search config with same weights as MentionsMenu', () => {
const [domain] = createSignal('example.com');
diff --git a/apps/web/src/features/property/editors/selectors/entityUtils.ts b/apps/web/src/features/property/editors/selectors/entityUtils.ts
index a9e59bd1ba..1c6208b783 100644
--- a/apps/web/src/features/property/editors/selectors/entityUtils.ts
+++ b/apps/web/src/features/property/editors/selectors/entityUtils.ts
@@ -21,7 +21,7 @@ import type {
} from '@entity';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { Accessor } from 'solid-js';
-import { match } from 'ts-pattern';
+import { match, P } from 'ts-pattern';
export type EntityTypeItemMap = {
USER: UserItem;
@@ -59,7 +59,7 @@ function entityTypeToBuckets(entityType: EntityType): readonly Bucket[] {
.with('CALL_RECORD', () => [] as const) // Call records aren't in quickAccess
.with('CALENDAR_EVENT', () => [] as const) // Calendar events aren't in quickAccess
.with('DATABASE_ROW', () => [] as const) // Database rows aren't in quickAccess
- .exhaustive();
+ .exhaustive(() => [] as const);
return buckets;
}
@@ -149,34 +149,43 @@ export function getEntitySearchText(entity: CombinedEntity): string {
return entity.data.name ?? '';
}
-/** Gets the EntityType string for an entity */
-export function getEntityType(entity: CombinedEntity): EntityType {
+/**
+ * The properties-service entity type for an entity, or `undefined` when the
+ * properties service can't reference it.
+ */
+export function getEntityType(entity: CombinedEntity): EntityType | undefined {
if (entity.kind === 'user') {
return 'USER';
}
- const data = entity.data;
- switch (data.type) {
- case 'channel':
- return 'CHANNEL';
- case 'document':
- if (data.subType?.type === 'task') {
- return 'TASK';
- }
- return 'DOCUMENT';
- case 'chat':
- return 'CHAT';
- case 'project':
- return 'PROJECT';
- case 'email':
- return 'THREAD';
- case 'crm_company':
- return 'COMPANY';
- case 'crm_contact':
- return 'CONTACT';
- default:
- return (data as EntityData).type.toUpperCase() as EntityType;
- }
+ return match<EntityData, EntityType | undefined>(entity.data)
+ .with({ type: 'channel' }, () => 'CHANNEL')
+ .with({ type: 'document' }, (data) =>
+ data.subType?.type === 'task' ? 'TASK' : 'DOCUMENT'
+ )
+ .with({ type: 'chat' }, () => 'CHAT')
+ .with({ type: 'project' }, () => 'PROJECT')
+ .with({ type: 'email' }, () => 'THREAD')
+ .with({ type: 'crm_company' }, () => 'COMPANY')
+ .with({ type: 'crm_contact' }, () => 'CONTACT')
+ .with({ type: 'initiative' }, () => 'INITIATIVE')
+ .with({ type: 'call' }, () => 'CALL_RECORD')
+ .with({ type: 'calendar_event' }, () => 'CALENDAR_EVENT')
+ .with(
+ {
+ type: P.union(
+ 'agent_session',
+ 'channel_message',
+ 'channel_thread',
+ 'database',
+ 'form',
+ 'routine',
+ 'foreign'
+ ),
+ },
+ () => undefined
+ )
+ .exhaustive(() => undefined);
}
/** Check if entity is a channel */
diff --git a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
index d12ae242e1..afa7961e2e 100644
--- a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
+++ b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
@@ -62,7 +62,7 @@ type PropertyEntityDisplayResult = {
*/
export function usePropertyEntityDisplay(
entityId: Accessor<string>,
- entityType: Accessor<EntityType>,
+ entityType: Accessor<EntityType | undefined>,
options?: {
/** Custom fallback icon for unknown entity types (null to show nothing) */
fallbackIcon?: JSX.Element | null;
@@ -87,12 +87,10 @@ export function usePropertyEntityDisplay(
? source.data?.id
: undefined;
};
- const previewType = () => entityTypeToItemType(entityType());
-
const previewSource = createMemo(() => {
const eType = entityType();
- const pType = previewType();
if (isPreviewable(eType)) {
+ const pType = entityTypeToItemType(eType);
return untrack(
() =>
useItemPreview(() => ({
@@ -142,7 +140,7 @@ export function usePropertyEntityDisplay(
if (isAccessiblePreviewItem(item)) {
return item.name;
}
- return `Unknown ${entityType().toLowerCase()}`;
+ return `Unknown ${entityType()?.toLowerCase() ?? 'entity'}`;
})
);
diff --git a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
index 1aeeb620a5..c225bab90b 100644
--- a/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
+++ b/apps/web/src/features/property/side-panel/properties/EntityPropertiesSection.tsx
@@ -437,7 +437,7 @@ function propertyFromPendingDefinition(
}))
.with('LINK', () => ({ ...base, valueType: 'LINK' as const, value: null }))
.with('TAG', () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
}
function sortPinnedProperties<T extends Property>(
diff --git a/apps/web/src/features/property/utils/entityConversion.test.ts b/apps/web/src/features/property/utils/entityConversion.test.ts
new file mode 100644
index 0000000000..c784a58543
--- /dev/null
+++ b/apps/web/src/features/property/utils/entityConversion.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@entity', () => ({ isTaskEntity: () => false }));
+
+import { entityTypeToItemType, parseEntityType } from './entityConversion';
+
+describe('entityTypeToItemType', () => {
+ it('has no preview for an entity type a newer service added', () => {
+ const fromNewerService = JSON.parse('"AGENT_SESSION"');
+
+ expect(entityTypeToItemType(fromNewerService)).toBeUndefined();
+ });
+
+ it('previews a call record as a call', () => {
+ expect(entityTypeToItemType('CALL_RECORD')).toBe('call');
+ });
+});
+
+describe('parseEntityType', () => {
+ it('accepts a properties-service entity type', () => {
+ expect(parseEntityType('CONTACT')).toBe('CONTACT');
+ });
+
+ it('rejects an entity type the properties service does not have', () => {
+ expect(parseEntityType('AGENT_SESSION')).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/features/property/utils/entityConversion.ts b/apps/web/src/features/property/utils/entityConversion.ts
index 743879f01f..18d1756ebf 100644
--- a/apps/web/src/features/property/utils/entityConversion.ts
+++ b/apps/web/src/features/property/utils/entityConversion.ts
@@ -19,7 +19,7 @@ export function entityReferencesToIdSet(refs: EntityReference[]): Set<string> {
export function updateEntityReferences(
currentRefs: EntityReference[],
newSelectedIds: Set<string>,
- entityInfo?: Array<{ id: string; entity_type: string }>
+ entityInfo?: Array<{ id: string; entity_type: EntityType }>
): EntityReference[] {
const currentIds = new Set(currentRefs.map((ref) => ref.entity_id));
@@ -38,17 +38,21 @@ export function updateEntityReferences(
// Add new entities with proper entity type
for (const id of addedIds) {
- const entityType =
- entityInfo?.find((info) => info.id === id)?.entity_type || 'DOCUMENT';
updatedRefs.push({
entity_id: id,
- entity_type: entityType as EntityReference['entity_type'],
+ entity_type:
+ entityInfo?.find((info) => info.id === id)?.entity_type ?? 'DOCUMENT',
});
}
return updatedRefs;
}
+/** `undefined` means this build doesn't know the entity type. */
+export function parseEntityType(value: string): EntityType | undefined {
+ return Object.values(EntityType).find((type) => type === value);
+}
+
/** `undefined` means the entity type has no item-preview surface. */
export function entityTypeToItemType(type: EntityType): ItemType | undefined {
return match<EntityType, ItemType | undefined>(type)
@@ -68,7 +72,7 @@ export function entityTypeToItemType(type: EntityType): ItemType | undefined {
'DATABASE_ROW',
() => undefined
)
- .exhaustive();
+ .exhaustive(() => undefined);
}
export function macroEntityToPropertyEntityType(
diff --git a/apps/web/src/features/property/utils/typeGuards.ts b/apps/web/src/features/property/utils/typeGuards.ts
index 9e58fe9306..fa3c24f548 100644
--- a/apps/web/src/features/property/utils/typeGuards.ts
+++ b/apps/web/src/features/property/utils/typeGuards.ts
@@ -252,7 +252,7 @@ function isSingleEntityReference(value: unknown): value is EntityReference {
*/
function createNullApiValue(
valueType: Property['valueType']
-): PropertyApiValues {
+): PropertyApiValues | null {
return match(valueType)
.with('STRING', () => ({ valueType: 'STRING' as const, value: null }))
.with('NUMBER', () => ({ valueType: 'NUMBER' as const, value: null }))
@@ -268,7 +268,7 @@ function createNullApiValue(
}))
.with('ENTITY', () => ({ valueType: 'ENTITY' as const, refs: null }))
.with('LINK', () => ({ valueType: 'LINK' as const, values: null }))
- .exhaustive();
+ .exhaustive(() => null);
}
/**
@@ -345,5 +345,5 @@ export function toPropertyApiValue(
}
return null;
})
- .exhaustive();
+ .exhaustive(() => null);
}
diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
index 924674157c..e221cc0112 100644
--- a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts
@@ -43,7 +43,9 @@ export function serializeTrigger(trigger: RoutineTriggerDraft) {
)
.with('month', () => `0 ${minute} ${hour} ${trigger.dayOfMonth} * *`)
.with('custom', () => trigger.cron.trim())
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error('Choose how often the routine runs.');
+ });
return { type: 'cron' as const, schedule, timezone: trigger.timezone };
}
export function serializeTriggers(
diff --git a/apps/web/src/features/scheduling/components/event-types-panel.tsx b/apps/web/src/features/scheduling/components/event-types-panel.tsx
index 1b7729348d..76726dfa5b 100644
--- a/apps/web/src/features/scheduling/components/event-types-panel.tsx
+++ b/apps/web/src/features/scheduling/components/event-types-panel.tsx
@@ -384,7 +384,7 @@ export function EventTypesPanel(props: {
Round robin
</>
))
- .exhaustive()}
+ .exhaustive(() => null)}
</Badge>
<Dropdown>
<Dropdown.Trigger
diff --git a/apps/web/src/features/settings/Email.tsx b/apps/web/src/features/settings/Email.tsx
index f68d2593e2..27f5799d7f 100644
--- a/apps/web/src/features/settings/Email.tsx
+++ b/apps/web/src/features/settings/Email.tsx
@@ -362,7 +362,7 @@ function syncStatusLabel(status: SyncStatus): string {
.with(SyncStatus.ERROR, () => 'Error — re-sync')
.with(SyncStatus.NEEDS_REAUTH, () => 'Reconnect to resume sync')
.with(SyncStatus.INACTIVE, () => 'Disabled')
- .exhaustive();
+ .exhaustive(() => 'Unknown sync status');
}
// Live backfill progress bar. `completed`/`total` are the connection-gateway
diff --git a/apps/web/src/features/settings/connections/slack-channel-import/model.ts b/apps/web/src/features/settings/connections/slack-channel-import/model.ts
index a9c63e1637..18b06e9576 100644
--- a/apps/web/src/features/settings/connections/slack-channel-import/model.ts
+++ b/apps/web/src/features/settings/connections/slack-channel-import/model.ts
@@ -96,5 +96,5 @@ export function runLabel(run: ImportRun | undefined): string {
.with('importing', () => 'Importing channels…')
.with('completed', () => 'Import complete')
.with('dismissed', () => 'Find public Slack channels to import.')
- .exhaustive();
+ .exhaustive(() => 'Find public Slack channels to import.');
}
diff --git a/apps/web/src/features/slack-import/components/import-ui.tsx b/apps/web/src/features/slack-import/components/import-ui.tsx
index 4ed5934713..8192175c07 100644
--- a/apps/web/src/features/slack-import/components/import-ui.tsx
+++ b/apps/web/src/features/slack-import/components/import-ui.tsx
@@ -44,7 +44,7 @@ export function jobTone(status: ImportJobStatus): StatusTone {
.with('completed', () => 'success' as const)
.with('completed_with_errors', 'cancelling', () => 'warning' as const)
.with('failed', 'cancelled', () => 'failure' as const)
- .exhaustive();
+ .exhaustive(() => 'neutral' as const);
}
export function conversationTone(
@@ -56,7 +56,7 @@ export function conversationTone(
.with('completed', () => 'success' as const)
.with('skipped', () => 'warning' as const)
.with('failed', () => 'failure' as const)
- .exhaustive();
+ .exhaustive(() => 'neutral' as const);
}
const TONE_CLASS: Record<StatusTone, string> = {
diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.test.ts b/apps/web/src/lib/core/agent-fold/fold.worker.test.ts
index a06cf3c9e0..cb9a697684 100644
--- a/apps/web/src/lib/core/agent-fold/fold.worker.test.ts
+++ b/apps/web/src/lib/core/agent-fold/fold.worker.test.ts
@@ -71,3 +71,26 @@ it('initializes on preload without opening a fold, then processes a session afte
{ kind: 'snapshot', rows: [] },
]);
});
+
+it('answers a request kind this build does not know with an error', async () => {
+ const scope = new WorkerScope();
+ vi.stubGlobal('self', scope);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ fold.initialize.mockResolvedValue({ FoldStream: class {} });
+ const posted = new Promise<FoldResponse>((resolve) =>
+ scope.postMessage.mockImplementation(resolve)
+ );
+ await import('./fold.worker');
+
+ scope.dispatchEvent(
+ new MessageEvent('message', {
+ data: JSON.parse('{"id":7,"kind":"compact"}'),
+ })
+ );
+
+ expect(await posted).toEqual({
+ id: 7,
+ ok: false,
+ error: 'unknown request',
+ });
+});
diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.ts b/apps/web/src/lib/core/agent-fold/fold.worker.ts
index bb32f91731..4a9c5a9baa 100644
--- a/apps/web/src/lib/core/agent-fold/fold.worker.ts
+++ b/apps/web/src/lib/core/agent-fold/fold.worker.ts
@@ -73,7 +73,10 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {
streams.delete(sessionId);
return { id, kind, ok: true as const };
})
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('fold worker: unknown request', unknown);
+ return { id: request.id, ok: false as const, error: 'unknown request' };
+ });
}
scope.addEventListener('message', (event: MessageEvent<FoldRequest>) => {
diff --git a/apps/web/src/lib/core/ai-engine/ai.worker.ts b/apps/web/src/lib/core/ai-engine/ai.worker.ts
index 8ada37f5e2..280733ff63 100644
--- a/apps/web/src/lib/core/ai-engine/ai.worker.ts
+++ b/apps/web/src/lib/core/ai-engine/ai.worker.ts
@@ -89,7 +89,7 @@ function query(
.with('textGeometry', () => f.textGeometry(a as number))
.with('describe', () => JSON.stringify(f.describe()))
.with('isEdited', () => JSON.stringify(f.isEdited()))
- .exhaustive();
+ .exhaustive(() => 'null');
}
type Request<K extends AiRequest['kind']> = Extract<AiRequest, { kind: K }>;
@@ -159,7 +159,11 @@ function edit(request: Request<'edit'>) {
.with('redo', () => f.redo())
.with('remote', () => f.applyCollab(request.changes ?? '[]'))
.with('apply', () => f.apply(request.ops ?? '[]', request.coalesce))
- .exhaustive();
+ .exhaustive(() => undefined);
+ if (json === undefined) {
+ fail(request.id, `unknown edit action: ${request.action}`);
+ return;
+ }
post({ id: request.id, ok: true, kind: 'edit', json });
}
@@ -221,7 +225,10 @@ async function serve(request: AiRequest): Promise<void> {
.with({ kind: 'blank' }, blank)
.with({ kind: 'save' }, (r) => postSaved(r.id, openFile().save()))
.with({ kind: 'cancel' }, () => undefined)
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('ai worker: unknown request', unknown);
+ fail(request.id, 'unknown request');
+ });
}
function takeRender(): Render | undefined {
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
index 4be281a36c..9cafd55043 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadActivity.tsx
@@ -79,7 +79,7 @@ function activityAction(action: Activity['action']): ActivityAction {
kind: 'unknown' as const,
tag,
}))
- .exhaustive();
+ .exhaustive(() => ({ kind: 'unknown' as const, tag: action.type }));
}
function activityEvent(activity: Activity, index: number): ActivityEvent {
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ReadChannel.tsx b/apps/web/src/lib/core/component/AI/component/tool/ReadChannel.tsx
index cd7d99d1bc..6ddb810c10 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/ReadChannel.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/ReadChannel.tsx
@@ -90,7 +90,7 @@ function formatReadChannelWindow(args: {
.with({ windowType: 'aroundMessage' }, () => 'around message')
.with({ windowType: 'messages' }, () => 'specific messages')
.with({ windowType: 'latest' }, () => 'latest')
- .exhaustive();
+ .exhaustive(() => 'latest');
}
export const readChannelMessagesHandler = createToolRenderer({
diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsx
index 77f7c23f8b..dece8fbb0c 100644
--- a/apps/web/src/lib/core/component/EntityIcon.tsx
+++ b/apps/web/src/lib/core/component/EntityIcon.tsx
@@ -703,7 +703,7 @@ export function getEntityIconType(entity: EntityIconData): EntityWithValidIcon {
.with({ type: 'crm_contact' }, () => 'contact')
.with({ type: 'database' }, () => 'database')
.with({ type: 'form' }, () => 'form')
- .exhaustive();
+ .exhaustive(() => 'default');
}
export function getEntityIconConfig(
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index 5a30a9c4c3..4239dac17c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -388,7 +388,11 @@ function statusActivity(status: MagicChipStatus): MagicChipActivity {
busy: false,
tone: 'stopped' as const,
}))
- .exhaustive();
+ .exhaustive(() => ({
+ label: 'Queued',
+ busy: false,
+ tone: 'neutral' as const,
+ }));
}
/**
diff --git a/apps/web/src/lib/core/docx-engine/docx.worker.ts b/apps/web/src/lib/core/docx-engine/docx.worker.ts
index be2a35b66c..dd6dd9301f 100644
--- a/apps/web/src/lib/core/docx-engine/docx.worker.ts
+++ b/apps/web/src/lib/core/docx-engine/docx.worker.ts
@@ -92,7 +92,9 @@ function openSource(wasm: WasmModule, source: Source): WasmDocxDocument {
wasm.DocxDocument.fromCollab(state, seed)
)
.with({ kind: 'v1' }, ({ state }) => wasm.DocxDocument.fromV1(state))
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error('Unknown document source');
+ });
}
/**
@@ -121,7 +123,9 @@ async function recover() {
doc.setExternalUndo(external)
)
.with({ kind: 'setAuthor' }, ({ author }) => doc.setAuthor(author))
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error('Unknown change log entry');
+ });
}
open.doc = doc;
} catch {
@@ -421,7 +425,10 @@ async function serve(request: DocxRequest): Promise<Served> {
) as ArrayBuffer;
return [{ id, ok: true, kind: 'save', bytes }, [bytes]];
})
- .exhaustive();
+ .exhaustive((unknown): Served => {
+ console.warn('docx worker: unknown request', unknown);
+ return [{ id, ok: false, error: 'Unknown document request.' }, []];
+ });
}
scope.addEventListener('message', (event: MessageEvent<DocxRequest>) => {
diff --git a/apps/web/src/lib/core/fig-engine/fig.worker.ts b/apps/web/src/lib/core/fig-engine/fig.worker.ts
index b490339236..0bcf7e9093 100644
--- a/apps/web/src/lib/core/fig-engine/fig.worker.ts
+++ b/apps/web/src/lib/core/fig-engine/fig.worker.ts
@@ -323,7 +323,11 @@ async function serve(request: FigRequest) {
.with('apply', () =>
f.apply(request.page, request.ops ?? '[]', request.coalesce)
)
- .exhaustive();
+ .exhaustive(() => undefined);
+ if (json === undefined) {
+ fail(request.id, `unknown edit action: ${request.action}`);
+ return;
+ }
post({ id: request.id, ok: true, kind: 'edit', json });
return;
}
diff --git a/apps/web/src/lib/core/pptx-engine/pptx.worker.ts b/apps/web/src/lib/core/pptx-engine/pptx.worker.ts
index aa090f3e24..bb9f5a85f0 100644
--- a/apps/web/src/lib/core/pptx-engine/pptx.worker.ts
+++ b/apps/web/src/lib/core/pptx-engine/pptx.worker.ts
@@ -112,7 +112,9 @@ async function recover() {
.with({ kind: 'applyCollab' }, ({ changes }) =>
doc.applyCollab(changes)
)
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error('Unknown change log entry');
+ });
}
open.doc = doc;
} catch {
@@ -438,7 +440,10 @@ async function serve(
Transferable[],
];
})
- .exhaustive();
+ .exhaustive((unknown): [PptxResponse, Transferable[]] => {
+ console.warn('pptx worker: unknown request', unknown);
+ return [{ id, ok: false, error: 'Unknown presentation request.' }, []];
+ });
}
scope.addEventListener('message', (event: MessageEvent<PptxRequest>) => {
diff --git a/apps/web/src/lib/core/psd-engine/psd.worker.ts b/apps/web/src/lib/core/psd-engine/psd.worker.ts
index 49a15115db..cee38cffb9 100644
--- a/apps/web/src/lib/core/psd-engine/psd.worker.ts
+++ b/apps/web/src/lib/core/psd-engine/psd.worker.ts
@@ -119,7 +119,10 @@ function query(request: Extract<PsdRequest, { kind: 'query' }>): string {
.with('describe', () => JSON.stringify(f.describe()))
.with('isEdited', () => JSON.stringify(f.isEdited()))
.with('fileLayers', () => f.fileLayers())
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('psd worker: unknown query method', unknown);
+ return 'null';
+ });
}
function bytes(request: Extract<PsdRequest, { kind: 'bytes' }>): Uint8Array {
@@ -133,7 +136,10 @@ function bytes(request: Extract<PsdRequest, { kind: 'bytes' }>): Uint8Array {
.with('exportPng', () => f.exportPng(optional(a)))
.with('exportJpeg', () => f.exportJpeg(a ?? 90))
.with('sample', () => f.sample(a ?? 0, b ?? 0, optional(c)))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('psd worker: unknown bytes method', unknown);
+ return new Uint8Array();
+ });
}
async function serve(request: PsdRequest) {
@@ -177,7 +183,11 @@ async function serve(request: PsdRequest) {
.with('redo', () => f.redo())
.with('remote', () => f.applyCollab(request.changes ?? '[]'))
.with('apply', () => f.apply(request.ops ?? '[]', request.coalesce))
- .exhaustive();
+ .exhaustive(() => undefined);
+ if (json === undefined) {
+ fail(request.id, `unknown edit action: ${request.action}`);
+ return;
+ }
post({ id: request.id, ok: true, kind: 'json', json });
return;
}
diff --git a/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts b/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
index 6e7946fa47..2eaa433b90 100644
--- a/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/mutation-queue-runner.ts
@@ -763,7 +763,10 @@ export function createMutationQueueRunner(
resolveLiveOperationsAsQueued();
scheduleDrain(EMPTY_QUEUE_POLL_MS);
})
- .exhaustive();
+ .exhaustive(() => {
+ resolveLiveOperationsAsQueued();
+ scheduleDrain();
+ });
} catch (error) {
// Enqueue already succeeded. Preserve durable-runner ownership even
// if routing or claim rollback fails unexpectedly.
diff --git a/apps/web/src/lib/graphql-cache/telemetry.ts b/apps/web/src/lib/graphql-cache/telemetry.ts
index f45e041bec..3a42ec369a 100644
--- a/apps/web/src/lib/graphql-cache/telemetry.ts
+++ b/apps/web/src/lib/graphql-cache/telemetry.ts
@@ -530,7 +530,7 @@ export function operationCategoryForRequest(
'inspect-mutations',
() => 'lifecycle' as const
)
- .exhaustive();
+ .exhaustive(() => 'lifecycle' as const);
}
export function isStorageTransactionRequest(
diff --git a/apps/web/src/lib/graphql-cache/worker/cache-engine-runtime.ts b/apps/web/src/lib/graphql-cache/worker/cache-engine-runtime.ts
index 87cde967cb..b388322742 100644
--- a/apps/web/src/lib/graphql-cache/worker/cache-engine-runtime.ts
+++ b/apps/web/src/lib/graphql-cache/worker/cache-engine-runtime.ts
@@ -454,7 +454,9 @@ async function activate(
})
);
})
- .exhaustive();
+ .exhaustive((unknown) =>
+ console.warn('cache engine: unknown coordinator envelope', unknown)
+ );
},
onError: (error) => {
runnerFailed = true;
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-router.test.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-router.test.ts
index 71cc76246c..57f7ec912e 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-router.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-router.test.ts
@@ -412,6 +412,30 @@ describe('CoordinatorRouter', () => {
expect(router.snapshot()).toBeUndefined();
});
+ it('reports an unknown message kind from a newer tab as a protocol error', async () => {
+ const router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => {},
+ });
+ const port = new FakePort();
+ await register(router, port, 'tab-a');
+ const fromNewerTab = JSON.parse('"tab-took-a-nap"');
+
+ await expect(
+ router.handleTabMessage(port as CoordinatorMessagePort, {
+ ...version,
+ kind: fromNewerTab,
+ tabId: 'tab-a',
+ })
+ ).resolves.toBeUndefined();
+
+ expect(messagesOfKind(port, 'protocol-error')).toContainEqual(
+ expect.objectContaining({
+ error: 'invalid tab-took-a-nap coordinator envelope',
+ })
+ );
+ });
+
it('routes colliding tab ids through unique engine ids, restores responses, and fans pushes', async () => {
const router = new CoordinatorRouter({
verifyTabLockHeld: async () => true,
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
index 15cc8af033..7f0c8fc998 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
@@ -405,7 +405,9 @@ export class CoordinatorRouter {
.with({ kind: 'disconnect-tab' }, ({ reason }) => {
this.loseTab(tabId, reason);
})
- .exhaustive();
+ .exhaustive(() =>
+ this.postProtocolError(port, 'unknown coordinator message kind')
+ );
}
private async register(
@@ -1053,7 +1055,7 @@ export class CoordinatorRouter {
.with('loading-assets', () => this.assetLoadTimeoutMs)
.with('awaiting-owner-lock', () => this.ownerLockWaitTimeoutMs)
.with('opening-database', () => this.activationTimeoutMs)
- .exhaustive(),
+ .exhaustive(() => this.activationTimeoutMs),
});
}
@@ -1080,7 +1082,7 @@ export class CoordinatorRouter {
'opening-database',
() => 'engine database opening watchdog timed out'
)
- .exhaustive()
+ .exhaustive(() => 'engine startup watchdog timed out')
);
}, timeoutMs);
}
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
index dcd1ca1a8c..d8eccb024e 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
@@ -1334,6 +1334,17 @@ describe('CacheWorkerCore', () => {
expect(messages.at(-1)).toEqual({ id: 2, ok: true, result: variants });
});
+ it('fails a request kind from a newer page instead of answering it', async () => {
+ const messages: unknown[] = [];
+ const port = { postMessage: (message: unknown) => messages.push(message) };
+ const core = new CacheWorkerCore();
+ const fromNewerPage = JSON.parse('{"id":1,"kind":"future-request"}');
+
+ await core.handleRequest(port, fromNewerPage);
+
+ expect(messages).toEqual([expect.objectContaining({ id: 1, ok: false })]);
+ });
+
it('pushes cache changes even without affected operations', async () => {
const writeResult = {
revision: INITIAL_CACHE_REVISION,
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index dd990a123e..1f63731733 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -818,7 +818,9 @@ export class CacheWorkerCore {
this.push({ kind: 'cache-changed', revision, reset: true });
return revision;
})
- .exhaustive();
+ .exhaustive(() =>
+ Promise.reject(new Error('Unknown cache worker request'))
+ );
}
/** Emits the latest successful snapshot without touching storage. */
diff --git a/apps/web/src/lib/queries/database-sql/graphql-source.test.ts b/apps/web/src/lib/queries/database-sql/graphql-source.test.ts
index 3ff45f27c1..f4fc676fb8 100644
--- a/apps/web/src/lib/queries/database-sql/graphql-source.test.ts
+++ b/apps/web/src/lib/queries/database-sql/graphql-source.test.ts
@@ -335,6 +335,48 @@ describe('the GraphQL row source', () => {
});
});
+ it('reads a property value type from a newer server as an empty cell', async () => {
+ const fromNewerServer = JSON.parse(
+ '{"__typename":"GraphqlRatingPropertyValue","rating":4}'
+ );
+ const server = fakeClient(() =>
+ soupPage(
+ [
+ row(ACME, DEALS, '80', [
+ property(NAME, {
+ __typename: 'GraphqlStringPropertyValue',
+ stringValue: 'Acme',
+ }),
+ property(AMOUNT, fromNewerServer),
+ ]),
+ ],
+ null
+ )
+ );
+ const source = createGraphqlRowSource({
+ client: server.client,
+ catalog: { tables: [] },
+ requestPolicy: 'network-only',
+ people: noPeople,
+ });
+
+ const page = await source.page(
+ { type: 'soup', table: DEALS, propf: null, keyHint: null },
+ [],
+ null,
+ 500,
+ { request: () => {}, headers: () => ({}) }
+ );
+
+ expect(page._unsafeUnwrap().rows).toEqual([
+ {
+ id: ACME,
+ position: '80',
+ cells: { [NAME]: { type: 'text', value: 'Acme' } },
+ },
+ ]);
+ });
+
it('follows the Soup cursor page by page', async () => {
const transcript = readTranscript('paging');
const server = fakeClient((operation) =>
diff --git a/apps/web/src/lib/queries/database-sql/graphql-source.ts b/apps/web/src/lib/queries/database-sql/graphql-source.ts
index 0025847141..6d05d7051d 100644
--- a/apps/web/src/lib/queries/database-sql/graphql-source.ts
+++ b/apps/web/src/lib/queries/database-sql/graphql-source.ts
@@ -201,7 +201,9 @@ export function createGraphqlRowSource({
.with({ type: 'groupSoup' }, () =>
errAsync(fetchFailure('a grouped query is read as bins, not pages'))
)
- .exhaustive(),
+ .exhaustive(() =>
+ errAsync(fetchFailure('an unknown query has no pages'))
+ ),
bins: (query, step) =>
match(query)
.returnType<ResultAsync<Bin[], DatabaseSqlFetchFailure>>()
@@ -211,7 +213,9 @@ export function createGraphqlRowSource({
.with({ type: P.union('soup', 'people') }, () =>
errAsync(fetchFailure('only a grouped query has bins'))
)
- .exhaustive(),
+ .exhaustive(() =>
+ errAsync(fetchFailure('only a grouped query has bins'))
+ ),
};
}
@@ -288,10 +292,15 @@ function propertiesExpression(propf: Propf): GraphqlFilterPropertiesExpr {
value: match(v)
.with({ so: P.string }, ({ so }) => ({ selectOption: so }))
.with({ er: P.string }, ({ er }) => ({ entityRef: er }))
- .exhaustive(),
+ .exhaustive(() => ({ entityRef: NIL_UUID })),
},
}))
- .exhaustive();
+ .exhaustive(() => ({
+ literal: {
+ propertyDefinitionId: NIL_UUID,
+ value: { entityRef: NIL_UUID },
+ },
+ }));
}
/** A balanced OR keeps a long list inside the filter depth limit. */
@@ -474,7 +483,7 @@ function cell(
): Cell | undefined {
if (!value) return undefined;
return match(value)
- .returnType<Cell>()
+ .returnType<Cell | undefined>()
.with({ __typename: 'GraphqlBooleanPropertyValue' }, ({ boolValue }) => ({
type: 'bool',
value: boolValue,
@@ -509,7 +518,7 @@ function cell(
type: 'text',
value: urls.join(' '),
}))
- .exhaustive();
+ .exhaustive(() => undefined);
}
function groupBins(
diff --git a/apps/web/src/lib/queries/email/graphql/mapper.test.ts b/apps/web/src/lib/queries/email/graphql/mapper.test.ts
index 9b0a6e3392..342505918b 100644
--- a/apps/web/src/lib/queries/email/graphql/mapper.test.ts
+++ b/apps/web/src/lib/queries/email/graphql/mapper.test.ts
@@ -195,6 +195,20 @@ describe('mapGraphqlEmailThreadPage', () => {
expect(mapped.access_level).toBe('view');
});
+ it('defaults an access level from a newer server to view-only', () => {
+ const fromNewerServer = JSON.parse('"SUPER_OWNER"');
+ const mapped = mapGraphqlEmailThreadPage(
+ thread({
+ viewerPermission: {
+ __typename: 'GraphqlAccessLevelPermission',
+ accessLevel: fromNewerServer,
+ },
+ })
+ );
+
+ expect(mapped.access_level).toBe('view');
+ });
+
it('uses message metadata when a canonical label is unavailable', () => {
const mapped = mapGraphqlEmailThreadPage(thread({ labels: [] }));
diff --git a/apps/web/src/lib/queries/email/graphql/mapper.ts b/apps/web/src/lib/queries/email/graphql/mapper.ts
index 8321ac6b13..178b1dba64 100644
--- a/apps/web/src/lib/queries/email/graphql/mapper.ts
+++ b/apps/web/src/lib/queries/email/graphql/mapper.ts
@@ -32,7 +32,7 @@ function mapAccessLevel(
.with('COMMENT', () => 'comment')
.with('EDIT', () => 'edit')
.with('OWNER', () => 'owner')
- .exhaustive();
+ .exhaustive(() => 'view');
}
function mapContact(
diff --git a/apps/web/src/lib/queries/messages/tests/timeline.test.ts b/apps/web/src/lib/queries/messages/tests/timeline.test.ts
index 2f7b9a01c0..b63776b8a8 100644
--- a/apps/web/src/lib/queries/messages/tests/timeline.test.ts
+++ b/apps/web/src/lib/queries/messages/tests/timeline.test.ts
@@ -58,7 +58,11 @@ import {
removeTopLevelMessageFromMessageTimeline,
restoreTopLevelMessageInMessageTimeline,
} from '../timeline';
-import { timelineEntryKey, timelineMessages } from '../timeline-entries';
+import {
+ reconcileTimelineEntries,
+ timelineEntryKey,
+ timelineMessages,
+} from '../timeline-entries';
const parent: MessageParent = { type: 'channel', id: 'channel-1' };
const document: MessageParent = { type: 'document', id: 'document-1' };
@@ -790,6 +794,21 @@ describe('channel activity entries', () => {
expect(index.byId.get('n')?.content).toBe('Message n');
});
+ it('keeps an entry type from a newer server instead of throwing', () => {
+ const message: MessageTimelineEntry = {
+ type: 'message',
+ message: createMessage('m', '2026-09-10T15:00:00Z'),
+ };
+ const fromNewerServer = JSON.parse('{"type":"poll","poll":{"id":"p"}}');
+
+ expect(timelineEntryKey(fromNewerServer)).toBe(
+ '{"type":"poll","poll":{"id":"p"}}'
+ );
+ const merged = reconcileTimelineEntries([message], [fromNewerServer]);
+ expect(merged).toHaveLength(2);
+ expect(merged).toContain(fromNewerServer);
+ });
+
it('keeps activity in place through message removal and rollback', () => {
const data = mixedPage();
testQueryClient.setQueryData(getMessageTimelineQueryKey(parent), data);
diff --git a/apps/web/src/lib/queries/messages/timeline-entries.ts b/apps/web/src/lib/queries/messages/timeline-entries.ts
index 0e847ef045..ea9f8a75e2 100644
--- a/apps/web/src/lib/queries/messages/timeline-entries.ts
+++ b/apps/web/src/lib/queries/messages/timeline-entries.ts
@@ -16,7 +16,7 @@ export function timelineEntryKey(entry: KeyedEntry): string {
return match(entry)
.with({ type: 'message' }, ({ message }) => message.id)
.with({ type: 'activity' }, ({ activity }) => `activity:${activity.id}`)
- .exhaustive();
+ .exhaustive((unknown) => JSON.stringify(unknown));
}
function timelineEntryPosition(entry: MessageTimelineEntry) {
@@ -29,7 +29,7 @@ function timelineEntryPosition(entry: MessageTimelineEntry) {
id: activity.id,
createdAt: activity.occurred_at,
}))
- .exhaustive();
+ .exhaustive(() => ({ id: '', createdAt: '' }));
}
/** Message-only projections for thread operations and document annotations. */
diff --git a/apps/web/src/lib/queries/notification/notification-soup.ts b/apps/web/src/lib/queries/notification/notification-soup.ts
index 3a91f82051..1d2d63dc74 100644
--- a/apps/web/src/lib/queries/notification/notification-soup.ts
+++ b/apps/web/src/lib/queries/notification/notification-soup.ts
@@ -43,7 +43,7 @@ function notificationEntityTypeToSoupTag(
),
() => null
)
- .exhaustive();
+ .exhaustive(() => null);
}
/** Keep REST-backed Home rows live even when notifications use GraphQL. */
diff --git a/apps/web/src/lib/queries/preview/graphql.ts b/apps/web/src/lib/queries/preview/graphql.ts
index 7ebdc42dd9..40f2ccbbdd 100644
--- a/apps/web/src/lib/queries/preview/graphql.ts
+++ b/apps/web/src/lib/queries/preview/graphql.ts
@@ -439,7 +439,8 @@ export async function setGraphqlPreviewName(
...base,
__typename: 'GraphqlSoupInitiative' as const,
}))
- .exhaustive();
+ .exhaustive(() => null);
+ if (!record) return;
await writeGraphqlPreviewCache({
query: stringifyDocument(ItemPreviewNameCacheWriteDocument),
operationName: 'ItemPreviewNameCacheWrite',
diff --git a/apps/web/src/lib/queries/properties/graphql/assignment-links.test.ts b/apps/web/src/lib/queries/properties/graphql/assignment-links.test.ts
index 76b33217be..6c56fb151a 100644
--- a/apps/web/src/lib/queries/properties/graphql/assignment-links.test.ts
+++ b/apps/web/src/lib/queries/properties/graphql/assignment-links.test.ts
@@ -46,4 +46,16 @@ describe('new property assignment links', () => {
buildPropertyAssignmentLinks('USER', 'user-1', 'temporary-1', 'priority')
).toEqual([]);
});
+
+ it('links nothing for an entity type from a newer server', () => {
+ const fromNewerServer = JSON.parse('"SPREADSHEET"');
+ expect(
+ buildPropertyAssignmentLinks(
+ fromNewerServer,
+ 'entity-1',
+ 'temporary-1',
+ 'priority'
+ )
+ ).toEqual([]);
+ });
});
diff --git a/apps/web/src/lib/queries/properties/graphql/assignment-links.ts b/apps/web/src/lib/queries/properties/graphql/assignment-links.ts
index 35b735c884..b05a31140f 100644
--- a/apps/web/src/lib/queries/properties/graphql/assignment-links.ts
+++ b/apps/web/src/lib/queries/properties/graphql/assignment-links.ts
@@ -29,7 +29,7 @@ function propertyParent(
.with('COMPANY', () => 'GraphqlSoupCrmCompany' as const)
.with('DATABASE_ROW', () => 'GraphqlSoupDatabaseRow' as const)
.with('USER', () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
return typename
? selectRecord(PropertyAssignmentParentFragmentDoc, {
__typename: typename,
diff --git a/apps/web/src/lib/queries/properties/graphql/entity.test.ts b/apps/web/src/lib/queries/properties/graphql/entity.test.ts
index e30c48b760..4c5bcbd9be 100644
--- a/apps/web/src/lib/queries/properties/graphql/entity.test.ts
+++ b/apps/web/src/lib/queries/properties/graphql/entity.test.ts
@@ -48,6 +48,7 @@ import {
entityPropertyOptimisticMutationUuid,
mapGraphqlEntityProperties,
refetchGraphqlInitiativeProperties,
+ toGraphqlSetPropertyValue,
} from './entity';
type ControlledRequest = {
@@ -146,6 +147,14 @@ describe('buildEntityPropertiesInput', () => {
).toBeUndefined();
}
);
+
+ it('loads nothing for an entity type a newer service added', () => {
+ const fromNewerService = JSON.parse('"AGENT_SESSION"');
+
+ expect(
+ buildEntityPropertiesInput(fromNewerService, 'entity-1')
+ ).toBeUndefined();
+ });
});
describe('mapGraphqlEntityProperties', () => {
@@ -241,6 +250,16 @@ describe('entityPropertyOptimisticMutationUuid', () => {
});
});
+describe('toGraphqlSetPropertyValue', () => {
+ it('refuses to send a value type this build does not know', () => {
+ const fromNewerBuild = JSON.parse('{"type":"color","value":"#ff0000"}');
+
+ expect(() => toGraphqlSetPropertyValue(fromNewerBuild)).toThrow(
+ 'Unsupported property value type: color'
+ );
+ });
+});
+
describe('GraphQL entity property mutations', () => {
let dispose: (() => void) | undefined;
diff --git a/apps/web/src/lib/queries/properties/graphql/entity.ts b/apps/web/src/lib/queries/properties/graphql/entity.ts
index f4dbf3b6c8..9aafd8911c 100644
--- a/apps/web/src/lib/queries/properties/graphql/entity.ts
+++ b/apps/web/src/lib/queries/properties/graphql/entity.ts
@@ -69,7 +69,7 @@ export function buildEntityPropertiesInput(
.with('DATABASE_ROW', () => 'DATABASE_ROW')
// Users and CRM contacts carry no Soup properties.
.with('USER', 'CONTACT', () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
return soupEntityType && { entityType: soupEntityType, entityId };
}
@@ -213,7 +213,9 @@ export function toGraphqlSetPropertyValue(
}))
.with({ type: 'link' }, (v) => ({ link: v.url }))
.with({ type: 'multi_link' }, (v) => ({ multiLink: v.urls }))
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error(`Unsupported property value type: ${value.type}`);
+ });
}
/** Maps a REST property target type onto its GraphQL enum. */
diff --git a/apps/web/src/lib/queries/soup/graphql/ast.test.ts b/apps/web/src/lib/queries/soup/graphql/ast.test.ts
index 5670d96b46..55727db84d 100644
--- a/apps/web/src/lib/queries/soup/graphql/ast.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/ast.test.ts
@@ -209,6 +209,19 @@ describe('makeGraphqlSoupInput', () => {
});
});
+ it('groups by entity type when a newer build saved a grouping this one does not know', () => {
+ const fromNewerBuild = JSON.parse('{"type":"assignee"}');
+ const input = makeGraphqlGroupedSoupInput({
+ params: { limit: 100, sort_method: 'updated_at' },
+ body: compileToAst(queryStateFrom({ include: { documentDone: false } })),
+ groupBy: fromNewerBuild,
+ });
+
+ expect(input).toMatchObject({
+ initial: { groupBy: { field: 'ENTITY_TYPE' } },
+ });
+ });
+
it('maps grouped cursor continuations to GraphQL input', () => {
expect(
makeGraphqlGroupedSoupContinuationInput({
diff --git a/apps/web/src/lib/queries/soup/graphql/ast.ts b/apps/web/src/lib/queries/soup/graphql/ast.ts
index 1ad1c35822..78190944f8 100644
--- a/apps/web/src/lib/queries/soup/graphql/ast.ts
+++ b/apps/web/src/lib/queries/soup/graphql/ast.ts
@@ -487,7 +487,7 @@ function mapChannelThreadLiteral(
.with('NotificationState', () => ({
notificationState: mapNotificationState(value),
}))
- .exhaustive();
+ .exhaustive(() => ({ threadId: '00000000-0000-0000-0000-000000000000' }));
}
function mapCallLiteral(literal: unknown): GraphqlCallLiteralInput {
@@ -817,7 +817,7 @@ function makeGraphqlGroupByInput(groupBy: GroupByField): GraphqlGroupByInput {
propertyDefinitionId: field.propertyDefinitionId,
entityType: field.entityType,
}))
- .exhaustive();
+ .exhaustive(() => ({ field: 'ENTITY_TYPE' as const }));
}
/** Maps the existing grouped Soup request shape to its GraphQL input. */
diff --git a/apps/web/src/lib/queries/soup/graphql/entity-input.test.ts b/apps/web/src/lib/queries/soup/graphql/entity-input.test.ts
index 282d996649..be6802cd99 100644
--- a/apps/web/src/lib/queries/soup/graphql/entity-input.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/entity-input.test.ts
@@ -91,6 +91,11 @@ describe('batched entity Soup inputs', () => {
buildGraphqlEntitiesSoupInput([{ entityType: 'USER', entityId: 'user' }])
).toBeUndefined();
});
+
+ it('skips an entity type from a newer server', () => {
+ const fromNewerServer = JSON.parse('"NEW_KIND"');
+ expect(buildGraphqlEntitySoupInput(fromNewerServer, 'id')).toBeUndefined();
+ });
});
describe('database rows', () => {
diff --git a/apps/web/src/lib/queries/soup/graphql/entity-input.ts b/apps/web/src/lib/queries/soup/graphql/entity-input.ts
index b8865c1100..974de1c408 100644
--- a/apps/web/src/lib/queries/soup/graphql/entity-input.ts
+++ b/apps/web/src/lib/queries/soup/graphql/entity-input.ts
@@ -125,7 +125,7 @@ export function buildGraphqlEntitySoupInput(
}))
// Users and CRM contacts are not Soup items.
.with('USER', 'CONTACT', () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
if (!targetFilter) return undefined;
const filters: GraphqlEntityFilterAst = {
diff --git a/apps/web/src/lib/queries/soup/grouped/api.ts b/apps/web/src/lib/queries/soup/grouped/api.ts
index 9857b54fde..b3e01b8e7e 100644
--- a/apps/web/src/lib/queries/soup/grouped/api.ts
+++ b/apps/web/src/lib/queries/soup/grouped/api.ts
@@ -159,7 +159,7 @@ export function resolveGroupMetaForKey(
return;
})
.with({ type: 'date' }, () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
}
function getGroupedPropertyValueType(
@@ -297,5 +297,5 @@ export function computeGroupKeysForItem(
return;
})
.with({ type: 'date' }, () => undefined)
- .exhaustive();
+ .exhaustive(() => undefined);
}
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index 8f7d6543ea..d97f6eec4f 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -552,6 +552,19 @@ describe('removeSearchEntities', () => {
expect(getSearchQuery()!.pages[0].results[0]).toEqual(session);
});
+ it('keeps a result of a type this build does not know', () => {
+ const fromNewerServer = JSON.parse('{"type":"newKind","id":"new-1"}');
+ seedSearchQuery(
+ mockSearchCache([
+ [fromNewerServer, mockSearchResult('document', 'doc-1')],
+ ])
+ );
+
+ removeSearchEntities(new Set(['doc-1']));
+
+ expect(getSearchQuery()!.pages[0].results).toEqual([fromNewerServer]);
+ });
+
it('filters matching IDs from search results', () => {
seedSearchQuery(
mockSearchCache([
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index 69bc276931..d4b9c2077f 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -884,7 +884,9 @@ export function buildSingleEntityFilter(
.with('crmContact', () => {
throw new Error('CRM contacts are read through GraphQL Soup only');
})
- .exhaustive();
+ .exhaustive(() => {
+ throw new Error(`Unknown soup entity type: ${entityType}`);
+ });
}
async function updateRecentlyViewedItemLazily(
@@ -1003,7 +1005,7 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {
.with({ type: 'company' }, (r) => r.id)
.with({ type: 'calendarEvent' }, (r) => r.id)
.with({ type: 'agentSession' }, (r) => r.id)
- .exhaustive();
+ .exhaustive(() => '');
}
/** @private Captures every soup-list-shaped query (legacy items, parent
diff --git a/apps/web/src/lib/queries/soup/transform-utils.test.ts b/apps/web/src/lib/queries/soup/transform-utils.test.ts
index 5cc1f994fd..2e9d6295a6 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.test.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.test.ts
@@ -276,3 +276,15 @@ describe('document soup entities', () => {
}
);
});
+
+describe('unknown soup entities', () => {
+ it('maps a tag from a newer server to a placeholder row instead of throwing', () => {
+ const fromNewerServer = JSON.parse(
+ '{"tag":"whiteboard","frecency_score":0,"is_favorited":false,"data":{"id":"board"}}'
+ );
+ expect(mapApiSoupItemToEntity(fromNewerServer)).toMatchObject({
+ type: 'document',
+ id: 'board',
+ });
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 00df0badca..38bf6f82a5 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -1034,7 +1034,12 @@ export const mapApiSoupItemToEntity = (
frecencyScore: item.frecency_score,
} satisfies CalendarEventEntity;
})
- .exhaustive();
+ .exhaustive(() => ({
+ type: 'document' as const,
+ id: 'id' in item.data ? item.data.id : '',
+ name: '',
+ ownerId: '',
+ }));
// Attached once for every tag: only touched_by_me pages carry the field,
// and the Recent feed's client sort reads it off the entity. Resolved
diff --git a/apps/web/src/lib/service-clients/service-cognition/database-query.test.ts b/apps/web/src/lib/service-clients/service-cognition/database-query.test.ts
index 99009f8480..8a26de94e2 100644
--- a/apps/web/src/lib/service-clients/service-cognition/database-query.test.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/database-query.test.ts
@@ -130,6 +130,23 @@ describe('database AI transport boundaries', () => {
});
});
+ it('reports an outcome status from a newer service as an interruption', async () => {
+ complete.mockResolvedValue(
+ ok({
+ outcome: JSON.parse('{"status":"paused"}'),
+ toolActivity: [],
+ })
+ );
+ const result = await generateDatabaseQuery(
+ input,
+ 'google/gemini-3.8-flash'
+ );
+ expect(result._unsafeUnwrapErr()).toEqual({
+ kind: 'interrupted',
+ reason: 'unknown',
+ });
+ });
+
it('keeps the service errors of a failed completion', async () => {
complete.mockResolvedValue(
err([
diff --git a/apps/web/src/lib/service-clients/service-cognition/database-query.ts b/apps/web/src/lib/service-clients/service-cognition/database-query.ts
index 5a1db70d76..bd43ac7146 100644
--- a/apps/web/src/lib/service-clients/service-cognition/database-query.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/database-query.ts
@@ -34,6 +34,6 @@ export function generateDatabaseQuery(
.with({ status: 'interrupted' }, ({ reason }) =>
err({ kind: 'interrupted', reason })
)
- .exhaustive()
+ .exhaustive(() => err({ kind: 'interrupted', reason: 'unknown' }))
);
}
diff --git a/apps/web/src/lib/service-clients/service-connection/stream.ts b/apps/web/src/lib/service-clients/service-connection/stream.ts
index cb912776b2..5d93a75262 100644
--- a/apps/web/src/lib/service-clients/service-connection/stream.ts
+++ b/apps/web/src/lib/service-clients/service-connection/stream.ts
@@ -85,7 +85,10 @@ function streamIsDone(
): boolean {
const isDone = match({ kind, item })
.with({ kind: 'chat' }, ({ item }) => item.type === 'stream_end')
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('connection stream: unknown entity type', unknown);
+ return false;
+ });
return isDone;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index a028b90734..f9395a2e13 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -164,6 +164,14 @@ it('preserves initiative identity, properties, and metadata separately from fold
});
});
+it('skips a Soup item type from a newer server', async () => {
+ const { mapGraphqlSoupItem } = await import('./graphql-soup');
+ const fromNewerServer = JSON.parse(
+ '{"__typename":"GraphqlSoupNewKind","id":"new-1","frecencyScore":null}'
+ );
+ expect(mapGraphqlSoupItem(fromNewerServer)).toBeNull();
+});
+
it('preserves the scheduled occurrence identity on reminder notifications', async () => {
const { mapGraphqlNotification } = await import('./graphql-soup');
const mapped = mapGraphqlNotification({
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 9aa975e50e..34bd80bf30 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -827,7 +827,7 @@ function mapGraphqlPropertyValue(
type: 'Link' as const,
value: urls,
}))
- .exhaustive();
+ .exhaustive(() => null);
}
/** Maps GraphQL property fragments to the shared Soup property shape. */
@@ -868,7 +868,7 @@ function mapDocumentSubType(subType: GraphqlSoupDocument['subType']) {
.with({ __typename: 'GraphqlInitiativeDescriptionSubType' }, () => ({
type: 'initiative_description' as const,
}))
- .exhaustive();
+ .exhaustive(() => undefined);
}
function mapChannelMessage(
@@ -1104,7 +1104,7 @@ function mapGraphqlNotificationMetadata(
.with('REPLY', () => 'reply' as const)
.with('ASSIGNEE', () => 'assignee' as const)
.with('OWNER', () => 'owner' as const)
- .exhaustive(),
+ .exhaustive(() => 'mention' as const),
messageId: metadata.initiativeDiscussionMessageId,
threadId: metadata.initiativeDiscussionThreadId,
text: metadata.initiativeDiscussionText,
@@ -1125,7 +1125,7 @@ function mapGraphqlNotificationMetadata(
.with('MENTION', () => 'mention' as const)
.with('REPLY', () => 'reply' as const)
.with('OWNER', () => 'owner' as const)
- .exhaustive(),
+ .exhaustive(() => 'mention' as const),
messageId: metadata.crmDiscussionMessageId,
threadId: metadata.crmDiscussionThreadId,
text: metadata.crmDiscussionText,
@@ -1528,7 +1528,13 @@ function mapGraphqlNotificationMetadata(
},
}) satisfies NotifEventMember<'agent_session_mentioned'>
)
- .exhaustive();
+ .exhaustive(
+ () =>
+ ({
+ tag: 'reminder',
+ content: { description: '', reminderId: '' },
+ }) satisfies NotifEventMember<'reminder'>
+ );
}
/**
@@ -2002,7 +2008,7 @@ export function mapGraphqlSoupItem(
> & { notifications: ReturnType<typeof mapGraphqlNotifications> },
}) as unknown as SoupApiItem
)
- .exhaustive();
+ .exhaustive(() => null);
}
export type FetchGraphqlSoupOptions = {
diff --git a/apps/web/src/lib/workers/slack-import/unzip-worker.ts b/apps/web/src/lib/workers/slack-import/unzip-worker.ts
index 3306ed98f8..33e80c9f8e 100644
--- a/apps/web/src/lib/workers/slack-import/unzip-worker.ts
+++ b/apps/web/src/lib/workers/slack-import/unzip-worker.ts
@@ -1,4 +1,4 @@
-import { match } from 'ts-pattern';
+import { match, P } from 'ts-pattern';
import {
ArchiveError,
DEFAULT_ARCHIVE_LIMITS,
@@ -185,7 +185,15 @@ export function installArchiveWorker(port: ArchiveWorkerPort): void {
port.postMessage({ type: 'cancelled', sessionId: request.sessionId });
}
})
- .exhaustive();
+ .exhaustive((unknown) =>
+ match(unknown)
+ .with({ sessionId: P.string }, ({ sessionId }) =>
+ reportError(sessionId, new ArchiveError('invalid_state'))
+ )
+ .otherwise(() =>
+ console.warn('slack import worker: unknown request', unknown)
+ )
+ );
};
}
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index eda899dd63..9db0f98649 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,5 +1,5 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function bO($,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 J${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*a($){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 SO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class w extends b{constructor($){super($);this.name="MacroNotFoundError"}}function J($){if($.error!==void 0)throw new SO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>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=J(await $(this.client));return this.detail.clear(),O}}class F$ extends A{async permission(){return J(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return J(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class S$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=J(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){J(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return J(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($){J(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function l$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function H6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var R6={toMention:()=>({tag:l$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function D6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(H6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:C6(x)}}function C6($){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 V$ extends A{static byId($,O){return new V$($,O)}static from($,O){return new V$($,O.id,O)}async fetch(){let $=J(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new w(`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 N$ extends A{static byId($,O){return new N$($,O)}static from($,O){return new N$($,O.bot.id,O)}async fetch(){let $=J(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new w(`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",($)=>$?V$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Fx($)}))}}function Fx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.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 Xj($,O,j){let{channelId:x,thread:S}=_6(O);if(await M6($)){let{id:Z}=J(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new 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:K}=J(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function _6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class g${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:$}=J(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Xj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new g$(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 Gj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return N$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new Ex(this.client,this,$))}async startFresh($){J(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 Ex{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 i.byId(this.client,this.record.sessionId)}async retry($){J(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 W$ extends A{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 W$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return J(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 E$($,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=J(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var A6=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??A6;return a(async(Y)=>{let{results:Q,next_cursor:T}=J(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class ZO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new ZO(this.client,this.channel,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends S${async recordActivity($){return new ZO(this.client,this,J(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 W$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return J(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Gj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return J(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}=J(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=J(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=J(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 Xj(this.client,O?.thread??this,$$($));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 a(async(O)=>{let j=J(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:$}=J(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 J(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){J(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=J(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 M extends S${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=J(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=J(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:l$("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=J(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?WO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>WO.from(this.client,this,j))}}async submit($,O){return WO.from(this.client,this,J(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){J(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return J(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){J(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){J(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 J(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class WO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new WO($,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 w(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function r$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class B$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new B$($,O,j)}static fromRecord($,O,j){return new B$($,O,j.id,j)}static async create($,O,j){return B$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=J(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return B$.fromRecord($,O,S)}static async list($,O){return J(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>B$.fromRecord($,O.session(),x))}async fetch(){return J(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 wx($,{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 wx{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 kO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return J(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>B$.create(this.client,this,$),list:()=>B$.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 Kj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Kj($,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 J(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){J(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){J(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class gO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new gO($,O,j)}async answer($){return J(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 i extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return gO.byId(this.client,this,$)}async sharePermissions(){return J(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:r$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=J(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=J(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=J(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return J(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}=J(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=J(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){J(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){J(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 J(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return J(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return J(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return J(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:$}=J(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Kj.from(this.client,this.id,O))}async changes(){return J(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return J(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}=J(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return J(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>B$.createForSession(this.client,this,$),byId:($)=>B$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class qx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class fx{client;constructor($){this.client=$}byId($){return N$.byId(this.client,$)}async list(){return J(await this.client.storage.listAgents()).map(($)=>N$.from(this.client,$))}async create($){return N$.from(this.client,J(await this.client.storage.createAgent({body:Fx($)})))}}class bx{client;async usage($={}){let{users:O,...j}=$;return J(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return J(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return J(await this.client.cognition.decisions({body:$}))}}class p$ extends A{static byId($,O){return new p$($,O)}static from($,O){return new p$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=J(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new w(`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 kx{client;constructor($){this.client=$}byId($){return p$.byId(this.client,$)}async list(){return J(await this.client.storage.listUserApiKeys()).keys.map(($)=>p$.from(this.client,$))}async create($){let O=J(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:p$.from(this.client,O),secret:O.key}}async tokenForEmail($){return J(await this.client.auth.macroApiToken({query:{email:$}}))}}class yO{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 J(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 J(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 U$ extends A{async fetch(){let{links:$}=J(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`email link ${this.id} not found`);return O}static byId($,O){return new U$($,O)}static async list($){let{links:O}=J(await $.email.listLinks());return O.map((j)=>new U$($,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 J(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class y$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=J(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`calendar ${this.id} not found`);return O}static byId($,O){return new y$($,O)}static async list($){let{calendars:O}=J(await $.calendar.listCalendars());return O.map((j)=>new y$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>U$.byId(this.client,$))}class vO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return J(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return J(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){J(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class z$ extends A{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 z$($,O)}static fromRecord($,O){return new z$($,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");calendar=this.mappedField("calendarId",($)=>$?y$.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:P6($)}));return z$.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}}))}async prepareReplacement($){let O=J(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new vO(this.client,O.operationId)}async providerUrl($={}){return J(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}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 z$.fromRecord(this.client,O)}}function P6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class gx{client;async availabilityCalendars(){return J(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:y$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return J(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return J(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=J(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:z$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=J(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=J(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:z$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return y$.list(this.client)}calendar($){return y$.byId(this.client,$)}event($){return z$.byId(this.client,$)}replacement($){return new vO(this.client,$)}async createEvent($){let O=J(await this.client.calendar.createCalendarEvent({body:F6($)}));return z$.fromRecord(this.client,O)}}function F6($){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,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class I$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}async fetch(){if(this.lookupToken)return J(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=J(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new w(`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",($)=>$?K$.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 J(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){J(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){J(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 v$ extends A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new v$($,O,j)}static from($,O,j){return new v$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=J(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return v$.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 K$ extends F${messageThreadById($){return W$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>v$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return I$.from(this.client,J(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 J(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return v$.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",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class yx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}async list(){let{labels:$}=J(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return J(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return J(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return J(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){J(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){J(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class hx{client;async activity(){return J(await this.client.storage.getActivity()).map(($)=>new ZO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new vx($)}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:$}=J(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}=J(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 S${async sharePermissions(){return J(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return J(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=J(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}=J(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:$}=J(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 hO{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 hO($,O,j,x)}async stop(){J(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 mO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new mO($,O,j)}async fetch(){let $=J(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new w(`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 Z$ extends S${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=Z$.byId(this.client,S.chat_id);return hO.byId(this.client,K,S.stream_id,mO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=J(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Z$($,O)}static async create($,O){let{id:j}=J(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Z$($,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 Z$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=J(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 Z$($,O.chat_id)});toMention(){return{tag:l$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class mx{client;constructor($){this.client=$}byId($){return Z$.byId(this.client,$)}create($){return Z$.create(this.client,$)}search($,O){return Z$.search(this.client,$,O)}}class T$ extends A{async fetch(){let O=J(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new w(`team ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async current($){let O=J(await $.auth.getTeam());if(!O)throw new w("caller has no current team");return new T$($,O.team.id,O.team)}static async list($){return J(await $.auth.getUserTeams()).map((j)=>new T$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=J(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:M.byId(this.client,O.user_id),role:O.role}))}}var E6=8;class _$ extends A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return cO(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 Yj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=J(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 bO(S,E6,async(K)=>{let{state:Z,root:X,replies:G}=J(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function cO($,O,j,x){let S=J(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class w$ extends F${messageThreadById($){return W$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return J(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new w$($,O)}static from($,O){return new w$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>q$.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 Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class q$ extends S${messageThreadById($){return W$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return J(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>T$.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 J(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>w$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new q$($,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 w$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class a$ extends A{tableDetail=new J$(async()=>J(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return J(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>T$.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 J(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:r$($)}))}async table(){return Qj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=J(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>XO.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 a(async(O)=>{let j=J(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)=>XO.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 Qj extends A{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 Qj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Jj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return XO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class XO extends A{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 XO($,O,j)}static from($,O,j){return new XO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new w(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Jj extends A{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 Jj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new w(`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 cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return J(await this.client.storage.listCrmPipelines()).map(($)=>a$.from(this.client,$))}async create($){return a$.from(this.client,J(await this.client.storage.createCrmPipeline({body:$})))}}class ux{client;pipelines;constructor($){this.client=$;this.pipelines=new cx($)}companyById($){return q$.byId(this.client,$)}contactById($){return w$.byId(this.client,$)}async contactByEmail($){let{contact:O}=J(await this.client.storage.getContactByEmail({query:{email:$}}));return O?w$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=J(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>w$.from(this.client,x))}async createCompany($){return q$.from(this.client,J(await this.client.storage.createCrmCompany({body:$})))}async settings(){return J(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return J(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return J(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){J(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return q$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),P1=Symbol.for("@ts-pattern/isVariadic");var dx=($)=>Boolean($&&typeof $=="object"),Vj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Vj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(dx($)){if(!dx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Vj(X)&&X[P1]?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,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],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)||Vj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},X$=($)=>{var O,j,x;return dx($)?Vj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?uO($,X$):uO(Object.values($),X$):[]},uO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function w6(...$){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:()=>px($),and:(O)=>u($,O),or:(O)=>F1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function lx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[P1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>lx(px($)),select:(O)=>lx(O===void 0?dO($):dO(O,$))})}function px($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(X$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>X$($),matcherType:"optional"})})}var q6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},f6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},b6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"and"})})}function F1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return uO($,X$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){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?[]:X$(j))})})}function E1($){return!0}function f$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var w1=t(m(E1)),k6=t(m(E1)),g6=w1,s$=($)=>Object.assign(t($),{startsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),A1=s$(m(i$)),b$=($)=>Object.assign(t($),{between:(O,j)=>b$(u($,((x,S)=>m((K)=>f$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<j))(O))),gt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>j))(O))),lte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<=j))(O))),gte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>=j))(O))),int:()=>b$(u($,m((O)=>f$(O)&&Number.isInteger(O)))),finite:()=>b$(u($,m((O)=>f$(O)&&Number.isFinite(O)))),positive:()=>b$(u($,m((O)=>f$(O)&&O>0))),negative:()=>b$(u($,m((O)=>f$(O)&&O<0)))}),y6=b$(m(f$)),t$=($)=>Object.assign(t($),{between:(O,j)=>t$(u($,((x,S)=>m((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(u($,m((O)=>n$(O)&&O>0))),negative:()=>t$(u($,m((O)=>n$(O)&&O<0)))}),v6=t$(m(n$)),h6=t(m(function($){return typeof $=="boolean"})),m6=t(m(function($){return typeof $=="symbol"})),c6=t(m(function($){return $==null})),u6=t(m(function($){return $!=null})),x$={__proto__:null,matcher:G$,optional:px,array:function(...$){return lx({[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 X$(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?[]:X$($[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:q6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:X$($[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:f6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[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?[A1,$[0]]:$;return{matched:b6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),Q=s(K,X,S),T=s(Z,G,S);return(Q||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},intersection:u,union:F1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:dO,any:w1,unknown:k6,_:g6,string:A1,number:y6,bigint:v6,boolean:h6,symbol:m6,nullish:c6,nonNullable:u6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(w6($)))}};class q1 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 rx={matched:!1,value:void 0};function c($){return new Wj($,rx)}class Wj{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))?rx:{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 Wj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Wj(this.input,j?{matched:!0,value:O(this.input,this.input)}:rx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=d6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function d6($){throw new q1($)}var ax,l6=new Uint8Array(16);function Bj(){if(!ax){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ax=crypto.getRandomValues.bind(crypto)}return ax(l6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function f1($,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 ix={};function r6($,O,j){let x;if($)x=b1($.random??$.rng?.()??Bj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Bj();p6(ix,S,K),x=b1(K,ix.msecs,ix.seq,O,j)}return O??f1(x)}function p6($,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 b1($,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 h$=r6;class M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new w(`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 A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Lj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Lj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`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 Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new w(`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)=>M$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return A$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Lj.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 Nj($,O,j,x={}){let S=J(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:Q})=>[Y.id,Q]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:Q})=>Q.database)]){if(!Y)continue;let Q=K.get(Y.id);if(Q)Q.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let Q=K.get(Y)?.values().next().value;if(Q)return Q;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let Q=S.tableDatabases[Y];if(!Q)throw Error(`SQL response is missing the owner of table ${Y}`);return Y$.byId(Z(Q),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let Q of K.get(Y)??[])Q.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:Q})=>({kind:"schema",database:Z(Y),summary:Q})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:Q,tableName:T})=>({kind:Y,table:X(Q),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:Q,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:Q,column:M$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?a6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>A$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,Q])=>({table:X(Y),version:Q})),readVersions:Object.entries(S.readVersions).map(([Y,Q])=>({table:X(Y),version:Q})),truncatedTables:S.truncatedTables,statement:L}}function a6($,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)=>A$.byId(x,S)):[]}}class Uj{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 Uj($,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 tx extends SO{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 zj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:x$.not("relation")},(O)=>O).exhaustive()}var i6={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 n6($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").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})=>i6[O]).with({type:"relation"},()=>"Relation").exhaustive()}function nx($){return $.map((O)=>({id:h$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function sx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:x$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive()}function m$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(sx).join(", ")||"none"}`);return x}class Q$ extends A{access=new o(this.client,"database",this);async fetch(){return J(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 Q$($,O)}static async create($,O){let j=J(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}static async list($){return J(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Nj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?Y$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=m$(await this.applyOps([{kind:"table",table:h$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.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 tx(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(sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>Y$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),J(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}=J(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}=J(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 Y$.byId(this,O.id)}webhookOf($){return Uj.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=J(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=J(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),J(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return J(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 m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:zj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:zj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${n6(O.to)})`,S=h$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:zj(O.to),options:nx(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(!k1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?sx(Z):"none"}`);return M$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=m$(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}=m$(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}=m$(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}=m$(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:zj(O.type),...O.options!==void 0?{options:nx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=m$(await this.applyOps([{kind:"column",table:$.id,column:h$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return M$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:nx(O)}}]),"column","options_added")}}class ex{client;constructor($){this.client=$}query($,O){return Nj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class GO extends A{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 GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=J(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new w(`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 A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);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 lO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new J$(async()=>J(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new lO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s6=8;class q extends S${async anchors(){return J(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,J(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return lO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return J(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return J(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 W$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(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:$}=J(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}=J(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}=J(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}=J(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 a(async(x)=>{let S=J(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}=J(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=J(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=J(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new SO(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}=J(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=a(async(x)=>{let S=J(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 bO(j,s6,async(x)=>{let{state:S,root:K,replies:Z}=J(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:{...$$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return J(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return J(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:$}=J(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=J(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:l$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ij{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=J(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ij(j.id,j.name))}}class ox{client;async byTeamSlug($){let O=J(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=J(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=J(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,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Ij.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class KO extends A{async fetch(){let{attachment:$}=J(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new KO($,O)}static from($,O){return new KO($,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:$}=J(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends S${access=new o(this.client,"email_thread",this);async followup(){return J(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return J(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return J(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}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?r$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=J(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,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",($)=>U$.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 J(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>KO.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?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return J(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 H$($,O.thread_id)})}class R$ extends A{async fetch(){return J(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=J(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?R$.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",($)=>U$.byId(this.client,$));async operationStatus(){return J(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($){let O=await this.link();await this.mutate((j)=>j.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},headers:{"X-Email-Link-Id":O.id}}))}async transferDraft($){let O=await this.link();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:$,headers:{"X-Email-Link-Id":O.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 H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class YO extends R${async inboxHeaders(){return{"X-Email-Link-Id":(await this.link()).id}}static byId($,O){return new YO($,O)}async update($){let O=await this.inboxHeaders();await this.mutate((j)=>j.email.createDraft({headers:O,body:{draft:{...$0($),db_id:this.id}}}))}async delete(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteDraft({path:{id:this.id},headers:$}))}async schedule($,O){let j=await this.inboxHeaders();await this.mutate((x)=>x.email.upsertScheduledMessage({path:{id:this.id},headers:j,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteScheduledDraft({path:{message_id:this.id},headers:$}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},j=await this.inboxHeaders(),x=await this.mutate((S)=>S.email.addDraftAttachment({path:{id:this.id},headers:j,body:O}));return{attachment:rO.byId(this.client,this,x.attachment_id),uploadUrl:x.upload_url,contentType:x.content_type}}async forwardAttachment($){let O=await this.inboxHeaders(),j=await this.mutate((x)=>x.email.addForwardedAttachment({path:{id:this.id},headers:O,body:{attachment_id:$.id}}));return rO.byId(this.client,this,j.attachment_id,!0)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let O=await this.inboxHeaders();if($.forwarded)await this.mutate((j)=>j.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O}));else await this.mutate((j)=>j.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id)}}class rO{draft;id;forwarded;constructor($,O,j){this.draft=$;this.id=O;this.forwarded=j}static byId($,O,j,x=!1){return new rO(O,j,x)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded}}}function $0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,thread:Z,replyingTo:X,...G}=$;return{...G,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(L)=>String.fromCharCode(L)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,thread_db_id:Z?.id,replying_to_id:X?.id}}class QO extends A{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 QO($,O,void 0,j)}static from($,O,j){return new QO($,O.id,O,j)}async fetch(){let $=J(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new w(`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 e$ extends A{async fetch(){let{labels:$}=J(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`label ${this.id} not found`);return O}static byId($,O){return new e$($,O)}static async list($){let{labels:O}=J(await $.email.listLabels());return O.map((j)=>new e$($,j.id,j))}static async create($,O){let{label:j}=J(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new e$($,j.id)}async delete(){J(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 O0{client;async createDraft($,O){let j=J(await this.client.email.createDraft({body:{draft:$0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return YO.byId(this.client,j.draft.db_id)}draftById($){return YO.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=J(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 YO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return J(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>QO.from(this.client,O,$))}async upsertFilter($,O){return QO.from(this.client,J(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 J(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=J(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:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return KO.byId(this.client,$)}link($){return U$.byId(this.client,$)}links(){return U$.list(this.client)}async connectionProviders(){return J(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return J(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=J(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)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return e$.byId(this.client,$)}labels(){return e$.list(this.client)}createLabel($){return e$.create(this.client,$)}async deleteLabel($){J(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){J(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){J(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return J(await this.client.email.listBlockedSenders()).blocked_emails}}class BO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new BO($,O)}async delete(){J(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class j0{client;constructor($){this.client=$}byId($){return BO.byId(this.client,$)}async create($,O){let j=J(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 BO.byId(this.client,j.id)}}class x0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=J(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return J(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){J(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class o$ extends F${entityType="foreign_entity";async fetch(){return J(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new o$($,O)}static fromRecord($,O){return new o$($,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 g1({login:$,...O}){return{...O,login:$??void 0}}class S0{client;constructor($){this.client=$}byId($){return o$.byId(this.client,$)}async bySource($,O){return o$.fromRecord(this.client,J(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=J(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(g1),assignees:j.map(g1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class u${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new u$($,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 w(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return M$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>JO.byId(this,$.id))}}class JO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new JO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new w(`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 LO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new J$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new w(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new LO($,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 J$(()=>this.load(),$),this}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new w(`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)=>u$.byId(this.form,O.id)):[]}}class Tj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Tj($,O)}}class k$ extends A{async fetch(){return J(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=J(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 k$($,j.form.id,j)}static async list($,O){if(!O)return J(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return J(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.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(($)=>d$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>u$.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)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:x$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??h$(),title:Z.title,description:Z.description??""};return c(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??h$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new 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:x$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:d$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:d$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=A$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:LO.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(J(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=J(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=u$.byId(this,K.question),X=await c(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 JO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Tj.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 Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((Q)=>A$.byId(Y,Q))}}).with({type:x$.union("text","number","boolean","date","link","clear")},(G)=>G).exhaustive();return{question:Z,value:X}})),x=$.response.row?A$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:LO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?d$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=J(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:d$.byId(this,O.section),count:O.count}))}}async tally(){return J(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=u$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.map((x)=>({count:x.count,value:c(x.value).with({kind:"option"},(S)=>({kind:"option",option:JO.byId(j,S.option)})).with({kind:"checkbox"},(S)=>S).exhaustive()}))}})}async sharePermissions(){return J(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 Z0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends A{static byId($,O){return new NO($,O)}async fetch(){return J(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=J(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new X0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class X0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return J(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class G0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class UO extends A{static byId($,O){return new UO($,O)}async fetch(){return J(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 V$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class pO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new pO($,O)}async claim($){let O=J(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:V$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class K0{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}async list(){return J(await this.client.storage.listHarnesses()).map(($)=>V$.from(this.client,$))}async me(){return V$.from(this.client,J(await this.client.storage.getSelfHarness()))}async deleteSelf(){J(await this.client.storage.deleteSelfHarness())}async agents(){return J(await this.client.storage.listHarnessAgents()).map(($)=>N$.byId(this.client,$.bot_id))}async sessions(){return J(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return UO.byId(this.client,$)}async createPairing($){let O=J(await this.client.storage.createHarnessPairing({body:$}));return{pairing:UO.byId(this.client,O.code),device:pO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var t6="00000001-0000-0000-0000-000000000002",e6="00000001-0000-0000-0002-000000000004";function o6($){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 D$ extends q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,j)}static async forPullRequest($,O){let j=o6(O),{pullRequests:x}=J(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===t6)?.value;return j?.type==="SelectOption"&&j.value.includes(e6)}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 D$($,O.document_id)})}class $O extends A{access=new o(this.client,"initiative",this);static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,O)}async fetch(){return J(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.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?r$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Y0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return J(await this.client.storage.listInitiatives()).initiatives.map(($)=>$O.byId(this.client,$.id))}async create($){return $O.from(this.client,J(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Q0{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async create($){return I$.from(this.client,J(await this.client.storage.meetingCreate({body:$})))}async list(){return J(await this.client.storage.meetingList()).meetings.map(($)=>I$.from(this.client,$))}async active(){return J(await this.client.storage.meetingListActive()).meetings.map(($)=>I$.from(this.client,$))}async lookup($){return I$.from(this.client,J(await this.client.storage.meetingLookup({path:{token:$}})))}}class VO extends A{async fetch(){return J(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new VO($,O)}static from($,O){return new VO($,O.id,O)}static list($,O){return a(async(j)=>{let x=J(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)=>VO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class J0{client;constructor($){this.client=$}byId($){return VO.byId(this.client,$)}list($){return VO.list(this.client,$)}async markSeen($){J(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){J(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){J(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return J(await this.client.notification.getNotificationTypePreferences())}async enableType($){J(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){J(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class V0{client;constructor($){this.client=$}async list(){let{data:$}=J(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){J(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){J(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){J(await this.client.storage.reorderPinsHandler({body:$}))}}class W0{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 zO{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 zO($,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=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){J(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class OO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}async fetch(){return J(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=J(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new OO($,j.id,j)}static byId($,O){return new OO($,O)}static fromRecord($,O){return new OO($,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 J(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return J(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>zO.from(this.client,this.id,O))}async addOption($){let O=J(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return zO.from(this.client,this.id,O)}async updateOption($,O){let j=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return zO.from(this.client,this.id,j)}async deleteOption($){return J(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class B0{client;constructor($){this.client=$}async list($){return J(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 OO.fromRecord(this.client,x)})}create($){return OO.create(this.client,$)}definition($){return OO.byId(this.client,$)}async bulkEntityProperties($){return J(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return J(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 J(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return J(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return J(await this.client.properties.listTags({}))}}function L0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function $7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(L0)})).with({type:"cron"},L0).with({type:"events"},L0).exhaustive()}class jO extends A{static byId($,O){return new jO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new jO($,O.id,O)}async fetch(){return J(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:U0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=J(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>Z$.byId(this.client,O.id)).exhaustive();return $.chat_id?Z$.byId(this.client,$.chat_id):void 0}async history(){return J(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{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 U0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,trigger:$7($.trigger),task:{...O}}}class z0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async create($){return jO.from(this.client,J(await this.client.scheduledAction.createScheduledAction({body:{...U0($),enabled:$.enabled??!0}})))}async list($){return J(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>jO.from(this.client,O))}}class I0{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class T0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}current(){return T$.current(this.client)}list(){return T$.list(this.client)}}class H0{client;constructor($){this.client=$}async get($){return J(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return J(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class R0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class xO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return J(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=J(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new xO($,j.id,j,j.signing_secret)}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class D0{client;constructor($){this.client=$}create($){return xO.create(this.client,$)}byId($){return xO.byId(this.client,$)}async list(){let{webhooks:$}=J(await this.client.storage.listWebhooks());return $.map((O)=>xO.fromRecord(this.client,O))}}function C0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function y1($,O,j){let x=[];for(let S of C0(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:Z$.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:H$.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 g$($,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:K$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:z$.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:o$.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 v1="00000000-0000-0000-0000-000000000000",_0={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"]},Hj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),h1=($,O)=>$==null?O:{"&":[$,O]};function M0($,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==="!"){M0(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)=>{M0(Z,`${O}.${S}[${X}]`)})}class Rj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(J),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(_0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(_0).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)M0($[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:v1}},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}=J(await this.client.email.listLinks()),K=S.filter((X)=>Hj(X.email_address)===Hj(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=h1(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(_0))if(!x.includes(S))O[K]={l:{[Z]:v1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Hj(Y.label)===Hj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}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=h1(O.propf,X)}return O}}class A0{client;constructor($){this.client=$}async page($={}){let O=new Rj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Rj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=J(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>C0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>y1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function m1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
+async function bO($,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 J${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*a($){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 SO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class w extends b{constructor($){super($);this.name="MacroNotFoundError"}}function J($){if($.error!==void 0)throw new SO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>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=J(await $(this.client));return this.detail.clear(),O}}class F$ extends A{async permission(){return J(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return J(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class S$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=J(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){J(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return J(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($){J(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function l$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function H6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var R6={toMention:()=>({tag:l$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function D6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(H6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:C6(x)}}function C6($){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 V$ extends A{static byId($,O){return new V$($,O)}static from($,O){return new V$($,O.id,O)}async fetch(){let $=J(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new w(`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 N$ extends A{static byId($,O){return new N$($,O)}static from($,O){return new N$($,O.bot.id,O)}async fetch(){let $=J(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new w(`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",($)=>$?V$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Fx($)}))}}function Fx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.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 Xj($,O,j){let{channelId:x,thread:S}=_6(O);if(await M6($)){let{id:Z}=J(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new 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:K}=J(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function _6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class g${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:$}=J(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Xj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new g$(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 Gj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return N$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new Ex(this.client,this,$))}async startFresh($){J(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 Ex{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 i.byId(this.client,this.record.sessionId)}async retry($){J(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 W$ extends A{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 W$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return J(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 E$($,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=J(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var A6=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??A6;return a(async(Y)=>{let{results:Q,next_cursor:T}=J(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class ZO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new ZO(this.client,this.channel,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends S${async recordActivity($){return new ZO(this.client,this,J(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 W$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return J(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Gj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return J(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}=J(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=J(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=J(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 Xj(this.client,O?.thread??this,$$($));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 a(async(O)=>{let j=J(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:$}=J(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 J(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){J(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=J(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 M extends S${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=J(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=J(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:l$("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=J(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?WO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>WO.from(this.client,this,j))}}async submit($,O){return WO.from(this.client,this,J(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){J(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return J(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){J(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){J(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 J(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class WO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new WO($,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 w(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function r$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class B$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new B$($,O,j)}static fromRecord($,O,j){return new B$($,O,j.id,j)}static async create($,O,j){return B$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=J(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return B$.fromRecord($,O,S)}static async list($,O){return J(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>B$.fromRecord($,O.session(),x))}async fetch(){return J(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 wx($,{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 wx{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 kO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return J(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>B$.create(this.client,this,$),list:()=>B$.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 Kj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Kj($,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 J(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){J(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){J(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class gO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new gO($,O,j)}async answer($){return J(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 i extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return gO.byId(this.client,this,$)}async sharePermissions(){return J(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:r$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=J(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=J(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=J(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return J(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}=J(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=J(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){J(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){J(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 J(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return J(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return J(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return J(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:$}=J(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Kj.from(this.client,this.id,O))}async changes(){return J(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return J(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}=J(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return J(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>B$.createForSession(this.client,this,$),byId:($)=>B$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class qx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class fx{client;constructor($){this.client=$}byId($){return N$.byId(this.client,$)}async list(){return J(await this.client.storage.listAgents()).map(($)=>N$.from(this.client,$))}async create($){return N$.from(this.client,J(await this.client.storage.createAgent({body:Fx($)})))}}class bx{client;async usage($={}){let{users:O,...j}=$;return J(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return J(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return J(await this.client.cognition.decisions({body:$}))}}class p$ extends A{static byId($,O){return new p$($,O)}static from($,O){return new p$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=J(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new w(`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 kx{client;constructor($){this.client=$}byId($){return p$.byId(this.client,$)}async list(){return J(await this.client.storage.listUserApiKeys()).keys.map(($)=>p$.from(this.client,$))}async create($){let O=J(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:p$.from(this.client,O),secret:O.key}}async tokenForEmail($){return J(await this.client.auth.macroApiToken({query:{email:$}}))}}class yO{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 J(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 J(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 U$ extends A{async fetch(){let{links:$}=J(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`email link ${this.id} not found`);return O}static byId($,O){return new U$($,O)}static async list($){let{links:O}=J(await $.email.listLinks());return O.map((j)=>new U$($,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 J(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class y$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=J(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`calendar ${this.id} not found`);return O}static byId($,O){return new y$($,O)}static async list($){let{calendars:O}=J(await $.calendar.listCalendars());return O.map((j)=>new y$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>U$.byId(this.client,$))}class vO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return J(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return J(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){J(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class z$ extends A{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 z$($,O)}static fromRecord($,O){return new z$($,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");calendar=this.mappedField("calendarId",($)=>$?y$.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:P6($)}));return z$.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}}))}async prepareReplacement($){let O=J(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new vO(this.client,O.operationId)}async providerUrl($={}){return J(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}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 z$.fromRecord(this.client,O)}}function P6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class gx{client;async availabilityCalendars(){return J(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:y$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return J(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return J(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=J(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:z$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=J(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=J(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:z$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return y$.list(this.client)}calendar($){return y$.byId(this.client,$)}event($){return z$.byId(this.client,$)}replacement($){return new vO(this.client,$)}async createEvent($){let O=J(await this.client.calendar.createCalendarEvent({body:F6($)}));return z$.fromRecord(this.client,O)}}function F6($){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,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class I$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}async fetch(){if(this.lookupToken)return J(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=J(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new w(`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",($)=>$?K$.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 J(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){J(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){J(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 v$ extends A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new v$($,O,j)}static from($,O,j){return new v$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=J(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return v$.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 K$ extends F${messageThreadById($){return W$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>v$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return I$.from(this.client,J(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 J(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return v$.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",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class yx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}async list(){let{labels:$}=J(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return J(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return J(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return J(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){J(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){J(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class hx{client;async activity(){return J(await this.client.storage.getActivity()).map(($)=>new ZO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new vx($)}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:$}=J(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}=J(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 S${async sharePermissions(){return J(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return J(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=J(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}=J(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:$}=J(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 hO{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 hO($,O,j,x)}async stop(){J(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 mO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new mO($,O,j)}async fetch(){let $=J(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new w(`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 Z$ extends S${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=Z$.byId(this.client,S.chat_id);return hO.byId(this.client,K,S.stream_id,mO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=J(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Z$($,O)}static async create($,O){let{id:j}=J(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Z$($,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 Z$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=J(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 Z$($,O.chat_id)});toMention(){return{tag:l$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class mx{client;constructor($){this.client=$}byId($){return Z$.byId(this.client,$)}create($){return Z$.create(this.client,$)}search($,O){return Z$.search(this.client,$,O)}}class T$ extends A{async fetch(){let O=J(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new w(`team ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async current($){let O=J(await $.auth.getTeam());if(!O)throw new w("caller has no current team");return new T$($,O.team.id,O.team)}static async list($){return J(await $.auth.getUserTeams()).map((j)=>new T$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=J(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:M.byId(this.client,O.user_id),role:O.role}))}}var E6=8;class _$ extends A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return cO(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 Yj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=J(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 bO(S,E6,async(K)=>{let{state:Z,root:X,replies:G}=J(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function cO($,O,j,x){let S=J(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class w$ extends F${messageThreadById($){return W$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return J(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new w$($,O)}static from($,O){return new w$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>q$.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 Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class q$ extends S${messageThreadById($){return W$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return J(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>T$.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 J(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>w$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new q$($,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 w$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class a$ extends A{tableDetail=new J$(async()=>J(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return J(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>T$.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 J(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:r$($)}))}async table(){return Qj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=J(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>XO.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 a(async(O)=>{let j=J(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)=>XO.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 Qj extends A{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 Qj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Jj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return XO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class XO extends A{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 XO($,O,j)}static from($,O,j){return new XO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new w(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Jj extends A{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 Jj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new w(`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 cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return J(await this.client.storage.listCrmPipelines()).map(($)=>a$.from(this.client,$))}async create($){return a$.from(this.client,J(await this.client.storage.createCrmPipeline({body:$})))}}class ux{client;pipelines;constructor($){this.client=$;this.pipelines=new cx($)}companyById($){return q$.byId(this.client,$)}contactById($){return w$.byId(this.client,$)}async contactByEmail($){let{contact:O}=J(await this.client.storage.getContactByEmail({query:{email:$}}));return O?w$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=J(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>w$.from(this.client,x))}async createCompany($){return q$.from(this.client,J(await this.client.storage.createCrmCompany({body:$})))}async settings(){return J(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return J(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return J(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){J(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return q$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),P1=Symbol.for("@ts-pattern/isVariadic");var dx=($)=>Boolean($&&typeof $=="object"),Vj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Vj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(dx($)){if(!dx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Vj(X)&&X[P1]?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,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],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)||Vj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},X$=($)=>{var O,j,x;return dx($)?Vj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?uO($,X$):uO(Object.values($),X$):[]},uO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function w6(...$){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:()=>px($),and:(O)=>u($,O),or:(O)=>F1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function lx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[P1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>lx(px($)),select:(O)=>lx(O===void 0?dO($):dO(O,$))})}function px($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(X$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>X$($),matcherType:"optional"})})}var q6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},f6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},b6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"and"})})}function F1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return uO($,X$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){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?[]:X$(j))})})}function E1($){return!0}function f$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var w1=t(m(E1)),k6=t(m(E1)),g6=w1,s$=($)=>Object.assign(t($),{startsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),A1=s$(m(i$)),b$=($)=>Object.assign(t($),{between:(O,j)=>b$(u($,((x,S)=>m((K)=>f$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<j))(O))),gt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>j))(O))),lte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<=j))(O))),gte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>=j))(O))),int:()=>b$(u($,m((O)=>f$(O)&&Number.isInteger(O)))),finite:()=>b$(u($,m((O)=>f$(O)&&Number.isFinite(O)))),positive:()=>b$(u($,m((O)=>f$(O)&&O>0))),negative:()=>b$(u($,m((O)=>f$(O)&&O<0)))}),y6=b$(m(f$)),t$=($)=>Object.assign(t($),{between:(O,j)=>t$(u($,((x,S)=>m((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(u($,m((O)=>n$(O)&&O>0))),negative:()=>t$(u($,m((O)=>n$(O)&&O<0)))}),v6=t$(m(n$)),h6=t(m(function($){return typeof $=="boolean"})),m6=t(m(function($){return typeof $=="symbol"})),c6=t(m(function($){return $==null})),u6=t(m(function($){return $!=null})),x$={__proto__:null,matcher:G$,optional:px,array:function(...$){return lx({[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 X$(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?[]:X$($[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:q6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:X$($[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:f6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[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?[A1,$[0]]:$;return{matched:b6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),Q=s(K,X,S),T=s(Z,G,S);return(Q||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},intersection:u,union:F1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:dO,any:w1,unknown:k6,_:g6,string:A1,number:y6,bigint:v6,boolean:h6,symbol:m6,nullish:c6,nonNullable:u6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(w6($)))}};class q1 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 rx={matched:!1,value:void 0};function c($){return new Wj($,rx)}class Wj{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))?rx:{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 Wj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Wj(this.input,j?{matched:!0,value:O(this.input,this.input)}:rx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=d6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function d6($){throw new q1($)}var ax,l6=new Uint8Array(16);function Bj(){if(!ax){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ax=crypto.getRandomValues.bind(crypto)}return ax(l6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function f1($,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 ix={};function r6($,O,j){let x;if($)x=b1($.random??$.rng?.()??Bj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Bj();p6(ix,S,K),x=b1(K,ix.msecs,ix.seq,O,j)}return O??f1(x)}function p6($,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 b1($,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 h$=r6;class M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new w(`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 A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Lj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Lj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`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 Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new w(`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)=>M$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return A$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Lj.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 Nj($,O,j,x={}){let S=J(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:Q})=>[Y.id,Q]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:Q})=>Q.database)]){if(!Y)continue;let Q=K.get(Y.id);if(Q)Q.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let Q=K.get(Y)?.values().next().value;if(Q)return Q;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let Q=S.tableDatabases[Y];if(!Q)throw Error(`SQL response is missing the owner of table ${Y}`);return Y$.byId(Z(Q),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let Q of K.get(Y)??[])Q.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:Q})=>({kind:"schema",database:Z(Y),summary:Q})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:Q,tableName:T})=>({kind:Y,table:X(Q),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:Q,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:Q,column:M$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?a6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>A$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,Q])=>({table:X(Y),version:Q})),readVersions:Object.entries(S.readVersions).map(([Y,Q])=>({table:X(Y),version:Q})),truncatedTables:S.truncatedTables,statement:L}}function a6($,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)=>A$.byId(x,S)):[]}}class Uj{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 Uj($,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 tx extends SO{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 zj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:x$.not("relation")},(O)=>O).exhaustive()}var i6={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 n6($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").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})=>i6[O]).with({type:"relation"},()=>"Relation").exhaustive(()=>"Column")}function nx($){return $.map((O)=>({id:h$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function sx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:x$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive(()=>"unknown")}function m$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(sx).join(", ")||"none"}`);return x}class Q$ extends A{access=new o(this.client,"database",this);async fetch(){return J(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 Q$($,O)}static async create($,O){let j=J(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}static async list($){return J(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Nj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?Y$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=m$(await this.applyOps([{kind:"table",table:h$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.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 tx(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(sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>Y$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),J(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}=J(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}=J(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 Y$.byId(this,O.id)}webhookOf($){return Uj.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=J(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=J(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),J(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return J(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 m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:zj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:zj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${n6(O.to)})`,S=h$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:zj(O.to),options:nx(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(!k1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?sx(Z):"none"}`);return M$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=m$(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}=m$(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}=m$(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}=m$(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:zj(O.type),...O.options!==void 0?{options:nx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=m$(await this.applyOps([{kind:"column",table:$.id,column:h$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return M$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:nx(O)}}]),"column","options_added")}}class ex{client;constructor($){this.client=$}query($,O){return Nj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class GO extends A{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 GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=J(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new w(`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 A{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 J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);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 lO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new J$(async()=>J(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new lO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s6=8;class q extends S${async anchors(){return J(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,J(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return lO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return J(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return J(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 W$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(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:$}=J(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}=J(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}=J(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}=J(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 a(async(x)=>{let S=J(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}=J(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=J(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=J(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new SO(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}=J(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=a(async(x)=>{let S=J(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 bO(j,s6,async(x)=>{let{state:S,root:K,replies:Z}=J(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:{...$$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return J(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return J(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:$}=J(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=J(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:l$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ij{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=J(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ij(j.id,j.name))}}class ox{client;async byTeamSlug($){let O=J(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=J(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=J(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,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Ij.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class KO extends A{async fetch(){let{attachment:$}=J(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new KO($,O)}static from($,O){return new KO($,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:$}=J(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends S${access=new o(this.client,"email_thread",this);async followup(){return J(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return J(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return J(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}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?r$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=J(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,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",($)=>U$.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 J(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>KO.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?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return J(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 H$($,O.thread_id)})}class R$ extends A{async fetch(){return J(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=J(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?R$.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",($)=>U$.byId(this.client,$));async operationStatus(){return J(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($){let O=await this.link();await this.mutate((j)=>j.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},headers:{"X-Email-Link-Id":O.id}}))}async transferDraft($){let O=await this.link();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:$,headers:{"X-Email-Link-Id":O.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 H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class YO extends R${async inboxHeaders(){return{"X-Email-Link-Id":(await this.link()).id}}static byId($,O){return new YO($,O)}async update($){let O=await this.inboxHeaders();await this.mutate((j)=>j.email.createDraft({headers:O,body:{draft:{...$0($),db_id:this.id}}}))}async delete(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteDraft({path:{id:this.id},headers:$}))}async schedule($,O){let j=await this.inboxHeaders();await this.mutate((x)=>x.email.upsertScheduledMessage({path:{id:this.id},headers:j,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteScheduledDraft({path:{message_id:this.id},headers:$}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},j=await this.inboxHeaders(),x=await this.mutate((S)=>S.email.addDraftAttachment({path:{id:this.id},headers:j,body:O}));return{attachment:rO.byId(this.client,this,x.attachment_id),uploadUrl:x.upload_url,contentType:x.content_type}}async forwardAttachment($){let O=await this.inboxHeaders(),j=await this.mutate((x)=>x.email.addForwardedAttachment({path:{id:this.id},headers:O,body:{attachment_id:$.id}}));return rO.byId(this.client,this,j.attachment_id,!0)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let O=await this.inboxHeaders();if($.forwarded)await this.mutate((j)=>j.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O}));else await this.mutate((j)=>j.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id)}}class rO{draft;id;forwarded;constructor($,O,j){this.draft=$;this.id=O;this.forwarded=j}static byId($,O,j,x=!1){return new rO(O,j,x)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded}}}function $0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,thread:Z,replyingTo:X,...G}=$;return{...G,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(L)=>String.fromCharCode(L)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,thread_db_id:Z?.id,replying_to_id:X?.id}}class QO extends A{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 QO($,O,void 0,j)}static from($,O,j){return new QO($,O.id,O,j)}async fetch(){let $=J(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new w(`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 e$ extends A{async fetch(){let{labels:$}=J(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`label ${this.id} not found`);return O}static byId($,O){return new e$($,O)}static async list($){let{labels:O}=J(await $.email.listLabels());return O.map((j)=>new e$($,j.id,j))}static async create($,O){let{label:j}=J(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new e$($,j.id)}async delete(){J(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 O0{client;async createDraft($,O){let j=J(await this.client.email.createDraft({body:{draft:$0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return YO.byId(this.client,j.draft.db_id)}draftById($){return YO.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=J(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 YO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return J(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>QO.from(this.client,O,$))}async upsertFilter($,O){return QO.from(this.client,J(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 J(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=J(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:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return KO.byId(this.client,$)}link($){return U$.byId(this.client,$)}links(){return U$.list(this.client)}async connectionProviders(){return J(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return J(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=J(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)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return e$.byId(this.client,$)}labels(){return e$.list(this.client)}createLabel($){return e$.create(this.client,$)}async deleteLabel($){J(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){J(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){J(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return J(await this.client.email.listBlockedSenders()).blocked_emails}}class BO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new BO($,O)}async delete(){J(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class j0{client;constructor($){this.client=$}byId($){return BO.byId(this.client,$)}async create($,O){let j=J(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 BO.byId(this.client,j.id)}}class x0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=J(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return J(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){J(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class o$ extends F${entityType="foreign_entity";async fetch(){return J(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new o$($,O)}static fromRecord($,O){return new o$($,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 g1({login:$,...O}){return{...O,login:$??void 0}}class S0{client;constructor($){this.client=$}byId($){return o$.byId(this.client,$)}async bySource($,O){return o$.fromRecord(this.client,J(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=J(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(g1),assignees:j.map(g1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class u${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new u$($,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 w(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return M$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>JO.byId(this,$.id))}}class JO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new JO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new w(`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 LO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new J$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new w(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new LO($,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 J$(()=>this.load(),$),this}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new w(`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)=>u$.byId(this.form,O.id)):[]}}class Tj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Tj($,O)}}class k$ extends A{async fetch(){return J(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=J(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 k$($,j.form.id,j)}static async list($,O){if(!O)return J(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return J(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.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(($)=>d$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>u$.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)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:x$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??h$(),title:Z.title,description:Z.description??""};return c(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??h$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new 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:x$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:d$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:d$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=A$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:LO.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(J(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=J(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=u$.byId(this,K.question),X=await c(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 JO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Tj.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 Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((Q)=>A$.byId(Y,Q))}}).with({type:x$.union("text","number","boolean","date","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?A$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:LO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?d$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=J(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:d$.byId(this,O.section),count:O.count}))}}async tally(){return J(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=u$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.flatMap((x)=>c(x.value).with({kind:"option"},(S)=>[{count:x.count,value:{kind:"option",option:JO.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 J(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 Z0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends A{static byId($,O){return new NO($,O)}async fetch(){return J(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=J(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new X0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class X0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return J(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class G0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class UO extends A{static byId($,O){return new UO($,O)}async fetch(){return J(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 V$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class pO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new pO($,O)}async claim($){let O=J(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:V$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class K0{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}async list(){return J(await this.client.storage.listHarnesses()).map(($)=>V$.from(this.client,$))}async me(){return V$.from(this.client,J(await this.client.storage.getSelfHarness()))}async deleteSelf(){J(await this.client.storage.deleteSelfHarness())}async agents(){return J(await this.client.storage.listHarnessAgents()).map(($)=>N$.byId(this.client,$.bot_id))}async sessions(){return J(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return UO.byId(this.client,$)}async createPairing($){let O=J(await this.client.storage.createHarnessPairing({body:$}));return{pairing:UO.byId(this.client,O.code),device:pO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var t6="00000001-0000-0000-0000-000000000002",e6="00000001-0000-0000-0002-000000000004";function o6($){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 D$ extends q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,j)}static async forPullRequest($,O){let j=o6(O),{pullRequests:x}=J(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===t6)?.value;return j?.type==="SelectOption"&&j.value.includes(e6)}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 D$($,O.document_id)})}class $O extends A{access=new o(this.client,"initiative",this);static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,O)}async fetch(){return J(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.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?r$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Y0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return J(await this.client.storage.listInitiatives()).initiatives.map(($)=>$O.byId(this.client,$.id))}async create($){return $O.from(this.client,J(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Q0{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async create($){return I$.from(this.client,J(await this.client.storage.meetingCreate({body:$})))}async list(){return J(await this.client.storage.meetingList()).meetings.map(($)=>I$.from(this.client,$))}async active(){return J(await this.client.storage.meetingListActive()).meetings.map(($)=>I$.from(this.client,$))}async lookup($){return I$.from(this.client,J(await this.client.storage.meetingLookup({path:{token:$}})))}}class VO extends A{async fetch(){return J(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new VO($,O)}static from($,O){return new VO($,O.id,O)}static list($,O){return a(async(j)=>{let x=J(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)=>VO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class J0{client;constructor($){this.client=$}byId($){return VO.byId(this.client,$)}list($){return VO.list(this.client,$)}async markSeen($){J(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){J(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){J(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return J(await this.client.notification.getNotificationTypePreferences())}async enableType($){J(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){J(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class V0{client;constructor($){this.client=$}async list(){let{data:$}=J(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){J(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){J(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){J(await this.client.storage.reorderPinsHandler({body:$}))}}class W0{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 zO{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 zO($,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=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){J(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class OO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}async fetch(){return J(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=J(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new OO($,j.id,j)}static byId($,O){return new OO($,O)}static fromRecord($,O){return new OO($,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 J(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return J(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>zO.from(this.client,this.id,O))}async addOption($){let O=J(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return zO.from(this.client,this.id,O)}async updateOption($,O){let j=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return zO.from(this.client,this.id,j)}async deleteOption($){return J(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class B0{client;constructor($){this.client=$}async list($){return J(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 OO.fromRecord(this.client,x)})}create($){return OO.create(this.client,$)}definition($){return OO.byId(this.client,$)}async bulkEntityProperties($){return J(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return J(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 J(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return J(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return J(await this.client.properties.listTags({}))}}function L0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function $7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(L0)})).with({type:"cron"},L0).with({type:"events"},L0).exhaustive()}class jO extends A{static byId($,O){return new jO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new jO($,O.id,O)}async fetch(){return J(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:U0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=J(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>Z$.byId(this.client,O.id)).exhaustive();return $.chat_id?Z$.byId(this.client,$.chat_id):void 0}async history(){return J(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{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 U0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,trigger:$7($.trigger),task:{...O}}}class z0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async create($){return jO.from(this.client,J(await this.client.scheduledAction.createScheduledAction({body:{...U0($),enabled:$.enabled??!0}})))}async list($){return J(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>jO.from(this.client,O))}}class I0{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class T0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}current(){return T$.current(this.client)}list(){return T$.list(this.client)}}class H0{client;constructor($){this.client=$}async get($){return J(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return J(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class R0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class xO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return J(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=J(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new xO($,j.id,j,j.signing_secret)}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class D0{client;constructor($){this.client=$}create($){return xO.create(this.client,$)}byId($){return xO.byId(this.client,$)}async list(){let{webhooks:$}=J(await this.client.storage.listWebhooks());return $.map((O)=>xO.fromRecord(this.client,O))}}function C0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function y1($,O,j){let x=[];for(let S of C0(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:Z$.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:H$.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 g$($,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:K$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:z$.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:o$.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 v1="00000000-0000-0000-0000-000000000000",_0={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"]},Hj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),h1=($,O)=>$==null?O:{"&":[$,O]};function M0($,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==="!"){M0(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)=>{M0(Z,`${O}.${S}[${X}]`)})}class Rj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(J),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(_0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(_0).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)M0($[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:v1}},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}=J(await this.client.email.listLinks()),K=S.filter((X)=>Hj(X.email_address)===Hj(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=h1(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(_0))if(!x.includes(S))O[K]={l:{[Z]:v1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Hj(Y.label)===Hj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}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=h1(O.propf,X)}return O}}class A0{client;constructor($){this.client=$}async page($={}){let O=new Rj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Rj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=J(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>C0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>y1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function m1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let r of g){let p=r.split(`
@@ -59,4 +59,4 @@ async function bO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre
`);U=g.pop()??"";for(let r of g){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))Q=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:Q,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}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"&"}},Cx=({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 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)}`},_x=({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(([Y,Q])=>{G=[...G,Y,$?Q:encodeURIComponent(Q)]});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])=>EO({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,Cx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,_x({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},$6=({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 U1($){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 O6=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 j6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x6=({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=Cx({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=_x({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("&")}},S6=($)=>{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 Z6($){for(let O of $.security??[]){if(t5($,O.name))continue;let j=await O6(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=($)=>$6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x6($.querySerializer),url:$.url}),I1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ax($.headers,O.headers),j},e5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ax=(...$)=>{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 Mx{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 X6=()=>({error:new Mx,request:new Mx,response:new Mx}),o5=x6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$4={"Content-Type":"application/json"},Zj=($={})=>({...j6,headers:$4,parseAs:"auto",querySerializer:o5,...$});var T1=($={})=>{let O=I1(Zj(),$),j=()=>({...O}),x=(Y)=>{return O=I1(O,Y),j()},S=X6(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Ax(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await Z6(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=z1(T);return{opts:T,url:z}},Z=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:U1(V)};z=new Request(B,I);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"?S6(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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=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(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(Q)=>Z({...Q,method:Y}),G=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return o2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:U1(T),url:z})};return{buildUrl:(Y)=>z1({...O,...Y}),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=T1(Zj());class K6{client;constructor($){this.client=$?.client??G6}}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 Px extends K6{static __registry=new Y6;constructor($){super($);Px.__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 Q6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},H1={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:8085",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8099","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function O4($,O){let j=O?.channel_id;return O&&j?{channel:f.byId($,j),thread:new g$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function P$($,O){return{session:i.byId($,O.session_id),owner:M.byId($,O.owner_id),...O4($,O.origin)}}function wO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function qO($,O){return O?M.byId($,O):void 0}function J6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...P$($,j.identity),actor:qO($,j.last_turn?.actor),announcement:wO($,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,...P$($,j.identity),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...P$($,j.identity),mentionedBy:qO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>M.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...P$($,j.identity),actor:qO($,j.turn_in_flight?.actor),announcement:wO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...P$($,j.identity)})).exhaustive()}var V6="macro|";function C$($,O){return O.startsWith(V6)&&O.length>V6.length?M.byId($,O.toLowerCase()):void 0}function W6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:f.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:f.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive()}function B6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive()}function fO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:K$.byId($,x.id),message:v$.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 g$($,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 L6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:fO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:fO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:fO($,j),actor:C$($,j.actor)})).exhaustive()}async function N6($){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 j4="webhook.validation.test";function x4($,O){return c(O).with({event_type:x$.string.startsWith("document.")},(j)=>B6($,j)).with({event_type:x$.string.startsWith("channel.")},(j)=>W6($,j)).with({event_type:x$.string.startsWith("message.")},(j)=>L6($,j)).with({event_type:x$.string.startsWith("agent_session.")},(j)=>J6($,j)).otherwise(()=>{return})}class R1{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 N6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new b("invalid webhook signature");if(O.event===j4)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=x4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function U6(){return}var S4=0,D1;function Z4($){D1=$}function L$($,O,j){if(!j&&!D1)return $;let x=(S)=>{for(let K of[D1,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:++S4,service:O,operation:K};x({...L,status:"started"});try{let Y=await Reflect.apply(X,S,G),Q=Y!==null&&typeof Y==="object"&&"error"in Y&&Y.error!=null;return x({...L,status:Q?"failed":"completed"}),Y}catch(Y){throw x({...L,status:"failed"}),Y}}}})}var I6="x-macro-user-api-key",X4="mak_",C1="mbot_";function G4($){return c($).with(x$.string.startsWith(C1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(x$.string.startsWith(X4),(O)=>[I6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function z6($){return typeof $==="function"?await $():$}async function K4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await z6(x.token);if(!S.startsWith(C1))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:x$.string},({apiKey:x})=>{if(x.startsWith(C1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[I6,x]]}).with({type:"user"},async({token:x})=>{return[G4(await z6(x))]}).exhaustive()}class _1{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"?U6():void 0,x={...H1[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??Q6[O],this.authConfig=Q4($),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=L$(new Wx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=L$(new Px({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=L$(new Aj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=L$(new qj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=L$(new yj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=L$(new uj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=L$(new aj({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=L$(new ej({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=L$(new xx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=L$(new Kx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=L$(new zx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=L$(new Dx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new R1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new yO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):M.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Sj({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 Y4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in H1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function Q4($){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 M1{id;constructor($){this.id=$}static byId($){return new M1($)}toJSON(){return{id:this.id}}}class T6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new _1($);this._client=O,this.routines=new z0(O),this.unfurls=new H0(O),this.agents=new fx(O),this.initiatives=new Y0(O),this.apiKeys=new kx(O),this.harnesses=new K0(O),this.meetings=new Q0(O),this.githubPullRequests=new G0(O),this.entityMentions=new j0(O),this.agentSessions=new qx(O),this.ai=new bx(O),this.bots=new yO(O),this.calendar=new gx(O),this.calls=new yx(O),this.channels=new hx(O),this.chats=new mx(O),this.crm=new ux(O),this.databases=new ex(O),this.documents=new ox(O),this.email=new O0(O),this.favorites=new x0(O),this.foreignEntities=new S0(O),this.forms=new Z0(O),this.notifications=new J0(O),this.pins=new V0(O),this.projects=new W0(O),this.properties=new B0(O),this.tasks=new I0(O),this.teams=new T0(O),this.users=new R0(O),this.webhooks=new D0(O),this.workspace=new A0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new T6({...this.opts,requestedAs:$.id})}}export{l$ as wrapXml,$$ as toBody,Z4 as observeRequests,D6 as msg,R6 as here,p$ as UserApiKey,gO as ToolApproval,B$ as SessionReview,N0 as RoutineExecution,jO as Routine,wx as ReviewItem,X0 as PullRequestChangeset,Qj as PipelineTable,XO as PipelineRow,Jj as PipelineColumn,W$ as MessageThread,I$ as Meeting,tx as MacroOpRefusedError,T6 as Macro,$O as Initiative,UO as HarnessPairing,V$ as Harness,NO as GithubPullRequest,d$ as FormSection,LO as FormResponse,Tj as FormReference,u$ as FormQuestion,JO as FormOption,k$ as Form,BO as EntityMention,o as EntityAccess,QO as EmailFilter,YO as EmailDraft,rO as DraftAttachment,lO as DocumentVersion,GO as DocumentAnchor,pO as DevicePairing,a$ as CrmPipeline,Ex as ConversationTurn,kO as CodeExecution,mO as ChatMessage,hO as ChatGeneration,M1 as ChannelPicture,ZO as ChannelActivity,Gj as AgentConversation,N$ as Agent,WO as AccessRequest};
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:Q,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}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"&"}},Cx=({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 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)}`},_x=({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(([Y,Q])=>{G=[...G,Y,$?Q:encodeURIComponent(Q)]});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])=>EO({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,Cx({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,_x({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},$6=({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 U1($){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 O6=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 j6={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var x6=({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=Cx({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=_x({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("&")}},S6=($)=>{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 Z6($){for(let O of $.security??[]){if(t5($,O.name))continue;let j=await O6(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=($)=>$6({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:x6($.querySerializer),url:$.url}),I1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Ax($.headers,O.headers),j},e5=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Ax=(...$)=>{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 Mx{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 X6=()=>({error:new Mx,request:new Mx,response:new Mx}),o5=x6({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),$4={"Content-Type":"application/json"},Zj=($={})=>({...j6,headers:$4,parseAs:"auto",querySerializer:o5,...$});var T1=($={})=>{let O=I1(Zj(),$),j=()=>({...O}),x=(Y)=>{return O=I1(O,Y),j()},S=X6(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Ax(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await Z6(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=z1(T);return{opts:T,url:z}},Z=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:U1(V)};z=new Request(B,I);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"?S6(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 H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=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(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(Q)=>Z({...Q,method:Y}),G=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return o2({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:U1(T),url:z})};return{buildUrl:(Y)=>z1({...O,...Y}),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=T1(Zj());class K6{client;constructor($){this.client=$?.client??G6}}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 Px extends K6{static __registry=new Y6;constructor($){super($);Px.__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 Q6={dev:"https://dev.macro.com",prod:"https://macro.com",local:"http://localhost:3000"},H1={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:8085",notification:"http://localhost:8089",properties:"http://localhost:8086",search:"http://localhost:8086","scheduled-action":"http://localhost:8099","static-files":"http://localhost:8100",connection:"http://localhost:8082",contacts:"http://localhost:8083",unfurl:"http://localhost:8095"}};function O4($,O){let j=O?.channel_id;return O&&j?{channel:f.byId($,j),thread:new g$($,j,O.thread_id)}:{channel:void 0,thread:void 0}}function P$($,O){return{session:i.byId($,O.session_id),owner:M.byId($,O.owner_id),...O4($,O.origin)}}function wO($,O,j){let x=O.origin?.channel_id;return x&&j?e.byId($,x,j):void 0}function qO($,O){return O?M.byId($,O):void 0}function J6($,O){return c(O).with({event_type:"agent_session.opened"},({metadata:j})=>({event_type:"agent_session.opened",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.turn_started"},({metadata:j})=>({event_type:"agent_session.turn_started",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.turn_ended"},({metadata:j})=>({event_type:"agent_session.turn_ended",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.command_rejected"},({metadata:j})=>({event_type:"agent_session.command_rejected",metadata:j,...P$($,j.identity),actor:qO($,j.actor),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.settled"},({metadata:j})=>({event_type:"agent_session.settled",metadata:j,...P$($,j.identity),actor:qO($,j.last_turn?.actor),announcement:wO($,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,...P$($,j.identity),announcement:wO($,j.identity,j.announcement_message_id)})).with({event_type:"agent_session.input_received"},({metadata:j})=>({event_type:"agent_session.input_received",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.mentioned"},({metadata:j})=>({event_type:"agent_session.mentioned",metadata:j,...P$($,j.identity),mentionedBy:qO($,j.mentioned_by),mentioned:j.mentioned.map((x)=>M.byId($,x))})).with({event_type:"agent_session.stopped"},({metadata:j})=>({event_type:"agent_session.stopped",metadata:j,...P$($,j.identity),actor:qO($,j.turn_in_flight?.actor),announcement:wO($,j.identity,j.turn_in_flight?.announcement_message_id)})).with({event_type:"agent_session.renamed"},({metadata:j})=>({event_type:"agent_session.renamed",metadata:j,...P$($,j.identity)})).with({event_type:"agent_session.deleted"},({metadata:j})=>({event_type:"agent_session.deleted",metadata:j,...P$($,j.identity)})).exhaustive((j)=>{console.warn("macro sdk: unknown agent session event",j);return})}var V6="macro|";function C$($,O){return O.startsWith(V6)&&O.length>V6.length?M.byId($,O.toLowerCase()):void 0}function W6($,O){return c(O).with({event_type:"channel.created"},({metadata:j})=>({event_type:"channel.created",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor),participants:j.participant_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.updated"},({metadata:j})=>({event_type:"channel.updated",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.deleted"},({metadata:j})=>({event_type:"channel.deleted",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.picture_changed"},({metadata:j})=>({event_type:"channel.picture_changed",metadata:j,channel:f.byId($,j.channel_id),actor:C$($,j.actor)})).with({event_type:"channel.participant_added"},({metadata:j})=>({event_type:"channel.participant_added",metadata:j,channel:f.byId($,j.channel_id),addedBy:C$($,j.added_by),addedUsers:j.added_user_ids.map((x)=>M.byId($,x))})).with({event_type:"channel.participant_removed"},({metadata:j})=>({event_type:"channel.participant_removed",metadata:j,channel:f.byId($,j.channel_id),removedBy:M.byId($,j.removed_by),removedUsers:j.removed_user_ids.map((x)=>M.byId($,x))})).exhaustive((j)=>{console.warn("macro sdk: unknown channel event",j);return})}function B6($,O){return c(O).with({event_type:"document.created"},({metadata:j})=>({event_type:"document.created",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.updated"},({metadata:j})=>({event_type:"document.updated",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0,previousProject:j.previous_project_id?n.byId($,j.previous_project_id):void 0})).with({event_type:"document.deleted"},({metadata:j})=>({event_type:"document.deleted",metadata:j,document:q.byId($,j.document_id),actor:j.actor_user_id?M.byId($,j.actor_user_id):void 0,project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.content_uploaded"},({metadata:j})=>({event_type:"document.content_uploaded",metadata:j,document:q.byId($,j.document_id),owner:M.byId($,j.owner)})).with({event_type:"document.sync_content_updated"},({metadata:j})=>({event_type:"document.sync_content_updated",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.purged"},({metadata:j})=>({event_type:"document.purged",metadata:j,document:q.byId($,j.document_id)})).with({event_type:"document.copied"},({metadata:j})=>({event_type:"document.copied",metadata:j,document:q.byId($,j.document_id),sourceDocument:q.byId($,j.source_document_id),owner:M.byId($,j.owner),project:j.project_id?n.byId($,j.project_id):void 0})).with({event_type:"document.interaction"},({metadata:j})=>({event_type:"document.interaction",metadata:j,document:q.byId($,j.document_id)})).exhaustive((j)=>{console.warn("macro sdk: unknown document event",j);return})}function fO($,O,j=[]){let x=O.parent;if(x.type==="call")return{type:"call",call:K$.byId($,x.id),message:v$.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 g$($,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 L6($,O){return c(O).with({event_type:"message.posted"},({metadata:j})=>({event_type:"message.posted",metadata:j,target:fO($,j,j.mentions),sender:C$($,j.sender)})).with({event_type:"message.mentioned"},({metadata:j})=>({event_type:"message.mentioned",metadata:j,target:fO($,j),sender:C$($,j.sender)})).with({event_type:"message.patched"},({metadata:j})=>({event_type:"message.patched",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.deleted"},({metadata:j})=>({event_type:"message.deleted",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_created"},({metadata:j})=>({event_type:"message.attachment_created",metadata:j,target:fO($,j),actor:C$($,j.actor)})).with({event_type:"message.attachment_removed"},({metadata:j})=>({event_type:"message.attachment_removed",metadata:j,target:fO($,j),actor:C$($,j.actor)})).exhaustive((j)=>{console.warn("macro sdk: unknown message event",j);return})}async function N6($){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 j4="webhook.validation.test";function x4($,O){return c(O).with({event_type:x$.string.startsWith("document.")},(j)=>B6($,j)).with({event_type:x$.string.startsWith("channel.")},(j)=>W6($,j)).with({event_type:x$.string.startsWith("message.")},(j)=>L6($,j)).with({event_type:x$.string.startsWith("agent_session.")},(j)=>J6($,j)).otherwise(()=>{return})}class R1{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 N6({secret:this.secret,timestamp:O.timestamp??"",rawBody:$,signature:O.signature??""}))throw new b("invalid webhook signature");if(O.event===j4)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=x4(this.client,j);if(!S)return;await Promise.all([...x].map((K)=>K(S)))}}function U6(){return}var S4=0,D1;function Z4($){D1=$}function L$($,O,j){if(!j&&!D1)return $;let x=(S)=>{for(let K of[D1,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:++S4,service:O,operation:K};x({...L,status:"started"});try{let Y=await Reflect.apply(X,S,G),Q=Y!==null&&typeof Y==="object"&&"error"in Y&&Y.error!=null;return x({...L,status:Q?"failed":"completed"}),Y}catch(Y){throw x({...L,status:"failed"}),Y}}}})}var I6="x-macro-user-api-key",X4="mak_",C1="mbot_";function G4($){return c($).with(x$.string.startsWith(C1),()=>{throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.")}).with(x$.string.startsWith(X4),(O)=>[I6,O]).otherwise((O)=>["Authorization",`Bearer ${O}`])}async function z6($){return typeof $==="function"?await $():$}async function K4($,O,j){return c($).with({type:"bot"},async(x)=>{let S=await z6(x.token);if(!S.startsWith(C1))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:x$.string},({apiKey:x})=>{if(x.startsWith(C1))throw Error("bot token passed as a user credential. Use auth: { type: 'bot', token } or MACRO_BOT_TOKEN.");return[[I6,x]]}).with({type:"user"},async({token:x})=>{return[G4(await z6(x))]}).exhaustive()}class _1{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"?U6():void 0,x={...H1[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??Q6[O],this.authConfig=Q4($),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=L$(new Wx({client:this.makeClient(x["scheduled-action"])}),"scheduled-action",$.onRequest),this.unfurl=L$(new Px({client:this.makeClient(x.unfurl)}),"unfurl",$.onRequest),this.agentHarness=L$(new Aj({client:this.makeClient(x["agent-harness"])}),"agent-harness",$.onRequest),this.auth=L$(new qj({client:this.makeClient(x.auth)}),"auth",$.onRequest),this.calendar=L$(new yj({client:this.makeClient(x.calendar)}),"calendar",$.onRequest),this.cognition=L$(new uj({client:this.makeClient(x.cognition)}),"cognition",$.onRequest),this.contacts=L$(new aj({client:this.makeClient(x.contacts)}),"contacts",$.onRequest),this.email=L$(new ej({client:this.makeClient(x.email)}),"email",$.onRequest),this.notification=L$(new xx({client:this.makeClient(x.notification)}),"notification",$.onRequest),this.properties=L$(new Kx({client:this.makeClient(x.properties)}),"properties",$.onRequest),this.search=L$(new zx({client:this.makeClient(x.search)}),"search",$.onRequest),this.storage=L$(new Dx({client:this.makeClient(x.storage)}),"storage",$.onRequest);let K=typeof process<"u"?{}.MACRO_WEBHOOK_SECRET:void 0,Z=$.webhookSecret??K;this.events=new R1(this,Z)}hasActingUser(){return this.authConfig.type==="user"||this.requestedAs!==void 0}selfBot(){return this.selfBotRecord??=new yO(this).me().catch(($)=>{throw this.selfBotRecord=void 0,$}),this.selfBotRecord}myPrincipalId(){return this.selfPrincipal??=(this.authConfig.type==="bot"?this.selfBot().then(($)=>`bot|${$.id}`):M.me(this).then(($)=>$.id)).catch(($)=>{throw this.selfPrincipal=void 0,$}),this.selfPrincipal}makeClient($){let O=Sj({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 Y4($){if($.env)return $.env;let O=typeof process<"u"?{}.MACRO_ENV:void 0;if(!O)return"prod";if(!(O in H1))throw Error(`invalid MACRO_ENV "${O}" — expected local, dev, or prod`);return O}function Q4($){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 M1{id;constructor($){this.id=$}static byId($){return new M1($)}toJSON(){return{id:this.id}}}class T6{routines;unfurls;agents;initiatives;apiKeys;harnesses;meetings;githubPullRequests;entityMentions;agentSessions;ai;bots;calendar;calls;channels;chats;crm;databases;documents;email;favorites;foreignEntities;forms;notifications;pins;projects;properties;tasks;teams;users;webhooks;workspace;events;webAppUrl;_client;opts;constructor($){this.opts=$;let O=new _1($);this._client=O,this.routines=new z0(O),this.unfurls=new H0(O),this.agents=new fx(O),this.initiatives=new Y0(O),this.apiKeys=new kx(O),this.harnesses=new K0(O),this.meetings=new Q0(O),this.githubPullRequests=new G0(O),this.entityMentions=new j0(O),this.agentSessions=new qx(O),this.ai=new bx(O),this.bots=new yO(O),this.calendar=new gx(O),this.calls=new yx(O),this.channels=new hx(O),this.chats=new mx(O),this.crm=new ux(O),this.databases=new ex(O),this.documents=new ox(O),this.email=new O0(O),this.favorites=new x0(O),this.foreignEntities=new S0(O),this.forms=new Z0(O),this.notifications=new J0(O),this.pins=new V0(O),this.projects=new W0(O),this.properties=new B0(O),this.tasks=new I0(O),this.teams=new T0(O),this.users=new R0(O),this.webhooks=new D0(O),this.workspace=new A0(O),this.events=O.events,this.webAppUrl=O.webAppUrl}myPrincipalId(){return this._client.myPrincipalId()}requestedAs($){return new T6({...this.opts,requestedAs:$.id})}}export{l$ as wrapXml,$$ as toBody,Z4 as observeRequests,D6 as msg,R6 as here,p$ as UserApiKey,gO as ToolApproval,B$ as SessionReview,N0 as RoutineExecution,jO as Routine,wx as ReviewItem,X0 as PullRequestChangeset,Qj as PipelineTable,XO as PipelineRow,Jj as PipelineColumn,W$ as MessageThread,I$ as Meeting,tx as MacroOpRefusedError,T6 as Macro,$O as Initiative,UO as HarnessPairing,V$ as Harness,NO as GithubPullRequest,d$ as FormSection,LO as FormResponse,Tj as FormReference,u$ as FormQuestion,JO as FormOption,k$ as Form,BO as EntityMention,o as EntityAccess,QO as EmailFilter,YO as EmailDraft,rO as DraftAttachment,lO as DocumentVersion,GO as DocumentAnchor,pO as DevicePairing,a$ as CrmPipeline,Ex as ConversationTurn,kO as CodeExecution,mO as ChatMessage,hO as ChatGeneration,M1 as ChannelPicture,ZO as ChannelActivity,Gj as AgentConversation,N$ as Agent,WO as AccessRequest};
diff --git a/docs/guides/add-entity.md b/docs/guides/add-entity.md
index 024f9e3d38..61c87bc97f 100644
--- a/docs/guides/add-entity.md
+++ b/docs/guides/add-entity.md
@@ -411,8 +411,11 @@ adapter translates legacy block state into feature context (FE-34).
`rules/ast-grep/{ts,tsx}-feature-*.yml` files.
**Exhaustiveness.** New branches on a kind use `match().exhaustive()` or a
-`Record<Kind, ...>`, never `.otherwise`, `P._`, `default`, or `switch`. Never cast
-a string to `ItemType`; parse it with `stringToItemType` (FE-31, enforced by
+`Record<Kind, ...>`, never `.otherwise`, `P._`, `default`, or `switch`. Where the
+kind arrives from the wire (queries, service clients, workers, SDK hydrators),
+pass a fallback, `.exhaustive((unknown) => fallback)`, so older clients survive
+the new kind (FE-35). Never cast a string to `ItemType` or an `EntityType`; parse
+it with `stringToItemType` or `parseEntityType` (FE-31, enforced by
`rules/ast-grep/ts-no-item-type-cast.yml`). Existing catch-alls hide the new kind,
so grep for the sibling kind.
diff --git a/packages/collaboration/src/collab/engine.ts b/packages/collaboration/src/collab/engine.ts
index 6dbc0ae6c9..693a52270d 100644
--- a/packages/collaboration/src/collab/engine.ts
+++ b/packages/collaboration/src/collab/engine.ts
@@ -149,7 +149,9 @@ export class SyncEngine<S extends GenericRootSchema, D> {
.with({ type: 'awareness' }, (m) =>
this.awareness.importRemoteAwareness(m.data)
)
- .exhaustive()
+ .exhaustive(() =>
+ this.log('warn', 'engine.chatter: unknown message ignored')
+ )
);
this._isRunning = true;
diff --git a/packages/collaboration/src/websocket/core/websocket.ts b/packages/collaboration/src/websocket/core/websocket.ts
index f055cd9578..b320007c43 100644
--- a/packages/collaboration/src/websocket/core/websocket.ts
+++ b/packages/collaboration/src/websocket/core/websocket.ts
@@ -679,7 +679,7 @@ export class Websocket<Send = WebsocketData, Receive = WebsocketData> {
this.dispatchEvent(type, event);
}
)
- .exhaustive();
+ .exhaustive(() => undefined);
}
/**
diff --git a/packages/sdk/src/entities/databases/database.ts b/packages/sdk/src/entities/databases/database.ts
index c10b22d3fe..f8cb9df147 100644
--- a/packages/sdk/src/entities/databases/database.ts
+++ b/packages/sdk/src/entities/databases/database.ts
@@ -198,7 +198,7 @@ function typeLabel(type: ColumnType): string {
.with({ type: 'tag' }, () => 'Tag')
.with({ type: 'entity' }, ({ target }) => entityLabels[target])
.with({ type: 'relation' }, () => 'Relation')
- .exhaustive();
+ .exhaustive(() => 'Column');
}
function newOptions(labels: string[]): NewOption[] {
@@ -226,7 +226,7 @@ function resultName(result: OpResult): string {
{ kind: P.union('table', 'column', 'rows', 'view') },
({ kind, change }) => `${kind}.${change.kind}`,
)
- .exhaustive();
+ .exhaustive(() => 'unknown');
}
/** The one result of a one-op batch, which must be what the op answers. */
diff --git a/packages/sdk/src/entities/forms/form.ts b/packages/sdk/src/entities/forms/form.ts
index fe2b6a1922..65db66dc80 100644
--- a/packages/sdk/src/entities/forms/form.ts
+++ b/packages/sdk/src/entities/forms/form.ts
@@ -541,7 +541,11 @@ export class Form extends MacroEntity<FormDetail> {
},
(cell) => cell,
)
- .exhaustive();
+ .exhaustive(() => {
+ throw new MacroError(
+ `answer to question ${question.id} has a type this SDK doesn't know`,
+ );
+ });
return { question, value };
}),
);
@@ -594,16 +598,25 @@ export class Form extends MacroEntity<FormDetail> {
return {
question,
responses: entry.responses,
- buckets: entry.buckets.map((bucket) => ({
- count: bucket.count,
- value: match(bucket.value)
- .with({ kind: 'option' }, (value) => ({
- kind: 'option' as const,
- option: FormOption.byId(question, value.option),
- }))
- .with({ kind: 'checkbox' }, (value) => value)
- .exhaustive(),
- })),
+ buckets: entry.buckets.flatMap((bucket): FormQuestionTally['buckets'] =>
+ match(bucket.value)
+ .with({ kind: 'option' }, (value) => [
+ {
+ count: bucket.count,
+ value: {
+ kind: 'option' as const,
+ option: FormOption.byId(question, value.option),
+ },
+ },
+ ])
+ .with({ kind: 'checkbox' }, (value) => [
+ { count: bucket.count, value },
+ ])
+ .exhaustive((unknown) => {
+ console.warn('macro sdk: unknown form tally bucket', unknown);
+ return [];
+ }),
+ ),
};
});
}
diff --git a/packages/sdk/src/events/hydrate/agentSession.ts b/packages/sdk/src/events/hydrate/agentSession.ts
index 6ef2c3ecb4..9a63f80103 100644
--- a/packages/sdk/src/events/hydrate/agentSession.ts
+++ b/packages/sdk/src/events/hydrate/agentSession.ts
@@ -163,5 +163,8 @@ export function hydrateAgentSessionEvent(
metadata,
...sessionHandles(client, metadata.identity),
}))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('macro sdk: unknown agent session event', unknown);
+ return undefined;
+ });
}
diff --git a/packages/sdk/src/events/hydrate/channel.ts b/packages/sdk/src/events/hydrate/channel.ts
index 747563f2f3..5fc3e52c4f 100644
--- a/packages/sdk/src/events/hydrate/channel.ts
+++ b/packages/sdk/src/events/hydrate/channel.ts
@@ -72,5 +72,8 @@ export function hydrateChannelEvent(client: MacroClient, event: ChannelEvent) {
User.byId(client, userId),
),
}))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('macro sdk: unknown channel event', unknown);
+ return undefined;
+ });
}
diff --git a/packages/sdk/src/events/hydrate/document.ts b/packages/sdk/src/events/hydrate/document.ts
index 4fa376277c..e49dd909a7 100644
--- a/packages/sdk/src/events/hydrate/document.ts
+++ b/packages/sdk/src/events/hydrate/document.ts
@@ -82,5 +82,8 @@ export function hydrateDocumentEvent(
metadata,
document: Document.byId(client, metadata.document_id),
}))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('macro sdk: unknown document event', unknown);
+ return undefined;
+ });
}
diff --git a/packages/sdk/src/events/hydrate/message.ts b/packages/sdk/src/events/hydrate/message.ts
index 93f3505cf9..8e61d359d2 100644
--- a/packages/sdk/src/events/hydrate/message.ts
+++ b/packages/sdk/src/events/hydrate/message.ts
@@ -123,5 +123,8 @@ export function hydrateMessageEvent(client: MacroClient, event: MessageEvent) {
target: target(client, metadata),
actor: userFromPrincipal(client, metadata.actor),
}))
- .exhaustive();
+ .exhaustive((unknown) => {
+ console.warn('macro sdk: unknown message event', unknown);
+ return undefined;
+ });
}
diff --git a/packages/sdk/tests/agent-session-hydrate.test.ts b/packages/sdk/tests/agent-session-hydrate.test.ts
index 7332c0643a..cc4d70cd1d 100644
--- a/packages/sdk/tests/agent-session-hydrate.test.ts
+++ b/packages/sdk/tests/agent-session-hydrate.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import type { AgentSessionLifecycleEvent } from '../generated/storage/types.gen';
import { hydrateAgentSessionEvent } from '../src/events/hydrate/agentSession';
import type { MacroClient } from '../src/utils/client';
@@ -41,8 +41,8 @@ const settled: AgentSessionLifecycleEvent = {
describe('hydrateAgentSessionEvent', () => {
test('settled hands out the session, owner, origin, chip, and actor', () => {
const event = hydrateAgentSessionEvent(client, settled);
- if (event.event_type !== 'agent_session.settled')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.settled')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.owner.id).toBe(identity.owner_id);
@@ -64,8 +64,8 @@ describe('hydrateAgentSessionEvent', () => {
question: 'Tea or coffee?',
},
});
- if (event.event_type !== 'agent_session.waiting_for_input')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.waiting_for_input')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.channel).toBeUndefined();
@@ -91,8 +91,8 @@ describe('hydrateAgentSessionEvent', () => {
event_type: 'agent_session.command_rejected',
metadata,
});
- if (event.event_type !== 'agent_session.command_rejected')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.command_rejected')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.owner.id).toBe(identity.owner_id);
@@ -116,8 +116,8 @@ describe('hydrateAgentSessionEvent', () => {
},
},
});
- if (event.event_type !== 'agent_session.command_rejected')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.command_rejected')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.owner.id).toBe(identity.owner_id);
@@ -133,8 +133,8 @@ describe('hydrateAgentSessionEvent', () => {
event_type: 'agent_session.deleted',
metadata: { identity },
});
- if (event.event_type !== 'agent_session.deleted')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.deleted')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.owner.id).toBe(identity.owner_id);
@@ -151,8 +151,8 @@ describe('hydrateAgentSessionEvent', () => {
mentioned: ['macro|[email protected]', 'macro|[email protected]'],
},
});
- if (event.event_type !== 'agent_session.mentioned')
- throw new Error(event.event_type);
+ if (event?.event_type !== 'agent_session.mentioned')
+ throw new Error(event?.event_type);
expect(event.session.id).toBe(identity.session_id);
expect(event.mentionedBy?.id).toBe('macro|[email protected]');
@@ -161,4 +161,15 @@ describe('hydrateAgentSessionEvent', () => {
]);
});
+
+ test('an event type from a newer server is skipped instead of throwing', () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const fromNewerServer = JSON.parse(
+ '{"event_type":"agent_session.paused","metadata":{}}',
+ );
+
+ expect(hydrateAgentSessionEvent(client, fromNewerServer)).toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
});
diff --git a/packages/sdk/tests/channel-principal.test.ts b/packages/sdk/tests/channel-principal.test.ts
index 0718032e89..db6aab9f1a 100644
--- a/packages/sdk/tests/channel-principal.test.ts
+++ b/packages/sdk/tests/channel-principal.test.ts
@@ -1,5 +1,8 @@
-import { describe, expect, test } from 'bun:test';
-import { userFromPrincipal } from '../src/events/hydrate/channel';
+import { describe, expect, spyOn, test } from 'bun:test';
+import {
+ hydrateChannelEvent,
+ userFromPrincipal,
+} from '../src/events/hydrate/channel';
import type { MacroClient } from '../src/utils/client';
const client = {} as MacroClient;
@@ -27,3 +30,16 @@ describe('userFromPrincipal', () => {
}
});
});
+
+describe('hydrateChannelEvent', () => {
+ test('an event type from a newer server is skipped instead of throwing', () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const fromNewerServer = JSON.parse(
+ '{"event_type":"channel.archived","metadata":{}}',
+ );
+
+ expect(hydrateChannelEvent(client, fromNewerServer)).toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
+});
diff --git a/packages/sdk/tests/messages.test.ts b/packages/sdk/tests/messages.test.ts
index 5a74a1b0b5..9e7fd94dbb 100644
--- a/packages/sdk/tests/messages.test.ts
+++ b/packages/sdk/tests/messages.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, spyOn, test } from 'bun:test';
import type {
Bot,
Message,
@@ -126,7 +126,7 @@ describe('shared message API contracts', () => {
mentions: [],
},
});
- if (event.target.type !== 'call') throw new Error(event.target.type);
+ if (event?.target.type !== 'call') throw new Error(event?.target.type);
expect(requests).toHaveLength(0);
expect(event.target.call.id).toBe(callId);
expect(event.target.threadId).toBe(callId);
@@ -164,6 +164,19 @@ describe('shared message API contracts', () => {
});
});
+ test('a message event type from a newer server is skipped instead of throwing', () => {
+ const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const fromNewerServer = JSON.parse(
+ '{"event_type":"message.pinned","metadata":{}}',
+ );
+
+ expect(
+ hydrateMessageEvent(macro()._client, fromNewerServer),
+ ).toBeUndefined();
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockRestore();
+ });
+
test('channel posts, lazy reads, edits, reactions, and deletes use message routes', async () => {
let record = message();
const path = `/messages/channel/${channelId}`;
diff --git a/rules/ast-grep/ts-exhaustive-boundary-fallback.yml b/rules/ast-grep/ts-exhaustive-boundary-fallback.yml
new file mode 100644
index 0000000000..edca850141
--- /dev/null
+++ b/rules/ast-grep/ts-exhaustive-boundary-fallback.yml
@@ -0,0 +1,33 @@
+id: ts-exhaustive-boundary-fallback
+language: typescript
+# Twin of tsx-exhaustive-boundary-fallback — ast-grep rules are
+# single-language, and `tsx` only scans .tsx files.
+severity: error
+message: Pass a fallback to .exhaustive() in boundary code — `.exhaustive((unknown) => fallback)`; a bare .exhaustive() throws on a variant this build doesn't know.
+note: |-
+ Rule FE-35 in docs/development/style-guide.md. ts-pattern's .exhaustive() is
+ a compile-time completeness check that also throws at runtime ("no pattern
+ matches value X"). Wire adapters, service clients, transports, workers, and
+ event hydrators match on values another service, app version, or native
+ plugin produced, so a new variant crashes every older client.
+ `.exhaustive(fallback)` keeps the compile-time check and returns the fallback
+ instead of throwing. Parse the value into a closed client type first if the
+ match must not fall back.
+files:
+ - apps/web/src/**/queries/**
+ - apps/web/src/**/queries.ts
+ - apps/web/src/lib/service-clients/**
+ - apps/web/src/**/workers/**
+ - apps/web/src/**/worker/**
+ - apps/web/src/**/*.worker.ts
+ - packages/collaboration/src/websocket/**
+ - packages/sdk/src/events/hydrate/**
+ignores:
+ - '**/*.test.ts'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/browser-test/**'
+ # Being rewritten by the Tauri IPC teardown fix (#8207); drop once it lands.
+ - packages/collaboration/src/websocket/platform/tauri-websocket.ts
+rule:
+ pattern: $MATCH.exhaustive()
diff --git a/rules/ast-grep/ts-no-item-type-cast.yml b/rules/ast-grep/ts-no-item-type-cast.yml
index 26a8b409e5..a03891f94d 100644
--- a/rules/ast-grep/ts-no-item-type-cast.yml
+++ b/rules/ast-grep/ts-no-item-type-cast.yml
@@ -3,14 +3,21 @@ language: typescript
# Twin of tsx-no-item-type-cast — ast-grep rules are single-language, and
# `tsx` only scans .tsx files.
severity: error
-message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
+message: Don't cast to ItemType or an EntityType — parse the string (stringToItemType, parseEntityType) or type the source.
note: |-
Rule FE-31 in docs/development/style-guide.md. Entity-type strings arrive in several
stored spellings (email threads alone are `email`, `thread`, and
- `email_thread`), so a cast smuggles a value no preview fetcher handles.
- stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
- the one parser; extend it there if a spelling is missing.
+ `email_thread`), and each service has its own EntityType enum, so a cast
+ smuggles a value no preview fetcher or exhaustive match handles (an
+ `AGENT_SESSION` cast into the properties EntityType crashed the property
+ editor). stringToItemType in
+ src/lib/service-clients/service-storage/itemType.ts and parseEntityType in
+ src/features/property/utils/entityConversion.ts are the parsers; extend
+ them if a spelling is missing.
files:
- apps/web/src/**
rule:
- pattern: $EXPR as ItemType
+ any:
+ - pattern: $EXPR as ItemType
+ - pattern: $EXPR as EntityType
+ - pattern: $EXPR as EntityReference['entity_type']
diff --git a/rules/ast-grep/tsx-exhaustive-boundary-fallback.yml b/rules/ast-grep/tsx-exhaustive-boundary-fallback.yml
new file mode 100644
index 0000000000..316c292d1b
--- /dev/null
+++ b/rules/ast-grep/tsx-exhaustive-boundary-fallback.yml
@@ -0,0 +1,33 @@
+id: tsx-exhaustive-boundary-fallback
+language: tsx
+# Twin of ts-exhaustive-boundary-fallback — ast-grep rules are
+# single-language, and `typescript` only scans .ts files.
+severity: error
+message: Pass a fallback to .exhaustive() in boundary code — `.exhaustive((unknown) => fallback)`; a bare .exhaustive() throws on a variant this build doesn't know.
+note: |-
+ Rule FE-35 in docs/development/style-guide.md. ts-pattern's .exhaustive() is
+ a compile-time completeness check that also throws at runtime ("no pattern
+ matches value X"). Wire adapters, service clients, transports, workers, and
+ event hydrators match on values another service, app version, or native
+ plugin produced, so a new variant crashes every older client.
+ `.exhaustive(fallback)` keeps the compile-time check and returns the fallback
+ instead of throwing. Parse the value into a closed client type first if the
+ match must not fall back.
+files:
+ - apps/web/src/**/queries/**
+ - apps/web/src/**/queries.ts
+ - apps/web/src/lib/service-clients/**
+ - apps/web/src/**/workers/**
+ - apps/web/src/**/worker/**
+ - apps/web/src/**/*.worker.ts
+ - packages/collaboration/src/websocket/**
+ - packages/sdk/src/events/hydrate/**
+ignores:
+ - '**/*.test.tsx'
+ - '**/test/**'
+ - '**/tests/**'
+ - '**/browser-test/**'
+ # Being rewritten by the Tauri IPC teardown fix (#8207); drop once it lands.
+ - packages/collaboration/src/websocket/platform/tauri-websocket.ts
+rule:
+ pattern: $MATCH.exhaustive()
diff --git a/rules/ast-grep/tsx-no-item-type-cast.yml b/rules/ast-grep/tsx-no-item-type-cast.yml
index caed64ab4d..cb20d77598 100644
--- a/rules/ast-grep/tsx-no-item-type-cast.yml
+++ b/rules/ast-grep/tsx-no-item-type-cast.yml
@@ -3,14 +3,21 @@ language: tsx
# Twin of ts-no-item-type-cast — ast-grep rules are single-language, and
# `typescript` only scans .ts files.
severity: error
-message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
+message: Don't cast to ItemType or an EntityType — parse the string (stringToItemType, parseEntityType) or type the source.
note: |-
Rule FE-31 in docs/development/style-guide.md. Entity-type strings arrive in several
stored spellings (email threads alone are `email`, `thread`, and
- `email_thread`), so a cast smuggles a value no preview fetcher handles.
- stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
- the one parser; extend it there if a spelling is missing.
+ `email_thread`), and each service has its own EntityType enum, so a cast
+ smuggles a value no preview fetcher or exhaustive match handles (an
+ `AGENT_SESSION` cast into the properties EntityType crashed the property
+ editor). stringToItemType in
+ src/lib/service-clients/service-storage/itemType.ts and parseEntityType in
+ src/features/property/utils/entityConversion.ts are the parsers; extend
+ them if a spelling is missing.
files:
- apps/web/src/**
rule:
- pattern: $EXPR as ItemType
+ any:
+ - pattern: $EXPR as ItemType
+ - pattern: $EXPR as EntityType
+ - pattern: $EXPR as EntityReference['entity_type']