Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.20.0): the Sound wave — library, Freesound, voiceover, SFX
Ashiq Hussain Mir1c5b094676c9
diff --git a/.env.example b/.env.exampleindex 5aaab26..c84ed11 100644--- a/.env.example+++ b/.env.example@@ -49,6 +49,15 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-c# PEXELS_API_BASE=https://api.pexels.com# PIXABAY_API_BASE=https://pixabay.com/api+# ── Stock sound search (optional, Sound wave) ────────────────+# The Audio rail's Freesound search. One FREE key; results are+# Creative Commons 0 by default. With no key the offline 16-sound+# pack, voiceover recording and uploads keep working (see+# docs/SOUND.md). Keys are server-side only.+# https://freesound.org/apiv2/apply/+# FREESOUND_API_KEY=your-free-key+# FREESOUND_API_BASE=https://freesound.org/apiv2+# ── AI agents / MCP server (optional, v0.6) ───────────────────# Model Context Protocol endpoint: POST /api/mcp# Lets AI assistants (Claude Desktop, Cursor, ChatGPT, any MCP client)diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 65bf667..66ba315 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,88 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.20.0] — 2026-11-10++The Sound wave — closing the audit's Sound gap cluster in full+(guide + licence manifest: `docs/SOUND.md`). The beat-sync moat had+no sound source: audio elements, waveform rendering and beat+detection shipped in v0.11, but there was no way to GET a sound.+Four features, all riding existing rails (the A4 stock-connector+architecture, the chunked media store, the v0.11 audio analysis):+the CC0 library (3.1), the Freesound connector (3.2), voiceover+recording (3.3) and animation/transition SFX (3.4). **No+migration** — `ElementAnimation.sfxId`, `PageTransition.sfxId` and+`AudioElement.credit` ride as additive nullable fields; pre-sound+documents open unchanged.++### Added++- **Offline sound library — 16 original CC0 sounds.** `public/sfx/`+ generated by `scripts/gen-sfx-pack.mjs`: pure code synthesis+ (oscillators, shaped noise, envelopes; deterministic LCG noise so+ builds are reproducible — no samples, no third-party recordings,+ the project can actually grant CC0). Four categories (Transitions,+ Impacts, UI, Musical), mono 16-bit 44.1 kHz, ≤ 1.1 s each.+ Catalogue `src/lib/assets/sfx-pack.ts` with stable ids; unit tests+ pin catalogue ↔ files ↔ RIFF headers ↔ durations.+- **Freesound search — the fourth stock-media connector.**+ `src/lib/stock-sound.ts` + `POST /api/stock-sound/search` (rate+ bucket `stocksound:search` 20/min, admin `soundSearch` kill+ switch, F2b NO_PROVIDER + operator hint) + secret-free+ `GET /api/stock-sound/available`. **CC0-filtered by default** (the+ audit's standing requirement; wider licences are an explicit+ request). Key resolution console-first (Stock media card →+ `FREESOUND_API_KEY` env), 24 h in-memory response cache,+ status-only errors, defensive parsing. Inserts download the+ preview MP3 in the browser, ride the chunked media store and the+ full audio analysis, and store a durable credit block on+ `AudioElement.credit` (properties-bar chip — the A4 photo+ pattern).+- **Voiceover recording.** The Audio panel's Record button:+ `getUserMedia` + `MediaRecorder` (Opus/WebM, MP4 on Safari),+ 5-minute cap, live timer; permission denials surface as an honest+ toast. The recording rides the same insert path — waveform, BPM+ and beat grid bake in.+- **Animation + page-transition sound effects.**+ `ElementAnimation.sfxId` / `PageTransition.sfxId` (additive,+ nullable): one of the 16 pack sounds, picked in the Animate panel+ ("Entrance sound" / "Transition sound") with an inline audition+ button. Playback in Preview/Presenter: element SFX fire on the+ rAF clock when the animation triggers (at its delay); transition+ SFX fire when a page appears. `prefers-reduced-motion` mutes+ everything. Video export does not fire sfxId triggers in v1 —+ documented, with the autoplay-element workaround stated in the+ panel.+- **The Audio rail.** `AudioPanel` in the editor's left rail:+ library grid (audition + insert), gated Freesound search (the+ PhotosPanel debounce/race-guard pattern), voiceover recorder, and+ the uploads pointer. Panel id `audio` through the store/rail/Editor.++### Changed++- **Admin console.** The Stock media card gains the Freesound row+ (write-only key, Test = one real CC0 probe, Clear) and is renamed+ "Stock media — Pexels, Pixabay & Freesound"; feature toggles gain+ the Sound search switch; `/api/ai/capabilities` reports+ `soundSearch`.+- **Stock key plumbing generalized** — `StockProviderName` extends+ to `freesound` through the admin config (validation, stored keys,+ env fallback), and the stock card's input state became a generic+ per-provider record.++### Tested++- 21 new unit tests: sfx-pack integrity (ids/files/RIFF/durations),+ sanitizeAnimation/sanitizePageTransition sfxId acceptance ++ hostile-id dropping, stock-sound parsing against recorded+ Freesound shapes (licence mapping, hostile rows dropped, cache,+ sanitized errors), route invariants (F2b gate, CSRF, happy path,+ key-never-leaks).+- `tests/e2e/sound-gated.spec.ts`: the no-key world (available+ 503-gated, hint, capabilities false, rail + 16-sound grid + insert+ landing an audio element, voiceover surface) and the SFX picker+ round-trip in the Animate panel.+## [0.19.0] — 2026-11-09Wave 4 of the consolidation programme — AI Power-Up (roadmap:diff --git a/README.md b/README.mdindex a7415ca..50957e6 100644--- a/README.md+++ b/README.md@@ -261,6 +261,18 @@ is right here.`docs/GIF-EXPORT.md`); rides the same deterministic frame rendereras video export. GIFs are silent — the dialog says so before youclick+- **Sound — library, Freesound, voiceover, animation SFX** *(the+ Sound wave)* — the **Audio** rail: a 16-sound offline library+ (**original code synthesis — pure CC0**, generated by+ `scripts/gen-sfx-pack.mjs`), provider-gated **Freesound** search+ (**CC0 by default**, one free key, durable attribution on every+ insert — the A4 stock-connector pattern), and **voiceover+ recording** through your mic into the media library. Every insert+ bakes the full analysis (waveform + BPM + beat grid), so Beat+ Sync works day one. Animations and page transitions gained+ **sound effects** (16 pack sounds, auditioned inline, played in+ Preview/Present, muted by reduce-motion). Zero new dependencies;+ operator guide + licence manifest in `docs/SOUND.md`- **Stock photos** *(v0.16.4 A4)* — the Photos panel's search runs onthe stock-provider keys (Pexels / Pixabay, the same free keys as theVideos rail — no key = the bundled library keeps working and the@@ -780,6 +792,8 @@ limited per IP and logs usage into the `AIUsage` table.| Translate | ⚙️ needs a server AI provider || Stock photo search | ⚙️ needs `PEXELS_API_KEY` or `PIXABAY_API_KEY` (free) || Stock video search | ⚙️ needs `PEXELS_API_KEY` or `PIXABAY_API_KEY` (free) |+| **Sound library + voiceover + animation SFX** | ✅ local — Sound wave, always available |+| **Freesound sound search** | ⚙️ needs `FREESOUND_API_KEY` (free, CC0 default) — Sound wave || MCP server (agent tools) | ✅ with token set — `generate_design` needs the AI provider, `vision_ground` the vision slot |See `docs/AI-POWER-UP.md` for the full Wave 4 guide.diff --git a/docs/ADMIN.md b/docs/ADMIN.mdindex 46c66d9..ed44d44 100644--- a/docs/ADMIN.md+++ b/docs/ADMIN.md@@ -352,6 +352,20 @@ probes that provider; `model` overrides the model for the probe.and caps at 240 chars. The same string flows to AIUsage (`error`),the client 502 body (`detail`) and the console — no place shows araw provider body, and no place shows different truths.+- **D18 (Sound wave) — Freesound is the fourth stock connector, and+ the SFX pack is original CC0 synthesis.** Sound search rides the+ A4/R6 stock-connector architecture (`src/lib/stock-sound.ts`,+ one free Freesound key, console-manageable in the Stock media+ card, `FREESOUND_API_KEY` env fallback, 24 h response cache,+ status-only errors) — never an AI slot; the `soundSearch` feature+ switch gates it with the photoSearch semantics. Results are+ **CC0-filtered by default** (the wider licence filter is an+ explicit request), and every insert stores a durable credit block+ on `AudioElement.credit`. The 16-sound offline pack+ (`public/sfx/`, generated by `scripts/gen-sfx-pack.mjs`) is pure+ code synthesis — no samples — released CC0 (manifest:+ docs/SOUND.md). Animation/transition `sfxId` fields are additive+ and validated against the catalogue on sanitize. No migration.- **D17 (A4) — photo search LEFT the AI provider table.** The`imageSearch` slot called an `images/search` route that almost noOpenAI-compatible vendor serves — a category error: stock photodiff --git a/docs/COMPETITIVE-ANALYSIS.md b/docs/COMPETITIVE-ANALYSIS.mdindex 31d7e0d..6a5fbe9 100644--- a/docs/COMPETITIVE-ANALYSIS.md+++ b/docs/COMPETITIVE-ANALYSIS.md@@ -103,6 +103,17 @@ generations" refusal surfaces as a structured 422 pointing at the localtools. No migration. Guide: docs/AI-POWER-UP.md · acceptance: 1309 unittests (+54), wave4 e2e suite (tests/e2e/wave4-ai-powerup.spec.ts).+### Sound cluster ✅ SHIPPED (v0.20.0, 2026-11-10)+The original audit's Wave 3 ("Sound — feed the beat-sync moat") was re-scoped+out of the consolidation programme's Wave 3 (editor depth) and is now closed+as its own release: 16-sound offline library (original code synthesis, CC0 —+no samples) · Freesound connector (the fourth stock-media connector, CC0+filter by default, durable attribution) · voiceover recording (MediaRecorder →+media store, full beat analysis) · animation + page-transition SFX+(`sfxId`, additive). The v0.11 beat-sync infrastructure finally has a sound+source. No migration. Guide + licence manifest: docs/SOUND.md · acceptance:+1330 unit tests (+21), tests/e2e/sound-gated.spec.ts.+### Wave 5 — Export & Sharing ProfessionalisationShare links with view/comment/edit roles + password + expiry · ZIP batch export · WebP · PPTX ·print production marks (bleed/crop/300 DPI) · server-side rendering · portable `.canvix` projectdiff --git a/docs/SOUND.md b/docs/SOUND.mdnew file mode 100644index 0000000..44a9b6a--- /dev/null+++ b/docs/SOUND.md@@ -0,0 +1,117 @@+# Sound — operator guide & decision record (the Sound wave)++The Audio rail puts every way of getting sound into a design in+one place: an **offline pack of 16 synthesized sounds** (works with+zero configuration), **Freesound search** (provider-gated, CC0 by+default), **voiceover recording** (your mic), and a pointer to+audio **uploads**. Sound effects also attach to **element+animations and page transitions** (`sfxId`) and play in Preview and+Present.++This closes the audit's Sound gap cluster in full: 3.1 the CC0+library, 3.2 the Freesound connector, 3.3 voiceover recording,+3.4 animation and transition sound effects.++## The licence manifest (3.1)++Every file in `public/sfx/*.wav` is an **original synthesis by the+Canvix project** — oscillators, shaped noise and envelopes in pure+code (`scripts/gen-sfx-pack.mjs`, deterministic LCG noise so builds+are reproducible). No samples, no third-party recordings. The pack+is released **CC0** (`docs/SOUND.md` is the manifest): use the+sounds anywhere, no attribution required — the credit block on an+inserted pack sound says so for the record.++Freesound results carry the licence the API reports; the connector+**filters to Creative Commons 0 by default**, and the credit block+stored on the element shows provider · author · licence with the+source URL (the A4 photo attribution pattern — durable on the+element, shown in the properties bar, never burned into exports).++## Why sound search is NOT an AI feature (the A4 pattern, again)++"Find me a rain sound" is a library query against a licensed+catalog — the same reasoning that moved photo search off the AI+provider table (docs/STOCK-PHOTO.md). Freesound is the **fourth+stock-media connector**, riding the R6/A4/A5 architecture: plain+REST, one free key, console-manageable, 24 h in-memory response+cache, status-only errors, normalized results with durable credit+blocks.++## Providers++| Provider | Console card | Env fallback | Where to get it | License |+|---|---|---|---|---|+| Freesound | Stock media → Freesound | `FREESOUND_API_KEY` | https://freesound.org/apiv2/apply/ (free) | CC0 (default filter) · CC BY & friends opt-in |++**Key resolution (A5 pattern):** a key stored on the admin AI &+models page (Stock media card) wins over the env var; clearing the+stored key restores the env fallback; no key at all ⇒ the Freesound+section shows the operator hint and `POST /api/stock-sound/search`+answers `503 NO_PROVIDER` — the offline pack and everything else+keep working (F2b fail-closed).++The admin **Test** button runs one minimal real search through the+effective key (`POST /api/admin/config/stock-test` with+`{provider: 'freesound'}`) — the same probe shape as Pexels and+Pixabay, rate-limited to one per 10 s.++## The insert path (and its honest limits)++- **Freesound results** insert the **preview MP3** (HQ when+ present). Original FLAC/WAV/OGG downloads need OAuth2 on+ Freesound's side — out of scope for the self-hoster key flow, and+ the preview quality is what Canva-class tools insert anyway.+ Downloads happen in the browser (the CDN is CORS-open), then ride+ the existing chunked media store: quota, sha256 dedupe and the+ size caps all apply.+- **Every insert** (pack sound, Freesound result, voiceover) runs+ the full audio analysis — waveform peaks, BPM, beat grid — so+ **Beat Sync works on day one** (an audio element with a beat grid+ drives the beat clock in Preview).+- **Voiceover** records through `MediaRecorder` (Opus/WebM, MP4 on+ Safari), capped at 5 minutes, and stores the "recorded by the+ author" credit block. Mic permission denials surface as an honest+ toast, never a broken UI.++## Animation + transition SFX (3.4)++`ElementAnimation.sfxId` and `PageTransition.sfxId` (both additive,+nullable, no migration) name one of the 16 pack sounds:++- The **Animate panel** exposes "Entrance sound" on animated+ elements and "Transition sound" on page transitions — a select+ with an inline audition button.+- **Playback**: the Preview/Presenter engine fires element SFX on+ the rAF clock when the animation triggers (at its delay), and the+ transition SFX when a page appears. `prefers-reduced-motion`+ mutes everything (the accessibility posture of the animations+ themselves).+- **Sanitization**: `sanitizeAnimation` / `sanitizePageTransition`+ validate the id against the pack catalogue — hostile or stale+ input can only pick from the bundled files, and unknown ids are+ dropped, never stored.+- **Video export does not fire sfxId triggers in v1** (the export+ muxer mixes page audio elements, not per-animation triggers —+ recorded here so nobody has to rediscover it). The panel says the+ workaround inline: insert the sound from the Audio panel as an+ autoplay audio element and it rides the existing export path.++## API surface++| Route | What |+|---|---|+| `GET /api/stock-sound/available` | secret-free feature detection (`{available, providers}`) |+| `POST /api/stock-sound/search` | `{query, count, includeOtherLicenses?}` → normalized CC0-first results (rate bucket `stocksound:search`, 20/min; admin `soundSearch` kill switch) |+| `POST /api/admin/config/stock-test` | `{provider: 'freesound'}` — one real probe through the effective key |++`/api/ai/capabilities` reports `soundSearch` (stock key + admin+flag — never an AI slot). The admin console's feature toggles+include the Sound search switch.++## Dependency decision++**Zero new runtime dependencies** — the Freesound API is+JSON-over-GET with one token, the SFX pack is generated at build+time by a Node script with no imports, and the player is ~80 lines+over the native `Audio` element. Recorded per the house rule.diff --git a/package-lock.json b/package-lock.jsonindex ae1a1d7..491586e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "canvix",- "version": "0.19.0",+ "version": "0.20.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "canvix",- "version": "0.19.0",+ "version": "0.20.0","hasInstallScript": true,"dependencies": {"@imgly/background-removal": "^1.7.0",diff --git a/package.json b/package.jsonindex 01c6345..9dc71cd 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.19.0",+ "version": "0.20.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.jsonindex d33866f..fa5a597 100644--- a/public/plugins/wordcloud/manifest.json+++ b/public/plugins/wordcloud/manifest.json@@ -9,7 +9,7 @@"url": "https://github.com/mir-ashiq/canvix"},"engines": {- "canvix": ">=0.13.4 <0.20.0"+ "canvix": ">=0.13.4 <0.21.0"},"entry": {"panel": "panel.html",diff --git a/public/sfx/boom.wav b/public/sfx/boom.wavnew file mode 100644index 0000000..34e9de1Binary files /dev/null and b/public/sfx/boom.wav differdiff --git a/public/sfx/camera.wav b/public/sfx/camera.wavnew file mode 100644index 0000000..e34f75aBinary files /dev/null and b/public/sfx/camera.wav differdiff --git a/public/sfx/chime-sparkle.wav b/public/sfx/chime-sparkle.wavnew file mode 100644index 0000000..e6ebeb1Binary files /dev/null and b/public/sfx/chime-sparkle.wav differdiff --git a/public/sfx/chime.wav b/public/sfx/chime.wavnew file mode 100644index 0000000..6a6940cBinary files /dev/null and b/public/sfx/chime.wav differdiff --git a/public/sfx/click.wav b/public/sfx/click.wavnew file mode 100644index 0000000..6e6c434Binary files /dev/null and b/public/sfx/click.wav differdiff --git a/public/sfx/drum-kick.wav b/public/sfx/drum-kick.wavnew file mode 100644index 0000000..1f37f0fBinary files /dev/null and b/public/sfx/drum-kick.wav differdiff --git a/public/sfx/hat.wav b/public/sfx/hat.wavnew file mode 100644index 0000000..d828297Binary files /dev/null and b/public/sfx/hat.wav differdiff --git a/public/sfx/impact-hit.wav b/public/sfx/impact-hit.wavnew file mode 100644index 0000000..0abb741Binary files /dev/null and b/public/sfx/impact-hit.wav differdiff --git a/public/sfx/pop.wav b/public/sfx/pop.wavnew file mode 100644index 0000000..dbfc687Binary files /dev/null and b/public/sfx/pop.wav differdiff --git a/public/sfx/slide-in.wav b/public/sfx/slide-in.wavnew file mode 100644index 0000000..06e89b5Binary files /dev/null and b/public/sfx/slide-in.wav differdiff --git a/public/sfx/swoosh-reverse.wav b/public/sfx/swoosh-reverse.wavnew file mode 100644index 0000000..fad23fbBinary files /dev/null and b/public/sfx/swoosh-reverse.wav differdiff --git a/public/sfx/thud.wav b/public/sfx/thud.wavnew file mode 100644index 0000000..a4f5defBinary files /dev/null and b/public/sfx/thud.wav differdiff --git a/public/sfx/tick.wav b/public/sfx/tick.wavnew file mode 100644index 0000000..f491bd4Binary files /dev/null and b/public/sfx/tick.wav differdiff --git a/public/sfx/toggle.wav b/public/sfx/toggle.wavnew file mode 100644index 0000000..0565728Binary files /dev/null and b/public/sfx/toggle.wav differdiff --git a/public/sfx/whoosh-fast.wav b/public/sfx/whoosh-fast.wavnew file mode 100644index 0000000..a834491Binary files /dev/null and b/public/sfx/whoosh-fast.wav differdiff --git a/public/sfx/whoosh-soft.wav b/public/sfx/whoosh-soft.wavnew file mode 100644index 0000000..226e35fBinary files /dev/null and b/public/sfx/whoosh-soft.wav differdiff --git a/scripts/gen-sfx-pack.mjs b/scripts/gen-sfx-pack.mjsnew file mode 100755index 0000000..c75103f--- /dev/null+++ b/scripts/gen-sfx-pack.mjs@@ -0,0 +1,212 @@+// gen-sfx-pack.mjs — synthesize the Canvix offline sound pack (Wave: Sound).+//+// Every file is an ORIGINAL synthesis (oscillators, shaped noise, envelopes+// — no samples, no third-party recordings), so the pack ships CC0 with a+// licence manifest we can actually grant (docs/SOUND.md). Sounds are small+// (mono 16-bit 44.1 kHz WAV, 0.12–1.4 s) because they double as animation+// SFX played in tight succession.+//+// Output: public/sfx/<id>.wav (16 sounds) — the catalogue lives in+// src/lib/assets/sfx-pack.ts (ids must match; sfx-pack.test.ts pins it).+// Run: node scripts/gen-sfx-pack.mjs+import { mkdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++const SR = 44100++// ── tiny DSP kit ──────────────────────────────────────────────+/** deterministic LCG noise (same seed ⇒ same bytes ⇒ reproducible builds) */+function lcg(seed) {+ let s = seed >>> 0+ return () => {+ s = (Math.imul(s, 1664525) + 1013904223) >>> 0+ return s / 0xffffffff+ }+}++/** one-pole lowpass — smooths noise into whooshes/airs */+function lowpass(samples, cutoffHz, sr = SR) {+ const a = Math.exp((-2 * Math.PI * cutoffHz) / sr)+ let y = 0+ return samples.map((x) => (y = x * (1 - a) + y * a))+}++/** attack/decay envelope: 0→1 over attack s, 1→0 over the rest */+function env(n, attackS, releaseS = 0, sr = SR) {+ const a = Math.max(1, Math.round(attackS * sr))+ const rel = Math.max(0, Math.round(releaseS * sr))+ return (i) => {+ if (i < a) return i / a+ if (rel && i > n - rel) return Math.max(0, (n - i) / rel)+ return 1+ }+}++/** pad/truncate to exact length */+function fit(buf, n) {+ const out = new Float64Array(n)+ for (let i = 0; i < Math.min(n, buf.length); i++) out[i] = buf[i]+ return out+}++/** soft clip to [-1, 1] with gentle saturation */+function clip(x) {+ return Math.tanh(x * 1.2) * 0.92+}++// ── synth recipes (each returns Float64Array) ─────────────────++/** pure sine with exponential decay — chimes, pings */+function tone(freq, durS, { decay = 6, harmonics = [], attack = 0.004, sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const out = new Float64Array(n)+ const e = env(n, attack, 0, sr)+ for (let i = 0; i < n; i++) {+ const t = i / sr+ const d = Math.exp(-decay * t) * e(i)+ let v = Math.sin(2 * Math.PI * freq * t)+ for (const [mult, amp] of harmonics) v += amp * Math.sin(2 * Math.PI * freq * mult * t)+ out[i] = clip(v * d)+ }+ return out+}++/** frequency sweep with an envelope — whooshes, risers */+function sweep(fromHz, toHz, durS, { decay = 3, attack = 0.05, tail = 0.15, sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const out = new Float64Array(n)+ const e = env(n, attack, tail * 0, sr)+ let phase = 0+ for (let i = 0; i < n; i++) {+ const p = i / n+ const f = fromHz * Math.pow(toHz / fromHz, p)+ phase += (2 * Math.PI * f) / sr+ const d = Math.exp(-decay * p * 2) * e(i) * (p < 0.9 ? 1 : (1 - p) / 0.1)+ out[i] = clip(Math.sin(phase) * d * 0.8)+ }+ return out+}++/** shaped noise — whoosh bodies, tape-ish textures */+function noise(durS, { cutoff = 900, attack = 0.08, release = 0.25, gain = 0.8, seed = 7, sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const rnd = lcg(seed)+ const raw = new Float64Array(n)+ for (let i = 0; i < n; i++) raw[i] = rnd() * 2 - 1+ const smooth = lowpass(Array.from(raw), cutoff, sr)+ const e = env(n, attack, release, sr)+ return smooth.map((x, i) => clip(x * e(i) * gain))+}++/** kick — sine pitch drop with fast decay (classic 808-ish shape) */+function kick(fromHz = 160, toHz = 46, durS = 0.42, { sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const out = new Float64Array(n)+ let phase = 0+ for (let i = 0; i < n; i++) {+ const p = i / n+ const f = fromHz * Math.pow(toHz / fromHz, Math.pow(p, 0.55))+ phase += (2 * Math.PI * f) / sr+ const d = Math.exp(-7 * p) * Math.min(1, i / (0.004 * sr))+ out[i] = clip(Math.sin(phase) * d)+ }+ return out+}++/** pop — short sine blip with a pitch flip and tiny click */+function pop(durS = 0.14, { sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const out = new Float64Array(n)+ for (let i = 0; i < n; i++) {+ const t = i / sr+ const p = i / n+ const f = 340 + 900 * Math.exp(-26 * t)+ const d = Math.exp(-16 * t)+ out[i] = clip(Math.sin(2 * Math.PI * f * t) * d * 0.9 + (i < 40 ? (i / 40) * 0.25 : 0))+ }+ return out+}++/** sparkle — staggered high sine pings (arpeggio-ish shimmer) */+function sparkle(notes, noteDur, { decay = 7, sr = SR } = {}) {+ const n = Math.round((notes.length * noteDur + 0.5) * sr)+ const out = new Float64Array(n)+ notes.forEach((f, k) => {+ const seg = tone(f, noteDur + 0.4, { decay, attack: 0.002, sr })+ const off = Math.round(k * noteDur * sr)+ for (let i = 0; i < seg.length && off + i < n; i++) out[off + i] = clip(out[off + i] + seg[i] * 0.7)+ })+ return out+}++/** click — the shortest useful UI tick */+function click(durS = 0.045, { sr = SR } = {}) {+ const n = Math.round(durS * sr)+ const out = new Float64Array(n)+ for (let i = 0; i < n; i++) {+ const t = i / sr+ out[i] = clip((Math.sin(2 * Math.PI * 2100 * t) * 0.6 + (i < 30 ? 0.35 * (1 - i / 30) : 0)) * Math.exp(-70 * t))+ }+ return out+}++// ── the pack (16 sounds, 4 categories) ────────────────────────+const SOUNDS = [+ // Transitions — played on page changes / big element entrances+ { id: 'whoosh-soft', make: () => noise(0.85, { cutoff: 650, attack: 0.12, release: 0.3, gain: 0.85, seed: 11 }) },+ { id: 'whoosh-fast', make: () => noise(0.45, { cutoff: 1400, attack: 0.03, release: 0.12, gain: 0.9, seed: 23 }) },+ { id: 'swoosh-reverse', make: () => sweep(180, 900, 0.9, { decay: 0.6, attack: 0.02, tail: 0.2 }) },+ { id: 'slide-in', make: () => sweep(700, 240, 0.5, { decay: 1.2, attack: 0.01, tail: 0.1 }) },+ // Impacts — pops, drops, hits+ { id: 'pop', make: () => pop() },+ { id: 'thud', make: () => kick(120, 38, 0.35) },+ { id: 'boom', make: () => kick(95, 30, 0.9) },+ { id: 'impact-hit', make: () => fit([...noise(0.18, { cutoff: 2600, attack: 0.002, release: 0.1, gain: 0.7, seed: 41 }), ...kick(220, 70, 0.3)], Math.round(0.5 * SR)) },+ // UI — clicks, ticks, camera+ { id: 'click', make: () => click() },+ { id: 'tick', make: () => click(0.03) },+ { id: 'toggle', make: () => fit([...click(0.035), ...new Float64Array(Math.round(0.03 * SR)), ...click(0.05)], Math.round(0.14 * SR)) },+ { id: 'camera', make: () => fit([...noise(0.03, { cutoff: 3800, attack: 0.001, release: 0.02, gain: 0.8, seed: 5 }), ...new Float64Array(Math.round(0.045 * SR)), ...noise(0.05, { cutoff: 3000, attack: 0.001, release: 0.03, gain: 0.6, seed: 9 })], Math.round(0.16 * SR)) },+ // Musical — chimes, drums, shimmer+ { id: 'chime', make: () => tone(880, 1.1, { decay: 4.2, harmonics: [[2, 0.28], [3, 0.1]], attack: 0.003 }) },+ { id: 'chime-sparkle', make: () => sparkle([1174.7, 1318.5, 1760, 2093], 0.09) },+ { id: 'drum-kick', make: () => kick(150, 48, 0.4) },+ { id: 'hat', make: () => noise(0.09, { cutoff: 6800, attack: 0.001, release: 0.05, gain: 0.55, seed: 77 }) },+]++// ── WAV writer (mono 16-bit PCM) ─────────────────────────────+function wav(samples) {+ const n = samples.length+ const buf = Buffer.alloc(44 + n * 2)+ buf.write('RIFF', 0)+ buf.writeUInt32LE(36 + n * 2, 4)+ buf.write('WAVE', 8)+ buf.write('fmt ', 12)+ buf.writeUInt32LE(16, 16)+ buf.writeUInt16LE(1, 20) // PCM+ buf.writeUInt16LE(1, 22) // mono+ buf.writeUInt32LE(SR, 24)+ buf.writeUInt32LE(SR * 2, 28)+ buf.writeUInt16LE(2, 32)+ buf.writeUInt16LE(16, 34)+ buf.write('data', 36)+ buf.writeUInt32LE(n * 2, 40)+ for (let i = 0; i < n; i++) {+ const v = Math.max(-1, Math.min(1, samples[i]))+ buf.writeInt16LE(Math.round(v * 32767), 44 + i * 2)+ }+ return buf+}++// ── emit ──────────────────────────────────────────────────────+const OUT = join(process.cwd(), 'public', 'sfx')+mkdirSync(OUT, { recursive: true })+const manifest = []+for (const { id, make } of SOUNDS) {+ const samples = make()+ const bytes = wav(samples)+ writeFileSync(join(OUT, `${id}.wav`), bytes)+ manifest.push({ id, seconds: +(samples.length / SR).toFixed(2), bytes: bytes.length })+}+console.log(`sfx pack: ${manifest.length} sounds → public/sfx/`)+for (const m of manifest) console.log(` ${m.id}.wav ${m.seconds}s ${(m.bytes / 1024).toFixed(1)} kB`)diff --git a/scripts/verify-sound.sh b/scripts/verify-sound.shnew file mode 100755index 0000000..7fa484c--- /dev/null+++ b/scripts/verify-sound.sh@@ -0,0 +1,105 @@+#!/bin/bash+# scripts/verify-sound.sh — one-shot Sound wave (v0.20.0) verification+# (sandbox): embedded Postgres + migrate deploy + seed + dev server ++# targeted playwright e2e (sound-gated + smoke). Everything in ONE shell+# because background processes don't outlive the session.+set -euo pipefail+cd "$(dirname "$0")/.."+ROOT="$(pwd)"++export DATABASE_URL="postgresql://canvix:canvix@localhost:5433/canvix"+PGDIR=/tmp/pgembed+LOG=$PGDIR/verify-sound.log+: > "$LOG"++echo "── 1. embedded postgres ─────────────────────────────"+pkill -f 'pgembed/data3' 2>/dev/null || true+pkill -f 'start3.mjs' 2>/dev/null || true+for i in $(seq 1 15); do+ if node -e "const n=require('net');const s=n.connect(5433,'127.0.0.1',()=>{s.end();process.exit(0)});s.on('error',()=>process.exit(1))" 2>/dev/null; then sleep 1; else break; fi+done+rm -rf "$PGDIR/data3" "$PGDIR/ready3.marker"+mkdir -p "$PGDIR"+# embedded-postgres lives in the repo's node_modules when installed+# (dev sandbox); fall back to the persisted copy when it isn't.+PG_MODULES="$ROOT/node_modules"+if [ ! -f "$PG_MODULES/embedded-postgres/dist/index.js" ]; then+ PG_MODULES=/tmp/my-project/pgembed/node_modules+fi+echo "pg modules: $PG_MODULES"+cat > "$PGDIR/start3.mjs" << EOF+// ESM resolution is file-location based — /tmp has no node_modules, so+// import the modules by absolute path (PG_MODULES comes from the env).+const { default: EmbeddedPostgres } = await import(+ process.env.PG_MODULES + '/embedded-postgres/dist/index.js'+)+import { writeFileSync } from 'node:fs'+const pg = new EmbeddedPostgres({+ databaseDir: '/tmp/pgembed/data3',+ user: 'canvix',+ password: 'canvix',+ port: 5433,+ persistent: true,+})+await pg.initialise()+await pg.start()+await pg.createDatabase('canvix').catch(() => {})+const { Client } = (await import(process.env.PG_MODULES + '/pg/lib/index.js')).default+for (let i = 0; i < 60; i++) {+ try {+ const c = new Client({ connectionString: 'postgresql://canvix:[email protected]:5433/canvix' })+ await c.connect()+ await c.query('SELECT 1')+ await c.end()+ writeFileSync('/tmp/pgembed/ready3.marker', 'ok')+ console.log('PG READY (query verified)')+ break+ } catch {+ await new Promise((r) => setTimeout(r, 500))+ }+}+setInterval(() => {}, 1 << 30)+EOF+setsid nohup env PG_MODULES="$PG_MODULES" node "$PGDIR/start3.mjs" >> "$LOG" 2>&1 < /dev/null &+for i in $(seq 1 150); do+ [ -f "$PGDIR/ready3.marker" ] && break+ sleep 1+done+[ -f "$PGDIR/ready3.marker" ] || { echo "PG FAILED"; tail -25 "$LOG"; exit 1; }+echo "PG up on 5433"++echo "── 2. migrate deploy (Sound wave = no new migrations; must be a no-op) ──"+npx prisma migrate deploy 2>&1 | tail -3 | tee -a "$LOG"++echo "── 3. seed (366 templates) ──────────────────────────"+npx tsx prisma/seed.ts 2>&1 | grep -E "Seeding|Done" | tee -a "$LOG"++echo "── 4. dev server ────────────────────────────────────"+pkill -f 'next dev -p 3000' 2>/dev/null || true+sleep 1+# CANVIX_RATE_LIMITS=off — the suite registers/logs in accounts; the+# sandbox IP budget is reserved for production.+setsid nohup env CANVIX_RATE_LIMITS=off npx next dev -p 3000 > /tmp/pgembed/dev-sound.log 2>&1 < /dev/null &+for i in $(seq 1 150); do+ if curl -sf http://localhost:3000/api/health >/dev/null 2>&1; then break; fi+ sleep 1+done+curl -sf http://localhost:3000/api/health >/dev/null || { echo "DEV FAILED"; tail -30 /tmp/pgembed/dev-sound.log; exit 1; }+echo "dev up"++echo "── 5. API spot-checks (no Freesound key ⇒ honest gates) ──"+HEALTH=$(curl -sf http://localhost:3000/api/health)+echo "health: $HEALTH"+echo "capabilities: $(curl -sf http://localhost:3000/api/ai/capabilities)"+echo "sound availability: $(curl -sf http://localhost:3000/api/stock-sound/available)"+echo "sound search (expect 503 NO_PROVIDER + hint):"+curl -s -o /tmp/pgembed/sound-search.json -w ' status %{http_code}\n' \+ -X POST http://localhost:3000/api/stock-sound/search \+ -H 'Content-Type: application/json' -H "Origin: http://localhost:3000" \+ -d '{"query":"rain"}'+head -c 400 /tmp/pgembed/sound-search.json; echo++echo "── 6. playwright e2e (sound-gated + smoke) ──────────"+BASE_URL=http://localhost:3000 npx playwright test tests/e2e/sound-gated.spec.ts tests/e2e/smoke.spec.ts 2>&1 | tail -25++echo "── done ─────────────────────────────────────────────"diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.tsindex aee6aa0..46902fe 100644--- a/src/app/api/admin/config/route.ts+++ b/src/app/api/admin/config/route.ts@@ -123,14 +123,15 @@ async function sanitizedView() {models,features,settings,- // v0.16.5 (A5): the stock-media card's data — per-connector mask- // + which layer answers (console key vs env var), plus whether the+ // v0.16.5 (A5) + Sound wave: the stock-media card's data — per-connector+ // mask + which layer answers (console key vs env var), plus whether the// rails are live at all. Secret-free: masks and names only, never keys.stock: {- available: Boolean(stockEffective.pexels || stockEffective.pixabay),+ available: Boolean(stockEffective.pexels || stockEffective.pixabay || stockEffective.freesound),providers: {pexels: stockProviderView('pexels', stockKeys.pexels),pixabay: stockProviderView('pixabay', stockKeys.pixabay),+ freesound: stockProviderView('freesound', stockKeys.freesound),},},}diff --git a/src/app/api/admin/config/stock-test/route.ts b/src/app/api/admin/config/stock-test/route.tsindex 80e904b..50b4b14 100644--- a/src/app/api/admin/config/stock-test/route.ts+++ b/src/app/api/admin/config/stock-test/route.ts@@ -42,8 +42,8 @@ async function __canvix_post(req: NextRequest) {const body = (await req.json().catch(() => ({}))) as Record<string, unknown>const provider = typeof body.provider === 'string' ? body.provider.trim() : ''- if (provider !== 'pexels' && provider !== 'pixabay') {- return NextResponse.json({ ok: false, error: 'provider must be "pexels" or "pixabay".' }, { status: 400 })+ if (provider !== 'pexels' && provider !== 'pixabay' && provider !== 'freesound') {+ return NextResponse.json({ ok: false, error: 'provider must be "pexels", "pixabay" or "freesound".' }, { status: 400 })}const name = provider as StockProviderName@@ -65,6 +65,13 @@ async function __canvix_post(req: NextRequest) {const base = (process.env.PEXELS_API_BASE ?? 'https://api.pexels.com').replace(/\/+$/, '')url = `${base}/v1/search?query=nature&per_page=1&orientation=landscape`init = { headers: { Authorization: key } }+ } else if (name === 'freesound') {+ // Sound wave: same probe shape — one CC0 result for "click"+ const base = (process.env.FREESOUND_API_BASE ?? 'https://freesound.org/apiv2').replace(/\/+$/, '')+ url =+ `${base}/search/text/?query=click&filter=license:"Creative Commons 0"` ++ `&fields=id,name&page_size=1&token=${encodeURIComponent(key)}`+ init = {}} else {const base = (process.env.PIXABAY_API_BASE ?? 'https://pixabay.com/api').replace(/\/+$/, '')url = `${base}/?key=${encodeURIComponent(key)}&q=nature&image_type=photo&per_page=3&safesearch=true`@@ -97,7 +104,9 @@ async function __canvix_post(req: NextRequest) {const total =name === 'pexels'? Number((payload as { total_results?: unknown } | null)?.total_results)- : Number((payload as { total?: unknown } | null)?.total)+ : name === 'freesound'+ ? Number((payload as { count?: unknown } | null)?.count)+ : Number((payload as { total?: unknown } | null)?.total)return NextResponse.json({ok: true,provider: name,diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsindex c43e235..3d9d7ed 100644--- a/src/app/api/ai/capabilities/route.ts+++ b/src/app/api/ai/capabilities/route.ts@@ -1,6 +1,7 @@import { NextResponse } from 'next/server'import { hasProviderForSlot } from '@/lib/ai/provider'import { stockPhotoAvailable } from '@/lib/stock-photo'+import { stockSoundAvailable } from '@/lib/stock-sound'import { getFeatures } from '@/lib/admin/config'import { withLogging } from '@/lib/observability'@@ -25,13 +26,15 @@ async function __canvix_get() {// v0.19 (Wave 4): five AI Power-Up capabilities — the text-slot// trio (plan/notes/theme), vision-slot alt text, the video slot,// and the two LOCAL image tools that need no provider at all.- const [text, vision, image, imageEdit, video, stockPhotos] = await Promise.all([+ // Sound wave: soundSearch rides the Freesound stock key.+ const [text, vision, image, imageEdit, video, stockPhotos, stockSounds] = await Promise.all([hasProviderForSlot('text'),hasProviderForSlot('vision'),hasProviderForSlot('image'),hasProviderForSlot('imageEdit'),hasProviderForSlot('video'),stockPhotoAvailable(), // async since A5 — keys resolve console-first+ stockSoundAvailable(),])const configured = text || vision || image || imageEdit || videoconst flags = await getFeatures()@@ -45,6 +48,7 @@ async function __canvix_get() {translation: text && flags.translation,assistant: text && flags.assistant,photoSearch: stockPhotos && flags.photoSearch, // stock keys, not a model slot+ soundSearch: stockSounds && flags.soundSearch, // Freesound stock keybackgroundRemoval: true, // local ONNX — always availablecolorPalette: true, // local deterministiclayoutSuggestions: true, // local deterministicdiff --git a/src/app/api/stock-sound/available/route.ts b/src/app/api/stock-sound/available/route.tsnew file mode 100644index 0000000..ed37784--- /dev/null+++ b/src/app/api/stock-sound/available/route.ts@@ -0,0 +1,27 @@+import { NextResponse } from 'next/server'+import { stockSoundProviders } from '@/lib/stock-sound'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++/**+ * GET /api/stock-sound/available — public, secret-free feature+ * detection for the Audio panel's web-search section (the Sound+ * wave, the F2b pattern): the panel queries this to know whether+ * stock sound search is keyed before the first search runs.+ * Exposes WHICH connector is keyed, never the key itself.+ */+async function __canvix_get() {+ // keys resolve console-first (stored → env), so this reads the+ // AppConfig cache — one findMany per 10 s per instance at most.+ const providers = await stockSoundProviders()+ return NextResponse.json({+ available: providers.length > 0,+ providers,+ })+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const GET = withLogging('GET /api/stock-sound/available', __canvix_get)diff --git a/src/app/api/stock-sound/search/route.test.ts b/src/app/api/stock-sound/search/route.test.tsnew file mode 100644index 0000000..86dfb61--- /dev/null+++ b/src/app/api/stock-sound/search/route.test.ts@@ -0,0 +1,136 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Route tests for the Sound wave stock-sound API. No network, no+// Postgres. Invariants (the A4 stock-photo twin):+// 1. no provider key → 503 NO_PROVIDER (the F2b gate)+// 2. available is secret-free and never leaks the key+// 3. CSRF on the search POST+// 4. the happy path proxies the normalized result set++import { NextRequest } from 'next/server'+import { GET as getAvailable } from '../available/route'+import { POST as searchSounds } from './route'+import { resetStockSoundCache } from '@/lib/stock-sound'+import { resetRateLimitState } from '@/lib/rate-limit'++function req(url: string, init?: Omit<RequestInit, 'signal' | 'headers'> & { headers?: Record<string, string> }) {+ return new NextRequest(url, {+ ...init,+ headers: { host: 'canvix.test', ...(init?.headers ?? {}) },+ })+}++const FREESOUND_FIXTURE = {+ count: 1,+ results: [+ {+ id: 42,+ name: 'Click',+ tags: ['ui', 'click'],+ username: 'routeTester',+ duration: 0.2,+ license: 'https://creativecommons.org/publicdomain/zero/1.0/',+ previews: { 'preview-hq-mp3': 'https://cdn.freesound.org/previews/42/42_1-hq.mp3' },+ },+ ],+}++beforeEach(() => {+ vi.unstubAllEnvs()+ vi.stubEnv('FREESOUND_API_KEY', 'route-test-key')+ delete process.env.FREESOUND_API_BASE+ resetStockSoundCache()+ resetRateLimitState()+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ resetRateLimitState()+})++describe('GET /api/stock-sound/available', () => {+ it('no key → available=false, empty providers, no secrets', async () => {+ vi.stubEnv('FREESOUND_API_KEY', '')+ const res = await getAvailable(req('http://canvix.test/api/stock-sound/available'))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: false, providers: [] })+ })++ it('a key flips availability and names only the provider', async () => {+ const res = await getAvailable(req('http://canvix.test/api/stock-sound/available'))+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: true, providers: ['freesound'] })+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ })+})++describe('POST /api/stock-sound/search', () => {+ it('no provider key → 503 NO_PROVIDER with the operator hint', async () => {+ vi.stubEnv('FREESOUND_API_KEY', '')+ const res = await searchSounds(+ req('http://canvix.test/api/stock-sound/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'rain' }),+ }),+ )+ expect(res.status).toBe(503)+ const body = (await res.json()) as { code?: string; hint?: string }+ expect(body.code).toBe('NO_PROVIDER')+ expect(body.hint).toContain('FREESOUND_API_KEY')+ expect(body.hint).toContain('Creative Commons 0')+ })++ it('cross-site Origin → 403 CSRF_REJECTED', async () => {+ const res = await searchSounds(+ req('http://canvix.test/api/stock-sound/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json', origin: 'https://evil.example' },+ body: JSON.stringify({ query: 'rain' }),+ }),+ )+ expect(res.status).toBe(403)+ const body = (await res.json()) as { code?: string }+ expect(body.code).toBe('CSRF_REJECTED')+ })++ it('missing/blank query → 400', async () => {+ for (const query of ['', ' ']) {+ const res = await searchSounds(+ req('http://canvix.test/api/stock-sound/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query }),+ }),+ )+ expect(res.status).toBe(400)+ }+ })++ it('happy path → 200 with the normalized results, key never in the response', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(FREESOUND_FIXTURE), { status: 200 }),+ )+ vi.stubGlobal('fetch', fetchMock)+ const res = await searchSounds(+ req('http://canvix.test/api/stock-sound/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'click' }),+ }),+ )+ expect(res.status).toBe(200)+ const body = (await res.json()) as {+ results?: { id: string; name: string; credit: { license: string } }[]+ }+ expect(body.results).toHaveLength(1)+ expect(body.results?.[0]?.id).toBe('freesound-42')+ expect(body.results?.[0]?.credit.license).toBe('CC0')+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ // default request is CC0-filtered+ const calledUrl = fetchMock.mock.calls[0]?.[0] as string+ expect(calledUrl).toContain(encodeURIComponent('license:"Creative Commons 0"'))+ })+})diff --git a/src/app/api/stock-sound/search/route.ts b/src/app/api/stock-sound/search/route.tsnew file mode 100644index 0000000..a5629a9--- /dev/null+++ b/src/app/api/stock-sound/search/route.ts@@ -0,0 +1,73 @@+import { NextRequest, NextResponse } from 'next/server'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { aiFeatureEnabled } from '@/lib/admin/config'+import { FEATURE_DISABLED } from '@/lib/ai/provider'+import { searchStockSounds, stockSoundProviders } from '@/lib/stock-sound'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 30++interface SearchBody {+ query?: unknown+ count?: unknown+ includeOtherLicenses?: unknown+}++/**+ * POST /api/stock-sound/search — runtime stock SOUND search+ * (the Sound wave). The fourth stock-media connector: Freesound,+ * CC0-filtered by default, riding the same self-hoster-key+ * architecture as photos (A4) and videos (R6). Provider-gated the+ * F2b way: no key configured ⇒ 503 NO_PROVIDER and the Audio+ * panel shows the operator hint. The response is the normalized,+ * sanitized result set — preview MP3 URL + durable credit blocks;+ * the key never leaves the server (and the provider's error+ * bodies never reach the client).+ */+async function __canvix_post(req: NextRequest) {+ // stock search spends provider quota on every call — same-origin+ // only, like every other mutating POST (fail-closed default)+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ // the admin soundSearch kill switch (same semantics as photoSearch:+ // switched off ⇒ 503, everywhere)+ if (!(await aiFeatureEnabled('soundSearch'))) {+ return NextResponse.json(FEATURE_DISABLED, { status: 503 })+ }+ const limit = checkRateLimit(req, 'stocksound:search')+ if (!limit.ok) return rateLimitResponse(limit)++ const providers = await stockSoundProviders()+ if (providers.length === 0) {+ return NextResponse.json(+ {+ error: 'Sound search needs the Freesound key on the server.',+ code: 'NO_PROVIDER',+ hint: 'Store a Freesound key on the admin AI & models page (stock media card), or set FREESOUND_API_KEY — a free key from freesound.org (docs/SOUND.md). Results are Creative Commons 0 by default.',+ },+ { status: 503 },+ )+ }++ const body = (await req.json().catch(() => ({}))) as SearchBody+ const query = typeof body.query === 'string' ? body.query.trim().slice(0, 120) : ''+ if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })+ const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)+ // CC0 by default — opting into CC BY & friends is an explicit ask+ const includeOtherLicenses = body.includeOtherLicenses === true++ try {+ const results = await searchStockSounds(query, count, includeOtherLicenses ? { includeOtherLicenses } : {})+ return NextResponse.json({ query, count: results.length, results })+ } catch (error) {+ // sanitized upstream (status-only messages); NEVER echo provider+ // bodies or URLs — the freesound key rides the query string+ const message = error instanceof Error && error.message !== 'NO_PROVIDER' ? error.message : 'Sound search failed.'+ return NextResponse.json({ error: message }, { status: 502 })+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/stock-sound/search', __canvix_post)diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsxindex d1d2bed..d2f4d83 100644--- a/src/components/admin/ai-config.tsx+++ b/src/components/admin/ai-config.tsx@@ -96,6 +96,7 @@ const FEATURE_INFO: { key: string; label: string; hint: string }[] = [{ key: 'translation', label: 'Translate', hint: 'Text translation in the text toolbar' },{ key: 'assistant', label: 'Assistant', hint: 'The chat assistant that edits designs' },{ key: 'photoSearch', label: 'Photo search', hint: 'Stock photo search in the Photos panel — Pexels/Pixabay keys, not an AI provider' },+ { key: 'soundSearch', label: 'Sound search', hint: 'Stock sound search in the Audio panel — Freesound key (CC0 by default), not an AI provider' },// v0.19 (Wave 4 — AI Power-Up):{ key: 'agenticPlanning', label: 'AI design plan', hint: 'Describe → review the plan → apply editable pages' },{ key: 'notesGeneration', label: 'Speaker notes', hint: 'AI drafts presenter notes (reviewed before saving)' },@@ -144,7 +145,8 @@ const SLOT_ENDPOINT: Record<string, string> = {}/** The stock-media connectors (A5) — a fixed set, one free key each,- * shared by the Photos and Videos search rails. */+ * shared by the Photos and Videos search rails; Freesound (Sound wave)+ * keys the Audio rail on its own key. */const STOCK_PROVIDERS = [{key: 'pexels',@@ -160,6 +162,13 @@ const STOCK_PROVIDERS = [env: 'PIXABAY_API_KEY',placeholder: 'free Pixabay key',},+ {+ key: 'freesound',+ label: 'Freesound',+ hint: 'Audio search (CC0 by default) · free key at freesound.org/apiv2/apply',+ env: 'FREESOUND_API_KEY',+ placeholder: 'free Freesound key',+ },] as constexport function AdminAiConfig() {@@ -200,8 +209,7 @@ export function AdminAiConfig() {})setFeatures(data.features)// write-only credentials: never prefilled, cleared after every save- setStockPexels('')- setStockPixabay('')+ setStockKeys({})}async function put(body: unknown, message: string) {@@ -262,9 +270,8 @@ export function AdminAiConfig() {const [slotTest, setSlotTest] = useState<SlotTestState | null>(null)- // ── stock media (A5): Pexels/Pixabay keys, write-only like providers ──- const [stockPexels, setStockPexels] = useState('')- const [stockPixabay, setStockPixabay] = useState('')+ // ── stock media (A5 + Sound wave): stock keys, write-only like providers ──+ const [stockKeys, setStockKeys] = useState<Record<string, string>>({})const [stockTest, setStockTest] = useState<StockTestState | null>(null)/** Probe the ENDPOINT the slot actually uses (A3) — a chat-only@@ -291,18 +298,20 @@ export function AdminAiConfig() {* empty keeps the stored credential (the write-only posture). */async function saveStockKeys() {const stock: Record<string, string> = {}- if (stockPexels.trim()) stock.pexels = stockPexels.trim()- if (stockPixabay.trim()) stock.pixabay = stockPixabay.trim()- await put({ stock }, 'Stock keys saved — the Photos and Videos rails pick them up immediately.')+ for (const p of STOCK_PROVIDERS) {+ const v = (stockKeys[p.key] ?? '').trim()+ if (v) stock[p.key] = v+ }+ await put({ stock }, 'Stock keys saved — the stock rails pick them up immediately.')}/** Remove one stored key (explicit null) — env fallback restored. */- async function clearStockKey(name: 'pexels' | 'pixabay') {+ async function clearStockKey(name: 'pexels' | 'pixabay' | 'freesound') {await put({ stock: { [name]: null } }, `Stored ${name} key cleared.`)}/** Probe the provider's real search endpoint with the effective key. */- async function testStockKey(name: 'pexels' | 'pixabay') {+ async function testStockKey(name: 'pexels' | 'pixabay' | 'freesound') {setStockTest({ provider: name, ok: true, busy: true, message: 'probing…' })const res = await sendJson<{ ok: boolean; message?: string; error?: string }>('/api/admin/config/stock-test',@@ -579,28 +588,35 @@ export function AdminAiConfig() {</button></Card>- {/* v0.16.5 (A5): the stock-media card — Pexels/Pixabay keys for the- Photos + Videos search rails, managed like the AI providers:- write-only credentials, masked placeholders, per-provider Test- (a real one-result search through the effective key) and Clear- (env fallback restored). NOT model slots — the A4 decision. */}+ {/* v0.16.5 (A5) + Sound wave: the stock-media card — Pexels/Pixabay+ keys for the Photos + Videos search rails and the Freesound key+ for the Audio rail, managed like the AI providers: write-only+ credentials, masked placeholders, per-provider Test (a real+ one-result search through the effective key) and Clear (env+ fallback restored). NOT model slots — the A4 decision. */}<Card- title="Stock media — Pexels & Pixabay"+ title="Stock media — Pexels, Pixabay & Freesound"right={<Chip tone={stockKeyedCount > 0 ? 'good' : 'neutral'}>{stockKeyedCount > 0 ? `${stockKeyedCount} keyed` : 'no keys'}</Chip>}><p className="mb-4 text-sm text-muted-foreground">- The same two free keys power the Photos and Videos search rails — no AI provider involved. Get a free key at{' '}+ The Pexels/Pixabay keys power the Photos and Videos search rails; the Freesound key powers the Audio rail+ (Creative Commons 0 results by default) — no AI provider involved. Get free keys at{' '}<a href="https://www.pexels.com/api/" target="_blank" rel="noreferrer" className="underline">pexels.com/api- </a>{' '}- and{' '}+ </a>+ ,{' '}<a href="https://pixabay.com/api/docs/" target="_blank" rel="noreferrer" className="underline">pixabay.com/api/docs+ </a>{' '}+ and{' '}+ <a href="https://freesound.org/apiv2/apply/" target="_blank" rel="noreferrer" className="underline">+ freesound.org/apiv2/apply</a>. Keys are write-only — stored, never displayed again; leave a field empty to keep the stored one. A stored- key wins over the <code className="rounded bg-muted px-1">PEXELS_API_KEY</code> /{' '}- <code className="rounded bg-muted px-1">PIXABAY_API_KEY</code> environment variables; clearing a stored key- falls back to the env key when one is set.+ key wins over the matching environment variable (<code className="rounded bg-muted px-1">PEXELS_API_KEY</code> /{' '}+ <code className="rounded bg-muted px-1">PIXABAY_API_KEY</code> /{' '}+ <code className="rounded bg-muted px-1">FREESOUND_API_KEY</code>); clearing a stored key falls back to the+ env key when one is set.</p><div className="space-y-3">{STOCK_PROVIDERS.map((s) => {@@ -621,10 +637,8 @@ export function AdminAiConfig() {<span className="mb-1 block font-medium">API key</span><inputtype="password"- value={s.key === 'pexels' ? stockPexels : stockPixabay}- onChange={(e) =>- s.key === 'pexels' ? setStockPexels(e.target.value) : setStockPixabay(e.target.value)- }+ value={stockKeys[s.key] ?? ''}+ onChange={(e) => setStockKeys((m) => ({ ...m, [s.key]: e.target.value }))}placeholder={state?.keyMasked? `stored: ${state.keyMasked}`@@ -667,15 +681,15 @@ export function AdminAiConfig() {<div className="mt-3 flex flex-wrap items-center gap-3"><buttononClick={() => void saveStockKeys()}- disabled={busy || (!stockPexels.trim() && !stockPixabay.trim())}+ disabled={busy || !STOCK_PROVIDERS.some((p) => (stockKeys[p.key] ?? '').trim())}className="rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50">Save stock keys</button><span className="text-xs text-muted-foreground">{view.stock.available- ? 'Search active — the Photos web-results section and the Videos rail answer now.'- : 'No stock key set — Photos keeps its bundled library and the Videos rail stays hidden.'}+ ? 'Stock search active — the keyed rails answer now.'+ : 'No stock key set — Photos keeps its bundled library, the Videos and Audio web-search sections stay hidden.'}</span></div></Card>diff --git a/src/components/editor/AnimatePanel.tsx b/src/components/editor/AnimatePanel.tsxindex 7f840bd..108365f 100644--- a/src/components/editor/AnimatePanel.tsx+++ b/src/components/editor/AnimatePanel.tsx@@ -1,9 +1,11 @@'use client'import { useState } from 'react'-import { Sparkles, X, Zap, Play, RotateCcw, ArrowLeft, ArrowRight, ArrowUp, ArrowDown } from 'lucide-react'+import { Sparkles, X, Zap, Play, RotateCcw, ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Volume2 } from 'lucide-react'import { useEditorStore } from '@/store/editor-store'import { ANIMATION_KINDS, TRANSITION_KINDS } from '@/lib/animations'+import { SFX_PACK, isSfxId } from '@/lib/assets/sfx-pack'+import { playSfx } from '@/lib/sfx'import type { AnimationDirection, AnimationEasing, AnimationKind, AnimationSpeed, ElementAnimation, PageTransition } from '@/lib/types'import { SPEED_PRESETS } from '@/lib/types'import { Button } from '@/components/ui/button'@@ -80,6 +82,7 @@ export function AnimatePanel({ onClose }: { onClose: () => void }) {kind,duration: pageTransition?.kind === kind ? pageTransition.duration : 0.7,direction: pageTransition?.direction ?? 'left',+ ...(isSfxId(pageTransition?.sfxId) ? { sfxId: pageTransition.sfxId } : {}),})}@@ -229,6 +232,13 @@ export function AnimatePanel({ onClose }: { onClose: () => void }) {))}</div>)}+ {/* Sound wave: transition SFX — the 16 offline pack sounds,+ auditioned inline, stored on the transition config */}+ <SfxPicker+ label="Transition sound"+ value={pageTransition.sfxId}+ onChange={(sfxId) => setPageTransition({ ...pageTransition, ...(sfxId ? { sfxId } : { sfxId: undefined }) })}+ /></div>)}</div>@@ -367,6 +377,13 @@ export function AnimatePanel({ onClose }: { onClose: () => void }) {</div></div>)}+ {/* Sound wave: element animation SFX — fires when the+ animation triggers (at its delay) in preview/present */}+ <SfxPicker+ label="Entrance sound"+ value={selectedAnim.sfxId}+ onChange={(sfxId) => patchAnim({ ...(sfxId ? { sfxId } : { sfxId: undefined }) })}+ /></div>)}</>@@ -403,3 +420,44 @@ function AnimationGlyph({ kind }: { kind: AnimationKind }) {return <div className={cls}>?</div>}}++/**+ * Sound wave: the SFX picker — a compact select over the 16 offline+ * pack sounds with an inline audition button. `value` undefined =+ * "None". Changing the pick previews nothing (Preview plays it in+ * context); the speaker button auditions immediately.+ */+function SfxPicker({ label, value, onChange }: { label: string; value: string | undefined; onChange: (sfxId: string | undefined) => void }) {+ return (+ <div className="mt-2.5" data-testid="sfx-picker">+ <span className="text-[10px] font-semibold text-white/50 block mb-1.5">{label}</span>+ <div className="flex items-center gap-1.5">+ <select+ value={value ?? ''}+ onChange={(e) => onChange(e.target.value || undefined)}+ className="min-w-0 flex-1 rounded-md border border-white/10 bg-[#16181D] px-2 py-1.5 text-[11px] text-white/85 outline-none focus:border-[#02C0CC]"+ aria-label={label}+ >+ <option value="">None</option>+ {SFX_PACK.map((s) => (+ <option key={s.id} value={s.id}>+ {s.label} · {s.seconds}s+ </option>+ ))}+ </select>+ <button+ onClick={() => value && playSfx(value, 0.8)}+ disabled={!value}+ title={value ? 'Audition this sound' : 'Pick a sound first'}+ aria-label={`Audition ${label}`}+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-white/10 text-white/60 transition-colors hover:text-white hover:border-white/25 disabled:opacity-40"+ >+ <Volume2 size={13} />+ </button>+ </div>+ <p className="mt-1 text-[9px] leading-snug text-white/30">+ Plays in Preview and Present. For video export, insert the sound from the Audio panel as an autoplay element instead.+ </p>+ </div>+ )+}diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex d50b741..1aa1856 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -19,6 +19,7 @@ import { TextPanel } from './panels/TextPanel'import { UploadsPanel } from './panels/UploadsPanel'import { PhotosPanel } from './panels/PhotosPanel'import { VideosPanel } from './panels/VideosPanel'+import { AudioPanel } from './panels/AudioPanel'import { BrandPanel } from './panels/BrandPanel'import { ToolsPanel } from './panels/ToolsPanel'import { ProjectsPanel } from './panels/ProjectsPanel'@@ -54,6 +55,7 @@ const PANEL_TITLES: Record<Exclude<PanelId, null>, string> = {uploads: 'Uploads',photos: 'Photos',videos: 'Videos',+ audio: 'Audio',tools: 'Tools',projects: 'Projects',apps: 'Apps',@@ -481,6 +483,7 @@ export default function Editor() {case 'uploads': return <UploadsPanel />case 'photos': return <PhotosPanel />case 'videos': return <VideosPanel />+ case 'audio': return <AudioPanel />case 'brand': return <BrandPanel />case 'tools': return <ToolsPanel />case 'projects': return <ProjectsPanel />diff --git a/src/components/editor/LeftRail.tsx b/src/components/editor/LeftRail.tsxindex df1e112..bbb9f8c 100644--- a/src/components/editor/LeftRail.tsx+++ b/src/components/editor/LeftRail.tsx@@ -1,7 +1,7 @@'use client'import { useMemo } from 'react'-import { LayoutTemplate, Shapes, Type, Upload, Palette, Layers, Wrench, FolderOpen, LayoutGrid, BookMarked, Image, Video } from 'lucide-react'+import { LayoutTemplate, Shapes, Type, Upload, Palette, Layers, Wrench, FolderOpen, LayoutGrid, BookMarked, Image, Video, AudioLines } from 'lucide-react'import { useEditorStore, type PanelId } from '@/store/editor-store'import { cn } from '@/lib/utils'import { useIsMobile } from '@/hooks/use-mobile'@@ -20,6 +20,7 @@ const PANELS: { id: Exclude<PanelId, null>; label: string; icon: typeof LayoutTe{ id: 'uploads', label: 'Uploads', icon: Upload },{ id: 'photos', label: 'Photos', icon: Image },{ id: 'videos', label: 'Videos', icon: Video },+ { id: 'audio', label: 'Audio', icon: AudioLines },{ id: 'tools', label: 'Tools', icon: Wrench },{ id: 'projects', label: 'Projects', icon: FolderOpen },{ id: 'apps', label: 'Apps', icon: LayoutGrid },diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 430d43f..8914aa6 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -554,6 +554,20 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm{Math.round(audio.bpm)} BPM</span>) : null}+ {/* Sound wave: durable audio attribution — the A4 photo pattern+ (Freesound results, pack sounds, voiceover recordings). */}+ {audio.credit ? (+ <a+ href={audio.credit.url || undefined}+ target="_blank"+ rel="noreferrer"+ className="text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2 py-0.5 shrink-0 max-w-[190px] truncate"+ title={`${audio.credit.license}${audio.credit.url ? ` — ${audio.credit.url}` : ''}`}+ aria-label={`Audio by ${audio.credit.author} on ${audio.credit.provider}`}+ >+ {audio.credit.provider} · {audio.credit.author}+ </a>+ ) : null}<Divider /><PositionPopover ids={ids} count={1} element={first} /></>diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex 6d67394..e20e8db 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -419,6 +419,99 @@ export async function addAudioFromFile()}+/**+ * Sound wave: shared insert path for bytes we hold in the browser —+ * stock previews (Freesound), pack sounds, voiceover recordings.+ * Uploads through the chunked media store, bakes the analysis in+ * (waveform + BPM + beats — beat sync works day one), and stores a+ * durable credit block on the element when one applies.+ */+async function addAudioBlob(+ blob: Blob,+ name: string,+ credit?: { provider: string; author: string; license: string; url: string },+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { analyzeAudioFile } = await import('@/lib/media/decode')+ const { createAudioElement } = await import('@/lib/types')+ const file = new File([blob], name, { type: blob.type || 'audio/mpeg' })+ const [handle, analysis] = await Promise.all([uploadMediaFile(file, onProgress), analyzeAudioFile(file)])+ const store = useEditorStore.getState()+ const w = Math.min(520, Math.max(360, store.width * 0.55))+ const pos = placement(w, 96, store.pages[store.currentPage].elements.length)+ store.addElement(+ createAudioElement(mediaSrc(handle.id), name.replace(/\.[^.]+$/, '').slice(0, 60), analysis.duration, {+ ...pos,+ width: Math.round(w),+ height: 96,+ peaks: analysis.peaks,+ bpm: analysis.bpm,+ beats: analysis.beats,+ ...(credit ? { credit } : {}),+ })+ )+}++/**+ * Sound wave: insert a Freesound search result. Downloads the CC0+ * preview MP3 in the browser (the CDN answers CORS-open on GET),+ * then rides the shared audio insert — quota, dedupe, caps and the+ * full analysis all apply as-is.+ */+export async function addStockSound(+ sound: {+ id: string+ name: string+ preview: string+ credit: { provider: string; author: string; license: string; url: string }+ },+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const blob = await fetch(sound.preview).then((r) => {+ if (!r.ok) throw new Error(`Download failed (${r.status}).`)+ return r.blob()+ })+ await addAudioBlob(blob, `${sound.id}.mp3`, sound.credit, onProgress)+}++/**+ * Sound wave: insert an offline pack sound as a native audio+ * element — the same bundled file the animation SFX player uses,+ * landing on the canvas so it can autoplay in preview/present and+ * ride video export (the per-animation sfxId triggers do not).+ */+export async function addSfxToCanvas(id: string): Promise<void> {+ const { sfxUrl, sfxById } = await import('@/lib/assets/sfx-pack')+ const def = sfxById(id)+ if (!def) return+ const blob = await fetch(sfxUrl(id)).then((r) => {+ if (!r.ok) throw new Error(`Could not load the sound (${r.status}).`)+ return r.blob()+ })+ await addAudioBlob(blob, `${def.label}.wav`, {+ provider: 'Canvix',+ author: 'Canvix sound pack',+ license: 'CC0 (synthesized for Canvix)',+ url: 'https://canvix.app',+ })+}++/**+ * Sound wave: persist a voiceover recording (MediaRecorder blob+ * from the Audio panel) through the shared audio insert path.+ * Carries the "recorded by the author" credit block.+ */+export async function addVoiceoverRecording(blob: Blob): Promise<void> {+ const ext = blob.type.includes('mp4') ? 'm4a' : blob.type.includes('webm') ? 'webm' : 'audio'+ await addAudioBlob(blob, `voiceover-${new Date().toISOString().slice(11, 19).replace(/:/g, '')}.${ext}`, {+ provider: 'Canvix',+ author: 'Recorded in the editor',+ license: 'Yours — recorded locally, stored in your media library',+ url: 'https://canvix.app',+ })+}+/** Upload a video file, capture its poster frame, and add it to the canvas. */export async function addVideoFromFile(file: File,diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsxindex 7e7ab7d..6bffa3e 100644--- a/src/components/editor/canvas/preview-stage.tsx+++ b/src/components/editor/canvas/preview-stage.tsx@@ -7,6 +7,7 @@ import type { AudioElement, PageData, VideoElement } from '@/lib/types'import { gradientProps, pageSize } from '@/lib/editor-utils'import { animateElementAt, pageAnimationDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'+import { playSfx } from '@/lib/sfx'import { PreviewElements } from './element-node'interface PreviewStageProps {@@ -65,6 +66,15 @@ export default function PreviewStage({ page, designWidth, designHeight, animated// ── v0.5: element animation playback (rAF timeline over Konva nodes) ──const hasAnimations = animated && page.elements.some((e) => e.animation && e.animation.kind !== 'none')+ // Sound wave: page-transition SFX — fires when this page's animated+ // stage mounts (the incoming page of a transition; outgoing pages+ // render non-animated, so no double-fire). reduce-motion mutes it —+ // the same accessibility posture as the animation itself.+ useEffect(() => {+ if (!animated || reduceMotion || !stageReady) return+ const sfxId = page.transition?.sfxId+ if (sfxId && page.transition?.kind !== 'none') playSfx(sfxId, 0.7)+ }, [animated, reduceMotion, playKey, stageReady, page])useEffect(() => {const layer = layerRef.currentconst stage = stageRef.current@@ -97,11 +107,20 @@ export default function PreviewStage({ page, designWidth, designHeight, animatedconst total = pageAnimationDuration(page) + 0.1let raf = 0let stopped = false+ // Sound wave: element SFX fire once, on the rAF clock, when the+ // element's animation triggers (t crosses its delay) — synced+ // with the visual timeline, cancelled with it.+ const fired = new Set<string>()const tick = (now: number) => {if (stopped) returnconst t = Math.min((now - start) / 1000, total)for (const el of animatable) {+ const sfxId = el.animation?.sfxId+ if (sfxId && !fired.has(el.id) && t >= (el.animation?.delay || 0)) {+ fired.add(el.id)+ playSfx(sfxId, 0.8)+ }const node = layer.findOne(`#${el.id}`)const base = bases.get(el.id)if (!node || !base) continuediff --git a/src/components/editor/panels/AudioPanel.tsx b/src/components/editor/panels/AudioPanel.tsxnew file mode 100644index 0000000..d8c62f9--- /dev/null+++ b/src/components/editor/panels/AudioPanel.tsx@@ -0,0 +1,381 @@+'use client'++// ─────────────────────────────────────────────────────────────+// AudioPanel — the Sound wave's rail: everything that puts sound+// into a design, in one place.+//+// 1. Sound library — the 16-sound offline pack (original+// synthesized CC0). Click = audition, plus = insert as a+// native audio element (full analysis baked in — beat sync+// works on day one).+// 2. Freesound search — the fourth stock connector, CC0 by+// default, the PhotosPanel gated pattern (debounced live+// search, F2b unkeyed hint, durable credit on insert).+// 3. Record voiceover — MediaRecorder into the chunked media+// store through the same audio insert path. Mic denials are+// handled honestly (permission toast, no broken UI).+// 4. Upload — audio files ride the Uploads panel (audio/* is+// already accepted there); a hint points the way.+// ─────────────────────────────────────────────────────────────++import { useEffect, useMemo, useRef, useState } from 'react'+import { AudioLines, Info, Loader2, Mic, Plus, Search, Square, Volume2 } from 'lucide-react'+import { PanelShell } from './panel-shell'+import { addSfxToCanvas, addStockSound } from '../add-element'+import { SFX_CATEGORIES, SFX_PACK, sfxUrl, type SfxCategory } from '@/lib/assets/sfx-pack'+import { playSfx } from '@/lib/sfx'+import { useStockSound } from '@/hooks/use-stock-sound'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++/** normalized result — the /api/stock-sound/search shape */+interface StockSoundTile {+ id: string+ name: string+ duration: number+ preview: string+ tags: string[]+ credit: { provider: string; author: string; license: string; url: string }+}++type SearchError = { kind: 'no-provider' } | { kind: 'service'; message: string }++/** hard stop at 5 minutes — voiceovers are page narration, not podcasts */+const MAX_VOICEOVER_MS = 5 * 60 * 1000++export function AudioPanel() {+ const { available, loaded } = useStockSound()+ const [query, setQuery] = useState('')+ const [cat, setCat] = useState<SfxCategory | 'all'>('all')+ const [results, setResults] = useState<StockSoundTile[] | null>(null)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<SearchError | null>(null)+ const [busyTile, setBusyTile] = useState<string | null>(null)+ const [insertingSfx, setInsertingSfx] = useState<string | null>(null)++ // ── voiceover state ──+ const [recording, setRecording] = useState(false)+ const [recordMs, setRecordMs] = useState(0)+ const recorderRef = useRef<MediaRecorder | null>(null)+ const chunksRef = useRef<Blob[]>([])+ const tickRef = useRef<number | null>(null)++ const lastQuery = useRef('')+ // a POSITIVE unkeyed answer (not "probe still in flight")+ const noProvider = loaded && !available++ // debounced live search (600 ms — the PhotosPanel cadence)+ useEffect(() => {+ const q = query.trim()+ const run = async () => {+ setBusy(true)+ setError(null)+ try {+ const res = await fetch('/api/stock-sound/search', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query: q, count: 24 }),+ })+ const data = (await res.json().catch(() => ({}))) as { results?: StockSoundTile[]; error?: string; code?: string }+ if (res.status === 503 && data.code === 'NO_PROVIDER') {+ setError({ kind: 'no-provider' })+ setResults([])+ } else if (!res.ok) {+ setError(data.error ? { kind: 'service', message: data.error } : null)+ setResults([])+ } else {+ setResults(Array.isArray(data.results) ? data.results : [])+ }+ } catch {+ setResults([])+ } finally {+ setBusy(false)+ }+ }+ const t = setTimeout(() => {+ if (q === lastQuery.current) return+ // RACE GUARD (the A4 lesson): never consume the query while+ // availability is unresolved — the probe's landing re-runs this+ // effect, and a consumed query searches never again.+ if (q.length < 2 || !available) {+ setResults(null)+ setError(null)+ return+ }+ lastQuery.current = q+ void run()+ }, 600)+ return () => clearTimeout(t)+ }, [query, available])++ const pack = useMemo(() => SFX_PACK.filter((s) => cat === 'all' || s.category === cat), [cat])++ const insertSfx = async (id: string) => {+ if (insertingSfx) return+ setInsertingSfx(id)+ try {+ await addSfxToCanvas(id)+ toast({ title: 'Sound added', description: 'Plays in Preview and Present — autoplay it on the page for video export.' })+ } catch (err) {+ toast({ title: 'Could not add the sound', description: err instanceof Error ? err.message : 'Try again.' })+ } finally {+ setInsertingSfx(null)+ }+ }++ const insertStock = async (tile: StockSoundTile) => {+ if (busyTile) return+ setBusyTile(tile.id)+ try {+ await addStockSound(tile)+ toast({+ title: 'Sound added',+ description: `${tile.credit.provider} · ${tile.credit.author} — ${tile.credit.license}`,+ })+ } catch (err) {+ toast({+ title: 'Could not add the sound',+ description: err instanceof Error ? err.message : 'Try again — or pick another result.',+ })+ } finally {+ setBusyTile(null)+ }+ }++ // ── voiceover: MediaRecorder → chunked media store ──+ const startRecording = async () => {+ try {+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })+ // codec ladder: opus/webm everywhere modern, mp4 for Safari+ const mime = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')+ ? 'audio/webm;codecs=opus'+ : MediaRecorder.isTypeSupported('audio/mp4')+ ? 'audio/mp4'+ : ''+ const rec = mime ? new MediaRecorder(stream, { mimeType: mime }) : new MediaRecorder(stream)+ chunksRef.current = []+ rec.ondataavailable = (e) => {+ if (e.data.size > 0) chunksRef.current.push(e.data)+ }+ rec.onstop = () => {+ stream.getTracks().forEach((t) => t.stop())+ const blob = new Blob(chunksRef.current, { type: rec.mimeType || 'audio/webm' })+ void saveVoiceover(blob)+ }+ recorderRef.current = rec+ rec.start(250)+ setRecording(true)+ setRecordMs(0)+ const started = performance.now()+ tickRef.current = window.setInterval(() => {+ const ms = performance.now() - started+ setRecordMs(ms)+ if (ms >= MAX_VOICEOVER_MS) stopRecording()+ }, 200)+ } catch {+ toast({+ title: 'Microphone unavailable',+ description: 'The browser denied mic access, or no mic is connected — check the site permissions and try again.',+ })+ }+ }++ const stopRecording = () => {+ if (tickRef.current) {+ clearInterval(tickRef.current)+ tickRef.current = null+ }+ const rec = recorderRef.current+ if (rec && rec.state !== 'inactive') rec.stop()+ setRecording(false)+ recorderRef.current = null+ }++ const saveVoiceover = async (blob: Blob) => {+ if (blob.size < 512) {+ toast({ title: 'Recording too short', description: 'Hold the button a moment longer and try again.' })+ return+ }+ try {+ const { addVoiceoverRecording } = await import('../add-element')+ await addVoiceoverRecording(blob)+ toast({ title: 'Voiceover added', description: 'A waveform card landed on the page — play it in Preview.' })+ } catch (err) {+ toast({ title: 'Could not save the voiceover', description: err instanceof Error ? err.message : 'Try again.' })+ }+ }++ useEffect(() => () => stopRecording(), [])++ return (+ <PanelShell title="Audio" subtitle="Sound library, Freesound search and voiceover">+ <div className="space-y-5 p-3">+ {/* ── 1. offline pack ── */}+ <section aria-label="Sound library">+ <div className="flex items-center justify-between">+ <h4 className="text-xs font-semibold uppercase tracking-wide text-white/50">Sound library</h4>+ <span className="text-[10px] text-white/40">16 CC0 sounds · works offline</span>+ </div>+ <div className="mt-2 flex flex-wrap gap-1">+ {(['all', 'transitions', 'impacts', 'ui', 'musical'] as const).map((c) => (+ <button+ key={c}+ onClick={() => setCat(c)}+ className={cn(+ 'rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors',+ cat === c ? 'bg-[#7630D7] text-white' : 'bg-white/5 text-white/60 hover:bg-white/10',+ )}+ aria-pressed={cat === c}+ >+ {c === 'all' ? 'All' : SFX_CATEGORIES[c]}+ </button>+ ))}+ </div>+ <div className="mt-2 grid grid-cols-2 gap-1.5" data-testid="sfx-grid">+ {pack.map((s) => (+ <div+ key={s.id}+ className="group flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] p-2 hover:border-[#7630D7]/60"+ >+ <button+ onClick={() => playSfx(s.id)}+ title={`Play ${s.label}`}+ aria-label={`Play ${s.label}`}+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/70 transition-colors hover:bg-[#7630D7]/40 hover:text-white"+ >+ <Volume2 size={14} />+ </button>+ <button+ onClick={() => void insertSfx(s.id)}+ disabled={insertingSfx === s.id}+ title={`${s.hint} — add to the page`}+ className="flex min-w-0 flex-1 flex-col items-start text-left disabled:opacity-50"+ >+ <span className="w-full truncate text-[12px] font-medium text-white/85">{s.label}</span>+ <span className="w-full truncate text-[10px] text-white/40">{s.seconds}s · {s.hint}</span>+ </button>+ {insertingSfx === s.id && <Loader2 size={13} className="shrink-0 animate-spin text-white/50" />}+ </div>+ ))}+ </div>+ </section>++ {/* ── 2. Freesound search ── */}+ <section aria-label="Freesound search">+ <div className="flex items-center justify-between">+ <h4 className="text-xs font-semibold uppercase tracking-wide text-white/50">Freesound</h4>+ <span className="text-[10px] text-white/40">CC0 by default</span>+ </div>+ <div className="mt-2 flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2">+ <Search size={14} className="shrink-0 text-white/40" />+ <input+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={available ? 'Search sounds — rain, whoosh, click…' : 'Search sounds (needs the Freesound key)'}+ className="min-w-0 flex-1 bg-transparent text-[13px] text-white/85 outline-none placeholder:text-white/35"+ aria-label="Search Freesound"+ data-testid="sound-search-input"+ />+ {busy && <Loader2 size={14} className="shrink-0 animate-spin text-white/40" />}+ </div>++ {noProvider && (+ <div className="mt-2 rounded-xl border border-amber-400/25 bg-amber-400/10 p-2.5 text-[11px] leading-relaxed text-amber-200/90" data-testid="sound-unkeyed-hint">+ <span className="flex items-start gap-1.5">+ <Info size={13} className="mt-0.5 shrink-0" />+ <span>+ Sound search is off on this server — the operator sets a free{' '}+ <strong>Freesound</strong> key on the admin AI & models page (or{' '}+ <code className="rounded bg-black/20 px-1">FREESOUND_API_KEY</code>). Results are+ Creative Commons 0 by default. The Sound library above works without any key.+ </span>+ </span>+ </div>+ )}++ {error?.kind === 'service' && (+ <p className="mt-2 rounded-xl border border-red-400/25 bg-red-400/10 p-2.5 text-[11px] text-red-200/90">{error.message}</p>+ )}++ {results !== null && results.length === 0 && !error && (+ <p className="mt-2 text-[11px] text-white/40">No sounds matched — try a broader term.</p>+ )}++ {results && results.length > 0 && (+ <div className="mt-2 space-y-1.5" data-testid="sound-results">+ {results.map((tile) => (+ <div+ key={tile.id}+ className="flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.03] p-2 hover:border-[#7630D7]/60"+ >+ <button+ onClick={() => {+ const a = new Audio(tile.preview)+ void a.play().catch(() => toast({ title: 'Could not play the preview' }))+ }}+ title={`Play ${tile.name}`}+ aria-label={`Play ${tile.name}`}+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/5 text-white/70 transition-colors hover:bg-[#7630D7]/40 hover:text-white"+ >+ <Volume2 size={14} />+ </button>+ <button+ onClick={() => void insertStock(tile)}+ disabled={busyTile === tile.id}+ className="flex min-w-0 flex-1 flex-col items-start text-left disabled:opacity-50"+ >+ <span className="w-full truncate text-[12px] font-medium text-white/85">{tile.name}</span>+ <span className="w-full truncate text-[10px] text-white/40">+ {tile.duration.toFixed(1)}s · {tile.credit.provider} · {tile.credit.author} — {tile.credit.license}+ </span>+ </button>+ {busyTile === tile.id ? (+ <Loader2 size={13} className="shrink-0 animate-spin text-white/50" />+ ) : (+ <Plus size={14} className="shrink-0 text-white/30" />+ )}+ </div>+ ))}+ </div>+ )}+ </section>++ {/* ── 3. voiceover ── */}+ <section aria-label="Voiceover">+ <h4 className="text-xs font-semibold uppercase tracking-wide text-white/50">Voiceover</h4>+ <p className="mt-1 text-[11px] leading-relaxed text-white/40">+ Record page narration with your mic — it lands as a waveform card, autoplayed in Preview and Present.+ </p>+ <button+ onClick={() => (recording ? stopRecording() : void startRecording())}+ className={cn(+ 'mt-2 flex w-full items-center justify-center gap-2 rounded-xl border px-3 py-2.5 text-[13px] font-semibold transition-colors',+ recording+ ? 'border-red-400/40 bg-red-500/20 text-red-200 hover:bg-red-500/30'+ : 'border-white/10 bg-white/[0.03] text-white/80 hover:border-[#7630D7]/60 hover:bg-[#7630D7]/15',+ )}+ data-testid="voiceover-button"+ aria-pressed={recording}+ >+ {recording ? <Square size={14} /> : <Mic size={14} />}+ {recording+ ? `Stop — ${(recordMs / 1000).toFixed(1)}s (max 5 min)`+ : 'Record voiceover'}+ </button>+ </section>++ {/* ── 4. uploads hint ── */}+ <section aria-label="Upload audio">+ <h4 className="text-xs font-semibold uppercase tracking-wide text-white/50">Your audio files</h4>+ <p className="mt-1 flex items-start gap-1.5 text-[11px] leading-relaxed text-white/40">+ <AudioLines size={13} className="mt-0.5 shrink-0" />+ <span>+ Music and audio files upload from the Uploads panel (MP3, WAV, OGG…) — waveform, BPM and beat+ grid bake in automatically.+ </span>+ </p>+ </section>+ </div>+ </PanelShell>+ )+}diff --git a/src/hooks/use-stock-sound.ts b/src/hooks/use-stock-sound.tsnew file mode 100644index 0000000..429b7ed--- /dev/null+++ b/src/hooks/use-stock-sound.ts@@ -0,0 +1,54 @@+'use client'++// ─────────────────────────────────────────────────────────────+// use-stock-sound — client availability probe for the Audio+// panel's stock-search section (the Sound wave — the+// use-stock-photo twin, F2b fail-closed).+// ─────────────────────────────────────────────────────────────++import { useEffect, useState } from 'react'++export interface StockSoundAvailability {+ available: boolean+ providers: string[]+}++const FALLBACK: StockSoundAvailability = { available: false, providers: [] }++let inflight: Promise<StockSoundAvailability> | null = null+let resolved: StockSoundAvailability | null = null++function probe(): Promise<StockSoundAvailability> {+ if (resolved) return Promise.resolve(resolved)+ inflight ??= fetch('/api/stock-sound/available')+ .then(async (res) => {+ if (!res.ok) return FALLBACK+ const body = (await res.json().catch(() => null)) as StockSoundAvailability | null+ if (!body || typeof body.available !== 'boolean' || !Array.isArray(body.providers)) return FALLBACK+ resolved = body+ return body+ })+ .catch(() => FALLBACK)+ return inflight+}++/**+ * The stock-sound search state. `loaded` distinguishes "probe still+ * in flight" from "probe answered no" — the web-results section only+ * renders its unkeyed hint on a POSITIVE no (no flash on cold mounts).+ */+export function useStockSound(): StockSoundAvailability & { loaded: boolean } {+ const [state, setState] = useState<StockSoundAvailability>(resolved ?? FALLBACK)++ useEffect(() => {+ let alive = true+ void probe().then((v) => {+ if (alive) setState(v)+ })+ return () => {+ alive = false+ }+ }, [])++ return { ...state, loaded: state.available || resolved !== null }+}diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.tsindex 2ee4d23..50072b1 100644--- a/src/lib/admin/config.test.ts+++ b/src/lib/admin/config.test.ts@@ -388,16 +388,18 @@ describe('stock keys (v0.16.5 A5)', () => {it('effectiveStockKeys: the console key wins, env fills the rest', async () => {vi.stubEnv('PEXELS_API_KEY', 'env-pexels')vi.stubEnv('PIXABAY_API_KEY', 'env-pixabay')- findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'db-pexels' } }])- expect(await effectiveStockKeys()).toEqual({ pexels: 'db-pexels', pixabay: 'env-pixabay' })+ vi.stubEnv('FREESOUND_API_KEY', 'env-freesound')+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'db-pexels', freesound: 'db-freesound' } }])+ expect(await effectiveStockKeys()).toEqual({ pexels: 'db-pexels', pixabay: 'env-pixabay', freesound: 'db-freesound' })vi.unstubAllEnvs()})it('effectiveStockKeys with nothing anywhere → empty strings, never a throw', async () => {vi.stubEnv('PEXELS_API_KEY', '')vi.stubEnv('PIXABAY_API_KEY', ' ')+ vi.stubEnv('FREESOUND_API_KEY', undefined as unknown as string)findMany.mockResolvedValue([])- expect(await effectiveStockKeys()).toEqual({ pexels: '', pixabay: '' })+ expect(await effectiveStockKeys()).toEqual({ pexels: '', pixabay: '', freesound: '' })vi.unstubAllEnvs()})})diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.tsindex 2eea893..1a1d58c 100644--- a/src/lib/admin/config.ts+++ b/src/lib/admin/config.ts@@ -53,6 +53,9 @@ export const AI_FEATURES = ['translation','assistant','photoSearch',+ // Sound wave — stock sound search rides the Freesound key, the+ // same stock-connector posture as photoSearch (not an AI slot)+ 'soundSearch',// v0.19 (Wave 4 — AI Power-Up):'agenticPlanning', // describe → AI multi-page plan → editable review gate'notesGeneration', // speaker notes from page content@@ -115,6 +118,7 @@ export const DEFAULT_FEATURES: StoredFeatures = {translation: true,assistant: true,photoSearch: true,+ soundSearch: true,// v0.19 (Wave 4) — default ON; stored tables that predate the flags// merge over these defaults (getFeatures spreads DEFAULT first).agenticPlanning: true,@@ -131,14 +135,16 @@ export const DEFAULT_SETTINGS: StoredSettings = {// ── stock-media keys (v0.16.5 A5) ─────────────────────────────-/** The two stock-media connectors — photos + videos share each key. */-export type StockProviderName = 'pexels' | 'pixabay'+/** The stock-media connectors — photos + videos share the Pexels/Pixabay+ * keys; the Sound wave adds Freesound (its own key). */+export type StockProviderName = 'pexels' | 'pixabay' | 'freesound'/** Stored stock keys (AppConfig `stock.providers`) — write-only like every credential here. */export type StoredStockKeys = Partial<Record<StockProviderName, string>>/** The pre-A5 way to key stock search — still the fallback when nothing is stored. */export const STOCK_ENV_KEYS: Record<StockProviderName, string> = {pexels: 'PEXELS_API_KEY',pixabay: 'PIXABAY_API_KEY',+ freesound: 'FREESOUND_API_KEY',}const BASEURL_MAX = 2048@@ -253,7 +259,7 @@ export function validateStockKeys(}const raw = input as Record<string, unknown>const out: Partial<Record<StockProviderName, string | null>> = {}- for (const name of ['pexels', 'pixabay'] as const) {+ for (const name of ['pexels', 'pixabay', 'freesound'] as const) {const v = raw[name]if (v === undefined) continueif (v === null) {@@ -570,7 +576,7 @@ export async function getStockKeys(): Promise<StoredStockKeys> {const rows = await readRows()const raw = asRecord(rows.get(CONFIG_KEYS.stock))const out: StoredStockKeys = {}- for (const name of ['pexels', 'pixabay'] as const) {+ for (const name of ['pexels', 'pixabay', 'freesound'] as const) {const v = raw[name]if (typeof v === 'string' && v.trim()) out[name] = v.trim()}@@ -580,7 +586,7 @@ export async function getStockKeys(): Promise<StoredStockKeys> {/** Merge a validated patch over the stored keys and write the full state. */export async function setStockKeys(patch: Partial<Record<StockProviderName, string | null>>): Promise<void> {const next: StoredStockKeys = { ...(await getStockKeys()) }- for (const name of ['pexels', 'pixabay'] as const) {+ for (const name of ['pexels', 'pixabay', 'freesound'] as const) {const v = patch[name]if (v === null) delete next[name]else if (typeof v === 'string' && v) next[name] = v@@ -597,8 +603,8 @@ export async function setStockKeys(patch: Partial<Record<StockProviderName, stri*/export async function effectiveStockKeys(): Promise<Record<StockProviderName, string>> {const stored = await getStockKeys()- const out = { pexels: '', pixabay: '' }- for (const name of ['pexels', 'pixabay'] as const) {+ const out = { pexels: '', pixabay: '', freesound: '' }+ for (const name of ['pexels', 'pixabay', 'freesound'] as const) {out[name] = stored[name] ?? (process.env[STOCK_ENV_KEYS[name]] ?? '').trim()}return outdiff --git a/src/lib/animations.ts b/src/lib/animations.tsindex 80d7209..53dfbc6 100644--- a/src/lib/animations.ts+++ b/src/lib/animations.ts@@ -7,12 +7,14 @@// Static exports (PNG/JPG/PDF/SVG) ignore animations entirely.// ─────────────────────────────────────────────────────────────+import { isSfxId } from '@/lib/assets/sfx-pack'import type {AnimationEasing,AnimationKind,AnyElement,ElementAnimation,PageData,+ PageTransition,} from '@/lib/types'// ── easings ──────────────────────────────────────────────────@@ -297,11 +299,35 @@ export function sanitizeAnimation(input: unknown): ElementAnimation | undefinedconst direction = (['left', 'right', 'up', 'down'] as const).includes(a.direction as never)? (a.direction as ElementAnimation['direction']): undefined+ // Sound wave: sfxId must name a real pack sound — unknown ids are+ // dropped (never stored), so hostile/AI input can only pick from+ // the 16 bundled files.+ const sfxId = isSfxId(a.sfxId) ? a.sfxId : undefinedreturn {kind,duration: Math.min(4, Math.max(0.1, Number(a.duration) || 0.9)),delay: Math.min(5, Math.max(0, Number(a.delay) || 0)),easing,direction,+ ...(sfxId ? { sfxId } : {}),+ }+}++/** normalize/clamp a page transition config (Sound wave: sfxId rides along) */+export function sanitizePageTransition(input: unknown): PageTransition | undefined {+ if (!input || typeof input !== 'object') return undefined+ const t = input as Partial<PageTransition>+ const kind = t.kind+ if (!kind || !TRANSITION_KINDS.some((k) => k.kind === kind)) return undefined+ if (kind === 'none') return undefined+ const direction = (['left', 'right', 'up', 'down'] as const).includes(t.direction as never)+ ? (t.direction as PageTransition['direction'])+ : undefined+ const sfxId = isSfxId(t.sfxId) ? t.sfxId : undefined+ return {+ kind,+ duration: Math.min(2.5, Math.max(0.1, Number(t.duration) || 0.7)),+ ...(direction ? { direction } : {}),+ ...(sfxId ? { sfxId } : {}),}}diff --git a/src/lib/assets/sfx-pack.test.ts b/src/lib/assets/sfx-pack.test.tsnew file mode 100644index 0000000..6aeeae2--- /dev/null+++ b/src/lib/assets/sfx-pack.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest'+import { existsSync, readFileSync } from 'node:fs'+import { join } from 'node:path'++// Sound wave tests for the offline SFX pack + the sfxId plumbing:+// 1. catalogue integrity — unique ids, sane fields, ids are+// filesystem-safe (they become /sfx/<id>.wav URLs)+// 2. every catalogue id has a real WAV file on disk (the pack+// ships in public/sfx — a missing file would 404 at play time)+// 3. every file is a parseable RIFF/WAVE mono 16-bit PCM at 44.1 kHz+// 4. sanitizeAnimation / sanitizePageTransition accept known ids,+// DROP unknown ones (hostile input can only pick bundled files)+// 5. the player validates ids and no-ops in Node (no Audio)++import { SFX_PACK, SFX_CATEGORIES, isSfxId, sfxById, sfxUrl } from './sfx-pack'+import { sanitizeAnimation, sanitizePageTransition } from '@/lib/animations'+import { playSfx, resetSfxPlayer } from '@/lib/sfx'++const SFX_DIR = join(process.cwd(), 'public', 'sfx')++describe('sfx pack catalogue', () => {+ it('16 sounds across 4 categories, unique safe ids', () => {+ expect(SFX_PACK).toHaveLength(16)+ const ids = new Set(SFX_PACK.map((s) => s.id))+ expect(ids.size).toBe(SFX_PACK.length)+ for (const s of SFX_PACK) {+ expect(s.id).toMatch(/^[a-z0-9-]+$/)+ expect(s.label.length).toBeGreaterThan(0)+ expect(s.seconds).toBeGreaterThan(0)+ expect(s.seconds).toBeLessThanOrEqual(1.5)+ expect(Object.keys(SFX_CATEGORIES)).toContain(s.category)+ }+ })++ it('every id has a real WAV file on disk', () => {+ for (const s of SFX_PACK) {+ const file = join(SFX_DIR, `${s.id}.wav`)+ expect(existsSync(file), `public/sfx/${s.id}.wav must exist`).toBe(true)+ }+ })++ it('every file is RIFF/WAVE, mono, 16-bit, 44.1 kHz', () => {+ for (const s of SFX_PACK) {+ const buf = readFileSync(join(SFX_DIR, `${s.id}.wav`))+ expect(buf.toString('ascii', 0, 4)).toBe('RIFF')+ expect(buf.toString('ascii', 8, 12)).toBe('WAVE')+ expect(buf.readUInt16LE(22)).toBe(1) // mono+ expect(buf.readUInt32LE(24)).toBe(44100)+ expect(buf.readUInt16LE(34)).toBe(16) // bits per sample+ // the catalogue duration matches the file payload+ const seconds = buf.readUInt32LE(40) / 2 / 44100+ expect(Math.abs(seconds - s.seconds)).toBeLessThan(0.05)+ }+ })++ it('isSfxId / sfxById / sfxUrl behave', () => {+ expect(isSfxId('chime')).toBe(true)+ expect(isSfxId('not-a-sound')).toBe(false)+ expect(isSfxId(42)).toBe(false)+ expect(isSfxId(undefined)).toBe(false)+ expect(sfxById('pop')?.label).toBe('Pop')+ expect(sfxById('missing')).toBeUndefined()+ expect(sfxUrl('pop')).toBe('/sfx/pop.wav')+ })+})++describe('sfxId sanitization', () => {+ it('sanitizeAnimation keeps a known id and drops unknown/hostile ones', () => {+ const good = sanitizeAnimation({ kind: 'fade', duration: 0.8, delay: 0, easing: 'easeOut', sfxId: 'whoosh-soft' })+ expect(good?.sfxId).toBe('whoosh-soft')++ expect(sanitizeAnimation({ kind: 'fade', duration: 0.8, delay: 0, easing: 'easeOut', sfxId: '../../etc/passwd' })?.sfxId).toBeUndefined()+ expect(sanitizeAnimation({ kind: 'fade', duration: 0.8, delay: 0, easing: 'easeOut', sfxId: 42 as unknown as string })?.sfxId).toBeUndefined()+ // pre-sound documents (no sfxId) stay byte-shape-compatible: the+ // key is simply absent, not null+ const legacy = sanitizeAnimation({ kind: 'fade', duration: 0.8, delay: 0, easing: 'easeOut' })+ expect(legacy).not.toHaveProperty('sfxId')+ })++ it('sanitizePageTransition clamps and keeps/drops sfxId', () => {+ const good = sanitizePageTransition({ kind: 'slide', duration: 0.7, direction: 'left', sfxId: 'swoosh-reverse' })+ expect(good).toEqual({ kind: 'slide', duration: 0.7, direction: 'left', sfxId: 'swoosh-reverse' })++ expect(sanitizePageTransition({ kind: 'fade', duration: 99, sfxId: 'nope' })).toEqual({ kind: 'fade', duration: 2.5 })+ expect(sanitizePageTransition({ kind: 'none' })).toBeUndefined()+ expect(sanitizePageTransition('garbage' as unknown as object)).toBeUndefined()+ })+})++describe('sfx player (Node — no Audio global)', () => {+ it('playSfx no-ops safely for unknown ids and without Audio', () => {+ resetSfxPlayer()+ expect(() => playSfx('chime')).not.toThrow()+ expect(() => playSfx('not-a-sound')).not.toThrow()+ expect(() => playSfx('pop', 5)).not.toThrow()+ })+})diff --git a/src/lib/assets/sfx-pack.ts b/src/lib/assets/sfx-pack.tsnew file mode 100644index 0000000..aff57d7--- /dev/null+++ b/src/lib/assets/sfx-pack.ts@@ -0,0 +1,79 @@+// ─────────────────────────────────────────────────────────────+// Canvix offline sound pack (the Sound wave) — 16 original+// synthesized effects in four categories, generated by+// scripts/gen-sfx-pack.mjs (pure DSP: oscillators, shaped noise,+// envelopes — NO samples, NO third-party recordings). The pack is+// therefore an original work of the Canvix project, released CC0+// (the licence manifest lives in docs/SOUND.md).+//+// Two consumers:+// 1. The Audio panel's Sound library — click to audition, insert+// as a native audio element (rides the media store, autoplay+// in preview/present, beat analysis and all).+// 2. Animation + page-transition SFX (`sfxId` on+// ElementAnimation / PageTransition) — the same files played+// by the preview/presenter playback engines.+//+// ids are stable API: documents reference them; renaming an id+// strands saved designs (sanitizeAnimation drops unknown ids).+// ─────────────────────────────────────────────────────────────++export type SfxCategory = 'transitions' | 'impacts' | 'ui' | 'musical'++export interface SfxDef {+ /** stable id — the file is /sfx/<id>.wav */+ id: string+ /** display label */+ label: string+ category: SfxCategory+ /** synthesized duration in seconds (informational) */+ seconds: number+ hint: string+}++export const SFX_CATEGORIES: Record<SfxCategory, string> = {+ transitions: 'Transitions',+ impacts: 'Impacts',+ ui: 'UI',+ musical: 'Musical',+}++export const SFX_PACK: SfxDef[] = [+ // transitions+ { id: 'whoosh-soft', label: 'Whoosh soft', category: 'transitions', seconds: 0.85, hint: 'Gentle page or section change' },+ { id: 'whoosh-fast', label: 'Whoosh fast', category: 'transitions', seconds: 0.45, hint: 'Quick swish between pages' },+ { id: 'swoosh-reverse', label: 'Swoosh reverse', category: 'transitions', seconds: 0.9, hint: 'Rising build-up before a reveal' },+ { id: 'slide-in', label: 'Slide in', category: 'transitions', seconds: 0.5, hint: 'Content sliding into place' },+ // impacts+ { id: 'pop', label: 'Pop', category: 'impacts', seconds: 0.14, hint: 'Light, playful entrance' },+ { id: 'thud', label: 'Thud', category: 'impacts', seconds: 0.35, hint: 'Soft heavy landing' },+ { id: 'boom', label: 'Boom', category: 'impacts', seconds: 0.9, hint: 'Big cinematic hit' },+ { id: 'impact-hit', label: 'Impact hit', category: 'impacts', seconds: 0.5, hint: 'Crisp punch with body' },+ // ui+ { id: 'click', label: 'Click', category: 'ui', seconds: 0.05, hint: 'Minimal UI tick' },+ { id: 'tick', label: 'Tick', category: 'ui', seconds: 0.03, hint: 'Even shorter tick' },+ { id: 'toggle', label: 'Toggle', category: 'ui', seconds: 0.14, hint: 'Two-stage switch' },+ { id: 'camera', label: 'Camera', category: 'ui', seconds: 0.16, hint: 'Shutter double-click' },+ // musical+ { id: 'chime', label: 'Chime', category: 'musical', seconds: 1.1, hint: 'Clean single ping' },+ { id: 'chime-sparkle', label: 'Chime sparkle', category: 'musical', seconds: 0.86, hint: 'Rising shimmer of pings' },+ { id: 'drum-kick', label: 'Drum kick', category: 'musical', seconds: 0.4, hint: 'Classic kick drum' },+ { id: 'hat', label: 'Hat', category: 'musical', seconds: 0.09, hint: 'Hi-hat tick' },+]++const SFX_IDS = new Set(SFX_PACK.map((s) => s.id))++/** Is `id` a known pack sound? (sanitizeAnimation + the player both gate on this) */+export function isSfxId(id: unknown): id is string {+ return typeof id === 'string' && SFX_IDS.has(id)+}++/** The public URL of a pack sound (same-origin, cacheable forever). */+export function sfxUrl(id: string): string {+ return `/sfx/${id}.wav`+}++/** Look up a definition by id (for labels/durations in the UI). */+export function sfxById(id: string): SfxDef | undefined {+ return SFX_PACK.find((s) => s.id === id)+}diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex 5ecd793..1602b85 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -44,6 +44,7 @@ export type RateLimitBucket =| 'plugins:serve'| 'stockvideo:search'| 'stockphoto:search'+ | 'stocksound:search'| 'icons:search'| 'templates:fill'@@ -87,6 +88,10 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {// — one shared bucket shape with the video rail (the panel also// debounces at 600 ms and caches server-side for 24 h)'stockphoto:search': { windowMs: 60_000, max: 20 },+ // Sound wave: stock-sound search spends the same PROVIDER quota+ // (Freesound key) — the Audio panel debounces at 600 ms and caches+ // server-side for 24 h, same bucket shape as the photo/video rails+ 'stocksound:search': { windowMs: 60_000, max: 20 },// v0.17 (Wave 2): iconify search/svg proxy — free public API, no key,// but every hit is outbound traffic from the Worker; the panel debounces// at 500 ms and caches, so 30/min per IP is generous for humansdiff --git a/src/lib/sfx.ts b/src/lib/sfx.tsnew file mode 100644index 0000000..1d625ca--- /dev/null+++ b/src/lib/sfx.ts@@ -0,0 +1,87 @@+// ─────────────────────────────────────────────────────────────+// sfx — play offline pack sounds in the browser (the Sound wave).+//+// A tiny, allocation-conscious player for /sfx/<id>.wav:+// • one pooled <audio> per id (16 max — the pack size), reused+// across plays, so repeated triggers never leak elements+// • hard same-id retrigger guard (60 ms) — double fires, rAF+// restarts and collab replays don't machine-gun one sound+// • total-concurrency cap (8) — a page with 30 animated elements+// each carrying a sound still degrades gracefully+// • SSR-safe and testable: every entry point no-ops when+// `window` or `Audio` is absent (unit tests run in Node)+//+// Used by the preview/presenter playback engines (element+// animation SFX at their delay, page-transition SFX on page+// change) and by the Audio panel's audition buttons. Video export+// does NOT play sfxId triggers in v1 — documented in+// docs/SOUND.md; inserted pack sounds as AUDIO ELEMENTS ride the+// existing export path.+// ─────────────────────────────────────────────────────────────++import { isSfxId, sfxUrl } from '@/lib/assets/sfx-pack'++/** ms — one id cannot retrigger within this window */+const RETRIGGER_GUARD_MS = 60+/** max simultaneously playing pooled sounds */+const MAX_CONCURRENT = 8++const pool = new Map<string, HTMLAudioElement>()+const lastPlayed = new Map<string, number>()++function activeCount(): number {+ let n = 0+ for (const a of pool.values()) if (!a.paused) n+++ return n+}++/** Release everything (called on unmount of long-lived surfaces). */+export function stopAllSfx(): void {+ for (const a of pool.values()) {+ a.pause()+ a.currentTime = 0+ }+}++/** Play a pack sound by id. Unknown ids are ignored (defensive —+ * sanitizeAnimation already gates what can be stored). `volume`+ * clamps to 0..1. Never throws. */+export function playSfx(id: string, volume = 0.8): void {+ if (!isSfxId(id)) return+ if (typeof window === 'undefined' || typeof Audio === 'undefined') return+ try {+ const now = performance.now()+ const last = lastPlayed.get(id) ?? -Infinity+ if (now - last < RETRIGGER_GUARD_MS) return+ lastPlayed.set(id, now)++ let audio = pool.get(id)+ if (!audio) {+ audio = new Audio(sfxUrl(id))+ audio.preload = 'auto'+ pool.set(id, audio)+ }+ // concurrency cap: stop the oldest playing sound if we're full+ if (activeCount() >= MAX_CONCURRENT) {+ for (const a of pool.values()) {+ if (!a.paused) {+ a.pause()+ break+ }+ }+ }+ audio.volume = Math.min(1, Math.max(0, volume))+ audio.currentTime = 0+ void audio.play().catch(() => {+ /* autoplay policy / decode race — silence is acceptable */+ })+ } catch {+ /* player must never take playback down */+ }+}++/** Test-only: wipe the pool + guards. */+export function resetSfxPlayer(): void {+ pool.clear()+ lastPlayed.clear()+}diff --git a/src/lib/stock-sound.test.ts b/src/lib/stock-sound.test.tsnew file mode 100644index 0000000..eb13de5--- /dev/null+++ b/src/lib/stock-sound.test.ts@@ -0,0 +1,175 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Sound wave tests for the Freesound connector. Same posture as+// stock-photo.test.ts: availability resolves console-first through+// the admin config — mock the db (empty AppConfig by default) so+// the env path is the default. CI has no keys, so recorded+// response shapes are the parsing oracle.++const findMany = vi.hoisted(() => vi.fn())+vi.mock('@/lib/db', () => ({ db: { appConfig: { findMany } } }))++import {+ resetStockSoundCache,+ searchStockSounds,+ stockSoundAvailable,+ stockSoundProviders,+ type StockSoundResult,+} from './stock-sound'+import { invalidateAdminConfig } from '@/lib/admin/config'++// ── recorded Freesound response shape (documented Search results) ──+const FREESOUND_RESPONSE = {+ count: 1234,+ previous: null,+ next: 'https://freesound.org/apiv2/search/text/?page=2',+ results: [+ {+ id: 123456,+ name: 'Soft rain on a window',+ tags: ['rain', 'ambient', 'water', 'window', 'loopable', 'field-recording', 'extra'],+ username: 'rainmaker',+ duration: 12.4,+ license: 'https://creativecommons.org/publicdomain/zero/1.0/',+ previews: {+ 'preview-hq-mp3': 'https://cdn.freesound.org/previews/123/123456_1234-hq.mp3',+ 'preview-lq-mp3': 'https://cdn.freesound.org/previews/123/123456_1234-lq.mp3',+ 'preview-hq-ogg': 'https://cdn.freesound.org/previews/123/123456_1234-hq.ogg',+ 'preview-lq-ogg': 'https://cdn.freesound.org/previews/123/123456_1234-lq.ogg',+ },+ },+ {+ // CC BY result — the label mapping+ id: 789,+ name: 'Thunder clap',+ tags: ['thunder'],+ username: 'stormy',+ duration: 3.1,+ license: 'http://creativecommons.org/licenses/by/4.0/',+ previews: {+ 'preview-hq-mp3': 'https://cdn.freesound.org/previews/789/789_1-hq.mp3',+ },+ },+ {+ // hostile/malformed: no previews at all — dropped, not crashed+ id: 666,+ name: 'Evil',+ tags: 'not-an-array',+ username: 'nobody',+ duration: 'long',+ license: 'javascript:alert(1)',+ url: 'javascript:alert(1)',+ },+ {+ // missing id — dropped+ name: 'No id',+ username: 'x',+ duration: 1,+ license: 'https://creativecommons.org/publicdomain/zero/1.0/',+ previews: { 'preview-hq-mp3': 'https://cdn.freesound.org/previews/x.mp3' },+ },+ ],+}++beforeEach(() => {+ vi.unstubAllEnvs()+ vi.stubEnv('FREESOUND_API_KEY', 'test-key')+ delete process.env.FREESOUND_API_BASE+ findMany.mockReset().mockResolvedValue([])+ invalidateAdminConfig()+ resetStockSoundCache()+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+})++describe('stock-sound availability', () => {+ it('no key → not available, no providers', async () => {+ vi.stubEnv('FREESOUND_API_KEY', '')+ expect(await stockSoundAvailable()).toBe(false)+ expect(await stockSoundProviders()).toEqual([])+ })++ it('env key → available as freesound', async () => {+ expect(await stockSoundAvailable()).toBe(true)+ expect(await stockSoundProviders()).toEqual(['freesound'])+ })+})++describe('searchStockSounds', () => {+ it('no key → NO_PROVIDER', async () => {+ vi.stubEnv('FREESOUND_API_KEY', '')+ await expect(searchStockSounds('rain', 10)).rejects.toThrow('NO_PROVIDER')+ })++ it('blank query → [] without any fetch', async () => {+ const fetchMock = vi.fn()+ expect(await searchStockSounds(' ', 10, { fetchImpl: fetchMock as unknown as typeof fetch })).toEqual([])+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('parses the documented shape, drops hostile rows, maps licences', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(FREESOUND_RESPONSE), { status: 200 }),+ )+ const out = await searchStockSounds('rain', 24, {+ fetchImpl: fetchMock as unknown as typeof fetch,+ noCache: true,+ })+ expect(out).toHaveLength(2)+ const first = out[0] as StockSoundResult+ expect(first.id).toBe('freesound-123456')+ expect(first.name).toBe('Soft rain on a window')+ expect(first.duration).toBe(12.4)+ expect(first.preview).toBe('https://cdn.freesound.org/previews/123/123456_1234-hq.mp3')+ expect(first.tags).toHaveLength(6) // capped+ expect(first.credit.license).toBe('CC0')+ expect(first.credit.author).toBe('rainmaker')+ expect(first.credit.provider).toBe('Freesound')+ expect(first.credit.url).toBe('https://freesound.org/s/123456/')+ // CC BY mapping on the second row+ expect(out[1]?.credit.license).toBe('CC BY')+ // the request is CC0-filtered by default and carries the token+ const calledUrl = fetchMock.mock.calls[0]?.[0] as string+ expect(calledUrl).toContain(encodeURIComponent('license:"Creative Commons 0"'))+ expect(calledUrl).toContain('token=test-key')+ })++ it('includeOtherLicenses drops the CC0 filter', async () => {+ const fetchMock = vi.fn().mockImplementation(() =>+ Promise.resolve(new Response(JSON.stringify(FREESOUND_RESPONSE), { status: 200 })),+ )+ await searchStockSounds('rain', 24, {+ fetchImpl: fetchMock as unknown as typeof fetch,+ noCache: true,+ includeOtherLicenses: true,+ })+ const calledUrl = fetchMock.mock.calls[0]?.[0] as string+ expect(calledUrl).not.toContain('filter=')+ expect(calledUrl).toContain('fields=')+ })++ it('provider error → sanitized status-only message, never the body', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response('{"detail": "Invalid token test-key"}', { status: 401 }),+ )+ await expect(+ searchStockSounds('rain', 10, { fetchImpl: fetchMock as unknown as typeof fetch, noCache: true }),+ ).rejects.toThrow('Freesound search failed (401).')+ })++ it('results cache for 24 h per query+count+filter', async () => {+ const fetchMock = vi.fn().mockImplementation(() =>+ Promise.resolve(new Response(JSON.stringify(FREESOUND_RESPONSE), { status: 200 })),+ )+ const opts = { fetchImpl: fetchMock as unknown as typeof fetch }+ await searchStockSounds('rain', 24, opts)+ await searchStockSounds('rain', 24, opts)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ // different filter → different cache key+ await searchStockSounds('rain', 24, { ...opts, includeOtherLicenses: true })+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/lib/stock-sound.ts b/src/lib/stock-sound.tsnew file mode 100644index 0000000..b453ca9--- /dev/null+++ b/src/lib/stock-sound.ts@@ -0,0 +1,258 @@+// ─────────────────────────────────────────────────────────────+// stock-sound — provider-gated stock SOUND search (the Sound wave).+//+// The fourth stock-media connector, riding the SAME self-hoster-key+// architecture as stock photo (v0.16.4 A4) and stock video (v0.15+// R6): Freesound, plain REST, one free API key. Sound search is a+// library query against a licensed catalogue — never an AI slot —+// and the CC0 filter is ON BY DEFAULT (the audit's requirement):+// everything the connector returns is Creative Commons 0 unless+// the user explicitly opts into wider licences via+// `includeOtherLicenses`.+//+// Key resolution (the A5 pattern): a key stored on the admin AI &+// models page (stock.providers row, freesound) wins over the+// FREESOUND_API_KEY env var; no key configured ⇒ the Audio panel+// keeps its bundled library, web results answer 503 NO_PROVIDER+// with the operator hint, everything else keeps working (F2b+// fail-closed; docs/SOUND.md).+//+// Insert path: the browser downloads the CC0 preview MP3+// (cdn.freesound.org answers CORS-open on GET — verified pattern+// with the other stock CDNs), wraps it in a File and rides the+// existing chunked media store + audio analysis (waveform/BPM/beats+// bake in at insert), landing as a native AudioElement with a+// durable credit block.+//+// Honest limits (same shape as the photo connector):+// - responses cached IN MEMORY per instance for 24 h+// - preview MP3s are the insert rendition (HQ when present);+// original FLAC/WAV/OGG downloads need OAuth2 and are out of+// scope for the self-hoster key flow — recorded in SOUND.md+// - CI has no key: unit tests run against recorded response+// fixtures; the no-provider states are e2e-asserted+// (tests/e2e/sound-gated.spec.ts)+// ─────────────────────────────────────────────────────────────++import { effectiveStockKeys } from '@/lib/admin/config'++export type StockSoundProvider = 'freesound'++/** Sanitized attribution block — also the shape stored on AudioElement.credit. */+export interface StockSoundCredit {+ provider: string+ author: string+ license: string+ url: string+}++/** One normalized search result — provider shape erased. */+export interface StockSoundResult {+ /** provider-prefixed unique id, e.g. 'freesound-123456' */+ id: string+ provider: StockSoundProvider+ /** cleaned display name */+ name: string+ /** seconds */+ duration: number+ /** preview MP3 (the insert rendition) */+ preview: string+ /** cleaned tags (max 6, tile-sized) */+ tags: string[]+ credit: StockSoundCredit+}++// ── availability (secret-free — never expose the key) ─────────++export async function stockSoundProviders(): Promise<StockSoundProvider[]> {+ const keys = await effectiveStockKeys()+ return keys.freesound ? ['freesound'] : []+}++export async function stockSoundAvailable(): Promise<boolean> {+ return (await stockSoundProviders()).length > 0+}++// ── shared helpers (the photo connector's, kept local) ────────++function isHttpUrl(v: unknown): v is string {+ if (typeof v !== 'string' || v.length === 0 || v.length > 2000) return false+ try {+ const u = new URL(v)+ return u.protocol === 'http:' || u.protocol === 'https:'+ } catch {+ return false+ }+}++function num(v: unknown, fallback = 0): number {+ const n = Number(v)+ return Number.isFinite(n) && n >= 0 ? n : fallback+}++function cleanText(v: unknown, max: number): string {+ const s = typeof v === 'number' && Number.isFinite(v) ? String(v) : typeof v === 'string' ? v : ''+ if (!s) return ''+ return s.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max)+}++function sanitizeCredit(raw: { provider: string; author: string; license: string; url: unknown }): StockSoundCredit | null {+ const url = isHttpUrl(raw.url) ? raw.url : ''+ const provider = cleanText(raw.provider, 24)+ const author = cleanText(raw.author, 80)+ const license = cleanText(raw.license, 80)+ if (!provider || !author || !license) return null+ return { provider, author, license, url }+}++// ── Freesound — GET /apiv2/search/text/, token query param ────+// Documented response (parsed defensively — the API may add keys):+// { count: number, results: [{ id, name, tags: string[],+// username, duration, license, previews: {+// 'preview-hq-mp3': url, 'preview-lq-mp3': url,+// 'preview-hq-ogg': url, 'preview-lq-ogg': url } }] }+//+// License values are URLs like https://creativecommons.org/publicdomain/zero/1.0/+// — mapped to the short display form; anything CC0 stays CC0.++const FREESOUND_LICENSE_LABELS: [RegExp, string][] = [+ [/publicdomain\/zero/i, 'CC0'],+ [/licenses\/by\//i, 'CC BY'],+ [/licenses\/by-nc/i, 'CC BY-NC'],+ [/licenses\/sampling\+/i, 'CC Sampling+'],+]++function licenseLabel(v: unknown): string {+ const s = typeof v === 'string' ? v : ''+ for (const [re, label] of FREESOUND_LICENSE_LABELS) if (re.test(s)) return label+ return cleanText(s.replace(/^https?:\/\/creativecommons\.org\//, ''), 40) || 'See source'+}++function parseFreesound(body: unknown): StockSoundResult[] {+ const results = (body as { results?: unknown })?.results+ if (!Array.isArray(results)) return []+ const out: StockSoundResult[] = []+ for (const r of results) {+ if (!r || typeof r !== 'object') continue+ const s = r as Record<string, unknown>+ const previews = s.previews && typeof s.previews === 'object' ? (s.previews as Record<string, unknown>) : {}+ const preview =+ (typeof previews['preview-hq-mp3'] === 'string' && previews['preview-hq-mp3']) ||+ (typeof previews['preview-lq-mp3'] === 'string' && previews['preview-lq-mp3']) ||+ ''+ if (!isHttpUrl(preview)) continue+ const id = cleanText(s.id, 32)+ if (!id) continue+ const tags = Array.isArray(s.tags)+ ? s.tags.filter((t): t is string => typeof t === 'string').map((t) => cleanText(t, 24)).filter(Boolean).slice(0, 6)+ : []+ const license = licenseLabel(s.license)+ const credit = sanitizeCredit({+ provider: 'Freesound',+ author: typeof s.username === 'string' && s.username ? s.username : 'Freesound creator',+ license,+ url: `https://freesound.org/s/${id}/`,+ })+ if (!credit) continue+ out.push({+ id: `freesound-${id}`,+ provider: 'freesound',+ name: cleanText(s.name, 80) || 'Untitled sound',+ duration: Math.min(600, num(s.duration)),+ preview,+ tags,+ credit,+ })+ }+ return out+}++// ── the 24 h in-memory response cache (per instance) ──────────++interface CacheEntry {+ at: number+ results: StockSoundResult[]+}+const CACHE_TTL_MS = 24 * 3600_000+const CACHE_MAX = 256+const searchCache = new Map<string, CacheEntry>()++function cacheGet(key: string): StockSoundResult[] | null {+ const entry = searchCache.get(key)+ if (!entry) return null+ if (Date.now() - entry.at > CACHE_TTL_MS) {+ searchCache.delete(key)+ return null+ }+ return entry.results+}++function cacheSet(key: string, results: StockSoundResult[]): void {+ searchCache.set(key, { at: Date.now(), results })+ if (searchCache.size > CACHE_MAX) {+ const oldest = [...searchCache.entries()].sort((a, b) => a[1].at - b[1].at)+ for (const [k] of oldest.slice(0, Math.floor(oldest.length / 2))) searchCache.delete(k)+ }+}++/** Test-only: wipe the response cache. */+export function resetStockSoundCache(): void {+ searchCache.clear()+}++// ── search ─────────────────────────────────────────────────────++const PROVIDER_FETCH_TIMEOUT_MS = 10_000+const FREESOUND_FIELDS = 'id,name,tags,username,duration,license,previews'++export interface SearchStockSoundsOptions {+ /** include non-CC0 licences (CC BY etc.) — default CC0 only */+ includeOtherLicenses?: boolean+ /** injected for tests — defaults to the global fetch */+ fetchImpl?: typeof fetch+ /** test-only: bypass the response cache */+ noCache?: boolean+}++export async function searchStockSounds(+ query: string,+ count: number,+ opts: SearchStockSoundsOptions = {},+): Promise<StockSoundResult[]> {+ const keys = await effectiveStockKeys()+ if (!keys.freesound) throw new Error('NO_PROVIDER')++ const q = query.trim().slice(0, 120)+ if (!q) return []+ const n = Math.min(Math.max(count, 1), 40)++ const cacheKey = `freesound:${q}:${n}:${opts.includeOtherLicenses ? 'all' : 'cc0'}`+ if (!opts.noCache) {+ const cached = cacheGet(cacheKey)+ if (cached) return cached+ }++ const base = (process.env.FREESOUND_API_BASE ?? 'https://freesound.org/apiv2').replace(/\/+$/, '')+ // CC0 by default — the audit's standing requirement. The wider+ // filter only ever UNIONs more permissive-looking licences the+ // user explicitly asked for; credit blocks stay durable either way.+ const licenseFilter = opts.includeOtherLicenses+ ? ''+ : `filter=${encodeURIComponent('license:"Creative Commons 0"')}&`+ const url =+ `${base}/search/text/?query=${encodeURIComponent(q)}&${licenseFilter}` ++ `fields=${FREESOUND_FIELDS}&page_size=${n}&token=${encodeURIComponent(keys.freesound)}`+ const doFetch = opts.fetchImpl ?? fetch+ const res = await doFetch(url, {+ signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),+ })+ if (!res.ok) {+ // never surface the provider body — the key lives in this URL+ console.error(`[stock-sound] freesound search failed: ${res.status}`)+ throw new Error(`Freesound search failed (${res.status}).`)+ }+ const body = await res.json()+ const results = parseFreesound(body)+ cacheSet(cacheKey, results)+ return results+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex 0064572..1fca75d 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -41,6 +41,11 @@ export interface ElementAnimation {easing: AnimationEasing/** pan/rise travel direction */direction?: AnimationDirection+ /** Sound wave: offline pack sound played when the animation+ * triggers (at its delay) in preview/present. Additive —+ * pre-sound documents are unaffected. Validated against the+ * pack catalogue; unknown ids are dropped on sanitize. */+ sfxId?: string}export type TransitionKind = 'none' | 'fade' | 'slide' | 'morph'@@ -50,6 +55,9 @@ export interface PageTransition {/** 0.1–2.5 s */duration: numberdirection?: AnimationDirection+ /** Sound wave: offline pack sound played when this page+ * appears after another (preview/present). Additive. */+ sfxId?: string}/** canva speed presets (seconds) */@@ -423,6 +431,10 @@ export interface AudioElement extends BaseElement {bpm?: number/** beat grid in seconds (aligned to the strongest onset) */beats?: number[]+ /** Sound wave: durable attribution for stock/recorded audio —+ * {provider, author, license, url} (the A4 photo pattern; shown in+ * the properties bar, never burned into exports). */+ credit?: { provider: string; author: string; license: string; url: string }}/** Native video element — the editor renders the poster frame (captured atdiff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 0f543c9..cd4e748 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -32,6 +32,7 @@ export type PanelId =| 'uploads'| 'photos'| 'videos'+ | 'audio'| 'tools'| 'projects'| 'apps'diff --git a/tests/e2e/sound-gated.spec.ts b/tests/e2e/sound-gated.spec.tsnew file mode 100644index 0000000..4625643--- /dev/null+++ b/tests/e2e/sound-gated.spec.ts@@ -0,0 +1,121 @@+import { expect, test } from '@playwright/test'++/**+ * Sound wave — the Audio rail, NO FREESOUND KEY (the F2b gate).+ *+ * The Audio tab ALWAYS shows (like Photos — it ships the offline+ * pack that works with zero configuration). What gates is the+ * Freesound search section. On the default suite (no+ * FREESOUND_API_KEY):+ * 1. /api/stock-sound/available answers available=false+ * 2. POST /api/stock-sound/search answers 503 NO_PROVIDER (+ the+ * hint names the key and the CC0 default; nothing leaks)+ * 3. the Audio tab is right there; the 16-sound library renders+ * and inserting a pack sound lands a native audio element+ * 4. the voiceover button renders (mic denied in CI → honest toast)+ * 5. the Animate panel exposes the SFX picker on an animated+ * element; the pick survives the store (sanitize keeps known ids)+ * 6. /api/ai/capabilities reports soundSearch=false (no key)+ *+ * The keyed world (search → insert → durable attribution) is covered+ * by unit tests against recorded fixtures (the stock-photo posture).+ */+test.describe('sound wave without the Freesound key (F2b gate)', () => {+ test('available=false, search 503 NO_PROVIDER with hint, Audio rail intact', async ({ page, request }) => {+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // 1. secret-free availability probe+ const avail = await request.get('/api/stock-sound/available')+ expect(avail.status()).toBe(200)+ expect(await avail.json()).toEqual({ available: false, providers: [] })++ // 2. the gated search route — hint names the key, nothing leaks+ const res = await request.post('/api/stock-sound/search', { data: { query: 'rain' } })+ expect(res.status()).toBe(503)+ const body = (await res.json()) as { code?: string; hint?: string }+ expect(body.code).toBe('NO_PROVIDER')+ expect(body.hint).toContain('FREESOUND_API_KEY')+ expect(body.hint).toContain('Creative Commons 0')++ // capabilities reports the sound gate honestly+ const caps = (await (await request.get('/api/ai/capabilities')).json()) as {+ capabilities?: Record<string, boolean>+ }+ expect(caps.capabilities?.soundSearch).toBe(false)+ expect(caps.capabilities?.upscale).toBe(true) // local tools unaffected++ // 3. the editor: Audio tab renders, library + insert work offline+ await page.goto('/')+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ await page.getByRole('button', { name: 'Audio', exact: true }).click()+ await expect(page.getByRole('heading', { name: 'Audio', exact: true })).toBeVisible()++ // the 16-sound offline pack renders+ const grid = page.getByTestId('sfx-grid')+ await expect(grid).toBeVisible()+ await expect(grid.locator('button[aria-label^="Play "]')).toHaveCount(16, { timeout: 15_000 })++ // the unkeyed Freesound hint (positive no, not probe-in-flight)+ await expect(page.getByTestId('sound-unkeyed-hint')).toBeVisible({ timeout: 15_000 })+ await expect(page.getByTestId('sound-unkeyed-hint')).toContainText('Freesound')++ // 4. the voiceover surface renders (CI denies the mic — the+ // honest denial toast is the no-permission contract)+ await expect(page.getByTestId('voiceover-button')).toBeVisible()+ await expect(page.getByTestId('voiceover-button')).toContainText(/record voiceover/i)++ // 5. insert a pack sound → a native audio element lands on the page+ await grid.locator('button[aria-label^="Play "]').first().click() // audition path+ await grid.locator('button', { hasText: 'Whoosh soft' }).first().click()+ await expect(page.getByText('Sound added').first()).toBeVisible({ timeout: 20_000 })+ // the waveform card (audio element) renders on the canvas+ await expect(page.getByLabel('Design canvas')).toBeVisible()++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })++ test('Animate panel exposes the SFX picker; known ids survive sanitize', async ({ page }) => {+ await page.goto('/')+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // the starter page is empty — add a heading first (auto-selects),+ // then open Animate+ await page.getByRole('button', { name: 'Text', exact: true }).click()+ await page.getByRole('button', { name: 'Add a heading', exact: true }).click()+ await expect(page.getByLabel('Design canvas')).toBeVisible()+ await page.getByRole('button', { name: 'Animate', exact: true }).click()++ await page.getByRole('button', { name: 'Element', exact: true }).click()+ await page.getByRole('button', { name: /fade/i }).first().click()++ // the entrance-sound picker appears with the pack's options+ const picker = page.getByTestId('sfx-picker').locator('select')+ await expect(picker).toBeVisible()+ const options = await picker.locator('option').allTextContents()+ expect(options.join(' ')).toContain('None')+ expect(options.join(' ')).toContain('Chime')+ expect(options).toHaveLength(17) // None + the 16 pack sounds++ // pick one — it applies to the animation config (store round-trip)+ await picker.selectOption('chime')+ await expect(picker).toHaveValue('chime')+ })+})