@tangle-network/agent-app 0.60.115 → 0.60.116
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VaultPane-OWOPGPXP.js +7 -0
- package/dist/assistant/index.js +8 -8
- package/dist/chat-react/index.js +2 -2
- package/dist/chat-routes/index.js +1 -1
- package/dist/{chunk-Y4WLCFDZ.js → chunk-2FLSODOX.js} +6 -6
- package/dist/chunk-BTEVD7HG.js +198 -0
- package/dist/chunk-BTEVD7HG.js.map +1 -0
- package/dist/chunk-FVI2MHUL.js +1152 -0
- package/dist/chunk-FVI2MHUL.js.map +1 -0
- package/dist/{chunk-RQSYR4AV.js → chunk-GHUQ5HXU.js} +4 -4
- package/dist/{chunk-OGDEUCNW.js → chunk-JGLK5RDK.js} +176 -1
- package/dist/chunk-JGLK5RDK.js.map +1 -0
- package/dist/{chunk-AB63T2LM.js → chunk-KBJZMR4E.js} +8 -1
- package/dist/chunk-KBJZMR4E.js.map +1 -0
- package/dist/{chunk-RQSNTJTW.js → chunk-MO7PDQRZ.js} +526 -187
- package/dist/chunk-MO7PDQRZ.js.map +1 -0
- package/dist/{chunk-MEUNTJL5.js → chunk-N3CYCSKK.js} +6 -1
- package/dist/chunk-N3CYCSKK.js.map +1 -0
- package/dist/{chunk-56GPDCOJ.js → chunk-TSGWACTC.js} +5 -5
- package/dist/journeys/cli.d.ts +2 -0
- package/dist/journeys/cli.js +165 -0
- package/dist/journeys/cli.js.map +1 -0
- package/dist/journeys/config.d.ts +96 -0
- package/dist/journeys/index.d.ts +18 -0
- package/dist/journeys/index.js +731 -0
- package/dist/journeys/index.js.map +1 -0
- package/dist/journeys/journey.d.ts +173 -0
- package/dist/journeys/page-reading.d.ts +42 -0
- package/dist/journeys/report.d.ts +51 -0
- package/dist/journeys/score.d.ts +115 -0
- package/dist/journeys/scrub.d.ts +21 -0
- package/dist/journeys/send.d.ts +46 -0
- package/dist/journeys/session.d.ts +27 -0
- package/dist/journeys/trace-zip.d.ts +28 -0
- package/dist/journeys/video.d.ts +53 -0
- package/dist/public-consultation/index.d.ts +2 -2
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.js +13 -1
- package/dist/sandbox/sandbox-exec-tool.d.ts +68 -0
- package/dist/sandbox/sandbox-run-tool.d.ts +70 -0
- package/dist/studio-react/index.js +2 -2
- package/dist/teams/index.js +10 -6
- package/dist/teams/invitations-api.js +6 -3
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/teams/invitations.d.ts +4 -0
- package/dist/teams/members-api.js +2 -1
- package/dist/teams-react/components/InviteForm.d.ts +20 -0
- package/dist/teams-react/contracts.d.ts +2 -0
- package/dist/teams-react/index.js +196 -217
- package/dist/teams-react/index.js.map +1 -1
- package/dist/vault/VaultContentResults.d.ts +29 -0
- package/dist/vault/VaultHistoryPanel.d.ts +20 -0
- package/dist/vault/VaultPane.d.ts +3 -1
- package/dist/vault/contracts.d.ts +38 -0
- package/dist/vault/index.js +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/web-react/index.js +22 -22
- package/dist/workspace-export/index.js +4 -193
- package/dist/workspace-export/index.js.map +1 -1
- package/dist/workspace-react/index.js +9 -7
- package/dist/workspace-react/index.js.map +1 -1
- package/dist/workspace-react/workspace-list.d.ts +7 -1
- package/package.json +8 -2
- package/dist/VaultPane-JUSNGOV7.js +0 -7
- package/dist/chunk-AB63T2LM.js.map +0 -1
- package/dist/chunk-MEUNTJL5.js.map +0 -1
- package/dist/chunk-OGDEUCNW.js.map +0 -1
- package/dist/chunk-RQSNTJTW.js.map +0 -1
- /package/dist/{VaultPane-JUSNGOV7.js.map → VaultPane-OWOPGPXP.js.map} +0 -0
- /package/dist/{chunk-Y4WLCFDZ.js.map → chunk-2FLSODOX.js.map} +0 -0
- /package/dist/{chunk-RQSYR4AV.js.map → chunk-GHUQ5HXU.js.map} +0 -0
- /package/dist/{chunk-56GPDCOJ.js.map → chunk-TSGWACTC.js.map} +0 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
interface ZipEntryInfo {
|
|
2
|
+
readonly name: string;
|
|
3
|
+
readonly method: number;
|
|
4
|
+
readonly crc32: number;
|
|
5
|
+
readonly compressedSize: number;
|
|
6
|
+
readonly uncompressedSize: number;
|
|
7
|
+
readonly localOffset: number;
|
|
8
|
+
readonly dosTime: number;
|
|
9
|
+
readonly dosDate: number;
|
|
10
|
+
}
|
|
11
|
+
/** Every entry in the central directory, sizes and offsets resolved through zip64 extras. */
|
|
12
|
+
export declare function readCentralDirectory(fd: number): ZipEntryInfo[];
|
|
13
|
+
/** One entry's stored bytes, still compressed. */
|
|
14
|
+
export declare function readRaw(fd: number, entry: ZipEntryInfo): Buffer;
|
|
15
|
+
/** One entry's content. */
|
|
16
|
+
export declare function inflateEntry(entry: ZipEntryInfo, raw: Buffer): Buffer;
|
|
17
|
+
interface ZipWriter {
|
|
18
|
+
/** Add an entry from its content (deflated here). */
|
|
19
|
+
add(name: string, content: Buffer, from?: Pick<ZipEntryInfo, 'dosTime' | 'dosDate'>): void;
|
|
20
|
+
/** Add an entry exactly as another archive stored it. */
|
|
21
|
+
copy(entry: ZipEntryInfo, raw: Buffer): void;
|
|
22
|
+
close(): void;
|
|
23
|
+
}
|
|
24
|
+
/** Write a zip to `path`, entries in the order added. `forceZip64` exercises the large-archive records in tests. */
|
|
25
|
+
export declare function createZipWriter(path: string, opts?: {
|
|
26
|
+
forceZip64?: boolean;
|
|
27
|
+
}): ZipWriter;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export interface Chapter {
|
|
2
|
+
/** Epoch ms. */
|
|
3
|
+
at: number;
|
|
4
|
+
caption: string;
|
|
5
|
+
/** Context label, or null for every context. */
|
|
6
|
+
label: string | null;
|
|
7
|
+
kind: 'step' | 'wait';
|
|
8
|
+
/** Epoch ms a wait ended. */
|
|
9
|
+
until?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface Cue {
|
|
12
|
+
start: number;
|
|
13
|
+
end: number;
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
export interface HighlightSegment {
|
|
17
|
+
/** Source range, seconds. */
|
|
18
|
+
a: number;
|
|
19
|
+
b: number;
|
|
20
|
+
/** Speed-up factor. */
|
|
21
|
+
k: number;
|
|
22
|
+
text: string;
|
|
23
|
+
}
|
|
24
|
+
export declare const MAX_HIGHLIGHTS_S = 178;
|
|
25
|
+
export declare function probeSeconds(file: string): number;
|
|
26
|
+
/** Chapters on the video's own clock; each caption holds until the next. */
|
|
27
|
+
export declare function chapterCues(chapters: readonly Chapter[], t0: number, duration: number): Cue[];
|
|
28
|
+
/**
|
|
29
|
+
* The highlights cut: which source ranges, at what speed, under which caption.
|
|
30
|
+
* A wait longer than 6 s plays in about 5 s; an idle stretch longer than 15 s
|
|
31
|
+
* plays in about 10 s; then everything scales to fit {@link MAX_HIGHLIGHTS_S}.
|
|
32
|
+
*/
|
|
33
|
+
export declare function highlightPlan(chapters: readonly Chapter[], t0: number, duration: number): HighlightSegment[];
|
|
34
|
+
interface PostProcessInput {
|
|
35
|
+
webm: string;
|
|
36
|
+
/** Raw working folder on the host; keeps the webm and chapters for a rebuild. */
|
|
37
|
+
workDir: string;
|
|
38
|
+
videoDir: string;
|
|
39
|
+
label: string;
|
|
40
|
+
/** Epoch ms the recorded page was created. */
|
|
41
|
+
t0: number;
|
|
42
|
+
wallSeconds: number;
|
|
43
|
+
chapters: readonly Chapter[];
|
|
44
|
+
speedup2x: boolean;
|
|
45
|
+
}
|
|
46
|
+
export declare function postProcessVideo(o: PostProcessInput): string[];
|
|
47
|
+
/** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */
|
|
48
|
+
export declare function rebuildVideo(rawLabelDir: string, videoDir: string, label: string, speedup2x: boolean): string[];
|
|
49
|
+
/** Seconds at which to grab frames: one per caption (1.5 s in), at most `max`, evenly spread. */
|
|
50
|
+
export declare function frameTimes(srt: string | null, times: readonly number[], max?: number): number[];
|
|
51
|
+
/** PNG frames of a video, named by label and timestamp, into `outDir`. */
|
|
52
|
+
export declare function extractFrames(video: string, srtFile: string | null, outDir: string, times: readonly number[], max?: number): string[];
|
|
53
|
+
export {};
|
|
@@ -102,8 +102,8 @@ interface GatewayConsultationContext {
|
|
|
102
102
|
/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */
|
|
103
103
|
export declare function createPublicConsultation(options: PublicConsultationOptions): {
|
|
104
104
|
authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer): Promise<{
|
|
105
|
-
reason?: undefined;
|
|
106
105
|
allow: true;
|
|
106
|
+
reason?: undefined;
|
|
107
107
|
code?: undefined;
|
|
108
108
|
} | {
|
|
109
109
|
allow: false;
|
|
@@ -121,9 +121,9 @@ export declare function createPublicConsultation(options: PublicConsultationOpti
|
|
|
121
121
|
executionBudget?: ChatTurnExecutionLimits;
|
|
122
122
|
maxOutputTokens?: number;
|
|
123
123
|
}) => Promise<{
|
|
124
|
+
start?: undefined;
|
|
124
125
|
status: 'unsupported';
|
|
125
126
|
reason: string;
|
|
126
|
-
start?: undefined;
|
|
127
127
|
} | {
|
|
128
128
|
reason?: undefined;
|
|
129
129
|
status: 'prepared';
|
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -874,6 +874,8 @@ export declare function detectInteractiveQuestion(event: unknown): string | null
|
|
|
874
874
|
export * from './workspace-sandbox-manager';
|
|
875
875
|
export * from './terminal-connection';
|
|
876
876
|
export * from './prewarm';
|
|
877
|
+
export * from './sandbox-run-tool';
|
|
878
|
+
export * from './sandbox-exec-tool';
|
|
877
879
|
export * from './prewarm-claim-d1';
|
|
878
880
|
export * from './prewarm-route';
|
|
879
881
|
export * from './foreground-single-flight';
|
package/dist/sandbox/index.js
CHANGED
|
@@ -12,11 +12,14 @@ import {
|
|
|
12
12
|
PROVISION_PAYLOAD_MAX_BYTES,
|
|
13
13
|
PYPI_EGRESS_DOMAINS,
|
|
14
14
|
SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS,
|
|
15
|
+
SANDBOX_EXEC_DESCRIPTION,
|
|
16
|
+
SANDBOX_RUN_DESCRIPTION,
|
|
15
17
|
SandboxEgressPolicyMismatchError,
|
|
16
18
|
SandboxFilesystemNotReadyError,
|
|
17
19
|
SandboxModelResolutionError,
|
|
18
20
|
SandboxProvisioningFailedElsewhereError,
|
|
19
21
|
SandboxRecoveryFailedError,
|
|
22
|
+
SandboxRunError,
|
|
20
23
|
SandboxRuntimeAuthRefreshError,
|
|
21
24
|
WARM_LEASE_DECLINED_UNTIL_DDL,
|
|
22
25
|
WARM_LEASE_PENDING_DDL,
|
|
@@ -40,7 +43,9 @@ import {
|
|
|
40
43
|
createD1PrewarmClaimStore,
|
|
41
44
|
createD1WarmLeaseStore,
|
|
42
45
|
createEscalationSpeculator,
|
|
46
|
+
createSandboxExecTool,
|
|
43
47
|
createSandboxPrewarmer,
|
|
48
|
+
createSandboxRunTool,
|
|
44
49
|
createSandboxTerminalConnectionRoute,
|
|
45
50
|
createWarmLeases,
|
|
46
51
|
createWorkspacePrewarmRoute,
|
|
@@ -74,6 +79,7 @@ import {
|
|
|
74
79
|
runSandboxPrompt,
|
|
75
80
|
runSandboxToolPathSetup,
|
|
76
81
|
sandboxPrewarmClaimKey,
|
|
82
|
+
sandboxPromptRunner,
|
|
77
83
|
sandboxToolBinDir,
|
|
78
84
|
sandboxToolPath,
|
|
79
85
|
sandboxToolRootDir,
|
|
@@ -90,7 +96,7 @@ import {
|
|
|
90
96
|
warmBinOf,
|
|
91
97
|
warmWeekdayOf,
|
|
92
98
|
writeProfileFilesToBox
|
|
93
|
-
} from "../chunk-
|
|
99
|
+
} from "../chunk-JGLK5RDK.js";
|
|
94
100
|
import {
|
|
95
101
|
EGRESS_PROXY_RECOVERY_PHASE,
|
|
96
102
|
EGRESS_PROXY_RECOVERY_REQUIRED,
|
|
@@ -156,12 +162,15 @@ export {
|
|
|
156
162
|
PYPI_EGRESS_DOMAINS,
|
|
157
163
|
SANDBOX_BACKING_CONTAINER_MISSING_CODE,
|
|
158
164
|
SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS,
|
|
165
|
+
SANDBOX_EXEC_DESCRIPTION,
|
|
166
|
+
SANDBOX_RUN_DESCRIPTION,
|
|
159
167
|
SANDBOX_TRANSIENT_DEADLINE_MS,
|
|
160
168
|
SandboxEgressPolicyMismatchError,
|
|
161
169
|
SandboxFilesystemNotReadyError,
|
|
162
170
|
SandboxModelResolutionError,
|
|
163
171
|
SandboxProvisioningFailedElsewhereError,
|
|
164
172
|
SandboxRecoveryFailedError,
|
|
173
|
+
SandboxRunError,
|
|
165
174
|
SandboxRuntimeAuthRefreshError,
|
|
166
175
|
SandboxTransientDeadlineError,
|
|
167
176
|
WARM_LEASE_DECLINED_UNTIL_DDL,
|
|
@@ -195,7 +204,9 @@ export {
|
|
|
195
204
|
createD1PrewarmClaimStore,
|
|
196
205
|
createD1WarmLeaseStore,
|
|
197
206
|
createEscalationSpeculator,
|
|
207
|
+
createSandboxExecTool,
|
|
198
208
|
createSandboxPrewarmer,
|
|
209
|
+
createSandboxRunTool,
|
|
199
210
|
createSandboxTerminalConnectionRoute,
|
|
200
211
|
createWarmLeases,
|
|
201
212
|
createWorkspacePrewarmRoute,
|
|
@@ -244,6 +255,7 @@ export {
|
|
|
244
255
|
runSandboxPrompt,
|
|
245
256
|
runSandboxToolPathSetup,
|
|
246
257
|
sandboxPrewarmClaimKey,
|
|
258
|
+
sandboxPromptRunner,
|
|
247
259
|
sandboxToolBinDir,
|
|
248
260
|
sandboxToolPath,
|
|
249
261
|
sandboxToolRootDir,
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createSandboxExecTool`: the `sandbox_exec` tool a Router turn calls to run
|
|
3
|
+
* one command in the product's box — a toolkit script, a converter, a check —
|
|
4
|
+
* and read its exit code and output. Unlike `sandbox_run` it starts no box
|
|
5
|
+
* agent: the Router model stays in charge and the box only executes.
|
|
6
|
+
*
|
|
7
|
+
* WHY. Tax's Router default lost its Python form toolkit because the lane had
|
|
8
|
+
* no way to reach a box: 685 tool calls, 0 form fills (2026-10). A toolkit
|
|
9
|
+
* the product mounts in the box is reachable from the Router lane only
|
|
10
|
+
* through a command tool.
|
|
11
|
+
*
|
|
12
|
+
* NEVER SILENT. A box that cannot start or be prepared, and a command that
|
|
13
|
+
* cannot run or outruns its cap, come back as a typed `SandboxRunError`
|
|
14
|
+
* (`sandbox_unavailable`, `sandbox_failed`) the model must report. A command
|
|
15
|
+
* that runs and exits non-zero is a result, not a failure: the model reads
|
|
16
|
+
* its exit code and stderr and can correct itself.
|
|
17
|
+
*
|
|
18
|
+
* `prepare` runs once per tool, before the first command (install a runtime,
|
|
19
|
+
* copy the session's documents in). `allow` is the product's command policy.
|
|
20
|
+
*/
|
|
21
|
+
import type { SandboxInstance } from '@tangle-network/sandbox';
|
|
22
|
+
import { SandboxRunError } from './sandbox-run-tool';
|
|
23
|
+
export interface SandboxExecToolOptions {
|
|
24
|
+
/** The box commands run in. The product provisions, binds and bills it. A throw is
|
|
25
|
+
* `sandbox_unavailable`, unless it is a `SandboxRunError`, which is kept as it is. */
|
|
26
|
+
box(signal: AbortSignal): Promise<SandboxInstance>;
|
|
27
|
+
/** Once per tool, before the first command: install a runtime, sync files in. */
|
|
28
|
+
prepare?(box: SandboxInstance, signal: AbortSignal): Promise<void>;
|
|
29
|
+
/** Default working directory. */
|
|
30
|
+
cwd?: string;
|
|
31
|
+
env?: Record<string, string>;
|
|
32
|
+
/** Cap for one command, box start and prepare included. Default 2 minutes. */
|
|
33
|
+
timeoutMs?: number;
|
|
34
|
+
/** Characters of stdout and of stderr returned to the model, each. Default 20 000 (the tail is kept). */
|
|
35
|
+
maxOutputChars?: number;
|
|
36
|
+
/** The product's command policy: a string refuses the command with that reason. */
|
|
37
|
+
allow?(command: string): string | null;
|
|
38
|
+
/** After each command, the files the product wants the model to know about (e.g. its output folder). */
|
|
39
|
+
listFiles?(box: SandboxInstance, signal: AbortSignal): Promise<string[]>;
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
/** The box's warm lease, so a call is recorded as a turn on it. */
|
|
42
|
+
warm?: {
|
|
43
|
+
leases: {
|
|
44
|
+
turn(key: string): Promise<unknown>;
|
|
45
|
+
};
|
|
46
|
+
key: string;
|
|
47
|
+
};
|
|
48
|
+
onFailure?(error: SandboxRunError): void;
|
|
49
|
+
name?: string;
|
|
50
|
+
description?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface SandboxExecResult {
|
|
53
|
+
exitCode: number;
|
|
54
|
+
stdout: string;
|
|
55
|
+
stderr: string;
|
|
56
|
+
/** True when stdout or stderr was cut to `maxOutputChars`. */
|
|
57
|
+
truncated: boolean;
|
|
58
|
+
ms: number;
|
|
59
|
+
files?: string[];
|
|
60
|
+
}
|
|
61
|
+
export interface SandboxExecTool {
|
|
62
|
+
name: string;
|
|
63
|
+
description: string;
|
|
64
|
+
inputSchema: Record<string, unknown>;
|
|
65
|
+
run(args: Record<string, unknown>): Promise<SandboxExecResult>;
|
|
66
|
+
}
|
|
67
|
+
export declare const SANDBOX_EXEC_DESCRIPTION: string;
|
|
68
|
+
export declare function createSandboxExecTool(options: SandboxExecToolOptions): SandboxExecTool;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createSandboxRunTool`: the `sandbox_run` tool a Router turn calls when the
|
|
3
|
+
* work needs a computer — run code, read a PDF or a sheet, fill a form with a
|
|
4
|
+
* Python toolkit. The conversational turn stays on the Router engine
|
|
5
|
+
* (`./router-turn`); only this call enters the box, and its final answer comes
|
|
6
|
+
* back to the model as the tool result.
|
|
7
|
+
*
|
|
8
|
+
* NEVER SILENT. A box that cannot start, a run that fails and a run that ends
|
|
9
|
+
* with no answer each come back as a typed failure (`sandbox_unavailable`,
|
|
10
|
+
* `sandbox_failed`, `sandbox_empty`) that the model reads and must report. A
|
|
11
|
+
* product that leaves this tool out when it cannot place a box drops the
|
|
12
|
+
* capability without the model or the user knowing; mount the tool and let it
|
|
13
|
+
* fail instead.
|
|
14
|
+
*
|
|
15
|
+
* WARM LEASES. When the product passes `warm`, the call counts as a turn on the
|
|
16
|
+
* box's lease (`leases.turn(key)`), so an `escalation-likely` warm from
|
|
17
|
+
* `createEscalationSpeculator` is recorded as used. The default name is the
|
|
18
|
+
* one the speculator listens for (`DEFAULT_ESCALATION_TOOLS`).
|
|
19
|
+
*/
|
|
20
|
+
import type { SandboxInstance } from '@tangle-network/sandbox';
|
|
21
|
+
import { type SandboxRuntimeConfig, type StreamSandboxPromptOptions } from './index';
|
|
22
|
+
export type SandboxRunFailureCode = 'sandbox_unavailable' | 'sandbox_failed' | 'sandbox_empty' | 'invalid_arguments';
|
|
23
|
+
/** A typed `sandbox_run` failure. `code` and `message` are what the model reads. */
|
|
24
|
+
export declare class SandboxRunError extends Error {
|
|
25
|
+
readonly code: SandboxRunFailureCode;
|
|
26
|
+
constructor(code: SandboxRunFailureCode, message: string, options?: {
|
|
27
|
+
cause?: unknown;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
export interface SandboxRunToolOptions {
|
|
31
|
+
/** The box this call runs in. The product provisions, binds and bills it; this module never
|
|
32
|
+
* creates one. A throw is reported to the model as `sandbox_unavailable`, unless it is a
|
|
33
|
+
* `SandboxRunError`, whose own code and message are kept (an unpaid account, for example). */
|
|
34
|
+
box(signal: AbortSignal): Promise<SandboxInstance>;
|
|
35
|
+
/** Runs the task on the box and returns the box agent's final answer: {@link sandboxPromptRunner}
|
|
36
|
+
* for the shell's own prompt path, or the product's runner (skill placement, app-tool MCP, a spend tap). */
|
|
37
|
+
runTask(box: SandboxInstance, task: string, options: {
|
|
38
|
+
signal: AbortSignal;
|
|
39
|
+
timeoutMs: number;
|
|
40
|
+
}): Promise<string>;
|
|
41
|
+
/** Wall-clock cap for one call, box start included. Default 5 minutes. */
|
|
42
|
+
timeoutMs?: number;
|
|
43
|
+
/** Cancels a call in flight, for example the turn's own signal. */
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
/** The box's warm lease, so the call is recorded as a turn on it. */
|
|
46
|
+
warm?: {
|
|
47
|
+
leases: {
|
|
48
|
+
turn(key: string): Promise<unknown>;
|
|
49
|
+
};
|
|
50
|
+
key: string;
|
|
51
|
+
};
|
|
52
|
+
/** Every failure with its cause, for the product's logs. The model only reads the typed message. */
|
|
53
|
+
onFailure?(error: SandboxRunError): void;
|
|
54
|
+
name?: string;
|
|
55
|
+
description?: string;
|
|
56
|
+
}
|
|
57
|
+
/** The tool shape `runRouterTurn` takes (`RouterTurnTool`), kept structural so this module does not import the engine. */
|
|
58
|
+
export interface SandboxRunTool {
|
|
59
|
+
name: string;
|
|
60
|
+
description: string;
|
|
61
|
+
inputSchema: Record<string, unknown>;
|
|
62
|
+
run(args: Record<string, unknown>): Promise<{
|
|
63
|
+
answer: string;
|
|
64
|
+
ms: number;
|
|
65
|
+
}>;
|
|
66
|
+
}
|
|
67
|
+
export declare const SANDBOX_RUN_DESCRIPTION: string;
|
|
68
|
+
/** The default `runTask`: the shell's own `runSandboxPrompt`, unattended (questions refused). */
|
|
69
|
+
export declare function sandboxPromptRunner(shell: SandboxRuntimeConfig, prompt?: Omit<StreamSandboxPromptOptions, 'signal' | 'history'>): SandboxRunToolOptions['runTask'];
|
|
70
|
+
export declare function createSandboxRunTool(options: SandboxRunToolOptions): SandboxRunTool;
|
|
@@ -39,9 +39,8 @@ import {
|
|
|
39
39
|
} from "../chunk-PT7H37YH.js";
|
|
40
40
|
import {
|
|
41
41
|
useInfiniteScroll
|
|
42
|
-
} from "../chunk-
|
|
42
|
+
} from "../chunk-2FLSODOX.js";
|
|
43
43
|
import "../chunk-XEURJVS5.js";
|
|
44
|
-
import "../chunk-SJWIZT7B.js";
|
|
45
44
|
import {
|
|
46
45
|
CheckGlyph,
|
|
47
46
|
ChevronDown,
|
|
@@ -51,6 +50,7 @@ import {
|
|
|
51
50
|
PopoverSurface,
|
|
52
51
|
usePopover
|
|
53
52
|
} from "../chunk-HG4OONJA.js";
|
|
53
|
+
import "../chunk-SJWIZT7B.js";
|
|
54
54
|
import {
|
|
55
55
|
ProviderLogo
|
|
56
56
|
} from "../chunk-MLG6XKPV.js";
|
package/dist/teams/index.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
|
+
generateInviteToken,
|
|
3
|
+
isInviteTokenShape,
|
|
4
|
+
validateInviteToken
|
|
5
|
+
} from "../chunk-DJ4VJIH5.js";
|
|
6
|
+
import {
|
|
7
|
+
INVITATION_EMAIL_HINT,
|
|
2
8
|
INVITATION_EXPIRY_DAYS,
|
|
3
9
|
generateInvitationToken,
|
|
4
10
|
getInvitationExpiresAt,
|
|
5
11
|
inviteUrlForToken,
|
|
12
|
+
isInvitationEmail,
|
|
6
13
|
normalizeInvitationEmail,
|
|
7
14
|
parseInvitationPermission
|
|
8
|
-
} from "../chunk-
|
|
9
|
-
import {
|
|
10
|
-
generateInviteToken,
|
|
11
|
-
isInviteTokenShape,
|
|
12
|
-
validateInviteToken
|
|
13
|
-
} from "../chunk-DJ4VJIH5.js";
|
|
15
|
+
} from "../chunk-KBJZMR4E.js";
|
|
14
16
|
import {
|
|
15
17
|
ASSIGNABLE_WORKSPACE_ROLES,
|
|
16
18
|
ORGANIZATION_ROLES,
|
|
@@ -28,6 +30,7 @@ import {
|
|
|
28
30
|
} from "../chunk-6XIAPIW6.js";
|
|
29
31
|
export {
|
|
30
32
|
ASSIGNABLE_WORKSPACE_ROLES,
|
|
33
|
+
INVITATION_EMAIL_HINT,
|
|
31
34
|
INVITATION_EXPIRY_DAYS,
|
|
32
35
|
ORGANIZATION_ROLES,
|
|
33
36
|
ORGANIZATION_ROLE_RANK,
|
|
@@ -41,6 +44,7 @@ export {
|
|
|
41
44
|
hasWorkspaceRole,
|
|
42
45
|
inviteUrlForToken,
|
|
43
46
|
isAssignableWorkspaceRole,
|
|
47
|
+
isInvitationEmail,
|
|
44
48
|
isInviteTokenShape,
|
|
45
49
|
normalizeInvitationEmail,
|
|
46
50
|
organizationRoleGrantsWorkspaceOwner,
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
SeatLimitError
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-N3CYCSKK.js";
|
|
4
|
+
import "../chunk-DJ4VJIH5.js";
|
|
4
5
|
import {
|
|
6
|
+
INVITATION_EMAIL_HINT,
|
|
5
7
|
generateInvitationToken,
|
|
6
8
|
getInvitationExpiresAt,
|
|
7
9
|
inviteUrlForToken,
|
|
10
|
+
isInvitationEmail,
|
|
8
11
|
normalizeInvitationEmail,
|
|
9
12
|
parseInvitationPermission
|
|
10
|
-
} from "../chunk-
|
|
11
|
-
import "../chunk-DJ4VJIH5.js";
|
|
13
|
+
} from "../chunk-KBJZMR4E.js";
|
|
12
14
|
import {
|
|
13
15
|
hasWorkspaceRole
|
|
14
16
|
} from "../chunk-6XIAPIW6.js";
|
|
@@ -40,6 +42,7 @@ function createInvitationsApi(opts) {
|
|
|
40
42
|
}
|
|
41
43
|
const email = normalizeInvitationEmail(input.email);
|
|
42
44
|
if (!email) return { succeeded: false, status: 400, error: "Missing email" };
|
|
45
|
+
if (!isInvitationEmail(email)) return { succeeded: false, status: 400, error: INVITATION_EMAIL_HINT };
|
|
43
46
|
const organizationId = accessRow.organization.id;
|
|
44
47
|
const workspaceName = accessRow.workspace.name;
|
|
45
48
|
await expirePendingInvitations(input.workspaceId, email, now);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/teams/invitations-api.ts"],"sourcesContent":["/**\n * Framework-neutral email-invitation lifecycle for the teams module: create /\n * list / resend / revoke / preview / accept over the dedicated\n * `workspace_invitation` table (from `createWorkspaceInvitationTable`). Lifted out\n * of any one app's route file — each app binds this once to its own db/tables/\n * access and mounts the handlers in its own routes with its own auth.\n *\n * Unlike `members-api` (whose \"invite\" is a pending workspaceMember row, no\n * email), this models the rich lifecycle: a dedicated invitation row with status,\n * 7-day expiry, emailStatus, resend, and revoke. On accept it materializes the\n * `organizationMembers` + `workspaceMembers` rows, so `members-api.listMembers`\n * still surfaces accepted members; pending invites live only here.\n *\n * Handlers return a discriminated `InvitationOutcome` (not a `Response`) so the\n * route adapter maps `{ status }` to its own framework's response. Three seams:\n * - `sendInvitationEmail` (REQUIRED) — the app's mail transport. Returns a\n * typed outcome; a failed send never blocks invitation creation (emailStatus\n * is recorded as 'failed' and the invite link is still returned).\n * - `enforceSeat` (OPTIONAL) — billing/seat-limit gate, called at create time\n * only when the invite would consume a NEW seat. Reused from members-api.\n * - `memberSyncSeam.add` (OPTIONAL) — fire-and-forget propagation of the new\n * member to a sandbox/external system on accept. Fail-soft by contract.\n *\n * Imports `drizzle-orm`, so this is a subpath, never re-exported from root.\n */\n\nimport { and, eq, lte, sql } from 'drizzle-orm'\nimport {\n type InvitationEmailStatus,\n type InvitationPermission,\n type InvitationStatus,\n generateInvitationToken,\n getInvitationExpiresAt,\n inviteUrlForToken,\n normalizeInvitationEmail,\n parseInvitationPermission,\n} from './invitations'\nimport { type WorkspaceRole, hasWorkspaceRole } from './roles'\nimport { type EnforceSeatSeam, type MemberSyncSeam, SeatLimitError } from './members-api'\nimport type { TeamDatabase, WorkspaceAccessApi } from './drizzle/access'\nimport type { TeamParentTable, TeamTables } from './drizzle/schema'\nimport type { WorkspaceInvitationRow, WorkspaceInvitationTables } from './drizzle/invitations-schema'\n\n// Re-export the seams an adopter wires, so a consumer can import everything the\n// invitations API needs from this one subpath.\nexport { SeatLimitError } from './members-api'\nexport type { EnforceSeatSeam, MemberSyncSeam } from './members-api'\n\n/** The app's mail transport. Returns a typed outcome; never throws to the API. */\nexport interface SendInvitationEmailInput {\n to: string\n workspaceName: string\n inviterEmail: string\n permission: InvitationPermission\n inviteUrl: string\n expiresAt: Date\n}\n/** Represent the outcome of sending an invitation email with success status and optional error message */\nexport type SendInvitationEmailResult = { succeeded: true } | { succeeded: false; error: string }\n/** Resolve sending an invitation email and return the result asynchronously */\nexport interface SendInvitationEmailSeam {\n (input: SendInvitationEmailInput): Promise<SendInvitationEmailResult>\n}\n\n/** The product's user table, narrowed to the columns the queries read. */\nexport interface InvitationUserTable {\n id: any\n email: any\n emailVerified: any\n}\n\n/** The product's workspace table, narrowed to the columns the queries read. */\nexport interface InvitationWorkspaceTable {\n id: any\n name: any\n}\n\n/** Define configuration options required to manage workspace invitations and related data sources */\nexport interface InvitationsApiOptions {\n db: TeamDatabase\n tables: TeamTables\n /** The invitation table from `createWorkspaceInvitationTable`. */\n invitationsTable: WorkspaceInvitationTables\n userTable: TeamParentTable & InvitationUserTable\n workspaceTable: TeamParentTable & InvitationWorkspaceTable\n access: Pick<WorkspaceAccessApi, 'getWorkspaceAccess'>\n /** REQUIRED — the app's mail transport (e.g. Resend + `inviteEmail` from `./email`). */\n sendInvitationEmail: SendInvitationEmailSeam\n /** OPTIONAL — seat-limit gate at create time; mirrors members-api. */\n enforceSeat?: EnforceSeatSeam\n /** OPTIONAL — fire-and-forget member propagation on accept. */\n memberSyncSeam?: Pick<MemberSyncSeam, 'add'>\n /** Inviter display fallback when the inviter's email is unknown. */\n productDisplayName?: string\n}\n\n/** Represent a workspace invitation with details about inviter, permissions, status, and timestamps */\nexport interface WorkspaceInvitationView {\n id: string\n workspaceId: string\n organizationId: string\n email: string\n invitedByUserId: string\n inviterEmail: string | null\n permissions: InvitationPermission\n token: string\n status: InvitationStatus\n emailStatus: InvitationEmailStatus\n expiresAt: Date\n createdAt: Date\n acceptedAt: Date | null\n revokedAt: Date | null\n lastSentAt: Date | null\n}\n\n/** Describe the structure of an invitation preview with workspace, email, permissions, status, and expiration details */\nexport interface InvitationPreview {\n workspaceId: string\n workspaceName: string\n email: string\n inviterEmail: string | null\n permissions: InvitationPermission\n status: InvitationStatus\n expiresAt: Date\n}\n\n/** Resolve the result of an invitation as success with a value or failure with status and error details */\nexport type InvitationOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; error: string }\n\n/**\n * Build the invitations API bound to one product's db/tables/access/seams.\n * Returns the six lifecycle handlers an app mounts in its routes.\n */\nexport function createInvitationsApi(opts: InvitationsApiOptions) {\n const { db, tables, access, sendInvitationEmail, enforceSeat, memberSyncSeam } = opts\n const { organizationMembers, workspaceMembers } = tables\n const { workspaceInvitations } = opts.invitationsTable\n const users = opts.userTable\n const workspaces = opts.workspaceTable\n const productDisplayName = opts.productDisplayName ?? 'A workspace admin'\n\n function fireSync(op: () => Promise<void> | void) {\n try {\n Promise.resolve(op()).catch(() => {})\n } catch {\n // seam threw synchronously — swallow; sync is best-effort by contract.\n }\n }\n\n async function createInvitation(input: {\n workspaceId: string\n email: string\n permissions: string | undefined\n invitedByUserId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView; inviteUrl: string; emailError?: string }>> {\n const now = input.now ?? new Date()\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.invitedByUserId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n const permissions = parseInvitationPermission(input.permissions ?? 'editor')\n if (!permissions) return { succeeded: false, status: 400, error: 'Invalid permissions' }\n if (!hasWorkspaceRole(accessRow.role, permissions)) {\n return { succeeded: false, status: 403, error: 'Cannot assign higher permissions than your own' }\n }\n\n const email = normalizeInvitationEmail(input.email)\n if (!email) return { succeeded: false, status: 400, error: 'Missing email' }\n\n const organizationId = accessRow.organization.id\n const workspaceName = (accessRow.workspace as { name: string }).name\n\n await expirePendingInvitations(input.workspaceId, email, now)\n\n const existingPending = await getPendingInvitation(input.workspaceId, email)\n if (existingPending) return { succeeded: false, status: 409, error: 'A pending invitation already exists for this email' }\n\n const accountCheck = await checkExistingAccountAccess(organizationId, input.workspaceId, email, input.invitedByUserId)\n if (!accountCheck.succeeded) return accountCheck\n\n // Seat gate: only a genuinely NEW seat. The checks above reject re-invites,\n // existing workspace members, and org admins; an existing plain org member is\n // already billable (no new seat), so skip the gate for them — mirrors\n // members-api. The pending row is not inserted yet, so the seam's count\n // reflects current usage and denies the invite that would push OVER the limit\n // (at invite time, not accept time).\n if (enforceSeat && !accountCheck.isExistingOrgMember) {\n try {\n await enforceSeat({ actorId: input.invitedByUserId, organizationId })\n } catch (err) {\n if (err instanceof SeatLimitError) return { succeeded: false, status: err.status, error: err.message }\n throw err\n }\n }\n\n const token = generateInvitationToken()\n const expiresAt = getInvitationExpiresAt(now)\n\n const [created] = await db.insert(workspaceInvitations).values({\n workspaceId: input.workspaceId,\n organizationId,\n email,\n invitedByUserId: input.invitedByUserId,\n permissions,\n token,\n status: 'pending',\n emailStatus: 'not_sent',\n expiresAt,\n createdAt: now,\n }).returning()\n\n const inviteUrl = inviteUrlForToken(input.origin, token)\n const emailResult = await sendInvitationEmail({\n to: email,\n workspaceName,\n inviterEmail: accountCheck.inviterEmail ?? productDisplayName,\n permission: permissions,\n inviteUrl,\n expiresAt,\n })\n\n const emailStatus: InvitationEmailStatus = emailResult.succeeded ? 'sent' : 'failed'\n const [updated] = await db.update(workspaceInvitations)\n .set({ emailStatus, lastSentAt: emailResult.succeeded ? now : null })\n .where(eq(workspaceInvitations.id, created!.id))\n .returning()\n\n return {\n succeeded: true,\n value: {\n invitation: toInvitationView(updated!, accountCheck.inviterEmail),\n inviteUrl,\n emailError: emailResult.succeeded ? undefined : emailResult.error,\n },\n }\n }\n\n async function listInvitations(input: {\n workspaceId: string\n userId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitations: Array<WorkspaceInvitationView & { inviteUrl: string }> }>> {\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n await expirePendingInvitations(input.workspaceId, undefined, input.now ?? new Date())\n\n const rows = await db\n .select({ invitation: workspaceInvitations, inviterEmail: users.email })\n .from(workspaceInvitations)\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.workspaceId, input.workspaceId))\n .orderBy(sql`${workspaceInvitations.createdAt} desc`)\n\n return {\n succeeded: true,\n value: {\n invitations: rows.map((row: { invitation: WorkspaceInvitationRow; inviterEmail: string | null }) => ({\n ...toInvitationView(row.invitation, row.inviterEmail),\n inviteUrl: inviteUrlForToken(input.origin, row.invitation.token),\n })),\n },\n }\n }\n\n async function resendInvitation(input: {\n invitationId: string\n userId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView; inviteUrl: string; emailError?: string }>> {\n const row = await getInvitationById(input.invitationId)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n const accessRow = await access.getWorkspaceAccess(row.invitation.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n const now = input.now ?? new Date()\n if (row.invitation.status !== 'pending') {\n return { succeeded: false, status: 409, error: 'Only pending invitations can be resent' }\n }\n if (row.invitation.expiresAt <= now) {\n await markInvitationExpired(row.invitation.id)\n return { succeeded: false, status: 409, error: 'Invitation has expired' }\n }\n\n const workspaceName = (accessRow.workspace as { name: string }).name\n const inviteUrl = inviteUrlForToken(input.origin, row.invitation.token)\n const emailResult = await sendInvitationEmail({\n to: row.invitation.email,\n workspaceName,\n inviterEmail: row.inviterEmail ?? productDisplayName,\n permission: row.invitation.permissions,\n inviteUrl,\n expiresAt: row.invitation.expiresAt,\n })\n\n const [updated] = await db.update(workspaceInvitations)\n .set({\n emailStatus: emailResult.succeeded ? 'sent' : 'failed',\n lastSentAt: emailResult.succeeded ? now : row.invitation.lastSentAt,\n })\n .where(eq(workspaceInvitations.id, row.invitation.id))\n .returning()\n\n return {\n succeeded: true,\n value: {\n invitation: toInvitationView(updated!, row.inviterEmail),\n inviteUrl,\n emailError: emailResult.succeeded ? undefined : emailResult.error,\n },\n }\n }\n\n async function revokeInvitation(input: {\n invitationId: string\n userId: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView }>> {\n const row = await getInvitationById(input.invitationId)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n const accessRow = await access.getWorkspaceAccess(row.invitation.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n if (row.invitation.status !== 'pending') {\n return { succeeded: false, status: 409, error: 'Only pending invitations can be revoked' }\n }\n\n const [updated] = await db.update(workspaceInvitations)\n .set({ status: 'revoked', revokedAt: input.now ?? new Date() })\n .where(and(eq(workspaceInvitations.id, row.invitation.id), eq(workspaceInvitations.status, 'pending')))\n .returning()\n\n // The status read above is advisory. A concurrent accept may win between\n // that read and this update, so the write must be compare-and-set.\n if (!updated) return { succeeded: false, status: 409, error: 'The invitation changed. Reload it before continuing.' }\n\n return { succeeded: true, value: { invitation: toInvitationView(updated!, row.inviterEmail) } }\n }\n\n async function getPreview(token: string, now: Date = new Date()): Promise<InvitationOutcome<InvitationPreview>> {\n const row = await getInvitationByToken(token)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n let invitation = row.invitation\n if (invitation.status === 'pending' && invitation.expiresAt <= now) {\n invitation = await markInvitationExpired(invitation.id)\n }\n\n return {\n succeeded: true,\n value: {\n workspaceId: invitation.workspaceId,\n workspaceName: row.workspaceName,\n email: invitation.email,\n inviterEmail: row.inviterEmail,\n permissions: invitation.permissions,\n status: invitation.status,\n expiresAt: invitation.expiresAt,\n },\n }\n }\n\n async function acceptInvitation(input: {\n token: string\n userId: string\n now?: Date\n }): Promise<InvitationOutcome<{ workspaceId: string }>> {\n const now = input.now ?? new Date()\n const row = await getInvitationByToken(input.token)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n let invitation = row.invitation\n if (invitation.status === 'pending' && invitation.expiresAt <= now) {\n invitation = await markInvitationExpired(invitation.id)\n }\n\n const [currentUser] = await db\n .select({ id: users.id, email: users.email, emailVerified: users.emailVerified })\n .from(users)\n .where(eq(users.id, input.userId))\n .limit(1)\n if (!currentUser) return { succeeded: false, status: 401, error: 'Authentication required' }\n\n if (normalizeInvitationEmail(currentUser.email) !== invitation.email) {\n return { succeeded: false, status: 403, error: 'Sign in with the invited email address to accept this invitation' }\n }\n\n const collisionCheck = await findUsersByNormalizedEmail(invitation.email)\n if (collisionCheck.length > 1) {\n return {\n succeeded: false,\n status: 409,\n error: 'Multiple accounts use this email. Contact support to reconcile before accepting this invitation.',\n }\n }\n\n let orgMember = await getOrganizationMember(invitation.organizationId, currentUser.id)\n if (orgMember?.role === 'owner' || orgMember?.role === 'admin') {\n return { succeeded: false, status: 409, error: 'This user already has account-level access.' }\n }\n\n if (invitation.status === 'accepted') {\n const existing = orgMember ? await getWorkspaceMemberByOrganizationMember(invitation.workspaceId, orgMember.id) : null\n if (existing) return { succeeded: true, value: { workspaceId: invitation.workspaceId } }\n return { succeeded: false, status: 409, error: 'Invitation has already been accepted' }\n }\n if (invitation.status === 'expired') return { succeeded: false, status: 409, error: 'Invitation has expired' }\n if (invitation.status === 'revoked') return { succeeded: false, status: 409, error: 'Invitation has been revoked' }\n\n if (!orgMember) {\n const [inserted] = await db.insert(organizationMembers).values({\n organizationId: invitation.organizationId,\n userId: currentUser.id,\n role: 'member',\n createdAt: now,\n updatedAt: now,\n }).returning()\n if (!inserted) return { succeeded: false, status: 500, error: 'Failed to create organization membership' }\n orgMember = inserted\n }\n\n const existingMember = await getWorkspaceMemberByOrganizationMember(invitation.workspaceId, orgMember.id)\n if (!existingMember) {\n await db.insert(workspaceMembers).values({\n workspaceId: invitation.workspaceId,\n organizationMemberId: orgMember.id,\n userId: currentUser.id,\n role: invitation.permissions,\n inviteEmail: invitation.email,\n // members-api nulls the token on accept to release the unique slot; the\n // invitations flow keeps it (its `inv_` tokens never collide), so the\n // materialized row carries the originating token for audit.\n inviteToken: invitation.token,\n invitedAt: now,\n acceptedAt: now,\n })\n if (memberSyncSeam?.add) {\n const userId = currentUser.id\n const role = invitation.permissions as WorkspaceRole\n fireSync(() => memberSyncSeam.add!({ workspaceId: invitation.workspaceId, userId, role }))\n }\n }\n\n const [accepted] = await db.update(workspaceInvitations)\n .set({ status: 'accepted', acceptedAt: now })\n .where(and(eq(workspaceInvitations.id, invitation.id), eq(workspaceInvitations.status, 'pending')))\n .returning()\n\n if (!accepted) {\n // Membership was materialized before the final compare-and-set. Remove\n // only the row created by this attempt before reporting the conflict.\n await db.delete(workspaceMembers)\n .where(and(eq(workspaceMembers.workspaceId, invitation.workspaceId), eq(workspaceMembers.userId, currentUser.id)))\n return { succeeded: false, status: 409, error: 'The invitation changed. Reload it before continuing.' }\n }\n\n return { succeeded: true, value: { workspaceId: invitation.workspaceId } }\n }\n\n // ── internal query helpers ──\n\n async function expirePendingInvitations(workspaceId: string, email: string | undefined, now: Date) {\n const conditions = [\n eq(workspaceInvitations.workspaceId, workspaceId),\n eq(workspaceInvitations.status, 'pending' as const),\n lte(workspaceInvitations.expiresAt, now),\n ]\n if (email) conditions.push(eq(workspaceInvitations.email, email))\n await db.update(workspaceInvitations).set({ status: 'expired' }).where(and(...conditions))\n }\n\n async function getPendingInvitation(workspaceId: string, email: string) {\n const [invitation] = await db\n .select({ id: workspaceInvitations.id })\n .from(workspaceInvitations)\n .where(and(\n eq(workspaceInvitations.workspaceId, workspaceId),\n eq(workspaceInvitations.email, email),\n eq(workspaceInvitations.status, 'pending' as const),\n ))\n .limit(1)\n return invitation ?? null\n }\n\n async function checkExistingAccountAccess(\n organizationId: string,\n workspaceId: string,\n email: string,\n invitedByUserId: string,\n ): Promise<\n | { succeeded: false; status: number; error: string }\n | { succeeded: true; inviterEmail: string | null; isExistingOrgMember: boolean }\n > {\n const matchingUsers = await findUsersByNormalizedEmail(email)\n const [inviter] = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, invitedByUserId))\n .limit(1)\n\n if (matchingUsers.length > 1) {\n return {\n succeeded: false,\n status: 409,\n error: 'Multiple accounts use this email. Contact support to reconcile before inviting this user.',\n }\n }\n const existingUser = matchingUsers[0]\n if (!existingUser) return { succeeded: true, inviterEmail: inviter?.email ?? null, isExistingOrgMember: false }\n\n const orgMember = await getOrganizationMember(organizationId, existingUser.id)\n if (orgMember?.role === 'owner' || orgMember?.role === 'admin') {\n return { succeeded: false, status: 409, error: 'This user already has account-level access.' }\n }\n if (orgMember) {\n const workspaceMember = await getWorkspaceMemberByOrganizationMember(workspaceId, orgMember.id)\n if (workspaceMember) return { succeeded: false, status: 409, error: 'User is already a workspace member' }\n }\n\n return { succeeded: true, inviterEmail: inviter?.email ?? null, isExistingOrgMember: Boolean(orgMember) }\n }\n\n async function findUsersByNormalizedEmail(email: string) {\n return db\n .select({ id: users.id, email: users.email, emailVerified: users.emailVerified })\n .from(users)\n .where(sql`lower(${users.email}) = ${email}`)\n }\n\n async function getOrganizationMember(organizationId: string, userId: string) {\n const [member] = await db\n .select()\n .from(organizationMembers)\n .where(and(eq(organizationMembers.organizationId, organizationId), eq(organizationMembers.userId, userId)))\n .limit(1)\n return member ?? null\n }\n\n async function getWorkspaceMemberByOrganizationMember(workspaceId: string, organizationMemberId: string) {\n const [member] = await db\n .select({ id: workspaceMembers.id })\n .from(workspaceMembers)\n .where(and(\n eq(workspaceMembers.workspaceId, workspaceId),\n eq(workspaceMembers.organizationMemberId, organizationMemberId),\n ))\n .limit(1)\n return member ?? null\n }\n\n async function getInvitationById(invitationId: string) {\n const [row] = await db\n .select({ invitation: workspaceInvitations, inviterEmail: users.email })\n .from(workspaceInvitations)\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.id, invitationId))\n .limit(1)\n return row ?? null\n }\n\n async function getInvitationByToken(token: string) {\n const [row] = await db\n .select({\n invitation: workspaceInvitations,\n workspaceName: workspaces.name,\n inviterEmail: users.email,\n })\n .from(workspaceInvitations)\n .innerJoin(workspaces, eq(workspaces.id, workspaceInvitations.workspaceId))\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.token, token))\n .limit(1)\n return row ?? null\n }\n\n async function markInvitationExpired(invitationId: string) {\n const [updated] = await db.update(workspaceInvitations)\n .set({ status: 'expired' })\n .where(eq(workspaceInvitations.id, invitationId))\n .returning()\n return updated!\n }\n\n function toInvitationView(invitation: WorkspaceInvitationRow, inviterEmail: string | null): WorkspaceInvitationView {\n return {\n id: invitation.id,\n workspaceId: invitation.workspaceId,\n organizationId: invitation.organizationId,\n email: invitation.email,\n invitedByUserId: invitation.invitedByUserId,\n inviterEmail,\n permissions: invitation.permissions,\n token: invitation.token,\n status: invitation.status,\n emailStatus: invitation.emailStatus,\n expiresAt: invitation.expiresAt,\n createdAt: invitation.createdAt,\n acceptedAt: invitation.acceptedAt,\n revokedAt: invitation.revokedAt,\n lastSentAt: invitation.lastSentAt,\n }\n }\n\n return { createInvitation, listInvitations, resendInvitation, revokeInvitation, getPreview, acceptInvitation }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,SAAS,KAAK,IAAI,KAAK,WAAW;AA6G3B,SAAS,qBAAqB,MAA6B;AAChE,QAAM,EAAE,IAAI,QAAQ,QAAQ,qBAAqB,aAAa,eAAe,IAAI;AACjF,QAAM,EAAE,qBAAqB,iBAAiB,IAAI;AAClD,QAAM,EAAE,qBAAqB,IAAI,KAAK;AACtC,QAAM,QAAQ,KAAK;AACnB,QAAM,aAAa,KAAK;AACxB,QAAM,qBAAqB,KAAK,sBAAsB;AAEtD,WAAS,SAAS,IAAgC;AAChD,QAAI;AACF,cAAQ,QAAQ,GAAG,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IACtC,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,iBAAe,iBAAiB,OAOgF;AAC9G,UAAM,MAAM,MAAM,OAAO,oBAAI,KAAK;AAClC,UAAM,YAAY,MAAM,OAAO,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,OAAO;AACnG,QAAI,CAAC,UAAW,QAAO,EAAE,WAAW,OAAO,QAAQ,KAAK,OAAO,sBAAsB;AAErF,UAAM,cAAc,0BAA0B,MAAM,eAAe,QAAQ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,OAAO;AAAA,EAChB;AAEA,iBAAe,sBAAsB,cAAsB;AACzD,UAAM,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,oBAAoB,EACnD,IAAI,EAAE,QAAQ,UAAU,CAAC,EACzB,MAAM,GAAG,qBAAqB,IAAI,YAAY,CAAC,EAC/C,UAAU;AACb,WAAO;AAAA,EACT;AAEA,WAAS,iBAAiB,YAAoC,cAAsD;AAClH,WAAO;AAAA,MACL,IAAI,WAAW;AAAA,MACf,aAAa,WAAW;AAAA,MACxB,gBAAgB,WAAW;AAAA,MAC3B,OAAO,WAAW;AAAA,MAClB,iBAAiB,WAAW;AAAA,MAC5B;AAAA,MACA,aAAa,WAAW;AAAA,MACxB,OAAO,WAAW;AAAA,MAClB,QAAQ,WAAW;AAAA,MACnB,aAAa,WAAW;AAAA,MACxB,WAAW,WAAW;AAAA,MACtB,WAAW,WAAW;AAAA,MACtB,YAAY,WAAW;AAAA,MACvB,WAAW,WAAW;AAAA,MACtB,YAAY,WAAW;AAAA,IACzB;AAAA,EACF;AAEA,SAAO,EAAE,kBAAkB,iBAAiB,kBAAkB,kBAAkB,YAAY,iBAAiB;AAC/G;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/teams/invitations-api.ts"],"sourcesContent":["/**\n * Framework-neutral email-invitation lifecycle for the teams module: create /\n * list / resend / revoke / preview / accept over the dedicated\n * `workspace_invitation` table (from `createWorkspaceInvitationTable`). Lifted out\n * of any one app's route file — each app binds this once to its own db/tables/\n * access and mounts the handlers in its own routes with its own auth.\n *\n * Unlike `members-api` (whose \"invite\" is a pending workspaceMember row, no\n * email), this models the rich lifecycle: a dedicated invitation row with status,\n * 7-day expiry, emailStatus, resend, and revoke. On accept it materializes the\n * `organizationMembers` + `workspaceMembers` rows, so `members-api.listMembers`\n * still surfaces accepted members; pending invites live only here.\n *\n * Handlers return a discriminated `InvitationOutcome` (not a `Response`) so the\n * route adapter maps `{ status }` to its own framework's response. Three seams:\n * - `sendInvitationEmail` (REQUIRED) — the app's mail transport. Returns a\n * typed outcome; a failed send never blocks invitation creation (emailStatus\n * is recorded as 'failed' and the invite link is still returned).\n * - `enforceSeat` (OPTIONAL) — billing/seat-limit gate, called at create time\n * only when the invite would consume a NEW seat. Reused from members-api.\n * - `memberSyncSeam.add` (OPTIONAL) — fire-and-forget propagation of the new\n * member to a sandbox/external system on accept. Fail-soft by contract.\n *\n * Imports `drizzle-orm`, so this is a subpath, never re-exported from root.\n */\n\nimport { and, eq, lte, sql } from 'drizzle-orm'\nimport {\n type InvitationEmailStatus,\n type InvitationPermission,\n type InvitationStatus,\n generateInvitationToken,\n getInvitationExpiresAt,\n inviteUrlForToken,\n INVITATION_EMAIL_HINT,\n isInvitationEmail,\n normalizeInvitationEmail,\n parseInvitationPermission,\n} from './invitations'\nimport { type WorkspaceRole, hasWorkspaceRole } from './roles'\nimport { type EnforceSeatSeam, type MemberSyncSeam, SeatLimitError } from './members-api'\nimport type { TeamDatabase, WorkspaceAccessApi } from './drizzle/access'\nimport type { TeamParentTable, TeamTables } from './drizzle/schema'\nimport type { WorkspaceInvitationRow, WorkspaceInvitationTables } from './drizzle/invitations-schema'\n\n// Re-export the seams an adopter wires, so a consumer can import everything the\n// invitations API needs from this one subpath.\nexport { SeatLimitError } from './members-api'\nexport type { EnforceSeatSeam, MemberSyncSeam } from './members-api'\n\n/** The app's mail transport. Returns a typed outcome; never throws to the API. */\nexport interface SendInvitationEmailInput {\n to: string\n workspaceName: string\n inviterEmail: string\n permission: InvitationPermission\n inviteUrl: string\n expiresAt: Date\n}\n/** Represent the outcome of sending an invitation email with success status and optional error message */\nexport type SendInvitationEmailResult = { succeeded: true } | { succeeded: false; error: string }\n/** Resolve sending an invitation email and return the result asynchronously */\nexport interface SendInvitationEmailSeam {\n (input: SendInvitationEmailInput): Promise<SendInvitationEmailResult>\n}\n\n/** The product's user table, narrowed to the columns the queries read. */\nexport interface InvitationUserTable {\n id: any\n email: any\n emailVerified: any\n}\n\n/** The product's workspace table, narrowed to the columns the queries read. */\nexport interface InvitationWorkspaceTable {\n id: any\n name: any\n}\n\n/** Define configuration options required to manage workspace invitations and related data sources */\nexport interface InvitationsApiOptions {\n db: TeamDatabase\n tables: TeamTables\n /** The invitation table from `createWorkspaceInvitationTable`. */\n invitationsTable: WorkspaceInvitationTables\n userTable: TeamParentTable & InvitationUserTable\n workspaceTable: TeamParentTable & InvitationWorkspaceTable\n access: Pick<WorkspaceAccessApi, 'getWorkspaceAccess'>\n /** REQUIRED — the app's mail transport (e.g. Resend + `inviteEmail` from `./email`). */\n sendInvitationEmail: SendInvitationEmailSeam\n /** OPTIONAL — seat-limit gate at create time; mirrors members-api. */\n enforceSeat?: EnforceSeatSeam\n /** OPTIONAL — fire-and-forget member propagation on accept. */\n memberSyncSeam?: Pick<MemberSyncSeam, 'add'>\n /** Inviter display fallback when the inviter's email is unknown. */\n productDisplayName?: string\n}\n\n/** Represent a workspace invitation with details about inviter, permissions, status, and timestamps */\nexport interface WorkspaceInvitationView {\n id: string\n workspaceId: string\n organizationId: string\n email: string\n invitedByUserId: string\n inviterEmail: string | null\n permissions: InvitationPermission\n token: string\n status: InvitationStatus\n emailStatus: InvitationEmailStatus\n expiresAt: Date\n createdAt: Date\n acceptedAt: Date | null\n revokedAt: Date | null\n lastSentAt: Date | null\n}\n\n/** Describe the structure of an invitation preview with workspace, email, permissions, status, and expiration details */\nexport interface InvitationPreview {\n workspaceId: string\n workspaceName: string\n email: string\n inviterEmail: string | null\n permissions: InvitationPermission\n status: InvitationStatus\n expiresAt: Date\n}\n\n/** Resolve the result of an invitation as success with a value or failure with status and error details */\nexport type InvitationOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; error: string }\n\n/**\n * Build the invitations API bound to one product's db/tables/access/seams.\n * Returns the six lifecycle handlers an app mounts in its routes.\n */\nexport function createInvitationsApi(opts: InvitationsApiOptions) {\n const { db, tables, access, sendInvitationEmail, enforceSeat, memberSyncSeam } = opts\n const { organizationMembers, workspaceMembers } = tables\n const { workspaceInvitations } = opts.invitationsTable\n const users = opts.userTable\n const workspaces = opts.workspaceTable\n const productDisplayName = opts.productDisplayName ?? 'A workspace admin'\n\n function fireSync(op: () => Promise<void> | void) {\n try {\n Promise.resolve(op()).catch(() => {})\n } catch {\n // seam threw synchronously — swallow; sync is best-effort by contract.\n }\n }\n\n async function createInvitation(input: {\n workspaceId: string\n email: string\n permissions: string | undefined\n invitedByUserId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView; inviteUrl: string; emailError?: string }>> {\n const now = input.now ?? new Date()\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.invitedByUserId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n const permissions = parseInvitationPermission(input.permissions ?? 'editor')\n if (!permissions) return { succeeded: false, status: 400, error: 'Invalid permissions' }\n if (!hasWorkspaceRole(accessRow.role, permissions)) {\n return { succeeded: false, status: 403, error: 'Cannot assign higher permissions than your own' }\n }\n\n const email = normalizeInvitationEmail(input.email)\n if (!email) return { succeeded: false, status: 400, error: 'Missing email' }\n if (!isInvitationEmail(email)) return { succeeded: false, status: 400, error: INVITATION_EMAIL_HINT }\n\n const organizationId = accessRow.organization.id\n const workspaceName = (accessRow.workspace as { name: string }).name\n\n await expirePendingInvitations(input.workspaceId, email, now)\n\n const existingPending = await getPendingInvitation(input.workspaceId, email)\n if (existingPending) return { succeeded: false, status: 409, error: 'A pending invitation already exists for this email' }\n\n const accountCheck = await checkExistingAccountAccess(organizationId, input.workspaceId, email, input.invitedByUserId)\n if (!accountCheck.succeeded) return accountCheck\n\n // Seat gate: only a genuinely NEW seat. The checks above reject re-invites,\n // existing workspace members, and org admins; an existing plain org member is\n // already billable (no new seat), so skip the gate for them — mirrors\n // members-api. The pending row is not inserted yet, so the seam's count\n // reflects current usage and denies the invite that would push OVER the limit\n // (at invite time, not accept time).\n if (enforceSeat && !accountCheck.isExistingOrgMember) {\n try {\n await enforceSeat({ actorId: input.invitedByUserId, organizationId })\n } catch (err) {\n if (err instanceof SeatLimitError) return { succeeded: false, status: err.status, error: err.message }\n throw err\n }\n }\n\n const token = generateInvitationToken()\n const expiresAt = getInvitationExpiresAt(now)\n\n const [created] = await db.insert(workspaceInvitations).values({\n workspaceId: input.workspaceId,\n organizationId,\n email,\n invitedByUserId: input.invitedByUserId,\n permissions,\n token,\n status: 'pending',\n emailStatus: 'not_sent',\n expiresAt,\n createdAt: now,\n }).returning()\n\n const inviteUrl = inviteUrlForToken(input.origin, token)\n const emailResult = await sendInvitationEmail({\n to: email,\n workspaceName,\n inviterEmail: accountCheck.inviterEmail ?? productDisplayName,\n permission: permissions,\n inviteUrl,\n expiresAt,\n })\n\n const emailStatus: InvitationEmailStatus = emailResult.succeeded ? 'sent' : 'failed'\n const [updated] = await db.update(workspaceInvitations)\n .set({ emailStatus, lastSentAt: emailResult.succeeded ? now : null })\n .where(eq(workspaceInvitations.id, created!.id))\n .returning()\n\n return {\n succeeded: true,\n value: {\n invitation: toInvitationView(updated!, accountCheck.inviterEmail),\n inviteUrl,\n emailError: emailResult.succeeded ? undefined : emailResult.error,\n },\n }\n }\n\n async function listInvitations(input: {\n workspaceId: string\n userId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitations: Array<WorkspaceInvitationView & { inviteUrl: string }> }>> {\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n await expirePendingInvitations(input.workspaceId, undefined, input.now ?? new Date())\n\n const rows = await db\n .select({ invitation: workspaceInvitations, inviterEmail: users.email })\n .from(workspaceInvitations)\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.workspaceId, input.workspaceId))\n .orderBy(sql`${workspaceInvitations.createdAt} desc`)\n\n return {\n succeeded: true,\n value: {\n invitations: rows.map((row: { invitation: WorkspaceInvitationRow; inviterEmail: string | null }) => ({\n ...toInvitationView(row.invitation, row.inviterEmail),\n inviteUrl: inviteUrlForToken(input.origin, row.invitation.token),\n })),\n },\n }\n }\n\n async function resendInvitation(input: {\n invitationId: string\n userId: string\n origin: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView; inviteUrl: string; emailError?: string }>> {\n const row = await getInvitationById(input.invitationId)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n const accessRow = await access.getWorkspaceAccess(row.invitation.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n\n const now = input.now ?? new Date()\n if (row.invitation.status !== 'pending') {\n return { succeeded: false, status: 409, error: 'Only pending invitations can be resent' }\n }\n if (row.invitation.expiresAt <= now) {\n await markInvitationExpired(row.invitation.id)\n return { succeeded: false, status: 409, error: 'Invitation has expired' }\n }\n\n const workspaceName = (accessRow.workspace as { name: string }).name\n const inviteUrl = inviteUrlForToken(input.origin, row.invitation.token)\n const emailResult = await sendInvitationEmail({\n to: row.invitation.email,\n workspaceName,\n inviterEmail: row.inviterEmail ?? productDisplayName,\n permission: row.invitation.permissions,\n inviteUrl,\n expiresAt: row.invitation.expiresAt,\n })\n\n const [updated] = await db.update(workspaceInvitations)\n .set({\n emailStatus: emailResult.succeeded ? 'sent' : 'failed',\n lastSentAt: emailResult.succeeded ? now : row.invitation.lastSentAt,\n })\n .where(eq(workspaceInvitations.id, row.invitation.id))\n .returning()\n\n return {\n succeeded: true,\n value: {\n invitation: toInvitationView(updated!, row.inviterEmail),\n inviteUrl,\n emailError: emailResult.succeeded ? undefined : emailResult.error,\n },\n }\n }\n\n async function revokeInvitation(input: {\n invitationId: string\n userId: string\n now?: Date\n }): Promise<InvitationOutcome<{ invitation: WorkspaceInvitationView }>> {\n const row = await getInvitationById(input.invitationId)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n const accessRow = await access.getWorkspaceAccess(row.invitation.workspaceId, input.userId, 'admin')\n if (!accessRow) return { succeeded: false, status: 404, error: 'Workspace not found' }\n if (row.invitation.status !== 'pending') {\n return { succeeded: false, status: 409, error: 'Only pending invitations can be revoked' }\n }\n\n const [updated] = await db.update(workspaceInvitations)\n .set({ status: 'revoked', revokedAt: input.now ?? new Date() })\n .where(and(eq(workspaceInvitations.id, row.invitation.id), eq(workspaceInvitations.status, 'pending')))\n .returning()\n\n // The status read above is advisory. A concurrent accept may win between\n // that read and this update, so the write must be compare-and-set.\n if (!updated) return { succeeded: false, status: 409, error: 'The invitation changed. Reload it before continuing.' }\n\n return { succeeded: true, value: { invitation: toInvitationView(updated!, row.inviterEmail) } }\n }\n\n async function getPreview(token: string, now: Date = new Date()): Promise<InvitationOutcome<InvitationPreview>> {\n const row = await getInvitationByToken(token)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n let invitation = row.invitation\n if (invitation.status === 'pending' && invitation.expiresAt <= now) {\n invitation = await markInvitationExpired(invitation.id)\n }\n\n return {\n succeeded: true,\n value: {\n workspaceId: invitation.workspaceId,\n workspaceName: row.workspaceName,\n email: invitation.email,\n inviterEmail: row.inviterEmail,\n permissions: invitation.permissions,\n status: invitation.status,\n expiresAt: invitation.expiresAt,\n },\n }\n }\n\n async function acceptInvitation(input: {\n token: string\n userId: string\n now?: Date\n }): Promise<InvitationOutcome<{ workspaceId: string }>> {\n const now = input.now ?? new Date()\n const row = await getInvitationByToken(input.token)\n if (!row) return { succeeded: false, status: 404, error: 'Invitation not found' }\n\n let invitation = row.invitation\n if (invitation.status === 'pending' && invitation.expiresAt <= now) {\n invitation = await markInvitationExpired(invitation.id)\n }\n\n const [currentUser] = await db\n .select({ id: users.id, email: users.email, emailVerified: users.emailVerified })\n .from(users)\n .where(eq(users.id, input.userId))\n .limit(1)\n if (!currentUser) return { succeeded: false, status: 401, error: 'Authentication required' }\n\n if (normalizeInvitationEmail(currentUser.email) !== invitation.email) {\n return { succeeded: false, status: 403, error: 'Sign in with the invited email address to accept this invitation' }\n }\n\n const collisionCheck = await findUsersByNormalizedEmail(invitation.email)\n if (collisionCheck.length > 1) {\n return {\n succeeded: false,\n status: 409,\n error: 'Multiple accounts use this email. Contact support to reconcile before accepting this invitation.',\n }\n }\n\n let orgMember = await getOrganizationMember(invitation.organizationId, currentUser.id)\n if (orgMember?.role === 'owner' || orgMember?.role === 'admin') {\n return { succeeded: false, status: 409, error: 'This user already has account-level access.' }\n }\n\n if (invitation.status === 'accepted') {\n const existing = orgMember ? await getWorkspaceMemberByOrganizationMember(invitation.workspaceId, orgMember.id) : null\n if (existing) return { succeeded: true, value: { workspaceId: invitation.workspaceId } }\n return { succeeded: false, status: 409, error: 'Invitation has already been accepted' }\n }\n if (invitation.status === 'expired') return { succeeded: false, status: 409, error: 'Invitation has expired' }\n if (invitation.status === 'revoked') return { succeeded: false, status: 409, error: 'Invitation has been revoked' }\n\n if (!orgMember) {\n const [inserted] = await db.insert(organizationMembers).values({\n organizationId: invitation.organizationId,\n userId: currentUser.id,\n role: 'member',\n createdAt: now,\n updatedAt: now,\n }).returning()\n if (!inserted) return { succeeded: false, status: 500, error: 'Failed to create organization membership' }\n orgMember = inserted\n }\n\n const existingMember = await getWorkspaceMemberByOrganizationMember(invitation.workspaceId, orgMember.id)\n if (!existingMember) {\n await db.insert(workspaceMembers).values({\n workspaceId: invitation.workspaceId,\n organizationMemberId: orgMember.id,\n userId: currentUser.id,\n role: invitation.permissions,\n inviteEmail: invitation.email,\n // members-api nulls the token on accept to release the unique slot; the\n // invitations flow keeps it (its `inv_` tokens never collide), so the\n // materialized row carries the originating token for audit.\n inviteToken: invitation.token,\n invitedAt: now,\n acceptedAt: now,\n })\n if (memberSyncSeam?.add) {\n const userId = currentUser.id\n const role = invitation.permissions as WorkspaceRole\n fireSync(() => memberSyncSeam.add!({ workspaceId: invitation.workspaceId, userId, role }))\n }\n }\n\n const [accepted] = await db.update(workspaceInvitations)\n .set({ status: 'accepted', acceptedAt: now })\n .where(and(eq(workspaceInvitations.id, invitation.id), eq(workspaceInvitations.status, 'pending')))\n .returning()\n\n if (!accepted) {\n // Membership was materialized before the final compare-and-set. Remove\n // only the row created by this attempt before reporting the conflict.\n await db.delete(workspaceMembers)\n .where(and(eq(workspaceMembers.workspaceId, invitation.workspaceId), eq(workspaceMembers.userId, currentUser.id)))\n return { succeeded: false, status: 409, error: 'The invitation changed. Reload it before continuing.' }\n }\n\n return { succeeded: true, value: { workspaceId: invitation.workspaceId } }\n }\n\n // ── internal query helpers ──\n\n async function expirePendingInvitations(workspaceId: string, email: string | undefined, now: Date) {\n const conditions = [\n eq(workspaceInvitations.workspaceId, workspaceId),\n eq(workspaceInvitations.status, 'pending' as const),\n lte(workspaceInvitations.expiresAt, now),\n ]\n if (email) conditions.push(eq(workspaceInvitations.email, email))\n await db.update(workspaceInvitations).set({ status: 'expired' }).where(and(...conditions))\n }\n\n async function getPendingInvitation(workspaceId: string, email: string) {\n const [invitation] = await db\n .select({ id: workspaceInvitations.id })\n .from(workspaceInvitations)\n .where(and(\n eq(workspaceInvitations.workspaceId, workspaceId),\n eq(workspaceInvitations.email, email),\n eq(workspaceInvitations.status, 'pending' as const),\n ))\n .limit(1)\n return invitation ?? null\n }\n\n async function checkExistingAccountAccess(\n organizationId: string,\n workspaceId: string,\n email: string,\n invitedByUserId: string,\n ): Promise<\n | { succeeded: false; status: number; error: string }\n | { succeeded: true; inviterEmail: string | null; isExistingOrgMember: boolean }\n > {\n const matchingUsers = await findUsersByNormalizedEmail(email)\n const [inviter] = await db\n .select({ email: users.email })\n .from(users)\n .where(eq(users.id, invitedByUserId))\n .limit(1)\n\n if (matchingUsers.length > 1) {\n return {\n succeeded: false,\n status: 409,\n error: 'Multiple accounts use this email. Contact support to reconcile before inviting this user.',\n }\n }\n const existingUser = matchingUsers[0]\n if (!existingUser) return { succeeded: true, inviterEmail: inviter?.email ?? null, isExistingOrgMember: false }\n\n const orgMember = await getOrganizationMember(organizationId, existingUser.id)\n if (orgMember?.role === 'owner' || orgMember?.role === 'admin') {\n return { succeeded: false, status: 409, error: 'This user already has account-level access.' }\n }\n if (orgMember) {\n const workspaceMember = await getWorkspaceMemberByOrganizationMember(workspaceId, orgMember.id)\n if (workspaceMember) return { succeeded: false, status: 409, error: 'User is already a workspace member' }\n }\n\n return { succeeded: true, inviterEmail: inviter?.email ?? null, isExistingOrgMember: Boolean(orgMember) }\n }\n\n async function findUsersByNormalizedEmail(email: string) {\n return db\n .select({ id: users.id, email: users.email, emailVerified: users.emailVerified })\n .from(users)\n .where(sql`lower(${users.email}) = ${email}`)\n }\n\n async function getOrganizationMember(organizationId: string, userId: string) {\n const [member] = await db\n .select()\n .from(organizationMembers)\n .where(and(eq(organizationMembers.organizationId, organizationId), eq(organizationMembers.userId, userId)))\n .limit(1)\n return member ?? null\n }\n\n async function getWorkspaceMemberByOrganizationMember(workspaceId: string, organizationMemberId: string) {\n const [member] = await db\n .select({ id: workspaceMembers.id })\n .from(workspaceMembers)\n .where(and(\n eq(workspaceMembers.workspaceId, workspaceId),\n eq(workspaceMembers.organizationMemberId, organizationMemberId),\n ))\n .limit(1)\n return member ?? null\n }\n\n async function getInvitationById(invitationId: string) {\n const [row] = await db\n .select({ invitation: workspaceInvitations, inviterEmail: users.email })\n .from(workspaceInvitations)\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.id, invitationId))\n .limit(1)\n return row ?? null\n }\n\n async function getInvitationByToken(token: string) {\n const [row] = await db\n .select({\n invitation: workspaceInvitations,\n workspaceName: workspaces.name,\n inviterEmail: users.email,\n })\n .from(workspaceInvitations)\n .innerJoin(workspaces, eq(workspaces.id, workspaceInvitations.workspaceId))\n .leftJoin(users, eq(users.id, workspaceInvitations.invitedByUserId))\n .where(eq(workspaceInvitations.token, token))\n .limit(1)\n return row ?? null\n }\n\n async function markInvitationExpired(invitationId: string) {\n const [updated] = await db.update(workspaceInvitations)\n .set({ status: 'expired' })\n .where(eq(workspaceInvitations.id, invitationId))\n .returning()\n return updated!\n }\n\n function toInvitationView(invitation: WorkspaceInvitationRow, inviterEmail: string | null): WorkspaceInvitationView {\n return {\n id: invitation.id,\n workspaceId: invitation.workspaceId,\n organizationId: invitation.organizationId,\n email: invitation.email,\n invitedByUserId: invitation.invitedByUserId,\n inviterEmail,\n permissions: invitation.permissions,\n token: invitation.token,\n status: invitation.status,\n emailStatus: invitation.emailStatus,\n expiresAt: invitation.expiresAt,\n createdAt: invitation.createdAt,\n acceptedAt: invitation.acceptedAt,\n revokedAt: invitation.revokedAt,\n lastSentAt: invitation.lastSentAt,\n }\n }\n\n return { createInvitation, listInvitations, resendInvitation, revokeInvitation, getPreview, acceptInvitation }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,SAAS,KAAK,IAAI,KAAK,WAAW;AA+G3B,SAAS,qBAAqB,MAA6B;AAChE,QAAM,EAAE,IAAI,QAAQ,QAAQ,qBAAqB,aAAa,eAAe,IAAI;AACjF,QAAM,EAAE,qBAAqB,iBAAiB,IAAI;AAClD,QAAM,EAAE,qBAAqB,IAAI,KAAK;AACtC,QAAM,QAAQ,KAAK;AACnB,QAAM,aAAa,KAAK;AACxB,QAAM,qBAAqB,KAAK,sBAAsB;AAEtD,WAAS,SAAS,IAAgC;AAChD,QAAI;AACF,cAAQ,QAAQ,GAAG,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IACtC,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,iBAAe,iBAAiB,OAOgF;AAC9G,UAAM,MAAM,MAAM,OAAO,oBAAI,KAAK;AAClC,UAAM,YAAY,MAAM,OAAO,mBAAmB,MAAM,aAAa,MAAM,iBAAiB,OAAO;AACnG,QAAI,CAAC,UAAW,QAAO,EAAE,WAAW,OAAO,QAAQ,KAAK,OAAO,sBAAsB;AAErF,UAAM,cAAc,0BAA0B,MAAM,eAAe,QAAQ;AAC3E,QAAI,CAAC,YAAa,QAAO,EAAE,WAAW,OAAO,QAAQ,KAAK,OAAO,sBAAsB;AACvF,QAAI,CAA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AAO;AAAA,EAChB;AAEA,iBAAe,sBAAsB,cAAsB;AACzD,UAAM,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,oBAAoB,EACnD,IAAI,EAAE,QAAQ,UAAU,CAAC,EACzB,MAAM,GAAG,qBAAqB,IAAI,YAAY,CAAC,EAC/C,UAAU;AACb,WAAO;AAAA,EACT;AAEA,WAAS,iBAAiB,YAAoC,cAAsD;AAClH,WAAO;AAAA,MACL,IAAI,WAAW;AAAA,MACf,aAAa,WAAW;AAAA,MACxB,gBAAgB,WAAW;AAAA,MAC3B,OAAO,WAAW;AAAA,MAClB,iBAAiB,WAAW;AAAA,MAC5B;AAAA,MACA,aAAa,WAAW;AAAA,MACxB,OAAO,WAAW;AAAA,MAClB,QAAQ,WAAW;AAAA,MACnB,aAAa,WAAW;AAAA,MACxB,WAAW,WAAW;AAAA,MACtB,WAAW,WAAW;AAAA,MACtB,YAAY,WAAW;AAAA,MACvB,WAAW,WAAW;AAAA,MACtB,YAAY,WAAW;AAAA,IACzB;AAAA,EACF;AAEA,SAAO,EAAE,kBAAkB,iBAAiB,kBAAkB,kBAAkB,YAAY,iBAAiB;AAC/G;","names":[]}
|
|
@@ -15,6 +15,10 @@ export type InvitationEmailStatus = 'not_sent' | 'sent' | 'failed';
|
|
|
15
15
|
export declare const INVITATION_EXPIRY_DAYS = 7;
|
|
16
16
|
/** Normalize an invitation email by trimming whitespace and converting to lowercase */
|
|
17
17
|
export declare function normalizeInvitationEmail(email: string): string;
|
|
18
|
+
/** Whether an address has the shape an invitation can be delivered to. */
|
|
19
|
+
export declare function isInvitationEmail(email: string): boolean;
|
|
20
|
+
/** What to tell someone whose invite address cannot be delivered to. */
|
|
21
|
+
export declare const INVITATION_EMAIL_HINT = "Enter a full email address, such as name@company.com.";
|
|
18
22
|
/** Resolve invitation permission from a string or return null if invalid */
|
|
19
23
|
export declare function parseInvitationPermission(value: string | undefined): InvitationPermission | null;
|
|
20
24
|
/** Calculate the expiration date of an invitation based on the given or current date */
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The invite-by-email row both team panels share: address, role, Invite. The
|
|
3
|
+
* address is checked with the same rule the invitations API enforces, so
|
|
4
|
+
* Invite stays disabled until the address could be delivered to, and the
|
|
5
|
+
* reason appears under the field once the person leaves it or tries to send.
|
|
6
|
+
* On a narrow card the role and Invite wrap below the field together instead
|
|
7
|
+
* of being pushed past the card's edge.
|
|
8
|
+
*/
|
|
9
|
+
import type { WorkspaceRole } from '../../teams/roles';
|
|
10
|
+
interface InviteFormProps {
|
|
11
|
+
label: string;
|
|
12
|
+
placeholder: string;
|
|
13
|
+
/** Send the invite; resolve true to clear the field, false to keep it for a retry. */
|
|
14
|
+
onInvite(input: {
|
|
15
|
+
email: string;
|
|
16
|
+
role: WorkspaceRole;
|
|
17
|
+
}): Promise<boolean>;
|
|
18
|
+
}
|
|
19
|
+
export declare function InviteForm({ label, placeholder, onInvite }: InviteFormProps): import("react").JSX.Element;
|
|
20
|
+
export {};
|
|
@@ -61,6 +61,8 @@ export interface InvitationView {
|
|
|
61
61
|
emailStatus: InvitationEmailStatus;
|
|
62
62
|
/** Date | epoch-ms | ISO string — normalized to a Date for display. */
|
|
63
63
|
expiresAt: Date | number | string;
|
|
64
|
+
/** When the invitee joined. An accepted row reads "joined <date>" instead of its expiry. */
|
|
65
|
+
acceptedAt?: Date | number | string | null;
|
|
64
66
|
/** Shareable accept link, for copy-to-clipboard. */
|
|
65
67
|
inviteUrl: string;
|
|
66
68
|
}
|