@lincyaw/workbench 0.2.0-rc.24 → 0.2.0-rc.26

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.24",
3
+ "version": "0.2.0-rc.26",
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": {
@@ -39,6 +39,7 @@
39
39
  "@floating-ui/react": "0.27.20",
40
40
  "@mantine/core": "8.3.11",
41
41
  "@mantine/hooks": "8.3.11",
42
+ "@noble/hashes": "2.4.0",
42
43
  "@radix-ui/react-dialog": "^1.3.1",
43
44
  "@radix-ui/react-dropdown-menu": "^2.2.1",
44
45
  "@radix-ui/react-popover": "^1.1.15",
@@ -54,8 +55,8 @@
54
55
  "@tiptap/pm": "3.32.0",
55
56
  "katex": "0.18.10",
56
57
  "react-resizable-panels": "4.14.5",
57
- "@lincyaw/kernel": "1.0.0-rc.25",
58
- "@lincyaw/design": "1.0.0-rc.25"
58
+ "@lincyaw/design": "1.0.0-rc.27",
59
+ "@lincyaw/kernel": "1.0.0-rc.27"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "react": "^18.3.1",
@@ -66,6 +67,6 @@
66
67
  "@types/react-dom": "18.3.7",
67
68
  "react": "^18.3.1",
68
69
  "react-dom": "^18.3.1",
69
- "@lincyaw/compiler": "1.0.0-rc.25"
70
+ "@lincyaw/compiler": "1.0.0-rc.27"
70
71
  }
71
72
  }
@@ -1,4 +1,4 @@
1
- import { authoringClientResultFits } from '@lincyaw/kernel'
1
+ import { authoringClientResultFits, randomUUID } from '@lincyaw/kernel'
2
2
  import type { AuthoringClientActionResult, AuthoringClientEvent, AuthoringClientSnapshot, CanonicalSource } from '@lincyaw/kernel'
3
3
  import type { Workbench } from './workbench.ts'
4
4
  import type { AuthoringClientChannel } from './workspace-client.ts'
@@ -13,7 +13,7 @@ type Attachment = { directory: string, identity: string, epoch: string, channel:
13
13
  export function connectAuthoringClient(workbench: Workbench): () => void {
14
14
  const open = workbench.client.openAuthoringClient
15
15
  if (!open) return () => {}
16
- const clientId = crypto.randomUUID()
16
+ const clientId = randomUUID()
17
17
  let closed = false, revision = 0, sequence = 0
18
18
  let attached: Attachment | undefined
19
19
  let lastSignature: string | undefined, lastContent: object | undefined
@@ -120,7 +120,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
120
120
  if (!value) { detach(); return }
121
121
  if (attached && (attached.directory !== state.document || attached.identity !== source.identity)) detach()
122
122
  if (!attached) {
123
- const epoch = crypto.randomUUID()
123
+ const epoch = randomUUID()
124
124
  // Callbacks run after the channel has been installed; the socket implementation is asynchronous.
125
125
  const owner = { directory: state.document, identity: source.identity, epoch } as Attachment
126
126
  owner.channel = open(state.document, { clientId, epoch, snapshot: value }, event => { void received(owner, event) }, () => {
@@ -1,9 +1,11 @@
1
1
  import type { AuthoringClientActionResult } from '@lincyaw/kernel'
2
+ import { sha256 as draftContentHash } from './sha256.ts'
3
+
4
+ export { draftContentHash }
2
5
 
3
6
  type Fragment = Extract<AuthoringClientActionResult, { jsonText: string }>
4
7
  type Fields = 'offset' | 'endOffset' | 'totalUtf16' | 'totalUtf8' | 'sha256' | 'jsonText'
5
8
  type FragmentBase = Fragment extends infer Value ? Value extends Fragment ? Omit<Value, Fields> : never : never
6
- export const draftContentHash = async (text: string): Promise<string> => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].map(value => value.toString(16).padStart(2, '0')).join('')
7
9
  const boundary = (text: string, offset: number) => !(offset > 0 && offset < text.length && /[\uD800-\uDBFF]/.test(text[offset - 1]!) && /[\uDC00-\uDFFF]/.test(text[offset]!))
8
10
 
9
11
  /** Budget the complete client receipt and WS frame, preserving exact JSON text and Unicode progress. */
@@ -1,6 +1,7 @@
1
- import { isRecord } from '@lincyaw/kernel'
1
+ import { isRecord, randomUUID } from '@lincyaw/kernel'
2
2
  import type { CanonicalSource, ClientComponentDraftReference, JsonObject } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface ComponentPropertyTarget { identity: string, memberId: string, blockId: string, stepId?: string }
@@ -32,7 +33,6 @@ const scopedPrefix = (kind: string, identity: string, memberId: string) => `${ki
32
33
  const markerOf = (target: ComponentPropertyTarget, reference: { id: string, revision: number, token: string }) => `${markerPrefix(target)}${JSON.stringify([reference.id, reference.revision, reference.token])}`
33
34
  const marker = (backup: ComponentPropertyBackup) => markerOf(backup.record.target, { id: backup.record.id, revision: backup.record.revision, token: backup.token })
34
35
  const keyOf = (record: ComponentPropertyDraft) => `${prefix(record.target)}${record.id}`
35
- const tokenOf = async (raw: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw)))].map(byte => byte.toString(16).padStart(2, '0')).join('')
36
36
 
37
37
  function valid(value: unknown, target: ComponentPropertyTarget): value is ComponentPropertyDraft {
38
38
  return isRecord(value) && value.format === 1 && typeof value.id === 'string' && value.id.length > 0
@@ -50,7 +50,7 @@ export class ComponentPropertyDrafts {
50
50
  readonly #revisions = new Map<string, number>()
51
51
  readonly #settling = new Map<string, number>()
52
52
  #agentReader?: { identity: string, memberId: string, store: DocumentDraftStore }
53
- readonly #writerOwner = crypto.randomUUID()
53
+ readonly #writerOwner = randomUUID()
54
54
  #revision = 0
55
55
  #closed = false
56
56
  readonly #leave = (event: BeforeUnloadEvent) => {
@@ -149,7 +149,7 @@ export class ComponentPropertyDrafts {
149
149
  if (this.#closed) throw new Error('component-draft-closed')
150
150
  const key = targetKey(target), previous = this.#entries.get(key)
151
151
  if (!previous && this.#entries.size >= 512) throw new Error('component-draft-limit')
152
- const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? crypto.randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
152
+ const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
153
153
  target: structuredClone(target), source: structuredClone(value.source), definitionId: value.definitionId, baseline: structuredClone(value.baseline), value: structuredClone(value.value),
154
154
  reset: Boolean(value.reset), composing: Boolean(value.composing), updatedAt: new Date().toISOString() }
155
155
  const entry: Entry = previous ?? { record, store: new DocumentDraftStore(scope(target), undefined, { owner: this.#writerOwner, family: 'component' }), failed: false, origins: [] }
@@ -213,7 +213,7 @@ export class ComponentPropertyDrafts {
213
213
  try { value = JSON.parse(raw) } catch { return false }
214
214
  if (!valid(value, target) || backup.key !== keyOf(value)) return false
215
215
  guard?.()
216
- const record: ComponentPropertyDraft = { ...structuredClone(value), id: crypto.randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
216
+ const record: ComponentPropertyDraft = { ...structuredClone(value), id: randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
217
217
  const fork = JSON.stringify(record)
218
218
  if (fork.length > MAX_CHARS) return false
219
219
  const operation = store.put(keyOf(record), fork)
@@ -1,6 +1,7 @@
1
- import { isRecord, validateDocument } from '@lincyaw/kernel'
1
+ import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
@@ -45,14 +46,10 @@ function documentDraft(value: unknown, documentId: string): DocumentDraft | unde
45
46
  return { content: checked.document, baseVersion: value.baseVersion, baseHash: value.baseHash, input: value.input,
46
47
  pendingHash: value.pendingHash, composing: value.composing, origins: value.origins }
47
48
  }
48
- async function tokenOf(raw: string): Promise<string> {
49
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
50
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
51
- }
52
49
 
53
50
  /** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
54
51
  export class DocumentDrafts {
55
- readonly #owner = crypto.randomUUID()
52
+ readonly #owner = randomUUID()
56
53
  readonly #owned = new Map<string, { identity: string, revision: number, raw: string }>()
57
54
  #store?: DocumentDraftStore
58
55
  #identity?: string
@@ -113,7 +110,7 @@ export class DocumentDrafts {
113
110
  const owned = previous && this.#owned.get(previous.id)
114
111
  if (previous && (!owned || owned.identity !== identity || previous.owner !== this.#owner || previous.revision !== owned.revision)) return
115
112
  const changed = previous && store.conflicted(keyOf(identity, previous.id))
116
- const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : crypto.randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
113
+ const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
117
114
  if (!Number.isSafeInteger(record.revision)) return
118
115
  try { const raw = JSON.stringify(record); return raw.length <= MAX_CHARS ? { record, raw } : undefined }
119
116
  catch { return }
@@ -1,5 +1,6 @@
1
1
  import { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
2
2
  import type { ForwardRefExoticComponent, ReactNode, RefAttributes } from 'react'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { filterSuggestionItems } from '@blocknote/core'
4
5
  import { BlockNoteView, components } from '@blocknote/mantine'
5
6
  import { AddCommentButton, BasicTextStyleButton, BlockNoteViewEditor, BlockTypeSelect, ComponentsContext, CreateLinkButton, FormattingToolbar, FormattingToolbarController, getDefaultReactSlashMenuItems, LinkToolbarController, NestBlockButton, RenderInPortalElement, SideMenuController, SuggestionMenuController, TableCellMergeButton, TableHandlesController, TextAlignButton, UnnestBlockButton, useBlockNoteEditor, useCreateBlockNote, useEditorState } from '@blocknote/react'
@@ -206,7 +207,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
206
207
  onItemClick: () => current.current.animationRequest?.request(editor),
207
208
  }] : []), {
208
209
  title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
209
- onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: crypto.randomUUID() }, content: t.untitledPage }], current, 'after') },
210
+ onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
210
211
  }], query)} />
211
212
  {props.children}
212
213
  </NewCommentDraftProvider></BlockNoteViewEditor>
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
- import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, validateDocumentParameters } from '@lincyaw/kernel'
2
+ import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, randomUUID, validateDocumentParameters } from '@lincyaw/kernel'
3
3
  import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject, TeachingDocument } from '@lincyaw/kernel'
4
4
  import { PmButton, PmDialog, PmNotice, PmSelect } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -17,7 +17,7 @@ function fresh(document: TeachingDocument, source: CanonicalSource, target: Comp
17
17
  const block = document.blocks[target.blockId]
18
18
  if (block?.type !== 'component') throw new Error('component-block-missing')
19
19
  const value = effectiveComponentParameters(document, block.id, target.stepId).parameters
20
- return { format: 1, id: crypto.randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
20
+ return { format: 1, id: randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
21
21
  composing: false, reset: false, updatedAt: new Date().toISOString() }
22
22
  }
23
23
  function message(error: unknown, t: ComponentPropertyMessages): string {
@@ -164,7 +164,7 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
164
164
  const submit = async (action: DocumentComponentAction, submitted?: ComponentPropertyDraft) => {
165
165
  if (!canonical || !source?.version || !clean || current.current.busy) return
166
166
  const expected = { identity, version: source.version, fingerprint: source.fingerprint! }, signature = JSON.stringify([canonical, action])
167
- if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: crypto.randomUUID() }
167
+ if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: randomUUID() }
168
168
  const captured = intent.current, controller = new AbortController(), submittedKey = key
169
169
  flight.current = controller; current.current.busy = true; setBusy(true); setError(undefined)
170
170
  try {
@@ -1,5 +1,6 @@
1
1
  import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { FocusEvent, ReactNode } from 'react'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
4
5
  import { components } from '@blocknote/mantine'
5
6
  import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
@@ -174,7 +175,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
174
175
  return value
175
176
  }, [props.editor, drafts])
176
177
  const rich = useMemo(() => ({ current: record.rich }), [record])
177
- const composerId = useRef(crypto.randomUUID())
178
+ const composerId = useRef(randomUUID())
178
179
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
179
180
  useLayoutEffect(() => {
180
181
  if (!context || !threadId) return
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useMemo, useRef } from 'react'
2
2
  import type { Transaction } from '@tiptap/pm/state'
3
3
  import { closeHistory } from '@tiptap/pm/history'
4
- import { allocateDocumentPage } from '@lincyaw/kernel'
4
+ import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
5
5
  import type { Member, TeachingDocument } from '@lincyaw/kernel'
6
6
  import type { Locale } from '../messages.ts'
7
7
  import { BlockNoteSurface } from './BlockNoteSurface.tsx'
@@ -189,7 +189,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
189
189
  const next = after ? blocks.slice(index + 1).find(block => block.type === 'presmiumPage') : undefined
190
190
  const latest = current.current.getDocument ? current.current.getDocument() : current.current.document
191
191
  if (!latest) throw new Error('page-context-changed')
192
- const creation = allocateDocumentPage(latest, () => crypto.randomUUID())
192
+ const creation = allocateDocumentPage(latest, () => randomUUID())
193
193
  projection.createdPages.set(creation.sectionId, creation)
194
194
  try {
195
195
  value.transact(transaction => {
@@ -1,5 +1,6 @@
1
1
  import { useRef, useState } from 'react'
2
2
  import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { PmIconButton } from '../components.tsx'
4
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
6
  import { isAgentChanging } from '../workbench.ts'
@@ -30,7 +31,7 @@ function NarrationField({ identity, reset, blockId, stepId, slot, narrationId, c
30
31
  // Reserving an identity does not create an entity. The first actual input commits it.
31
32
  const [reservedId] = useState(() => {
32
33
  const pending = workbench.pendingDocumentField(blockId, identity)
33
- return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ?? crypto.randomUUID()
34
+ return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ?? randomUUID()
34
35
  })
35
36
  const id = narrationId ?? reservedId
36
37
  const target = () => narrationId ?? workbench.getDocument(identity)?.steps[stepId]?.narrationIds[slot] ?? id
@@ -5,6 +5,7 @@ import { components } from '@blocknote/mantine'
5
5
  import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
6
6
  import type { ComponentProps } from '@blocknote/react'
7
7
  import type { BlockNoteEditor } from '@blocknote/core'
8
+ import { randomUUID } from '@lincyaw/kernel'
8
9
  import { TextSelection } from '@tiptap/pm/state'
9
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
10
11
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
@@ -60,7 +61,7 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
60
61
  && editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
61
62
  && (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
62
63
  if (record && !await drafts.confirm(record) || !owns()) return
63
- const nextTarget = { ...target, intentId: crypto.randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
64
+ const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
64
65
  store.beforeAction?.()
65
66
  if (!next || !owns()) return
66
67
  const positions = store.newDraftPositions(nextTarget, editor)
@@ -185,7 +186,7 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
185
186
  })
186
187
  return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
187
188
  }, [binding, drafts, props.editor])
188
- const composerId = useRef(crypto.randomUUID())
189
+ const composerId = useRef(randomUUID())
189
190
  useLayoutEffect(() => {
190
191
  if (!binding || !drafts || !context) return
191
192
  return drafts.registerComposer({ id: composerId.current, target: binding.target,
@@ -1,6 +1,7 @@
1
- import { documentCommentTargets, isRecord, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
1
+ import { documentCommentTargets, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
2
2
  import type { DocumentComment, DocumentThread, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from '../document-draft-store.ts'
4
+ import { sha256 as tokenOf } from '../sha256.ts'
4
5
  import type { DraftStoreResult } from '../document-draft-store.ts'
5
6
 
6
7
  export interface CommentDraftTarget { threadId: string, commentId?: string, threadCreatedAt: string, commentCreatedAt?: string, baseline?: string }
@@ -52,10 +53,6 @@ const committedValue = (comment: DocumentComment) => JSON.stringify({ id: commen
52
53
  export const sameCommentDraftTarget = (a: CommentComposerTarget, b: CommentComposerTarget) => isNewCommentDraft(a) || isNewCommentDraft(b)
53
54
  ? isNewCommentDraft(a) && isNewCommentDraft(b) && a.documentId === b.documentId && a.signature === b.signature && JSON.stringify(a.anchor) === JSON.stringify(b.anchor)
54
55
  : a.threadId === b.threadId && a.commentId === b.commentId && a.threadCreatedAt === b.threadCreatedAt && a.commentCreatedAt === b.commentCreatedAt
55
- async function tokenOf(raw: string): Promise<string> {
56
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
57
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
58
- }
59
56
  const point = (value: unknown): boolean => isRecord(value) && typeof value.blockId === 'string' && value.blockId.length > 0 && value.blockId.length <= 205 && Number.isSafeInteger(value.offset) && Number(value.offset) >= 0
60
57
  function targetShape(value: unknown): boolean {
61
58
  if (!isRecord(value)) return false
@@ -77,7 +74,7 @@ function valid(value: unknown, scope: string): value is CommentDraftRecord {
77
74
  /** Native composer backups use the document backup owner's strict transactions, never the source writer. */
78
75
  export class CommentDrafts {
79
76
  readonly #scope: string
80
- readonly #owner = crypto.randomUUID()
77
+ readonly #owner = randomUUID()
81
78
  #reader?: DocumentDraftStore
82
79
  readonly #listeners = new Set<() => void>()
83
80
  readonly #writing = new Map<string, Writing>()
@@ -240,7 +237,7 @@ export class CommentDrafts {
240
237
  const known = previous && this.#writing.get(previous.id)
241
238
  if (previous && (known && known.record.revision !== previous.revision || previous.owner !== this.#owner)) return
242
239
  const branched = known?.store.conflicted(keyOf(this.#scope, known.record.id))
243
- const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id : crypto.randomUUID(), owner: this.#owner,
240
+ const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id : randomUUID(), owner: this.#owner,
244
241
  revision: !branched && known ? known.record.revision + 1 : 1, updatedAt: Date.now(), target: structuredClone(target), version, content: structuredClone(content), composing }
245
242
  return this.#put(record, !branched ? known : undefined)
246
243
  }
@@ -323,7 +320,7 @@ export class CommentDrafts {
323
320
  const value: unknown = JSON.parse(raw)
324
321
  if (!valid(value, this.#scope) || value.revision !== reference.revision || !sameCommentDraftTarget(value.target, target) || !this.#validContent(value) || this.#closed) return
325
322
  operation?.signal?.throwIfAborted(); operation?.guard?.()
326
- const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: crypto.randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
323
+ const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
327
324
  const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
328
325
  if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
329
326
  try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }
@@ -4,7 +4,7 @@ import type { BlockNoteEditor } from '@blocknote/core'
4
4
  import type { CommentData, ThreadData } from '@blocknote/core/comments'
5
5
  import { AddMarkStep, RemoveMarkStep } from '@tiptap/pm/transform'
6
6
  import { Plugin } from '@tiptap/pm/state'
7
- import { applyDocumentCommentAction, hasRole, LOCAL_AUTHOR, validateDocumentCommentAnchor } from '@lincyaw/kernel'
7
+ import { applyDocumentCommentAction, hasRole, LOCAL_AUTHOR, randomUUID, validateDocumentCommentAnchor } from '@lincyaw/kernel'
8
8
  import type { DocumentComment, DocumentCommentAction, DocumentThread, Member, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
9
9
  import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
10
10
  import type { RichProjection } from './rich-text.ts'
@@ -96,7 +96,7 @@ export class DocumentThreadStore extends ThreadStore {
96
96
  if (!thread || thread.deletedAt || thread.createdAt !== target.threadCreatedAt || target.commentId && (!comment || comment.deletedAt || comment.createdAt !== target.commentCreatedAt)) return 'unavailable'
97
97
  return comment && target.baseline !== commentDraftBaseline(comment) ? 'changed' : 'current'
98
98
  }
99
- newDraftTarget(editor: NativeDocumentEditor, intentId = crypto.randomUUID()): NewCommentDraftTarget {
99
+ newDraftTarget(editor: NativeDocumentEditor, intentId = randomUUID()): NewCommentDraftTarget {
100
100
  this.beforeAction?.()
101
101
  const target: NewCommentDraftTarget = { kind: 'create', intentId, documentId: this.#document.id }
102
102
  const selection = editor.prosemirrorState.selection
@@ -162,7 +162,7 @@ export class DocumentThreadStore extends ThreadStore {
162
162
  #content(comment: NewComment): RichTextNode[] { return nativeRichTextToProduct(comment.body as DocumentEditorBlock[], this.#rich) }
163
163
  #act(action: DocumentCommentAction, nativeBody?: unknown) {
164
164
  this.beforeAction?.()
165
- const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () => crypto.randomUUID() })
165
+ const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () => randomUUID() })
166
166
  if (answer.effect.changed) {
167
167
  this.#replace(answer.threads, answer.effect.commentId && nativeBody !== undefined ? { id: answer.effect.commentId, body: nativeBody } : undefined)
168
168
  this.#notify()
@@ -1,6 +1,6 @@
1
1
  import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
2
2
  import { FileHandler } from '@tiptap/extension-file-handler'
3
- import { DOCUMENT_IMAGE_MEDIA_TYPES } from '@lincyaw/kernel'
3
+ import { DOCUMENT_IMAGE_MEDIA_TYPES, randomUUID } from '@lincyaw/kernel'
4
4
  import { isObservedWorkspaceFailure, WorkspaceServerError } from '../workspace-client.ts'
5
5
  import type { NativeDocumentEditor } from './schema.tsx'
6
6
 
@@ -34,7 +34,7 @@ export const imageFileInput = createExtension(({ editor, options }: { editor: Na
34
34
  const state = editor.prosemirrorState, info = getBlockInfoNearPos(state, position)
35
35
  const anchor = editor.getBlock(getNodeId(info.block.node, state.doc))
36
36
  if (!anchor) throw new Error('document-file-position')
37
- const blocks = accepted.map(file => ({ id: crypto.randomUUID(), type: 'image' as const, props: { name: file.name } }))
37
+ const blocks = accepted.map(file => ({ id: randomUUID(), type: 'image' as const, props: { name: file.name } }))
38
38
  const before = anchor.type !== 'presmiumPage' && position <= (info.contentStart ?? info.block.beforePos)
39
39
  const inserted = editor.insertBlocks(blocks, anchor, before ? 'before' : 'after')
40
40
  pending = inserted.map((block, index) => ({ file: accepted[index]!, id: block.id }))
@@ -6,6 +6,7 @@ import { Extension } from '@tiptap/core'
6
6
  import { Plugin } from '@tiptap/pm/state'
7
7
  import { Fragment, Slice } from '@tiptap/pm/model'
8
8
  import type { Node } from '@tiptap/pm/model'
9
+ import { randomUUID } from '@lincyaw/kernel'
9
10
  import { PmButton, PmDialog, PmInput } from '../components.tsx'
10
11
  import type { Locale } from '../messages.ts'
11
12
 
@@ -56,7 +57,7 @@ const cueIdentities = createExtension({
56
57
  const copied = (fragment: Fragment): Fragment => {
57
58
  const nodes: Node[] = []
58
59
  fragment.forEach(node => nodes.push(node.type.name === 'narrationAtom' && node.attrs.kind === 'cue'
59
- ? node.type.create({ ...node.attrs, cueId: crypto.randomUUID() }, node.content, node.marks)
60
+ ? node.type.create({ ...node.attrs, cueId: randomUUID() }, node.content, node.marks)
60
61
  : node.isLeaf ? node : node.copy(copied(node.content))))
61
62
  return Fragment.fromArray(nodes)
62
63
  }
@@ -67,7 +68,7 @@ const cueIdentities = createExtension({
67
68
  state.doc.descendants((node, position) => {
68
69
  if (node.type.name !== 'narrationAtom' || node.attrs.kind !== 'cue') return
69
70
  const id = node.attrs.cueId as string
70
- if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: crypto.randomUUID() })
71
+ if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: randomUUID() })
71
72
  else seen.add(id)
72
73
  })
73
74
  return transaction.docChanged ? transaction : null
@@ -1,4 +1,4 @@
1
- import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING } from '@lincyaw/kernel'
1
+ import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, randomUUID } from '@lincyaw/kernel'
2
2
  import type { DocumentBlock, DocumentPageIds, NarrationNode, RichTextNode, Section, TeachingDocument, TextBlock } from '@lincyaw/kernel'
3
3
  import { productInlineToNative } from './inline.ts'
4
4
  import { captureRichBaseline, createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
@@ -17,7 +17,7 @@ export interface DocumentProjection extends RichProjection {
17
17
  componentConfiguration: Map<string, string>
18
18
  }
19
19
  export type NativePageCreation = DocumentPageIds
20
- const newId = () => crypto.randomUUID()
20
+ const newId = () => randomUUID()
21
21
  export const pageId = (sectionId: string) => `page:${sectionId}`
22
22
  function plain(nodes: readonly { type: string, text?: string, children?: readonly unknown[] }[]): string {
23
23
  return nodes.map(node => node.type === 'text' ? node.text ?? '' : node.type === 'break' ? '\n' : node.children ? plain(node.children as Parameters<typeof plain>[0]) : '').join('')
@@ -1,4 +1,5 @@
1
1
  import type { InlineNode, JsonValue, ListItemNode, RichTextNode, TableNode } from '@lincyaw/kernel'
2
+ import { randomUUID } from '@lincyaw/kernel'
2
3
  import type { TableCellProps } from '@blocknote/core'
3
4
  import { nativeInlineToProduct, nativeTextStyleToProduct, productInlineToNative, productTextStyleToNative } from './inline.ts'
4
5
  import type { InlineProjectionContext, NativeInline } from './inline.ts'
@@ -27,12 +28,12 @@ export interface RichProjection extends InlineProjectionContext {
27
28
  tables: Map<string, { id: string, cells: string[] }[]>
28
29
  }
29
30
  export function createRichProjection(): RichProjection {
30
- return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => crypto.randomUUID() }
31
+ return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => randomUUID() }
31
32
  }
32
33
  export function captureRichBaseline(blocks: readonly DocumentEditorBlock[], context: RichProjection): void {
33
34
  for (const block of blocks) { context.baseline.set(block.id, JSON.stringify(block)); captureRichBaseline(block.children, context) }
34
35
  }
35
- const id = () => crypto.randomUUID()
36
+ const id = () => randomUUID()
36
37
  const atom = (node: RichTextNode): DocumentEditorInput => ({ id: node.id, type: 'presmiumAtom', props: { entityId: node.id, kind: `rich:${node.type}`, label: node.type === 'extension' ? fallbackText(node.fallback) : fallbackText(node) } })
37
38
 
38
39
  /** The projection records structural identities; the saved document owns all content. */
@@ -1,6 +1,7 @@
1
1
  import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
2
2
  import { Extension } from '@tiptap/core'
3
3
  import { Plugin } from '@tiptap/pm/state'
4
+ import { randomUUID } from '@lincyaw/kernel'
4
5
  import type { NativeDocumentEditor } from './schema.tsx'
5
6
  import type { RichProjection } from './rich-text.ts'
6
7
 
@@ -24,7 +25,7 @@ export const tableIdentityExtension = createExtension({
24
25
  after.doc.descendants((node, position) => {
25
26
  if (!TYPES.includes(node.type.name)) return
26
27
  let id = node.attrs[ATTR] as string | null
27
- if (!id || used.has(id)) { id = crypto.randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
+ if (!id || used.has(id)) { id = randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
28
29
  used.add(id)
29
30
  })
30
31
  if (transaction.steps.length) return transaction.setMeta('addToHistory', false)
@@ -1,8 +1,9 @@
1
- import { hasRole, validateDocument } from '@lincyaw/kernel'
1
+ import { hasRole, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
  import { DocumentDrafts } from './document-drafts.ts'
6
+ import { sha256 } from './sha256.ts'
6
7
  import type { DocumentDraftChoice, DocumentDraftCommit, DocumentDraftReference, StoredDocumentDraft } from './document-drafts.ts'
7
8
 
8
9
  export interface DocumentSessionState {
@@ -88,10 +89,7 @@ function keepsEditorContent(before: TeachingDocument, after: TeachingDocument):
88
89
  }
89
90
 
90
91
  async function digest(value: TeachingDocument): Promise<string> {
91
- const text = serialize(value)
92
- if (!globalThis.crypto?.subtle) return `json:${text}`
93
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
94
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
92
+ return sha256(serialize(value))
95
93
  }
96
94
 
97
95
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
@@ -288,7 +286,7 @@ export class DocumentSession {
288
286
  else if (slot.timer !== undefined) return
289
287
  if (this.#readOnly(slot) || slot.flight || slot.assetFlight || !slot.state.dirty || slot.state.composing || slot.state.restored || slot.state.error || !slot.state.content || !slot.state.version) return
290
288
  slot.read++
291
- const flight = { id: crypto.randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
289
+ const flight = { id: randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
292
290
  slot.flight = flight
293
291
  slot.state = { ...slot.state, saving: true }; this.#emit(slot)
294
292
  try {
@@ -406,7 +404,7 @@ export class DocumentSession {
406
404
  const before = structuredClone(slot.state.content), input = slot.input, version = slot.state.version
407
405
  let request = this.#imageImports.get(file)
408
406
  if (!request || request.identity !== identity || request.version !== version) {
409
- request = { identity, version, id: crypto.randomUUID() }
407
+ request = { identity, version, id: randomUUID() }
410
408
  this.#imageImports.set(file, request)
411
409
  }
412
410
  const read = ++slot.read
@@ -609,7 +607,12 @@ export class DocumentSession {
609
607
  const answer = await this.#client.readDocument(slot.state.directory)
610
608
  if (!current()) return
611
609
  if (answer.document !== slot.state.directory || answer.content.id !== documentId) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
612
- const [localHash, remoteHash] = await Promise.all([digest(candidate.content), digest(answer.content)])
610
+ // Older LAN HTTP drafts stored canonical JSON in place of a SHA-256 fingerprint.
611
+ const [localHash, remoteHash, candidateBaseHash, pendingHash] = await Promise.all([
612
+ digest(candidate.content), digest(answer.content),
613
+ candidate.baseHash.startsWith('json:') ? sha256(candidate.baseHash.slice(5)) : candidate.baseHash,
614
+ candidate.pendingHash?.startsWith('json:') ? sha256(candidate.pendingHash.slice(5)) : candidate.pendingHash,
615
+ ])
613
616
  if (!current()) return
614
617
  const origins = [...new Map([...(candidate.origins ?? []), { id: candidate.id, revision: candidate.revision, token: candidate.token }].map(value => [JSON.stringify([value.id, value.revision, value.token]), value])).values()]
615
618
  if (localHash === remoteHash && !candidate.composing) {
@@ -618,16 +621,16 @@ export class DocumentSession {
618
621
  slot.persistFailure = !settled
619
622
  return
620
623
  }
621
- const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidate.baseHash && remoteHash !== candidate.pendingHash
622
- const version = remoteHash === candidate.pendingHash || remoteHash === candidate.baseHash ? answer.version : candidate.baseVersion
623
- const baseHash = remoteHash === candidate.pendingHash ? remoteHash : candidate.baseHash
624
+ const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidateBaseHash && remoteHash !== pendingHash
625
+ const version = remoteHash === pendingHash || remoteHash === candidateBaseHash ? answer.version : candidate.baseVersion
626
+ const baseHash = remoteHash === pendingHash ? remoteHash : candidateBaseHash
624
627
  const record = await slot.drafts.fork(identity, { content: candidate.content, baseVersion: version, baseHash, input: input + 1,
625
- pendingHash: candidate.pendingHash, composing: Boolean(candidate.composing), origins })
628
+ pendingHash, composing: Boolean(candidate.composing), origins })
626
629
  if (!current()) { if (record) slot.drafts.archive(record); return }
627
630
  if (!record) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true }; return }
628
631
  clearTimeout(slot.timer); slot.timer = undefined
629
632
  if (slot.draft) slot.drafts.archive(slot.draft)
630
- slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = candidate.pendingHash; slot.draft = record; slot.draftOrigins = origins
633
+ slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = pendingHash; slot.draft = record; slot.draftOrigins = origins
631
634
  slot.backup = undefined; slot.persistFailure = false
632
635
  adopted = true
633
636
  slot.compositions.clear()
package/src/history.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { errorMessage } from '@lincyaw/kernel'
1
+ import { errorMessage, randomUUID } from '@lincyaw/kernel'
2
2
  import type { RevertResult, ReviewChange, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
3
3
  import type { WorkbenchStore } from './workbench.ts'
4
4
  import { WorkspaceServerError } from './workspace-client.ts'
@@ -129,7 +129,7 @@ export class DocumentHistory {
129
129
  #change(which: 'undo' | 'redo' | 'revertRevision', expect: string | undefined): Promise<boolean> {
130
130
  const binding = this.#store.state.history?.historyBinding
131
131
  if (!binding || !expect) return Promise.resolve(false)
132
- const request = { id: crypto.randomUUID(), ...binding, expect }
132
+ const request = { id: randomUUID(), ...binding, expect }
133
133
  return this.#run(dir => this.#client[which](dir, request))
134
134
  }
135
135
 
@@ -1,5 +1,5 @@
1
1
  import { useEffect, useRef, useState } from 'react'
2
- import { CAPTION_TIMING_MAX_SEGMENTS, captionSourceFingerprint, captionTimingProblem, stepCaptionText } from '@lincyaw/kernel'
2
+ import { CAPTION_TIMING_MAX_SEGMENTS, captionSourceFingerprint, captionTimingProblem, randomUUID, stepCaptionText } from '@lincyaw/kernel'
3
3
  import type { CaptionTiming, CaptionTimingSource, DocumentCaptionTimingAction, ProductionPlan } from '@lincyaw/kernel'
4
4
  import { PmButton, PmCard, PmDialog, PmInput, PmNotice } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -23,7 +23,7 @@ function lineRows(text: string): Row[] {
23
23
  else if (ranges.length && !text.slice(ranges.at(-1)!.from, ranges.at(-1)!.to).trim()) ranges[ranges.length - 1]!.to = to
24
24
  else ranges.push({ from, to })
25
25
  }
26
- return ranges.map(range => ({ ...range, id: crypto.randomUUID(), start: '', end: '' }))
26
+ return ranges.map(range => ({ ...range, id: randomUUID(), start: '', end: '' }))
27
27
  }
28
28
  function valueOf(draft: Draft): CaptionTiming | undefined {
29
29
  if (!draft.basis.available || !draft.basis.playbackFingerprint || draft.basis.durationMs === undefined) return
@@ -72,7 +72,7 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
72
72
  const action: DocumentCaptionTimingAction = automatic ? { type: 'caption.timing.reset', stepId } : { type: 'caption.timing.set', stepId, value: value! }
73
73
  request.current = controller; setBusy(true); setFailure(undefined)
74
74
  try {
75
- const answer = await workbench.applyDocumentCaptionTiming(action, crypto.randomUUID(), expected, controller.signal)
75
+ const answer = await workbench.applyDocumentCaptionTiming(action, randomUUID(), expected, controller.signal)
76
76
  needsRefresh.current = true
77
77
  if (!alive.current || workbench.getState().authoring?.identity !== identity) return
78
78
  const ownsInput = drafts.current.get(target) === sent
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useRef, useState } from 'react'
2
2
  import type { DocumentChangeAnswer, MediaClip, ProductionAssetInspection, ProductionBinding, TeachingDocument } from '@lincyaw/kernel'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { MediaClipEditor } from '../MediaClipEditor.tsx'
4
5
  import type { MediaClipDraft } from '../MediaClipEditor.tsx'
5
6
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -18,7 +19,7 @@ interface Props {
18
19
  disabled: boolean
19
20
  onChanged(): void
20
21
  }
21
- const newDraft = (version: string, stepId: string): MediaClipDraft => ({ version, clip: { id: `clip_${crypto.randomUUID().replaceAll('-', '')}`, assetId: '', sourceRange: { startMs: 0, endMs: 0 }, attachment: { stepId, offsetMs: 0 }, volume: 1, muted: false } })
22
+ const newDraft = (version: string, stepId: string): MediaClipDraft => ({ version, clip: { id: `clip_${randomUUID().replaceAll('-', '')}`, assetId: '', sourceRange: { startMs: 0, endMs: 0 }, attachment: { stepId, offsetMs: 0 }, volume: 1, muted: false } })
22
23
  const fromClip = (version: string, clip: MediaClip): MediaClipDraft => ({ version, clip: structuredClone(clip), baseClip: structuredClone(clip) })
23
24
  const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
24
25
  const draftKey = (clipId?: string) => clipId === undefined ? 'new' : `clip:${clipId}`
@@ -1,5 +1,5 @@
1
1
  import { useEffect, useId, useRef, useState } from 'react'
2
- import { recordingSourceRange } from '@lincyaw/kernel'
2
+ import { randomUUID, recordingSourceRange } from '@lincyaw/kernel'
3
3
  import type { DocumentRecordingAdoption, ProductionAssetInspection, TimeRange, VoiceSource } from '@lincyaw/kernel'
4
4
  import { PmButton, PmInput, PmNotice } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -81,7 +81,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
81
81
  const controller = new AbortController(), proposed = { startMs: start!, endMs: end! }
82
82
  const previous = sent.current?.request
83
83
  const change: DocumentRecordingAdoption = previous && previous.source.version === source.version && previous.stepId === stepId && previous.assetId === voice.assetId && previous.sha256 === inspected.sha256 && same(previous.sourceRange, proposed)
84
- ? previous : { id: crypto.randomUUID(), source: { documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, stepId, assetId: voice.assetId, sha256: inspected.sha256, sourceRange: proposed }
84
+ ? previous : { id: randomUUID(), source: { documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, stepId, assetId: voice.assetId, sha256: inspected.sha256, sourceRange: proposed }
85
85
  const stored = drafts.current.get(key) ?? draft
86
86
  drafts.current.set(key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
87
87
  setBusy(true); setFailure(undefined)
@@ -1,5 +1,6 @@
1
1
  import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { DocumentTranscriptionRequest, TeachingDocument, TranscriptionCapabilities, TranscriptionListAnswer, TranscriptionRevision, TranscriptionTask } from '@lincyaw/kernel'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { PmBadge, PmButton, PmCard, PmDialog, PmField, PmIconButton, PmNotice, PmSelect } from '../components.tsx'
4
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
6
  import { documentTranscriptionSession } from '../transcription-session.ts'
@@ -94,7 +95,7 @@ export function ProductionTranscription({ identity, directory, document, section
94
95
  try {
95
96
  const expected = { identity, version: now.version }, audio = await workbench.inspectDocumentAudio(assetId, expected, controller.signal)
96
97
  if (!current() || controller.signal.aborted) return
97
- const request: DocumentTranscriptionRequest = { intent: `transcription_${crypto.randomUUID()}`, source: { documentId: now.content.id, version: now.version, fingerprint: now.fingerprint }, assetId, audioSha256: audio.inspection.sha256, engine, lang: now.content.metadata.lang, confirmed: true }
98
+ const request: DocumentTranscriptionRequest = { intent: `transcription_${randomUUID()}`, source: { documentId: now.content.id, version: now.version, fingerprint: now.fingerprint }, assetId, audioSha256: audio.inspection.sha256, engine, lang: now.content.metadata.lang, confirmed: true }
98
99
  await session.start(request, () => workbench.startDocumentTranscription(request, expected))
99
100
  } catch (error) { if (current() && !controller.signal.aborted) setFailure(transcriptionFailure(error, locale)) }
100
101
  finally { if (inspectionRequest.current === controller) { inspectionRequest.current = undefined; if (current()) setInspecting(false) } }
@@ -1,5 +1,5 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react'
2
- import { prepareTranscriptionAdoption } from '@lincyaw/kernel'
2
+ import { prepareTranscriptionAdoption, randomUUID } from '@lincyaw/kernel'
3
3
  import type { CanonicalSource, NarrationNode, TeachingDocument, TranscriptionRevision, TranscriptionAdoptionDraft, TranscriptionAdoptionPart, TranscriptionAdoptionPlan } from '@lincyaw/kernel'
4
4
  import { PmBadge, PmButton, PmDialog, PmField, PmNotice, PmSelect, PmTextarea } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -14,7 +14,7 @@ const ordered = (value: unknown): unknown => Array.isArray(value) ? value.map(or
14
14
  const same = (a: unknown, b: unknown) => JSON.stringify(ordered(a)) === JSON.stringify(ordered(b))
15
15
  const displayed = (nodes: readonly NarrationNode[]) => nodes.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
16
16
  function restore(key: string): { draft: Draft, failed: boolean } {
17
- const fallback = () => ({ draft: { id: crypto.randomUUID(), revision: 0, discarded: [], shared: 'fork' as const }, failed: false })
17
+ const fallback = () => ({ draft: { id: randomUUID(), revision: 0, discarded: [], shared: 'fork' as const }, failed: false })
18
18
  try {
19
19
  const raw = localStorage.getItem(key)
20
20
  if (!raw) return fallback()
@@ -83,7 +83,7 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
83
83
  const now = workbench.getState().authoring
84
84
  if (disabled || reviewing || applying || composing || !sourceReady || !now?.version || !now.fingerprint || parsed.invalid) return
85
85
  pause()
86
- if (latest.current.baseVersion && latest.current.baseVersion !== now.version) change({ id: crypto.randomUUID(), baseVersion: now.version })
86
+ if (latest.current.baseVersion && latest.current.baseVersion !== now.version) change({ id: randomUUID(), baseVersion: now.version })
87
87
  else if (!latest.current.baseVersion) change({ baseVersion: now.version })
88
88
  const value = latest.current, request = ++generation.current, normalized = content()
89
89
  const retainsOriginal = references.length > 1 && value.shared === 'fork'
@@ -104,7 +104,7 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
104
104
  try {
105
105
  const answer = await workbench.adoptDocumentTranscription({ planId, source: sent.source, candidate: sent.candidate, draftRevision: sent.draftRevision }, { identity, version: sent.source.version })
106
106
  if (latest.current.id === sent.changeId && latest.current.revision === sent.draftRevision) {
107
- const next: Draft = { ...latest.current, id: crypto.randomUUID(), revision: 0, discarded: [], baseVersion: answer.version, applied: true }
107
+ const next: Draft = { ...latest.current, id: randomUUID(), revision: 0, discarded: [], baseVersion: answer.version, applied: true }
108
108
  latest.current = next; setDraft(next)
109
109
  try { localStorage.setItem(key, JSON.stringify(next)); setStorageFailed(false) } catch { setStorageFailed(true) }
110
110
  }
package/src/sha256.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { sha256 as hash } from '@noble/hashes/sha2.js'
2
+ import { bytesToHex } from '@noble/hashes/utils.js'
3
+
4
+ /** The same SHA-256 fingerprint on HTTPS, localhost and LAN HTTP. */
5
+ export async function sha256(value: string | ArrayBuffer): Promise<string> {
6
+ const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : new Uint8Array(value)
7
+ const subtle = globalThis.crypto?.subtle
8
+ return bytesToHex(subtle ? new Uint8Array(await subtle.digest('SHA-256', bytes)) : hash(bytes))
9
+ }
package/src/workbench.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { applyDocumentCaptionTiming } from '@lincyaw/kernel'
1
+ import { applyDocumentCaptionTiming, randomUUID } from '@lincyaw/kernel'
2
2
  import type { DocumentCaptionTimingAction } from '@lincyaw/kernel'
3
3
  import { reconcileCaptionTiming } from './caption-timing.ts'
4
4
  import type { ProjectOperation, ProjectPlan } from '@lincyaw/kernel'
@@ -15,6 +15,7 @@ import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
15
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
16
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
17
  import { DocumentSession } from './document-session.ts'
18
+ import { sha256 } from './sha256.ts'
18
19
  import { reconcileRecordingAdoption } from './recording-adoption.ts'
19
20
  import { disposeTranscriptionSessions } from './transcription-session.ts'
20
21
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
@@ -560,7 +561,7 @@ export class Workbench {
560
561
  }
561
562
 
562
563
  planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
563
- return this.client.planProjectChange({ id: crypto.randomUUID(), operation })
564
+ return this.client.planProjectChange({ id: randomUUID(), operation })
564
565
  }
565
566
 
566
567
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
@@ -1402,7 +1403,7 @@ export class Workbench {
1402
1403
  let request: { identity: string, version: string, id: string } | undefined
1403
1404
  const answer = await this.#writeDocumentMedia(expected, async directory => {
1404
1405
  const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
1405
- request = first ? { identity: expected.identity, version: expected.version, id: crypto.randomUUID() } : existing!
1406
+ request = first ? { identity: expected.identity, version: expected.version, id: randomUUID() } : existing!
1406
1407
  this.#audioImports.set(file, request)
1407
1408
  try { return await this.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
1408
1409
  catch (error) {
@@ -1420,7 +1421,7 @@ export class Workbench {
1420
1421
  if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
1421
1422
  let pending = this.#audioFingerprints.get(file)
1422
1423
  if (!pending) {
1423
- pending = file.arrayBuffer().then(bytes => crypto.subtle.digest('SHA-256', bytes)).then(bytes => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join(''))
1424
+ pending = file.arrayBuffer().then(sha256)
1424
1425
  this.#audioFingerprints.set(file, pending)
1425
1426
  }
1426
1427
  const hash = await pending
@@ -1471,13 +1472,13 @@ export class Workbench {
1471
1472
  async applyDocumentMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1472
1473
  this.#mediaSource(expected)
1473
1474
  if (!this.#state.productionPlan || !sameProductionBinding(this.#state.productionPlan.binding, expected.binding) || !this.#productionSourceCurrent(expected.binding)) throw new Error('production-source-changed')
1474
- const id = crypto.randomUUID(), value = structuredClone(clip)
1475
+ const id = randomUUID(), value = structuredClone(clip)
1475
1476
  const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
1476
1477
  if (answer.changeId !== id) throw new Error('production-source-changed')
1477
1478
  return answer
1478
1479
  }
1479
1480
  async removeDocumentMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1480
- const id = crypto.randomUUID()
1481
+ const id = randomUUID()
1481
1482
  const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
1482
1483
  if (answer.changeId !== id) throw new Error('production-source-changed')
1483
1484
  return answer
@@ -1627,7 +1628,7 @@ export class Workbench {
1627
1628
  const existing = target !== undefined && Object.hasOwn(document.narrations, target) ? document.narrations[target] : undefined
1628
1629
  if (existing && !step.narrationIds.includes(existing.id)) throw new Error('document-narration-target')
1629
1630
  if (!existing && !meaningful) return undefined
1630
- const id = target ?? crypto.randomUUID()
1631
+ const id = target ?? randomUUID()
1631
1632
  if (!id || id.length > 200 || /[\u0000-\u001f]/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id)) throw new Error('document-narration-target')
1632
1633
  if (!existing && (document.id === id || [document.sections, document.blocks, document.steps, document.assets, document.definitions].some(map => Object.hasOwn(map, id)))) throw new Error('document-narration-target')
1633
1634
  if (existing && JSON.stringify(existing.content) === JSON.stringify(content)) return id
@@ -1844,7 +1845,7 @@ export class Workbench {
1844
1845
  if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity) throw new Error('page-context-changed')
1845
1846
  const page = document.sections[section]
1846
1847
  if (!page) throw new Error('page-boundary')
1847
- const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => crypto.randomUUID())
1848
+ const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => randomUUID())
1848
1849
  copied = copy.section
1849
1850
  Object.assign(document, copy.document)
1850
1851
  if (generation === this.#documentSelectionGeneration) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
@@ -1880,8 +1881,8 @@ export class Workbench {
1880
1881
  if (this.#state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
1881
1882
  const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
1882
1883
  if (!current.allowed) throw new Error(current.reason)
1883
- Object.assign(document, removeDocumentPage(document, plan.section, () => crypto.randomUUID()))
1884
- this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: crypto.randomUUID() } })
1884
+ Object.assign(document, removeDocumentPage(document, plan.section, () => randomUUID()))
1885
+ this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: randomUUID() } })
1885
1886
  })
1886
1887
  }
1887
1888
  createPage(after = this.#state.position?.section): boolean {
@@ -1893,7 +1894,7 @@ export class Workbench {
1893
1894
  this.#set({ pageEditFailure: undefined })
1894
1895
  const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
1895
1896
  this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
1896
- this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: crypto.randomUUID() } })
1897
+ this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: randomUUID() } })
1897
1898
  // The default title is selected: the author's first words name the page, and Enter goes on to its body.
1898
1899
  this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
1899
1900
  return true
@@ -2030,7 +2031,7 @@ export class Workbench {
2030
2031
  /** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
2031
2032
  goToSection(section: string): void {
2032
2033
  if (this.#state.webView === 'document' && this.#state.authoring?.content?.sections[section]) {
2033
- this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: crypto.randomUUID() } }); return
2034
+ this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
2034
2035
  }
2035
2036
  this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
2036
2037
  }
@@ -2044,7 +2045,7 @@ export class Workbench {
2044
2045
  const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
2045
2046
  const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
2046
2047
  this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
2047
- documentNavigation: { section: sectionId, block: blockId, request: crypto.randomUUID() } })
2048
+ documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
2048
2049
  }
2049
2050
 
2050
2051
  observeDocumentSection(section: string): void {
@@ -13,6 +13,7 @@ import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, Docu
13
13
  import type { DocumentImageImport, DocumentImageImportAnswer } from '@lincyaw/kernel'
14
14
  import type { ProductionAssetAnswer, ProductionAssetQuery, ProductionMediaQuery, ProductionPlan, ProductionPlanQuery } from '@lincyaw/kernel'
15
15
  import type { DocumentTranscriptionRequest, TranscriptionCapabilities, TranscriptionTask, TranscriptionListAnswer, TranscriptionRevision, TranscriptionCancellation, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionAdoptionApply, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
16
+ import { randomUUID } from '@lincyaw/kernel'
16
17
 
17
18
  /** A change of the host's pending approvals that this author may answer. */
18
19
  export type ApprovalEvent =
@@ -341,7 +342,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
341
342
  if (operation.op === 'delete' && (!planned || JSON.stringify(planned.operation) !== JSON.stringify(operation))) throw new Error('project-deletion-plan-required')
342
343
  const key = JSON.stringify(operation)
343
344
  let intent = projectIntents.get(key)
344
- if (!intent) { intent = { id: crypto.randomUUID() }; projectIntents.set(key, intent) }
345
+ if (!intent) { intent = { id: randomUUID() }; projectIntents.set(key, intent) }
345
346
  while (projectIntents.size > 64) projectIntents.delete(projectIntents.keys().next().value!)
346
347
  try {
347
348
  intent.plan ??= planned