@lincyaw/workbench 0.2.0-rc.56 → 0.2.0-rc.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.56",
3
+ "version": "0.2.0-rc.58",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.56",
59
- "@lincyaw/kernel": "1.0.0-rc.56"
58
+ "@lincyaw/design": "1.0.0-rc.58",
59
+ "@lincyaw/kernel": "1.0.0-rc.58"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.56"
70
+ "@lincyaw/compiler": "1.0.0-rc.58"
71
71
  }
72
72
  }
@@ -21,6 +21,8 @@ import { clearVoiceDraft, keepVoiceDraft, voiceDraftSnapshot } from './voice-dra
21
21
  import type { VoiceDraft } from './voice-drafts.ts'
22
22
  import { discardMediaDraft, keepMediaDrafts, mediaDraftSnapshot } from './media-drafts.ts'
23
23
  import type { MediaDrafts } from './media-drafts.ts'
24
+ import { TranscriptionCorrections } from './transcription-drafts.ts'
25
+ import type { TranscriptionCorrection, TranscriptionCorrectionTarget } from './transcription-drafts.ts'
24
26
 
25
27
  interface ProductionOptions {
26
28
  store: WorkbenchStore
@@ -56,6 +58,7 @@ export class DocumentProduction {
56
58
  readonly #documentTimingDrafts = new DocumentTimingDrafts()
57
59
  readonly #captionTimingDrafts = new CaptionTimingDrafts()
58
60
  readonly #recordingRangeDrafts = new Map<string, Map<string, RecordingRangeDraft>>()
61
+ readonly #transcriptionCorrections = new TranscriptionCorrections()
59
62
  readonly #draftViews = new Set<ProductionDraftView>()
60
63
  readonly #draftSalt = randomUUID()
61
64
  #draftRevision = 0
@@ -77,7 +80,7 @@ export class DocumentProduction {
77
80
  }
78
81
  }
79
82
  reset(): void { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined }
80
- dispose(): void { this.#closed = true; this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear(); this.#draftViews.clear() }
83
+ dispose(): void { this.#closed = true; this.reset(); this.#captionTimingDrafts.close(); this.#transcriptionCorrections.close(); this.#recordingRangeDrafts.clear(); this.#draftViews.clear() }
81
84
  get draftRevision(): number { return this.#draftRevision }
82
85
  get productionDraftsBlocked(): boolean {
83
86
  const identity = this.#options.store.state.authoring?.identity
@@ -112,6 +115,15 @@ export class DocumentProduction {
112
115
  const kept = keepMediaDrafts(this.#options.client, identity, stepId, value)
113
116
  this.#draftChanged(); return kept
114
117
  }
118
+ transcriptionCorrection(target: TranscriptionCorrectionTarget) { return this.#transcriptionCorrections.read(target) }
119
+ keepTranscriptionCorrection(target: TranscriptionCorrectionTarget, draft: TranscriptionCorrection): boolean {
120
+ const kept = this.#transcriptionCorrections.keep(target, draft)
121
+ this.#draftChanged(); return kept
122
+ }
123
+ completeTranscriptionCorrection(target: TranscriptionCorrectionTarget, expected: TranscriptionCorrection, next: TranscriptionCorrection): boolean {
124
+ const completed = this.#transcriptionCorrections.complete(target, expected, next)
125
+ this.#draftChanged(); return completed
126
+ }
115
127
  /** Native pending range input survives mode and document changes within this workbench. */
116
128
  recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
117
129
  let values = this.#recordingRangeDrafts.get(identity)
@@ -130,6 +142,7 @@ export class DocumentProduction {
130
142
  const state = this.#options.store.state, source = state.authoring, identity = source?.identity, memberId = source?.member?.id, content = source?.content
131
143
  if (this.#closed || !source || !identity || !memberId || !content || !source.version || !source.fingerprint || source.loading) throw new Error('client-production-drafts-unavailable')
132
144
  const revision = this.#draftRevision, version = source.version, reset = source.reset
145
+ const corrections = this.#transcriptionCorrections.snapshot(identity)
133
146
  const views = [...this.#draftViews].filter(view => view.identity === identity)
134
147
  const viewState = () => JSON.stringify(views.map(view => view.blocked()))
135
148
  const blocked = viewState()
@@ -139,6 +152,7 @@ export class DocumentProduction {
139
152
  && !isAgentChanging(value) && !value.isCreatingPage && !value.isEditingPage && !value.isHistoryBusy && !value.isHistoryPreparing && !this.productionDraftsBlocked)
140
153
  }
141
154
  const guard = () => {
155
+ corrections.guard()
142
156
  const current = this.#options.store.state.authoring
143
157
  if (!current || current.identity !== identity || current.member?.id !== memberId || current.content !== content || current.version !== version || current.reset !== reset
144
158
  || current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
@@ -181,9 +195,14 @@ export class DocumentProduction {
181
195
  add('media-clip', JSON.stringify([stepId, name]), stepId, draft, draft.version !== version || Boolean(draft.baseClip && JSON.stringify(draft.baseClip) !== JSON.stringify(original)), persisted ? 'tab' : 'memory',
182
196
  () => discardMediaDraft(this.#options.client, identity, stepId, name, value), { clipId: draft.clip.id, ...draft.clip.assetId ? { assetId: draft.clip.assetId } : {} }, !media.partial)
183
197
  }
198
+ for (const { key, target, draft, persisted } of corrections.entries) {
199
+ const { identity: _identity, ...binding } = target
200
+ add('transcription', key, target.stepId, { ...binding, draft }, true, persisted ? 'tab' : 'memory',
201
+ () => this.#transcriptionCorrections.discard(key, draft), {}, !corrections.partial)
202
+ }
184
203
  candidates.sort((a, b) => a.key.localeCompare(b.key))
185
204
  guard()
186
- return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial || voices.partial || media.partial ? 'partial' : 'tab-state', candidates, guard }
205
+ return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial || voices.partial || media.partial || corrections.partial ? 'partial' : 'tab-state', candidates, guard }
187
206
  }
188
207
 
189
208
  source(expected: { identity: string, version: string }): DocumentSessionState {
@@ -7,24 +7,13 @@ import { NarrationEditor } from '../document-editor/NarrationEditor.tsx'
7
7
  import { narrationToNative, nativeToNarration } from '../document-editor/narration.ts'
8
8
  import type { NativeNarrationEditor } from '../document-editor/narration-schema.tsx'
9
9
  import { TRANSCRIPTION_MESSAGES } from '../transcription-messages.ts'
10
+ import { transcriptionCorrectionKey } from '../transcription-drafts.ts'
11
+ import type { TranscriptionCorrection as Draft } from '../transcription-drafts.ts'
10
12
 
11
13
  interface Props { identity: string, candidate: TranscriptionRevision, document: TeachingDocument, sectionId: string, stepId: string, disabled: boolean }
12
- interface Draft { id: string, revision: number, nodes?: NarrationNode[], discarded: string[], shared: 'fork' | 'edit-shared', baseVersion?: string, applied?: boolean }
13
14
  const ordered = (value: unknown): unknown => Array.isArray(value) ? value.map(ordered) : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered((value as Record<string, unknown>)[key])])) : value
14
15
  const same = (a: unknown, b: unknown) => JSON.stringify(ordered(a)) === JSON.stringify(ordered(b))
15
16
  const displayed = (nodes: readonly NarrationNode[]) => nodes.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
16
- function restore(key: string): { draft: Draft, failed: boolean } {
17
- const fallback = () => ({ draft: { id: randomUUID(), revision: 0, discarded: [], shared: 'fork' as const }, failed: false })
18
- try {
19
- const raw = localStorage.getItem(key)
20
- if (!raw) return fallback()
21
- const value = JSON.parse(raw)
22
- if (!value || typeof value.id !== 'string' || !Number.isSafeInteger(value.revision) || value.revision < 0 || !Array.isArray(value.discarded) || !value.discarded.every((key: unknown) => typeof key === 'string') || !['fork', 'edit-shared'].includes(value.shared)
23
- || value.baseVersion !== undefined && typeof value.baseVersion !== 'string' || value.applied !== undefined && typeof value.applied !== 'boolean'
24
- || value.nodes !== undefined && (!Array.isArray(value.nodes) || !value.nodes.every((node: NarrationNode) => node && (node.type === 'text' && typeof node.text === 'string' || node.type === 'pronunciation' && typeof node.display === 'string' && typeof node.spoken === 'string' || node.type === 'cue' && typeof node.id === 'string' && typeof node.action === 'string')))) throw new Error('invalid-draft')
25
- return { draft: value, failed: false }
26
- } catch { return { ...fallback(), failed: true } }
27
- }
28
17
 
29
18
  export function TranscriptionAdoption(props: Props) {
30
19
  const locale = useWorkbenchState(state => state.locale), t = TRANSCRIPTION_MESSAGES[locale]
@@ -41,11 +30,27 @@ export function TranscriptionAdoption(props: Props) {
41
30
 
42
31
  function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disabled, narrationId, segments }: Props & { narrationId?: string, segments: string[] }) {
43
32
  const workbench = useWorkbench(), locale = useWorkbenchState(state => state.locale), t = TRANSCRIPTION_MESSAGES[locale], source = useWorkbenchState(state => state.authoring)
44
- const key = `presmium.transcription-draft.v1:${JSON.stringify([identity, candidate.transcriptionId, candidate.revision, stepId, narrationId, segments])}`
45
- const [restored] = useState(() => restore(key)), [draft, setDraft] = useState(restored.draft), latest = useRef(draft)
33
+ const correctionTarget = useMemo(() => ({ identity, candidate: { id: candidate.transcriptionId, revision: candidate.revision }, stepId, narrationId, segmentIds: segments }), [identity, candidate.transcriptionId, candidate.revision, stepId, narrationId, JSON.stringify(segments)])
34
+ const correctionKey = transcriptionCorrectionKey(correctionTarget), key = `presmium.transcription-draft.v1:${correctionKey}`
35
+ const [restored] = useState(() => workbench.production.transcriptionCorrection(correctionTarget)), [draft, setDraft] = useState(restored.draft), latest = useRef(draft)
46
36
  const [storageFailed, setStorageFailed] = useState(restored.failed), [composing, setComposing] = useState(false)
47
37
  const [plan, setPlan] = useState<TranscriptionAdoptionPlan>(), [reviewing, setReviewing] = useState(false), [applying, setApplying] = useState(false), [open, setOpen] = useState(false), [failure, setFailure] = useState<string>(), [status, setStatus] = useState<string>()
48
- const editor = useRef<NativeNarrationEditor>(), generation = useRef(0)
38
+ const editor = useRef<NativeNarrationEditor>(), generation = useRef(0), interaction = useRef({ composing: false, pending: false }), unavailable = useRef(false)
39
+ unavailable.current = disabled || reviewing || applying || open
40
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'transcription', has: target => target === correctionKey,
41
+ blocked: () => interaction.current.composing || interaction.current.pending || unavailable.current,
42
+ clear: () => {
43
+ generation.current++
44
+ const value = workbench.production.transcriptionCorrection(correctionTarget)
45
+ latest.current = value.draft; setDraft(value.draft); setStorageFailed(value.failed)
46
+ setPlan(undefined); setOpen(false); setFailure(undefined); setStatus(undefined)
47
+ } }), [workbench, identity, correctionKey])
48
+ useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, disabled, reviewing, applying, open])
49
+ const busy = (value: boolean) => { interaction.current.pending = value; workbench.refreshAuthoringClientControls() }
50
+ const composition = (value: boolean) => {
51
+ if (interaction.current.composing === value) return
52
+ interaction.current.composing = value; setComposing(value); workbench.refreshAuthoringClientControls()
53
+ }
49
54
  useEffect(() => () => { generation.current++ }, [])
50
55
  const binding: CanonicalSource = { documentId: document.id, version: source?.version ?? '', fingerprint: source?.fingerprint ?? '' }
51
56
  const references = narrationId ? Object.values(document.steps).filter(step => step.narrationIds.includes(narrationId)).map(step => step.id) : []
@@ -76,7 +81,7 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
76
81
  generation.current++
77
82
  const next = { ...latest.current, ...patch, revision: latest.current.revision + 1, applied: false }
78
83
  latest.current = next; setDraft(next); setPlan(undefined); setFailure(undefined); setStatus(undefined)
79
- try { localStorage.setItem(key, JSON.stringify(next)); setStorageFailed(false) } catch { setStorageFailed(true) }
84
+ setStorageFailed(!workbench.production.keepTranscriptionCorrection(correctionTarget, next))
80
85
  }
81
86
  const pause = () => { workbench.stopAuditions(); void workbench.pausePlayback().catch(() => {}) }
82
87
  const preview = async () => {
@@ -89,34 +94,34 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
89
94
  const retainsOriginal = references.length > 1 && value.shared === 'fork'
90
95
  const removeCueTimings = atoms.filter(atom => value.discarded.includes(atom.key) && atom.node.type === 'cue' && !retainsOriginal && Object.hasOwn(document.production.cueTimings ?? {}, atom.node.id)).map(atom => (atom.node as Extract<NarrationNode, { type: 'cue' }>).id)
91
96
  const sent: TranscriptionAdoptionDraft = { id: value.id, source: { documentId: document.id, version: now.version, fingerprint: now.fingerprint }, candidate: { id: candidate.transcriptionId, revision: candidate.revision }, draftRevision: value.revision, targets: [{ ...target, content: normalized.parts, discardAtoms: value.discarded.filter(key => atoms.some(atom => atom.key === key)) }], ...removeCueTimings.length ? { removeCueTimings } : {} }
92
- setReviewing(true); setFailure(undefined)
97
+ busy(true); setReviewing(true); setFailure(undefined)
93
98
  try {
94
99
  const answer = await workbench.production.planTranscription(sent, { identity, version: now.version })
95
100
  if (request !== generation.current || latest.current.revision !== sent.draftRevision) return
96
101
  setPlan(answer); setOpen(true)
97
102
  } catch { if (request === generation.current) setFailure(t.previewFailed) }
98
- finally { setReviewing(false) }
103
+ finally { busy(false); setReviewing(false) }
99
104
  }
100
105
  const apply = async () => {
101
106
  if (!plan?.planId || !planCurrent || plan.conflicts.length || plan.draftRevision !== latest.current.revision || composing || applying || !sourceReady) return
102
- const sent = plan, planId = plan.planId
103
- setApplying(true); setFailure(undefined)
107
+ const sent = plan, planId = plan.planId, expected = latest.current, request = ++generation.current
108
+ busy(true); setApplying(true); setFailure(undefined)
104
109
  try {
105
110
  const answer = await workbench.production.adoptTranscription({ planId, source: sent.source, candidate: sent.candidate, draftRevision: sent.draftRevision }, { identity, version: sent.source.version })
106
- if (latest.current.id === sent.changeId && latest.current.revision === sent.draftRevision) {
107
- const next: Draft = { ...latest.current, id: randomUUID(), revision: 0, discarded: [], baseVersion: answer.version, applied: true }
108
- latest.current = next; setDraft(next)
109
- try { localStorage.setItem(key, JSON.stringify(next)); setStorageFailed(false) } catch { setStorageFailed(true) }
110
- }
111
+ const next: Draft = { ...expected, id: randomUUID(), revision: 0, discarded: [], baseVersion: answer.version, applied: true }
112
+ const completed = workbench.production.completeTranscriptionCorrection(correctionTarget, expected, next)
113
+ if (request !== generation.current) return
114
+ if (completed) { latest.current = next; setDraft(next) }
115
+ setStorageFailed(!completed)
111
116
  setPlan(undefined); setOpen(false); setStatus(t.adopted)
112
117
  } catch { setFailure(t.applyFailed) }
113
- finally { setApplying(false) }
118
+ finally { busy(false); setApplying(false) }
114
119
  }
115
120
  if (!displayed(nodes).trim() && !atoms.length) return <span>{t.empty}</span>
116
121
  return <>
117
122
  <PmField label={t.text} group><NarrationEditor identity={key} fieldId={original?.outputNarrationId ?? draft.id} content={nodes} getContent={() => latest.current.nodes ?? nodes} locale={locale} advanced={false} readOnly={disabled || applying}
118
123
  toNative={value => narrationToNative(original?.outputNarrationId ?? draft.id, value)} fromNative={nativeToNarration}
119
- onReady={value => { editor.current = value }} onComposition={setComposing} onFocus={pause} onChange={value => {
124
+ onReady={value => { editor.current = value }} onComposition={composition} onFocus={pause} onChange={value => {
120
125
  const used = new Set<string>()
121
126
  for (const node of value) { const atom = atoms.find(atom => !used.has(atom.key) && same(atom.node, node)); if (atom) used.add(atom.key) }
122
127
  change({ nodes: value, discarded: latest.current.discarded.filter(key => !used.has(key)) })
@@ -0,0 +1,124 @@
1
+ import { isRecord, randomUUID } from '@lincyaw/kernel'
2
+ import type { NarrationNode, TranscriptionAdoptionDraft } from '@lincyaw/kernel'
3
+
4
+ export interface TranscriptionCorrection { id: string, revision: number, nodes?: NarrationNode[], discarded: string[], shared: 'fork' | 'edit-shared', baseVersion?: string, applied?: boolean }
5
+ export interface TranscriptionCorrectionTarget { identity: string, candidate: TranscriptionAdoptionDraft['candidate'], stepId: string, narrationId?: string, segmentIds: string[] }
6
+ interface Entry { target: TranscriptionCorrectionTarget, draft?: TranscriptionCorrection, raw?: string | null, failed: boolean, corrupt: boolean }
7
+ const prefix = 'presmium.transcription-draft.v1:'
8
+ export const transcriptionCorrectionKey = (target: TranscriptionCorrectionTarget): string => JSON.stringify([target.identity, target.candidate.id, target.candidate.revision, target.stepId, target.narrationId ?? null, target.segmentIds])
9
+ const fresh = (): TranscriptionCorrection => ({ id: randomUUID(), revision: 0, discarded: [], shared: 'fork' })
10
+ function valid(value: unknown): value is TranscriptionCorrection {
11
+ return isRecord(value) && typeof value.id === 'string' && Number.isSafeInteger(value.revision) && Number(value.revision) >= 0 && Array.isArray(value.discarded) && value.discarded.every(key => typeof key === 'string') && ['fork', 'edit-shared'].includes(String(value.shared))
12
+ && (value.baseVersion === undefined || typeof value.baseVersion === 'string') && (value.applied === undefined || typeof value.applied === 'boolean')
13
+ && (value.nodes === undefined || Array.isArray(value.nodes) && value.nodes.every(node => isRecord(node) && (node.type === 'text' && typeof node.text === 'string' || node.type === 'pronunciation' && typeof node.display === 'string' && typeof node.spoken === 'string' || node.type === 'cue' && typeof node.id === 'string' && typeof node.action === 'string')))
14
+ }
15
+ function parseTarget(key: string): TranscriptionCorrectionTarget | undefined {
16
+ try {
17
+ const value: unknown = JSON.parse(key)
18
+ if (!Array.isArray(value) || value.length !== 6) return
19
+ const [identity, id, revision, stepId, narrationId, segmentIds] = value
20
+ if (typeof identity !== 'string' || typeof id !== 'string' || typeof revision !== 'string' || typeof stepId !== 'string' || narrationId !== null && typeof narrationId !== 'string' || !Array.isArray(segmentIds) || !segmentIds.every(id => typeof id === 'string')) return
21
+ return { identity, candidate: { id, revision }, stepId, ...narrationId !== null ? { narrationId } : {}, segmentIds }
22
+ } catch { return }
23
+ }
24
+
25
+ /** The native correction bank uses its existing localStorage keys; no MCP copy or provider result is changed. */
26
+ export class TranscriptionCorrections {
27
+ readonly #entries = new Map<string, Entry>()
28
+ #load(target: TranscriptionCorrectionTarget): Entry {
29
+ const key = transcriptionCorrectionKey(target), known = this.#entries.get(key)
30
+ if (known) return known
31
+ const entry: Entry = { target: structuredClone(target), failed: false, corrupt: false }
32
+ this.#entries.set(key, entry)
33
+ try {
34
+ entry.raw = localStorage.getItem(prefix + key)
35
+ if (entry.raw !== null) {
36
+ const value: unknown = JSON.parse(entry.raw)
37
+ if (!valid(value)) throw new Error('invalid-draft')
38
+ entry.draft = value
39
+ }
40
+ } catch { entry.failed = true; entry.corrupt = entry.raw != null }
41
+ return entry
42
+ }
43
+ read(target: TranscriptionCorrectionTarget): { draft: TranscriptionCorrection, failed: boolean } {
44
+ const entry = this.#load(target)
45
+ // A reopened native form adopts another window's saved value, retaining failed local input.
46
+ try {
47
+ const raw = localStorage.getItem(prefix + transcriptionCorrectionKey(target))
48
+ if (raw !== entry.raw && !(entry.failed && entry.draft)) {
49
+ const value: unknown = raw === null ? undefined : JSON.parse(raw)
50
+ if (value !== undefined && !valid(value)) throw new Error('invalid-draft')
51
+ entry.raw = raw; entry.draft = value as TranscriptionCorrection | undefined; entry.failed = false; entry.corrupt = false
52
+ } else if (raw !== entry.raw) entry.failed = true
53
+ } catch { entry.failed = true }
54
+ return { draft: entry.draft ? structuredClone(entry.draft) : fresh(), failed: entry.failed }
55
+ }
56
+ keep(target: TranscriptionCorrectionTarget, draft: TranscriptionCorrection): boolean {
57
+ if (!valid(draft)) throw new Error('invalid-draft')
58
+ const entry = this.#load(target), key = prefix + transcriptionCorrectionKey(target)
59
+ entry.draft = structuredClone(draft)
60
+ try {
61
+ if (entry.raw === undefined || localStorage.getItem(key) !== entry.raw) throw new Error('changed-draft')
62
+ if (entry.corrupt && entry.raw != null) localStorage.setItem(key + ':unreadable', entry.raw)
63
+ const raw = JSON.stringify(draft)
64
+ localStorage.setItem(key, raw)
65
+ entry.raw = raw; entry.failed = false; entry.corrupt = false
66
+ return true
67
+ } catch { entry.failed = true; return false }
68
+ }
69
+ /** A completed native adoption cannot retire input changed in another form/window while it ran. */
70
+ complete(target: TranscriptionCorrectionTarget, expected: TranscriptionCorrection, next: TranscriptionCorrection): boolean {
71
+ const key = transcriptionCorrectionKey(target), entry = this.#entries.get(key)
72
+ if (!entry || entry.corrupt || JSON.stringify(entry.draft) !== JSON.stringify(expected)) return false
73
+ try {
74
+ if (entry.raw === undefined || localStorage.getItem(prefix + key) !== entry.raw) return false
75
+ const raw = JSON.stringify(next)
76
+ localStorage.setItem(prefix + key, raw)
77
+ entry.raw = raw; entry.draft = structuredClone(next); entry.failed = false
78
+ return true
79
+ } catch { entry.failed = true; return false }
80
+ }
81
+ discard(key: string, expected: TranscriptionCorrection): boolean {
82
+ const entry = this.#entries.get(key)
83
+ if (!entry || entry.corrupt || JSON.stringify(entry.draft) !== JSON.stringify(expected)) return false
84
+ try {
85
+ if (entry.raw === undefined || localStorage.getItem(prefix + key) !== entry.raw) return false
86
+ localStorage.removeItem(prefix + key)
87
+ this.#entries.delete(key)
88
+ return true
89
+ } catch { entry.failed = true; return false }
90
+ }
91
+ snapshot(identity: string) {
92
+ const keys = new Set([...this.#entries].filter(([, entry]) => entry.target.identity === identity).map(([key]) => key))
93
+ let partial = false
94
+ const head = prefix + JSON.stringify([identity]).slice(0, -1) + ','
95
+ try {
96
+ for (let i = 0; i < localStorage.length; i++) {
97
+ const key = localStorage.key(i)
98
+ if (key?.startsWith(head) && !key.endsWith(':unreadable')) keys.add(key.slice(prefix.length))
99
+ }
100
+ } catch { partial = true }
101
+ const entries: { key: string, target: TranscriptionCorrectionTarget, draft: TranscriptionCorrection, persisted: boolean }[] = [], observed: [string, string | null][] = []
102
+ for (const key of keys) {
103
+ const target = parseTarget(key)
104
+ if (!target || target.identity !== identity) { partial = true; continue }
105
+ const entry = this.#load(target)
106
+ let persisted = false
107
+ try {
108
+ const raw = localStorage.getItem(prefix + key)
109
+ observed.push([key, raw])
110
+ persisted = !entry.failed && !entry.corrupt && raw === entry.raw
111
+ if (raw !== entry.raw) partial = true
112
+ } catch { partial = true }
113
+ if (entry.corrupt || entry.raw === undefined) partial = true
114
+ if (entry.draft && !entry.draft.applied) entries.push({ key, target: structuredClone(target), draft: structuredClone(entry.draft), persisted })
115
+ }
116
+ return { entries, partial, guard: () => {
117
+ for (const [key, raw] of observed) {
118
+ try { if (localStorage.getItem(prefix + key) === raw) continue } catch { /* Cannot verify the same persisted input. */ }
119
+ throw new Error('client-production-drafts-changed')
120
+ }
121
+ } }
122
+ }
123
+ close(): void { this.#entries.clear() }
124
+ }