@devbie/fewbie-cli 1.13.1 → 1.13.2

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.
@@ -7,7 +7,7 @@
7
7
  "files": [
8
8
  {
9
9
  "path": "src/components/data-table.tsx",
10
- "content": "\"use client\";\n\nimport { useState, useMemo, type ReactNode } from \"react\";\nimport { ArrowUpDown, ChevronLeft, ChevronRight } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\n\n/** Column definition for the data table. */\nexport interface Column<T> {\n /** Key used to access the row value; also used as the sort key. */\n accessorKey: keyof T & string;\n /** Column header label. */\n header: string;\n /** Optional custom cell renderer. Receives the row's value for this column. */\n cell?: (value: T[keyof T], row: T) => ReactNode;\n /** Disable sorting for this column. */\n enableSorting?: boolean;\n}\n\ninterface DataTableProps<T> {\n columns: Column<T>[];\n data: T[];\n /** Number of rows per page. Defaults to 10. */\n pageSize?: number;\n className?: string;\n}\n\ntype SortDir = \"asc\" | \"desc\";\n\n/**\n * Generic data table with client-side sorting and pagination.\n *\n * Pass `columns` describing each field and `data` as the row array. The\n * component manages its own sort and page state internally.\n */\nexport function DataTable<T extends Record<string, unknown>>({\n columns,\n data,\n pageSize = 10,\n className,\n}: DataTableProps<T>) {\n const [sortKey, setSortKey] = useState<string | null>(null);\n const [sortDir, setSortDir] = useState<SortDir>(\"asc\");\n const [page, setPage] = useState(0);\n\n const sorted = useMemo(() => {\n if (!sortKey) return data;\n const copy = [...data];\n copy.sort((a, b) => {\n const av = a[sortKey];\n const bv = b[sortKey];\n if (av == null && bv == null) return 0;\n if (av == null) return 1;\n if (bv == null) return -1;\n if (typeof av === \"number\" && typeof bv === \"number\") {\n return sortDir === \"asc\" ? av - bv : bv - av;\n }\n const as = String(av);\n const bs = String(bv);\n return sortDir === \"asc\" ? as.localeCompare(bs) : bs.localeCompare(as);\n });\n return copy;\n }, [data, sortKey, sortDir]);\n\n const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize));\n const safePage = Math.min(page, pageCount - 1);\n const pageData = sorted.slice(safePage * pageSize, (safePage + 1) * pageSize);\n\n function toggleSort(key: string) {\n if (sortKey === key) {\n setSortDir((d) => (d === \"asc\" ? \"desc\" : \"asc\"));\n } else {\n setSortKey(key);\n setSortDir(\"asc\");\n }\n setPage(0);\n }\n\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n <div className=\"rounded-md border\">\n <Table>\n <TableHeader>\n <TableRow>\n {columns.map((col) => (\n <TableHead key={col.accessorKey}>\n {col.enableSorting === false ? (\n col.header\n ) : (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"-ml-3 h-8 px-2\"\n onClick={() => toggleSort(col.accessorKey)}\n >\n {col.header}\n <ArrowUpDown className=\"ml-2 size-3 opacity-50\" />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>\n {pageData.length === 0 ? (\n <TableRow>\n <TableCell colSpan={columns.length} className=\"h-24 text-center text-muted-foreground\">\n No results.\n </TableCell>\n </TableRow>\n ) : (\n pageData.map((row, i) => (\n <TableRow key={i}>\n {columns.map((col) => (\n <TableCell key={col.accessorKey}>\n {col.cell ? col.cell(row[col.accessorKey], row) : String(row[col.accessorKey] ?? \"\")}\n </TableCell>\n ))}\n </TableRow>\n ))\n )}\n </TableBody>\n </Table>\n </div>\n\n {pageCount > 1 && (\n <div className=\"flex items-center justify-between text-sm text-muted-foreground\">\n <span>\n {safePage * pageSize + 1}–{Math.min((safePage + 1) * pageSize, sorted.length)} of {sorted.length}\n </span>\n <div className=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={safePage === 0}\n onClick={() => setPage((p) => Math.max(0, p - 1))}\n >\n <ChevronLeft className=\"size-4\" />\n </Button>\n <span className=\"px-2\">\n {safePage + 1} / {pageCount}\n </span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={safePage >= pageCount - 1}\n onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}\n >\n <ChevronRight className=\"size-4\" />\n </Button>\n </div>\n </div>\n )}\n </div>\n );\n}\n",
10
+ "content": "\"use client\";\n\nimport { useState, useMemo, type ReactNode } from \"react\";\nimport { ArrowUpDown, ChevronLeft, ChevronRight } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from \"@/components/ui/table\";\nimport { cn } from \"@/lib/utils\";\n\n/** Column definition for the data table. */\nexport interface Column<T> {\n /** Key used to access the row value; also used as the sort key. */\n accessorKey: keyof T & string;\n /** Column header label. */\n header: string;\n /** Optional custom cell renderer. Receives the row's value for this column. */\n cell?: (value: T[keyof T], row: T) => ReactNode;\n /** Disable sorting for this column. */\n enableSorting?: boolean;\n}\n\ninterface DataTableProps<T> {\n columns: Column<T>[];\n data: T[];\n /** Number of rows per page. Defaults to 10. */\n pageSize?: number;\n className?: string;\n /** Host-supplied copy; English defaults keep the component usable as-is. */\n labels?: Partial<DataTableLabels>;\n}\n\n/** Every string the table renders or announces. */\nexport interface DataTableLabels {\n /** Shown when the current page has no rows. */\n empty: string;\n /** Accessible name of the previous-page button. */\n previousPage: string;\n /** Accessible name of the next-page button. */\n nextPage: string;\n /** Page summary; `from` and `to` are 1-based and inclusive. */\n range: (from: number, to: number, total: number) => string;\n}\n\nconst DEFAULT_LABELS: DataTableLabels = {\n empty: \"No results.\",\n previousPage: \"Previous page\",\n nextPage: \"Next page\",\n range: (from, to, total) => `${from}–${to} of ${total}`,\n};\n\ntype SortDir = \"asc\" | \"desc\";\n\n/**\n * Generic data table with client-side sorting and pagination.\n *\n * Pass `columns` describing each field and `data` as the row array. The\n * component manages its own sort and page state internally.\n */\nexport function DataTable<T extends Record<string, unknown>>({\n columns,\n data,\n pageSize = 10,\n className,\n labels,\n}: DataTableProps<T>) {\n const copy = { ...DEFAULT_LABELS, ...labels };\n const [sortKey, setSortKey] = useState<string | null>(null);\n const [sortDir, setSortDir] = useState<SortDir>(\"asc\");\n const [page, setPage] = useState(0);\n\n const sorted = useMemo(() => {\n if (!sortKey) return data;\n const copy = [...data];\n copy.sort((a, b) => {\n const av = a[sortKey];\n const bv = b[sortKey];\n if (av == null && bv == null) return 0;\n if (av == null) return 1;\n if (bv == null) return -1;\n if (typeof av === \"number\" && typeof bv === \"number\") {\n return sortDir === \"asc\" ? av - bv : bv - av;\n }\n const as = String(av);\n const bs = String(bv);\n return sortDir === \"asc\" ? as.localeCompare(bs) : bs.localeCompare(as);\n });\n return copy;\n }, [data, sortKey, sortDir]);\n\n const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize));\n const safePage = Math.min(page, pageCount - 1);\n const pageData = sorted.slice(safePage * pageSize, (safePage + 1) * pageSize);\n\n function toggleSort(key: string) {\n if (sortKey === key) {\n setSortDir((d) => (d === \"asc\" ? \"desc\" : \"asc\"));\n } else {\n setSortKey(key);\n setSortDir(\"asc\");\n }\n setPage(0);\n }\n\n return (\n <div className={cn(\"flex flex-col gap-3\", className)}>\n <div className=\"rounded-md border\">\n <Table>\n <TableHeader>\n <TableRow>\n {columns.map((col) => (\n <TableHead key={col.accessorKey}>\n {col.enableSorting === false ? (\n col.header\n ) : (\n <Button\n variant=\"ghost\"\n size=\"sm\"\n className=\"-ml-3 h-8 px-2\"\n onClick={() => toggleSort(col.accessorKey)}\n >\n {col.header}\n <ArrowUpDown className=\"ml-2 size-3 opacity-50\" />\n </Button>\n )}\n </TableHead>\n ))}\n </TableRow>\n </TableHeader>\n <TableBody>\n {pageData.length === 0 ? (\n <TableRow>\n <TableCell colSpan={columns.length} className=\"h-24 text-center text-muted-foreground\">\n {copy.empty}\n </TableCell>\n </TableRow>\n ) : (\n pageData.map((row, i) => (\n <TableRow key={i}>\n {columns.map((col) => (\n <TableCell key={col.accessorKey}>\n {col.cell ? col.cell(row[col.accessorKey], row) : String(row[col.accessorKey] ?? \"\")}\n </TableCell>\n ))}\n </TableRow>\n ))\n )}\n </TableBody>\n </Table>\n </div>\n\n {pageCount > 1 && (\n <div className=\"flex items-center justify-between text-sm text-muted-foreground\">\n <span>\n {copy.range(safePage * pageSize + 1, Math.min((safePage + 1) * pageSize, sorted.length), sorted.length)}\n </span>\n <div className=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n aria-label={copy.previousPage}\n disabled={safePage === 0}\n onClick={() => setPage((p) => Math.max(0, p - 1))}\n >\n <ChevronLeft className=\"size-4\" />\n </Button>\n <span className=\"px-2\">\n {safePage + 1} / {pageCount}\n </span>\n <Button\n variant=\"outline\"\n size=\"sm\"\n aria-label={copy.nextPage}\n disabled={safePage >= pageCount - 1}\n onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}\n >\n <ChevronRight className=\"size-4\" />\n </Button>\n </div>\n </div>\n )}\n </div>\n );\n}\n",
11
11
  "type": "registry:component"
12
12
  }
13
13
  ]
@@ -4,6 +4,9 @@
4
4
  "type": "registry:block",
5
5
  "title": "Forgot password page",
6
6
  "description": "Page-level password reset block: email and verification code plus a new password with a live strength checklist. Transport and navigation come from the host through props.",
7
+ "registryDependencies": [
8
+ "password-checklist"
9
+ ],
7
10
  "postInstall": "Render <ForgotPasswordPage labels={...} port={...} /> inside your auth shell. The host supplies translated labels, a sendResetCode/resetPassword port, an optional initialEmail and navigates from onReset/onBack. Requires the shadcn ui primitives button, card, input and label.",
8
11
  "x-fewbie.contract": {
9
12
  "version": "1.0.0",
@@ -67,7 +70,7 @@
67
70
  },
68
71
  {
69
72
  "path": "src/modules/forgot-password/forgot-password.tsx",
70
- "content": "\"use client\";\n\nimport { useEffect, useState, type FormEvent } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { ForgotPasswordLabels, ForgotPasswordProps } from \"./types\";\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst CODE_LENGTH = 6;\nconst DEFAULT_RESEND_SECONDS = 60;\nconst PASSWORD_PATTERN = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\w\\s]).{8,}$/;\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction ClearIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n );\n}\n\nfunction EyeIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </svg>\n );\n}\n\nfunction EyeOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 3l18 18\" />\n <path d=\"M10.6 10.6a3 3 0 0 0 4.2 4.2\" />\n <path d=\"M9.9 5.2A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-3.2 4.1\" />\n <path d=\"M6.2 6.2A17.4 17.4 0 0 0 2 12s3.5 7 10 7a10.6 10.6 0 0 0 4.2-.9\" />\n </svg>\n );\n}\n\nfunction CheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-3.5 w-3.5\"\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n );\n}\n\nfunction PasswordChecklist({ password, labels }: { password: string; labels: ForgotPasswordLabels }) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n const rules = [\n { key: \"length\", label: labels.passwordRuleLength, met: password.length >= 8 },\n { key: \"lowercase\", label: labels.passwordRuleLowercase, met: /[a-z]/.test(password) },\n { key: \"uppercase\", label: labels.passwordRuleUppercase, met: /[A-Z]/.test(password) },\n { key: \"number\", label: labels.passwordRuleNumber, met: /\\d/.test(password) },\n { key: \"symbol\", label: labels.passwordRuleSymbol, met: /[^\\w\\s]/.test(password) },\n ];\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label={labels.passwordRequirements}>\n {rules.map((rule) => (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${\n rule.met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"\n }`}\n >\n {rule.met ? <CheckIcon /> : <ClearIcon />}\n {rule.label}\n </li>\n ))}\n </ul>\n );\n}\n\n/**\n * Page-level password reset module: email plus verification code plus a new\n * password, with a live strength checklist. Transport, navigation and toasts\n * belong to the host and enter through `port` and the `on*` callbacks.\n */\nexport function ForgotPasswordPage({\n labels,\n port,\n initialEmail = \"\",\n notices,\n onCodeSent,\n onReset,\n onBack,\n}: ForgotPasswordProps) {\n const [email, setEmail] = useState(initialEmail);\n const [code, setCode] = useState(\"\");\n const [newPassword, setNewPassword] = useState(\"\");\n const [showPassword, setShowPassword] = useState(false);\n // Seconds left before the user can request another verification code.\n const [secondsLeft, setSecondsLeft] = useState(0);\n const [sendPending, setSendPending] = useState(false);\n const [resetPending, setResetPending] = useState(false);\n const [errors, setErrors] = useState<{ email?: string; code?: string; newPassword?: string }>({});\n const [error, setError] = useState<string | null>(null);\n\n const isCountingDown = secondsLeft > 0;\n\n // Countdown timer for resending the verification code.\n useEffect(() => {\n if (!isCountingDown) return;\n const timer = setInterval(() => setSecondsLeft((prev) => Math.max(0, prev - 1)), 1000);\n return () => clearInterval(timer);\n }, [isCountingDown]);\n\n function validateEmail(value: string): string | undefined {\n if (!value.trim()) return labels.emailRequired;\n if (!EMAIL_PATTERN.test(value)) return labels.invalidEmail;\n return undefined;\n }\n\n async function handleGetCode(): Promise<void> {\n if (secondsLeft > 0 || sendPending) return;\n const emailError = validateEmail(email);\n setErrors((prev) => ({ ...prev, email: emailError }));\n if (emailError) return;\n\n setSendPending(true);\n setError(null);\n try {\n const result = await port.sendResetCode(email);\n // Follow the resend cooldown returned by the backend.\n setSecondsLeft(result.secondsOfCountdown ?? DEFAULT_RESEND_SECONDS);\n onCodeSent?.();\n } catch {\n setError(labels.requestFailed);\n } finally {\n setSendPending(false);\n }\n }\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {\n event.preventDefault();\n if (resetPending) return;\n\n const nextErrors = {\n email: validateEmail(email),\n code: !code ? labels.codeRequired : code.length !== CODE_LENGTH ? labels.codeDigits : undefined,\n newPassword: !newPassword\n ? labels.passwordRequired\n : PASSWORD_PATTERN.test(newPassword)\n ? undefined\n : labels.passwordRule,\n };\n setErrors(nextErrors);\n if (nextErrors.email || nextErrors.code || nextErrors.newPassword) return;\n\n setResetPending(true);\n setError(null);\n try {\n await port.resetPassword({ email, verificationCode: code, newPassword });\n onReset?.();\n } catch {\n setError(labels.resetFailed);\n } finally {\n setResetPending(false);\n }\n }\n\n return (\n <Card className=\"w-full shadow-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">{labels.title}</CardTitle>\n <CardDescription>{labels.description}</CardDescription>\n </CardHeader>\n <CardContent>\n {notices}\n\n {/* method=\"post\" keeps a native submit (before hydration) from\n serializing the new password into the query string. */}\n <form method=\"post\" onSubmit={(event) => void handleSubmit(event)} noValidate className=\"space-y-5\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-email\">{labels.emailLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-email\"\n autoComplete=\"email\"\n value={email}\n onChange={(event) => setEmail(event.target.value)}\n className=\"pr-10\"\n />\n {email && (\n <button\n type=\"button\"\n onClick={() => setEmail(\"\")}\n className=\"absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearEmail}\n >\n <ClearIcon />\n </button>\n )}\n </div>\n {errors.email && <p className=\"text-sm text-destructive\">{errors.email}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-code\">{labels.codeLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={code}\n onChange={(event) => setCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n className=\"pr-32\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-2\">\n {code && (\n <button\n type=\"button\"\n onClick={() => setCode(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearCode}\n >\n <ClearIcon />\n </button>\n )}\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0 text-xs font-normal\"\n onClick={() => void handleGetCode()}\n disabled={secondsLeft > 0 || sendPending}\n >\n {sendPending ? <Spinner /> : secondsLeft > 0 ? `${secondsLeft}s` : labels.getCode}\n </Button>\n </div>\n </div>\n {errors.code && <p className=\"text-sm text-destructive\">{errors.code}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-new-password\">{labels.newPasswordLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-new-password\"\n type={showPassword ? \"text\" : \"password\"}\n autoComplete=\"new-password\"\n value={newPassword}\n onChange={(event) => setNewPassword(event.target.value)}\n className=\"pr-20\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-1\">\n {newPassword && (\n <button\n type=\"button\"\n onClick={() => setNewPassword(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearPassword}\n >\n <ClearIcon />\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => setShowPassword((prev) => !prev)}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={showPassword ? labels.hidePassword : labels.showPassword}\n >\n {showPassword ? <EyeOffIcon /> : <EyeIcon />}\n </button>\n </div>\n </div>\n <PasswordChecklist password={newPassword} labels={labels} />\n {errors.newPassword && <p className=\"text-sm text-destructive\">{errors.newPassword}</p>}\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n {onBack && (\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0 text-xs font-normal\"\n onClick={onBack}\n >\n {labels.back}\n </Button>\n </div>\n )}\n\n <Button type=\"submit\" className=\"w-full\" disabled={resetPending}>\n {resetPending ? <Spinner /> : labels.resetButton}\n </Button>\n </form>\n </CardContent>\n </Card>\n );\n}\n",
73
+ "content": "\"use client\";\n\nimport { useEffect, useState, type FormEvent } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { checkPasswordPolicy, isStrongPassword } from \"@/modules/password-checklist\";\nimport type { ForgotPasswordLabels, ForgotPasswordProps } from \"./types\";\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst CODE_LENGTH = 6;\nconst DEFAULT_RESEND_SECONDS = 60;\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction ClearIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </svg>\n );\n}\n\nfunction EyeIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n </svg>\n );\n}\n\nfunction EyeOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 3l18 18\" />\n <path d=\"M10.6 10.6a3 3 0 0 0 4.2 4.2\" />\n <path d=\"M9.9 5.2A10.9 10.9 0 0 1 12 5c6.5 0 10 7 10 7a17.6 17.6 0 0 1-3.2 4.1\" />\n <path d=\"M6.2 6.2A17.4 17.4 0 0 0 2 12s3.5 7 10 7a10.6 10.6 0 0 0 4.2-.9\" />\n </svg>\n );\n}\n\nfunction CheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-3.5 w-3.5\"\n >\n <path d=\"M20 6 9 17l-5-5\" />\n </svg>\n );\n}\n\nfunction PasswordChecklist({ password, labels }: { password: string; labels: ForgotPasswordLabels }) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n const checks = checkPasswordPolicy(password);\n const rules = [\n { key: \"length\", label: labels.passwordRuleLength, met: checks.length },\n { key: \"lowercase\", label: labels.passwordRuleLowercase, met: checks.lowercase },\n { key: \"uppercase\", label: labels.passwordRuleUppercase, met: checks.uppercase },\n { key: \"number\", label: labels.passwordRuleNumber, met: checks.number },\n { key: \"symbol\", label: labels.passwordRuleSymbol, met: checks.symbol },\n ];\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label={labels.passwordRequirements}>\n {rules.map((rule) => (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${\n rule.met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"\n }`}\n >\n {rule.met ? <CheckIcon /> : <ClearIcon />}\n {rule.label}\n </li>\n ))}\n </ul>\n );\n}\n\n/**\n * Page-level password reset module: email plus verification code plus a new\n * password, with a live strength checklist. Transport, navigation and toasts\n * belong to the host and enter through `port` and the `on*` callbacks.\n */\nexport function ForgotPasswordPage({\n labels,\n port,\n initialEmail = \"\",\n notices,\n onCodeSent,\n onReset,\n onBack,\n}: ForgotPasswordProps) {\n const [email, setEmail] = useState(initialEmail);\n const [code, setCode] = useState(\"\");\n const [newPassword, setNewPassword] = useState(\"\");\n const [showPassword, setShowPassword] = useState(false);\n // Seconds left before the user can request another verification code.\n const [secondsLeft, setSecondsLeft] = useState(0);\n const [sendPending, setSendPending] = useState(false);\n const [resetPending, setResetPending] = useState(false);\n const [errors, setErrors] = useState<{ email?: string; code?: string; newPassword?: string }>({});\n const [error, setError] = useState<string | null>(null);\n\n const isCountingDown = secondsLeft > 0;\n\n // Countdown timer for resending the verification code.\n useEffect(() => {\n if (!isCountingDown) return;\n const timer = setInterval(() => setSecondsLeft((prev) => Math.max(0, prev - 1)), 1000);\n return () => clearInterval(timer);\n }, [isCountingDown]);\n\n function validateEmail(value: string): string | undefined {\n if (!value.trim()) return labels.emailRequired;\n if (!EMAIL_PATTERN.test(value)) return labels.invalidEmail;\n return undefined;\n }\n\n async function handleGetCode(): Promise<void> {\n if (secondsLeft > 0 || sendPending) return;\n const emailError = validateEmail(email);\n setErrors((prev) => ({ ...prev, email: emailError }));\n if (emailError) return;\n\n setSendPending(true);\n setError(null);\n try {\n const result = await port.sendResetCode(email);\n // Follow the resend cooldown returned by the backend.\n setSecondsLeft(result.secondsOfCountdown ?? DEFAULT_RESEND_SECONDS);\n onCodeSent?.();\n } catch {\n setError(labels.requestFailed);\n } finally {\n setSendPending(false);\n }\n }\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>): Promise<void> {\n event.preventDefault();\n if (resetPending) return;\n\n const nextErrors = {\n email: validateEmail(email),\n code: !code ? labels.codeRequired : code.length !== CODE_LENGTH ? labels.codeDigits : undefined,\n newPassword: !newPassword\n ? labels.passwordRequired\n : isStrongPassword(newPassword)\n ? undefined\n : labels.passwordRule,\n };\n setErrors(nextErrors);\n if (nextErrors.email || nextErrors.code || nextErrors.newPassword) return;\n\n setResetPending(true);\n setError(null);\n try {\n await port.resetPassword({ email, verificationCode: code, newPassword });\n onReset?.();\n } catch {\n setError(labels.resetFailed);\n } finally {\n setResetPending(false);\n }\n }\n\n return (\n <Card className=\"w-full shadow-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">{labels.title}</CardTitle>\n <CardDescription>{labels.description}</CardDescription>\n </CardHeader>\n <CardContent>\n {notices}\n\n {/* method=\"post\" keeps a native submit (before hydration) from\n serializing the new password into the query string. */}\n <form method=\"post\" onSubmit={(event) => void handleSubmit(event)} noValidate className=\"space-y-5\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-email\">{labels.emailLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-email\"\n autoComplete=\"email\"\n value={email}\n onChange={(event) => setEmail(event.target.value)}\n className=\"pr-10\"\n />\n {email && (\n <button\n type=\"button\"\n onClick={() => setEmail(\"\")}\n className=\"absolute top-1/2 right-2 -translate-y-1/2 text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearEmail}\n >\n <ClearIcon />\n </button>\n )}\n </div>\n {errors.email && <p className=\"text-sm text-destructive\">{errors.email}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-code\">{labels.codeLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={code}\n onChange={(event) => setCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n className=\"pr-32\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-2\">\n {code && (\n <button\n type=\"button\"\n onClick={() => setCode(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearCode}\n >\n <ClearIcon />\n </button>\n )}\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0 text-xs font-normal\"\n onClick={() => void handleGetCode()}\n disabled={secondsLeft > 0 || sendPending}\n >\n {sendPending ? <Spinner /> : secondsLeft > 0 ? `${secondsLeft}s` : labels.getCode}\n </Button>\n </div>\n </div>\n {errors.code && <p className=\"text-sm text-destructive\">{errors.code}</p>}\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"forgot-password-new-password\">{labels.newPasswordLabel}</Label>\n <div className=\"relative\">\n <Input\n id=\"forgot-password-new-password\"\n type={showPassword ? \"text\" : \"password\"}\n autoComplete=\"new-password\"\n value={newPassword}\n onChange={(event) => setNewPassword(event.target.value)}\n className=\"pr-20\"\n />\n <div className=\"absolute top-1/2 right-2 flex -translate-y-1/2 items-center gap-1\">\n {newPassword && (\n <button\n type=\"button\"\n onClick={() => setNewPassword(\"\")}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={labels.clearPassword}\n >\n <ClearIcon />\n </button>\n )}\n <button\n type=\"button\"\n onClick={() => setShowPassword((prev) => !prev)}\n className=\"text-muted-foreground hover:text-foreground\"\n aria-label={showPassword ? labels.hidePassword : labels.showPassword}\n >\n {showPassword ? <EyeOffIcon /> : <EyeIcon />}\n </button>\n </div>\n </div>\n <PasswordChecklist password={newPassword} labels={labels} />\n {errors.newPassword && <p className=\"text-sm text-destructive\">{errors.newPassword}</p>}\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n {onBack && (\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n variant=\"link\"\n size=\"sm\"\n className=\"h-auto p-0 text-xs font-normal\"\n onClick={onBack}\n >\n {labels.back}\n </Button>\n </div>\n )}\n\n <Button type=\"submit\" className=\"w-full\" disabled={resetPending}>\n {resetPending ? <Spinner /> : labels.resetButton}\n </Button>\n </form>\n </CardContent>\n </Card>\n );\n}\n",
71
74
  "type": "registry:block"
72
75
  }
73
76
  ]
@@ -11,7 +11,7 @@
11
11
  "files": [
12
12
  {
13
13
  "path": "src/components/frontend-monitor.tsx",
14
- "content": "\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Browser-side monitoring bootstrap.\n *\n * Dynamically imports @devbie/frontend-monitor-sdk on mount and initializes it\n * with NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT (report endpoint) and\n * NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN (report token — the collector resolves it to\n * the application partition). Renders nothing; it is a no-op until both env\n * vars are set. Heartbeat wiring is intentionally NOT handled here — it lives\n * in the template's instrumentation.ts (Node process only).\n *\n * The dynamic import keeps the SDK out of SSR/Edge evaluation entirely:\n * the monitor bundle is only loaded in the browser when the component mounts.\n */\nexport function FrontendMonitor() {\n useEffect(() => {\n const api = process.env.NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT;\n const token = process.env.NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN;\n\n // Required configuration missing — stay silent in production, warn in dev.\n if (!api || !token) {\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n \"[FrontendMonitor] NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT / NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN not set; monitoring disabled.\",\n );\n }\n return;\n }\n\n let disposed = false;\n\n void import(\"@devbie/frontend-monitor-sdk\").then(({ default: init }) => {\n // StrictMode mounts effects twice in dev; guard against double init.\n if (disposed) return;\n init({\n api,\n token,\n isPage: true,\n isAjax: true,\n isResource: true,\n isError: true,\n });\n });\n\n return () => {\n disposed = true;\n };\n }, []);\n\n return null;\n}\n",
14
+ "content": "\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Browser-side monitoring bootstrap.\n *\n * Dynamically imports @devbie/frontend-monitor-sdk on mount and initializes it\n * with NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT (report endpoint) and\n * NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN (report token — the collector resolves it to\n * the application partition). Renders nothing; it is a no-op until both env\n * vars are set. Heartbeat wiring is intentionally NOT handled here — it lives\n * in the template's instrumentation.ts (Node process only).\n *\n * The dynamic import keeps the SDK out of SSR/Edge evaluation entirely:\n * the monitor bundle is only loaded in the browser when the component mounts.\n */\nexport function FrontendMonitor() {\n useEffect(() => {\n const api = process.env.NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT;\n const token = process.env.NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN;\n\n // Required configuration missing — stay silent in production, warn in dev.\n if (!api || !token) {\n if (process.env.NODE_ENV === \"development\") {\n console.warn(\n \"[FrontendMonitor] NEXT_PUBLIC_FRONTEND_MONITOR_ENDPOINT / NEXT_PUBLIC_FRONTEND_MONITOR_TOKEN not set; monitoring disabled.\",\n );\n }\n return;\n }\n\n let disposed = false;\n\n void import(\"@devbie/frontend-monitor-sdk\")\n .then(({ default: init }) => {\n // StrictMode mounts effects twice in dev; guard against double init.\n if (disposed) return;\n init({\n api,\n token,\n isPage: true,\n isAjax: true,\n isResource: true,\n isError: true,\n });\n })\n .catch((error: unknown) => {\n // A failed chunk load is not fatal for the app, but monitoring is now\n // off; surface it instead of leaving an unhandled rejection (R84-13).\n console.error(\"[FrontendMonitor] failed to load the monitor SDK.\", error);\n });\n\n return () => {\n disposed = true;\n };\n }, []);\n\n return null;\n}\n",
15
15
  "type": "registry:component"
16
16
  }
17
17
  ]
@@ -44,12 +44,12 @@
44
44
  },
45
45
  {
46
46
  "path": "src/modules/login-form/types.ts",
47
- "content": "/**\n * Every string the form renders. The host supplies translated copy; the module\n * owns no user-facing text of its own.\n */\nexport interface LoginFormLabels {\n title: string;\n description: string;\n account: string;\n accountPlaceholder: string;\n password: string;\n submit: string;\n loginFailed: string;\n}\n\nexport interface LoginFormProps {\n labels: LoginFormLabels;\n /** App path to open after a successful sign-in; the host usually reads `?redirect=`. */\n redirectPath?: string;\n /** Called after sign-in succeeds; the host performs the navigation. */\n onLoggedIn: (path: string) => void;\n}\n",
47
+ "content": "/**\n * Every string the form renders. The host supplies translated copy; the module\n * owns no user-facing text of its own.\n */\nexport interface LoginFormLabels {\n title: string;\n description: string;\n account: string;\n accountPlaceholder: string;\n password: string;\n submit: string;\n loginFailed: string;\n}\n\nexport interface LoginFormProps {\n labels: LoginFormLabels;\n /** App path to open after a successful sign-in; the host usually reads `?redirect=`. */\n redirectPath?: string;\n /** Called after sign-in succeeds; the host performs the navigation. */\n onLoggedIn: (path: string) => void;\n /**\n * Maps a sign-in failure to user-facing copy. Defaults to\n * `labels.loginFailed` so a host error message never leaks into the form.\n */\n formatError?: (error: unknown) => string;\n}\n",
48
48
  "type": "registry:block"
49
49
  },
50
50
  {
51
51
  "path": "src/modules/login-form/login-form.tsx",
52
- "content": "\"use client\";\n\nimport { useState, type FormEvent } from \"react\";\nimport { Loader2 } from \"lucide-react\";\n\nimport { login } from \"@/lib/auth\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\n\nimport type { LoginFormProps } from \"./types\";\n\nexport function LoginForm({ labels, redirectPath = \"/\", onLoggedIn }: LoginFormProps) {\n const [account, setAccount] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setError(null);\n setSubmitting(true);\n try {\n await login({ account, password });\n onLoggedIn(redirectPath);\n } catch (err) {\n setError(err instanceof Error ? err.message : labels.loginFailed);\n } finally {\n setSubmitting(false);\n }\n }\n\n return (\n <div className=\"flex min-h-svh items-center justify-center p-4\">\n <Card className=\"w-full max-w-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">{labels.title}</CardTitle>\n <CardDescription>{labels.description}</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSubmit} className=\"flex flex-col gap-4\" noValidate>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"account\">{labels.account}</Label>\n <Input\n id=\"account\"\n name=\"account\"\n autoComplete=\"username\"\n placeholder={labels.accountPlaceholder}\n value={account}\n onChange={(event) => setAccount(event.target.value)}\n required\n />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"password\">{labels.password}</Label>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={password}\n onChange={(event) => setPassword(event.target.value)}\n required\n />\n </div>\n\n {error ? <p className=\"text-sm text-destructive\">{error}</p> : null}\n\n <Button type=\"submit\" disabled={submitting} className=\"w-full\">\n {submitting ? <Loader2 className=\"size-4 animate-spin\" /> : labels.submit}\n </Button>\n </form>\n </CardContent>\n </Card>\n </div>\n );\n}\n",
52
+ "content": "\"use client\";\n\nimport { useState, type FormEvent } from \"react\";\nimport { Loader2 } from \"lucide-react\";\n\nimport { login } from \"@/lib/auth\";\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\n\nimport type { LoginFormProps } from \"./types\";\n\nexport function LoginForm({ labels, redirectPath = \"/\", onLoggedIn, formatError }: LoginFormProps) {\n const [account, setAccount] = useState(\"\");\n const [password, setPassword] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n async function handleSubmit(event: FormEvent<HTMLFormElement>) {\n event.preventDefault();\n setError(null);\n setSubmitting(true);\n try {\n await login({ account, password });\n onLoggedIn(redirectPath);\n } catch (err) {\n setError(formatError ? formatError(err) : labels.loginFailed);\n } finally {\n setSubmitting(false);\n }\n }\n\n return (\n <div className=\"flex min-h-svh items-center justify-center p-4\">\n <Card className=\"w-full max-w-sm\">\n <CardHeader>\n <CardTitle className=\"text-xl\">{labels.title}</CardTitle>\n <CardDescription>{labels.description}</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSubmit} className=\"flex flex-col gap-4\" noValidate>\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"account\">{labels.account}</Label>\n <Input\n id=\"account\"\n name=\"account\"\n autoComplete=\"username\"\n placeholder={labels.accountPlaceholder}\n value={account}\n onChange={(event) => setAccount(event.target.value)}\n required\n />\n </div>\n\n <div className=\"flex flex-col gap-2\">\n <Label htmlFor=\"password\">{labels.password}</Label>\n <Input\n id=\"password\"\n name=\"password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={password}\n onChange={(event) => setPassword(event.target.value)}\n required\n />\n </div>\n\n {error ? <p className=\"text-sm text-destructive\">{error}</p> : null}\n\n <Button type=\"submit\" disabled={submitting} className=\"w-full\">\n {submitting ? <Loader2 className=\"size-4 animate-spin\" /> : labels.submit}\n </Button>\n </form>\n </CardContent>\n </Card>\n </div>\n );\n}\n",
53
53
  "type": "registry:block"
54
54
  }
55
55
  ]
@@ -26,7 +26,7 @@
26
26
  "files": [
27
27
  {
28
28
  "path": "src/modules/password-checklist/index.ts",
29
- "content": "export { PasswordChecklist, isStrongPassword } from \"./password-checklist\";\nexport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n",
29
+ "content": "export { PasswordChecklist, checkPasswordPolicy, isStrongPassword } from \"./password-checklist\";\nexport type { PasswordPolicyChecks, PasswordRuleKey } from \"./password-checklist\";\nexport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n",
30
30
  "type": "registry:block"
31
31
  },
32
32
  {
@@ -36,7 +36,7 @@
36
36
  },
37
37
  {
38
38
  "path": "src/modules/password-checklist/password-checklist.tsx",
39
- "content": "\"use client\";\n\nimport { Check, X } from \"lucide-react\";\n\nimport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n\n/**\n * Live password rule checklist. Rules mirror the backend IsStrongPassword\n * validator (validator.isStrongPassword defaults), so what the user sees is\n * exactly what the API enforces.\n *\n * NOTE: this is a manual mirror of the newbie account module's password\n * policy. When the backend strategy changes, update the rules array here.\n */\nconst rules: ReadonlyArray<{\n key: string;\n labelKey: keyof PasswordChecklistLabels;\n test: (password: string) => boolean;\n}> = [\n { key: \"length\", labelKey: \"ruleLength\", test: (password) => password.length >= 8 },\n { key: \"lowercase\", labelKey: \"ruleLowercase\", test: (password) => /[a-z]/.test(password) },\n { key: \"uppercase\", labelKey: \"ruleUppercase\", test: (password) => /[A-Z]/.test(password) },\n { key: \"number\", labelKey: \"ruleNumber\", test: (password) => /\\d/.test(password) },\n { key: \"symbol\", labelKey: \"ruleSymbol\", test: (password) => /[^\\w\\s]/.test(password) },\n];\n\nexport function isStrongPassword(password: string): boolean {\n return rules.every((rule) => rule.test(password));\n}\n\nexport function PasswordChecklist({ labels, password }: PasswordChecklistProps) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label={labels.requirements}>\n {rules.map((rule) => {\n const met = rule.test(password);\n return (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"}`}\n >\n {met ? <Check className=\"h-3.5 w-3.5\" /> : <X className=\"h-3.5 w-3.5\" />}\n {labels[rule.labelKey]}\n </li>\n );\n })}\n </ul>\n );\n}\n",
39
+ "content": "\"use client\";\n\nimport { Check, X } from \"lucide-react\";\n\nimport type { PasswordChecklistLabels, PasswordChecklistProps } from \"./types\";\n\n/** Rule keys in display order; each is also a field of `PasswordPolicyChecks`. */\nexport type PasswordRuleKey = \"length\" | \"lowercase\" | \"uppercase\" | \"number\" | \"symbol\";\n\nexport type PasswordPolicyChecks = Record<PasswordRuleKey, boolean>;\n\n/**\n * validator.isStrongPassword's symbol set, copied verbatim from\n * `validator/lib/isStrongPassword.js`. It includes `_`, space and `£`, and\n * excludes non-ASCII symbols such as `€` and `§` (R84-01).\n */\nconst SYMBOL_PATTERN = /^[-#!$@£%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\/\\\\ ]$/;\n\n/**\n * The backend password policy, mirrored exactly (R84-01): the newbie account\n * module calls `validator.isStrongPassword` with its default options — at\n * least 8 UTF-16 code units, one lowercase, one uppercase, one digit and one\n * symbol from the set above. Keep this in sync with\n * `newbie-modules/packages/modules/account/helpers/validator.ts`.\n */\nexport function checkPasswordPolicy(password: string): PasswordPolicyChecks {\n return {\n length: password.length >= 8,\n lowercase: /[a-z]/.test(password),\n uppercase: /[A-Z]/.test(password),\n number: /[0-9]/.test(password),\n // validator classifies characters one code point at a time, so emoji and\n // other surrogate pairs never count as a symbol.\n symbol: Array.from(password).some((char) => SYMBOL_PATTERN.test(char)),\n };\n}\n\nexport function isStrongPassword(password: string): boolean {\n const checks = checkPasswordPolicy(password);\n return checks.length && checks.lowercase && checks.uppercase && checks.number && checks.symbol;\n}\n\nconst RULES: ReadonlyArray<{ key: PasswordRuleKey; labelKey: keyof PasswordChecklistLabels }> = [\n { key: \"length\", labelKey: \"ruleLength\" },\n { key: \"lowercase\", labelKey: \"ruleLowercase\" },\n { key: \"uppercase\", labelKey: \"ruleUppercase\" },\n { key: \"number\", labelKey: \"ruleNumber\" },\n { key: \"symbol\", labelKey: \"ruleSymbol\" },\n];\n\nexport function PasswordChecklist({ labels, password }: PasswordChecklistProps) {\n // Show nothing until the user starts typing, to keep the form calm.\n if (!password) return null;\n\n const checks = checkPasswordPolicy(password);\n\n return (\n <ul className=\"space-y-1.5 rounded-md border bg-muted/40 p-3\" aria-label={labels.requirements}>\n {RULES.map((rule) => {\n const met = checks[rule.key];\n return (\n <li\n key={rule.key}\n className={`flex items-center gap-2 text-xs ${met ? \"text-green-600 dark:text-green-500\" : \"text-muted-foreground\"}`}\n >\n {met ? <Check className=\"h-3.5 w-3.5\" /> : <X className=\"h-3.5 w-3.5\" />}\n {labels[rule.labelKey]}\n </li>\n );\n })}\n </ul>\n );\n}\n",
40
40
  "type": "registry:block"
41
41
  }
42
42
  ]
@@ -55,7 +55,7 @@
55
55
  },
56
56
  {
57
57
  "path": "src/modules/preferences-settings/preferences-settings.tsx",
58
- "content": "\"use client\";\n\nimport { useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport type { PreferencesSettingsProps, ThemePreferenceValue } from \"./types\";\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction SunIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />\n </svg>\n );\n}\n\nfunction MoonIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z\" />\n </svg>\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction SaveIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z\" />\n <path d=\"M17 21v-8H7v8M7 3v5h8\" />\n </svg>\n );\n}\n\n/**\n * Account display preferences: interface language, theme and timezone. The\n * host owns transport and the side effects of each change (locale cookie,\n * theme class, caching), which enter through `port` and the `on*` callbacks.\n */\nexport function PreferencesSettings({\n labels,\n values,\n languages,\n port,\n onLanguageChanged,\n onThemeChanged,\n onTimezoneChanged,\n}: PreferencesSettingsProps) {\n const [timezone, setTimezone] = useState(values.timezone);\n // Re-seed when the host supplies a different account, comparing values (not\n // object identity) so a parent re-render never overwrites in-progress edits.\n const [seedTimezone, setSeedTimezone] = useState(values.timezone);\n if (values.timezone !== seedTimezone) {\n setSeedTimezone(values.timezone);\n setTimezone(values.timezone);\n }\n\n const [languagePending, setLanguagePending] = useState(false);\n const [themePending, setThemePending] = useState(false);\n const [timezonePending, setTimezonePending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n async function handleLanguage(value: string): Promise<void> {\n if (languagePending) return;\n setLanguagePending(true);\n setError(null);\n try {\n await port.saveLanguage(value);\n onLanguageChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setLanguagePending(false);\n }\n }\n\n async function handleTheme(value: ThemePreferenceValue): Promise<void> {\n if (themePending) return;\n setThemePending(true);\n setError(null);\n try {\n await port.saveTheme(value);\n onThemeChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setThemePending(false);\n }\n }\n\n async function handleTimezone(): Promise<void> {\n if (timezonePending) return;\n setTimezonePending(true);\n setError(null);\n try {\n await port.saveTimezone(timezone.trim());\n onTimezoneChanged?.(timezone.trim());\n } catch {\n setError(labels.updateFailed);\n } finally {\n setTimezonePending(false);\n }\n }\n\n // Read the browser zone only inside the click handler: resolving it during\n // render would differ between the server and the browser.\n function useBrowserTimezone(): void {\n setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);\n }\n\n const themeOptions: { value: ThemePreferenceValue; label: string; icon: React.ReactNode }[] = [\n { value: \"LIGHT\", label: labels.themeLight, icon: <SunIcon /> },\n { value: \"DARK\", label: labels.themeDark, icon: <MoonIcon /> },\n { value: \"SYSTEM\", label: labels.themeSystem, icon: <MonitorIcon /> },\n ];\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.languageTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.languageDesc}</p>\n <Select\n value={values.language}\n onValueChange={(value) => void handleLanguage(value)}\n disabled={languagePending}\n >\n <SelectTrigger id=\"preferences-settings-language\" aria-label={labels.languageTitle} className=\"w-60\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {languages.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.themeTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.themeDesc}</p>\n <div className=\"flex flex-wrap gap-2\">\n {themeOptions.map((option) => {\n const active = values.theme === option.value;\n return (\n <Button\n key={option.value}\n type=\"button\"\n variant={active ? \"default\" : \"outline\"}\n aria-pressed={active}\n disabled={themePending}\n onClick={() => void handleTheme(option.value)}\n >\n {option.icon}\n {option.label}\n </Button>\n );\n })}\n </div>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.timezoneTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.timezoneDesc}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"preferences-settings-timezone\">{labels.timezoneTitle}</Label>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Input\n id=\"preferences-settings-timezone\"\n value={timezone}\n onChange={(event) => setTimezone(event.target.value)}\n placeholder={labels.timezonePlaceholder}\n className=\"w-72\"\n disabled={timezonePending}\n />\n <Button\n type=\"button\"\n onClick={() => void handleTimezone()}\n disabled={timezonePending || timezone.trim() === \"\"}\n >\n {timezonePending ? <Spinner /> : <SaveIcon />}\n {labels.saveTimezone}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={useBrowserTimezone} disabled={timezonePending}>\n {labels.useBrowserTimezone}\n </Button>\n </div>\n </div>\n </CardContent>\n </Card>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n </div>\n );\n}\n",
58
+ "content": "\"use client\";\n\nimport { useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\";\nimport type { PreferencesSettingsProps, ThemePreferenceValue } from \"./types\";\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction SunIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"4\" />\n <path d=\"M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4\" />\n </svg>\n );\n}\n\nfunction MoonIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z\" />\n </svg>\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction SaveIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z\" />\n <path d=\"M17 21v-8H7v8M7 3v5h8\" />\n </svg>\n );\n}\n\n/**\n * Account display preferences: interface language, theme and timezone. The\n * host owns transport and the side effects of each change (locale cookie,\n * theme class, caching), which enter through `port` and the `on*` callbacks.\n */\nexport function PreferencesSettings({\n labels,\n values,\n languages,\n port,\n onLanguageChanged,\n onThemeChanged,\n onTimezoneChanged,\n}: PreferencesSettingsProps) {\n const [timezone, setTimezone] = useState(values.timezone);\n // Re-seed when the host supplies a different account, comparing values (not\n // object identity) so a parent re-render never overwrites in-progress edits.\n const [seedTimezone, setSeedTimezone] = useState(values.timezone);\n if (values.timezone !== seedTimezone) {\n setSeedTimezone(values.timezone);\n setTimezone(values.timezone);\n }\n\n const [languagePending, setLanguagePending] = useState(false);\n const [themePending, setThemePending] = useState(false);\n const [timezonePending, setTimezonePending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n async function handleLanguage(value: string): Promise<void> {\n if (languagePending) return;\n setLanguagePending(true);\n setError(null);\n try {\n await port.saveLanguage(value);\n onLanguageChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setLanguagePending(false);\n }\n }\n\n async function handleTheme(value: ThemePreferenceValue): Promise<void> {\n if (themePending) return;\n setThemePending(true);\n setError(null);\n try {\n await port.saveTheme(value);\n onThemeChanged?.(value);\n } catch {\n setError(labels.updateFailed);\n } finally {\n setThemePending(false);\n }\n }\n\n async function handleTimezone(): Promise<void> {\n if (timezonePending) return;\n setTimezonePending(true);\n setError(null);\n try {\n await port.saveTimezone(timezone.trim());\n onTimezoneChanged?.(timezone.trim());\n } catch {\n setError(labels.updateFailed);\n } finally {\n setTimezonePending(false);\n }\n }\n\n // Read the browser zone only inside the click handler: resolving it during\n // render would differ between the server and the browser.\n function fillBrowserTimezone(): void {\n setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);\n }\n\n const themeOptions: { value: ThemePreferenceValue; label: string; icon: React.ReactNode }[] = [\n { value: \"LIGHT\", label: labels.themeLight, icon: <SunIcon /> },\n { value: \"DARK\", label: labels.themeDark, icon: <MoonIcon /> },\n { value: \"SYSTEM\", label: labels.themeSystem, icon: <MonitorIcon /> },\n ];\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.languageTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.languageDesc}</p>\n <Select\n value={values.language}\n onValueChange={(value) => void handleLanguage(value)}\n disabled={languagePending}\n >\n <SelectTrigger id=\"preferences-settings-language\" aria-label={labels.languageTitle} className=\"w-60\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {languages.map((option) => (\n <SelectItem key={option.value} value={option.value}>\n {option.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.themeTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-3\">\n <p className=\"text-sm text-muted-foreground\">{labels.themeDesc}</p>\n <div className=\"flex flex-wrap gap-2\">\n {themeOptions.map((option) => {\n const active = values.theme === option.value;\n return (\n <Button\n key={option.value}\n type=\"button\"\n variant={active ? \"default\" : \"outline\"}\n aria-pressed={active}\n disabled={themePending}\n onClick={() => void handleTheme(option.value)}\n >\n {option.icon}\n {option.label}\n </Button>\n );\n })}\n </div>\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.timezoneTitle}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.timezoneDesc}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"preferences-settings-timezone\">{labels.timezoneTitle}</Label>\n <div className=\"flex flex-wrap items-center gap-2\">\n <Input\n id=\"preferences-settings-timezone\"\n value={timezone}\n onChange={(event) => setTimezone(event.target.value)}\n placeholder={labels.timezonePlaceholder}\n className=\"w-72\"\n disabled={timezonePending}\n />\n <Button\n type=\"button\"\n onClick={() => void handleTimezone()}\n disabled={timezonePending || timezone.trim() === \"\"}\n >\n {timezonePending ? <Spinner /> : <SaveIcon />}\n {labels.saveTimezone}\n </Button>\n <Button type=\"button\" variant=\"outline\" onClick={fillBrowserTimezone} disabled={timezonePending}>\n {labels.useBrowserTimezone}\n </Button>\n </div>\n </div>\n </CardContent>\n </Card>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n </div>\n );\n}\n",
59
59
  "type": "registry:block"
60
60
  }
61
61
  ]
@@ -70,7 +70,7 @@
70
70
  },
71
71
  {
72
72
  "path": "src/modules/security-settings/security-settings.tsx",
73
- "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { SecuritySession, SecuritySettingsProps, SecurityTwoFactorSetup } from \"./types\";\n\nconst CODE_LENGTH = 6;\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction ShieldCheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4 text-green-600\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n );\n}\n\nfunction ShieldOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m4 4 16 16\" />\n </svg>\n );\n}\n\nfunction TrashIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v5M14 11v5\" />\n </svg>\n );\n}\n\n/** Format the location parts carried on a session row. */\nfunction formatLocation(session: SecuritySession): string {\n return [session.city, session.region, session.countryCode].filter(Boolean).join(\", \");\n}\n\n/**\n * Account security cards: active sessions with per-row sign-out, and\n * authenticator-app enrollment. The host owns transport, cache invalidation\n * and toasts; the module only renders and reports through callbacks.\n */\nexport function SecuritySettings({\n labels,\n twoFactorEnabled,\n formatDateTime,\n port,\n onSessionsChanged,\n onTwoFactorChanged,\n}: SecuritySettingsProps) {\n // Keep the port reachable from the mount effect without re-running it when\n // the host re-creates its callback objects on every render.\n const portRef = useRef(port);\n useEffect(() => {\n portRef.current = port;\n }, [port]);\n\n const [sessions, setSessions] = useState<SecuritySession[] | null>(null);\n const [sessionsPending, setSessionsPending] = useState(true);\n const [sessionsFailed, setSessionsFailed] = useState(false);\n const [revokingId, setRevokingId] = useState<number | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const [setupData, setSetupData] = useState<SecurityTwoFactorSetup | null>(null);\n const [setupPending, setSetupPending] = useState(false);\n const [enableCode, setEnableCode] = useState(\"\");\n const [enablePending, setEnablePending] = useState(false);\n const [disableMode, setDisableMode] = useState(false);\n const [disablePassword, setDisablePassword] = useState(\"\");\n const [disableCode, setDisableCode] = useState(\"\");\n const [disablePending, setDisablePending] = useState(false);\n\n const loadSessions = useCallback(async (): Promise<void> => {\n try {\n const result = await portRef.current.listSessions();\n setSessions(result.records);\n setSessionsFailed(false);\n } catch {\n setSessionsFailed(true);\n } finally {\n setSessionsPending(false);\n }\n }, []);\n\n useEffect(() => {\n void loadSessions();\n }, [loadSessions]);\n\n function retrySessions(): void {\n setSessionsPending(true);\n setSessionsFailed(false);\n void loadSessions();\n }\n\n const formatDate = formatDateTime ?? ((iso: string) => new Date(iso).toLocaleString());\n\n async function handleRevoke(id: number): Promise<void> {\n if (revokingId !== null) return;\n setRevokingId(id);\n setActionError(null);\n try {\n await port.revokeSession(id);\n onSessionsChanged?.();\n await loadSessions();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setRevokingId(null);\n }\n }\n\n async function handleSetup(): Promise<void> {\n if (setupPending) return;\n setSetupPending(true);\n setActionError(null);\n try {\n setSetupData(await port.setupTwoFactor());\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setSetupPending(false);\n }\n }\n\n async function handleEnable(): Promise<void> {\n if (enablePending) return;\n setEnablePending(true);\n setActionError(null);\n try {\n await port.enableTwoFactor(enableCode);\n setSetupData(null);\n setEnableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setEnablePending(false);\n }\n }\n\n async function handleDisable(): Promise<void> {\n if (disablePending) return;\n setDisablePending(true);\n setActionError(null);\n try {\n await port.disableTwoFactor(disablePassword ? { password: disablePassword } : { code: disableCode });\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setDisablePending(false);\n }\n }\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-base\">\n <MonitorIcon />\n {labels.activeSessions}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {sessionsPending ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner />\n {labels.loadingSessions}\n </div>\n ) : sessionsFailed ? (\n <div className=\"flex flex-wrap items-center gap-2 text-sm text-destructive\">\n {labels.loadSessionsFailed}\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"h-auto p-0\" onClick={retrySessions}>\n {labels.retry}\n </Button>\n </div>\n ) : !sessions?.length ? (\n <p className=\"text-sm text-muted-foreground\">{labels.noSessions}</p>\n ) : (\n <ul className=\"divide-y\">\n {sessions.map((session) => (\n <li key={session.id} className=\"flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0\">\n <div className=\"min-w-0\">\n <div className=\"flex items-center gap-2\">\n <p className=\"truncate text-sm font-medium\">\n {[session.browser, session.operatingSystem].filter(Boolean).join(\" · \") || labels.unknownDevice}\n </p>\n {session.isCurrentSession && (\n <Badge variant=\"outline\" className=\"border-green-200 bg-green-50 text-green-700\">\n {labels.thisDevice}\n </Badge>\n )}\n </div>\n <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n {[session.ipAddress, formatLocation(session)].filter(Boolean).join(\" · \")} ·{\" \"}\n {formatDate(session.createdAt)}\n </p>\n </div>\n {!session.isCurrentSession && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n aria-label={labels.signOutSession}\n disabled={revokingId !== null}\n onClick={() => void handleRevoke(session.id)}\n >\n {revokingId === session.id ? <Spinner /> : <TrashIcon />}\n </Button>\n )}\n </li>\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center justify-between gap-2 text-base\">\n <span className=\"flex items-center gap-2\">\n {twoFactorEnabled ? <ShieldCheckIcon /> : <ShieldOffIcon />}\n {labels.twoFactorTitle}\n </span>\n <Badge variant={twoFactorEnabled ? \"default\" : \"outline\"}>\n {twoFactorEnabled ? labels.statusEnabled : labels.statusDisabled}\n </Badge>\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.twoFactorDesc}</p>\n\n {/* Enrollment flow: QR code plus code confirmation */}\n {setupData && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"flex flex-col items-center gap-3 sm:flex-row sm:items-start\">\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src={setupData.qrCodeDataUrl}\n alt={labels.qrAlt}\n className=\"h-40 w-40 rounded-md border bg-white p-2\"\n />\n <div className=\"min-w-0 space-y-2\">\n <p className=\"text-xs text-muted-foreground\">{labels.scanQr}</p>\n <p className=\"break-all rounded bg-background p-2 font-mono text-xs\">{setupData.secret}</p>\n </div>\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-enable-code\">{labels.enterCode}</Label>\n <Input\n id=\"security-settings-enable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={enableCode}\n onChange={(event) => setEnableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setSetupData(null);\n setEnableCode(\"\");\n }}\n disabled={enablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n onClick={() => void handleEnable()}\n disabled={enablePending || enableCode.length !== CODE_LENGTH}\n >\n {enablePending ? <Spinner /> : labels.confirmEnable}\n </Button>\n </div>\n </div>\n )}\n\n {/* Disable flow: prove identity with password or a current code */}\n {disableMode && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-password\">{labels.currentPassword}</Label>\n <Input\n id=\"security-settings-disable-password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={disablePassword}\n onChange={(event) => {\n setDisablePassword(event.target.value);\n setDisableCode(\"\");\n }}\n placeholder={labels.passwordPlaceholder}\n />\n </div>\n <p className=\"text-center text-xs text-muted-foreground\">{labels.or}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-code\">{labels.authenticatorCode}</Label>\n <Input\n id=\"security-settings-disable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={disableCode}\n onChange={(event) => {\n setDisableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH));\n setDisablePassword(\"\");\n }}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n }}\n disabled={disablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => void handleDisable()}\n disabled={disablePending || (!disablePassword && disableCode.length !== CODE_LENGTH)}\n >\n {disablePending ? <Spinner /> : labels.disable}\n </Button>\n </div>\n </div>\n )}\n\n {actionError && <p className=\"text-sm text-destructive\">{actionError}</p>}\n\n {/* Idle actions */}\n {!setupData && !disableMode && (\n <div>\n {twoFactorEnabled ? (\n <Button type=\"button\" variant=\"outline\" onClick={() => setDisableMode(true)}>\n {labels.disableTwoFactor}\n </Button>\n ) : (\n <Button type=\"button\" onClick={() => void handleSetup()} disabled={setupPending}>\n {setupPending ? <Spinner /> : labels.setupWithApp}\n </Button>\n )}\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
73
+ "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { SecuritySession, SecuritySettingsProps, SecurityTwoFactorSetup } from \"./types\";\n\nconst CODE_LENGTH = 6;\n\n/** SSR-safe date fallback: fixed locale and zone, so both renders agree. */\nconst DEFAULT_DATE_FORMATTER = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n});\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction ShieldCheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4 text-green-600 dark:text-green-500\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n );\n}\n\nfunction ShieldOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m4 4 16 16\" />\n </svg>\n );\n}\n\nfunction TrashIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v5M14 11v5\" />\n </svg>\n );\n}\n\n/** Format the location parts carried on a session row. */\nfunction formatLocation(session: SecuritySession): string {\n return [session.city, session.region, session.countryCode].filter(Boolean).join(\", \");\n}\n\n/**\n * Account security cards: active sessions with per-row sign-out, and\n * authenticator-app enrollment. The host owns transport, cache invalidation\n * and toasts; the module only renders and reports through callbacks.\n */\nexport function SecuritySettings({\n labels,\n twoFactorEnabled,\n formatDateTime,\n port,\n onSessionsChanged,\n onTwoFactorChanged,\n}: SecuritySettingsProps) {\n // Keep the port reachable from the mount effect without re-running it when\n // the host re-creates its callback objects on every render.\n const portRef = useRef(port);\n useEffect(() => {\n portRef.current = port;\n }, [port]);\n\n const [sessions, setSessions] = useState<SecuritySession[] | null>(null);\n const [sessionsPending, setSessionsPending] = useState(true);\n const [sessionsFailed, setSessionsFailed] = useState(false);\n const [revokingId, setRevokingId] = useState<number | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const [setupData, setSetupData] = useState<SecurityTwoFactorSetup | null>(null);\n const [setupPending, setSetupPending] = useState(false);\n const [enableCode, setEnableCode] = useState(\"\");\n const [enablePending, setEnablePending] = useState(false);\n const [disableMode, setDisableMode] = useState(false);\n const [disablePassword, setDisablePassword] = useState(\"\");\n const [disableCode, setDisableCode] = useState(\"\");\n const [disablePending, setDisablePending] = useState(false);\n\n const loadSessions = useCallback(async (): Promise<void> => {\n try {\n const result = await portRef.current.listSessions();\n setSessions(result.records);\n setSessionsFailed(false);\n } catch {\n setSessionsFailed(true);\n } finally {\n setSessionsPending(false);\n }\n }, []);\n\n useEffect(() => {\n void loadSessions();\n }, [loadSessions]);\n\n function retrySessions(): void {\n setSessionsPending(true);\n setSessionsFailed(false);\n void loadSessions();\n }\n\n // Deterministic fallback: a locale/timezone-sensitive formatter would render\n // differently on the server and in the browser (R84-10). Hosts pass\n // `formatDateTime` to localize.\n const formatDate = formatDateTime ?? ((iso: string) => DEFAULT_DATE_FORMATTER.format(new Date(iso)));\n\n async function handleRevoke(id: number): Promise<void> {\n if (revokingId !== null) return;\n setRevokingId(id);\n setActionError(null);\n try {\n await port.revokeSession(id);\n onSessionsChanged?.();\n await loadSessions();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setRevokingId(null);\n }\n }\n\n async function handleSetup(): Promise<void> {\n if (setupPending) return;\n setSetupPending(true);\n setActionError(null);\n try {\n setSetupData(await port.setupTwoFactor());\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setSetupPending(false);\n }\n }\n\n async function handleEnable(): Promise<void> {\n if (enablePending) return;\n setEnablePending(true);\n setActionError(null);\n try {\n await port.enableTwoFactor(enableCode);\n setSetupData(null);\n setEnableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setEnablePending(false);\n }\n }\n\n async function handleDisable(): Promise<void> {\n if (disablePending) return;\n setDisablePending(true);\n setActionError(null);\n try {\n await port.disableTwoFactor(disablePassword ? { password: disablePassword } : { code: disableCode });\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setDisablePending(false);\n }\n }\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-base\">\n <MonitorIcon />\n {labels.activeSessions}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {sessionsPending ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner />\n {labels.loadingSessions}\n </div>\n ) : sessionsFailed ? (\n <div className=\"flex flex-wrap items-center gap-2 text-sm text-destructive\">\n {labels.loadSessionsFailed}\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"h-auto p-0\" onClick={retrySessions}>\n {labels.retry}\n </Button>\n </div>\n ) : !sessions?.length ? (\n <p className=\"text-sm text-muted-foreground\">{labels.noSessions}</p>\n ) : (\n <ul className=\"divide-y\">\n {sessions.map((session) => (\n <li key={session.id} className=\"flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0\">\n <div className=\"min-w-0\">\n <div className=\"flex items-center gap-2\">\n <p className=\"truncate text-sm font-medium\">\n {[session.browser, session.operatingSystem].filter(Boolean).join(\" · \") || labels.unknownDevice}\n </p>\n {session.isCurrentSession && (\n <Badge\n variant=\"outline\"\n className=\"border-green-200 bg-green-50 text-green-700 dark:border-green-900 dark:bg-green-950 dark:text-green-400\"\n >\n {labels.thisDevice}\n </Badge>\n )}\n </div>\n <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n {[session.ipAddress, formatLocation(session)].filter(Boolean).join(\" · \")} ·{\" \"}\n {formatDate(session.createdAt)}\n </p>\n </div>\n {!session.isCurrentSession && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n aria-label={labels.signOutSession}\n disabled={revokingId !== null}\n onClick={() => void handleRevoke(session.id)}\n >\n {revokingId === session.id ? <Spinner /> : <TrashIcon />}\n </Button>\n )}\n </li>\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center justify-between gap-2 text-base\">\n <span className=\"flex items-center gap-2\">\n {twoFactorEnabled ? <ShieldCheckIcon /> : <ShieldOffIcon />}\n {labels.twoFactorTitle}\n </span>\n <Badge variant={twoFactorEnabled ? \"default\" : \"outline\"}>\n {twoFactorEnabled ? labels.statusEnabled : labels.statusDisabled}\n </Badge>\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.twoFactorDesc}</p>\n\n {/* Enrollment flow: QR code plus code confirmation */}\n {setupData && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"flex flex-col items-center gap-3 sm:flex-row sm:items-start\">\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src={setupData.qrCodeDataUrl}\n alt={labels.qrAlt}\n className=\"h-40 w-40 rounded-md border bg-white p-2\"\n />\n <div className=\"min-w-0 space-y-2\">\n <p className=\"text-xs text-muted-foreground\">{labels.scanQr}</p>\n <p className=\"break-all rounded bg-background p-2 font-mono text-xs\">{setupData.secret}</p>\n </div>\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-enable-code\">{labels.enterCode}</Label>\n <Input\n id=\"security-settings-enable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={enableCode}\n onChange={(event) => setEnableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setSetupData(null);\n setEnableCode(\"\");\n }}\n disabled={enablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n onClick={() => void handleEnable()}\n disabled={enablePending || enableCode.length !== CODE_LENGTH}\n >\n {enablePending ? <Spinner /> : labels.confirmEnable}\n </Button>\n </div>\n </div>\n )}\n\n {/* Disable flow: prove identity with password or a current code */}\n {disableMode && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-password\">{labels.currentPassword}</Label>\n <Input\n id=\"security-settings-disable-password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={disablePassword}\n onChange={(event) => {\n setDisablePassword(event.target.value);\n setDisableCode(\"\");\n }}\n placeholder={labels.passwordPlaceholder}\n />\n </div>\n <p className=\"text-center text-xs text-muted-foreground\">{labels.or}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-code\">{labels.authenticatorCode}</Label>\n <Input\n id=\"security-settings-disable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={disableCode}\n onChange={(event) => {\n setDisableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH));\n setDisablePassword(\"\");\n }}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n }}\n disabled={disablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => void handleDisable()}\n disabled={disablePending || (!disablePassword && disableCode.length !== CODE_LENGTH)}\n >\n {disablePending ? <Spinner /> : labels.disable}\n </Button>\n </div>\n </div>\n )}\n\n {actionError && <p className=\"text-sm text-destructive\">{actionError}</p>}\n\n {/* Idle actions */}\n {!setupData && !disableMode && (\n <div>\n {twoFactorEnabled ? (\n <Button type=\"button\" variant=\"outline\" onClick={() => setDisableMode(true)}>\n {labels.disableTwoFactor}\n </Button>\n ) : (\n <Button type=\"button\" onClick={() => void handleSetup()} disabled={setupPending}>\n {setupPending ? <Spinner /> : labels.setupWithApp}\n </Button>\n )}\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
74
74
  "type": "registry:block"
75
75
  }
76
76
  ]
@@ -1,18 +1,17 @@
1
1
  {
2
- "version": "1.0.0",
2
+ "version": "1.1.0",
3
3
  "framework": "^1.7.0",
4
4
  "entry": "src/modules/settings-required-state/index.ts",
5
5
  "labels": [
6
6
  "actionLabel"
7
7
  ],
8
- "ports": [
9
- "onOpenSettings"
10
- ],
8
+ "ports": [],
11
9
  "ui": [
12
10
  "button",
13
11
  "card"
14
12
  ],
15
13
  "states": [
14
+ "loading",
16
15
  "ready"
17
16
  ]
18
17
  }
@@ -4,22 +4,21 @@
4
4
  "type": "registry:block",
5
5
  "title": "Settings required state",
6
6
  "description": "Empty state shown when required configuration is missing, with a call-to-action whose navigation stays in the host.",
7
- "postInstall": "Render <SettingsRequiredState labels={...} title={...} settingsHref={...} onOpenSettings={...} /> wherever a feature needs its configuration first. The host supplies the translated action label, the in-app settings path and the navigation callback. Requires the shadcn ui primitives button and card.",
7
+ "postInstall": "Render <SettingsRequiredState labels={...} title={...} settingsHref={...} onOpenSettings={...} /> for the navigate-to-settings variant, or pass onAction (plus actionPending) for an in-place action. The host supplies the translated action label, the in-app settings path and either callback. Requires the shadcn ui primitives button and card.",
8
8
  "x-fewbie.contract": {
9
- "version": "1.0.0",
9
+ "version": "1.1.0",
10
10
  "framework": "^1.7.0",
11
11
  "entry": "src/modules/settings-required-state/index.ts",
12
12
  "labels": [
13
13
  "actionLabel"
14
14
  ],
15
- "ports": [
16
- "onOpenSettings"
17
- ],
15
+ "ports": [],
18
16
  "ui": [
19
17
  "button",
20
18
  "card"
21
19
  ],
22
20
  "states": [
21
+ "loading",
23
22
  "ready"
24
23
  ]
25
24
  },
@@ -31,12 +30,12 @@
31
30
  },
32
31
  {
33
32
  "path": "src/modules/settings-required-state/types.ts",
34
- "content": "import type { ReactNode } from \"react\";\n\n/**\n * Every string the state renders. The headline and description are already\n * host-supplied props, so only the call-to-action label lives here.\n */\nexport interface SettingsRequiredStateLabels {\n actionLabel: string;\n}\n\nexport interface SettingsRequiredStateProps {\n labels: SettingsRequiredStateLabels;\n /** Short headline shown below the icon, e.g. \"AWS credential required\". */\n title: string;\n /** Explanation of which setting is missing and why it is needed. */\n description?: ReactNode;\n /** Destination of the settings call-to-action, usually the project settings page. */\n settingsHref: string;\n /** Called with settingsHref; the host performs the client-side navigation. */\n onOpenSettings: (href: string) => void;\n /** Optional custom icon rendered inside the tinted badge. */\n icon?: ReactNode;\n /** Stretch the state to fill the parent height (used by full-screen panels). */\n fullHeight?: boolean;\n /** Allow callers to tweak the outer container when needed. */\n className?: string;\n}\n",
33
+ "content": "import type { ReactNode } from \"react\";\n\n/**\n * Every string the state renders. The headline and description are already\n * host-supplied props, so only the call-to-action label lives here.\n */\nexport interface SettingsRequiredStateLabels {\n actionLabel: string;\n}\n\nexport interface SettingsRequiredStateProps {\n labels: SettingsRequiredStateLabels;\n /** Short headline shown below the icon, e.g. \"AWS credential required\". */\n title: string;\n /** Explanation of which setting is missing and why it is needed. */\n description?: ReactNode;\n /** Destination of the settings call-to-action. Required unless `onAction` is provided. */\n settingsHref?: string;\n /** Called with settingsHref; the host performs the client-side navigation. */\n onOpenSettings?: (href: string) => void;\n /** In-place action (e.g. one-click initialization); takes precedence over the settings link. */\n onAction?: () => void;\n /** Shows a spinner and disables the action while the in-place action runs. */\n actionPending?: boolean;\n /** Optional custom icon rendered inside the tinted badge. */\n icon?: ReactNode;\n /** Stretch the state to fill the parent height (used by full-screen panels). */\n fullHeight?: boolean;\n /** Allow callers to tweak the outer container when needed. */\n className?: string;\n}\n",
35
34
  "type": "registry:block"
36
35
  },
37
36
  {
38
37
  "path": "src/modules/settings-required-state/settings-required-state.tsx",
39
- "content": "\"use client\";\n\nimport { ArrowRight, Settings2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { cn } from \"@/lib/utils\";\n\nimport type { SettingsRequiredStateProps } from \"./types\";\n\n/**\n * Unified \"required settings are missing\" state. Feature modules render this\n * when their backing configuration has not been set up yet, so the\n * empty-state visuals and the settings entry point stay consistent.\n */\nexport function SettingsRequiredState({\n labels,\n title,\n description,\n settingsHref,\n onOpenSettings,\n icon,\n fullHeight = false,\n className,\n}: SettingsRequiredStateProps) {\n return (\n <div className={cn(\"flex w-full items-center justify-center\", fullHeight ? \"h-full\" : \"py-8 md:py-16\", className)}>\n <Card className=\"w-full max-w-xl text-center\">\n <CardContent className=\"flex flex-col items-center px-6 py-10 md:px-12\">\n {/* Tinted icon badge */}\n <div className=\"mb-4 flex size-16 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {icon ?? <Settings2 className=\"size-8\" />}\n </div>\n\n <h2 className=\"text-lg font-semibold text-foreground\">{title}</h2>\n\n {description ? <p className=\"mt-2 max-w-md text-sm leading-7 text-muted-foreground\">{description}</p> : null}\n\n <Button className=\"mt-6\" onClick={() => onOpenSettings(settingsHref)}>\n {labels.actionLabel}\n <ArrowRight className=\"size-4\" />\n </Button>\n </CardContent>\n </Card>\n </div>\n );\n}\n",
38
+ "content": "\"use client\";\n\nimport { ArrowRight, LoaderCircle, Settings2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { cn } from \"@/lib/utils\";\n\nimport type { SettingsRequiredStateProps } from \"./types\";\n\n/**\n * Unified \"required settings are missing\" state. Feature modules render this\n * when their backing configuration has not been set up yet, so the\n * empty-state visuals and the settings entry point stay consistent.\n */\nexport function SettingsRequiredState({\n labels,\n title,\n description,\n settingsHref,\n onOpenSettings,\n onAction,\n actionPending = false,\n icon,\n fullHeight = false,\n className,\n}: SettingsRequiredStateProps) {\n return (\n <div className={cn(\"flex w-full items-center justify-center\", fullHeight ? \"h-full\" : \"py-8 md:py-16\", className)}>\n <Card className=\"w-full max-w-xl text-center\">\n <CardContent className=\"flex flex-col items-center px-6 py-10 md:px-12\">\n {/* Tinted icon badge */}\n <div className=\"mb-4 flex size-16 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {icon ?? <Settings2 className=\"size-8\" />}\n </div>\n\n <h2 className=\"text-lg font-semibold text-foreground\">{title}</h2>\n\n {description ? <p className=\"mt-2 max-w-md text-sm leading-7 text-muted-foreground\">{description}</p> : null}\n\n {onAction ? (\n <Button className=\"mt-6\" onClick={onAction} disabled={actionPending}>\n {actionPending ? <LoaderCircle className=\"size-4 animate-spin\" /> : null}\n {labels.actionLabel}\n </Button>\n ) : settingsHref && onOpenSettings ? (\n <Button className=\"mt-6\" onClick={() => onOpenSettings(settingsHref)}>\n {labels.actionLabel}\n <ArrowRight className=\"size-4\" />\n </Button>\n ) : null}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
40
39
  "type": "registry:block"
41
40
  }
42
41
  ]
@@ -8,7 +8,7 @@
8
8
  "files": [
9
9
  {
10
10
  "path": "src/lib/sse-stream.ts",
11
- "content": "/**\n * Minimal Server-Sent Events transport over fetch.\n *\n * `postSse` covers endpoints that EventSource cannot serve (POST bodies,\n * custom headers): it POSTs a JSON body, then decodes the response stream.\n * `consumeSseStream` is the lower-level decoder for callers that already\n * hold a fetch Response.\n *\n * The wire format handled is standard SSE:\n *\n * event: <name>\\n\n * data: <json>\\n\n * \\n\n *\n * with `: keepalive` comment lines during quiet periods. This layer is\n * transport-text only; JSON decoding of the data line is the caller's job.\n */\n\nexport interface SseFrame {\n event: string;\n data: string;\n}\n\n/** HTTP-level failure of a POST-initiated SSE request (non-2xx or no body). */\nexport class SseStreamError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"SseStreamError\";\n }\n}\n\nconst DECODER = new TextDecoder();\n\nconst NEVER_ABORTED = new AbortController().signal;\n\nexport interface PostSseOptions {\n /** JSON-encoded request body; omit to POST without a body. */\n body?: unknown;\n /** Extra request headers (e.g. Authorization). Content-Type and Accept are set automatically. */\n headers?: Record<string, string>;\n /** Aborting stops reading immediately; already received frames are retained by the caller. */\n signal?: AbortSignal;\n /** Called for every decoded frame, in arrival order. */\n onFrame: (frame: SseFrame) => void;\n}\n\n/**\n * POST-initiated SSE request: the standard workaround for EventSource's\n * inability to send POST bodies or custom headers. Resolves after the server\n * closes the stream; rejects with SseStreamError on HTTP-level failures.\n * Stream errors during reading propagate from the underlying reader.\n */\nexport async function postSse(url: string, options: PostSseOptions): Promise<void> {\n const { body, headers, signal = NEVER_ABORTED, onFrame } = options;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n\n if (!response.ok || !response.body) {\n const detail = await response.text().catch(() => \"\");\n throw new SseStreamError(\n response.status,\n `SSE request failed with ${response.status}${detail ? `: ${detail}` : \"\"}`,\n );\n }\n\n await consumeSseStream(response.body, signal, onFrame);\n}\n\n/**\n * Consume a fetch Response.body stream until the server closes it.\n *\n * Partial multibyte sequences and frames split across chunks are buffered, so\n * callers may invoke this directly on response.body without any framing\n * assumptions. Aborting `signal` stops reading immediately; the already\n * received frames are retained by the caller.\n */\nexport async function consumeSseStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n onFrame: (frame: SseFrame) => void,\n): Promise<void> {\n const reader = body.getReader();\n let buffer = \"\";\n\n const onAbort = (): void => {\n reader.cancel(\"aborted\").catch(() => {});\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += DECODER.decode(value, { stream: true });\n\n let separatorIndex: number;\n // SSE dispatches on a blank line; tolerate CRLF.\n while ((separatorIndex = findFrameBoundary(buffer)) !== -1) {\n const rawFrame = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex).replace(/^(\\r?\\n){2}/, \"\");\n const frame = parseFrame(rawFrame);\n if (frame) onFrame(frame);\n }\n }\n\n const tail = buffer.trim();\n if (tail) {\n const frame = parseFrame(tail);\n if (frame) onFrame(frame);\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n try {\n reader.releaseLock();\n } catch {\n // A lock held by a racing cancel() releases on its own.\n }\n }\n}\n\n/** Normalize the two possible blank-line styles (\\n\\n and \\r\\n\\r\\n). */\nfunction findFrameBoundary(buffer: string): number {\n const lf = buffer.indexOf(\"\\n\\n\");\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\");\n if (lf === -1) return crlf;\n if (crlf === -1) return lf;\n return Math.min(lf, crlf);\n}\n\nfunction parseFrame(rawFrame: string): SseFrame | null {\n let event = \"message\";\n const dataLines: string[] = [];\n\n for (const rawLine of rawFrame.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\r$/, \"\");\n if (!line || line.startsWith(\":\")) continue; // comments / keepalive\n if (line.startsWith(\"event:\")) {\n event = line.slice(\"event:\".length).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(\"data:\".length).trimStart());\n }\n }\n\n if (dataLines.length === 0) return null;\n return { event, data: dataLines.join(\"\\n\") };\n}\n",
11
+ "content": "/**\n * Minimal Server-Sent Events transport over fetch.\n *\n * `postSse` covers endpoints that EventSource cannot serve (POST bodies,\n * custom headers): it POSTs a JSON body, then decodes the response stream.\n * `consumeSseStream` is the lower-level decoder for callers that already\n * hold a fetch Response.\n *\n * The wire format handled is standard SSE:\n *\n * event: <name>\\n\n * data: <json>\\n\n * \\n\n *\n * with `: keepalive` comment lines during quiet periods. This layer is\n * transport-text only; JSON decoding of the data line is the caller's job.\n */\n\nexport interface SseFrame {\n event: string;\n data: string;\n}\n\n/** HTTP-level failure of a POST-initiated SSE request (non-2xx or no body). */\nexport class SseStreamError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"SseStreamError\";\n }\n}\n\nconst NEVER_ABORTED = new AbortController().signal;\n\nexport interface PostSseOptions {\n /** JSON-encoded request body; omit to POST without a body. */\n body?: unknown;\n /** Extra request headers (e.g. Authorization). Content-Type and Accept are set automatically. */\n headers?: Record<string, string>;\n /** Aborting stops reading immediately; already received frames are retained by the caller. */\n signal?: AbortSignal;\n /** Called for every decoded frame, in arrival order. */\n onFrame: (frame: SseFrame) => void;\n}\n\n/**\n * POST-initiated SSE request: the standard workaround for EventSource's\n * inability to send POST bodies or custom headers. Resolves after the server\n * closes the stream; rejects with SseStreamError on HTTP-level failures.\n * Stream errors during reading propagate from the underlying reader.\n */\nexport async function postSse(url: string, options: PostSseOptions): Promise<void> {\n const { body, headers, signal = NEVER_ABORTED, onFrame } = options;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n\n if (!response.ok || !response.body) {\n const detail = await response.text().catch(() => \"\");\n throw new SseStreamError(\n response.status,\n `SSE request failed with ${response.status}${detail ? `: ${detail}` : \"\"}`,\n );\n }\n\n await consumeSseStream(response.body, signal, onFrame);\n}\n\n/**\n * Consume a fetch Response.body stream until the server closes it.\n *\n * Partial multibyte sequences and frames split across chunks are buffered, so\n * callers may invoke this directly on response.body without any framing\n * assumptions. Aborting `signal` stops reading immediately; the already\n * received frames are retained by the caller.\n */\nexport async function consumeSseStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n onFrame: (frame: SseFrame) => void,\n): Promise<void> {\n const reader = body.getReader();\n // A decoder per call: `{ stream: true }` keeps an incomplete multibyte\n // sequence inside this instance, so a shared one would let concurrent\n // streams steal each other's bytes (R84-02).\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const onAbort = (): void => {\n reader.cancel(\"aborted\").catch(() => {});\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let separatorIndex: number;\n // SSE dispatches on a blank line; tolerate CRLF.\n while ((separatorIndex = findFrameBoundary(buffer)) !== -1) {\n const rawFrame = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex).replace(/^(\\r?\\n){2}/, \"\");\n const frame = parseFrame(rawFrame);\n if (frame) onFrame(frame);\n }\n }\n\n // Flush any complete sequence still buffered in the decoder.\n buffer += decoder.decode();\n\n const tail = buffer.trim();\n if (tail) {\n const frame = parseFrame(tail);\n if (frame) onFrame(frame);\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n try {\n reader.releaseLock();\n } catch {\n // A lock held by a racing cancel() releases on its own.\n }\n }\n}\n\n/** Normalize the two possible blank-line styles (\\n\\n and \\r\\n\\r\\n). */\nfunction findFrameBoundary(buffer: string): number {\n const lf = buffer.indexOf(\"\\n\\n\");\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\");\n if (lf === -1) return crlf;\n if (crlf === -1) return lf;\n return Math.min(lf, crlf);\n}\n\nfunction parseFrame(rawFrame: string): SseFrame | null {\n let event = \"message\";\n const dataLines: string[] = [];\n\n for (const rawLine of rawFrame.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\r$/, \"\");\n if (!line || line.startsWith(\":\")) continue; // comments / keepalive\n if (line.startsWith(\"event:\")) {\n event = line.slice(\"event:\".length).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(\"data:\".length).trimStart());\n }\n }\n\n if (dataLines.length === 0) return null;\n return { event, data: dataLines.join(\"\\n\") };\n}\n",
12
12
  "type": "registry:lib"
13
13
  }
14
14
  ]
@@ -16,7 +16,7 @@
16
16
  },
17
17
  {
18
18
  "path": "src/components/theme-toggle.tsx",
19
- "content": "\"use client\";\n\nimport { Moon, Sun } from \"lucide-react\";\nimport { useTheme } from \"next-themes\";\n\nimport { Button } from \"@/components/ui/button\";\n\nexport function ThemeToggle() {\n const { resolvedTheme, setTheme } = useTheme();\n\n return (\n <Button\n variant=\"outline\"\n size=\"icon\"\n aria-label=\"Toggle theme\"\n onClick={() => setTheme(resolvedTheme === \"dark\" ? \"light\" : \"dark\")}\n >\n <Sun className=\"size-5 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90\" />\n <Moon className=\"absolute size-5 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0\" />\n </Button>\n );\n}\n",
19
+ "content": "\"use client\";\n\nimport { Moon, Sun } from \"lucide-react\";\nimport { useTheme } from \"next-themes\";\n\nimport { Button } from \"@/components/ui/button\";\n\nexport interface ThemeToggleProps {\n /** Accessible name of the button; the host passes its translated copy. */\n label?: string;\n}\n\nexport function ThemeToggle({ label = \"Toggle theme\" }: ThemeToggleProps = {}) {\n const { resolvedTheme, setTheme } = useTheme();\n\n return (\n <Button\n variant=\"outline\"\n size=\"icon\"\n aria-label={label}\n onClick={() => setTheme(resolvedTheme === \"dark\" ? \"light\" : \"dark\")}\n >\n <Sun className=\"size-5 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90\" />\n <Moon className=\"absolute size-5 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0\" />\n </Button>\n );\n}\n",
20
20
  "type": "registry:component"
21
21
  }
22
22
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devbie/fewbie-cli",
3
- "version": "1.13.1",
3
+ "version": "1.13.2",
4
4
  "description": "fewbie frontend framework CLI",
5
5
  "license": "MIT",
6
6
  "author": "worldzhy",