@tangle-network/agent-app 0.28.0 → 0.29.0
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/{DesignCanvasEditor-TN7CWUJW.js → DesignCanvasEditor-IB2FMBBD.js} +3 -3
- package/dist/InviteAcceptPage-EUOGZO2X.js +7 -0
- package/dist/InviteAcceptPage-EUOGZO2X.js.map +1 -0
- package/dist/MembersPanel-4CGUQRPF.js +8 -0
- package/dist/MembersPanel-4CGUQRPF.js.map +1 -0
- package/dist/access-ChAHG4Tp.d.ts +539 -0
- package/dist/chunk-3G334FVA.js +162 -0
- package/dist/chunk-3G334FVA.js.map +1 -0
- package/dist/chunk-3SVAA3MA.js +41 -0
- package/dist/chunk-3SVAA3MA.js.map +1 -0
- package/dist/chunk-535V6BH6.js +128 -0
- package/dist/chunk-535V6BH6.js.map +1 -0
- package/dist/chunk-63CE7FEZ.js +63 -0
- package/dist/chunk-63CE7FEZ.js.map +1 -0
- package/dist/{chunk-7I37CO5D.js → chunk-N4ZFKQ5C.js} +4 -4
- package/dist/{chunk-J7JNV5BH.js → chunk-S5CAJX6O.js} +2 -2
- package/dist/design-canvas-react/index.js +3 -3
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/index.js +7 -7
- package/dist/roles-CLtYKHHl.d.ts +49 -0
- package/dist/teams/drizzle.d.ts +42 -0
- package/dist/teams/drizzle.js +194 -0
- package/dist/teams/drizzle.js.map +1 -0
- package/dist/teams/index.d.ts +44 -0
- package/dist/teams/index.js +39 -0
- package/dist/teams/index.js.map +1 -0
- package/dist/teams/members-api.d.ts +152 -0
- package/dist/teams/members-api.js +261 -0
- package/dist/teams/members-api.js.map +1 -0
- package/dist/teams-react/index.d.ts +81 -0
- package/dist/teams-react/index.js +12 -0
- package/dist/teams-react/index.js.map +1 -0
- package/dist/teams-react/lazy.d.ts +9 -0
- package/dist/teams-react/lazy.js +13 -0
- package/dist/teams-react/lazy.js.map +1 -0
- package/package.json +26 -1
- /package/dist/{DesignCanvasEditor-TN7CWUJW.js.map → DesignCanvasEditor-IB2FMBBD.js.map} +0 -0
- /package/dist/{chunk-7I37CO5D.js.map → chunk-N4ZFKQ5C.js.map} +0 -0
- /package/dist/{chunk-J7JNV5BH.js.map → chunk-S5CAJX6O.js.map} +0 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { T as TeamDatabase, a as TeamTables, O as OrganizationRow, b as OrganizationMemberRow } from '../access-ChAHG4Tp.js';
|
|
2
|
+
export { C as CreateAccessOptions, c as CreateOrganizationAccessOptions, d as CreateTeamTablesOptions, e as OrganizationAccess, f as OrganizationAccessApi, g as TeamParentTable, U as UserWorkspaceSummary, W as WorkspaceAccess, h as WorkspaceAccessApi, i as WorkspaceAccessTable, j as WorkspaceMemberRow, k as createOrganizationAccess, l as createTeamTables, m as createWorkspaceAccess } from '../access-ChAHG4Tp.js';
|
|
3
|
+
import { O as OrganizationRole } from '../roles-CLtYKHHl.js';
|
|
4
|
+
import 'drizzle-orm/sqlite-core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `ensurePersonalOrganization` — the substrate that makes solo-user adoption
|
|
8
|
+
* work. Every user gets exactly one auto-created `kind: 'personal'` org with
|
|
9
|
+
* the user as `owner` member. That org is the tenant that owns their
|
|
10
|
+
* workspaces, so role resolution (`getWorkspaceAccess`) has an org row to read
|
|
11
|
+
* even before any team/invite exists.
|
|
12
|
+
*
|
|
13
|
+
* Idempotent by construction: the org `slug` is derived from the user id
|
|
14
|
+
* (`personal-<id>`) and upserted; the membership upserts on the
|
|
15
|
+
* (organizationId, userId) unique index. Concurrent calls converge — no
|
|
16
|
+
* duplicate personal orgs, no duplicate owner rows.
|
|
17
|
+
*
|
|
18
|
+
* ADOPTION CONTRACT: call this once per user at first authenticated entry
|
|
19
|
+
* (e.g. right after sign-in / session bootstrap) BEFORE the first
|
|
20
|
+
* `getWorkspaceAccess`. Role resolution requires the org membership to exist;
|
|
21
|
+
* an adopter that skips this will see `null` access for a brand-new user with
|
|
22
|
+
* no org row. There is no implicit creation inside the access builders — that
|
|
23
|
+
* keeps reads side-effect-free; provisioning is this explicit call.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
interface EnsurePersonalOrganizationUser {
|
|
27
|
+
id: string;
|
|
28
|
+
name?: string | null;
|
|
29
|
+
email?: string | null;
|
|
30
|
+
}
|
|
31
|
+
interface PersonalOrganizationResult {
|
|
32
|
+
organization: OrganizationRow;
|
|
33
|
+
member: OrganizationMemberRow;
|
|
34
|
+
role: OrganizationRole;
|
|
35
|
+
}
|
|
36
|
+
interface CreatePersonalOrganizationOptions {
|
|
37
|
+
db: TeamDatabase;
|
|
38
|
+
tables: TeamTables;
|
|
39
|
+
}
|
|
40
|
+
declare function createEnsurePersonalOrganization(opts: CreatePersonalOrganizationOptions): (user: EnsurePersonalOrganizationUser) => Promise<PersonalOrganizationResult>;
|
|
41
|
+
|
|
42
|
+
export { type CreatePersonalOrganizationOptions, type EnsurePersonalOrganizationUser, OrganizationMemberRow, OrganizationRow, type PersonalOrganizationResult, TeamDatabase, TeamTables, createEnsurePersonalOrganization };
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hasOrganizationRole,
|
|
3
|
+
hasWorkspaceRole,
|
|
4
|
+
resolveWorkspaceRole
|
|
5
|
+
} from "../chunk-63CE7FEZ.js";
|
|
6
|
+
|
|
7
|
+
// src/teams/drizzle/schema.ts
|
|
8
|
+
import { sql } from "drizzle-orm";
|
|
9
|
+
import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
10
|
+
var hexId = () => text("id").primaryKey().default(sql`(lower(hex(randomblob(16))))`);
|
|
11
|
+
var createdAt = () => integer("created_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
12
|
+
var updatedAt = () => integer("updated_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`);
|
|
13
|
+
function createTeamTables(opts) {
|
|
14
|
+
const { userTable, workspaceTable } = opts;
|
|
15
|
+
const organizations = sqliteTable("organization", {
|
|
16
|
+
id: hexId(),
|
|
17
|
+
name: text("name").notNull(),
|
|
18
|
+
slug: text("slug").notNull().unique(),
|
|
19
|
+
kind: text("kind", { enum: ["personal", "team"] }).notNull().default("personal"),
|
|
20
|
+
createdBy: text("created_by").notNull().references(() => userTable.id, { onDelete: "cascade" }),
|
|
21
|
+
createdAt: createdAt(),
|
|
22
|
+
updatedAt: updatedAt()
|
|
23
|
+
}, (table) => [
|
|
24
|
+
index("idx_organization_created_by").on(table.createdBy)
|
|
25
|
+
]);
|
|
26
|
+
const organizationMembers = sqliteTable("organization_member", {
|
|
27
|
+
id: hexId(),
|
|
28
|
+
organizationId: text("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
|
29
|
+
userId: text("user_id").notNull().references(() => userTable.id, { onDelete: "cascade" }),
|
|
30
|
+
role: text("role", { enum: ["owner", "admin", "member", "billing"] }).notNull().default("member"),
|
|
31
|
+
createdAt: createdAt(),
|
|
32
|
+
updatedAt: updatedAt()
|
|
33
|
+
}, (table) => [
|
|
34
|
+
uniqueIndex("uniq_org_member_user").on(table.organizationId, table.userId),
|
|
35
|
+
index("idx_org_member_user").on(table.userId)
|
|
36
|
+
]);
|
|
37
|
+
const workspaceMembers = sqliteTable("workspace_member", {
|
|
38
|
+
id: hexId(),
|
|
39
|
+
workspaceId: text("workspace_id").notNull().references(() => workspaceTable.id, { onDelete: "cascade" }),
|
|
40
|
+
organizationMemberId: text("organization_member_id").references(() => organizationMembers.id, { onDelete: "cascade" }),
|
|
41
|
+
userId: text("user_id").references(() => userTable.id, { onDelete: "cascade" }),
|
|
42
|
+
role: text("role", { enum: ["owner", "admin", "editor", "viewer"] }).notNull().default("editor"),
|
|
43
|
+
invitedBy: text("invited_by"),
|
|
44
|
+
inviteEmail: text("invite_email"),
|
|
45
|
+
inviteToken: text("invite_token"),
|
|
46
|
+
invitedAt: integer("invited_at", { mode: "timestamp" }).notNull().default(sql`(unixepoch())`),
|
|
47
|
+
acceptedAt: integer("accepted_at", { mode: "timestamp" })
|
|
48
|
+
}, (table) => [
|
|
49
|
+
uniqueIndex("uniq_workspace_member_org_member").on(table.workspaceId, table.organizationMemberId),
|
|
50
|
+
index("idx_workspace_member_user").on(table.workspaceId, table.userId),
|
|
51
|
+
index("idx_member_user").on(table.userId),
|
|
52
|
+
uniqueIndex("idx_member_invite_token").on(table.inviteToken)
|
|
53
|
+
]);
|
|
54
|
+
return { organizations, organizationMembers, workspaceMembers };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/teams/drizzle/access.ts
|
|
58
|
+
import { and, desc, eq, isNotNull } from "drizzle-orm";
|
|
59
|
+
function createWorkspaceAccess(opts) {
|
|
60
|
+
const { db, tables, workspaceTable } = opts;
|
|
61
|
+
const { organizations, organizationMembers, workspaceMembers } = tables;
|
|
62
|
+
const workspaces = workspaceTable;
|
|
63
|
+
async function getWorkspaceAccess(workspaceId, userId, minRole = "viewer") {
|
|
64
|
+
const [row] = await db.select({
|
|
65
|
+
workspace: workspaces,
|
|
66
|
+
organization: organizations,
|
|
67
|
+
organizationMember: organizationMembers,
|
|
68
|
+
projectRole: workspaceMembers.role,
|
|
69
|
+
acceptedAt: workspaceMembers.acceptedAt
|
|
70
|
+
}).from(workspaces).innerJoin(organizations, eq(organizations.id, workspaces.organizationId)).innerJoin(organizationMembers, and(
|
|
71
|
+
eq(organizationMembers.organizationId, workspaces.organizationId),
|
|
72
|
+
eq(organizationMembers.userId, userId)
|
|
73
|
+
)).leftJoin(workspaceMembers, and(
|
|
74
|
+
eq(workspaceMembers.workspaceId, workspaces.id),
|
|
75
|
+
eq(workspaceMembers.organizationMemberId, organizationMembers.id),
|
|
76
|
+
isNotNull(workspaceMembers.acceptedAt)
|
|
77
|
+
)).where(eq(workspaces.id, workspaceId)).limit(1);
|
|
78
|
+
if (!row) return null;
|
|
79
|
+
const role = resolveWorkspaceRole(row.organizationMember.role, row.projectRole);
|
|
80
|
+
if (!role) return null;
|
|
81
|
+
if (!hasWorkspaceRole(role, minRole)) return null;
|
|
82
|
+
return {
|
|
83
|
+
workspace: row.workspace,
|
|
84
|
+
organization: row.organization,
|
|
85
|
+
organizationMember: row.organizationMember,
|
|
86
|
+
role
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async function requireWorkspaceAccess(workspaceId, userId, minRole = "viewer") {
|
|
90
|
+
const access = await getWorkspaceAccess(workspaceId, userId, minRole);
|
|
91
|
+
if (!access) throw new Response("Workspace not found", { status: 404 });
|
|
92
|
+
return access;
|
|
93
|
+
}
|
|
94
|
+
async function listUserWorkspaces(userId) {
|
|
95
|
+
const rows = await db.select({
|
|
96
|
+
workspace: workspaces,
|
|
97
|
+
organization: organizations,
|
|
98
|
+
organizationMember: organizationMembers,
|
|
99
|
+
projectRole: workspaceMembers.role
|
|
100
|
+
}).from(workspaces).innerJoin(organizations, eq(organizations.id, workspaces.organizationId)).innerJoin(organizationMembers, and(
|
|
101
|
+
eq(organizationMembers.organizationId, workspaces.organizationId),
|
|
102
|
+
eq(organizationMembers.userId, userId)
|
|
103
|
+
)).leftJoin(workspaceMembers, and(
|
|
104
|
+
eq(workspaceMembers.workspaceId, workspaces.id),
|
|
105
|
+
eq(workspaceMembers.organizationMemberId, organizationMembers.id),
|
|
106
|
+
isNotNull(workspaceMembers.acceptedAt)
|
|
107
|
+
)).orderBy(desc(workspaces.updatedAt));
|
|
108
|
+
return rows.flatMap((row) => {
|
|
109
|
+
const role = resolveWorkspaceRole(row.organizationMember.role, row.projectRole);
|
|
110
|
+
if (!role) return [];
|
|
111
|
+
return [{
|
|
112
|
+
...row.workspace,
|
|
113
|
+
organizationId: row.organization.id,
|
|
114
|
+
organizationName: row.organization.name,
|
|
115
|
+
role
|
|
116
|
+
}];
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return { getWorkspaceAccess, requireWorkspaceAccess, listUserWorkspaces };
|
|
120
|
+
}
|
|
121
|
+
function createOrganizationAccess(opts) {
|
|
122
|
+
const { db, tables } = opts;
|
|
123
|
+
const { organizations, organizationMembers } = tables;
|
|
124
|
+
async function getOrganizationAccess(organizationId, userId, minRole = "member") {
|
|
125
|
+
const [row] = await db.select({
|
|
126
|
+
organization: organizations,
|
|
127
|
+
member: organizationMembers
|
|
128
|
+
}).from(organizationMembers).innerJoin(organizations, eq(organizations.id, organizationMembers.organizationId)).where(and(
|
|
129
|
+
eq(organizationMembers.organizationId, organizationId),
|
|
130
|
+
eq(organizationMembers.userId, userId)
|
|
131
|
+
)).limit(1);
|
|
132
|
+
if (!row) return null;
|
|
133
|
+
const role = row.member.role;
|
|
134
|
+
if (!hasOrganizationRole(role, minRole)) return null;
|
|
135
|
+
return { organization: row.organization, member: row.member, role };
|
|
136
|
+
}
|
|
137
|
+
async function requireOrganizationAccess(organizationId, userId, minRole = "member") {
|
|
138
|
+
const access = await getOrganizationAccess(organizationId, userId, minRole);
|
|
139
|
+
if (!access) throw new Response("Organization not found", { status: 404 });
|
|
140
|
+
return access;
|
|
141
|
+
}
|
|
142
|
+
return { getOrganizationAccess, requireOrganizationAccess };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/teams/drizzle/personal-organization.ts
|
|
146
|
+
import { and as and2, eq as eq2 } from "drizzle-orm";
|
|
147
|
+
function createEnsurePersonalOrganization(opts) {
|
|
148
|
+
const { db, tables } = opts;
|
|
149
|
+
const { organizations, organizationMembers } = tables;
|
|
150
|
+
return async function ensurePersonalOrganization(user) {
|
|
151
|
+
const [existing] = await db.select({
|
|
152
|
+
organization: organizations,
|
|
153
|
+
member: organizationMembers
|
|
154
|
+
}).from(organizationMembers).innerJoin(organizations, eq2(organizations.id, organizationMembers.organizationId)).where(and2(
|
|
155
|
+
eq2(organizationMembers.userId, user.id),
|
|
156
|
+
eq2(organizations.kind, "personal")
|
|
157
|
+
)).limit(1);
|
|
158
|
+
if (existing) {
|
|
159
|
+
return {
|
|
160
|
+
organization: existing.organization,
|
|
161
|
+
member: existing.member,
|
|
162
|
+
role: existing.member.role
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const orgName = user.name?.trim() || user.email?.split("@")[0] || "Personal";
|
|
166
|
+
const slug = `personal-${user.id}`;
|
|
167
|
+
const [organization] = await db.insert(organizations).values({
|
|
168
|
+
name: `${orgName}'s Organization`,
|
|
169
|
+
slug,
|
|
170
|
+
kind: "personal",
|
|
171
|
+
createdBy: user.id
|
|
172
|
+
}).onConflictDoUpdate({
|
|
173
|
+
target: organizations.slug,
|
|
174
|
+
set: { updatedAt: /* @__PURE__ */ new Date() }
|
|
175
|
+
}).returning();
|
|
176
|
+
const org = organization;
|
|
177
|
+
const [member] = await db.insert(organizationMembers).values({
|
|
178
|
+
organizationId: org.id,
|
|
179
|
+
userId: user.id,
|
|
180
|
+
role: "owner"
|
|
181
|
+
}).onConflictDoUpdate({
|
|
182
|
+
target: [organizationMembers.organizationId, organizationMembers.userId],
|
|
183
|
+
set: { role: "owner", updatedAt: /* @__PURE__ */ new Date() }
|
|
184
|
+
}).returning();
|
|
185
|
+
return { organization: org, member, role: "owner" };
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
export {
|
|
189
|
+
createEnsurePersonalOrganization,
|
|
190
|
+
createOrganizationAccess,
|
|
191
|
+
createTeamTables,
|
|
192
|
+
createWorkspaceAccess
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=drizzle.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/teams/drizzle/schema.ts","../../src/teams/drizzle/access.ts","../../src/teams/drizzle/personal-organization.ts"],"sourcesContent":["/**\n * Drizzle schema factory for the teams tables. The product owns the user and\n * workspace tables; this factory creates the tenancy/membership tables and\n * wires their foreign keys into the passed-in tables so the whole graph lives\n * in one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror gtm's hand-rolled tables so a product\n * with those tables can adopt the factory without rewriting rows.\n *\n * The three tables and their roles:\n * - `organization` — the TENANT/ownership primitive. `kind` is 'personal'\n * (one auto-created per user; see ensurePersonalOrganization) or 'team'.\n * This is what owns workspaces and what billing/seats attach to.\n * - `organizationMember` — who belongs to an org and at what org role.\n * - `workspaceMember` — the additive invite/member surface: per-workspace\n * access grants, including pending email-only invites carrying a token.\n *\n * Imports `drizzle-orm` at module top — that is WHY this lives behind the\n * `/teams/drizzle` sub-subpath. The pure `./teams` leaf imports none of this,\n * so a consumer that never touches the DB never pulls the optional peer.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable } from 'drizzle-orm/sqlite-core'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type TeamParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\nexport interface CreateTeamTablesOptions {\n /** The product's user table — org/member rows reference `userTable.id`. */\n userTable: TeamParentTable\n /** The product's workspace table — workspace members reference `workspaceTable.id`. */\n workspaceTable: TeamParentTable\n}\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nexport function createTeamTables(opts: CreateTeamTablesOptions) {\n const { userTable, workspaceTable } = opts\n\n const organizations = sqliteTable('organization', {\n id: hexId(),\n name: text('name').notNull(),\n slug: text('slug').notNull().unique(),\n kind: text('kind', { enum: ['personal', 'team'] }).notNull().default('personal'),\n createdBy: text('created_by').notNull().references(() => userTable.id, { onDelete: 'cascade' }),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n }, (table) => [\n index('idx_organization_created_by').on(table.createdBy),\n ])\n\n const organizationMembers = sqliteTable('organization_member', {\n id: hexId(),\n organizationId: text('organization_id').notNull().references(() => organizations.id, { onDelete: 'cascade' }),\n userId: text('user_id').notNull().references(() => userTable.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['owner', 'admin', 'member', 'billing'] }).notNull().default('member'),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n }, (table) => [\n uniqueIndex('uniq_org_member_user').on(table.organizationId, table.userId),\n index('idx_org_member_user').on(table.userId),\n ])\n\n const workspaceMembers = sqliteTable('workspace_member', {\n id: hexId(),\n workspaceId: text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' }),\n organizationMemberId: text('organization_member_id').references(() => organizationMembers.id, { onDelete: 'cascade' }),\n userId: text('user_id').references(() => userTable.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['owner', 'admin', 'editor', 'viewer'] }).notNull().default('editor'),\n invitedBy: text('invited_by'),\n inviteEmail: text('invite_email'),\n inviteToken: text('invite_token'),\n invitedAt: integer('invited_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),\n acceptedAt: integer('accepted_at', { mode: 'timestamp' }),\n }, (table) => [\n uniqueIndex('uniq_workspace_member_org_member').on(table.workspaceId, table.organizationMemberId),\n index('idx_workspace_member_user').on(table.workspaceId, table.userId),\n index('idx_member_user').on(table.userId),\n uniqueIndex('idx_member_invite_token').on(table.inviteToken),\n ])\n\n return { organizations, organizationMembers, workspaceMembers }\n}\n\nexport type TeamTables = ReturnType<typeof createTeamTables>\n\nexport type OrganizationRow = TeamTables['organizations']['$inferSelect']\nexport type OrganizationMemberRow = TeamTables['organizationMembers']['$inferSelect']\nexport type WorkspaceMemberRow = TeamTables['workspaceMembers']['$inferSelect']\n","/**\n * RBAC access builders over the teams tables. `createWorkspaceAccess` and\n * `createOrganizationAccess` close over the product's `db`, the tables from\n * `createTeamTables`, and the product's `workspace` table, returning the exact\n * `getWorkspaceAccess` / `requireWorkspaceAccess` / `listUserWorkspaces` /\n * `getOrganizationAccess` / `requireOrganizationAccess` functions a consumer\n * already calls — so adoption is a one-line import swap, every call site stays\n * identical.\n *\n * Defense in depth: org owners/admins are workspace owners across the org;\n * everyone else gets their explicit per-workspace role. Effective role is the\n * fold in `resolveWorkspaceRole` (pure, from `../roles`). Every query pins\n * `userId`, so a leaked id can never read across the tenancy boundary — it\n * surfaces as \"not found\".\n *\n * Driver-agnostic: builders are awaited, never `.run()`/`.all()`, so\n * better-sqlite3, D1, and libsql handles all behave identically.\n */\n\nimport { and, desc, eq, isNotNull } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n type OrganizationRole,\n type WorkspaceRole,\n hasOrganizationRole,\n hasWorkspaceRole,\n resolveWorkspaceRole,\n} from '../roles'\nimport type { TeamParentTable } from './schema'\nimport type { OrganizationMemberRow, OrganizationRow, TeamTables } from './schema'\n\n/** Any SQLite drizzle database — `any` erases driver-specific generics so\n * better-sqlite3, D1, and libsql handles all fit. */\nexport type TeamDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>\n\n/**\n * The product's workspace table, narrowed to the columns the access joins read.\n * Adopters pass their real drizzle workspace table — it carries these columns\n * (gtm's does); the type only asserts the minimum the joins touch.\n */\nexport interface WorkspaceAccessTable {\n id: any\n organizationId: any\n name: any\n updatedAt: any\n}\n\nexport interface CreateAccessOptions {\n db: TeamDatabase\n tables: TeamTables\n /** The product's workspace table (the FK target passed to createTeamTables). */\n workspaceTable: TeamParentTable & WorkspaceAccessTable\n}\n\nexport interface WorkspaceAccess {\n workspace: Record<string, unknown>\n organization: OrganizationRow\n organizationMember: OrganizationMemberRow\n role: WorkspaceRole\n}\n\nexport interface UserWorkspaceSummary extends Record<string, unknown> {\n organizationId: string\n organizationName: string\n role: WorkspaceRole\n}\n\nexport interface WorkspaceAccessApi {\n getWorkspaceAccess(workspaceId: string, userId: string, minRole?: WorkspaceRole): Promise<WorkspaceAccess | null>\n requireWorkspaceAccess(workspaceId: string, userId: string, minRole?: WorkspaceRole): Promise<WorkspaceAccess>\n listUserWorkspaces(userId: string): Promise<UserWorkspaceSummary[]>\n}\n\nexport function createWorkspaceAccess(opts: CreateAccessOptions): WorkspaceAccessApi {\n const { db, tables, workspaceTable } = opts\n const { organizations, organizationMembers, workspaceMembers } = tables\n const workspaces = workspaceTable\n\n async function getWorkspaceAccess(\n workspaceId: string,\n userId: string,\n minRole: WorkspaceRole = 'viewer',\n ): Promise<WorkspaceAccess | null> {\n const [row] = await db\n .select({\n workspace: workspaces,\n organization: organizations,\n organizationMember: organizationMembers,\n projectRole: workspaceMembers.role,\n acceptedAt: workspaceMembers.acceptedAt,\n })\n .from(workspaces)\n .innerJoin(organizations, eq(organizations.id, workspaces.organizationId))\n .innerJoin(organizationMembers, and(\n eq(organizationMembers.organizationId, workspaces.organizationId),\n eq(organizationMembers.userId, userId),\n ))\n .leftJoin(workspaceMembers, and(\n eq(workspaceMembers.workspaceId, workspaces.id),\n eq(workspaceMembers.organizationMemberId, organizationMembers.id),\n isNotNull(workspaceMembers.acceptedAt),\n ))\n .where(eq(workspaces.id, workspaceId))\n .limit(1)\n\n if (!row) return null\n\n const role = resolveWorkspaceRole(row.organizationMember.role, row.projectRole as WorkspaceRole | null)\n if (!role) return null\n if (!hasWorkspaceRole(role, minRole)) return null\n\n return {\n workspace: row.workspace as Record<string, unknown>,\n organization: row.organization,\n organizationMember: row.organizationMember,\n role,\n }\n }\n\n async function requireWorkspaceAccess(\n workspaceId: string,\n userId: string,\n minRole: WorkspaceRole = 'viewer',\n ): Promise<WorkspaceAccess> {\n const access = await getWorkspaceAccess(workspaceId, userId, minRole)\n if (!access) throw new Response('Workspace not found', { status: 404 })\n return access\n }\n\n async function listUserWorkspaces(userId: string): Promise<UserWorkspaceSummary[]> {\n const rows = await db\n .select({\n workspace: workspaces,\n organization: organizations,\n organizationMember: organizationMembers,\n projectRole: workspaceMembers.role,\n })\n .from(workspaces)\n .innerJoin(organizations, eq(organizations.id, workspaces.organizationId))\n .innerJoin(organizationMembers, and(\n eq(organizationMembers.organizationId, workspaces.organizationId),\n eq(organizationMembers.userId, userId),\n ))\n .leftJoin(workspaceMembers, and(\n eq(workspaceMembers.workspaceId, workspaces.id),\n eq(workspaceMembers.organizationMemberId, organizationMembers.id),\n isNotNull(workspaceMembers.acceptedAt),\n ))\n // Most recently active workspace first, so callers taking rows[0] as the\n // default pick the freshest one.\n .orderBy(desc(workspaces.updatedAt))\n\n return rows.flatMap((row: any) => {\n const role = resolveWorkspaceRole(row.organizationMember.role, row.projectRole as WorkspaceRole | null)\n if (!role) return []\n return [{\n ...(row.workspace as Record<string, unknown>),\n organizationId: row.organization.id,\n organizationName: row.organization.name,\n role,\n } as UserWorkspaceSummary]\n })\n }\n\n return { getWorkspaceAccess, requireWorkspaceAccess, listUserWorkspaces }\n}\n\nexport interface OrganizationAccess {\n organization: OrganizationRow\n member: OrganizationMemberRow\n role: OrganizationRole\n}\n\nexport interface OrganizationAccessApi {\n getOrganizationAccess(organizationId: string, userId: string, minRole?: OrganizationRole): Promise<OrganizationAccess | null>\n requireOrganizationAccess(organizationId: string, userId: string, minRole?: OrganizationRole): Promise<OrganizationAccess>\n}\n\nexport interface CreateOrganizationAccessOptions {\n db: TeamDatabase\n tables: TeamTables\n}\n\nexport function createOrganizationAccess(opts: CreateOrganizationAccessOptions): OrganizationAccessApi {\n const { db, tables } = opts\n const { organizations, organizationMembers } = tables\n\n async function getOrganizationAccess(\n organizationId: string,\n userId: string,\n minRole: OrganizationRole = 'member',\n ): Promise<OrganizationAccess | null> {\n const [row] = await db\n .select({\n organization: organizations,\n member: organizationMembers,\n })\n .from(organizationMembers)\n .innerJoin(organizations, eq(organizations.id, organizationMembers.organizationId))\n .where(and(\n eq(organizationMembers.organizationId, organizationId),\n eq(organizationMembers.userId, userId),\n ))\n .limit(1)\n\n if (!row) return null\n const role = row.member.role as OrganizationRole\n if (!hasOrganizationRole(role, minRole)) return null\n return { organization: row.organization, member: row.member, role }\n }\n\n async function requireOrganizationAccess(\n organizationId: string,\n userId: string,\n minRole: OrganizationRole = 'member',\n ): Promise<OrganizationAccess> {\n const access = await getOrganizationAccess(organizationId, userId, minRole)\n if (!access) throw new Response('Organization not found', { status: 404 })\n return access\n }\n\n return { getOrganizationAccess, requireOrganizationAccess }\n}\n","/**\n * `ensurePersonalOrganization` — the substrate that makes solo-user adoption\n * work. Every user gets exactly one auto-created `kind: 'personal'` org with\n * the user as `owner` member. That org is the tenant that owns their\n * workspaces, so role resolution (`getWorkspaceAccess`) has an org row to read\n * even before any team/invite exists.\n *\n * Idempotent by construction: the org `slug` is derived from the user id\n * (`personal-<id>`) and upserted; the membership upserts on the\n * (organizationId, userId) unique index. Concurrent calls converge — no\n * duplicate personal orgs, no duplicate owner rows.\n *\n * ADOPTION CONTRACT: call this once per user at first authenticated entry\n * (e.g. right after sign-in / session bootstrap) BEFORE the first\n * `getWorkspaceAccess`. Role resolution requires the org membership to exist;\n * an adopter that skips this will see `null` access for a brand-new user with\n * no org row. There is no implicit creation inside the access builders — that\n * keeps reads side-effect-free; provisioning is this explicit call.\n */\n\nimport { and, eq } from 'drizzle-orm'\nimport type { OrganizationRole } from '../roles'\nimport type { TeamDatabase } from './access'\nimport type { OrganizationMemberRow, OrganizationRow, TeamTables } from './schema'\n\nexport interface EnsurePersonalOrganizationUser {\n id: string\n name?: string | null\n email?: string | null\n}\n\nexport interface PersonalOrganizationResult {\n organization: OrganizationRow\n member: OrganizationMemberRow\n role: OrganizationRole\n}\n\nexport interface CreatePersonalOrganizationOptions {\n db: TeamDatabase\n tables: TeamTables\n}\n\nexport function createEnsurePersonalOrganization(opts: CreatePersonalOrganizationOptions) {\n const { db, tables } = opts\n const { organizations, organizationMembers } = tables\n\n return async function ensurePersonalOrganization(\n user: EnsurePersonalOrganizationUser,\n ): Promise<PersonalOrganizationResult> {\n const [existing] = await db\n .select({\n organization: organizations,\n member: organizationMembers,\n })\n .from(organizationMembers)\n .innerJoin(organizations, eq(organizations.id, organizationMembers.organizationId))\n .where(and(\n eq(organizationMembers.userId, user.id),\n eq(organizations.kind, 'personal'),\n ))\n .limit(1)\n\n if (existing) {\n return {\n organization: existing.organization,\n member: existing.member,\n role: existing.member.role as OrganizationRole,\n }\n }\n\n const orgName = user.name?.trim() || user.email?.split('@')[0] || 'Personal'\n const slug = `personal-${user.id}`\n const [organization] = await db\n .insert(organizations)\n .values({\n name: `${orgName}'s Organization`,\n slug,\n kind: 'personal',\n createdBy: user.id,\n })\n .onConflictDoUpdate({\n target: organizations.slug,\n set: { updatedAt: new Date() },\n })\n .returning()\n\n // A single-row upsert with .returning() always yields exactly one row.\n const org = organization as OrganizationRow\n\n const [member] = await db\n .insert(organizationMembers)\n .values({\n organizationId: org.id,\n userId: user.id,\n role: 'owner',\n })\n .onConflictDoUpdate({\n target: [organizationMembers.organizationId, organizationMembers.userId],\n set: { role: 'owner', updatedAt: new Date() },\n })\n .returning()\n\n return { organization: org, member: member as OrganizationMemberRow, role: 'owner' }\n }\n}\n"],"mappings":";;;;;;;AAqBA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,aAAa,MAAM,mBAAmB;AAa/D,IAAM,QAAQ,MAAM,KAAK,IAAI,EAAE,WAAW,EAAE,QAAQ,iCAAiC;AAErF,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAEzG,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAElG,SAAS,iBAAiB,MAA+B;AAC9D,QAAM,EAAE,WAAW,eAAe,IAAI;AAEtC,QAAM,gBAAgB,YAAY,gBAAgB;AAAA,IAChD,IAAI,MAAM;AAAA,IACV,MAAM,KAAK,MAAM,EAAE,QAAQ;AAAA,IAC3B,MAAM,KAAK,MAAM,EAAE,QAAQ,EAAE,OAAO;AAAA,IACpC,MAAM,KAAK,QAAQ,EAAE,MAAM,CAAC,YAAY,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,UAAU;AAAA,IAC/E,WAAW,KAAK,YA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B,gBAAgB,oBAAoB,MAAM;AAAA,MACvE,KAAK,EAAE,MAAM,SAAS,WAAW,oBAAI,KAAK,EAAE;AAAA,IAC9C,CAAC,EACA,UAAU;AAEb,WAAO,EAAE,cAAc,KAAK,QAAyC,MAAM,QAAQ;AAAA,EACrF;AACF;","names":["and","eq"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export { A as ASSIGNABLE_WORKSPACE_ROLES, a as AssignableWorkspaceRole, b as ORGANIZATION_ROLES, c as ORGANIZATION_ROLE_RANK, O as OrganizationRole, S as SandboxWorkspaceRole, W as WORKSPACE_ROLES, d as WORKSPACE_ROLE_RANK, e as WorkspaceCollaborationAccess, f as WorkspaceRole, g as canManageWorkspaceMemberRole, h as hasOrganizationRole, i as hasWorkspaceRole, j as isAssignableWorkspaceRole, o as organizationRoleGrantsWorkspaceOwner, r as resolveWorkspaceRole, w as workspaceRoleToCollaborationAccess, k as workspaceRoleToSandboxRole } from '../roles-CLtYKHHl.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pure invite-token helpers — generation, shape validation, and expiry math.
|
|
5
|
+
* No I/O: the members API persists/looks up tokens; these functions only
|
|
6
|
+
* produce well-formed tokens and decide, given values the caller already
|
|
7
|
+
* loaded, whether an invite is usable.
|
|
8
|
+
*
|
|
9
|
+
* A token is an opaque high-entropy URL-safe string. It is the bearer secret
|
|
10
|
+
* in `/invite/:token`, so it must be unguessable and never derived from the
|
|
11
|
+
* email or workspace. `generateInviteToken` uses Web Crypto (`crypto`), which
|
|
12
|
+
* is present in Workers, Node 18+, Deno, and browsers — no Node-only import,
|
|
13
|
+
* so this stays a pure leaf.
|
|
14
|
+
*/
|
|
15
|
+
/** Cryptographically-random, URL-safe (base64url) invite token. */
|
|
16
|
+
declare function generateInviteToken(): string;
|
|
17
|
+
/** True when `value` has the shape of an invite token (not whether it exists). */
|
|
18
|
+
declare function isInviteTokenShape(value: unknown): value is string;
|
|
19
|
+
/** A pending invite row, narrowed to the fields invite acceptance reasons over. */
|
|
20
|
+
interface InviteTokenState {
|
|
21
|
+
/** null until accepted — a non-null value means the invite was already used. */
|
|
22
|
+
acceptedAt: Date | number | null | undefined;
|
|
23
|
+
/** Email the invite was addressed to, if any. */
|
|
24
|
+
inviteEmail?: string | null;
|
|
25
|
+
/** Optional hard expiry; omit/undefined for invites that never expire. */
|
|
26
|
+
expiresAt?: Date | number | null;
|
|
27
|
+
}
|
|
28
|
+
type InviteRejectionReason = 'already-accepted' | 'expired' | 'email-mismatch';
|
|
29
|
+
interface InviteValidationResult {
|
|
30
|
+
ok: boolean;
|
|
31
|
+
reason?: InviteRejectionReason;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Decide whether a loaded invite can be accepted by `acceptingEmail` at `now`.
|
|
35
|
+
* Pure: the caller has already fetched the row by token; this only judges it.
|
|
36
|
+
* Email match is case-insensitive and only enforced when the invite was
|
|
37
|
+
* addressed to a specific email (an open invite has no `inviteEmail`).
|
|
38
|
+
*/
|
|
39
|
+
declare function validateInviteToken(invite: InviteTokenState, opts?: {
|
|
40
|
+
acceptingEmail?: string | null;
|
|
41
|
+
now?: Date;
|
|
42
|
+
}): InviteValidationResult;
|
|
43
|
+
|
|
44
|
+
export { type InviteRejectionReason, type InviteTokenState, type InviteValidationResult, generateInviteToken, isInviteTokenShape, validateInviteToken };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateInviteToken,
|
|
3
|
+
isInviteTokenShape,
|
|
4
|
+
validateInviteToken
|
|
5
|
+
} from "../chunk-3SVAA3MA.js";
|
|
6
|
+
import {
|
|
7
|
+
ASSIGNABLE_WORKSPACE_ROLES,
|
|
8
|
+
ORGANIZATION_ROLES,
|
|
9
|
+
ORGANIZATION_ROLE_RANK,
|
|
10
|
+
WORKSPACE_ROLES,
|
|
11
|
+
WORKSPACE_ROLE_RANK,
|
|
12
|
+
canManageWorkspaceMemberRole,
|
|
13
|
+
hasOrganizationRole,
|
|
14
|
+
hasWorkspaceRole,
|
|
15
|
+
isAssignableWorkspaceRole,
|
|
16
|
+
organizationRoleGrantsWorkspaceOwner,
|
|
17
|
+
resolveWorkspaceRole,
|
|
18
|
+
workspaceRoleToCollaborationAccess,
|
|
19
|
+
workspaceRoleToSandboxRole
|
|
20
|
+
} from "../chunk-63CE7FEZ.js";
|
|
21
|
+
export {
|
|
22
|
+
ASSIGNABLE_WORKSPACE_ROLES,
|
|
23
|
+
ORGANIZATION_ROLES,
|
|
24
|
+
ORGANIZATION_ROLE_RANK,
|
|
25
|
+
WORKSPACE_ROLES,
|
|
26
|
+
WORKSPACE_ROLE_RANK,
|
|
27
|
+
canManageWorkspaceMemberRole,
|
|
28
|
+
generateInviteToken,
|
|
29
|
+
hasOrganizationRole,
|
|
30
|
+
hasWorkspaceRole,
|
|
31
|
+
isAssignableWorkspaceRole,
|
|
32
|
+
isInviteTokenShape,
|
|
33
|
+
organizationRoleGrantsWorkspaceOwner,
|
|
34
|
+
resolveWorkspaceRole,
|
|
35
|
+
validateInviteToken,
|
|
36
|
+
workspaceRoleToCollaborationAccess,
|
|
37
|
+
workspaceRoleToSandboxRole
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { f as WorkspaceRole } from '../roles-CLtYKHHl.js';
|
|
2
|
+
import { T as TeamDatabase, a as TeamTables, g as TeamParentTable, h as WorkspaceAccessApi } from '../access-ChAHG4Tp.js';
|
|
3
|
+
import 'drizzle-orm/sqlite-core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Framework-neutral members API for the teams module: the invite / list /
|
|
7
|
+
* update-role / remove / accept-invite logic, lifted out of any one app's route
|
|
8
|
+
* file. Each app mounts these in its own route with its own auth — the handlers
|
|
9
|
+
* take an already-authenticated `actor`, the parsed inputs, the `db` + `tables`
|
|
10
|
+
* from `createTeamTables`, the product's user + workspace tables, and the
|
|
11
|
+
* workspace-access API from `createWorkspaceAccess`. They return web-standard
|
|
12
|
+
* `Response`s (available in Workers, Node 18+, Deno, browsers), so
|
|
13
|
+
* "framework-neutral" is literal: no Remix/React-Router/Express import anywhere.
|
|
14
|
+
*
|
|
15
|
+
* Two OPTIONAL seams an app wires only if it needs them:
|
|
16
|
+
* - `enforceSeat` — billing/seat-limit gate, called at invite time only when
|
|
17
|
+
* the invite would consume a NEW billable seat. An app without seat billing
|
|
18
|
+
* passes nothing and seats are never checked.
|
|
19
|
+
* - `memberSyncSeam` — fire-and-forget propagation of membership changes to a
|
|
20
|
+
* sandbox/external system (add on accept, role on update, remove on
|
|
21
|
+
* delete). An app without sandbox sync passes nothing. Fail-soft by
|
|
22
|
+
* contract: a thrown sync is caught and never blocks the DB mutation.
|
|
23
|
+
*
|
|
24
|
+
* Imports `drizzle-orm`, so this is a subpath, never re-exported from root.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** The authenticated caller — apps resolve this from their own session layer. */
|
|
28
|
+
interface MembersApiActor {
|
|
29
|
+
id: string;
|
|
30
|
+
email?: string | null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The product's user table, narrowed to the columns the member queries read.
|
|
34
|
+
* Adopters pass their real drizzle user table.
|
|
35
|
+
*/
|
|
36
|
+
interface UserLookupTable {
|
|
37
|
+
id: any;
|
|
38
|
+
name: any;
|
|
39
|
+
email: any;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The product's workspace table, narrowed to the columns the member queries
|
|
43
|
+
* read. The handlers join it to resolve a workspace's organization (the same
|
|
44
|
+
* table passed to createTeamTables as workspaceTable).
|
|
45
|
+
*/
|
|
46
|
+
interface WorkspaceLookupTable {
|
|
47
|
+
id: any;
|
|
48
|
+
organizationId: any;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Optional billing seat gate. The seam resolves the count input itself (it
|
|
52
|
+
* owns the plan/seat model) and throws when over the limit; the handler turns a
|
|
53
|
+
* thrown `SeatLimitError` into a 402. Called only when an invite would consume
|
|
54
|
+
* a NEW seat (invitee is not already an org member and has no pending org
|
|
55
|
+
* invite) — the same guard gtm uses, so the seam never fires on a no-op invite.
|
|
56
|
+
*/
|
|
57
|
+
interface EnforceSeatSeam {
|
|
58
|
+
(input: {
|
|
59
|
+
actorId: string;
|
|
60
|
+
organizationId: string;
|
|
61
|
+
}): Promise<void> | void;
|
|
62
|
+
}
|
|
63
|
+
/** Thrown by an `enforceSeat` seam to deny an invite; serialized to a 402. */
|
|
64
|
+
declare class SeatLimitError extends Error {
|
|
65
|
+
readonly status: number;
|
|
66
|
+
readonly capability?: string;
|
|
67
|
+
readonly requiredPlan?: string;
|
|
68
|
+
constructor(message: string, opts?: {
|
|
69
|
+
status?: number;
|
|
70
|
+
capability?: string;
|
|
71
|
+
requiredPlan?: string;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Optional membership-change propagation to an external system (e.g. sandbox).
|
|
76
|
+
* Every method is fire-and-forget and fail-soft: the handler awaits nothing and
|
|
77
|
+
* swallows rejections, so an unavailable downstream never blocks the mutation.
|
|
78
|
+
* Each fires only for members with a real `userId` (never email-only invites).
|
|
79
|
+
*/
|
|
80
|
+
interface MemberSyncSeam {
|
|
81
|
+
add?(input: {
|
|
82
|
+
workspaceId: string;
|
|
83
|
+
userId: string;
|
|
84
|
+
role: WorkspaceRole;
|
|
85
|
+
}): Promise<void> | void;
|
|
86
|
+
role?(input: {
|
|
87
|
+
workspaceId: string;
|
|
88
|
+
userId: string;
|
|
89
|
+
role: WorkspaceRole;
|
|
90
|
+
}): Promise<void> | void;
|
|
91
|
+
remove?(input: {
|
|
92
|
+
workspaceId: string;
|
|
93
|
+
userId: string;
|
|
94
|
+
}): Promise<void> | void;
|
|
95
|
+
}
|
|
96
|
+
interface MembersApiOptions {
|
|
97
|
+
db: TeamDatabase;
|
|
98
|
+
tables: TeamTables;
|
|
99
|
+
/** The product's user table (FK target passed to createTeamTables). */
|
|
100
|
+
userTable: TeamParentTable & UserLookupTable;
|
|
101
|
+
/** The product's workspace table (FK target passed to createTeamTables). */
|
|
102
|
+
workspaceTable: TeamParentTable & WorkspaceLookupTable;
|
|
103
|
+
/** Workspace-access API from createWorkspaceAccess — RBAC stays one source. */
|
|
104
|
+
access: Pick<WorkspaceAccessApi, 'getWorkspaceAccess'>;
|
|
105
|
+
enforceSeat?: EnforceSeatSeam;
|
|
106
|
+
memberSyncSeam?: MemberSyncSeam;
|
|
107
|
+
}
|
|
108
|
+
interface MemberListEntry {
|
|
109
|
+
id: string;
|
|
110
|
+
userId: string | null;
|
|
111
|
+
organizationMemberId: string | null;
|
|
112
|
+
role: WorkspaceRole;
|
|
113
|
+
name: string | null;
|
|
114
|
+
email: string | null;
|
|
115
|
+
invitedAt: Date | number | null;
|
|
116
|
+
acceptedAt: Date | number | null;
|
|
117
|
+
inherited: boolean;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Build the members API bound to one product's db/tables/access. Returns five
|
|
121
|
+
* handlers; an app maps its route methods onto them (GET→list, POST→invite,
|
|
122
|
+
* PATCH→updateRole, DELETE→remove; accept on its own route).
|
|
123
|
+
*/
|
|
124
|
+
declare function createMembersApi(opts: MembersApiOptions): {
|
|
125
|
+
listMembers: (input: {
|
|
126
|
+
workspaceId: string;
|
|
127
|
+
actor: MembersApiActor;
|
|
128
|
+
}) => Promise<Response>;
|
|
129
|
+
inviteMember: (input: {
|
|
130
|
+
workspaceId: string;
|
|
131
|
+
actor: MembersApiActor;
|
|
132
|
+
email?: string;
|
|
133
|
+
role?: string;
|
|
134
|
+
}) => Promise<Response>;
|
|
135
|
+
updateMemberRole: (input: {
|
|
136
|
+
workspaceId: string;
|
|
137
|
+
actor: MembersApiActor;
|
|
138
|
+
memberId?: string;
|
|
139
|
+
role?: string;
|
|
140
|
+
}) => Promise<Response>;
|
|
141
|
+
removeMember: (input: {
|
|
142
|
+
workspaceId: string;
|
|
143
|
+
actor: MembersApiActor;
|
|
144
|
+
memberId?: string;
|
|
145
|
+
}) => Promise<Response>;
|
|
146
|
+
acceptInvite: (input: {
|
|
147
|
+
token?: string;
|
|
148
|
+
actor: MembersApiActor;
|
|
149
|
+
}) => Promise<Response>;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export { type EnforceSeatSeam, type MemberListEntry, type MemberSyncSeam, type MembersApiActor, type MembersApiOptions, SeatLimitError, type UserLookupTable, type WorkspaceLookupTable, createMembersApi };
|