Compare commits
9 Commits
feat/passw
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3411b4b145 | ||
|
|
eace15b140 | ||
|
|
aa170de8d1 | ||
|
|
7ed4d27844 | ||
| f3d9996b11 | |||
|
|
6830c827d7 | ||
|
|
cc0611b6a0 | ||
|
|
9159dd9c9b | ||
| 01769314cb |
11
.env.example
11
.env.example
@@ -17,7 +17,9 @@ NODE_ENV="development"
|
|||||||
# RESEND_API_KEY="re_xxxxxxxx"
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
# From address for outgoing email (must be a verified Resend sender)
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
# Public URL of the web app, used to build the accept-invitation links
|
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||||
|
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||||
|
# public origin users open in the browser.
|
||||||
WEB_APP_URL="http://localhost:7153"
|
WEB_APP_URL="http://localhost:7153"
|
||||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||||
@@ -27,6 +29,13 @@ WEB_APP_URL="http://localhost:7153"
|
|||||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
# Optional: timeout of the model request, in milliseconds
|
# Optional: timeout of the model request, in milliseconds
|
||||||
# GEMINI_TIMEOUT_MS="8000"
|
# GEMINI_TIMEOUT_MS="8000"
|
||||||
|
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||||
|
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||||
|
# GROQ_API_KEY=""
|
||||||
|
# Optional: model id
|
||||||
|
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GROQ_TIMEOUT_MS="8000"
|
||||||
|
|
||||||
# --- apps/web ---
|
# --- apps/web ---
|
||||||
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
# Optional. In dev, Vite proxies /api/* to the API (http://localhost:4100), so
|
||||||
|
|||||||
35
AGENTS.md
35
AGENTS.md
@@ -6,9 +6,10 @@ Scaffold is in place and verified: Turborepo monorepo with `apps/api`, `apps/web
|
|||||||
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
Biome as the only JS/TS tool and the text Bun lockfile committed. It is deployed with Docker Compose on
|
||||||
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
Dokploy (`docker-compose.yml`); there is no hosted CI.
|
||||||
|
|
||||||
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, shopping lists, list items and invitations exist;
|
Not done yet: product features are just starting (sign-up, password recovery with an emailed OTP, passkeys,
|
||||||
there is no Google login and no email verification; the `voice` module splits dictated text with Gemma 4
|
shopping lists, list items and invitations exist; there is no Google login and no email verification; the
|
||||||
through the Gemini API). The `health` module is the reference example.
|
`voice` module splits dictated text with Groq, or Gemma 4 through the Gemini API when Groq is not configured).
|
||||||
|
The `health` module is the reference example.
|
||||||
|
|
||||||
## Stack (source of truth: `STACK.md`)
|
## Stack (source of truth: `STACK.md`)
|
||||||
|
|
||||||
@@ -100,7 +101,9 @@ Run from the repo root. Verification order is `build`, then `lint` → `typechec
|
|||||||
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
`apps/web/nginx.conf`, which also proxies `/api/*` to `http://superlist-api:4100` (re-resolved through
|
||||||
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
Docker's DNS, so API redeploys don't leave nginx on a stale IP). Required env vars are interpolated
|
||||||
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
by Compose (`DATABASE_URL`, `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`, `CORS_ORIGIN`, `WEB_APP_URL`); set them
|
||||||
in Dokploy. The dictation variables (`GEMINI_API_KEY`, `GEMINI_MODEL`, `GEMINI_TIMEOUT_MS`) are optional and
|
in Dokploy. `WEB_APP_URL` is not only used for email links: it is also the WebAuthn relying-party origin, so
|
||||||
|
it must be the exact public URL of the web app. The dictation variables (`GROQ_API_KEY`, `GROQ_MODEL`, `GROQ_TIMEOUT_MS`, `GEMINI_API_KEY`, `GEMINI_MODEL`,
|
||||||
|
`GEMINI_TIMEOUT_MS`) are optional (Groq wins when its key is set) and
|
||||||
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI.
|
backend-only — never give them a `VITE_` prefix, or Vite would ship the key in the browser bundle. There is no hosted CI.
|
||||||
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
- Generated files are gitignored and must never be edited by hand: `apps/web/src/routeTree.gen.ts`,
|
||||||
`apps/api/src/generated/`.
|
`apps/api/src/generated/`.
|
||||||
@@ -207,6 +210,15 @@ export class CreateAlert {
|
|||||||
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
|
plugin (6-digit code, 10 minutes, hashed in `verifications`): the web `/forgot-password` route calls
|
||||||
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
|
`emailOtp.requestPasswordReset` / `emailOtp.resetPassword`, and the code is sent with `sendEmail`
|
||||||
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
|
(`lib/mailer.ts`, template in `lib/emails/password-reset.ts`). Without `RESEND_API_KEY` the code is logged.
|
||||||
|
- **Passkeys**: the separate `@better-auth/passkey` package (installed in both apps) adds WebAuthn sign-in.
|
||||||
|
Pin it to the exact same version as `better-auth` (currently `1.7.7`): its peer dependencies
|
||||||
|
(`better-call`, `@better-auth/core`) are version-locked, so a newer passkey package breaks the API.
|
||||||
|
`lib/passkey-config.ts` derives `rpID` and `origin` from `WEB_APP_URL`, **not** from `BETTER_AUTH_URL`:
|
||||||
|
WebAuthn runs in the browser, where the web origin is `:7153` in dev and the public web domain in
|
||||||
|
production. Sign-in is username-less, so the plugin is configured with `residentKey: 'required'`.
|
||||||
|
Passkeys are bound to the domain: those registered on `localhost` do not work in production (and vice
|
||||||
|
versa). The `Passkey`/`passkeys` Prisma model is mapped by hand like the rest of the schema; the plugin
|
||||||
|
also runs `prisma migrate deploy` before starting in production.
|
||||||
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
- **Prisma 7**: the generator is `prisma-client` and writes to `apps/api/src/generated/prisma` (gitignored), so
|
||||||
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
import it as `@/generated/prisma/client` — never `@prisma/client` directly. The client uses the
|
||||||
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
`@prisma/adapter-pg` adapter with `DATABASE_URL` and is exported as `prisma` (plus the `Database` type) from
|
||||||
@@ -215,9 +227,10 @@ export class CreateAlert {
|
|||||||
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
the generated migration under `apps/api/prisma/migrations` — never edit migration files by hand. The
|
||||||
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
datasource has no `url` in the schema: it comes from `prisma.config.ts` (`env('DATABASE_URL')`). For
|
||||||
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
production, `apps/api` also has `db:deploy` (`prisma migrate deploy`), which is not wired to a turbo task yet.
|
||||||
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`) are already in the schema and follow the
|
- The BetterAuth models (`User`, `Session`, `Account`, `Verification`, `Passkey`) are already in the schema and
|
||||||
naming convention above (`users`, `sessions`, `accounts`, `verifications` with snake_case columns); regenerate
|
follow the naming convention above (`users`, `sessions`, `accounts`, `verifications`, `passkeys` with
|
||||||
them with the BetterAuth CLI rather than by hand if the auth config changes, then re-apply the mapping.
|
snake_case columns); regenerate them with the BetterAuth CLI rather than by hand if the auth config changes,
|
||||||
|
then re-apply the mapping. `Passkey` comes from the `@better-auth/passkey` plugin, not the core CLI.
|
||||||
|
|
||||||
## Shared package (`@superlist/shared`)
|
## Shared package (`@superlist/shared`)
|
||||||
|
|
||||||
@@ -268,6 +281,14 @@ apps/web/src/
|
|||||||
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
hook (`use-list-events.ts`) reuses it, so the browser calls `/api/*` on the current origin: Vite proxies it
|
||||||
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
to `:4100` in dev and nginx does in production. `VITE_API_URL` is an optional override for a separate API
|
||||||
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
origin, and `auth-client.ts` defaults `baseURL` to `window.location.origin` (BetterAuth appends `/api/auth`).
|
||||||
|
- **Icon badge**: the installed PWA shows the pending items of the primary list on its icon through the Badging
|
||||||
|
API (`lib/app-badge.ts`). `hooks/use-app-badge.ts`, mounted by the authenticated layout, follows that list's
|
||||||
|
SSE stream even from other pages (the shared `lib/list-events-stream.ts` avoids opening a second stream) and
|
||||||
|
re-syncs on foreground. It only runs in standalone mode; iOS additionally needs notification permission,
|
||||||
|
requested from the settings card (`components/settings/app-badge-card.tsx`) because WebKit only grants
|
||||||
|
badging alongside notifications. Chrome on Android does not support numeric badges (notifications show a
|
||||||
|
dot), so this is a progressive enhancement. Updating the badge while the app is closed would need Web Push,
|
||||||
|
which is not implemented.
|
||||||
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
- **Forms: React Hook Form + Zod** (`zodResolver`). Render errors with the shadcn `Field`/`FieldError`
|
||||||
components — this registry version ships `field` instead of the older `form` component.
|
components — this registry version ships `field` instead of the older `form` component.
|
||||||
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
- **shadcn/ui**: components live in `src/components/ui` and are source, not generated output — edit them
|
||||||
|
|||||||
2
STACK.md
2
STACK.md
@@ -5,4 +5,4 @@
|
|||||||
- Rutas del frontend con TanStack Router usando file-based routing
|
- Rutas del frontend con TanStack Router usando file-based routing
|
||||||
- Estado del servidor en el frontend con TanStack Query
|
- Estado del servidor en el frontend con TanStack Query
|
||||||
- Formularios del frontend con React Hook Form + Zod
|
- Formularios del frontend con React Hook Form + Zod
|
||||||
- BetterAuth para autenticación
|
- BetterAuth para autenticación (email + contraseña, OTP por correo y passkeys/WebAuthn)
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ NODE_ENV="development"
|
|||||||
# RESEND_API_KEY="re_xxxxxxxx"
|
# RESEND_API_KEY="re_xxxxxxxx"
|
||||||
# From address for outgoing email (must be a verified Resend sender)
|
# From address for outgoing email (must be a verified Resend sender)
|
||||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||||
# Public URL of the web app, used to build the accept-invitation links
|
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||||
|
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||||
|
# public origin users open in the browser.
|
||||||
WEB_APP_URL="http://localhost:7153"
|
WEB_APP_URL="http://localhost:7153"
|
||||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||||
@@ -20,3 +22,10 @@ WEB_APP_URL="http://localhost:7153"
|
|||||||
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
# GEMINI_MODEL="gemma-4-26b-a4b-it"
|
||||||
# Optional: timeout of the model request, in milliseconds
|
# Optional: timeout of the model request, in milliseconds
|
||||||
# GEMINI_TIMEOUT_MS="8000"
|
# GEMINI_TIMEOUT_MS="8000"
|
||||||
|
# Dictation: Groq API key, backend only (NEVER prefix it with VITE_). When set, Groq
|
||||||
|
# splits dictated text instead of Gemini; it is faster and steadier.
|
||||||
|
# GROQ_API_KEY=""
|
||||||
|
# Optional: model id
|
||||||
|
# GROQ_MODEL="openai/gpt-oss-120b"
|
||||||
|
# Optional: timeout of the model request, in milliseconds
|
||||||
|
# GROQ_TIMEOUT_MS="8000"
|
||||||
|
|||||||
@@ -16,6 +16,7 @@
|
|||||||
"db:studio": "prisma studio"
|
"db:studio": "prisma studio"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@hono/zod-validator": "^0.9.1",
|
"@hono/zod-validator": "^0.9.1",
|
||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "passkeys" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"name" TEXT,
|
||||||
|
"public_key" TEXT NOT NULL,
|
||||||
|
"user_id" TEXT NOT NULL,
|
||||||
|
"credential_id" TEXT NOT NULL,
|
||||||
|
"counter" INTEGER NOT NULL,
|
||||||
|
"device_type" TEXT NOT NULL,
|
||||||
|
"backed_up" BOOLEAN NOT NULL,
|
||||||
|
"transports" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"aaguid" TEXT,
|
||||||
|
|
||||||
|
CONSTRAINT "passkeys_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "passkeys_user_id_idx" ON "passkeys"("user_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "passkeys_credential_id_idx" ON "passkeys"("credential_id");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "passkeys" ADD CONSTRAINT "passkeys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -34,6 +34,7 @@ model User {
|
|||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
sessions Session[]
|
sessions Session[]
|
||||||
accounts Account[]
|
accounts Account[]
|
||||||
|
passkeys Passkey[]
|
||||||
ownedLists ShoppingList[] @relation("ListOwner")
|
ownedLists ShoppingList[] @relation("ListOwner")
|
||||||
memberships ShoppingListMember[]
|
memberships ShoppingListMember[]
|
||||||
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
||||||
@@ -90,6 +91,29 @@ model Verification {
|
|||||||
@@map("verifications")
|
@@map("verifications")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WebAuthn credentials registered through the BetterAuth passkey plugin.
|
||||||
|
// `credentialID` is the raw credential id and `publicKey` the stored public key;
|
||||||
|
// the plugin reads and writes these rows directly, so keep the column names it
|
||||||
|
// expects (mapped to snake_case like the rest of the schema).
|
||||||
|
model Passkey {
|
||||||
|
id String @id
|
||||||
|
name String?
|
||||||
|
publicKey String @map("public_key")
|
||||||
|
userId String @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
credentialID String @map("credential_id")
|
||||||
|
counter Int
|
||||||
|
deviceType String @map("device_type")
|
||||||
|
backedUp Boolean @map("backed_up")
|
||||||
|
transports String?
|
||||||
|
createdAt DateTime? @default(now()) @map("created_at")
|
||||||
|
aaguid String?
|
||||||
|
|
||||||
|
@@index([userId])
|
||||||
|
@@index([credentialID])
|
||||||
|
@@map("passkeys")
|
||||||
|
}
|
||||||
|
|
||||||
// --- Domain models ----------------------------------------------------------
|
// --- Domain models ----------------------------------------------------------
|
||||||
|
|
||||||
/// A collaborative shopping list. Membership (and therefore access) lives in
|
/// A collaborative shopping list. Membership (and therefore access) lives in
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { passkey } from '@better-auth/passkey'
|
||||||
import { betterAuth } from 'better-auth'
|
import { betterAuth } from 'better-auth'
|
||||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||||
import { emailOTP } from 'better-auth/plugins'
|
import { emailOTP } from 'better-auth/plugins'
|
||||||
@@ -6,6 +7,7 @@ import { passwordResetEmail } from '@/lib/emails/password-reset'
|
|||||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||||
import { logger } from '@/lib/logger'
|
import { logger } from '@/lib/logger'
|
||||||
import { sendEmail } from '@/lib/mailer'
|
import { sendEmail } from '@/lib/mailer'
|
||||||
|
import { passkeyConfig } from '@/lib/passkey-config'
|
||||||
import { prisma } from '@/lib/prisma'
|
import { prisma } from '@/lib/prisma'
|
||||||
|
|
||||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||||
@@ -57,6 +59,15 @@ export const auth = betterAuth({
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
// Passkeys (Face ID, Touch ID, Windows Hello, security keys). Sign-in is
|
||||||
|
// username-less, so credentials must be discoverable: `residentKey` is
|
||||||
|
// required instead of the plugin's `preferred` default.
|
||||||
|
passkey({
|
||||||
|
...passkeyConfig,
|
||||||
|
authenticatorSelection: {
|
||||||
|
residentKey: 'required',
|
||||||
|
},
|
||||||
|
}),
|
||||||
],
|
],
|
||||||
databaseHooks: {
|
databaseHooks: {
|
||||||
user: {
|
user: {
|
||||||
|
|||||||
@@ -6,9 +6,21 @@
|
|||||||
* key in the browser bundle):
|
* key in the browser bundle):
|
||||||
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`.
|
* - `GEMINI_API_KEY`: AI Studio API key. Without it every call fails with `missing-key`.
|
||||||
* - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default.
|
* - `GEMINI_MODEL`: model id, `gemma-4-26b-a4b-it` by default.
|
||||||
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default.
|
* - `GEMINI_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included).
|
||||||
|
*
|
||||||
|
* Gemma 4 writes out its reasoning before answering, which takes from 5 to over 30
|
||||||
|
* seconds, so the request asks for `thinkingLevel: 'minimal'` (about a second). The API
|
||||||
|
* also answers 5xx now and then, fast; those calls are retried once.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
type GenerateInput,
|
||||||
|
ModelError,
|
||||||
|
postJson,
|
||||||
|
readTimeout,
|
||||||
|
type TextGenerator,
|
||||||
|
} from './text-generator'
|
||||||
|
|
||||||
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
|
const GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models'
|
||||||
|
|
||||||
/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
|
/** Gemma 4's small, fast variant (a mixture of experts with ~4B active parameters). */
|
||||||
@@ -24,90 +36,38 @@ export type GeminiConfig = {
|
|||||||
|
|
||||||
/** Reads the configuration from the environment, with the defaults above. */
|
/** Reads the configuration from the environment, with the defaults above. */
|
||||||
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
export function geminiConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||||
const timeout = Number.parseInt(env.GEMINI_TIMEOUT_MS ?? '', 10)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
apiKey: env.GEMINI_API_KEY?.trim() || undefined,
|
||||||
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
model: env.GEMINI_MODEL?.trim() || DEFAULT_GEMINI_MODEL,
|
||||||
timeoutMs: Number.isFinite(timeout) && timeout > 0 ? timeout : DEFAULT_GEMINI_TIMEOUT_MS,
|
timeoutMs: readTimeout(env.GEMINI_TIMEOUT_MS, DEFAULT_GEMINI_TIMEOUT_MS),
|
||||||
} satisfies GeminiConfig
|
} satisfies GeminiConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Why a call failed, short enough to log (it never includes the prompt). */
|
|
||||||
export type GeminiFailureReason =
|
|
||||||
| 'missing-key'
|
|
||||||
| 'timeout'
|
|
||||||
| 'rate-limited'
|
|
||||||
| `http-${number}`
|
|
||||||
| 'network'
|
|
||||||
| 'empty-response'
|
|
||||||
|
|
||||||
export class GeminiError extends Error {
|
|
||||||
constructor(readonly reason: GeminiFailureReason) {
|
|
||||||
super(`Gemini request failed: ${reason}`)
|
|
||||||
this.name = 'GeminiError'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
|
||||||
export type GeminiTurn = { role: 'user' | 'model'; text: string }
|
|
||||||
|
|
||||||
export type GenerateInput = {
|
|
||||||
systemInstruction: string
|
|
||||||
turns: GeminiTurn[]
|
|
||||||
}
|
|
||||||
|
|
||||||
type GenerateContentResponse = {
|
type GenerateContentResponse = {
|
||||||
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
candidates?: { content?: { parts?: { text?: string; thought?: boolean }[] } }[]
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Something that answers a prompt with text: the Gemini client, or a fake in tests. */
|
|
||||||
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
|
||||||
|
|
||||||
export class GeminiClient implements TextGenerator {
|
export class GeminiClient implements TextGenerator {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
private readonly config: GeminiConfig = geminiConfigFromEnv(),
|
||||||
private readonly fetchFn: typeof fetch = fetch,
|
private readonly fetchFn: typeof fetch = fetch,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** The model's text answer. Throws `GeminiError` on any failure. */
|
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||||
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||||
if (!this.config.apiKey) throw new GeminiError('missing-key')
|
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||||
|
|
||||||
let response: Response
|
const body = (await postJson(
|
||||||
try {
|
this.fetchFn,
|
||||||
response = await this.fetchFn(
|
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
||||||
`${GEMINI_API_URL}/${encodeURIComponent(this.config.model)}:generateContent`,
|
{ 'x-goog-api-key': this.config.apiKey },
|
||||||
{
|
{
|
||||||
method: 'POST',
|
systemInstruction: { parts: [{ text: systemInstruction }] },
|
||||||
headers: { 'content-type': 'application/json', 'x-goog-api-key': this.config.apiKey },
|
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
||||||
body: JSON.stringify({
|
generationConfig: { temperature: 0, thinkingConfig: { thinkingLevel: 'minimal' } },
|
||||||
systemInstruction: { parts: [{ text: systemInstruction }] },
|
},
|
||||||
contents: turns.map(({ role, text }) => ({ role, parts: [{ text }] })),
|
this.config.timeoutMs,
|
||||||
generationConfig: { temperature: 0 },
|
)) as GenerateContentResponse
|
||||||
}),
|
|
||||||
signal: AbortSignal.timeout(this.config.timeoutMs),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
} catch (error) {
|
|
||||||
const name = error instanceof Error ? error.name : ''
|
|
||||||
throw new GeminiError(
|
|
||||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (response.status === 429) throw new GeminiError('rate-limited')
|
|
||||||
if (!response.ok) throw new GeminiError(`http-${response.status}`)
|
|
||||||
|
|
||||||
let body: GenerateContentResponse
|
|
||||||
try {
|
|
||||||
body = (await response.json()) as GenerateContentResponse
|
|
||||||
} catch (error) {
|
|
||||||
const name = error instanceof Error ? error.name : ''
|
|
||||||
throw new GeminiError(
|
|
||||||
name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'empty-response',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
// Thinking models may send their reasoning as `thought` parts: only the answer counts.
|
||||||
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
const text = (body.candidates?.[0]?.content?.parts ?? [])
|
||||||
@@ -116,7 +76,7 @@ export class GeminiClient implements TextGenerator {
|
|||||||
.join('')
|
.join('')
|
||||||
.trim()
|
.trim()
|
||||||
|
|
||||||
if (!text) throw new GeminiError('empty-response')
|
if (!text) throw new ModelError('empty-response')
|
||||||
|
|
||||||
return text
|
return text
|
||||||
}
|
}
|
||||||
|
|||||||
79
apps/api/src/lib/groq.ts
Normal file
79
apps/api/src/lib/groq.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* Minimal client for Groq's OpenAI-compatible `chat/completions` endpoint, called with
|
||||||
|
* `fetch` — no SDK. Groq answers in about a second, which suits dictation. The model is
|
||||||
|
* a reasoning one (gpt-oss): Groq returns its reasoning apart, so `content` is the answer.
|
||||||
|
*
|
||||||
|
* Configuration (backend only — never prefix these with `VITE_`, or Vite would put the
|
||||||
|
* key in the browser bundle):
|
||||||
|
* - `GROQ_API_KEY`: Groq API key (`gsk_…`). Without it every call fails with `missing-key`.
|
||||||
|
* - `GROQ_MODEL`: model id, `openai/gpt-oss-120b` by default.
|
||||||
|
* - `GROQ_TIMEOUT_MS`: request timeout, 8000 ms by default (retries included).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
type GenerateInput,
|
||||||
|
ModelError,
|
||||||
|
postJson,
|
||||||
|
readTimeout,
|
||||||
|
type TextGenerator,
|
||||||
|
} from './text-generator'
|
||||||
|
|
||||||
|
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions'
|
||||||
|
|
||||||
|
export const DEFAULT_GROQ_MODEL = 'openai/gpt-oss-120b'
|
||||||
|
|
||||||
|
export const DEFAULT_GROQ_TIMEOUT_MS = 8000
|
||||||
|
|
||||||
|
export type GroqConfig = {
|
||||||
|
apiKey: string | undefined
|
||||||
|
model: string
|
||||||
|
timeoutMs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads the configuration from the environment, with the defaults above. */
|
||||||
|
export function groqConfigFromEnv(env: Record<string, string | undefined> = process.env) {
|
||||||
|
return {
|
||||||
|
apiKey: env.GROQ_API_KEY?.trim() || undefined,
|
||||||
|
model: env.GROQ_MODEL?.trim() || DEFAULT_GROQ_MODEL,
|
||||||
|
timeoutMs: readTimeout(env.GROQ_TIMEOUT_MS, DEFAULT_GROQ_TIMEOUT_MS),
|
||||||
|
} satisfies GroqConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
type ChatCompletionResponse = {
|
||||||
|
choices?: { message?: { content?: string | null } }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GroqClient implements TextGenerator {
|
||||||
|
constructor(
|
||||||
|
private readonly config: GroqConfig = groqConfigFromEnv(),
|
||||||
|
private readonly fetchFn: typeof fetch = fetch,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** The model's text answer. Throws `ModelError` on any failure. */
|
||||||
|
async generate({ systemInstruction, turns }: GenerateInput): Promise<string> {
|
||||||
|
if (!this.config.apiKey) throw new ModelError('missing-key')
|
||||||
|
|
||||||
|
const body = (await postJson(
|
||||||
|
this.fetchFn,
|
||||||
|
GROQ_API_URL,
|
||||||
|
{ authorization: `Bearer ${this.config.apiKey}` },
|
||||||
|
{
|
||||||
|
model: this.config.model,
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: systemInstruction },
|
||||||
|
...turns.map(({ role, text }) => ({
|
||||||
|
role: role === 'model' ? 'assistant' : 'user',
|
||||||
|
content: text,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
temperature: 0,
|
||||||
|
},
|
||||||
|
this.config.timeoutMs,
|
||||||
|
)) as ChatCompletionResponse
|
||||||
|
|
||||||
|
const text = body.choices?.[0]?.message?.content?.trim()
|
||||||
|
if (!text) throw new ModelError('empty-response')
|
||||||
|
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
}
|
||||||
17
apps/api/src/lib/model.ts
Normal file
17
apps/api/src/lib/model.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { GeminiClient, geminiConfigFromEnv } from './gemini'
|
||||||
|
import { GroqClient, groqConfigFromEnv } from './groq'
|
||||||
|
import type { TextGenerator } from './text-generator'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The model the API asks: Groq when `GROQ_API_KEY` is set (fast and steady), Gemini /
|
||||||
|
* Gemma otherwise. Without any key the Gemini client fails with `missing-key` and
|
||||||
|
* callers fall back to their own non-AI path.
|
||||||
|
*/
|
||||||
|
export function createTextGenerator(
|
||||||
|
env: Record<string, string | undefined> = process.env,
|
||||||
|
): TextGenerator {
|
||||||
|
const groq = groqConfigFromEnv(env)
|
||||||
|
if (groq.apiKey) return new GroqClient(groq)
|
||||||
|
|
||||||
|
return new GeminiClient(geminiConfigFromEnv(env))
|
||||||
|
}
|
||||||
37
apps/api/src/lib/passkey-config.test.ts
Normal file
37
apps/api/src/lib/passkey-config.test.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test'
|
||||||
|
|
||||||
|
import { passkeyOrigins } from './passkey-config'
|
||||||
|
|
||||||
|
describe('passkeyOrigins', () => {
|
||||||
|
test('keeps the development port in the origin but not in the RP ID', () => {
|
||||||
|
expect(passkeyOrigins('http://localhost:7153')).toEqual({
|
||||||
|
origin: 'http://localhost:7153',
|
||||||
|
rpID: 'localhost',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('normalises trailing slashes and paths to a bare origin', () => {
|
||||||
|
expect(passkeyOrigins('https://superlist.app/')).toEqual({
|
||||||
|
origin: 'https://superlist.app',
|
||||||
|
rpID: 'superlist.app',
|
||||||
|
})
|
||||||
|
expect(passkeyOrigins('https://superlist.app/settings')).toEqual({
|
||||||
|
origin: 'https://superlist.app',
|
||||||
|
rpID: 'superlist.app',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uses a subdomain as the RP ID', () => {
|
||||||
|
expect(passkeyOrigins('https://app.superlist.app')).toEqual({
|
||||||
|
origin: 'https://app.superlist.app',
|
||||||
|
rpID: 'app.superlist.app',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('falls back to localhost when the URL is invalid', () => {
|
||||||
|
expect(passkeyOrigins('not a url')).toEqual({
|
||||||
|
origin: 'http://localhost:7153',
|
||||||
|
rpID: 'localhost',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
30
apps/api/src/lib/passkey-config.ts
Normal file
30
apps/api/src/lib/passkey-config.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { webAppUrl } from '@/lib/web-app-url'
|
||||||
|
|
||||||
|
const FALLBACK_ORIGIN = 'http://localhost:7153'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebAuthn ceremonies happen in the browser, so the relying party is the public
|
||||||
|
* web origin, not the API one: in development the web runs on :7153 while the
|
||||||
|
* API listens on :4100. `WEB_APP_URL` is already the canonical public URL of
|
||||||
|
* the frontend (used for invitation links), so derive both values from it.
|
||||||
|
*
|
||||||
|
* The RP ID must be a registrable suffix of the origin and cannot include the
|
||||||
|
* port; `new URL().hostname` does the right thing for both `localhost` and a
|
||||||
|
* production domain.
|
||||||
|
*/
|
||||||
|
export function passkeyOrigins(webUrl: string) {
|
||||||
|
let origin: string
|
||||||
|
|
||||||
|
try {
|
||||||
|
origin = new URL(webUrl).origin
|
||||||
|
} catch {
|
||||||
|
origin = FALLBACK_ORIGIN
|
||||||
|
}
|
||||||
|
|
||||||
|
return { origin, rpID: new URL(origin).hostname }
|
||||||
|
}
|
||||||
|
|
||||||
|
export const passkeyConfig = {
|
||||||
|
...passkeyOrigins(webAppUrl),
|
||||||
|
rpName: 'Superlist',
|
||||||
|
}
|
||||||
89
apps/api/src/lib/text-generator.ts
Normal file
89
apps/api/src/lib/text-generator.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
/**
|
||||||
|
* What every model client shares: the prompt shape, the `TextGenerator` contract and the
|
||||||
|
* HTTP call with its deadline, retry and error reasons. The clients themselves
|
||||||
|
* (`gemini.ts`, `groq.ts`) only build the request body and read the answer.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Attempts per call when the API answers 5xx (those fail fast and often pass on retry). */
|
||||||
|
const MAX_ATTEMPTS = 2
|
||||||
|
|
||||||
|
/** One turn of the conversation: `user` for the input, `model` for an example answer. */
|
||||||
|
export type ModelTurn = { role: 'user' | 'model'; text: string }
|
||||||
|
|
||||||
|
export type GenerateInput = {
|
||||||
|
systemInstruction: string
|
||||||
|
turns: ModelTurn[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Something that answers a prompt with text: a model client, or a fake in tests. */
|
||||||
|
export type TextGenerator = { generate(input: GenerateInput): Promise<string> }
|
||||||
|
|
||||||
|
/** Why a call failed, short enough to log (it never includes the prompt). */
|
||||||
|
export type ModelFailureReason =
|
||||||
|
| 'missing-key'
|
||||||
|
| 'timeout'
|
||||||
|
| 'rate-limited'
|
||||||
|
| `http-${number}`
|
||||||
|
| 'network'
|
||||||
|
| 'empty-response'
|
||||||
|
|
||||||
|
export class ModelError extends Error {
|
||||||
|
constructor(readonly reason: ModelFailureReason) {
|
||||||
|
super(`Model request failed: ${reason}`)
|
||||||
|
this.name = 'ModelError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads a positive number of milliseconds, or `fallback` when it is missing or invalid. */
|
||||||
|
export function readTimeout(value: string | undefined, fallback: number): number {
|
||||||
|
const timeout = Number.parseInt(value ?? '', 10)
|
||||||
|
|
||||||
|
return Number.isFinite(timeout) && timeout > 0 ? timeout : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function isAbort(error: unknown): boolean {
|
||||||
|
const name = error instanceof Error ? error.name : ''
|
||||||
|
|
||||||
|
return name === 'TimeoutError' || name === 'AbortError'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POSTs `body` as JSON and returns the parsed answer. A 5xx is retried once, all attempts
|
||||||
|
* within one `timeoutMs` deadline so a retry never makes the user wait longer. Throws
|
||||||
|
* `ModelError` on any failure.
|
||||||
|
*/
|
||||||
|
export async function postJson(
|
||||||
|
fetchFn: typeof fetch,
|
||||||
|
url: string,
|
||||||
|
headers: Record<string, string>,
|
||||||
|
body: unknown,
|
||||||
|
timeoutMs: number,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const init = {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json', ...headers },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
}
|
||||||
|
|
||||||
|
let response: Response | undefined
|
||||||
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
|
try {
|
||||||
|
response = await fetchFn(url, init)
|
||||||
|
} catch (error) {
|
||||||
|
throw new ModelError(isAbort(error) ? 'timeout' : 'network')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status < 500) break
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response) throw new ModelError('network')
|
||||||
|
if (response.status === 429) throw new ModelError('rate-limited')
|
||||||
|
if (!response.ok) throw new ModelError(`http-${response.status}`)
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await response.json()
|
||||||
|
} catch (error) {
|
||||||
|
throw new ModelError(isAbort(error) ? 'timeout' : 'empty-response')
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
import { VOICE_SPLIT_EXAMPLES } from '@superlist/shared'
|
||||||
|
|
||||||
import type { GeminiTurn, GenerateInput } from '@/lib/gemini'
|
import type { GenerateInput, ModelTurn } from '@/lib/text-generator'
|
||||||
|
|
||||||
/** What the model is told to do. Gemma accepts it as `systemInstruction`. */
|
/** What the model is told to do. Gemma accepts it as `systemInstruction`. */
|
||||||
export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense.
|
export const SPLIT_INSTRUCTION = `Sos un asistente que arma listas de compras en español rioplatense.
|
||||||
@@ -8,6 +8,7 @@ Recibís la transcripción de lo que alguien dictó y respondés SOLO con un arr
|
|||||||
|
|
||||||
Reglas:
|
Reglas:
|
||||||
- Un elemento por producto.
|
- Un elemento por producto.
|
||||||
|
- La transcripción casi nunca trae comas: los productos nombrados uno tras otro son elementos distintos ("azúcar leche y café" son 3), salvo que juntos formen un solo producto ("dulce de leche", "queso crema", "pan rallado").
|
||||||
- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg.
|
- Números en dígitos: "dos" → 2, "media docena" → 6, "una docena" → 12, "un kilo" → 1 kg, "un kilo y medio" → 1,5 kg.
|
||||||
- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes".
|
- Unidades abreviadas: g, kg, ml, l. Los envases quedan como palabra: "1 lata", "2 paquetes".
|
||||||
- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".
|
- La cantidad va al principio: "2 l de leche", "400 g de queso", "12 huevos".
|
||||||
@@ -18,7 +19,7 @@ Reglas:
|
|||||||
|
|
||||||
/** The conversation sent to the model: the few-shot examples, then the transcript. */
|
/** The conversation sent to the model: the few-shot examples, then the transcript. */
|
||||||
export function buildSplitPrompt(text: string): GenerateInput {
|
export function buildSplitPrompt(text: string): GenerateInput {
|
||||||
const examples: GeminiTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
|
const examples: ModelTurn[] = VOICE_SPLIT_EXAMPLES.flatMap(({ said, items }) => [
|
||||||
{ role: 'user' as const, text: said },
|
{ role: 'user' as const, text: said },
|
||||||
{ role: 'model' as const, text: JSON.stringify(items) },
|
{ role: 'model' as const, text: JSON.stringify(items) },
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -52,6 +52,10 @@ beforeEach(() => {
|
|||||||
process.env.GEMINI_API_KEY = 'test-key'
|
process.env.GEMINI_API_KEY = 'test-key'
|
||||||
process.env.GEMINI_MODEL = 'gemma-test'
|
process.env.GEMINI_MODEL = 'gemma-test'
|
||||||
process.env.GEMINI_TIMEOUT_MS = '50'
|
process.env.GEMINI_TIMEOUT_MS = '50'
|
||||||
|
// `bun test` loads `.env`: a real Groq key there would take over these Gemini tests.
|
||||||
|
delete process.env.GROQ_API_KEY
|
||||||
|
delete process.env.GROQ_MODEL
|
||||||
|
delete process.env.GROQ_TIMEOUT_MS
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -120,6 +124,32 @@ describe('POST /api/voice/split', () => {
|
|||||||
expect(JSON.stringify(warnings)).toContain('invalid-json')
|
expect(JSON.stringify(warnings)).toContain('invalid-json')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('asks for minimal thinking and retries a 5xx once', async () => {
|
||||||
|
let calls = 0
|
||||||
|
const fetchMock = mockFetch(async () =>
|
||||||
|
++calls === 1
|
||||||
|
? new Response('{}', { status: 500 })
|
||||||
|
: modelAnswer('["Azúcar", "Leche", "Café"]'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const response = await split({ text: 'azúcar leche y café' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
const sent = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))
|
||||||
|
expect(sent.generationConfig.thinkingConfig).toEqual({ thinkingLevel: 'minimal' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when the model answers 5xx twice', async () => {
|
||||||
|
const fetchMock = mockFetch(async () => new Response('{}', { status: 503 }))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan y leche' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'leche'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
expect(JSON.stringify(warnings)).toContain('http-503')
|
||||||
|
})
|
||||||
|
|
||||||
it('falls back without calling the model when there is no API key', async () => {
|
it('falls back without calling the model when there is no API key', async () => {
|
||||||
delete process.env.GEMINI_API_KEY
|
delete process.env.GEMINI_API_KEY
|
||||||
const fetchMock = mockFetch(async () => modelAnswer('[]'))
|
const fetchMock = mockFetch(async () => modelAnswer('[]'))
|
||||||
@@ -149,3 +179,67 @@ describe('POST /api/voice/split', () => {
|
|||||||
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
|
expect(sent.contents.at(-1).parts[0].text).toHaveLength(500)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('POST /api/voice/split with Groq', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
process.env.GROQ_API_KEY = 'gsk_test'
|
||||||
|
process.env.GROQ_MODEL = 'llama-test'
|
||||||
|
process.env.GROQ_TIMEOUT_MS = '50'
|
||||||
|
})
|
||||||
|
|
||||||
|
function groqAnswer(content: string) {
|
||||||
|
return Response.json({ choices: [{ message: { role: 'assistant', content } }] })
|
||||||
|
}
|
||||||
|
|
||||||
|
it('asks Groq instead of Gemini when its key is set', async () => {
|
||||||
|
const fetchMock = mockFetch(async () => groqAnswer('["Azúcar", "Leche", "Café"]'))
|
||||||
|
|
||||||
|
const response = await split({ text: 'azúcar leche y café' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Azúcar', 'Leche', 'Café'] })
|
||||||
|
expect(warnings).toHaveLength(0)
|
||||||
|
|
||||||
|
const [url, init] = fetchMock.mock.calls[0] ?? []
|
||||||
|
expect(url).toBe('https://api.groq.com/openai/v1/chat/completions')
|
||||||
|
expect(new Headers(init?.headers).get('authorization')).toBe('Bearer gsk_test')
|
||||||
|
const sent = JSON.parse(String(init?.body))
|
||||||
|
expect(sent.model).toBe('llama-test')
|
||||||
|
expect(sent.temperature).toBe(0)
|
||||||
|
expect(sent.messages[0]).toEqual({
|
||||||
|
role: 'system',
|
||||||
|
content: expect.stringContaining('array JSON'),
|
||||||
|
})
|
||||||
|
expect(sent.messages[2].role).toBe('assistant')
|
||||||
|
expect(sent.messages.at(-1)).toEqual({ role: 'user', content: 'azúcar leche y café' })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('retries a 5xx once', async () => {
|
||||||
|
let calls = 0
|
||||||
|
const fetchMock = mockFetch(async () =>
|
||||||
|
++calls === 1 ? new Response('{}', { status: 502 }) : groqAnswer('["Pan"]'),
|
||||||
|
)
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['Pan'] })
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when Groq is rate limited (429)', async () => {
|
||||||
|
mockFetch(async () => new Response('{}', { status: 429 }))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan y queso' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||||
|
expect(JSON.stringify(warnings)).toContain('rate-limited')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('falls back when Groq answers with no content', async () => {
|
||||||
|
mockFetch(async () => groqAnswer(''))
|
||||||
|
|
||||||
|
const response = await split({ text: 'pan, queso' })
|
||||||
|
|
||||||
|
expect(await response.json()).toEqual({ items: ['pan', 'queso'] })
|
||||||
|
expect(JSON.stringify(warnings)).toContain('empty-response')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Hono } from 'hono'
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
import { requireSession } from '@/lib/auth-session'
|
import { requireSession } from '@/lib/auth-session'
|
||||||
import { GeminiClient } from '@/lib/gemini'
|
import { createTextGenerator } from '@/lib/model'
|
||||||
import { resultJson } from '@/lib/result-json'
|
import { resultJson } from '@/lib/result-json'
|
||||||
import { validate } from '@/lib/validate'
|
import { validate } from '@/lib/validate'
|
||||||
import type { AppEnv } from '@/types'
|
import type { AppEnv } from '@/types'
|
||||||
@@ -16,7 +16,9 @@ export const splitVoiceRoute = new Hono<AppEnv>().post(
|
|||||||
validate.json(SplitVoiceSchema),
|
validate.json(SplitVoiceSchema),
|
||||||
async (c) => {
|
async (c) => {
|
||||||
const { text } = c.req.valid('json')
|
const { text } = c.req.valid('json')
|
||||||
const result = await new SplitVoiceText(new GeminiClient(), c.get('logger')).execute({ text })
|
const result = await new SplitVoiceText(createTextGenerator(), c.get('logger')).execute({
|
||||||
|
text,
|
||||||
|
})
|
||||||
|
|
||||||
return resultJson(c, result)
|
return resultJson(c, result)
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ import {
|
|||||||
type VoiceSplitResponse,
|
type VoiceSplitResponse,
|
||||||
} from '@superlist/shared'
|
} from '@superlist/shared'
|
||||||
|
|
||||||
import { GeminiError, type TextGenerator } from '@/lib/gemini'
|
|
||||||
import type { Logger } from '@/lib/logger'
|
import type { Logger } from '@/lib/logger'
|
||||||
|
import { ModelError, type TextGenerator } from '@/lib/text-generator'
|
||||||
|
|
||||||
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
import { cleanItems, fallbackSplit, parseModelItems } from './items'
|
||||||
import { buildSplitPrompt } from './prompt'
|
import { buildSplitPrompt } from './prompt'
|
||||||
@@ -36,7 +36,7 @@ export class SplitVoiceText {
|
|||||||
try {
|
try {
|
||||||
answer = await this.model.generate(buildSplitPrompt(text))
|
answer = await this.model.generate(buildSplitPrompt(text))
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return this.fallback(text, error instanceof GeminiError ? error.reason : 'unexpected-error')
|
return this.fallback(text, error instanceof ModelError ? error.reason : 'unexpected-error')
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = parseModelItems(answer)
|
const items = parseModelItems(answer)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"test": "vitest run --passWithNoTests"
|
"test": "vitest run --passWithNoTests"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@fontsource-variable/geist": "^5.3.0",
|
"@fontsource-variable/geist": "^5.3.0",
|
||||||
"@hookform/resolvers": "^5.9.1",
|
"@hookform/resolvers": "^5.9.1",
|
||||||
"@superlist/shared": "workspace:*",
|
"@superlist/shared": "workspace:*",
|
||||||
|
|||||||
10
apps/web/src/components/app-badge.tsx
Normal file
10
apps/web/src/components/app-badge.tsx
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { useAppBadge } from '@/hooks/use-app-badge'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the installed app's icon badge in sync with the primary list. It renders
|
||||||
|
* nothing: the icon lives outside the page.
|
||||||
|
*/
|
||||||
|
export function AppBadge() {
|
||||||
|
useAppBadge()
|
||||||
|
return null
|
||||||
|
}
|
||||||
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
161
apps/web/src/components/items/dictate-fab.tsx
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
import { Loader2Icon, MicIcon, SquareIcon, XIcon } from 'lucide-react'
|
||||||
|
import { useRef, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { refocusNewItemInput } from '@/components/items/create-item-form'
|
||||||
|
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Sheet,
|
||||||
|
SheetClose,
|
||||||
|
SheetContent,
|
||||||
|
SheetDescription,
|
||||||
|
SheetTitle,
|
||||||
|
} from '@/components/ui/sheet'
|
||||||
|
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||||
|
import { DICTATION_MESSAGES } from '@/hooks/use-microphone-dictation'
|
||||||
|
|
||||||
|
type DictateFabProps = {
|
||||||
|
listId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Floating microphone for a list that already has items. An empty list dictates from
|
||||||
|
* its central card; this repeats that experience on a bottom sheet so the rows stay
|
||||||
|
* on screen. The tap opens the sheet and starts listening in the same gesture, which
|
||||||
|
* is what Safari needs to grant the microphone.
|
||||||
|
*/
|
||||||
|
export function DictateFab({ listId }: DictateFabProps) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
// "Escribir a mano" moves the focus to the composer once the sheet is gone.
|
||||||
|
const focusInput = useRef(false)
|
||||||
|
|
||||||
|
const { listening, busy, processing, supported, heard, message, start, stop } = useDictateItems(
|
||||||
|
listId,
|
||||||
|
{
|
||||||
|
onFinish: (added) => added && setOpen(false),
|
||||||
|
// Closing the sheet while it listened can still end in a rejection: show it.
|
||||||
|
onMessage: (detail) => {
|
||||||
|
if (!open) toast.error(detail)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
const label = processing
|
||||||
|
? 'Procesando el dictado'
|
||||||
|
: busy
|
||||||
|
? 'Pidiendo acceso al micrófono'
|
||||||
|
: listening
|
||||||
|
? 'Detener dictado'
|
||||||
|
: 'Dictar ítems'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="icon"
|
||||||
|
aria-label="Dictar ítems"
|
||||||
|
aria-haspopup="dialog"
|
||||||
|
aria-expanded={open}
|
||||||
|
className="fixed right-4 bottom-[calc(4.5rem+env(safe-area-inset-bottom)+0.75rem)] z-40 size-14 rounded-full shadow-lg md:right-6 md:bottom-6"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(true)
|
||||||
|
// Called right in the click, before any state update, so the browser still
|
||||||
|
// treats the microphone request as the user's.
|
||||||
|
start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MicIcon className="size-6" />
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Sheet
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
setOpen(next)
|
||||||
|
// Leaving the sheet ends the dictation: what was heard is delivered, like
|
||||||
|
// "Detener". While the permission is still being asked it just cancels, and
|
||||||
|
// with a request in flight it is a no-op.
|
||||||
|
if (!next) stop()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SheetContent
|
||||||
|
side="bottom"
|
||||||
|
showCloseButton={false}
|
||||||
|
className="max-h-[90dvh] gap-0 overflow-y-auto rounded-t-3xl px-5 pt-3 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:mx-auto sm:max-w-lg"
|
||||||
|
onCloseAutoFocus={(event) => {
|
||||||
|
if (!focusInput.current) return
|
||||||
|
focusInput.current = false
|
||||||
|
event.preventDefault()
|
||||||
|
refocusNewItemInput()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="bg-muted-foreground/30 mx-auto mb-3 h-1 w-10 rounded-full" aria-hidden />
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<SheetTitle className="text-lg font-semibold">Dictar ítems</SheetTitle>
|
||||||
|
<SheetClose asChild>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
size="icon"
|
||||||
|
className="size-11 rounded-full"
|
||||||
|
aria-label="Cerrar"
|
||||||
|
>
|
||||||
|
<XIcon className="size-5" />
|
||||||
|
</Button>
|
||||||
|
</SheetClose>
|
||||||
|
</div>
|
||||||
|
<SheetDescription className="text-muted-foreground mt-1">
|
||||||
|
Di los ítems con una pausa entre cada uno y los añadimos a la lista.
|
||||||
|
</SheetDescription>
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-3 pt-6 pb-2">
|
||||||
|
{supported ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={listening ? 'default' : 'secondary'}
|
||||||
|
aria-label={label}
|
||||||
|
aria-pressed={listening}
|
||||||
|
disabled={busy}
|
||||||
|
className="relative h-12 rounded-full px-6 text-base"
|
||||||
|
onClick={() => {
|
||||||
|
if (listening) stop()
|
||||||
|
else start()
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<Loader2Icon className="size-5 animate-spin" />
|
||||||
|
) : listening ? (
|
||||||
|
<SquareIcon className="size-5 fill-current" />
|
||||||
|
) : (
|
||||||
|
<MicIcon className="size-5" />
|
||||||
|
)}
|
||||||
|
{processing ? 'Procesando…' : listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-muted-foreground max-w-xs text-center text-sm">
|
||||||
|
{DICTATION_MESSAGES.unsupported}
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="secondary"
|
||||||
|
className="h-11 rounded-full px-5"
|
||||||
|
onClick={() => {
|
||||||
|
focusInput.current = true
|
||||||
|
setOpen(false)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Escribir a mano
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</SheetContent>
|
||||||
|
</Sheet>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
import { Loader2Icon, MicIcon, SquareIcon } from 'lucide-react'
|
||||||
import { useState } from 'react'
|
|
||||||
import { toast } from 'sonner'
|
|
||||||
|
|
||||||
|
import { DictationFeedback } from '@/components/items/dictation-feedback'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { useAddItems } from '@/hooks/use-add-items'
|
import { useDictateItems } from '@/hooks/use-dictate-items'
|
||||||
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
|
||||||
|
|
||||||
type DictateItemsButtonProps = {
|
type DictateItemsButtonProps = {
|
||||||
listId: string
|
listId: string
|
||||||
@@ -15,30 +13,13 @@ type DictateItemsButtonProps = {
|
|||||||
* said through the same flow as the input's microphone (split by the API, undoable).
|
* said through the same flow as the input's microphone (split by the API, undoable).
|
||||||
*/
|
*/
|
||||||
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
||||||
const [message, setMessage] = useState<string | null>(null)
|
const { listening, busy, processing, heard, message, start, stop } = useDictateItems(listId)
|
||||||
const { addDictation, processing } = useAddItems(listId, {
|
|
||||||
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
|
||||||
onDictationRejected: (_, detail) => setMessage(detail),
|
|
||||||
})
|
|
||||||
|
|
||||||
const dictation = useMicrophoneDictation({
|
|
||||||
onPhrases: async (phrases) => {
|
|
||||||
const understood = await addDictation(phrases.join('\n'))
|
|
||||||
if (understood === 0) setMessage(DICTATION_MESSAGES.empty)
|
|
||||||
},
|
|
||||||
onError: setMessage,
|
|
||||||
})
|
|
||||||
|
|
||||||
const listening = dictation.status === 'listening'
|
|
||||||
const busy = dictation.status === 'requesting' || processing
|
|
||||||
|
|
||||||
const label = processing
|
const label = processing
|
||||||
? 'Procesando el dictado'
|
? 'Procesando el dictado'
|
||||||
: dictation.status === 'requesting'
|
: listening
|
||||||
? 'Pidiendo acceso al micrófono'
|
? 'Detener dictado'
|
||||||
: listening
|
: 'Dictar ítems'
|
||||||
? 'Detener dictado'
|
|
||||||
: 'Dictar ítems'
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center gap-2">
|
<div className="flex flex-col items-center gap-2">
|
||||||
@@ -50,9 +31,8 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
|||||||
disabled={busy}
|
disabled={busy}
|
||||||
className="relative rounded-full"
|
className="relative rounded-full"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setMessage(null)
|
if (listening) stop()
|
||||||
if (listening) dictation.stop()
|
else start()
|
||||||
else dictation.start()
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{busy ? (
|
{busy ? (
|
||||||
@@ -65,24 +45,7 @@ export function DictateItemsButton({ listId }: DictateItemsButtonProps) {
|
|||||||
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
{listening ? 'Detener dictado' : 'Dictar ítems'}
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<div aria-live="polite" className="flex flex-col items-center gap-1 text-sm">
|
<DictationFeedback listening={listening} heard={heard} message={message} />
|
||||||
{listening && (
|
|
||||||
<p className="text-primary flex items-center gap-2 font-medium">
|
|
||||||
<span className="relative flex size-2.5" aria-hidden="true">
|
|
||||||
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
|
||||||
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
|
||||||
</span>
|
|
||||||
Micrófono activo, te escuchamos
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{listening && dictation.heard && (
|
|
||||||
<p className="text-muted-foreground max-w-xs">{dictation.heard}</p>
|
|
||||||
)}
|
|
||||||
{listening && !dictation.heard && (
|
|
||||||
<p className="text-muted-foreground">Di «nuevo ítem» o haz una pausa entre artículos.</p>
|
|
||||||
)}
|
|
||||||
{message && !listening && <p className="text-destructive max-w-xs">{message}</p>}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
44
apps/web/src/components/items/dictation-feedback.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
type DictationFeedbackProps = {
|
||||||
|
/** Whether the microphone is listening right now. */
|
||||||
|
listening: boolean
|
||||||
|
/** What has been heard so far, one phrase per item. */
|
||||||
|
heard: string
|
||||||
|
/** Why the last dictation did not deliver anything, in Spanish. */
|
||||||
|
message: string | null
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live state of a dictation: that we are listening, the phrases heard so far and the
|
||||||
|
* last error. Shared by the empty list's card and the floating button's sheet so both
|
||||||
|
* tell the same thing.
|
||||||
|
*/
|
||||||
|
export function DictationFeedback({
|
||||||
|
listening,
|
||||||
|
heard,
|
||||||
|
message,
|
||||||
|
className,
|
||||||
|
}: DictationFeedbackProps) {
|
||||||
|
return (
|
||||||
|
<div aria-live="polite" className={cn('flex flex-col items-center gap-1 text-sm', className)}>
|
||||||
|
{listening && (
|
||||||
|
<p className="text-primary flex items-center gap-2 font-medium">
|
||||||
|
<span className="relative flex size-2.5" aria-hidden="true">
|
||||||
|
<span className="bg-primary absolute inline-flex size-full rounded-full opacity-75 motion-safe:animate-ping" />
|
||||||
|
<span className="bg-primary relative inline-flex size-2.5 rounded-full" />
|
||||||
|
</span>
|
||||||
|
Micrófono activo, te escuchamos
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{listening && heard && <p className="text-muted-foreground max-w-xs text-center">{heard}</p>}
|
||||||
|
{listening && !heard && (
|
||||||
|
<p className="text-muted-foreground text-center">
|
||||||
|
Di «nuevo ítem» o haz una pausa entre artículos.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{message && !listening && <p className="text-destructive max-w-xs text-center">{message}</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ import { ApiError } from '@/lib/api-client'
|
|||||||
import { splitItems } from '@/lib/items'
|
import { splitItems } from '@/lib/items'
|
||||||
|
|
||||||
import { BoughtItemList } from './bought-item-list'
|
import { BoughtItemList } from './bought-item-list'
|
||||||
|
import { DictateFab } from './dictate-fab'
|
||||||
import { DictateItemsButton } from './dictate-items-button'
|
import { DictateItemsButton } from './dictate-items-button'
|
||||||
import { ItemRow } from './item-row'
|
import { ItemRow } from './item-row'
|
||||||
import { ItemSheet } from './item-sheet'
|
import { ItemSheet } from './item-sheet'
|
||||||
@@ -109,7 +110,7 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4 pb-16">
|
||||||
{pending.length > 0 && (
|
{pending.length > 0 && (
|
||||||
<Card className="py-0">
|
<Card className="py-0">
|
||||||
<ul className="divide-y">
|
<ul className="divide-y">
|
||||||
@@ -146,6 +147,9 @@ export function ItemList({ listId }: ItemListProps) {
|
|||||||
onDelete={handleDelete}
|
onDelete={handleDelete}
|
||||||
/>
|
/>
|
||||||
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
<MoveItemDialog listId={listId} item={movingItem} onClose={() => setMovingItem(null)} />
|
||||||
|
|
||||||
|
{/* An empty list dictates from its central card; with items, from this button. */}
|
||||||
|
<DictateFab listId={listId} />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
76
apps/web/src/components/settings/app-badge-card.tsx
Normal file
76
apps/web/src/components/settings/app-badge-card.tsx
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { BellRingIcon } from 'lucide-react'
|
||||||
|
import { useState } from 'react'
|
||||||
|
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { refreshAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||||
|
import { isIos, isStandalone } from '@/lib/platform'
|
||||||
|
|
||||||
|
type Permission = NotificationPermission | 'unsupported'
|
||||||
|
|
||||||
|
function readPermission(): Permission {
|
||||||
|
return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Explains the icon badge and, on iOS, asks for the notification permission the
|
||||||
|
* system requires before showing it. Elsewhere the badge works without asking.
|
||||||
|
*/
|
||||||
|
export function AppBadgeCard() {
|
||||||
|
const [permission, setPermission] = useState(readPermission)
|
||||||
|
const supported = supportsAppBadge()
|
||||||
|
const installed = isStandalone()
|
||||||
|
const needsPermission = supported && installed && isIos() && permission === 'default'
|
||||||
|
|
||||||
|
const enable = async () => {
|
||||||
|
if (typeof Notification === 'undefined') return
|
||||||
|
|
||||||
|
const result = await Notification.requestPermission()
|
||||||
|
setPermission(result)
|
||||||
|
if (result === 'granted') refreshAppBadge()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Indicador en el ícono</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Muestra cuántos artículos quedan por comprar en tu lista principal, en el ícono de la app
|
||||||
|
instalada. Se actualiza solo cuando agregas o compras artículos, aquí o desde otro móvil.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col gap-3">
|
||||||
|
{!supported ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Este navegador no permite mostrar números en el ícono. En Android, Chrome solo muestra
|
||||||
|
un punto cuando la app tiene avisos.
|
||||||
|
</p>
|
||||||
|
) : !installed ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Abre Superlist desde su ícono (la app instalada) para activar el indicador.
|
||||||
|
</p>
|
||||||
|
) : needsPermission ? (
|
||||||
|
<>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
En iPhone y iPad, el sistema pide permiso de avisos para mostrar el número en el
|
||||||
|
ícono. No enviamos notificaciones: solo usamos el permiso para el indicador.
|
||||||
|
</p>
|
||||||
|
<Button size="sm" className="self-start" onClick={enable}>
|
||||||
|
<BellRingIcon className="size-4" />
|
||||||
|
Activar indicador
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : permission === 'denied' ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Bloqueaste los avisos para Superlist. Actívalos en los ajustes de iOS para ver el número
|
||||||
|
en el ícono.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Activo: el número sigue a los artículos pendientes de tu lista principal.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
@@ -0,0 +1,336 @@
|
|||||||
|
import {
|
||||||
|
FingerprintIcon,
|
||||||
|
KeyRoundIcon,
|
||||||
|
MoreHorizontalIcon,
|
||||||
|
PencilIcon,
|
||||||
|
PlusIcon,
|
||||||
|
Trash2Icon,
|
||||||
|
} from 'lucide-react'
|
||||||
|
import { type FormEvent, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog'
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from '@/components/ui/dropdown-menu'
|
||||||
|
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import {
|
||||||
|
type Passkey,
|
||||||
|
useAddPasskey,
|
||||||
|
useDeletePasskey,
|
||||||
|
usePasskeys,
|
||||||
|
useUpdatePasskey,
|
||||||
|
} from '@/hooks/use-passkeys'
|
||||||
|
|
||||||
|
const DEFAULT_NAME = 'Este dispositivo'
|
||||||
|
const createdOnFormat = new Intl.DateTimeFormat('es', { dateStyle: 'medium' })
|
||||||
|
|
||||||
|
function passkeyLabel(passkey: Passkey) {
|
||||||
|
return passkey.name?.trim() || 'Passkey sin nombre'
|
||||||
|
}
|
||||||
|
|
||||||
|
function passkeyDetails(passkey: Passkey) {
|
||||||
|
const created = passkey.createdAt ? new Date(passkey.createdAt) : null
|
||||||
|
|
||||||
|
if (!created || Number.isNaN(created.getTime())) return 'Passkey de acceso'
|
||||||
|
|
||||||
|
return `Creada el ${createdOnFormat.format(created)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PasskeysCard() {
|
||||||
|
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
||||||
|
const passkeys = usePasskeys()
|
||||||
|
const addPasskey = useAddPasskey()
|
||||||
|
const updatePasskey = useUpdatePasskey()
|
||||||
|
const deletePasskey = useDeletePasskey()
|
||||||
|
|
||||||
|
const [addOpen, setAddOpen] = useState(false)
|
||||||
|
const [newName, setNewName] = useState(DEFAULT_NAME)
|
||||||
|
const [renaming, setRenaming] = useState<Passkey | null>(null)
|
||||||
|
const [renameName, setRenameName] = useState('')
|
||||||
|
const [deleting, setDeleting] = useState<Passkey | null>(null)
|
||||||
|
|
||||||
|
const openAdd = () => {
|
||||||
|
setNewName(DEFAULT_NAME)
|
||||||
|
setAddOpen(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const openRename = (passkey: Passkey) => {
|
||||||
|
setRenameName(passkeyLabel(passkey))
|
||||||
|
setRenaming(passkey)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onAdd = async (event: FormEvent) => {
|
||||||
|
event.preventDefault()
|
||||||
|
|
||||||
|
try {
|
||||||
|
await addPasskey.mutateAsync(newName.trim() || DEFAULT_NAME)
|
||||||
|
setAddOpen(false)
|
||||||
|
toast.success('Passkey creada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos crear la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onRename = async (event: FormEvent) => {
|
||||||
|
event.preventDefault()
|
||||||
|
if (!renaming) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await updatePasskey.mutateAsync({ id: renaming.id, name: renameName.trim() || DEFAULT_NAME })
|
||||||
|
setRenaming(null)
|
||||||
|
toast.success('Passkey renombrada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos renombrar la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onDelete = async () => {
|
||||||
|
if (!deleting) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deletePasskey.mutateAsync(deleting.id)
|
||||||
|
setDeleting(null)
|
||||||
|
toast.success('Passkey eliminada.')
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'No pudimos eliminar la passkey.')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<CardTitle>Passkeys</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Entra con Face ID, Touch ID o Windows Hello, sin escribir tu contraseña.
|
||||||
|
</CardDescription>
|
||||||
|
</div>
|
||||||
|
{supportsPasskeys && (
|
||||||
|
<Button variant="outline" size="sm" onClick={openAdd} disabled={addPasskey.isPending}>
|
||||||
|
<PlusIcon />
|
||||||
|
Añadir
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{!supportsPasskeys ? (
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Este navegador no admite passkeys. Prueba con uno más reciente o con la app instalada.
|
||||||
|
</p>
|
||||||
|
) : passkeys.isPending ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Skeleton className="h-14 w-full" />
|
||||||
|
<Skeleton className="h-14 w-full" />
|
||||||
|
</div>
|
||||||
|
) : passkeys.isError ? (
|
||||||
|
<div className="flex flex-col items-start gap-2">
|
||||||
|
<p className="text-destructive text-sm">
|
||||||
|
{passkeys.error instanceof Error
|
||||||
|
? passkeys.error.message
|
||||||
|
: 'No pudimos cargar tus passkeys.'}
|
||||||
|
</p>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => void passkeys.refetch()}>
|
||||||
|
Reintentar
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : passkeys.data.length === 0 ? (
|
||||||
|
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-center">
|
||||||
|
<KeyRoundIcon className="text-muted-foreground size-6" />
|
||||||
|
<p className="text-sm font-medium">Todavía no tienes passkeys</p>
|
||||||
|
<p className="text-muted-foreground text-sm">
|
||||||
|
Añade una para entrar sin escribir tu contraseña.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="divide-y rounded-lg border">
|
||||||
|
{passkeys.data.map((passkey) => (
|
||||||
|
<li key={passkey.id} className="flex items-center gap-3 px-3 py-3">
|
||||||
|
<span className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
|
||||||
|
<FingerprintIcon className="size-4" />
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="truncate text-sm font-medium">{passkeyLabel(passkey)}</p>
|
||||||
|
{passkey.backedUp && (
|
||||||
|
<Badge variant="secondary" className="shrink-0">
|
||||||
|
Sincronizada
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-muted-foreground truncate text-xs">
|
||||||
|
{passkeyDetails(passkey)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={`Acciones de ${passkeyLabel(passkey)}`}
|
||||||
|
>
|
||||||
|
<MoreHorizontalIcon />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end" className="w-40">
|
||||||
|
<DropdownMenuItem onClick={() => openRename(passkey)}>
|
||||||
|
<PencilIcon />
|
||||||
|
Renombrar
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(passkey)}>
|
||||||
|
<Trash2Icon />
|
||||||
|
Eliminar
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={addOpen}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!addPasskey.isPending) setAddOpen(open)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Añadir passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Tu dispositivo te pedirá Face ID, Touch ID, Windows Hello o tu llave de seguridad.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onAdd} className="flex flex-col gap-4">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="new-passkey-name">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="new-passkey-name"
|
||||||
|
value={newName}
|
||||||
|
onChange={(event) => setNewName(event.target.value)}
|
||||||
|
maxLength={60}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<FieldDescription>Te ayuda a reconocerla si añades más de una.</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setAddOpen(false)}
|
||||||
|
disabled={addPasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={addPasskey.isPending}>
|
||||||
|
{addPasskey.isPending ? 'Creando…' : 'Crear passkey'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={renaming !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open && !updatePasskey.isPending) setRenaming(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Renombrar passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Elige un nombre que te ayude a reconocer este dispositivo o llave.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={onRename} className="flex flex-col gap-4">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel htmlFor="rename-passkey">Nombre</FieldLabel>
|
||||||
|
<Input
|
||||||
|
id="rename-passkey"
|
||||||
|
value={renameName}
|
||||||
|
onChange={(event) => setRenameName(event.target.value)}
|
||||||
|
maxLength={60}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setRenaming(null)}
|
||||||
|
disabled={updatePasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={updatePasskey.isPending}>
|
||||||
|
{updatePasskey.isPending ? 'Guardando…' : 'Guardar'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
open={deleting !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open && !deletePasskey.isPending) setDeleting(null)
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Eliminar passkey</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{deleting
|
||||||
|
? `«${passkeyLabel(deleting)}» dejará de servir para iniciar sesión.`
|
||||||
|
: 'Esta passkey dejará de servir para iniciar sesión.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setDeleting(null)}
|
||||||
|
disabled={deletePasskey.isPending}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => void onDelete()}
|
||||||
|
disabled={deletePasskey.isPending}
|
||||||
|
>
|
||||||
|
{deletePasskey.isPending ? 'Eliminando…' : 'Eliminar passkey'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
88
apps/web/src/hooks/use-app-badge.ts
Normal file
88
apps/web/src/hooks/use-app-badge.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
import { useEffect, useState } from 'react'
|
||||||
|
import { itemsQueryOptions, usePendingDeletions } from '@/hooks/use-items'
|
||||||
|
import { useListEvents } from '@/hooks/use-list-events'
|
||||||
|
import { listsQueryOptions, pickPrimaryList } from '@/hooks/use-lists'
|
||||||
|
import { APP_BADGE_REFRESH_EVENT, setAppBadge, supportsAppBadge } from '@/lib/app-badge'
|
||||||
|
import { countPendingItems } from '@/lib/items'
|
||||||
|
import { isStandalone } from '@/lib/platform'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keeps the number on the installed app's icon equal to the items still to buy
|
||||||
|
* in the primary list — the list the home page opens. It follows that list's SSE
|
||||||
|
* stream even from other pages, so a change made by another member updates the
|
||||||
|
* badge too, and re-syncs whenever the app comes back to the foreground (iOS
|
||||||
|
* suspends the page, and with it the stream, in the background).
|
||||||
|
*
|
||||||
|
* Only runs in the installed app: browsers show the badge nowhere else.
|
||||||
|
*/
|
||||||
|
export function useAppBadge() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
const active = isStandalone() && supportsAppBadge()
|
||||||
|
|
||||||
|
const { data: lists } = useQuery({ ...listsQueryOptions(), enabled: active })
|
||||||
|
const primaryList = lists ? pickPrimaryList(lists) : undefined
|
||||||
|
const listId = primaryList?.id
|
||||||
|
|
||||||
|
const { data: items } = useQuery({
|
||||||
|
...itemsQueryOptions(listId ?? ''),
|
||||||
|
enabled: active && Boolean(listId),
|
||||||
|
})
|
||||||
|
const deletingIds = usePendingDeletions()
|
||||||
|
|
||||||
|
// Permission can be granted while the app is open (see the settings card); the
|
||||||
|
// data does not change, so the effect is nudged through this event.
|
||||||
|
const [refreshToken, setRefreshToken] = useState(0)
|
||||||
|
useEffect(() => {
|
||||||
|
const refresh = () => setRefreshToken((token) => token + 1)
|
||||||
|
window.addEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||||
|
return () => window.removeEventListener(APP_BADGE_REFRESH_EVENT, refresh)
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
|
||||||
|
// Re-run after a permission change even though the data is the same.
|
||||||
|
void refreshToken
|
||||||
|
|
||||||
|
// Lists still loading: keep whatever the badge already shows instead of
|
||||||
|
// flickering to zero (or clearing) on every launch.
|
||||||
|
if (!lists) return
|
||||||
|
|
||||||
|
if (!listId) {
|
||||||
|
void setAppBadge(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!items) return
|
||||||
|
|
||||||
|
void setAppBadge(countPendingItems(items, deletingIds))
|
||||||
|
}, [active, lists, listId, items, deletingIds, refreshToken])
|
||||||
|
|
||||||
|
// The icon outlives the page: signing out should not leave somebody else's
|
||||||
|
// pending items on it.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
return () => void setAppBadge(0)
|
||||||
|
}, [active])
|
||||||
|
|
||||||
|
// Remote additions to the primary list while another page is open.
|
||||||
|
useListEvents(active ? listId : undefined)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return
|
||||||
|
|
||||||
|
const refresh = () => {
|
||||||
|
if (document.visibilityState !== 'visible') return
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['lists'] })
|
||||||
|
if (listId) void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('visibilitychange', refresh)
|
||||||
|
window.addEventListener('online', refresh)
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('visibilitychange', refresh)
|
||||||
|
window.removeEventListener('online', refresh)
|
||||||
|
}
|
||||||
|
}, [active, listId, queryClient])
|
||||||
|
}
|
||||||
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
78
apps/web/src/hooks/use-dictate-items.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { useRef, useState } from 'react'
|
||||||
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
|
import { useAddItems } from '@/hooks/use-add-items'
|
||||||
|
import { DICTATION_MESSAGES, useMicrophoneDictation } from '@/hooks/use-microphone-dictation'
|
||||||
|
|
||||||
|
type UseDictateItemsOptions = {
|
||||||
|
/**
|
||||||
|
* The dictation finished: `added` says whether anything made it to the list, so a
|
||||||
|
* sheet can close on success and stay open to show why nothing was added.
|
||||||
|
*/
|
||||||
|
onFinish?: (added: boolean) => void
|
||||||
|
/**
|
||||||
|
* A message was set (an error, or a dictation the API limits rejected). A surface that
|
||||||
|
* may already be closed uses this to show it somewhere else, e.g. as a toast.
|
||||||
|
*/
|
||||||
|
onMessage?: (message: string) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dictation of items into a list, shared by the empty list's card and the floating
|
||||||
|
* button: the microphone listens until the user stops it and the transcript goes
|
||||||
|
* through `addDictation` (split by the API, undoable). Errors and limits stay in
|
||||||
|
* `message` so each surface can show them where it fits.
|
||||||
|
*/
|
||||||
|
export function useDictateItems(
|
||||||
|
listId: string,
|
||||||
|
{ onFinish, onMessage }: UseDictateItemsOptions = {},
|
||||||
|
) {
|
||||||
|
const [message, setMessage] = useState<string | null>(null)
|
||||||
|
// A rejected dictation is reported from a callback, so the outcome of `addDictation`
|
||||||
|
// is read from here once it resolves.
|
||||||
|
const rejected = useRef(false)
|
||||||
|
|
||||||
|
const showMessage = (detail: string) => {
|
||||||
|
setMessage(detail)
|
||||||
|
onMessage?.(detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { addDictation, processing } = useAddItems(listId, {
|
||||||
|
onItemFailed: (source, detail) => toast.error(`No pudimos añadir «${source}»: ${detail}`),
|
||||||
|
onDictationRejected: (_, detail) => {
|
||||||
|
rejected.current = true
|
||||||
|
showMessage(detail)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const dictation = useMicrophoneDictation({
|
||||||
|
onPhrases: async (phrases) => {
|
||||||
|
rejected.current = false
|
||||||
|
const understood = await addDictation(phrases.join('\n'))
|
||||||
|
if (!rejected.current && understood === 0) showMessage(DICTATION_MESSAGES.empty)
|
||||||
|
onFinish?.(understood > 0 && !rejected.current)
|
||||||
|
},
|
||||||
|
onError: (detail) => {
|
||||||
|
showMessage(detail)
|
||||||
|
onFinish?.(false)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const listening = dictation.status === 'listening'
|
||||||
|
|
||||||
|
return {
|
||||||
|
listening,
|
||||||
|
/** Asking for the microphone or splitting the transcript: no new dictation yet. */
|
||||||
|
busy: dictation.status === 'requesting' || processing,
|
||||||
|
processing,
|
||||||
|
supported: dictation.supported,
|
||||||
|
/** What has been heard so far, shown while listening. */
|
||||||
|
heard: dictation.heard,
|
||||||
|
message,
|
||||||
|
start: () => {
|
||||||
|
setMessage(null)
|
||||||
|
dictation.start()
|
||||||
|
},
|
||||||
|
stop: dictation.stop,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
canDictate,
|
||||||
getSpeechRecognition as getBrowserSpeechRecognition,
|
getSpeechRecognition as getBrowserSpeechRecognition,
|
||||||
isIosStandalone,
|
|
||||||
type SpeechRecognitionConstructor,
|
|
||||||
} from '@/lib/speech-recognition'
|
} from '@/lib/speech-recognition'
|
||||||
|
|
||||||
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
/** Errors that only mean "nothing was said" or "we stopped it": not worth telling. */
|
||||||
@@ -21,10 +20,8 @@ const ERROR_MESSAGES: Record<string, string> = {
|
|||||||
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
* app exposes `webkitSpeechRecognition` but it does not work there, so it counts as
|
||||||
* unsupported (the keyboard's own dictation still works).
|
* unsupported (the keyboard's own dictation still works).
|
||||||
*/
|
*/
|
||||||
function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
function getSpeechRecognition() {
|
||||||
if (typeof window === 'undefined' || isIosStandalone()) return null
|
return canDictate() ? getBrowserSpeechRecognition() : null
|
||||||
|
|
||||||
return getBrowserSpeechRecognition()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type UseDictationOptions = {
|
type UseDictationOptions = {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import * as React from 'react'
|
import * as React from 'react'
|
||||||
|
|
||||||
|
import { isIos, isStandalone } from '@/lib/platform'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
|
* `beforeinstallprompt` is still non-standard, so TypeScript has no DOM type
|
||||||
* for it. This is the subset of the event we use.
|
* for it. This is the subset of the event we use.
|
||||||
@@ -20,23 +22,13 @@ function readDismissed() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isStandalone() {
|
|
||||||
if (typeof window === 'undefined') return false
|
|
||||||
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
|
|
||||||
return (
|
|
||||||
window.matchMedia('(display-mode: standalone)').matches ||
|
|
||||||
navigatorWithStandalone.standalone === true
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function isIosSafari() {
|
function isIosSafari() {
|
||||||
if (typeof navigator === 'undefined') return false
|
if (typeof navigator === 'undefined') return false
|
||||||
const ua = navigator.userAgent
|
|
||||||
const isIos = /iphone|ipad|ipod/i.test(ua)
|
|
||||||
// On iOS only Safari can add apps to the home screen, and it never fires
|
// On iOS only Safari can add apps to the home screen, and it never fires
|
||||||
// `beforeinstallprompt`, so we detect it to show manual instructions.
|
// `beforeinstallprompt`, so we detect it to show manual instructions.
|
||||||
const isSafari = /safari/i.test(ua) && !/crios|fxios|edgios/i.test(ua)
|
const isSafari =
|
||||||
return isIos && isSafari
|
/safari/i.test(navigator.userAgent) && !/crios|fxios|edgios/i.test(navigator.userAgent)
|
||||||
|
return isIos() && isSafari
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InstallPromptState = {
|
export type InstallPromptState = {
|
||||||
@@ -58,7 +50,7 @@ export function useInstallPrompt(): InstallPromptState {
|
|||||||
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
|
const [deferredPrompt, setDeferredPrompt] = React.useState<BeforeInstallPromptEvent | null>(null)
|
||||||
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
|
const [isInstalled, setIsInstalled] = React.useState(isStandalone)
|
||||||
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
|
const [isDismissed, setIsDismissed] = React.useState(readDismissed)
|
||||||
const [isIos] = React.useState(isIosSafari)
|
const [isIosSafariDevice] = React.useState(isIosSafari)
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
const onBeforeInstallPrompt = (event: Event) => {
|
const onBeforeInstallPrompt = (event: Event) => {
|
||||||
@@ -97,7 +89,7 @@ export function useInstallPrompt(): InstallPromptState {
|
|||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const canInstall = deferredPrompt !== null
|
const canInstall = deferredPrompt !== null
|
||||||
const needsManualInstructions = isIos && !deferredPrompt && !isInstalled
|
const needsManualInstructions = isIosSafariDevice && !deferredPrompt && !isInstalled
|
||||||
|
|
||||||
return {
|
return {
|
||||||
canInstall,
|
canInstall,
|
||||||
|
|||||||
@@ -1,47 +1,35 @@
|
|||||||
import { useQueryClient } from '@tanstack/react-query'
|
import { useQueryClient } from '@tanstack/react-query'
|
||||||
import { useEffect } from 'react'
|
import { useEffect } from 'react'
|
||||||
|
import { queryKeysForListEvent } from '@/lib/list-events'
|
||||||
import { apiBaseUrl } from '@/lib/api-client'
|
import { subscribeToListEvents } from '@/lib/list-events-stream'
|
||||||
import { LIST_EVENT_TYPES, queryKeysForListEvent } from '@/lib/list-events'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Subscribes to a list's SSE stream (`GET /lists/:listId/events`) and refreshes
|
* Follows a list's SSE stream (`GET /lists/:listId/events`) and refreshes the
|
||||||
* the affected queries whenever another member adds or buys an item, invites
|
* affected queries whenever another member adds or buys an item, invites
|
||||||
* somebody or renames the list — so the page updates without a reload.
|
* somebody or renames the list — so the page updates without a reload.
|
||||||
*
|
*
|
||||||
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on
|
* The session cookie is sent via `withCredentials`. `EventSource` reconnects on
|
||||||
* its own; a `ready` event is emitted on every (re)connection, used here to
|
* its own; a `ready` event is emitted on every (re)connection, used here to
|
||||||
* reconcile anything missed while disconnected.
|
* reconcile anything missed while disconnected. The connection is shared with
|
||||||
|
* any other subscriber of the same list (see `list-events-stream.ts`).
|
||||||
|
*
|
||||||
|
* Pass `undefined` to follow nothing (e.g. while the primary list is unknown).
|
||||||
*/
|
*/
|
||||||
export function useListEvents(listId: string) {
|
export function useListEvents(listId: string | undefined) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
|
if (!listId) return
|
||||||
withCredentials: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
const onReady = () => {
|
return subscribeToListEvents(listId, {
|
||||||
queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
onEvent: (type) => {
|
||||||
}
|
|
||||||
|
|
||||||
source.addEventListener('ready', onReady)
|
|
||||||
|
|
||||||
const listeners = LIST_EVENT_TYPES.map((type) => {
|
|
||||||
const listener = () => {
|
|
||||||
for (const queryKey of queryKeysForListEvent(type, listId)) {
|
for (const queryKey of queryKeysForListEvent(type, listId)) {
|
||||||
queryClient.invalidateQueries({ queryKey })
|
void queryClient.invalidateQueries({ queryKey })
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
onReady: () => {
|
||||||
source.addEventListener(type, listener)
|
void queryClient.invalidateQueries({ queryKey: ['lists', listId, 'items'] })
|
||||||
return { type, listener }
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
return () => {
|
|
||||||
source.removeEventListener('ready', onReady)
|
|
||||||
for (const { type, listener } of listeners) source.removeEventListener(type, listener)
|
|
||||||
source.close()
|
|
||||||
}
|
|
||||||
}, [listId, queryClient])
|
}, [listId, queryClient])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ type UseMicrophoneDictationOptions = {
|
|||||||
* capture. Unmounting aborts the recognition.
|
* capture. Unmounting aborts the recognition.
|
||||||
*/
|
*/
|
||||||
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDictationOptions) {
|
||||||
|
const [supported] = useState(() => getSpeechRecognition() !== null)
|
||||||
const [status, setStatus] = useState<DictationStatus>('idle')
|
const [status, setStatus] = useState<DictationStatus>('idle')
|
||||||
// What has been heard so far, shown while listening.
|
// What has been heard so far, shown while listening.
|
||||||
const [heard, setHeard] = useState('')
|
const [heard, setHeard] = useState('')
|
||||||
@@ -150,5 +151,5 @@ export function useMicrophoneDictation({ onPhrases, onError }: UseMicrophoneDict
|
|||||||
/** Stops listening; what was heard so far is delivered. */
|
/** Stops listening; what was heard so far is delivered. */
|
||||||
const stop = useCallback(() => endRef.current?.(true), [])
|
const stop = useCallback(() => endRef.current?.(true), [])
|
||||||
|
|
||||||
return { status, heard, start, stop }
|
return { status, heard, supported, start, stop }
|
||||||
}
|
}
|
||||||
|
|||||||
76
apps/web/src/hooks/use-passkeys.ts
Normal file
76
apps/web/src/hooks/use-passkeys.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||||
|
|
||||||
|
import { authClient } from '@/lib/auth-client'
|
||||||
|
|
||||||
|
export type Passkey = NonNullable<
|
||||||
|
Awaited<ReturnType<typeof authClient.passkey.listUserPasskeys>>['data']
|
||||||
|
>[number]
|
||||||
|
|
||||||
|
const PASSKEYS_QUERY_KEY = ['passkeys'] as const
|
||||||
|
|
||||||
|
export const passkeysQueryOptions = () =>
|
||||||
|
queryOptions({
|
||||||
|
queryKey: PASSKEYS_QUERY_KEY,
|
||||||
|
queryFn: async () => {
|
||||||
|
const { data, error } = await authClient.passkey.listUserPasskeys()
|
||||||
|
|
||||||
|
if (error) throw new Error(error.message ?? 'No pudimos cargar tus passkeys.')
|
||||||
|
|
||||||
|
return data ?? []
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
export function usePasskeys() {
|
||||||
|
return useQuery(passkeysQueryOptions())
|
||||||
|
}
|
||||||
|
|
||||||
|
function toError(error: { message?: string } | null, fallback: string) {
|
||||||
|
return new Error(error?.message ?? fallback)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAddPasskey() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (name: string) => {
|
||||||
|
const { data, error } = await authClient.passkey.addPasskey({ name })
|
||||||
|
|
||||||
|
if (error) throw toError(error, 'No pudimos crear la passkey.')
|
||||||
|
|
||||||
|
return data
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdatePasskey() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async ({ id, name }: { id: string; name: string }) => {
|
||||||
|
const { error } = await authClient.passkey.updatePasskey({ id, name })
|
||||||
|
|
||||||
|
if (error) throw toError(error, 'No pudimos renombrar la passkey.')
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeletePasskey() {
|
||||||
|
const queryClient = useQueryClient()
|
||||||
|
|
||||||
|
return useMutation({
|
||||||
|
mutationFn: async (id: string) => {
|
||||||
|
const { error } = await authClient.passkey.deletePasskey({ id })
|
||||||
|
|
||||||
|
if (error) throw toError(error, 'No pudimos eliminar la passkey.')
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
56
apps/web/src/lib/app-badge.test.ts
Normal file
56
apps/web/src/lib/app-badge.test.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
|
||||||
|
import { setAppBadge, supportsAppBadge } from './app-badge'
|
||||||
|
|
||||||
|
type BadgingNavigator = Navigator & {
|
||||||
|
setAppBadge?: (contents?: number) => Promise<void>
|
||||||
|
clearAppBadge?: () => Promise<void>
|
||||||
|
}
|
||||||
|
|
||||||
|
const badging = navigator as BadgingNavigator
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
Reflect.deleteProperty(badging, 'setAppBadge')
|
||||||
|
Reflect.deleteProperty(badging, 'clearAppBadge')
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('supportsAppBadge', () => {
|
||||||
|
it('is false when the browser has no Badging API', () => {
|
||||||
|
expect(supportsAppBadge()).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is true when setAppBadge is available', () => {
|
||||||
|
badging.setAppBadge = () => Promise.resolve()
|
||||||
|
|
||||||
|
expect(supportsAppBadge()).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('setAppBadge', () => {
|
||||||
|
it('shows the count on the icon', async () => {
|
||||||
|
const set = vi.fn(() => Promise.resolve())
|
||||||
|
badging.setAppBadge = set
|
||||||
|
badging.clearAppBadge = () => Promise.resolve()
|
||||||
|
|
||||||
|
await setAppBadge(4)
|
||||||
|
|
||||||
|
expect(set).toHaveBeenCalledWith(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('clears the badge when nothing is pending', async () => {
|
||||||
|
const clear = vi.fn(() => Promise.resolve())
|
||||||
|
badging.setAppBadge = () => Promise.resolve()
|
||||||
|
badging.clearAppBadge = clear
|
||||||
|
|
||||||
|
await setAppBadge(0)
|
||||||
|
|
||||||
|
expect(clear).toHaveBeenCalledOnce()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores a rejected call (not installed, permission denied)', async () => {
|
||||||
|
badging.setAppBadge = () => Promise.reject(new Error('NotAllowedError'))
|
||||||
|
badging.clearAppBadge = () => Promise.resolve()
|
||||||
|
|
||||||
|
await expect(setAppBadge(2)).resolves.toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
39
apps/web/src/lib/app-badge.ts
Normal file
39
apps/web/src/lib/app-badge.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
/**
|
||||||
|
* Name of the window event used to ask `useAppBadge` for a fresh sync (for
|
||||||
|
* example right after the user grants notification permission, which the
|
||||||
|
* effect cannot observe on its own).
|
||||||
|
*/
|
||||||
|
export const APP_BADGE_REFRESH_EVENT = 'superlist:app-badge-refresh'
|
||||||
|
|
||||||
|
/** Whether this browser can show a badge on the installed app's icon. */
|
||||||
|
export function supportsAppBadge(): boolean {
|
||||||
|
return typeof navigator !== 'undefined' && 'setAppBadge' in navigator
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes `count` on the icon of the installed app (Badging API). Zero removes
|
||||||
|
* the badge. Browsers without support, calls made from a tab instead of the
|
||||||
|
* installed app, and platforms where the permission is missing (iOS needs
|
||||||
|
* notifications allowed) reject the promise; the badge simply stays as it was.
|
||||||
|
*/
|
||||||
|
export function setAppBadge(count: number): Promise<void> {
|
||||||
|
if (!supportsAppBadge()) return Promise.resolve()
|
||||||
|
|
||||||
|
const value = Math.max(0, Math.trunc(count))
|
||||||
|
const request =
|
||||||
|
value > 0
|
||||||
|
? navigator.setAppBadge(value)
|
||||||
|
: navigator.clearAppBadge
|
||||||
|
? navigator.clearAppBadge()
|
||||||
|
: Promise.resolve()
|
||||||
|
|
||||||
|
return request.catch(() => {
|
||||||
|
// Not installed, permission denied or document not fully active: a badge is
|
||||||
|
// a hint, never something worth breaking a render or logging an error for.
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Asks the badge sync to run again, even when no data changed. */
|
||||||
|
export function refreshAppBadge() {
|
||||||
|
if (typeof window !== 'undefined') window.dispatchEvent(new Event(APP_BADGE_REFRESH_EVENT))
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { passkeyClient } from '@better-auth/passkey/client'
|
||||||
import { emailOTPClient } from 'better-auth/client/plugins'
|
import { emailOTPClient } from 'better-auth/client/plugins'
|
||||||
import { createAuthClient } from 'better-auth/react'
|
import { createAuthClient } from 'better-auth/react'
|
||||||
|
|
||||||
@@ -8,7 +9,7 @@ import { createAuthClient } from 'better-auth/react'
|
|||||||
*/
|
*/
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||||
plugins: [emailOTPClient()],
|
plugins: [emailOTPClient(), passkeyClient()],
|
||||||
})
|
})
|
||||||
|
|
||||||
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient
|
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { ListItem } from '@superlist/shared'
|
import type { ListItem } from '@superlist/shared'
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
|
|
||||||
import { quantityLabel, splitItems } from './items'
|
import { countPendingItems, quantityLabel, splitItems } from './items'
|
||||||
|
|
||||||
function item(overrides: Partial<ListItem>): ListItem {
|
function item(overrides: Partial<ListItem>): ListItem {
|
||||||
return {
|
return {
|
||||||
@@ -86,6 +86,28 @@ describe('splitItems', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('countPendingItems', () => {
|
||||||
|
it('counts only the items still to buy', () => {
|
||||||
|
const items = [
|
||||||
|
item({ id: 'a' }),
|
||||||
|
item({ id: 'b' }),
|
||||||
|
item({ id: 'c', completed: true, boughtAt: new Date(2026, 9, 15, 9, 0).toISOString() }),
|
||||||
|
]
|
||||||
|
|
||||||
|
expect(countPendingItems(items)).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores items that are already hidden by a pending deletion', () => {
|
||||||
|
const items = [item({ id: 'a' }), item({ id: 'b' })]
|
||||||
|
|
||||||
|
expect(countPendingItems(items, new Set(['b']))).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is zero for an empty list', () => {
|
||||||
|
expect(countPendingItems([])).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('quantityLabel', () => {
|
describe('quantityLabel', () => {
|
||||||
it('shows quantities with a unit, litres in capitals', () => {
|
it('shows quantities with a unit, litres in capitals', () => {
|
||||||
expect(quantityLabel('2 l')).toBe('2 L')
|
expect(quantityLabel('2 l')).toBe('2 L')
|
||||||
|
|||||||
@@ -40,6 +40,24 @@ export function splitItems(items: ListItem[], now: Date): SplitItems {
|
|||||||
return { pending, boughtToday }
|
return { pending, boughtToday }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many items are still to buy. `hidden` holds ids that are already gone
|
||||||
|
* from the UI (a deletion waiting for undo), so a row the user no longer sees
|
||||||
|
* never counts.
|
||||||
|
*/
|
||||||
|
export function countPendingItems(
|
||||||
|
items: ListItem[],
|
||||||
|
hidden: ReadonlySet<string> = new Set(),
|
||||||
|
): number {
|
||||||
|
let count = 0
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
if (!item.completed && !hidden.has(item.id)) count++
|
||||||
|
}
|
||||||
|
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
/** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */
|
/** Bare amounts from here up are weights ("400 de jamón"), not counts: no "×". */
|
||||||
const BARE_WEIGHT_FROM = 50
|
const BARE_WEIGHT_FROM = 50
|
||||||
|
|
||||||
|
|||||||
66
apps/web/src/lib/list-events-stream.ts
Normal file
66
apps/web/src/lib/list-events-stream.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import type { ListEventType } from '@superlist/shared'
|
||||||
|
|
||||||
|
import { apiBaseUrl } from './api-client'
|
||||||
|
import { LIST_EVENT_TYPES } from './list-events'
|
||||||
|
|
||||||
|
type Subscriber = {
|
||||||
|
onEvent: (type: ListEventType) => void
|
||||||
|
onReady: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
type Stream = {
|
||||||
|
source: EventSource
|
||||||
|
subscribers: Set<Subscriber>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One `EventSource` per list, shared by every hook that needs it: the item list
|
||||||
|
* and the app badge both follow the primary list, and opening two streams to the
|
||||||
|
* same endpoint would only duplicate requests and invalidations.
|
||||||
|
*/
|
||||||
|
const streams = new Map<string, Stream>()
|
||||||
|
|
||||||
|
function createStream(listId: string): Stream {
|
||||||
|
const source = new EventSource(`${apiBaseUrl}/lists/${listId}/events`, {
|
||||||
|
withCredentials: true,
|
||||||
|
})
|
||||||
|
const stream: Stream = { source, subscribers: new Set() }
|
||||||
|
|
||||||
|
for (const type of LIST_EVENT_TYPES) {
|
||||||
|
source.addEventListener(type, () => {
|
||||||
|
for (const subscriber of stream.subscribers) subscriber.onEvent(type)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emitted on every (re)connection: anything missed while disconnected has to
|
||||||
|
// be fetched again.
|
||||||
|
source.addEventListener('ready', () => {
|
||||||
|
for (const subscriber of stream.subscribers) subscriber.onReady()
|
||||||
|
})
|
||||||
|
|
||||||
|
return stream
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Follows a list's stream while at least one subscriber exists. The connection
|
||||||
|
* opens with the first one and closes with the last; returns the unsubscribe.
|
||||||
|
*/
|
||||||
|
export function subscribeToListEvents(listId: string, subscriber: Subscriber): () => void {
|
||||||
|
let stream = streams.get(listId)
|
||||||
|
|
||||||
|
if (!stream) {
|
||||||
|
stream = createStream(listId)
|
||||||
|
streams.set(listId, stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
stream.subscribers.add(subscriber)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
stream.subscribers.delete(subscriber)
|
||||||
|
|
||||||
|
if (stream.subscribers.size === 0) {
|
||||||
|
stream.source.close()
|
||||||
|
streams.delete(listId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,9 @@ const EXPECTED: Record<
|
|||||||
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
|
'6 unidades de yogur': { name: 'Yogur', amount: 6, unit: null, notes: null },
|
||||||
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
|
'400g de queso': { name: 'Queso', amount: 400, unit: 'g', notes: null },
|
||||||
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' },
|
'Leche (descremada)': { name: 'Leche', amount: null, unit: null, notes: 'Descremada' },
|
||||||
|
Azúcar: { name: 'Azúcar', amount: null, unit: null, notes: null },
|
||||||
|
Leche: { name: 'Leche', amount: null, unit: null, notes: null },
|
||||||
|
Café: { name: 'Café', amount: null, unit: null, notes: null },
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('dictation few-shot examples', () => {
|
describe('dictation few-shot examples', () => {
|
||||||
|
|||||||
20
apps/web/src/lib/platform.ts
Normal file
20
apps/web/src/lib/platform.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
/** iOS or iPadOS (which reports a desktop Mac user agent). */
|
||||||
|
export function isIos() {
|
||||||
|
if (typeof navigator === 'undefined') return false
|
||||||
|
|
||||||
|
return (
|
||||||
|
/iphone|ipad|ipod/i.test(navigator.userAgent) ||
|
||||||
|
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app is running as an installed PWA instead of in a browser tab. */
|
||||||
|
export function isStandalone() {
|
||||||
|
if (typeof window === 'undefined') return false
|
||||||
|
|
||||||
|
const navigatorWithStandalone = navigator as Navigator & { standalone?: boolean }
|
||||||
|
return (
|
||||||
|
window.matchMedia('(display-mode: standalone)').matches ||
|
||||||
|
navigatorWithStandalone.standalone === true
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -32,3 +32,16 @@ export function getSpeechRecognition(): SpeechRecognitionConstructor | null {
|
|||||||
export function isIosStandalone(): boolean {
|
export function isIosStandalone(): boolean {
|
||||||
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
return (navigator as Navigator & { standalone?: boolean }).standalone === true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this browser can dictate a phrase without asking for the microphone first
|
||||||
|
* (the input's microphone). An iOS home-screen app exposes `webkitSpeechRecognition`
|
||||||
|
* but that flow does not work there, so it counts as unsupported (the keyboard's own
|
||||||
|
* dictation still works). Dictating several items does work there, because it asks
|
||||||
|
* for the microphone with `getUserMedia` first, so it checks `getSpeechRecognition()`.
|
||||||
|
*/
|
||||||
|
export function canDictate(): boolean {
|
||||||
|
if (typeof window === 'undefined' || isIosStandalone()) return false
|
||||||
|
|
||||||
|
return getSpeechRecognition() !== null
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { zodResolver } from '@hookform/resolvers/zod'
|
import { zodResolver } from '@hookform/resolvers/zod'
|
||||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||||
import { useState } from 'react'
|
import { FingerprintIcon } from 'lucide-react'
|
||||||
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
|
||||||
@@ -10,7 +11,7 @@ import { Button } from '@/components/ui/button'
|
|||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { signIn } from '@/lib/auth-client'
|
import { authClient, signIn } from '@/lib/auth-client'
|
||||||
|
|
||||||
export const Route = createFileRoute('/(auth)/sign-in')({
|
export const Route = createFileRoute('/(auth)/sign-in')({
|
||||||
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
||||||
@@ -26,16 +27,69 @@ const signInSchema = z.object({
|
|||||||
|
|
||||||
type SignInValues = z.infer<typeof signInSchema>
|
type SignInValues = z.infer<typeof signInSchema>
|
||||||
|
|
||||||
|
const PASSKEY_ERROR_MESSAGE = 'No pudimos iniciar tu sesión con passkey.'
|
||||||
|
|
||||||
|
/** The user dismissed the system sheet: not worth showing an error for. */
|
||||||
|
function isPasskeyCancellation(error: unknown) {
|
||||||
|
return (
|
||||||
|
typeof error === 'object' &&
|
||||||
|
error !== null &&
|
||||||
|
'code' in error &&
|
||||||
|
error.code === 'AUTH_CANCELLED'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function SignInPage() {
|
function SignInPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const { redirect } = Route.useSearch()
|
const { redirect } = Route.useSearch()
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [passkeyPending, setPasskeyPending] = useState(false)
|
||||||
|
const conditionalUiStarted = useRef(false)
|
||||||
|
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
||||||
|
|
||||||
const form = useForm<SignInValues>({
|
const form = useForm<SignInValues>({
|
||||||
resolver: zodResolver(signInSchema),
|
resolver: zodResolver(signInSchema),
|
||||||
defaultValues: { email: '', password: '' },
|
defaultValues: { email: '', password: '' },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const completeSignIn = useCallback(async () => {
|
||||||
|
if (redirect) {
|
||||||
|
window.location.assign(redirect)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await navigate({ to: '/' })
|
||||||
|
}, [navigate, redirect])
|
||||||
|
|
||||||
|
// Conditional UI: the browser offers the user's passkeys in the email field's
|
||||||
|
// autofill. Guarded with a ref because StrictMode mounts effects twice in dev
|
||||||
|
// and a second ceremony would abort the first one.
|
||||||
|
useEffect(() => {
|
||||||
|
if (conditionalUiStarted.current || !supportsPasskeys) return
|
||||||
|
if (typeof window.PublicKeyCredential.isConditionalMediationAvailable !== 'function') return
|
||||||
|
|
||||||
|
conditionalUiStarted.current = true
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
if (!(await window.PublicKeyCredential.isConditionalMediationAvailable())) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error: passkeyError } = await authClient.signIn.passkey({ autoFill: true })
|
||||||
|
|
||||||
|
if (passkeyError) {
|
||||||
|
if (!isPasskeyCancellation(passkeyError)) {
|
||||||
|
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await completeSignIn()
|
||||||
|
} catch {
|
||||||
|
setError(PASSKEY_ERROR_MESSAGE)
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
}, [completeSignIn, supportsPasskeys])
|
||||||
|
|
||||||
const onSubmit = form.handleSubmit(async (values) => {
|
const onSubmit = form.handleSubmit(async (values) => {
|
||||||
setError(null)
|
setError(null)
|
||||||
|
|
||||||
@@ -46,14 +100,31 @@ function SignInPage() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (redirect) {
|
await completeSignIn()
|
||||||
window.location.assign(redirect)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
await navigate({ to: '/' })
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const onPasskeySignIn = async () => {
|
||||||
|
setError(null)
|
||||||
|
setPasskeyPending(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { error: passkeyError } = await authClient.signIn.passkey()
|
||||||
|
|
||||||
|
if (passkeyError) {
|
||||||
|
if (!isPasskeyCancellation(passkeyError)) {
|
||||||
|
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
await completeSignIn()
|
||||||
|
} catch {
|
||||||
|
setError(PASSKEY_ERROR_MESSAGE)
|
||||||
|
} finally {
|
||||||
|
setPasskeyPending(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||||
<AppBrand />
|
<AppBrand />
|
||||||
@@ -77,7 +148,9 @@ function SignInPage() {
|
|||||||
<Input
|
<Input
|
||||||
id="email"
|
id="email"
|
||||||
type="email"
|
type="email"
|
||||||
autoComplete="email"
|
// `webauthn` lets the browser offer passkeys in autofill
|
||||||
|
// (conditional UI); `username` is what login forms use.
|
||||||
|
autoComplete="username webauthn"
|
||||||
placeholder="ada@ejemplo.com"
|
placeholder="ada@ejemplo.com"
|
||||||
{...form.register('email')}
|
{...form.register('email')}
|
||||||
/>
|
/>
|
||||||
@@ -107,11 +180,31 @@ function SignInPage() {
|
|||||||
<FieldError errors={[form.formState.errors.password]} />
|
<FieldError errors={[form.formState.errors.password]} />
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
<Button type="submit" disabled={form.formState.isSubmitting || passkeyPending}>
|
||||||
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
|
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
|
||||||
</Button>
|
</Button>
|
||||||
</FieldGroup>
|
</FieldGroup>
|
||||||
|
|
||||||
|
{supportsPasskeys && (
|
||||||
|
<>
|
||||||
|
<div className="flex items-center gap-3" aria-hidden>
|
||||||
|
<span className="bg-border h-px flex-1" />
|
||||||
|
<span className="text-muted-foreground text-xs uppercase">o</span>
|
||||||
|
<span className="bg-border h-px flex-1" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={onPasskeySignIn}
|
||||||
|
disabled={passkeyPending || form.formState.isSubmitting}
|
||||||
|
>
|
||||||
|
<FingerprintIcon />
|
||||||
|
{passkeyPending ? 'Esperando a tu passkey…' : 'Entrar con passkey'}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<p className="text-muted-foreground text-center text-sm">
|
<p className="text-muted-foreground text-center text-sm">
|
||||||
¿Todavía no tienes cuenta?{' '}
|
¿Todavía no tienes cuenta?{' '}
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
|
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router'
|
||||||
|
import { AppBadge } from '@/components/app-badge'
|
||||||
import { InstallPrompt } from '@/components/install-prompt'
|
import { InstallPrompt } from '@/components/install-prompt'
|
||||||
import { AppHeader } from '@/components/layout/app-header'
|
import { AppHeader } from '@/components/layout/app-header'
|
||||||
import { AppSidebar } from '@/components/layout/app-sidebar'
|
import { AppSidebar } from '@/components/layout/app-sidebar'
|
||||||
@@ -37,6 +38,7 @@ function AuthenticatedLayout() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<SidebarProvider>
|
<SidebarProvider>
|
||||||
|
<AppBadge />
|
||||||
<AppSidebar />
|
<AppSidebar />
|
||||||
<SidebarInset>
|
<SidebarInset>
|
||||||
<AppHeader />
|
<AppHeader />
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
|
|||||||
import { useForm } from 'react-hook-form'
|
import { useForm } from 'react-hook-form'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
|
import { AppBadgeCard } from '@/components/settings/app-badge-card'
|
||||||
|
import { PasskeysCard } from '@/components/settings/passkeys-card'
|
||||||
import { type Theme, useTheme } from '@/components/theme-provider'
|
import { type Theme, useTheme } from '@/components/theme-provider'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
@@ -22,6 +24,8 @@ function SettingsPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
|
<div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
|
||||||
<ProfileCard />
|
<ProfileCard />
|
||||||
|
<PasskeysCard />
|
||||||
|
<AppBadgeCard />
|
||||||
<AppearanceCard />
|
<AppearanceCard />
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
|
|||||||
50
bun.lock
50
bun.lock
@@ -14,6 +14,7 @@
|
|||||||
"name": "@superlist/api",
|
"name": "@superlist/api",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@hono/zod-validator": "^0.9.1",
|
"@hono/zod-validator": "^0.9.1",
|
||||||
"@prisma/adapter-pg": "^7.10.0",
|
"@prisma/adapter-pg": "^7.10.0",
|
||||||
"@prisma/client": "^7.10.0",
|
"@prisma/client": "^7.10.0",
|
||||||
@@ -38,6 +39,7 @@
|
|||||||
"name": "@superlist/web",
|
"name": "@superlist/web",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@better-auth/passkey": "1.7.7",
|
||||||
"@fontsource-variable/geist": "^5.3.0",
|
"@fontsource-variable/geist": "^5.3.0",
|
||||||
"@hookform/resolvers": "^5.9.1",
|
"@hookform/resolvers": "^5.9.1",
|
||||||
"@superlist/shared": "workspace:*",
|
"@superlist/shared": "workspace:*",
|
||||||
@@ -292,6 +294,8 @@
|
|||||||
|
|
||||||
"@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],
|
"@better-auth/mongo-adapter": ["@better-auth/mongo-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "mongodb": "^6.0.0 || ^7.0.0" }, "optionalPeers": ["mongodb"] }, "sha512-ZnVDuRrXqbf0oHphrEN27oTImNH5NTO26dtWatq5cXyYAsH7goof9QIoTOmxTbBxUQahKBw9T6+9h6n+RtOE+g=="],
|
||||||
|
|
||||||
|
"@better-auth/passkey": ["@better-auth/passkey@1.7.7", "", { "dependencies": { "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.3.1", "zod": "^4.5.4" }, "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2", "better-auth": "^1.7.7", "better-call": "1.4.0", "nanostores": "^1.0.1" } }, "sha512-FMhL3bspBxne8EcyPWx9LdWUCnmrNRoSxCnH9Q2FIWsSWXMYuPPcHOs07v4g0zUXmTlBSr4vwW3J6t2vdUIOlg=="],
|
||||||
|
|
||||||
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],
|
"@better-auth/prisma-adapter": ["@better-auth/prisma-adapter@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@prisma/client", "prisma"] }, "sha512-4YcnrcVdvWiAZw0sZl63tWUClPXg5r3QsLn7C2sG7kKEBY06zOng0ibecyxRBixKq1zE1ceHuEUqez5Rhi+nQA=="],
|
||||||
|
|
||||||
"@better-auth/telemetry": ["@better-auth/telemetry@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],
|
"@better-auth/telemetry": ["@better-auth/telemetry@1.7.7", "", { "peerDependencies": { "@better-auth/core": "^1.7.7", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.2" } }, "sha512-PaRA6i+kAioVYmza2gHPcdrxP0hAotph4KV9hft2GeNJq+AZXDiBu3FuLM9HxvcmiZeUT74Vufqd9ypmB8veTA=="],
|
||||||
@@ -340,6 +344,8 @@
|
|||||||
|
|
||||||
"@fontsource-variable/geist": ["@fontsource-variable/geist@5.3.0", "", {}, "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA=="],
|
"@fontsource-variable/geist": ["@fontsource-variable/geist@5.3.0", "", {}, "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA=="],
|
||||||
|
|
||||||
|
"@hexagon/base64": ["@hexagon/base64@1.1.28", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="],
|
||||||
|
|
||||||
"@hono/node-server": ["@hono/node-server@1.19.9", "", { "peerDependencies": { "hono": "^4" } }, "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw=="],
|
"@hono/node-server": ["@hono/node-server@1.19.9", "", { "peerDependencies": { "hono": "^4" } }, "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw=="],
|
||||||
|
|
||||||
"@hono/zod-validator": ["@hono/zod-validator@0.9.1", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="],
|
"@hono/zod-validator": ["@hono/zod-validator@0.9.1", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="],
|
||||||
@@ -366,6 +372,8 @@
|
|||||||
|
|
||||||
"@kobalte/utils": ["@kobalte/utils@0.9.2", "", { "dependencies": { "@solid-primitives/event-listener": "^2.2.14", "@solid-primitives/keyed": "^1.2.0", "@solid-primitives/map": "^0.4.7", "@solid-primitives/media": "^2.2.4", "@solid-primitives/props": "^3.1.8", "@solid-primitives/refs": "^1.0.5", "@solid-primitives/utils": "^6.2.1" }, "peerDependencies": { "solid-js": "^1.8.8" } }, "sha512-jRVXr+zsVHxzDXRoh+CDeXzvCsFJ6uiHhqqNQ26Cw9ZsZ3D6nqPUBt1gGVtj2ZPmRL3a9Uk1v8D1aJ8/I12Dow=="],
|
"@kobalte/utils": ["@kobalte/utils@0.9.2", "", { "dependencies": { "@solid-primitives/event-listener": "^2.2.14", "@solid-primitives/keyed": "^1.2.0", "@solid-primitives/map": "^0.4.7", "@solid-primitives/media": "^2.2.4", "@solid-primitives/props": "^3.1.8", "@solid-primitives/refs": "^1.0.5", "@solid-primitives/utils": "^6.2.1" }, "peerDependencies": { "solid-js": "^1.8.8" } }, "sha512-jRVXr+zsVHxzDXRoh+CDeXzvCsFJ6uiHhqqNQ26Cw9ZsZ3D6nqPUBt1gGVtj2ZPmRL3a9Uk1v8D1aJ8/I12Dow=="],
|
||||||
|
|
||||||
|
"@levischuck/tiny-cbor": ["@levischuck/tiny-cbor@0.2.11", "", {}, "sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow=="],
|
||||||
|
|
||||||
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="],
|
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="],
|
||||||
|
|
||||||
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
|
"@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="],
|
||||||
@@ -384,6 +392,32 @@
|
|||||||
|
|
||||||
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
|
"@oxc-project/types": ["@oxc-project/types@0.153.0", "", {}, "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-android": ["@peculiar/asn1-android@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-AuUBRDNdWrgtnuJGXARa0Xdtq6OAD8GqezDQz6Qka7kyynMo9fzkcrtpBEHuX984uEB570BrhMZfJfkUDfpQfw=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-cms": ["@peculiar/asn1-cms@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-Bk+oatE62dW0Tzzpfk6vdQxfGGEfvuGdWgmijnKjcv7HqZCJISs85z4zw2uDArrk+R1Oel1wts/BBl7HHrtAcA=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-csr": ["@peculiar/asn1-csr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-KVfbXaKng8886/tOPG55t5K1XkTkGbR4amjIJzytXWobFU5nZgw/sKnSpa1hxP17nUSsrOF/7Mt9WUYeyLsi6Q=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-ecc": ["@peculiar/asn1-ecc@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-7MSNji77fQa/oN3WAfwagMy8EoJFg50sW4hZ1dtr0zU1BSugit0I2DGpIdPhvkNplopQhz5bogxpn1077eaamA=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-pfx": ["@peculiar/asn1-pfx@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-rsa": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-2SN2z8qkc2hk/GgTYA8RN54wtsCDZShg9gI2Mq1vLhdj1adcv5fhTbiEmExZUaAMqlizxiEpULQDfHM5iYtn1g=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-pkcs8": ["@peculiar/asn1-pkcs8@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-HqsSrnpQghRp9SM9QSmR6fa4z/BNktnKq7928+oq4qF0VAnuHZ4cyePKvcxh9fP4taBCP/WHNItlVNsYaQm2qw=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-pkcs9": ["@peculiar/asn1-pkcs9@2.11.1", "", { "dependencies": { "@peculiar/asn1-cms": "^2.11.1", "@peculiar/asn1-pfx": "^2.11.1", "@peculiar/asn1-pkcs8": "^2.11.1", "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "@peculiar/asn1-x509-attr": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-OHFkTg8D2zYafILqFE4KPbqX8srpvd3diGDc2h2cduumawc765mOHGcuFMGvLWlL2bbCMWMmMSCtlXptsOuiPA=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-rsa": ["@peculiar/asn1-rsa@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-6KwKGjulF489CpidZqkogNgLj6oGzgC4BL2FClM8PuJQ4t5NqT4q4a6A4vrSxBIBhMnL8hGYkLOpbVw0Vq38Tw=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-schema": ["@peculiar/asn1-schema@2.11.1", "", { "dependencies": { "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-jaU9OaCcbZUdyXx9hMETZB9xoNmxTGjOGFqd3cOwKFkpKnyKd9WxF3uqj4PvX4cyOMP9bSdHg5YyML2qtx/d/g=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-x509": ["@peculiar/asn1-x509@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/utils": "^2.0.2", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-SXU4/X6B3FquqQAN6ARI0bFDUV7+L1WlvPEPMKzEMkstd2D7UyM0r93fv241+OjdhqAKYGx5MvV3gzZMAp0APA=="],
|
||||||
|
|
||||||
|
"@peculiar/asn1-x509-attr": ["@peculiar/asn1-x509-attr@2.11.1", "", { "dependencies": { "@peculiar/asn1-schema": "^2.11.1", "@peculiar/asn1-x509": "^2.11.1", "asn1js": "^3.0.10", "tslib": "^2.8.1" } }, "sha512-n7RKFrbTzt8pGBlZ90kmKEn1qsLTTyw7lrvHMK0xsA42kQugPk/GXYpNbEcl7DkkdVsU/one5UX7KQPfxLj8vQ=="],
|
||||||
|
|
||||||
|
"@peculiar/utils": ["@peculiar/utils@2.0.3", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ=="],
|
||||||
|
|
||||||
|
"@peculiar/x509": ["@peculiar/x509@1.14.3", "", { "dependencies": { "@peculiar/asn1-cms": "^2.6.0", "@peculiar/asn1-csr": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.0", "@peculiar/asn1-pkcs9": "^2.6.0", "@peculiar/asn1-rsa": "^2.6.0", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.0", "pvtsutils": "^1.3.6", "reflect-metadata": "^0.2.2", "tslib": "^2.8.1", "tsyringe": "^4.10.0" } }, "sha512-C2Xj8FZ0uHWeCXXqX5B4/gVFQmtSkiuOolzAgutjTfseNOHT3pUjljDZsTSxXFGgio54bCzVFqmEOUrIVk8RDA=="],
|
||||||
|
|
||||||
"@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
|
"@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="],
|
||||||
|
|
||||||
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
|
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
|
||||||
@@ -632,6 +666,10 @@
|
|||||||
|
|
||||||
"@shadcn/registry": ["@shadcn/registry@0.1.3", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "cn": "^0.2.4", "code-block-writer": "^13.0.3", "deepmerge": "^4.3.1", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "ora": "^8.2.0", "postcss": "^8.5.23", "prompts": "^2.4.2", "recast": "^0.23.11", "socks": "^2.8.8", "stringify-object": "^5.0.0", "tsconfig-paths": "^4.2.0", "type-fest": "^4.41.0", "undici": "^7.29.0", "zod": "^3.24.1" } }, "sha512-82/OmKAVM9pChDHFVAsDP9PcimPGSKZGdbcdwdGGGcSI69ImpN4ZnqsfZ4hkOFEMal92t3y9djYJHMjO4PcVZA=="],
|
"@shadcn/registry": ["@shadcn/registry@0.1.3", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "cn": "^0.2.4", "code-block-writer": "^13.0.3", "deepmerge": "^4.3.1", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "ora": "^8.2.0", "postcss": "^8.5.23", "prompts": "^2.4.2", "recast": "^0.23.11", "socks": "^2.8.8", "stringify-object": "^5.0.0", "tsconfig-paths": "^4.2.0", "type-fest": "^4.41.0", "undici": "^7.29.0", "zod": "^3.24.1" } }, "sha512-82/OmKAVM9pChDHFVAsDP9PcimPGSKZGdbcdwdGGGcSI69ImpN4ZnqsfZ4hkOFEMal92t3y9djYJHMjO4PcVZA=="],
|
||||||
|
|
||||||
|
"@simplewebauthn/browser": ["@simplewebauthn/browser@13.3.0", "", {}, "sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ=="],
|
||||||
|
|
||||||
|
"@simplewebauthn/server": ["@simplewebauthn/server@13.3.3", "", { "dependencies": { "@hexagon/base64": "^1.1.27", "@levischuck/tiny-cbor": "^0.2.2", "@peculiar/asn1-android": "^2.6.0", "@peculiar/asn1-ecc": "^2.6.1", "@peculiar/asn1-rsa": "^2.6.1", "@peculiar/asn1-schema": "^2.6.0", "@peculiar/asn1-x509": "^2.6.1", "@peculiar/x509": "^1.14.3" } }, "sha512-LelX/lcy5cjc15A86i/aNxHhB5eU7dd20QsbP0VLAf9e38+SLlsnqCCyecx3xqfGofhmX05h1J9fKRYWxw+luA=="],
|
||||||
|
|
||||||
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
|
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
|
||||||
|
|
||||||
"@solid-primitives/event-listener": ["@solid-primitives/event-listener@2.4.6", "", { "dependencies": { "@solid-primitives/utils": "^6.4.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-5I0YJcTVYIWoMmgBSROBZGcz+ymhew/pGTg2dHW74BUjFKsV8Li4bOZYl0YAGP4mHw5o4UBd9/BEesqBci3wxw=="],
|
"@solid-primitives/event-listener": ["@solid-primitives/event-listener@2.4.6", "", { "dependencies": { "@solid-primitives/utils": "^6.4.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-5I0YJcTVYIWoMmgBSROBZGcz+ymhew/pGTg2dHW74BUjFKsV8Li4bOZYl0YAGP4mHw5o4UBd9/BEesqBci3wxw=="],
|
||||||
@@ -854,6 +892,8 @@
|
|||||||
|
|
||||||
"arraybuffer.prototype.slice": ["arraybuffer.prototype.slice@1.0.4", "", { "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "is-array-buffer": "^3.0.4" } }, "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ=="],
|
"arraybuffer.prototype.slice": ["arraybuffer.prototype.slice@1.0.4", "", { "dependencies": { "array-buffer-byte-length": "^1.0.1", "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.5", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "is-array-buffer": "^3.0.4" } }, "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ=="],
|
||||||
|
|
||||||
|
"asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="],
|
||||||
|
|
||||||
"assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
|
"assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
|
||||||
|
|
||||||
"ast-types": ["ast-types@0.16.3", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA=="],
|
"ast-types": ["ast-types@0.16.3", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-FvWoWYfSCM6kRxCSH+MGLHIKKGRL6A6AW7Zek2O32REPQRdg131428uRTKMBYAeRd3XXAaHDS60Wpri7CdKDrA=="],
|
||||||
@@ -1596,6 +1636,10 @@
|
|||||||
|
|
||||||
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||||
|
|
||||||
|
"pvtsutils": ["pvtsutils@1.3.6", "", { "dependencies": { "tslib": "^2.8.1" } }, "sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg=="],
|
||||||
|
|
||||||
|
"pvutils": ["pvutils@1.2.0", "", {}, "sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg=="],
|
||||||
|
|
||||||
"qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="],
|
"qs": ["qs@6.16.0", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA=="],
|
||||||
|
|
||||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||||
@@ -1638,6 +1682,8 @@
|
|||||||
|
|
||||||
"redux-thunk": ["redux-thunk@3.1.0", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
|
"redux-thunk": ["redux-thunk@3.1.0", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
|
||||||
|
|
||||||
|
"reflect-metadata": ["reflect-metadata@0.2.2", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
|
||||||
|
|
||||||
"reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
|
"reflect.getprototypeof": ["reflect.getprototypeof@1.0.10", "", { "dependencies": { "call-bind": "^1.0.8", "define-properties": "^1.2.1", "es-abstract": "^1.23.9", "es-errors": "^1.3.0", "es-object-atoms": "^1.0.0", "get-intrinsic": "^1.2.7", "get-proto": "^1.0.1", "which-builtin-type": "^1.2.1" } }, "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw=="],
|
||||||
|
|
||||||
"regenerate": ["regenerate@1.5.0", "", {}, "sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw=="],
|
"regenerate": ["regenerate@1.5.0", "", {}, "sha512-1s+CxXjJ71i7LNVy8nYwg47XV4y6lAnOEhsMtSKq3WpmPfhl9LuKlTqKIn/3yUpE8lBz+W+TT88Bxyhnr0U4yw=="],
|
||||||
@@ -1844,6 +1890,8 @@
|
|||||||
|
|
||||||
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
|
||||||
|
|
||||||
|
"tsyringe": ["tsyringe@4.10.0", "", { "dependencies": { "tslib": "^1.9.3" } }, "sha512-axr3IdNuVIxnaK5XGEUFTu3YmAQ6lllgrvqfEoR16g/HGnYY/6We4oWENtAnzK6/LpJ2ur9PAb80RBt7/U4ugw=="],
|
||||||
|
|
||||||
"turbo": ["turbo@2.11.7", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.7", "@turbo/darwin-arm64": "2.11.7", "@turbo/linux-64": "2.11.7", "@turbo/linux-arm64": "2.11.7", "@turbo/windows-64": "2.11.7", "@turbo/windows-arm64": "2.11.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RhXHbqfvY6o3xt/zSHCwSNwLrZlXiqHzewi4eAj9PtZ1T1CqgMJ2yIDb7SKPTG9IikTm925mfzL6hldQVdyNWw=="],
|
"turbo": ["turbo@2.11.7", "", { "optionalDependencies": { "@turbo/darwin-64": "2.11.7", "@turbo/darwin-arm64": "2.11.7", "@turbo/linux-64": "2.11.7", "@turbo/linux-arm64": "2.11.7", "@turbo/windows-64": "2.11.7", "@turbo/windows-arm64": "2.11.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-RhXHbqfvY6o3xt/zSHCwSNwLrZlXiqHzewi4eAj9PtZ1T1CqgMJ2yIDb7SKPTG9IikTm925mfzL6hldQVdyNWw=="],
|
||||||
|
|
||||||
"tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
|
"tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="],
|
||||||
@@ -2118,6 +2166,8 @@
|
|||||||
|
|
||||||
"terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],
|
"terser/commander": ["commander@2.20.3", "", {}, "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ=="],
|
||||||
|
|
||||||
|
"tsyringe/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
|
||||||
|
|
||||||
"type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
|
"type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
|
||||||
|
|
||||||
"workbox-build/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="],
|
"workbox-build/fs-extra": ["fs-extra@9.1.0", "", { "dependencies": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ=="],
|
||||||
|
|||||||
@@ -24,7 +24,11 @@ services:
|
|||||||
LOG_LEVEL: ${LOG_LEVEL:-}
|
LOG_LEVEL: ${LOG_LEVEL:-}
|
||||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||||
MAIL_FROM: ${MAIL_FROM:-}
|
MAIL_FROM: ${MAIL_FROM:-}
|
||||||
# Dictation (optional): without the key, dictated text is split without AI.
|
# Dictation (optional): Groq when its key is set, else Gemini; without any key,
|
||||||
|
# dictated text is split without AI.
|
||||||
|
GROQ_API_KEY: ${GROQ_API_KEY:-}
|
||||||
|
GROQ_MODEL: ${GROQ_MODEL:-openai/gpt-oss-120b}
|
||||||
|
GROQ_TIMEOUT_MS: ${GROQ_TIMEOUT_MS:-8000}
|
||||||
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
|
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
|
||||||
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
|
GEMINI_MODEL: ${GEMINI_MODEL:-gemma-4-26b-a4b-it}
|
||||||
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
|
GEMINI_TIMEOUT_MS: ${GEMINI_TIMEOUT_MS:-8000}
|
||||||
|
|||||||
@@ -42,4 +42,8 @@ export const VOICE_SPLIT_EXAMPLES: { said: string; items: string[] }[] = [
|
|||||||
said: 'cuatrocientos gramos de queso y leche descremada',
|
said: 'cuatrocientos gramos de queso y leche descremada',
|
||||||
items: ['400g de queso', 'Leche (descremada)'],
|
items: ['400g de queso', 'Leche (descremada)'],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
said: 'azúcar leche y café',
|
||||||
|
items: ['Azúcar', 'Leche', 'Café'],
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -21,7 +21,10 @@
|
|||||||
"WEB_APP_URL",
|
"WEB_APP_URL",
|
||||||
"GEMINI_API_KEY",
|
"GEMINI_API_KEY",
|
||||||
"GEMINI_MODEL",
|
"GEMINI_MODEL",
|
||||||
"GEMINI_TIMEOUT_MS"
|
"GEMINI_TIMEOUT_MS",
|
||||||
|
"GROQ_API_KEY",
|
||||||
|
"GROQ_MODEL",
|
||||||
|
"GROQ_TIMEOUT_MS"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"dev": {
|
"dev": {
|
||||||
@@ -40,6 +43,9 @@
|
|||||||
"GEMINI_API_KEY",
|
"GEMINI_API_KEY",
|
||||||
"GEMINI_MODEL",
|
"GEMINI_MODEL",
|
||||||
"GEMINI_TIMEOUT_MS",
|
"GEMINI_TIMEOUT_MS",
|
||||||
|
"GROQ_API_KEY",
|
||||||
|
"GROQ_MODEL",
|
||||||
|
"GROQ_TIMEOUT_MS",
|
||||||
"VITE_API_URL"
|
"VITE_API_URL"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user