@adminide-stack/yantra-mobile 12.0.179 → 12.0.181-alpha.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.
Files changed (56) hide show
  1. package/lib/features/computer/computerChat.js +4 -1
  2. package/lib/features/computer/computerChat.js.map +1 -1
  3. package/lib/features/webbuilder/WebBuilderExperience.js +205 -31
  4. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  5. package/lib/features/webbuilder/components/GithubConnectSheet.js +159 -0
  6. package/lib/features/webbuilder/components/GithubConnectSheet.js.map +1 -0
  7. package/lib/features/webbuilder/components/ProjectSheets.js +3 -1
  8. package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
  9. package/lib/features/webbuilder/components/ProjectsScreen.js +122 -23
  10. package/lib/features/webbuilder/components/ProjectsScreen.js.map +1 -1
  11. package/lib/features/webbuilder/components/ShareSheet.js +144 -4
  12. package/lib/features/webbuilder/components/ShareSheet.js.map +1 -1
  13. package/lib/features/webbuilder/components/SiteUploadSheet.js +92 -3
  14. package/lib/features/webbuilder/components/SiteUploadSheet.js.map +1 -1
  15. package/lib/features/webbuilder/components/TemplateCard.js +33 -3
  16. package/lib/features/webbuilder/components/TemplateCard.js.map +1 -1
  17. package/lib/features/webbuilder/components/TemplatesSheet.js +54 -15
  18. package/lib/features/webbuilder/components/TemplatesSheet.js.map +1 -1
  19. package/lib/features/webbuilder/projectsList.js +117 -0
  20. package/lib/features/webbuilder/projectsList.js.map +1 -0
  21. package/lib/features/webbuilder/templateCatalog.js +13 -1
  22. package/lib/features/webbuilder/templateCatalog.js.map +1 -1
  23. package/lib/features/webbuilder/uploadCard.js +169 -0
  24. package/lib/features/webbuilder/uploadCard.js.map +1 -0
  25. package/lib/features/webbuilder/web/github/autoSync.js +1 -1
  26. package/lib/features/webbuilder/web/github/autoSync.js.map +1 -1
  27. package/lib/features/webbuilder/web/github/githubConnect.js +179 -0
  28. package/lib/features/webbuilder/web/github/githubConnect.js.map +1 -0
  29. package/lib/features/webbuilder/web/github/githubConnectApi.js +102 -0
  30. package/lib/features/webbuilder/web/github/githubConnectApi.js.map +1 -0
  31. package/lib/features/webbuilder/web/history/versions.js.map +1 -1
  32. package/lib/features/webbuilder/web/sharing/roles.js +50 -4
  33. package/lib/features/webbuilder/web/sharing/roles.js.map +1 -1
  34. package/lib/features/webbuilder/web/sharing/sharingApi.js +97 -6
  35. package/lib/features/webbuilder/web/sharing/sharingApi.js.map +1 -1
  36. package/lib/features/webbuilder/web/state/storageKeys.js +2 -0
  37. package/lib/features/webbuilder/web/state/storageKeys.js.map +1 -1
  38. package/lib/features/webbuilder/web/upload/sitePhotos.js +256 -2
  39. package/lib/features/webbuilder/web/upload/sitePhotos.js.map +1 -1
  40. package/lib/features/webbuilder/web/webServices.js +13 -1
  41. package/lib/features/webbuilder/web/webServices.js.map +1 -1
  42. package/lib/screens/ChatHistory/index.js +2 -2
  43. package/lib/screens/ChatHistory/index.js.map +1 -1
  44. package/lib/screens/ComputerNative/useComputerHostChat.js +7 -3
  45. package/lib/screens/ComputerNative/useComputerHostChat.js.map +1 -1
  46. package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js +11 -3
  47. package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js.map +1 -1
  48. package/lib/screens/WebBuilderNative/index.js +43 -10
  49. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  50. package/lib/screens/WebBuilderNative/runningBuilds.js +44 -2
  51. package/lib/screens/WebBuilderNative/runningBuilds.js.map +1 -1
  52. package/lib/screens/WebBuilderNative/useConnectorTemplates.js +12 -3
  53. package/lib/screens/WebBuilderNative/useConnectorTemplates.js.map +1 -1
  54. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +2 -0
  55. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  56. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"versions.js","sources":["../../../../../src/features/webbuilder/web/history/versions.ts"],"sourcesContent":["/**\n * W17: version history, restore and bookmarks (spec Phase 3-4 §1).\n *\n * The connector actions WEBBUILDER_LIST_VERSIONS / RESTORE_VERSION /\n * BOOKMARK_VERSION may not exist on a hosted agent yet. Until they do, the\n * surface falls back to WEBBUILDER_RUN_COMMAND with the git scripts built\n * here. Everything is pure (no connector, no React) so it is unit-tested:\n * - every sha is validated strictly (hex, 7-40 chars) before it reaches a shell;\n * - bookmark names become a safe slug (`bookmark/<slug>` git tags);\n * - commit subjects are single-line and single-quoted.\n *\n * Restore is always FORWARD: the files of the old version become a new commit\n * \"Restore to <short>: <message>\". History is never rewritten.\n *\n * Dirty tree (decision): a restore never refuses a dirty tree and never loses\n * work. Uncommitted changes (hand edits still waiting for their debounced\n * commit) are first committed as \"Manual edits: saved before restore\", so they\n * stay one click away in the history. `.env*`, node_modules and build output\n * are never staged. Refusing would only push the user into a dead end, because\n * the surface itself produces those uncommitted edits.\n */\n\nexport const DEFAULT_VERSION_LIMIT = 50;\nexport const MAX_VERSION_LIMIT = 200;\n/** RUN_COMMAND stdout is capped (~12 KB) - the git-log fallback asks for fewer rows. */\nexport const FALLBACK_VERSION_LIMIT = 40;\n\nexport interface WebbuilderVersion {\n sha: string;\n shortSha: string;\n message: string;\n author?: string;\n /** ISO date. */\n date?: string;\n /** Bookmark slug (the `bookmark/<slug>` tag), when the version has one. */\n bookmark?: string;\n isHead: boolean;\n}\n\nexport interface VersionList {\n versions: WebbuilderVersion[];\n head: string | null;\n dirty: boolean;\n /** Output was cut off, or the clone is shallow: older versions may be missing. */\n partial?: boolean;\n /** The project has no git repository yet (native `isGitRepo: false`). */\n noRepo?: boolean;\n}\n\nconst SHA_RE = /^[0-9a-f]{7,40}$/;\n\n/** Strict sha check: lowercase hex, 7-40 characters. Anything else is refused. */\nexport function isValidSha(value: unknown): value is string {\n return typeof value === 'string' && SHA_RE.test(value);\n}\n\n/** Lower-cased, trimmed sha, or null when it is not a valid sha. */\nexport function normalizeSha(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const v = value.trim().toLowerCase();\n return isValidSha(v) ? v : null;\n}\n\nexport function clampLimit(limit: unknown, fallback = DEFAULT_VERSION_LIMIT): number {\n const n = typeof limit === 'number' && Number.isFinite(limit) ? Math.floor(limit) : fallback;\n return Math.min(MAX_VERSION_LIMIT, Math.max(1, n));\n}\n\n/** Safe bookmark slug: lowercase `a-z0-9-`, at most 40 chars. Null when nothing is left. */\nexport function bookmarkSlug(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const slug = name\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '');\n return slug || null;\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Single-line, printable subject (max 72 chars). */\nexport function oneLineSubject(text: string, max = 72): string {\n const flat = String(text || '')\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/[^\\x20-\\x7E -￿]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n}\n\n/** \"Restore to <short>: <message>\" - the forward restore's commit subject. */\nexport function restoreCommitMessage(sha: string, message: string): string {\n const short = sha.slice(0, 7);\n return oneLineSubject(`Restore to ${short}: ${oneLineSubject(message, 200) || 'earlier version'}`);\n}\n\nexport const NO_REPO = 'git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo \"__GIT=norepo\"; exit 0; }';\nconst IDENTITY =\n 'ID=\"\"; git config user.email >/dev/null 2>&1 || ID=\"-c user.name=Yantra -c user.email=webbuilder@yantra.dev\"';\n/** Stage everything except secrets, dependencies and build output (same rules as the manual-edit commit). */\nconst SAFE_STAGE = [\n \"git add -A -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' >/dev/null 2>&1 || true\",\n \"git reset -q -- '.env*' '**/.env*' >/dev/null 2>&1 || true\",\n];\n\n/**\n * RUN_COMMAND script: HEAD, dirty flag and the last `limit` commits, one per line:\n * `__V<TAB>sha<TAB>isoDate<TAB>author<TAB>refs<TAB>subject`. Always exits 0.\n */\nexport function buildListVersionsCommand(limit: number = FALLBACK_VERSION_LIMIT): string {\n const n = clampLimit(limit, FALLBACK_VERSION_LIMIT);\n return [\n NO_REPO,\n 'echo \"__GIT=ok\"',\n 'echo \"__HEAD=$(git rev-parse HEAD 2>/dev/null)\"',\n \"if [ -n \\\"$(git status --porcelain -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' 2>/dev/null | head -n 1)\\\" ]; then echo \\\"__DIRTY=1\\\"; else echo \\\"__DIRTY=0\\\"; fi\",\n `git log -n ${n} --no-color --pretty=format:'__V%x09%H%x09%aI%x09%an%x09%D%x09%s' 2>/dev/null || true`,\n 'echo',\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport type ParsedVersionList = (VersionList & { ok: true }) | { ok: false; reason: 'norepo' | 'unreadable' };\n\n/** Bookmark slug from a `%D` refs list (\"HEAD -> main, tag: bookmark/launch\"). */\nexport function bookmarkFromRefs(refs: string): string | undefined {\n for (const part of refs.split(',')) {\n const m = /^\\s*tag:\\s*bookmark\\/([a-z0-9-]{1,40})\\s*$/.exec(part);\n if (m) return m[1];\n }\n return undefined;\n}\n\nexport function parseListVersionsOutput(stdout: string, opts?: { truncated?: boolean }): ParsedVersionList {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n if (!/^__GIT=ok\\s*$/m.test(text)) return { ok: false, reason: 'unreadable' };\n const head = normalizeSha(/^__HEAD=(.*)$/m.exec(text)?.[1] ?? '');\n const dirty = /^__DIRTY=1\\s*$/m.test(text);\n const versions: WebbuilderVersion[] = [];\n for (const line of text.split('\\n')) {\n if (!line.startsWith('__V\\t')) continue;\n const [, rawSha, date, author, refs, ...rest] = line.split('\\t');\n const sha = normalizeSha(rawSha);\n if (!sha || sha.length !== 40) continue;\n const bookmark = bookmarkFromRefs(refs ?? '');\n versions.push({\n sha,\n shortSha: sha.slice(0, 7),\n message: rest.join('\\t').replace(/\\r$/, '').trim(),\n ...(author ? { author: author.trim() } : {}),\n ...(date && !Number.isNaN(Date.parse(date)) ? { date: date.trim() } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: sha === head,\n });\n }\n const ended = /^__END=1\\s*$/m.test(text);\n return {\n ok: true,\n versions,\n head,\n dirty,\n ...(opts?.truncated || !ended ? { partial: true } : {}),\n };\n}\n\n/**\n * The action's fields. The transport already unwraps `{ data }`; a second\n * `data` layer (older transports) is tolerated.\n */\nexport function actionFields(data: Record<string, unknown> | null | undefined): Record<string, unknown> {\n const rec = data && typeof data === 'object' ? data : {};\n const inner = rec.data;\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner as Record<string, unknown>;\n return rec;\n}\n\n/**\n * The plain sentence of a connector error: `\"<sentence> [CODE]\\nLast output:…\"`\n * -> `\"<sentence>\"`. Falls back when there is nothing readable.\n */\nexport function plainConnectorError(error: unknown, fallback: string): string {\n const first = String(error ?? '')\n .split('\\n')[0]\n .replace(/\\s*\\[[A-Z][A-Z0-9_]*(?:;[^\\]]*)?\\]\\s*$/, '')\n .trim();\n if (!first || /^at\\s/.test(first)) return fallback;\n return first.length > 240 ? `${first.slice(0, 239)}…` : first;\n}\n\n/**\n * Tolerant reader for WEBBUILDER_LIST_VERSIONS `{ versions:[{ sha, shortSha,\n * message, author, date, bookmark?, bookmarks?, isHead }], head, dirty, branch,\n * shallow, isGitRepo, count }`; drops rows with a bad sha.\n */\nexport function normalizeListVersionsData(input: Record<string, unknown>): VersionList | null {\n const data = actionFields(input);\n if (data.isGitRepo === false) return { versions: [], head: null, dirty: false, noRepo: true };\n const raw = Array.isArray(data.versions) ? data.versions : null;\n if (!raw) return null;\n const head = normalizeSha(data.head);\n const versions: WebbuilderVersion[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const sha = normalizeSha(r.sha);\n if (!sha) continue;\n const marks = Array.isArray(r.bookmarks) ? r.bookmarks : [];\n const rawMark = typeof r.bookmark === 'string' ? r.bookmark : marks.find((m) => typeof m === 'string');\n const bookmark = typeof rawMark === 'string' ? bookmarkSlug(rawMark.replace(/^bookmark\\//, '')) : null;\n const date = typeof r.date === 'string' && !Number.isNaN(Date.parse(r.date)) ? r.date : undefined;\n versions.push({\n sha,\n shortSha: normalizeSha(r.shortSha) ?? sha.slice(0, 7),\n message: typeof r.message === 'string' ? r.message.split('\\n')[0].trim() : '',\n ...(typeof r.author === 'string' && r.author ? { author: r.author } : {}),\n ...(date ? { date } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: r.isHead === true || (head !== null && sha === head),\n });\n }\n return {\n versions,\n head: head ?? versions.find((v) => v.isHead)?.sha ?? null,\n dirty: data.dirty === true,\n ...(data.shallow === true ? { partial: true } : {}),\n };\n}\n\n/**\n * WEBBUILDER_RESTORE_VERSION `{ restored, sha, shortSha, newHead, noChange,\n * autoSaved, message }`. `noChange` = the project already matched that version.\n */\nexport function normalizeRestoreData(\n input: Record<string, unknown>,\n): { ok: true; newHead: string | null; autoSaved: string | null } | { ok: false; reason: 'none' | 'failed' } {\n const data = actionFields(input);\n if (data.restored === false) return { ok: false, reason: 'failed' };\n if (data.noChange === true) return { ok: false, reason: 'none' };\n return { ok: true, newHead: normalizeSha(data.newHead), autoSaved: normalizeSha(data.autoSaved) };\n}\n\n/**\n * WEBBUILDER_BOOKMARK_VERSION `{ bookmark, tag, sha, moved }` or, on remove,\n * `{ bookmark, tag, sha, removed }`. The slug, from `bookmark` or `tag`.\n */\nexport function bookmarkFromData(input: Record<string, unknown>): string | null {\n const data = actionFields(input);\n const raw = typeof data.bookmark === 'string' ? data.bookmark : typeof data.tag === 'string' ? data.tag : '';\n return bookmarkSlug(raw.replace(/^bookmark\\//, ''));\n}\n\n/**\n * RUN_COMMAND script for the forward restore. Prints\n * `__RESTORE=ok <newHead>` | `__RESTORE=none` (already identical) |\n * `__RESTORE=unknown` (no such commit) | `__GIT=norepo` | `__RESTORE=failed`.\n *\n * `git read-tree --reset -u <sha>` makes index + tracked files match the old\n * version exactly (files added later are removed too, unlike\n * `git checkout <sha> -- .`). Untracked/ignored files (.env, node_modules) are\n * left alone, and the dev server keeps running and hot-reloads.\n */\nexport function buildRestoreCommand(sha: string, message: string): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n const msg = shellQuote(restoreCommitMessage(s, message));\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__RESTORE=unknown\"; exit 0; }`,\n IDENTITY,\n // Keep uncommitted hand edits: commit them first (never .env*), so nothing is lost.\n ...SAFE_STAGE,\n 'git diff --cached --quiet || git $ID commit -q -m \\'Manual edits: saved before restore\\' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }',\n `git read-tree --reset -u '${s}' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }`,\n ...SAFE_STAGE,\n 'if git diff --cached --quiet HEAD; then echo \"__RESTORE=none\"; exit 0; fi',\n `if git $ID commit -q -m ${msg} >/dev/null 2>&1; then echo \"__RESTORE=ok $(git rev-parse HEAD)\"; else git reset -q --hard HEAD >/dev/null 2>&1; echo \"__RESTORE=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport type RestoreOutcome =\n | { ok: true; newHead: string | null }\n | { ok: false; reason: 'none' | 'unknown' | 'norepo' | 'failed' };\n\nexport function parseRestoreOutput(stdout: string): RestoreOutcome {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n const m = /^__RESTORE=(ok|none|unknown|failed)(?:\\s+([0-9a-f]{40}))?\\s*$/m.exec(text);\n if (!m) return { ok: false, reason: 'failed' };\n if (m[1] === 'ok') return { ok: true, newHead: normalizeSha(m[2] ?? '') };\n return { ok: false, reason: m[1] as 'none' | 'unknown' | 'failed' };\n}\n\n/**\n * RUN_COMMAND script for a bookmark: one bookmark per version, so existing\n * `bookmark/*` tags on that commit are removed first. `slug` null = remove.\n * Prints `__BOOKMARK=ok` | `__BOOKMARK=unknown` | `__BOOKMARK=failed` | `__GIT=norepo`.\n */\nexport function buildBookmarkCommand(sha: string, slug: string | null): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n if (slug !== null && bookmarkSlug(slug) !== slug) throw new Error('invalid bookmark name');\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__BOOKMARK=unknown\"; exit 0; }`,\n `for T in $(git tag --points-at '${s}' --list 'bookmark/*' 2>/dev/null); do git tag -d \"$T\" >/dev/null 2>&1; done`,\n slug === null\n ? 'echo \"__BOOKMARK=ok\"'\n : `if git tag -f 'bookmark/${slug}' '${s}' >/dev/null 2>&1; then echo \"__BOOKMARK=ok\"; else echo \"__BOOKMARK=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseBookmarkOutput(stdout: string): 'ok' | 'unknown' | 'failed' | 'norepo' {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return 'norepo';\n const m = /^__BOOKMARK=(ok|unknown|failed)\\s*$/m.exec(text);\n return (m?.[1] as 'ok' | 'unknown' | 'failed' | undefined) ?? 'failed';\n}\n\n/**\n * True when a connector error means \"this agent doesn't have that action yet\"\n * (the connector's `Unknown webbuilder action: X`, or the CLI's not-found forms).\n */\nexport function isUnknownActionError(error: string | null | undefined, data?: Record<string, unknown>): boolean {\n const blob = `${error || ''} ${typeof data?.error === 'string' ? data.error : ''} ${typeof data?.code === 'string' ? data.code : ''}`;\n return /unknown (webbuilder )?action|action[^\\n]{0,80}\\bnot (found|supported|available)|no such action|unsupported action|invalid action/i.test(\n blob,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Display helpers\n\nexport type VersionKind = 'ai' | 'manual' | 'restore' | 'backup' | 'other';\n\n/** The git identities the builder commits with (the connector's and the surface's own). */\nconst BUILDER_AUTHOR_RE = /^(?:yantra(?:[ -]?web ?builder)?|web ?builder|cdecli)$/i;\nconst BUILDER_MESSAGE_RE = /^(?:cdecli:|manual edits:|restore to [0-9a-f]{7,40}:|backup:|webbuilder:)/i;\n/** A restore point named after the site: \"Happy Paws - first build\". */\nconst SNAPSHOT_NAME_RE = /^.+?\\s+[-–—]\\s+(.+)$/;\nconst TEMPLATE_REPO_RE = /\\bfrom YantraTemplates\\//;\nconst FIRST_BUILD_RE = /^(?:.+?\\s+[-–—]\\s+)?first build$/i;\n\nexport function isBuilderAuthor(author: string | undefined): boolean {\n return BUILDER_AUTHOR_RE.test((author || '').trim());\n}\n\n/** A commit the builder made (AI turns, hand edits, restores, backups), not one inherited with the starting code. */\nexport function isBuilderVersion(version: Pick<WebbuilderVersion, 'message' | 'author'>): boolean {\n const m = (version.message || '').trim();\n return isBuilderAuthor(version.author) || BUILDER_MESSAGE_RE.test(m) || FIRST_BUILD_RE.test(m);\n}\n\nfunction sentence(text: string): string {\n const t = text.trim();\n return t ? t[0].toUpperCase() + t.slice(1) : t;\n}\n\n/**\n * Friendly label for a commit subject: AI turns (\"cdecli: …\", \"webbuilder: …\", \"<site> - first build\"),\n * hand edits (\"Manual edits: …\"), restores and backups. `author` lets a builder snapshot name lose its site prefix.\n */\nexport function describeVersion(message: string, author?: string): { kind: VersionKind; label: string } {\n const m = (message || '').trim();\n let r = /^cdecli:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: r[1].trim() || 'AI change' };\n r = /^Manual edits:\\s*(.*)$/i.exec(m);\n if (r) {\n const rest = r[1].trim();\n return { kind: 'manual', label: !rest || rest === 'canvas changes' ? 'Your edits' : `Your edits: ${rest}` };\n }\n r = /^Restore to ([0-9a-f]{7,40}):\\s*(.*)$/i.exec(m);\n if (r) {\n const inner = describeVersion(r[2]);\n // Restoring a restore (Undo right after one) names the original once, not \"Restored “Restored “…””\".\n return { kind: 'restore', label: inner.kind === 'restore' ? inner.label : `Restored “${inner.label}”` };\n }\n if (/^backup:/i.test(m)) return { kind: 'backup', label: 'Backup saved' };\n r = /^webbuilder:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: sentence(r[1]) || 'AI change' };\n if (FIRST_BUILD_RE.test(m)) return { kind: 'ai', label: 'First build' };\n r = isBuilderAuthor(author) ? SNAPSHOT_NAME_RE.exec(m) : null;\n if (r) return { kind: 'ai', label: sentence(r[1]) };\n return { kind: 'other', label: m || '(no message)' };\n}\n\n/** What History lists: the build's own versions, and how many inherited template commits were left out. */\nexport interface HistoryView {\n versions: WebbuilderVersion[];\n templateCommits: number;\n}\n\nexport interface TimelineOptions {\n /** Backups that changed no file. */\n unchanged?: ReadonlySet<string>;\n /** An imported repo, whose older commits are the user's own. */\n keepEarlier?: boolean;\n}\n\n/** The versions the user sees and steps through (History, Undo, Revert), as a list of its own. */\nexport interface VersionTimeline extends VersionList {\n templateCommits: number;\n /** A longer list may hold older versions. */\n hasMore?: boolean;\n}\n\n/** `historyView` as a `VersionList`: HEAD follows a folded backup down to the version it stands for. */\nexport function versionTimeline(list: VersionList, opts: TimelineOptions = {}): VersionTimeline {\n const view = historyView(list, opts);\n const head = view.versions.find((v) => v.isHead)?.sha ?? list.head;\n return { ...list, versions: view.versions, head, templateCommits: view.templateCommits };\n}\n\n/**\n * Commits older than the first build are the template's own history (written for its maintainers), so\n * only their count is kept. A backup that changed no file is folded into the version below it.\n * `keepEarlier`: an imported repo, whose older commits are the user's own.\n */\nexport function historyView(\n list: Pick<VersionList, 'versions'> | null | undefined,\n opts: TimelineOptions = {},\n): HistoryView {\n const all = list?.versions ?? [];\n let own = all;\n if (!opts.keepEarlier) {\n const oldest = (match: (v: WebbuilderVersion) => boolean) => {\n for (let i = all.length - 1; i >= 0; i--) if (match(all[i])) return i;\n return -1;\n };\n const firstBuild = oldest((v) => FIRST_BUILD_RE.test((v.message || '').trim()));\n const start = firstBuild >= 0 ? firstBuild : oldest(isBuilderVersion);\n if (start >= 0) own = all.slice(0, start + 1);\n else {\n // Nothing built yet: a Yantra template's own merge commit and everything before it are the template's.\n const templateTip = all.findIndex((v) => TEMPLATE_REPO_RE.test(v.message || ''));\n if (templateTip >= 0) own = all.slice(0, templateTip);\n }\n }\n const versions: WebbuilderVersion[] = [];\n let carryHead = false;\n own.forEach((v, i) => {\n const fold =\n i < own.length - 1 &&\n !v.bookmark &&\n opts.unchanged?.has(v.sha) &&\n describeVersion(v.message, v.author).kind === 'backup';\n if (fold) {\n carryHead ||= v.isHead;\n return;\n }\n versions.push(carryHead && !v.isHead ? { ...v, isHead: true } : v);\n carryHead = false;\n });\n return { versions, templateCommits: all.length - own.length };\n}\n\n/** RUN_COMMAND script: which of these commits changed no file since their parent (`__SAME=<sha>` each). */\nexport function buildUnchangedCommand(shas: ReadonlyArray<string>): string {\n const valid = shas.map(normalizeSha).filter((s): s is string => s !== null && s.length === 40);\n return [\n NO_REPO,\n ...valid.map((s) => `git diff --quiet '${s}~1' '${s}' -- >/dev/null 2>&1 && echo \"__SAME=${s}\"`),\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseUnchangedOutput(stdout: string): Set<string> {\n const out = new Set<string>();\n for (const m of String(stdout || '').matchAll(/^__SAME=([0-9a-f]{40})\\s*$/gm)) out.add(m[1]);\n return out;\n}\n\n/** \"just now\", \"5 min ago\", \"3 h ago\", \"2 days ago\", else a short date. */\nexport function relativeTime(iso: string | undefined, now: number = Date.now()): string {\n if (!iso) return '';\n const t = Date.parse(iso);\n if (Number.isNaN(t)) return '';\n const s = Math.max(0, Math.round((now - t) / 1000));\n if (s < 45) return 'just now';\n const min = Math.round(s / 60);\n if (min < 60) return `${min} min ago`;\n const h = Math.round(min / 60);\n if (h < 24) return `${h} h ago`;\n const d = Math.round(h / 24);\n if (d === 1) return 'yesterday';\n if (d < 7) return `${d} days ago`;\n return new Date(t).toISOString().slice(0, 10);\n}\n\n/** Who made it, in plain words: the AI, you, or (only on a person's own commit) their name. */\nfunction versionAuthor(kind: VersionKind, author: string | undefined): string {\n const name = author?.trim() || '';\n if (kind === 'ai' || kind === 'backup') return 'AI';\n if (kind === 'manual' || kind === 'restore') return name && !isBuilderAuthor(name) ? name : 'You';\n return isBuilderAuthor(name) ? 'AI' : name;\n}\n\n/** A History row: the commit message as the title, then time and author; the sha only in the tooltip. */\nexport function versionRow(\n version: Pick<WebbuilderVersion, 'shortSha' | 'message' | 'author' | 'date'>,\n now: number = Date.now(),\n): { kind: VersionKind; title: string; meta: string[]; tooltip: string } {\n const { kind, label } = describeVersion(version.message, version.author);\n const when = relativeTime(version.date, now);\n const who = versionAuthor(kind, version.author);\n const exact = version.date ? new Date(Date.parse(version.date)).toLocaleString() : '';\n return {\n kind,\n title: label,\n meta: [when, who].filter(Boolean),\n tooltip: [`Version ${version.shortSha}`, exact].filter(Boolean).join(' · '),\n };\n}\n\n/** A bookmark slug as a readable name: \"launch-ready\" -> \"Launch ready\". */\nexport function bookmarkLabel(slug: string): string {\n const text = slug.replace(/-+/g, ' ').trim();\n return text ? text[0].toUpperCase() + text.slice(1) : slug;\n}\n\n/** Chat line after a restore. */\nexport function restoredChatLine(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): string {\n return `Restored an earlier version: ${describeVersion(version.message).label}`;\n}\n\n/**\n * The `manualEdits`-style entry the next AI turn gets, so it knows the files\n * went back to an older version (and doesn't \"fix\" them forward again).\n */\nexport function restoreManualEdit(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): {\n file: string;\n summary: string;\n} {\n return {\n file: '(whole project)',\n summary: oneLineSubject(\n `The user restored every file to version ${version.shortSha} (\"${describeVersion(version.message).label}\"). Changes made after that version are gone on purpose; build on the restored code.`,\n 500,\n ),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,MAAM,MAAS,GAAA,kBAAA;AAGR,SAAS,WA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../../../src/features/webbuilder/web/history/versions.ts"],"sourcesContent":["/**\n * W17: version history, restore and bookmarks (spec Phase 3-4 §1).\n *\n * The connector actions WEBBUILDER_LIST_VERSIONS / RESTORE_VERSION /\n * BOOKMARK_VERSION may not exist on a hosted agent yet. Until they do, the\n * surface falls back to WEBBUILDER_RUN_COMMAND with the git scripts built\n * here. Everything is pure (no connector, no React) so it is unit-tested:\n * - every sha is validated strictly (hex, 7-40 chars) before it reaches a shell;\n * - bookmark names become a safe slug (`bookmark/<slug>` git tags);\n * - commit subjects are single-line and single-quoted.\n *\n * Restore is always FORWARD: the files of the old version become a new commit\n * \"Restore to <short>: <message>\". History is never rewritten.\n *\n * Dirty tree (decision): a restore never refuses a dirty tree and never loses\n * work. Uncommitted changes (hand edits still waiting for their debounced\n * commit) are first committed as \"Manual edits: saved before restore\", so they\n * stay one click away in the history. `.env*`, node_modules and build output\n * are never staged. Refusing would only push the user into a dead end, because\n * the surface itself produces those uncommitted edits.\n */\n\nexport const DEFAULT_VERSION_LIMIT = 50;\nexport const MAX_VERSION_LIMIT = 200;\n/** RUN_COMMAND stdout is capped (~12 KB) - the git-log fallback asks for fewer rows. */\nexport const FALLBACK_VERSION_LIMIT = 40;\n\nexport interface WebbuilderVersion {\n sha: string;\n shortSha: string;\n message: string;\n author?: string;\n /** ISO date. */\n date?: string;\n /** Bookmark slug (the `bookmark/<slug>` tag), when the version has one. */\n bookmark?: string;\n isHead: boolean;\n}\n\nexport interface VersionList {\n versions: WebbuilderVersion[];\n head: string | null;\n dirty: boolean;\n /** Output was cut off, or the clone is shallow: older versions may be missing. */\n partial?: boolean;\n /** The project has no git repository yet (native `isGitRepo: false`). */\n noRepo?: boolean;\n}\n\nconst SHA_RE = /^[0-9a-f]{7,40}$/;\n\n/** Strict sha check: lowercase hex, 7-40 characters. Anything else is refused. */\nexport function isValidSha(value: unknown): value is string {\n return typeof value === 'string' && SHA_RE.test(value);\n}\n\n/** Lower-cased, trimmed sha, or null when it is not a valid sha. */\nexport function normalizeSha(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const v = value.trim().toLowerCase();\n return isValidSha(v) ? v : null;\n}\n\nexport function clampLimit(limit: unknown, fallback = DEFAULT_VERSION_LIMIT): number {\n const n = typeof limit === 'number' && Number.isFinite(limit) ? Math.floor(limit) : fallback;\n return Math.min(MAX_VERSION_LIMIT, Math.max(1, n));\n}\n\n/** Safe bookmark slug: lowercase `a-z0-9-`, at most 40 chars. Null when nothing is left. */\nexport function bookmarkSlug(name: unknown): string | null {\n if (typeof name !== 'string') return null;\n const slug = name\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n .replace(/-+$/g, '');\n return slug || null;\n}\n\nexport function shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Single-line, printable subject (max 72 chars). */\nexport function oneLineSubject(text: string, max = 72): string {\n const flat = String(text || '')\n .replace(/[\\r\\n\\t]+/g, ' ')\n .replace(/[^\\x20-\\x7E -￿]/g, '')\n .replace(/\\s+/g, ' ')\n .trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;\n}\n\n/** \"Restore to <short>: <message>\" - the forward restore's commit subject. */\nexport function restoreCommitMessage(sha: string, message: string): string {\n const short = sha.slice(0, 7);\n return oneLineSubject(`Restore to ${short}: ${oneLineSubject(message, 200) || 'earlier version'}`);\n}\n\nexport const NO_REPO = 'git rev-parse --is-inside-work-tree >/dev/null 2>&1 || { echo \"__GIT=norepo\"; exit 0; }';\nconst IDENTITY =\n 'ID=\"\"; git config user.email >/dev/null 2>&1 || ID=\"-c user.name=Yantra -c user.email=webbuilder@yantra.dev\"';\n/** Stage everything except secrets, dependencies and build output (same rules as the manual-edit commit). */\nconst SAFE_STAGE = [\n \"git add -A -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' >/dev/null 2>&1 || true\",\n \"git reset -q -- '.env*' '**/.env*' >/dev/null 2>&1 || true\",\n];\n\n/**\n * RUN_COMMAND script: HEAD, dirty flag and the last `limit` commits, one per line:\n * `__V<TAB>sha<TAB>isoDate<TAB>author<TAB>refs<TAB>subject`. Always exits 0.\n */\nexport function buildListVersionsCommand(limit: number = FALLBACK_VERSION_LIMIT): string {\n const n = clampLimit(limit, FALLBACK_VERSION_LIMIT);\n return [\n NO_REPO,\n 'echo \"__GIT=ok\"',\n 'echo \"__HEAD=$(git rev-parse HEAD 2>/dev/null)\"',\n \"if [ -n \\\"$(git status --porcelain -- . ':!.env*' ':!**/.env*' ':!node_modules' ':!**/node_modules' ':!dist' ':!.output' 2>/dev/null | head -n 1)\\\" ]; then echo \\\"__DIRTY=1\\\"; else echo \\\"__DIRTY=0\\\"; fi\",\n `git log -n ${n} --no-color --pretty=format:'__V%x09%H%x09%aI%x09%an%x09%D%x09%s' 2>/dev/null || true`,\n 'echo',\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport type ParsedVersionList = (VersionList & { ok: true }) | { ok: false; reason: 'norepo' | 'unreadable' };\n\n/** Bookmark slug from a `%D` refs list (\"HEAD -> main, tag: bookmark/launch\"). */\nexport function bookmarkFromRefs(refs: string): string | undefined {\n for (const part of refs.split(',')) {\n const m = /^\\s*tag:\\s*bookmark\\/([a-z0-9-]{1,40})\\s*$/.exec(part);\n if (m) return m[1];\n }\n return undefined;\n}\n\nexport function parseListVersionsOutput(stdout: string, opts?: { truncated?: boolean }): ParsedVersionList {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n if (!/^__GIT=ok\\s*$/m.test(text)) return { ok: false, reason: 'unreadable' };\n const head = normalizeSha(/^__HEAD=(.*)$/m.exec(text)?.[1] ?? '');\n const dirty = /^__DIRTY=1\\s*$/m.test(text);\n const versions: WebbuilderVersion[] = [];\n for (const line of text.split('\\n')) {\n if (!line.startsWith('__V\\t')) continue;\n const [, rawSha, date, author, refs, ...rest] = line.split('\\t');\n const sha = normalizeSha(rawSha);\n if (!sha || sha.length !== 40) continue;\n const bookmark = bookmarkFromRefs(refs ?? '');\n versions.push({\n sha,\n shortSha: sha.slice(0, 7),\n message: rest.join('\\t').replace(/\\r$/, '').trim(),\n ...(author ? { author: author.trim() } : {}),\n ...(date && !Number.isNaN(Date.parse(date)) ? { date: date.trim() } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: sha === head,\n });\n }\n const ended = /^__END=1\\s*$/m.test(text);\n return {\n ok: true,\n versions,\n head,\n dirty,\n ...(opts?.truncated || !ended ? { partial: true } : {}),\n };\n}\n\n/**\n * The action's fields. The transport already unwraps `{ data }`; a second\n * `data` layer (older transports) is tolerated.\n */\nexport function actionFields(data: Record<string, unknown> | null | undefined): Record<string, unknown> {\n const rec = data && typeof data === 'object' ? data : {};\n const inner = rec.data;\n if (inner && typeof inner === 'object' && !Array.isArray(inner)) return inner as Record<string, unknown>;\n return rec;\n}\n\n/**\n * The plain sentence of a connector error: `\"<sentence> [CODE]\\nLast output:…\"`\n * -> `\"<sentence>\"`. Falls back when there is nothing readable.\n */\nexport function plainConnectorError(error: unknown, fallback: string): string {\n const first = String(error ?? '')\n .split('\\n')[0]\n .replace(/\\s*\\[[A-Z][A-Z0-9_]*(?:;[^\\]]*)?\\]\\s*$/, '')\n .trim();\n if (!first || /^at\\s/.test(first)) return fallback;\n return first.length > 240 ? `${first.slice(0, 239)}…` : first;\n}\n\n/**\n * Tolerant reader for WEBBUILDER_LIST_VERSIONS `{ versions:[{ sha, shortSha,\n * message, author, date, bookmark?, bookmarks?, isHead }], head, dirty, branch,\n * shallow, isGitRepo, count }`; drops rows with a bad sha.\n */\nexport function normalizeListVersionsData(input: Record<string, unknown>): VersionList | null {\n const data = actionFields(input);\n if (data.isGitRepo === false) return { versions: [], head: null, dirty: false, noRepo: true };\n const raw = Array.isArray(data.versions) ? data.versions : null;\n if (!raw) return null;\n const head = normalizeSha(data.head);\n const versions: WebbuilderVersion[] = [];\n for (const item of raw) {\n if (!item || typeof item !== 'object') continue;\n const r = item as Record<string, unknown>;\n const sha = normalizeSha(r.sha);\n if (!sha) continue;\n const marks = Array.isArray(r.bookmarks) ? r.bookmarks : [];\n const rawMark = typeof r.bookmark === 'string' ? r.bookmark : marks.find((m) => typeof m === 'string');\n const bookmark = typeof rawMark === 'string' ? bookmarkSlug(rawMark.replace(/^bookmark\\//, '')) : null;\n const date = typeof r.date === 'string' && !Number.isNaN(Date.parse(r.date)) ? r.date : undefined;\n versions.push({\n sha,\n shortSha: normalizeSha(r.shortSha) ?? sha.slice(0, 7),\n message: typeof r.message === 'string' ? r.message.split('\\n')[0].trim() : '',\n ...(typeof r.author === 'string' && r.author ? { author: r.author } : {}),\n ...(date ? { date } : {}),\n ...(bookmark ? { bookmark } : {}),\n isHead: r.isHead === true || (head !== null && sha === head),\n });\n }\n return {\n versions,\n head: head ?? versions.find((v) => v.isHead)?.sha ?? null,\n dirty: data.dirty === true,\n ...(data.shallow === true ? { partial: true } : {}),\n };\n}\n\n/**\n * WEBBUILDER_RESTORE_VERSION `{ restored, sha, shortSha, newHead, noChange,\n * autoSaved, message }`. `noChange` = the project already matched that version.\n */\nexport function normalizeRestoreData(\n input: Record<string, unknown>,\n): { ok: true; newHead: string | null; autoSaved: string | null } | { ok: false; reason: 'none' | 'failed' } {\n const data = actionFields(input);\n if (data.restored === false) return { ok: false, reason: 'failed' };\n if (data.noChange === true) return { ok: false, reason: 'none' };\n return { ok: true, newHead: normalizeSha(data.newHead), autoSaved: normalizeSha(data.autoSaved) };\n}\n\n/**\n * WEBBUILDER_BOOKMARK_VERSION `{ bookmark, tag, sha, moved }` or, on remove,\n * `{ bookmark, tag, sha, removed }`. The slug, from `bookmark` or `tag`.\n */\nexport function bookmarkFromData(input: Record<string, unknown>): string | null {\n const data = actionFields(input);\n const raw = typeof data.bookmark === 'string' ? data.bookmark : typeof data.tag === 'string' ? data.tag : '';\n return bookmarkSlug(raw.replace(/^bookmark\\//, ''));\n}\n\n/**\n * RUN_COMMAND script for the forward restore. Prints\n * `__RESTORE=ok <newHead>` | `__RESTORE=none` (already identical) |\n * `__RESTORE=unknown` (no such commit) | `__GIT=norepo` | `__RESTORE=failed`.\n *\n * `git read-tree --reset -u <sha>` makes index + tracked files match the old\n * version exactly (files added later are removed too, unlike\n * `git checkout <sha> -- .`). Untracked/ignored files (.env, node_modules) are\n * left alone, and the dev server keeps running and hot-reloads.\n */\nexport function buildRestoreCommand(sha: string, message: string): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n const msg = shellQuote(restoreCommitMessage(s, message));\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__RESTORE=unknown\"; exit 0; }`,\n IDENTITY,\n // Keep uncommitted hand edits: commit them first (never .env*), so nothing is lost.\n ...SAFE_STAGE,\n 'git diff --cached --quiet || git $ID commit -q -m \\'Manual edits: saved before restore\\' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }',\n `git read-tree --reset -u '${s}' >/dev/null 2>&1 || { echo \"__RESTORE=failed\"; exit 0; }`,\n ...SAFE_STAGE,\n 'if git diff --cached --quiet HEAD; then echo \"__RESTORE=none\"; exit 0; fi',\n `if git $ID commit -q -m ${msg} >/dev/null 2>&1; then echo \"__RESTORE=ok $(git rev-parse HEAD)\"; else git reset -q --hard HEAD >/dev/null 2>&1; echo \"__RESTORE=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport type RestoreOutcome =\n | { ok: true; newHead: string | null }\n | { ok: false; reason: 'none' | 'unknown' | 'norepo' | 'failed' };\n\nexport function parseRestoreOutput(stdout: string): RestoreOutcome {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return { ok: false, reason: 'norepo' };\n const m = /^__RESTORE=(ok|none|unknown|failed)(?:\\s+([0-9a-f]{40}))?\\s*$/m.exec(text);\n if (!m) return { ok: false, reason: 'failed' };\n if (m[1] === 'ok') return { ok: true, newHead: normalizeSha(m[2] ?? '') };\n return { ok: false, reason: m[1] as 'none' | 'unknown' | 'failed' };\n}\n\n/**\n * RUN_COMMAND script for a bookmark: one bookmark per version, so existing\n * `bookmark/*` tags on that commit are removed first. `slug` null = remove.\n * Prints `__BOOKMARK=ok` | `__BOOKMARK=unknown` | `__BOOKMARK=failed` | `__GIT=norepo`.\n */\nexport function buildBookmarkCommand(sha: string, slug: string | null): string {\n const s = normalizeSha(sha);\n if (!s) throw new Error('invalid version id');\n if (slug !== null && bookmarkSlug(slug) !== slug) throw new Error('invalid bookmark name');\n return [\n NO_REPO,\n `git cat-file -e '${s}^{commit}' 2>/dev/null || { echo \"__BOOKMARK=unknown\"; exit 0; }`,\n `for T in $(git tag --points-at '${s}' --list 'bookmark/*' 2>/dev/null); do git tag -d \"$T\" >/dev/null 2>&1; done`,\n slug === null\n ? 'echo \"__BOOKMARK=ok\"'\n : `if git tag -f 'bookmark/${slug}' '${s}' >/dev/null 2>&1; then echo \"__BOOKMARK=ok\"; else echo \"__BOOKMARK=failed\"; fi`,\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseBookmarkOutput(stdout: string): 'ok' | 'unknown' | 'failed' | 'norepo' {\n const text = String(stdout || '');\n if (/^__GIT=norepo\\s*$/m.test(text)) return 'norepo';\n const m = /^__BOOKMARK=(ok|unknown|failed)\\s*$/m.exec(text);\n return (m?.[1] as 'ok' | 'unknown' | 'failed' | undefined) ?? 'failed';\n}\n\n/**\n * True when a connector error means \"this agent doesn't have that action yet\"\n * (the connector's `Unknown webbuilder action: X`, or the CLI's not-found forms).\n */\nexport function isUnknownActionError(error: string | null | undefined, data?: Record<string, unknown>): boolean {\n const blob = `${error || ''} ${typeof data?.error === 'string' ? data.error : ''} ${typeof data?.code === 'string' ? data.code : ''}`;\n return /unknown (webbuilder )?action|action[^\\n]{0,80}\\bnot (found|supported|available)|no such action|unsupported action|invalid action/i.test(\n blob,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Display helpers\n\nexport type VersionKind = 'ai' | 'manual' | 'restore' | 'backup' | 'other';\n\n/** The git identities the builder commits with (the connector's and the surface's own). */\nconst BUILDER_AUTHOR_RE = /^(?:yantra(?:[ -]?web ?builder)?|web ?builder|cdecli)$/i;\nconst BUILDER_MESSAGE_RE = /^(?:cdecli:|manual edits:|restore to [0-9a-f]{7,40}:|backup:|webbuilder:)/i;\n/** A restore point named after the site: \"Happy Paws - first build\". */\nconst SNAPSHOT_NAME_RE = /^.+?\\s+[-–—]\\s+(.+)$/;\nconst TEMPLATE_REPO_RE = /\\bfrom YantraTemplates\\//;\nconst FIRST_BUILD_RE = /^(?:.+?\\s+[-–—]\\s+)?first build$/i;\n\nexport function isBuilderAuthor(author: string | undefined): boolean {\n return BUILDER_AUTHOR_RE.test((author || '').trim());\n}\n\n/** A commit the builder made (AI turns, hand edits, restores, backups), not one inherited with the starting code. */\nexport function isBuilderVersion(version: Pick<WebbuilderVersion, 'message' | 'author'>): boolean {\n const m = (version.message || '').trim();\n return isBuilderAuthor(version.author) || BUILDER_MESSAGE_RE.test(m) || FIRST_BUILD_RE.test(m);\n}\n\nfunction sentence(text: string): string {\n const t = text.trim();\n return t ? t[0].toUpperCase() + t.slice(1) : t;\n}\n\n/**\n * Friendly label for a commit subject: AI turns (\"cdecli: …\", \"webbuilder: …\", \"<site> - first build\"),\n * hand edits (\"Manual edits: …\"), restores and backups. `author` lets a builder snapshot name lose its site prefix.\n */\nexport function describeVersion(message: string, author?: string): { kind: VersionKind; label: string } {\n const m = (message || '').trim();\n let r = /^cdecli:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: r[1].trim() || 'AI change' };\n r = /^Manual edits:\\s*(.*)$/i.exec(m);\n if (r) {\n const rest = r[1].trim();\n return { kind: 'manual', label: !rest || rest === 'canvas changes' ? 'Your edits' : `Your edits: ${rest}` };\n }\n r = /^Restore to ([0-9a-f]{7,40}):\\s*(.*)$/i.exec(m);\n if (r) {\n const inner = describeVersion(r[2]);\n // Restoring a restore (Undo right after one) names the original once, not \"Restored “Restored “…””\".\n return { kind: 'restore', label: inner.kind === 'restore' ? inner.label : `Restored “${inner.label}”` };\n }\n if (/^backup:/i.test(m)) return { kind: 'backup', label: 'Backup saved' };\n r = /^webbuilder:\\s*(.*)$/i.exec(m);\n if (r) return { kind: 'ai', label: sentence(r[1]) || 'AI change' };\n if (FIRST_BUILD_RE.test(m)) return { kind: 'ai', label: 'First build' };\n r = isBuilderAuthor(author) ? SNAPSHOT_NAME_RE.exec(m) : null;\n if (r) return { kind: 'ai', label: sentence(r[1]) };\n return { kind: 'other', label: m || '(no message)' };\n}\n\n/** What History lists: the build's own versions, and how many inherited template commits were left out. */\nexport interface HistoryView {\n versions: WebbuilderVersion[];\n templateCommits: number;\n}\n\nexport interface TimelineOptions {\n /** Backups that changed no file. */\n unchanged?: ReadonlySet<string>;\n /** An imported repo, whose older commits are the user's own. */\n keepEarlier?: boolean;\n}\n\n/** The versions the user sees and steps through (History, Undo, Revert), as a list of its own. */\nexport interface VersionTimeline extends VersionList {\n templateCommits: number;\n /** A longer list may hold older versions. */\n hasMore?: boolean;\n}\n\n/** `historyView` as a `VersionList`: HEAD follows a folded backup down to the version it stands for. */\nexport function versionTimeline(list: VersionList, opts: TimelineOptions = {}): VersionTimeline {\n const view = historyView(list, opts);\n const head = view.versions.find((v) => v.isHead)?.sha ?? list.head;\n return { ...list, versions: view.versions, head, templateCommits: view.templateCommits };\n}\n\n/**\n * Commits older than the first build are the template's own history (written for its maintainers), so\n * only their count is kept. A backup that changed no file is folded into the version below it.\n * `keepEarlier`: an imported repo, whose older commits are the user's own.\n */\nexport function historyView(\n list: Pick<VersionList, 'versions'> | null | undefined,\n opts: TimelineOptions = {},\n): HistoryView {\n const all = list?.versions ?? [];\n let own = all;\n if (!opts.keepEarlier) {\n const oldest = (match: (v: WebbuilderVersion) => boolean) => {\n for (let i = all.length - 1; i >= 0; i--) if (match(all[i])) return i;\n return -1;\n };\n const firstBuild = oldest((v) => FIRST_BUILD_RE.test((v.message || '').trim()));\n const start = firstBuild >= 0 ? firstBuild : oldest(isBuilderVersion);\n if (start >= 0) own = all.slice(0, start + 1);\n else {\n // Nothing built yet: a Yantra template's own merge commit and everything before it are the template's.\n const templateTip = all.findIndex((v) => TEMPLATE_REPO_RE.test(v.message || ''));\n if (templateTip >= 0) own = all.slice(0, templateTip);\n }\n }\n const versions: WebbuilderVersion[] = [];\n let carryHead = false;\n own.forEach((v, i) => {\n const fold =\n i < own.length - 1 &&\n !v.bookmark &&\n opts.unchanged?.has(v.sha) &&\n describeVersion(v.message, v.author).kind === 'backup';\n if (fold) {\n carryHead ||= v.isHead;\n return;\n }\n versions.push(carryHead && !v.isHead ? { ...v, isHead: true } : v);\n carryHead = false;\n });\n return { versions, templateCommits: all.length - own.length };\n}\n\n/** RUN_COMMAND script: which of these commits changed no file since their parent (`__SAME=<sha>` each). */\nexport function buildUnchangedCommand(shas: ReadonlyArray<string>): string {\n const valid = shas.map(normalizeSha).filter((s): s is string => s !== null && s.length === 40);\n return [\n NO_REPO,\n ...valid.map((s) => `git diff --quiet '${s}~1' '${s}' -- >/dev/null 2>&1 && echo \"__SAME=${s}\"`),\n 'echo \"__END=1\"',\n 'exit 0',\n ].join('\\n');\n}\n\nexport function parseUnchangedOutput(stdout: string): Set<string> {\n const out = new Set<string>();\n for (const m of String(stdout || '').matchAll(/^__SAME=([0-9a-f]{40})\\s*$/gm)) out.add(m[1]);\n return out;\n}\n\n/** \"just now\", \"5 min ago\", \"3 h ago\", \"2 days ago\", else a short date. */\nexport function relativeTime(iso: string | undefined, now: number = Date.now()): string {\n if (!iso) return '';\n const t = Date.parse(iso);\n if (Number.isNaN(t)) return '';\n const s = Math.max(0, Math.round((now - t) / 1000));\n if (s < 45) return 'just now';\n const min = Math.round(s / 60);\n if (min < 60) return `${min} min ago`;\n const h = Math.round(min / 60);\n if (h < 24) return `${h} h ago`;\n const d = Math.round(h / 24);\n if (d === 1) return 'yesterday';\n if (d < 7) return `${d} days ago`;\n return new Date(t).toISOString().slice(0, 10);\n}\n\n/** Who made it, in plain words: the AI, you, or (only on a person's own commit) their name. */\nfunction versionAuthor(kind: VersionKind, author: string | undefined): string {\n const name = author?.trim() || '';\n if (kind === 'ai' || kind === 'backup') return 'AI';\n if (kind === 'manual' || kind === 'restore') return name && !isBuilderAuthor(name) ? name : 'You';\n return isBuilderAuthor(name) ? 'AI' : name;\n}\n\n/** A History row: the commit message as the title, then time and author; the sha only in the tooltip. */\nexport function versionRow(\n version: Pick<WebbuilderVersion, 'shortSha' | 'message' | 'author' | 'date'>,\n now: number = Date.now(),\n): { kind: VersionKind; title: string; meta: string[]; tooltip: string } {\n const { kind, label } = describeVersion(version.message, version.author);\n const when = relativeTime(version.date, now);\n const who = versionAuthor(kind, version.author);\n const exact = version.date ? new Date(Date.parse(version.date)).toLocaleString() : '';\n return {\n kind,\n title: label,\n meta: [when, who].filter(Boolean),\n tooltip: [`Version ${version.shortSha}`, exact].filter(Boolean).join(' · '),\n };\n}\n\n/** A row button's name with its version (\"Restore: Added a pricing page, 2 hours ago\"): every row has the same buttons. */\nexport function versionActionLabel(action: string, title: string, meta: string[] = []): string {\n const when = meta[0] ? `, ${meta[0]}` : '';\n return `${action}: ${oneLineSubject(title, 60) || 'this version'}${when}`;\n}\n\n/** A bookmark slug as a readable name: \"launch-ready\" -> \"Launch ready\". */\nexport function bookmarkLabel(slug: string): string {\n const text = slug.replace(/-+/g, ' ').trim();\n return text ? text[0].toUpperCase() + text.slice(1) : slug;\n}\n\n/** Chat line after a restore. */\nexport function restoredChatLine(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): string {\n return `Restored an earlier version: ${describeVersion(version.message).label}`;\n}\n\n/**\n * The `manualEdits`-style entry the next AI turn gets, so it knows the files\n * went back to an older version (and doesn't \"fix\" them forward again).\n */\nexport function restoreManualEdit(version: Pick<WebbuilderVersion, 'shortSha' | 'message'>): {\n file: string;\n summary: string;\n} {\n return {\n file: '(whole project)',\n summary: oneLineSubject(\n `The user restored every file to version ${version.shortSha} (\"${describeVersion(version.message).label}\"). Changes made after that version are gone on purpose; build on the restored code.`,\n 500,\n ),\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AA8CA,MAAM,MAAS,GAAA,kBAAA;AAGR,SAAS,WAAW,KAAiC,EAAA;AAC1D,EAAA,OAAO,OAAO,KAAA,KAAU,QAAY,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACvD;AAGO,SAAS,aAAa,KAA+B,EAAA;AAC1D,EAAI,IAAA,OAAO,KAAU,KAAA,QAAA,EAAiB,OAAA,IAAA;AACtC,EAAA,MAAM,CAAI,GAAA,KAAA,CAAM,IAAK,EAAA,CAAE,WAAY,EAAA;AACnC,EAAO,OAAA,UAAA,CAAW,CAAC,CAAA,GAAI,CAAI,GAAA,IAAA;AAC7B;AAOO,SAAS,aAAa,IAA8B,EAAA;AACzD,EAAI,IAAA,OAAO,IAAS,KAAA,QAAA,EAAiB,OAAA,IAAA;AACrC,EAAM,MAAA,IAAA,GAAO,IAAK,CAAA,SAAA,CAAU,MAAM,CAAA,CAAE,QAAQ,QAAU,EAAA,EAAE,CAAE,CAAA,WAAA,EAAc,CAAA,OAAA,CAAQ,eAAe,GAAG,CAAA,CAAE,OAAQ,CAAA,UAAA,EAAY,EAAE,CAAA,CAAE,KAAM,CAAA,CAAA,EAAG,EAAE,CAAA,CAAE,OAAQ,CAAA,MAAA,EAAQ,EAAE,CAAA;AAC3J,EAAA,OAAO,IAAQ,IAAA,IAAA;AACjB;AAiGO,SAAS,aAAa,IAA2E,EAAA;AACtG,EAAA,MAAM,MAAM,IAAQ,IAAA,OAAO,IAAS,KAAA,QAAA,GAAW,OAAO,EAAC;AACvD,EAAA,MAAM,QAAQ,GAAI,CAAA,IAAA;AAClB,EAAI,IAAA,KAAA,IAAS,OAAO,KAAU,KAAA,QAAA,IAAY,CAAC,KAAM,CAAA,OAAA,CAAQ,KA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,KAAtC,IAA6C,GAAA,EAAA,GAAA,IAAA;AAAA,IACnD,KAAA,EAAO,KAAK,KAAU,KAAA;AAAA,GAClB,EAAA,IAAA,CAAK,YAAY,IAAO,GAAA;AAAA,IAC1B,OAAS,EAAA;AAAA,MACP,EAAC,CAAA;AAET"}
@@ -17,15 +17,17 @@ var __spreadValues = (a, b) => {
17
17
  const PROJECT_ROLES = ["owner", "editor", "viewer"];
18
18
  const INVITE_ROLES = ["editor", "viewer"];
19
19
  const VIEWER_ACTIONS = /* @__PURE__ */ new Set(["view", "comment"]);
20
+ const CLIENT_ACTIONS = /* @__PURE__ */ new Set(["view", "comment", "build", "editCanvas"]);
20
21
  const OWNER_ONLY = /* @__PURE__ */ new Set(["share", "changeRole", "removeMember", "delete", "databaseStudio", "databaseSql", "databaseComponents", "githubSync", "secrets", "siteAlerts"]);
21
22
  function normalizeRole(raw) {
22
23
  const r = typeof raw === "string" ? raw.trim().toLowerCase() : "";
23
- return r === "owner" || r === "editor" || r === "viewer" ? r : null;
24
+ return r === "owner" || r === "editor" || r === "viewer" || r === "client" ? r : null;
24
25
  }
25
26
  function roleCan(role, action) {
26
27
  if (!role) return true;
27
28
  if (role === "owner") return true;
28
29
  if (role === "editor") return !OWNER_ONLY.has(action);
30
+ if (role === "client") return CLIENT_ACTIONS.has(action);
29
31
  return VIEWER_ACTIONS.has(action);
30
32
  }
31
33
  function isRec(v) {
@@ -70,7 +72,8 @@ function parseMembers(raw) {
70
72
  const rank = {
71
73
  owner: 0,
72
74
  editor: 1,
73
- viewer: 2
75
+ viewer: 2,
76
+ client: 3
74
77
  };
75
78
  return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));
76
79
  }
@@ -85,7 +88,8 @@ function memberLabel(m) {
85
88
  const ROLE_LABELS = {
86
89
  owner: "Owner",
87
90
  editor: "Can edit",
88
- viewer: "Can view"
91
+ viewer: "Can view",
92
+ client: "Client"
89
93
  };
90
94
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
91
95
  function normalizeEmail(raw) {
@@ -106,4 +110,46 @@ function sharingErrorText(message) {
106
110
  }
107
111
  if (/forbidden|not allowed|only owners|permission/i.test(m)) return "Only owners can change who has access.";
108
112
  return m || "Something went wrong.";
109
- }export{INVITE_ROLES,PROJECT_ROLES,ROLE_LABELS,lastOwnerProblem,memberLabel,normalizeEmail,normalizeRole,parseMembers,roleCan,roleOf,sharingErrorText};//# sourceMappingURL=roles.js.map
113
+ }
114
+ const CLIENT_STATUSES = /* @__PURE__ */ new Set(["PENDING", "ACTIVE", "REVOKED", "EXPIRED"]);
115
+ function parseSiteClients(raw) {
116
+ let value = raw;
117
+ if (typeof value === "string") {
118
+ try {
119
+ value = JSON.parse(value);
120
+ } catch (e) {
121
+ return [];
122
+ }
123
+ }
124
+ if (isRec(value) && Array.isArray(value.clients)) value = value.clients;
125
+ if (!Array.isArray(value)) return [];
126
+ const out = value.flatMap((item) => {
127
+ var _a, _b, _c, _d;
128
+ if (!isRec(item)) return [];
129
+ const grantId = text(item.grantId, 100);
130
+ const status = typeof item.status === "string" && CLIENT_STATUSES.has(item.status) ? item.status : null;
131
+ if (!grantId || !status) return [];
132
+ return [{
133
+ grantId,
134
+ email: (_a = text(item.email, 320)) != null ? _a : null,
135
+ status,
136
+ userId: (_b = text(item.userId, 100)) != null ? _b : null,
137
+ invitedAt: (_c = text(item.invitedAt, 40)) != null ? _c : null,
138
+ acceptedAt: (_d = text(item.acceptedAt, 40)) != null ? _d : null,
139
+ inviteSent: item.inviteSent === true
140
+ }];
141
+ });
142
+ const order = {
143
+ PENDING: 0,
144
+ ACTIVE: 1,
145
+ EXPIRED: 2,
146
+ REVOKED: 3
147
+ };
148
+ return out.sort((a, b) => order[a.status] - order[b.status]);
149
+ }
150
+ function siteClientStatusText(client) {
151
+ if (client.status === "ACTIVE") return "Has access";
152
+ if (client.status === "EXPIRED") return "Invitation expired";
153
+ if (client.status === "REVOKED") return "Removed";
154
+ return client.inviteSent ? "Invited, not accepted yet" : "Invited, email not sent yet";
155
+ }export{INVITE_ROLES,PROJECT_ROLES,ROLE_LABELS,lastOwnerProblem,memberLabel,normalizeEmail,normalizeRole,parseMembers,parseSiteClients,roleCan,roleOf,sharingErrorText,siteClientStatusText};//# sourceMappingURL=roles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"roles.js","sources":["../../../../../src/features/webbuilder/web/sharing/roles.ts"],"sourcesContent":["/**\n * W31 sharing and roles (Phase 6 spec §2), surface side. Pure: tested with node:test.\n *\n * `roleCan` mirrors the server's checks in page-creator (stream P6):\n * - viewers can look (preview, code, history, read-only data views) and comment;\n * - editors can do everything except share, change roles, remove members, delete,\n * open the database Studio, run SQL, change database components, and change\n * GitHub sync or secrets settings;\n * - owners can do everything. The channel creator is always an owner.\n * The server enforces all of this; the surface only hides what would be refused.\n * An unknown role (old server, members not loaded) means \"no restriction shown\".\n */\n\nexport type ProjectRole = 'owner' | 'editor' | 'viewer';\n\nexport const PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer'];\n/** Roles an owner can give when inviting (owners are made by changing a role). */\nexport const INVITE_ROLES: readonly ProjectRole[] = ['editor', 'viewer'];\n\nexport type RoleAction =\n | 'view'\n | 'comment'\n /** Build and edit turns (the composer, canvas Ask AI, \"Ask AI to fix\", Try to fix). */\n | 'build'\n /** Hand edits on the canvas and in the code editor. */\n | 'editCanvas'\n | 'editCode'\n | 'restoreVersion'\n | 'publish'\n | 'pushGithub'\n /** GitHub sync settings (auto-sync on or off). */\n | 'githubSync'\n /** Secrets settings (add, change, remove). */\n | 'secrets'\n | 'integrations'\n /** The database Studio link (full database access). */\n | 'databaseStudio'\n /** Cloud panel: data (read and edit rows), health, auth users and storage. Editors and owners. */\n | 'database'\n /** Cloud panel: the raw SQL runner (owners). */\n | 'databaseSql'\n /** Cloud panel: turn database components on or off (owners). */\n | 'databaseComponents'\n | 'updateSettings'\n /** Resolve production errors in the Health panel (editors and owners). */\n | 'resolveSiteErrors'\n /** The Health panel's alert settings (owners). */\n | 'siteAlerts'\n | 'share'\n | 'changeRole'\n | 'removeMember'\n | 'delete';\n\nconst VIEWER_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment']);\nconst OWNER_ONLY: ReadonlySet<RoleAction> = new Set([\n 'share',\n 'changeRole',\n 'removeMember',\n 'delete',\n 'databaseStudio',\n 'databaseSql',\n 'databaseComponents',\n 'githubSync',\n 'secrets',\n 'siteAlerts',\n]);\n\nexport function normalizeRole(raw: unknown): ProjectRole | null {\n const r = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return r === 'owner' || r === 'editor' || r === 'viewer' ? r : null;\n}\n\n/** May `role` do `action`? `null` (unknown) allows everything: the server still checks. */\nexport function roleCan(role: ProjectRole | null | undefined, action: RoleAction): boolean {\n if (!role) return true;\n if (role === 'owner') return true;\n if (role === 'editor') return !OWNER_ONLY.has(action);\n return VIEWER_ACTIONS.has(action);\n}\n\nexport interface ProjectMember {\n userId: string;\n name?: string;\n email?: string;\n role: ProjectRole;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction text(v: unknown, max: number): string | undefined {\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n return t ? t.slice(0, max) : undefined;\n}\n\n/** `aiCodeProjectMembers` JSON (an array, or `{ members }`, maybe as a string) -> members, owners first. */\nexport function parseMembers(raw: unknown): ProjectMember[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.members)) value = value.members;\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n const out: ProjectMember[] = [];\n for (const item of value) {\n if (!isRec(item)) continue;\n const userId = text(item.userId ?? item.id, 100);\n const role = normalizeRole(item.role);\n if (!userId || !role || seen.has(userId)) continue;\n seen.add(userId);\n const name = text(item.name, 200);\n const email = text(item.email, 320);\n out.push({ userId, role, ...(name ? { name } : {}), ...(email ? { email } : {}) });\n }\n const rank: Record<ProjectRole, number> = { owner: 0, editor: 1, viewer: 2 };\n return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));\n}\n\n/** The current user's role among `members`; null when they aren't listed (unknown). */\nexport function roleOf(members: readonly ProjectMember[], userId: string | null | undefined): ProjectRole | null {\n if (!userId) return null;\n return members.find((m) => m.userId === userId)?.role ?? null;\n}\n\nexport function memberLabel(m: Pick<ProjectMember, 'name' | 'email' | 'userId'>): string {\n return m.name || m.email || `User ${m.userId.slice(-6)}`;\n}\n\nexport const ROLE_LABELS: Record<ProjectRole, string> = {\n owner: 'Owner',\n editor: 'Can edit',\n viewer: 'Can view',\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\n\nexport function normalizeEmail(raw: string): string | null {\n const e = raw.trim().toLowerCase();\n return e.length <= 320 && EMAIL_RE.test(e) ? e : null;\n}\n\n/**\n * Spec §2: the last owner can't be removed or demoted. Returns the reason to\n * show, or null when the change is fine.\n */\nexport function lastOwnerProblem(\n members: readonly ProjectMember[],\n userId: string,\n next: ProjectRole | 'removed',\n): string | null {\n const target = members.find((m) => m.userId === userId);\n if (!target || target.role !== 'owner' || next === 'owner') return null;\n const owners = members.filter((m) => m.role === 'owner').length;\n if (owners > 1) return null;\n return next === 'removed'\n ? \"The project's only owner can't be removed. Make someone else an owner first.\"\n : \"The project's only owner can't be changed. Make someone else an owner first.\";\n}\n\n/** Board badge: shared with you when someone else created the channel. */\nexport function isSharedWithMe(creatorId: string | null | undefined, myUserId: string | null | undefined): boolean {\n if (!creatorId || !myUserId) return false;\n return creatorId !== myUserId;\n}\n\n/** The composer line while the open project is view-only (through `setExternalBusy`). */\nexport const VIEWER_BLOCKED_REASON = 'You have view access to this project. Ask an owner for edit access to change it.';\n\n/** `failure.stage === 'permission'` from the pipeline (spec §2 \"Limits\"). */\nexport const PERMISSION_FAILURE_TITLE = \"You can't change this project\";\n\nexport function permissionFailureText(message?: string | null): string {\n const m = String(message || '').trim();\n return m || 'You have view access to this project, so the AI did not change it. Ask an owner for edit access.';\n}\n\n/** Turn a server error from a sharing mutation into something a person can act on. */\nexport function sharingErrorText(message: string): string {\n const m = message.trim();\n if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {\n return `${m.replace(/\\.?$/, '.')} Only people in your organization can be added.`;\n }\n if (/forbidden|not allowed|only owners|permission/i.test(m)) return 'Only owners can change who has access.';\n return m || 'Something went wrong.';\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAcO,MAAM,aAAwC,GAAA,CAAC,OAAS,EAAA,QAAA,EAAU,QAAQ;AAEpE,MAAA,YAAA,GAAuC,CAAC,QAAA,EAAU,QAAQ;AAYvE,MAAM,iCAA8C,IAAA,GAAA,CAAI,CAAC,MAAA,EAAQ,SAAS,CAAC,CAAA;AAC3E,MAAM,UAAsC,mBAAA,IAAI,GAAI,CAAA,CAAC,SAAS,YAAc,EAAA,cAAA,EAAgB,QAAU,EAAA,gBAAA,EAAkB,aAAe,EAAA,oBAAA,EAAsB,YAAc,EAAA,SAAA,EAAW,YAAY,CAAC,CAAA;AAC5L,SAAS,cAAc,GAAkC,EAAA;AAC9D,EAAM,MAAA,CAAA,GAAI,OAAO,GAAQ,KAAA,QAAA,GAAW,IAAI,IAAK,EAAA,CAAE,aAAgB,GAAA,EAAA;AAC/D,EAAA,OAAO,MAAM,OAAW,IAAA,CAAA,KAAM,QAAY,IAAA,CAAA,KAAM,WAAW,CAAI,GAAA,IAAA;AACjE;AAGgB,SAAA,OAAA,CAAQ,MAAsC,MAA6B,EAAA;AACzF,EAAI,IAAA,CAAC,MAAa,OAAA,IAAA;AAClB,EAAI,IAAA,IAAA,KAAS,SAAgB,OAAA,IAAA;AAC7B,EAAA,IAAI,SAAS,QAAU,EAAA,OAAO,CAAC,UAAA,CAAW,IA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E,OAAQ,CAAA,MAAA,EAAQ,GAAG,CAAC,CAAA,+CAAA,CAAA;AAAA;AAElC,EAAA,IAAI,+CAAgD,CAAA,IAAA,CAAK,CAAC,CAAA,EAAU,OAAA,wCAAA;AACpE,EAAA,OAAO,CAAK,IAAA,uBAAA;AACd"}
1
+ {"version":3,"file":"roles.js","sources":["../../../../../src/features/webbuilder/web/sharing/roles.ts"],"sourcesContent":["/**\n * W31 sharing and roles (Phase 6 spec §2), surface side. Pure: tested with node:test.\n *\n * `roleCan` mirrors the server's checks in page-creator (stream P6):\n * - viewers can look (preview, code, history, read-only data views) and comment;\n * - editors can do everything except share, change roles, remove members, delete,\n * open the database Studio, run SQL, change database components, and change\n * GitHub sync or secrets settings;\n * - owners can do everything. The channel creator is always an owner;\n * - clients (an agency's customer, outside the organization, through an invitation) can look,\n * comment, edit the site with the AI and on the canvas, and ask the owners to publish. Nothing\n * else: no publishing, code editor, versions, GitHub, secrets, data, settings or sharing.\n * The server enforces all of this; the surface only hides what would be refused.\n * An unknown role (old server, members not loaded) means \"no restriction shown\".\n */\n\nexport type ProjectRole = 'owner' | 'editor' | 'viewer' | 'client';\n\n/** Every role a member can hold. */\nexport const ALL_PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer', 'client'];\n/** Roles an owner picks for a member. A client's role comes from their invitation, never from here. */\nexport const PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer'];\n/** Roles an owner can give when inviting (owners are made by changing a role). */\nexport const INVITE_ROLES: readonly ProjectRole[] = ['editor', 'viewer'];\n\nexport type RoleAction =\n | 'view'\n | 'comment'\n /** Build and edit turns (the composer, canvas Ask AI, \"Ask AI to fix\", Try to fix). */\n | 'build'\n /** Hand edits on the canvas and in the code editor. */\n | 'editCanvas'\n | 'editCode'\n | 'restoreVersion'\n | 'publish'\n | 'pushGithub'\n /** GitHub sync settings (auto-sync on or off). */\n | 'githubSync'\n /** Secrets settings (add, change, remove). */\n | 'secrets'\n | 'integrations'\n /** The database Studio link (full database access). */\n | 'databaseStudio'\n /** Cloud panel: data (read and edit rows), health, auth users and storage. Editors and owners. */\n | 'database'\n /** Cloud panel: the raw SQL runner (owners). */\n | 'databaseSql'\n /** Cloud panel: turn database components on or off (owners). */\n | 'databaseComponents'\n | 'updateSettings'\n /** Resolve production errors in the Health panel (editors and owners). */\n | 'resolveSiteErrors'\n /** The Health panel's alert settings (owners). */\n | 'siteAlerts'\n | 'share'\n | 'changeRole'\n | 'removeMember'\n | 'delete';\n\nconst VIEWER_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment']);\nconst CLIENT_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment', 'build', 'editCanvas']);\nconst OWNER_ONLY: ReadonlySet<RoleAction> = new Set([\n 'share',\n 'changeRole',\n 'removeMember',\n 'delete',\n 'databaseStudio',\n 'databaseSql',\n 'databaseComponents',\n 'githubSync',\n 'secrets',\n 'siteAlerts',\n]);\n\nexport function normalizeRole(raw: unknown): ProjectRole | null {\n const r = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return r === 'owner' || r === 'editor' || r === 'viewer' || r === 'client' ? r : null;\n}\n\n/** May `role` do `action`? `null` (unknown) allows everything: the server still checks. */\nexport function roleCan(role: ProjectRole | null | undefined, action: RoleAction): boolean {\n if (!role) return true;\n if (role === 'owner') return true;\n if (role === 'editor') return !OWNER_ONLY.has(action);\n if (role === 'client') return CLIENT_ACTIONS.has(action);\n return VIEWER_ACTIONS.has(action);\n}\n\nexport interface ProjectMember {\n userId: string;\n name?: string;\n email?: string;\n role: ProjectRole;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction text(v: unknown, max: number): string | undefined {\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n return t ? t.slice(0, max) : undefined;\n}\n\n/** `aiCodeProjectMembers` JSON (an array, or `{ members }`, maybe as a string) -> members, owners first. */\nexport function parseMembers(raw: unknown): ProjectMember[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.members)) value = value.members;\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n const out: ProjectMember[] = [];\n for (const item of value) {\n if (!isRec(item)) continue;\n const userId = text(item.userId ?? item.id, 100);\n const role = normalizeRole(item.role);\n if (!userId || !role || seen.has(userId)) continue;\n seen.add(userId);\n const name = text(item.name, 200);\n const email = text(item.email, 320);\n out.push({ userId, role, ...(name ? { name } : {}), ...(email ? { email } : {}) });\n }\n const rank: Record<ProjectRole, number> = { owner: 0, editor: 1, viewer: 2, client: 3 };\n return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));\n}\n\n/** The current user's role among `members`; null when they aren't listed (unknown). */\nexport function roleOf(members: readonly ProjectMember[], userId: string | null | undefined): ProjectRole | null {\n if (!userId) return null;\n return members.find((m) => m.userId === userId)?.role ?? null;\n}\n\nexport function memberLabel(m: Pick<ProjectMember, 'name' | 'email' | 'userId'>): string {\n return m.name || m.email || `User ${m.userId.slice(-6)}`;\n}\n\nexport const ROLE_LABELS: Record<ProjectRole, string> = {\n owner: 'Owner',\n editor: 'Can edit',\n viewer: 'Can view',\n client: 'Client',\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\n\nexport function normalizeEmail(raw: string): string | null {\n const e = raw.trim().toLowerCase();\n return e.length <= 320 && EMAIL_RE.test(e) ? e : null;\n}\n\n/**\n * Spec §2: the last owner can't be removed or demoted. Returns the reason to\n * show, or null when the change is fine.\n */\nexport function lastOwnerProblem(\n members: readonly ProjectMember[],\n userId: string,\n next: ProjectRole | 'removed',\n): string | null {\n const target = members.find((m) => m.userId === userId);\n if (!target || target.role !== 'owner' || next === 'owner') return null;\n const owners = members.filter((m) => m.role === 'owner').length;\n if (owners > 1) return null;\n return next === 'removed'\n ? \"The project's only owner can't be removed. Make someone else an owner first.\"\n : \"The project's only owner can't be changed. Make someone else an owner first.\";\n}\n\n/** Board badge: shared with you when someone else created the channel. */\nexport function isSharedWithMe(creatorId: string | null | undefined, myUserId: string | null | undefined): boolean {\n if (!creatorId || !myUserId) return false;\n return creatorId !== myUserId;\n}\n\n/** The composer line while the open project is view-only (through `setExternalBusy`). */\nexport const VIEWER_BLOCKED_REASON = 'You have view access to this project. Ask an owner for edit access to change it.';\n\n/** `failure.stage === 'permission'` from the pipeline (spec §2 \"Limits\"). */\nexport const PERMISSION_FAILURE_TITLE = \"You can't change this project\";\n\nexport function permissionFailureText(message?: string | null): string {\n const m = String(message || '').trim();\n return m || 'You have view access to this project, so the AI did not change it. Ask an owner for edit access.';\n}\n\n/** Turn a server error from a sharing mutation into something a person can act on. */\nexport function sharingErrorText(message: string): string {\n const m = message.trim();\n if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {\n return `${m.replace(/\\.?$/, '.')} Only people in your organization can be added.`;\n }\n if (/forbidden|not allowed|only owners|permission/i.test(m)) return 'Only owners can change who has access.';\n return m || 'Something went wrong.';\n}\n\n/** One client of the site, or a client invitation still waiting (`aiCodeSiteClients`). */\nexport interface SiteClient {\n grantId: string;\n email: string | null;\n status: 'PENDING' | 'ACTIVE' | 'REVOKED' | 'EXPIRED';\n userId: string | null;\n invitedAt: string | null;\n acceptedAt: string | null;\n inviteSent: boolean;\n}\n\nconst CLIENT_STATUSES = new Set(['PENDING', 'ACTIVE', 'REVOKED', 'EXPIRED']);\n\n/** `aiCodeSiteClients` JSON (an array or `{ clients }`, maybe a string) -> clients, pending first. */\nexport function parseSiteClients(raw: unknown): SiteClient[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.clients)) value = value.clients;\n if (!Array.isArray(value)) return [];\n const out = value.flatMap((item): SiteClient[] => {\n if (!isRec(item)) return [];\n const grantId = text(item.grantId, 100);\n const status = typeof item.status === 'string' && CLIENT_STATUSES.has(item.status) ? item.status : null;\n if (!grantId || !status) return [];\n return [\n {\n grantId,\n email: text(item.email, 320) ?? null,\n status: status as SiteClient['status'],\n userId: text(item.userId, 100) ?? null,\n invitedAt: text(item.invitedAt, 40) ?? null,\n acceptedAt: text(item.acceptedAt, 40) ?? null,\n inviteSent: item.inviteSent === true,\n },\n ];\n });\n const order = { PENDING: 0, ACTIVE: 1, EXPIRED: 2, REVOKED: 3 } as const;\n return out.sort((a, b) => order[a.status] - order[b.status]);\n}\n\n/** A client's line in the share dialog: who, and where their invitation stands. */\nexport function siteClientStatusText(client: SiteClient): string {\n if (client.status === 'ACTIVE') return 'Has access';\n if (client.status === 'EXPIRED') return 'Invitation expired';\n if (client.status === 'REVOKED') return 'Removed';\n return client.inviteSent ? 'Invited, not accepted yet' : 'Invited, email not sent yet';\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAqBO,MAAM,aAAwC,GAAA,CAAC,OAAS,EAAA,QAAA,EAAU,QAAQ;AAEpE,MAAA,YAAA,GAAuC,CAAC,QAAA,EAAU,QAAQ;AAYvE,MAAM,iCAA8C,IAAA,GAAA,CAAI,CAAC,MAAA,EAAQ,SAAS,CAAC,CAAA;AAC3E,MAAM,cAAA,uBAA8C,GAAI,CAAA,CAAC,QAAQ,SAAW,EAAA,OAAA,EAAS,YAAY,CAAC,CAAA;AAClG,MAAM,UAAsC,mBAAA,IAAI,GAAI,CAAA,CAAC,SAAS,YAAc,EAAA,cAAA,EAAgB,QAAU,EAAA,gBAAA,EAAkB,aAAe,EAAA,oBAAA,EAAsB,YAAc,EAAA,SAAA,EAAW,YAAY,CAAC,CAAA;AAC5L,SAAS,cAAc,GAAkC,EAAA;AAC9D,EAAM,MAAA,CAAA,GAAI,OAAO,GAAQ,KAAA,QAAA,GAAW,IAAI,IAAK,EAAA,CAAE,aAAgB,GAAA,EAAA;AAC/D,EA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AAA,EAAG,CAAM,KAAA,KAAA,CAAM,CAAE,CAAA,MAAM,CAAI,GAAA,KAAA,CAAM,CAAE,CAAA,MAAM,CAAC,CAAA;AAC7D;AAGO,SAAS,qBAAqB,MAA4B,EAAA;AAC/D,EAAI,IAAA,MAAA,CAAO,MAAW,KAAA,QAAA,EAAiB,OAAA,YAAA;AACvC,EAAI,IAAA,MAAA,CAAO,MAAW,KAAA,SAAA,EAAkB,OAAA,oBAAA;AACxC,EAAI,IAAA,MAAA,CAAO,MAAW,KAAA,SAAA,EAAkB,OAAA,SAAA;AACxC,EAAO,OAAA,MAAA,CAAO,aAAa,2BAA8B,GAAA,6BAAA;AAC3D"}
@@ -1,4 +1,4 @@
1
- import {runGql,failed}from'../data/graphql.js';import {unwrapResult}from'./okResult.js';import {roleOf,parseMembers}from'./roles.js';const PROJECT_MEMBERS_QUERY = `query aiCodeProjectMembers($channelId: String!) {
1
+ import {failed,runGql}from'../data/graphql.js';import {unwrapOk,unwrapResult}from'./okResult.js';import {parseSiteClients,roleOf,parseMembers}from'./roles.js';const PROJECT_MEMBERS_QUERY = `query aiCodeProjectMembers($channelId: String!) {
2
2
  aiCodeProjectMembers(channelId: $channelId)
3
3
  }`;
4
4
  const SHARE_PROJECT_MUTATION = `mutation aiCodeShareProject($channelId: String!, $email: String!, $role: String!) {
@@ -22,10 +22,51 @@ const CHANNEL_CREATORS_QUERY = `query WebbuilderChannelCreators($criteria: AnyOb
22
22
  creator { id }
23
23
  }
24
24
  }`;
25
+ const SITE_CLIENTS_QUERY = `query aiCodeSiteClients($channelId: String!) {
26
+ aiCodeSiteClients(channelId: $channelId)
27
+ }`;
28
+ const INVITE_CLIENT_MUTATION = `mutation aiCodeInviteSiteClient($channelId: String!, $email: String!, $message: String) {
29
+ aiCodeInviteSiteClient(channelId: $channelId, email: $email, message: $message)
30
+ }`;
31
+ const RESEND_CLIENT_INVITE_MUTATION = `mutation aiCodeResendSiteClientInvite($channelId: String!, $grantId: String!) {
32
+ aiCodeResendSiteClientInvite(channelId: $channelId, grantId: $grantId)
33
+ }`;
34
+ const REMOVE_CLIENT_MUTATION = `mutation aiCodeRemoveSiteClient($channelId: String!, $grantId: String!) {
35
+ aiCodeRemoveSiteClient(channelId: $channelId, grantId: $grantId)
36
+ }`;
37
+ const CLIENT_SITES_QUERY = `query aiCodeClientSites {
38
+ aiCodeClientSites
39
+ }`;
25
40
  const SHARING_OUTDATED_MESSAGE = "Sharing needs the latest server";
26
41
  function isRec(v) {
27
42
  return Boolean(v) && typeof v === "object" && !Array.isArray(v);
28
43
  }
44
+ function parseClientSites(raw) {
45
+ let value = raw;
46
+ if (typeof value === "string") {
47
+ try {
48
+ value = JSON.parse(value);
49
+ } catch (e) {
50
+ return [];
51
+ }
52
+ }
53
+ let list = [];
54
+ if (Array.isArray(value)) list = value;
55
+ else if (isRec(value) && Array.isArray(value.sites)) list = value.sites;
56
+ return list.flatMap((item) => {
57
+ if (!isRec(item) || typeof item.channelId !== "string" || !/^[A-Za-z0-9_-]{6,64}$/.test(item.channelId)) {
58
+ return [];
59
+ }
60
+ const title = typeof item.title === "string" ? item.title.trim().slice(0, 200) : "";
61
+ return [{
62
+ channelId: item.channelId,
63
+ title: title || "Website",
64
+ role: "client",
65
+ url: typeof item.url === "string" && /^https?:\/\//.test(item.url) ? item.url : null,
66
+ updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : null
67
+ }];
68
+ });
69
+ }
29
70
  function membersFromMutation(raw) {
30
71
  if (Array.isArray(raw) || isRec(raw) && Array.isArray(raw.members) || typeof raw === "string") {
31
72
  const list = parseMembers(raw);
@@ -171,20 +212,65 @@ function createSharingService(call, opts) {
171
212
  return null;
172
213
  }
173
214
  };
215
+ const clientSites = async () => {
216
+ var _a;
217
+ try {
218
+ const r = await call(CLIENT_SITES_QUERY, {});
219
+ const unwrapped = unwrapOk((_a = r.data) == null ? void 0 : _a.aiCodeClientSites, ["sites"]);
220
+ return unwrapped.ok ? parseClientSites(unwrapped.value) : [];
221
+ } catch (e) {
222
+ return [];
223
+ }
224
+ };
174
225
  const sharedWithMe = async (channelIds) => {
175
226
  const out = /* @__PURE__ */ new Set();
176
227
  if (!channelIds.length) return out;
177
228
  try {
178
- const [uid, creators] = await Promise.all([currentUserId(), creatorOf(channelIds)]);
179
- if (!uid) return out;
229
+ const [uid, creators, asClient] = await Promise.all([
230
+ currentUserId(),
231
+ creatorOf(channelIds),
232
+ // Sites shared from another organization are not in `channelsByUser`, so ask apart.
233
+ clientSites()
234
+ ]);
235
+ const clientIds = new Set(asClient.map((site) => site.channelId));
180
236
  for (const id of channelIds) {
181
237
  const creator = creators.get(id);
182
- if (creator && creator !== uid) out.add(id);
238
+ if (clientIds.has(id) || uid && creator && creator !== uid) out.add(id);
183
239
  }
184
240
  } catch (e) {
185
241
  }
186
242
  return out;
187
243
  };
244
+ const siteClients = async (channelId) => {
245
+ const raw = await runGql(() => call(SITE_CLIENTS_QUERY, {
246
+ channelId
247
+ }), (d) => d.aiCodeSiteClients, {
248
+ outdatedMessage: SHARING_OUTDATED_MESSAGE
249
+ });
250
+ const unwrapped = unwrapResult(raw, ["clients"]);
251
+ return unwrapped.ok ? {
252
+ ok: true,
253
+ value: parseSiteClients(unwrapped.value)
254
+ } : failed(unwrapped);
255
+ };
256
+ const afterClientChange = async (channelId, r) => {
257
+ if (!r.ok) return failed(r);
258
+ memberCache.delete(channelId);
259
+ return siteClients(channelId);
260
+ };
261
+ const inviteClient = async (channelId, email, message) => afterClientChange(channelId, await mutate(INVITE_CLIENT_MUTATION, {
262
+ channelId,
263
+ email,
264
+ message: message || null
265
+ }, "aiCodeInviteSiteClient"));
266
+ const resendClientInvite = async (channelId, grantId) => afterClientChange(channelId, await mutate(RESEND_CLIENT_INVITE_MUTATION, {
267
+ channelId,
268
+ grantId
269
+ }, "aiCodeResendSiteClientInvite"));
270
+ const removeClient = async (channelId, grantId) => afterClientChange(channelId, await mutate(REMOVE_CLIENT_MUTATION, {
271
+ channelId,
272
+ grantId
273
+ }, "aiCodeRemoveSiteClient"));
188
274
  return {
189
275
  currentUserId,
190
276
  members,
@@ -194,6 +280,11 @@ function createSharingService(call, opts) {
194
280
  removeMember,
195
281
  deleteProject,
196
282
  sharedWithMe,
197
- createdByMe
283
+ createdByMe,
284
+ siteClients,
285
+ inviteClient,
286
+ resendClientInvite,
287
+ removeClient,
288
+ clientSites
198
289
  };
199
- }export{CHANNEL_CREATORS_QUERY,CURRENT_USER_QUERY,DELETE_PROJECT_MUTATION,PROJECT_MEMBERS_QUERY,REMOVE_MEMBER_MUTATION,SHARE_PROJECT_MUTATION,SHARING_OUTDATED_MESSAGE,UPDATE_MEMBER_ROLE_MUTATION,createSharingService};//# sourceMappingURL=sharingApi.js.map
290
+ }export{CHANNEL_CREATORS_QUERY,CLIENT_SITES_QUERY,CURRENT_USER_QUERY,DELETE_PROJECT_MUTATION,INVITE_CLIENT_MUTATION,PROJECT_MEMBERS_QUERY,REMOVE_CLIENT_MUTATION,REMOVE_MEMBER_MUTATION,RESEND_CLIENT_INVITE_MUTATION,SHARE_PROJECT_MUTATION,SHARING_OUTDATED_MESSAGE,SITE_CLIENTS_QUERY,UPDATE_MEMBER_ROLE_MUTATION,createSharingService,parseClientSites};//# sourceMappingURL=sharingApi.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sharingApi.js","sources":["../../../../../src/features/webbuilder/web/sharing/sharingApi.ts"],"sourcesContent":["/**\n * W31: the sharing GraphQL calls (Phase 6 spec §2), on an injected transport so\n * they can be tested with a fake. A server without the new fields (\"Cannot\n * query field\") answers `{ ok: false, outdated: true }`: the surface then hides\n * sharing and keeps the Phase 5 behaviour (delete falls back to `deleteChannel`).\n */\n\nimport { failed, runGql, type DataResult, type GqlResult } from '../data/graphql';\nimport { unwrapResult } from './okResult';\nimport { parseMembers, roleOf, type ProjectMember, type ProjectRole } from './roles';\n\nexport const PROJECT_MEMBERS_QUERY = `query aiCodeProjectMembers($channelId: String!) {\n aiCodeProjectMembers(channelId: $channelId)\n}`;\n\nexport const SHARE_PROJECT_MUTATION = `mutation aiCodeShareProject($channelId: String!, $email: String!, $role: String!) {\n aiCodeShareProject(channelId: $channelId, email: $email, role: $role)\n}`;\n\nexport const UPDATE_MEMBER_ROLE_MUTATION = `mutation aiCodeUpdateProjectMemberRole($channelId: String!, $userId: String!, $role: String!) {\n aiCodeUpdateProjectMemberRole(channelId: $channelId, userId: $userId, role: $role)\n}`;\n\nexport const REMOVE_MEMBER_MUTATION = `mutation aiCodeRemoveProjectMember($channelId: String!, $userId: String!) {\n aiCodeRemoveProjectMember(channelId: $channelId, userId: $userId)\n}`;\n\nexport const DELETE_PROJECT_MUTATION = `mutation aiCodeDeleteProject($channelId: String!) {\n aiCodeDeleteProject(channelId: $channelId)\n}`;\n\nexport const CURRENT_USER_QUERY = `query WebbuilderCurrentUser {\n getUserAccount { id }\n}`;\n\n/** Who created each board channel (`Channel.creator`), for the \"Shared with you\" badge. */\nexport const CHANNEL_CREATORS_QUERY = `query WebbuilderChannelCreators($criteria: AnyObject, $limit: Int, $skip: Int, $sort: Sort) {\n channelsByUser(criteria: $criteria, limit: $limit, skip: $skip, sort: $sort) {\n id\n creator { id }\n }\n}`;\n\nexport const SHARING_OUTDATED_MESSAGE = 'Sharing needs the latest server';\n\nexport type GqlCall = <T>(document: string, variables: Record<string, unknown>) => Promise<GqlResult<T>>;\n\n/** One shape (native has no strict null checks, where the web's union does not narrow). */\nexport interface DeleteProjectResult {\n ok: boolean;\n outdated?: boolean;\n message?: string;\n}\n\nexport interface WebBuilderSharingService {\n /** The signed-in user's account id (cached); null when it can't be read. */\n currentUserId: () => Promise<string | null>;\n /** Members with roles. `outdated`: the server has no sharing - hide it. */\n members: (channelId: string, opts?: { force?: boolean }) => Promise<DataResult<ProjectMember[]>>;\n /** The current user's role; null = unknown (no restriction shown, the server still checks). */\n myRole: (channelId: string, opts?: { force?: boolean }) => Promise<ProjectRole | null>;\n /** Owners only. Resolves with the fresh member list. */\n share: (channelId: string, email: string, role: ProjectRole) => Promise<DataResult<ProjectMember[]>>;\n updateRole: (channelId: string, userId: string, role: ProjectRole) => Promise<DataResult<ProjectMember[]>>;\n removeMember: (channelId: string, userId: string) => Promise<DataResult<ProjectMember[]>>;\n /** `aiCodeDeleteProject` (owners only). `outdated`: call `deleteChannel` instead. */\n deleteProject: (channelId: string) => Promise<DeleteProjectResult>;\n /** Of these channels, the ones someone else created (best effort; empty on any failure). */\n sharedWithMe: (channelIds: readonly string[]) => Promise<Set<string>>;\n /** Whether the signed-in user created this channel; null when it can't be told. */\n createdByMe?: (channelId: string) => Promise<boolean | null>;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\n/** A mutation may answer with the members, `{ members }`, `true`, or nothing useful. */\nfunction membersFromMutation(raw: unknown): ProjectMember[] | null {\n if (Array.isArray(raw) || (isRec(raw) && Array.isArray(raw.members)) || typeof raw === 'string') {\n const list = parseMembers(raw);\n return list.length ? list : null;\n }\n return null;\n}\n\n/** Payload keys a members answer may use. */\nconst MEMBER_KEYS = ['members'] as const;\n\nexport function createSharingService(call: GqlCall, opts?: { gallerySize?: () => number }): WebBuilderSharingService {\n let me: Promise<string | null> | null = null;\n const memberCache = new Map<string, ProjectMember[]>();\n /** The server has no sharing fields: don't ask again this session. */\n let outdated = false;\n\n const currentUserId = () => {\n if (!me) {\n me = call<{ getUserAccount?: { id?: string } | null }>(CURRENT_USER_QUERY, {})\n .then((r) => (typeof r.data?.getUserAccount?.id === 'string' ? r.data.getUserAccount.id : null))\n .catch(() => null)\n .then((id) => {\n if (!id) me = null;\n return id;\n });\n }\n return me;\n };\n\n const members = async (channelId: string, o?: { force?: boolean }): Promise<DataResult<ProjectMember[]>> => {\n if (outdated) return { ok: false, outdated: true, message: SHARING_OUTDATED_MESSAGE };\n const cached = memberCache.get(channelId);\n if (cached && !o?.force) return { ok: true, value: cached };\n const raw = await runGql(\n () => call<{ aiCodeProjectMembers?: unknown }>(PROJECT_MEMBERS_QUERY, { channelId }),\n (d) => d.aiCodeProjectMembers,\n { outdatedMessage: SHARING_OUTDATED_MESSAGE },\n );\n // `{ ok: true, members }` (or a bare list); `{ ok: false, error(s) }` is a failure.\n const unwrapped = unwrapResult(raw, MEMBER_KEYS);\n if (!unwrapped.ok) {\n if (unwrapped.outdated) outdated = true;\n return failed(unwrapped);\n }\n const r: DataResult<ProjectMember[]> = { ok: true, value: parseMembers(unwrapped.value) };\n memberCache.set(channelId, r.value);\n return r;\n };\n\n const myRole = async (channelId: string, o?: { force?: boolean }) => {\n const [list, uid] = await Promise.all([members(channelId, o), currentUserId()]);\n return list.ok ? roleOf(list.value, uid) : null;\n };\n\n const afterChange = async (channelId: string, r: DataResult<unknown>): Promise<DataResult<ProjectMember[]>> => {\n if (!r.ok) return failed(r);\n const direct = membersFromMutation(r.value);\n if (direct) {\n memberCache.set(channelId, direct);\n return { ok: true, value: direct };\n }\n return members(channelId, { force: true });\n };\n\n /** One mutation, with `{ ok: false, error(s) }` folded into a failure and `members` unwrapped. */\n const mutate = async (document: string, variables: Record<string, unknown>, field: string) =>\n unwrapResult(\n await runGql(\n () => call<Record<string, unknown>>(document, variables),\n (d) => (d[field] === undefined ? undefined : d[field]),\n { outdatedMessage: SHARING_OUTDATED_MESSAGE },\n ),\n MEMBER_KEYS,\n );\n\n const share = async (channelId: string, email: string, role: ProjectRole) => {\n const r = await mutate(SHARE_PROJECT_MUTATION, { channelId, email, role }, 'aiCodeShareProject');\n return afterChange(channelId, r);\n };\n const updateRole = async (channelId: string, userId: string, role: ProjectRole) => {\n const r = await mutate(\n UPDATE_MEMBER_ROLE_MUTATION,\n { channelId, userId, role },\n 'aiCodeUpdateProjectMemberRole',\n );\n return afterChange(channelId, r);\n };\n const removeMember = async (channelId: string, userId: string) => {\n const r = await mutate(REMOVE_MEMBER_MUTATION, { channelId, userId }, 'aiCodeRemoveProjectMember');\n return afterChange(channelId, r);\n };\n\n const deleteProject = async (channelId: string): Promise<DeleteProjectResult> => {\n const r = await mutate(DELETE_PROJECT_MUTATION, { channelId }, 'aiCodeDeleteProject');\n if (!r.ok)\n return r.outdated ? { ok: false, outdated: true, message: r.message } : { ok: false, message: r.message };\n if (r.value === false) return { ok: false, message: 'The project could not be deleted.' };\n memberCache.delete(channelId);\n return { ok: true };\n };\n\n const creatorOf = async (channelIds: readonly string[]) => {\n const r = await call<{ channelsByUser?: Array<{ id?: string; creator?: { id?: string } | null } | null> }>(\n CHANNEL_CREATORS_QUERY,\n {\n criteria: { type: 'AIASSISTANT' },\n limit: Math.min(200, Math.max(channelIds.length, opts?.gallerySize?.() ?? 0, 10)),\n skip: 0,\n sort: { key: 'updatedAt', value: 'DESC' },\n },\n );\n const out = new Map<string, string>();\n for (const row of r.data?.channelsByUser ?? []) {\n if (row?.id && row.creator?.id) out.set(row.id, row.creator.id);\n }\n return out;\n };\n\n const createdByMe = async (channelId: string): Promise<boolean | null> => {\n try {\n const [uid, creators] = await Promise.all([currentUserId(), creatorOf([channelId])]);\n const creator = creators.get(channelId);\n return uid && creator ? creator === uid : null;\n } catch {\n return null;\n }\n };\n\n const sharedWithMe = async (channelIds: readonly string[]): Promise<Set<string>> => {\n const out = new Set<string>();\n if (!channelIds.length) return out;\n try {\n const [uid, creators] = await Promise.all([currentUserId(), creatorOf(channelIds)]);\n if (!uid) return out;\n for (const id of channelIds) {\n const creator = creators.get(id);\n if (creator && creator !== uid) out.add(id);\n }\n } catch {\n /* best effort: no badges */\n }\n return out;\n };\n\n return {\n currentUserId,\n members,\n myRole,\n share,\n updateRole,\n removeMember,\n deleteProject,\n sharedWithMe,\n createdByMe,\n };\n}\n"],"names":[],"mappings":"qIAUO,MAAM,qBAAwB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG9B,MAAM,sBAAyB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG/B,MAAM,2BAA8B,GAAA,CAAA;AAAA;AAAA,CAAA;AAGpC,MAAM,sBAAyB,GAAA,CAAA;AAAA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OAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,YAAA;AAAA,IACA;AAAA,GACF;AACF"}
1
+ {"version":3,"file":"sharingApi.js","sources":["../../../../../src/features/webbuilder/web/sharing/sharingApi.ts"],"sourcesContent":["/**\n * W31: the sharing GraphQL calls (Phase 6 spec §2), on an injected transport so\n * they can be tested with a fake. A server without the new fields (\"Cannot\n * query field\") answers `{ ok: false, outdated: true }`: the surface then hides\n * sharing and keeps the Phase 5 behaviour (delete falls back to `deleteChannel`).\n */\n\nimport { failed, runGql, type DataResult, type GqlResult } from '../data/graphql';\nimport { unwrapOk, unwrapResult } from './okResult';\nimport { parseMembers, parseSiteClients, roleOf, type ProjectMember, type ProjectRole, type SiteClient } from './roles';\n\nexport const PROJECT_MEMBERS_QUERY = `query aiCodeProjectMembers($channelId: String!) {\n aiCodeProjectMembers(channelId: $channelId)\n}`;\n\nexport const SHARE_PROJECT_MUTATION = `mutation aiCodeShareProject($channelId: String!, $email: String!, $role: String!) {\n aiCodeShareProject(channelId: $channelId, email: $email, role: $role)\n}`;\n\nexport const UPDATE_MEMBER_ROLE_MUTATION = `mutation aiCodeUpdateProjectMemberRole($channelId: String!, $userId: String!, $role: String!) {\n aiCodeUpdateProjectMemberRole(channelId: $channelId, userId: $userId, role: $role)\n}`;\n\nexport const REMOVE_MEMBER_MUTATION = `mutation aiCodeRemoveProjectMember($channelId: String!, $userId: String!) {\n aiCodeRemoveProjectMember(channelId: $channelId, userId: $userId)\n}`;\n\nexport const DELETE_PROJECT_MUTATION = `mutation aiCodeDeleteProject($channelId: String!) {\n aiCodeDeleteProject(channelId: $channelId)\n}`;\n\nexport const CURRENT_USER_QUERY = `query WebbuilderCurrentUser {\n getUserAccount { id }\n}`;\n\n/** Who created each board channel (`Channel.creator`), for the \"Shared with you\" badge. */\nexport const CHANNEL_CREATORS_QUERY = `query WebbuilderChannelCreators($criteria: AnyObject, $limit: Int, $skip: Int, $sort: Sort) {\n channelsByUser(criteria: $criteria, limit: $limit, skip: $skip, sort: $sort) {\n id\n creator { id }\n }\n}`;\n\nexport const SITE_CLIENTS_QUERY = `query aiCodeSiteClients($channelId: String!) {\n aiCodeSiteClients(channelId: $channelId)\n}`;\n\nexport const INVITE_CLIENT_MUTATION = `mutation aiCodeInviteSiteClient($channelId: String!, $email: String!, $message: String) {\n aiCodeInviteSiteClient(channelId: $channelId, email: $email, message: $message)\n}`;\n\nexport const RESEND_CLIENT_INVITE_MUTATION = `mutation aiCodeResendSiteClientInvite($channelId: String!, $grantId: String!) {\n aiCodeResendSiteClientInvite(channelId: $channelId, grantId: $grantId)\n}`;\n\nexport const REMOVE_CLIENT_MUTATION = `mutation aiCodeRemoveSiteClient($channelId: String!, $grantId: String!) {\n aiCodeRemoveSiteClient(channelId: $channelId, grantId: $grantId)\n}`;\n\nexport const CLIENT_SITES_QUERY = `query aiCodeClientSites {\n aiCodeClientSites\n}`;\n\nexport const SHARING_OUTDATED_MESSAGE = 'Sharing needs the latest server';\n\n/** A site shared with the signed-in user as a client, from another organization (`aiCodeClientSites`). */\nexport interface ClientSite {\n channelId: string;\n title: string;\n role: 'client';\n url: string | null;\n updatedAt: string | null;\n}\n\nexport type GqlCall = <T>(document: string, variables: Record<string, unknown>) => Promise<GqlResult<T>>;\n\n/** One shape (native has no strict null checks, where the web's union does not narrow). */\nexport interface DeleteProjectResult {\n ok: boolean;\n outdated?: boolean;\n message?: string;\n}\n\nexport interface WebBuilderSharingService {\n /** The signed-in user's account id (cached); null when it can't be read. */\n currentUserId: () => Promise<string | null>;\n /** Members with roles. `outdated`: the server has no sharing - hide it. */\n members: (channelId: string, opts?: { force?: boolean }) => Promise<DataResult<ProjectMember[]>>;\n /** The current user's role; null = unknown (no restriction shown, the server still checks). */\n myRole: (channelId: string, opts?: { force?: boolean }) => Promise<ProjectRole | null>;\n /** Owners only. Resolves with the fresh member list. */\n share: (channelId: string, email: string, role: ProjectRole) => Promise<DataResult<ProjectMember[]>>;\n updateRole: (channelId: string, userId: string, role: ProjectRole) => Promise<DataResult<ProjectMember[]>>;\n removeMember: (channelId: string, userId: string) => Promise<DataResult<ProjectMember[]>>;\n /** `aiCodeDeleteProject` (owners only). `outdated`: call `deleteChannel` instead. */\n deleteProject: (channelId: string) => Promise<DeleteProjectResult>;\n /** Of these channels, the ones someone else created (best effort; empty on any failure). */\n sharedWithMe: (channelIds: readonly string[]) => Promise<Set<string>>;\n /** Whether the signed-in user created this channel; null when it can't be told. */\n createdByMe?: (channelId: string) => Promise<boolean | null>;\n /** Owners only: the site's clients and pending client invitations. */\n siteClients?: (channelId: string) => Promise<DataResult<SiteClient[]>>;\n /** Owners only: invite someone outside the organization as a client. Resolves with the fresh list. */\n inviteClient?: (channelId: string, email: string, message?: string) => Promise<DataResult<SiteClient[]>>;\n resendClientInvite?: (channelId: string, grantId: string) => Promise<DataResult<SiteClient[]>>;\n /** Ends a client's access (or withdraws the invitation) at once. Resolves with the fresh list. */\n removeClient?: (channelId: string, grantId: string) => Promise<DataResult<SiteClient[]>>;\n /** Sites shared with the signed-in user as a client, from other organizations. */\n clientSites?: () => Promise<ClientSite[]>;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\n/** `aiCodeClientSites` JSON -> the sites, with anything malformed left out. */\nexport function parseClientSites(raw: unknown): ClientSite[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n let list: unknown[] = [];\n if (Array.isArray(value)) list = value;\n else if (isRec(value) && Array.isArray(value.sites)) list = value.sites;\n return list.flatMap((item): ClientSite[] => {\n if (!isRec(item) || typeof item.channelId !== 'string' || !/^[A-Za-z0-9_-]{6,64}$/.test(item.channelId)) {\n return [];\n }\n const title = typeof item.title === 'string' ? item.title.trim().slice(0, 200) : '';\n return [\n {\n channelId: item.channelId,\n title: title || 'Website',\n role: 'client',\n url: typeof item.url === 'string' && /^https?:\\/\\//.test(item.url) ? item.url : null,\n updatedAt: typeof item.updatedAt === 'string' ? item.updatedAt : null,\n },\n ];\n });\n}\n\n/** A mutation may answer with the members, `{ members }`, `true`, or nothing useful. */\nfunction membersFromMutation(raw: unknown): ProjectMember[] | null {\n if (Array.isArray(raw) || (isRec(raw) && Array.isArray(raw.members)) || typeof raw === 'string') {\n const list = parseMembers(raw);\n return list.length ? list : null;\n }\n return null;\n}\n\n/** Payload keys a members answer may use. */\nconst MEMBER_KEYS = ['members'] as const;\n\nexport function createSharingService(call: GqlCall, opts?: { gallerySize?: () => number }): WebBuilderSharingService {\n let me: Promise<string | null> | null = null;\n const memberCache = new Map<string, ProjectMember[]>();\n /** The server has no sharing fields: don't ask again this session. */\n let outdated = false;\n\n const currentUserId = () => {\n if (!me) {\n me = call<{ getUserAccount?: { id?: string } | null }>(CURRENT_USER_QUERY, {})\n .then((r) => (typeof r.data?.getUserAccount?.id === 'string' ? r.data.getUserAccount.id : null))\n .catch(() => null)\n .then((id) => {\n if (!id) me = null;\n return id;\n });\n }\n return me;\n };\n\n const members = async (channelId: string, o?: { force?: boolean }): Promise<DataResult<ProjectMember[]>> => {\n if (outdated) return { ok: false, outdated: true, message: SHARING_OUTDATED_MESSAGE };\n const cached = memberCache.get(channelId);\n if (cached && !o?.force) return { ok: true, value: cached };\n const raw = await runGql(\n () => call<{ aiCodeProjectMembers?: unknown }>(PROJECT_MEMBERS_QUERY, { channelId }),\n (d) => d.aiCodeProjectMembers,\n { outdatedMessage: SHARING_OUTDATED_MESSAGE },\n );\n // `{ ok: true, members }` (or a bare list); `{ ok: false, error(s) }` is a failure.\n const unwrapped = unwrapResult(raw, MEMBER_KEYS);\n if (!unwrapped.ok) {\n if (unwrapped.outdated) outdated = true;\n return failed(unwrapped);\n }\n const r: DataResult<ProjectMember[]> = { ok: true, value: parseMembers(unwrapped.value) };\n memberCache.set(channelId, r.value);\n return r;\n };\n\n const myRole = async (channelId: string, o?: { force?: boolean }) => {\n const [list, uid] = await Promise.all([members(channelId, o), currentUserId()]);\n return list.ok ? roleOf(list.value, uid) : null;\n };\n\n const afterChange = async (channelId: string, r: DataResult<unknown>): Promise<DataResult<ProjectMember[]>> => {\n if (!r.ok) return failed(r);\n const direct = membersFromMutation(r.value);\n if (direct) {\n memberCache.set(channelId, direct);\n return { ok: true, value: direct };\n }\n return members(channelId, { force: true });\n };\n\n /** One mutation, with `{ ok: false, error(s) }` folded into a failure and `members` unwrapped. */\n const mutate = async (document: string, variables: Record<string, unknown>, field: string) =>\n unwrapResult(\n await runGql(\n () => call<Record<string, unknown>>(document, variables),\n (d) => (d[field] === undefined ? undefined : d[field]),\n { outdatedMessage: SHARING_OUTDATED_MESSAGE },\n ),\n MEMBER_KEYS,\n );\n\n const share = async (channelId: string, email: string, role: ProjectRole) => {\n const r = await mutate(SHARE_PROJECT_MUTATION, { channelId, email, role }, 'aiCodeShareProject');\n return afterChange(channelId, r);\n };\n const updateRole = async (channelId: string, userId: string, role: ProjectRole) => {\n const r = await mutate(\n UPDATE_MEMBER_ROLE_MUTATION,\n { channelId, userId, role },\n 'aiCodeUpdateProjectMemberRole',\n );\n return afterChange(channelId, r);\n };\n const removeMember = async (channelId: string, userId: string) => {\n const r = await mutate(REMOVE_MEMBER_MUTATION, { channelId, userId }, 'aiCodeRemoveProjectMember');\n return afterChange(channelId, r);\n };\n\n const deleteProject = async (channelId: string): Promise<DeleteProjectResult> => {\n const r = await mutate(DELETE_PROJECT_MUTATION, { channelId }, 'aiCodeDeleteProject');\n if (!r.ok)\n return r.outdated ? { ok: false, outdated: true, message: r.message } : { ok: false, message: r.message };\n if (r.value === false) return { ok: false, message: 'The project could not be deleted.' };\n memberCache.delete(channelId);\n return { ok: true };\n };\n\n const creatorOf = async (channelIds: readonly string[]) => {\n const r = await call<{ channelsByUser?: Array<{ id?: string; creator?: { id?: string } | null } | null> }>(\n CHANNEL_CREATORS_QUERY,\n {\n criteria: { type: 'AIASSISTANT' },\n limit: Math.min(200, Math.max(channelIds.length, opts?.gallerySize?.() ?? 0, 10)),\n skip: 0,\n sort: { key: 'updatedAt', value: 'DESC' },\n },\n );\n const out = new Map<string, string>();\n for (const row of r.data?.channelsByUser ?? []) {\n if (row?.id && row.creator?.id) out.set(row.id, row.creator.id);\n }\n return out;\n };\n\n const createdByMe = async (channelId: string): Promise<boolean | null> => {\n try {\n const [uid, creators] = await Promise.all([currentUserId(), creatorOf([channelId])]);\n const creator = creators.get(channelId);\n return uid && creator ? creator === uid : null;\n } catch {\n return null;\n }\n };\n\n const clientSites = async (): Promise<ClientSite[]> => {\n try {\n const r = await call<{ aiCodeClientSites?: unknown }>(CLIENT_SITES_QUERY, {});\n const unwrapped = unwrapOk(r.data?.aiCodeClientSites, ['sites']);\n return unwrapped.ok ? parseClientSites(unwrapped.value) : [];\n } catch {\n // Best effort: an older server has no client sites, and the board is complete without them.\n return [];\n }\n };\n\n const sharedWithMe = async (channelIds: readonly string[]): Promise<Set<string>> => {\n const out = new Set<string>();\n if (!channelIds.length) return out;\n try {\n const [uid, creators, asClient] = await Promise.all([\n currentUserId(),\n creatorOf(channelIds),\n // Sites shared from another organization are not in `channelsByUser`, so ask apart.\n clientSites(),\n ]);\n const clientIds = new Set(asClient.map((site) => site.channelId));\n for (const id of channelIds) {\n const creator = creators.get(id);\n if (clientIds.has(id) || (uid && creator && creator !== uid)) out.add(id);\n }\n } catch {\n /* best effort: no badges */\n }\n return out;\n };\n\n const siteClients = async (channelId: string): Promise<DataResult<SiteClient[]>> => {\n const raw = await runGql(\n () => call<{ aiCodeSiteClients?: unknown }>(SITE_CLIENTS_QUERY, { channelId }),\n (d) => d.aiCodeSiteClients,\n { outdatedMessage: SHARING_OUTDATED_MESSAGE },\n );\n const unwrapped = unwrapResult(raw, ['clients']);\n return unwrapped.ok ? { ok: true, value: parseSiteClients(unwrapped.value) } : failed<SiteClient[]>(unwrapped);\n };\n\n /** After a client change: the members changed too (a client joined or left), so re-read both. */\n const afterClientChange = async (channelId: string, r: DataResult<unknown>): Promise<DataResult<SiteClient[]>> => {\n if (!r.ok) return failed<SiteClient[]>(r);\n memberCache.delete(channelId);\n return siteClients(channelId);\n };\n\n const inviteClient = async (channelId: string, email: string, message?: string) =>\n afterClientChange(\n channelId,\n await mutate(\n INVITE_CLIENT_MUTATION,\n { channelId, email, message: message || null },\n 'aiCodeInviteSiteClient',\n ),\n );\n const resendClientInvite = async (channelId: string, grantId: string) =>\n afterClientChange(\n channelId,\n await mutate(RESEND_CLIENT_INVITE_MUTATION, { channelId, grantId }, 'aiCodeResendSiteClientInvite'),\n );\n const removeClient = async (channelId: string, grantId: string) =>\n afterClientChange(\n channelId,\n await mutate(REMOVE_CLIENT_MUTATION, { channelId, grantId }, 'aiCodeRemoveSiteClient'),\n );\n\n return {\n currentUserId,\n members,\n myRole,\n share,\n updateRole,\n removeMember,\n deleteProject,\n sharedWithMe,\n createdByMe,\n siteClients,\n inviteClient,\n resendClientInvite,\n removeClient,\n clientSites,\n };\n}\n"],"names":[],"mappings":"+JAUO,MAAM,qBAAwB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG9B,MAAM,sBAAyB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG/B,MAAM,2BAA8B,GAAA,CAAA;AAAA;AAAA,CAAA;AAGpC,MAAM,sBAAyB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG/B,MAAM,uBAA0B,GAAA,CAAA;AAAA;AAAA,CAAA;AAGhC,MAAM,kBAAqB,GAAA,CAAA;AAAA;AAAA,CAAA;AAK3B,MAAM,sBAAyB,GAAA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAM/B,MAAM,kBAAqB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG3B,MAAM,sBAAyB,GAAA,CAAA;AAAA;AAAA,CAAA;AAG/B,MAAM,6BAAgC,GAAA,CAAA;AAAA;AAAA,CAAA;AAGtC,MAAM,sBAAyB,GAAA,C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AA,GAC9B;AACA,EAAM,MAAA,YAAA,GAAe,OAAO,SAAmB,EAAA,KAAA,EAAe,YAAqB,iBAAkB,CAAA,SAAA,EAAW,MAAM,MAAA,CAAO,sBAAwB,EAAA;AAAA,IACnJ,SAAA;AAAA,IACA,KAAA;AAAA,IACA,SAAS,OAAW,IAAA;AAAA,GACtB,EAAG,wBAAwB,CAAC,CAAA;AAC5B,EAAM,MAAA,kBAAA,GAAqB,OAAO,SAAmB,EAAA,OAAA,KAAoB,kBAAkB,SAAW,EAAA,MAAM,OAAO,6BAA+B,EAAA;AAAA,IAChJ,SAAA;AAAA,IACA;AAAA,GACF,EAAG,8BAA8B,CAAC,CAAA;AAClC,EAAM,MAAA,YAAA,GAAe,OAAO,SAAmB,EAAA,OAAA,KAAoB,kBAAkB,SAAW,EAAA,MAAM,OAAO,sBAAwB,EAAA;AAAA,IACnI,SAAA;AAAA,IACA;AAAA,GACF,EAAG,wBAAwB,CAAC,CAAA;AAC5B,EAAO,OAAA;AAAA,IACL,aAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAA;AAAA,IACA,aAAA;AAAA,IACA,YAAA;AAAA,IACA,WAAA;AAAA,IACA,WAAA;AAAA,IACA,YAAA;AAAA,IACA,kBAAA;AAAA,IACA,YAAA;AAAA,IACA;AAAA,GACF;AACF"}
@@ -41,6 +41,8 @@ const storageKeys = {
41
41
  session: () => userKey("session"),
42
42
  brandKit: () => userKey("brandKit"),
43
43
  lastSiteScore: () => userKey("lastSiteScore"),
44
+ /** Last good home data (templates, recent builds, credits) per org, shown while the network read runs. */
45
+ homeCache: (name, orgId) => userKey("homeCache", `${name}:${orgId || "_"}`),
44
46
  healthNoticeDismissed: (channelId) => userKey("healthNoticeDismissed", channelId),
45
47
  restoredSandbox: (channelId) => userKey("restoredSandbox", channelId),
46
48
  githubSyncPending: (channelId) => userKey("githubSyncPending", channelId),