@lincyaw/kernel 1.0.0-rc.8 → 1.0.0-rc.80

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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/package.json +4 -2
  3. package/src/authoring.ts +2 -0
  4. package/src/contracts/authoring-actions.ts +3 -3
  5. package/src/contracts/authoring-clients.ts +94 -6
  6. package/src/contracts/authoring-windows.ts +47 -0
  7. package/src/contracts/authoring.ts +1 -1
  8. package/src/contracts/capture.ts +148 -0
  9. package/src/contracts/document-audio.ts +8 -6
  10. package/src/contracts/document-image.ts +7 -5
  11. package/src/contracts/document-voice.ts +42 -2
  12. package/src/contracts/document.ts +16 -1
  13. package/src/contracts/media-uploads.ts +28 -0
  14. package/src/contracts/plugin.ts +1 -3
  15. package/src/contracts/preview.ts +3 -3
  16. package/src/contracts/projects.ts +4 -1
  17. package/src/contracts/speech-settings.ts +13 -0
  18. package/src/contracts/speech.ts +16 -0
  19. package/src/contracts/voiceover-execution.ts +25 -1
  20. package/src/contracts/workspace-changes.ts +27 -0
  21. package/src/contracts/workspace-review.ts +39 -0
  22. package/src/contracts/workspace-source.ts +38 -0
  23. package/src/contracts/workspace.ts +2 -0
  24. package/src/contracts.ts +6 -0
  25. package/src/document-authoring-actions.ts +23 -4
  26. package/src/document-caption-scale.ts +17 -0
  27. package/src/document-comments.ts +30 -37
  28. package/src/document-components.ts +4 -12
  29. package/src/document-narrations.ts +57 -0
  30. package/src/document-operations.ts +32 -2
  31. package/src/document-pages.ts +8 -1
  32. package/src/document-places.ts +92 -0
  33. package/src/document-schema.ts +3 -3
  34. package/src/document.ts +13 -1
  35. package/src/embed.ts +26 -0
  36. package/src/escape-html.ts +4 -0
  37. package/src/html.ts +1 -4
  38. package/src/index.ts +15 -6
  39. package/src/ir.ts +23 -48
  40. package/src/lower-myst.ts +3 -12
  41. package/src/myst-marks.ts +15 -0
  42. package/src/node/authoring-actions.ts +3 -1
  43. package/src/node/authoring-windows.ts +11 -0
  44. package/src/node/document-voice.ts +6 -2
  45. package/src/node/fonts.ts +6 -3
  46. package/src/node/index.ts +9 -3
  47. package/src/node/operator-speech.ts +4 -0
  48. package/src/node/packages.ts +25 -0
  49. package/src/node/service-state.ts +52 -0
  50. package/src/node/workspace-changes.ts +7 -0
  51. package/src/node/workspace-review.ts +9 -0
  52. package/src/node/workspace-source.ts +10 -0
  53. package/src/preview-events.ts +6 -4
  54. package/src/preview-frame-connect.ts +1105 -0
  55. package/src/preview-frame.ts +30 -1120
  56. package/src/random-uuid.ts +8 -0
  57. package/src/stale-module.ts +15 -0
@@ -1,6 +1,10 @@
1
1
  import { hasRole } from './access.ts'
2
2
  import type { DocumentCommentAction, DocumentCommentContext, DocumentCommentEffect } from './contracts/document-comments.ts'
3
- import type { DocumentComment, DocumentThread, InlineNode, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
3
+ import { isDocumentPlaceAnchor, isDocumentTextAnchor } from './contracts/document.ts'
4
+ import { documentBlockSection, documentCommentTargets } from './document-places.ts'
5
+ import type { DocumentComment, DocumentThread, DocumentThreadAnchor, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
6
+
7
+ export { documentCommentTargets, isDocumentTextLink } from './document-places.ts'
4
8
 
5
9
  export class DocumentCommentError extends Error {
6
10
  readonly status: number
@@ -8,45 +12,19 @@ export class DocumentCommentError extends Error {
8
12
  }
9
13
  function fail(status: number, code: string): never { throw new DocumentCommentError(status, code) }
10
14
 
11
- /** Canonical anchor v1 expands only nonempty styled-text links; other inline values are atoms. */
12
- export function isDocumentTextLink(node: InlineNode): node is Extract<InlineNode, { type: 'link' }> & { children: Extract<InlineNode, { type: 'text' | 'break' }>[] } {
13
- return node.type === 'link' && node.children.length > 0 && node.children.every(child => child.type === 'text' || child.type === 'break')
14
- }
15
- function inlineText(nodes: readonly InlineNode[]): string {
16
- return nodes.map(node => node.type === 'text' ? node.text : node.type === 'break' ? '\n' : isDocumentTextLink(node) ? inlineText(node.children) : '\uFFFC').join('')
17
- }
18
-
19
- /** Only addressable canonical text identities, in native document order; opaque data is never traversed. */
20
- export function documentCommentTargets(document: TeachingDocument): Map<string, { order: number, text: string }> {
21
- const targets = new Map<string, { order: number, text: string }>()
22
- const add = (id: string, text: string) => { targets.set(id, { order: targets.size, text }) }
23
- const rich = (node: RichTextNode): void => {
24
- if (node.type === 'paragraph' || node.type === 'heading') add(node.id, inlineText(node.children))
25
- else if (node.type === 'code') add(node.id, node.value)
26
- else if (node.type === 'list') for (const item of node.children) {
27
- const [first, ...rest] = item.children
28
- add(item.id, first?.type === 'paragraph' ? inlineText(first.children) : '')
29
- ;(first?.type === 'paragraph' ? rest : item.children).forEach(rich)
30
- }
31
- else if (node.type === 'blockquote') {
32
- const [first, ...rest] = node.children
33
- if (first?.type === 'paragraph') { add(node.id, inlineText(first.children)); rest.forEach(rich) }
34
- else node.children.forEach(rich)
35
- } else if (node.type === 'table') for (const row of node.children) for (const cell of row.children) add(cell.id, inlineText(cell.children))
36
- }
37
- const block = (id: string): void => {
38
- const value = document.blocks[id]
39
- if (value?.type === 'text') value.content.forEach(rich)
40
- else if (value?.type === 'code' && value.value !== undefined) add(id, value.value)
41
- else if (value?.type === 'container' || value?.type === 'component') value.children?.forEach(block)
42
- }
43
- for (const id of document.sectionOrder) { const page = document.sections[id]!; add(`page:${id}`, page.title); page.children.forEach(block) }
44
- return targets
45
- }
46
-
47
15
  /** No ordinal, offset clamping, surrogate splitting or guessed fallback identity. */
48
16
  export function validateDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThread['anchor']): void {
49
17
  if (!anchor) return
18
+ if (isDocumentPlaceAnchor(anchor)) {
19
+ if (!Object.hasOwn(document.blocks, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
20
+ if (anchor.stepId !== undefined) {
21
+ const step = Object.hasOwn(document.steps, anchor.stepId) ? document.steps[anchor.stepId] : undefined
22
+ const section = step ? document.sections[step.sectionId] : undefined
23
+ if (!step || !section || !section.stepOrder.includes(anchor.stepId) || step.sectionId !== documentBlockSection(document, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
24
+ }
25
+ return
26
+ }
27
+ if (!isDocumentTextAnchor(anchor)) fail(422, 'comment-anchor-target-unavailable')
50
28
  const targets = documentCommentTargets(document), a = targets.get(anchor.from.blockId), b = targets.get(anchor.to.blockId)
51
29
  if (!a || !b) fail(422, 'comment-anchor-target-unavailable')
52
30
  for (const [point, target] of [[anchor.from, a], [anchor.to, b]] as const) {
@@ -57,6 +35,21 @@ export function validateDocumentCommentAnchor(document: TeachingDocument, anchor
57
35
  if (a.order > b.order || a.order === b.order && anchor.from.offset >= anchor.to.offset) fail(422, 'comment-anchor-range-invalid')
58
36
  }
59
37
 
38
+ /**
39
+ * The strongest still-valid anchor. A place whose step no longer exists keeps the block; a missing block or an
40
+ * unmappable text range leaves the discussion explicitly unanchored rather than silently pointing elsewhere.
41
+ */
42
+ export function degradeDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThreadAnchor | undefined): DocumentThreadAnchor | undefined {
43
+ if (!anchor) return undefined
44
+ try { validateDocumentCommentAnchor(document, anchor); return anchor }
45
+ catch (error) { if (!(error instanceof DocumentCommentError) || error.status !== 422) throw error }
46
+ if (isDocumentPlaceAnchor(anchor) && anchor.stepId !== undefined && Object.hasOwn(document.blocks, anchor.blockId)) {
47
+ const place: DocumentThreadAnchor = { blockId: anchor.blockId }
48
+ try { validateDocumentCommentAnchor(document, place); return place } catch { /* The block itself is not addressable. */ }
49
+ }
50
+ return undefined
51
+ }
52
+
60
53
  /** Shared native/editor permissions: editors may delete any discussion, but edit their own comment; a document owner may manage earlier authors. */
61
54
  export function applyDocumentCommentAction(source: NonNullable<TeachingDocument['comments']>, action: DocumentCommentAction, context: DocumentCommentContext): { threads: NonNullable<TeachingDocument['comments']>, effect: DocumentCommentEffect } {
62
55
  const member = context.member
@@ -1,6 +1,7 @@
1
1
  import jsonPatch from 'fast-json-patch'
2
2
  import type { Operation } from 'fast-json-patch'
3
3
  import { validateDocument } from './document.ts'
4
+ import { documentBlockSection } from './document-places.ts'
4
5
  import { documentParameterAccess } from './parameters.ts'
5
6
  import { DOCUMENT_PARAMETER_MAX_CHANGES, DOCUMENT_PARAMETER_MAX_PATH_DEPTH } from './contracts/authoring-actions.ts'
6
7
  import type { DocumentComponentAction, DocumentComponentEffect, DocumentParameterChange } from './contracts/authoring-actions.ts'
@@ -26,18 +27,9 @@ function component(document: TeachingDocument, id: string): ComponentBlock {
26
27
  }
27
28
  export function documentComponentSection(document: TeachingDocument, blockId: string): string {
28
29
  component(document, blockId)
29
- for (const sectionId of document.sectionOrder) {
30
- const pending = [...document.sections[sectionId]!.children], seen = new Set<string>()
31
- while (pending.length) {
32
- const id = pending.pop()!
33
- if (id === blockId) return sectionId
34
- if (seen.has(id)) continue
35
- seen.add(id)
36
- const block = document.blocks[id]
37
- if (block?.type === 'container' || block?.type === 'component') pending.push(...block.children ?? [])
38
- }
39
- }
40
- return fail(422, 'component-block-owner-missing', { blockId })
30
+ const section = documentBlockSection(document, blockId)
31
+ if (!section) return fail(422, 'component-block-owner-missing', { blockId })
32
+ return section
41
33
  }
42
34
  function stepOf(document: TeachingDocument, stepId: string, sectionId: string) {
43
35
  const step = own(document.steps, stepId) ? document.steps[stepId] : undefined
@@ -0,0 +1,57 @@
1
+ import { Validator } from '@cfworker/json-schema'
2
+ import { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
3
+ import type { Narration, TeachingDocument } from './contracts/document.ts'
4
+
5
+ const schema = new Validator({ $id: 'urn:presmium:step-narrations:1', $defs: structuredClone(DOCUMENT_JSON_SCHEMA.$defs), type: 'array', items: { $ref: '#/$defs/Narration' } }, '2020-12', false)
6
+
7
+ /** Replace one step's ordered script blocks, retaining entities still used by other steps. */
8
+ export function replaceStepNarrations(source: TeachingDocument, stepId: string, narrations: readonly Narration[]): TeachingDocument {
9
+ const step = source.steps[stepId]
10
+ if (!step || !source.sections[step.sectionId]?.stepOrder.includes(stepId)) throw new Error('document-narration-target')
11
+ if (!schema.validate(narrations).valid) throw new Error('document-narration-content')
12
+ const ids = narrations.map(narration => narration.id)
13
+ if (new Set(ids).size !== ids.length) throw new Error('document-narration-target')
14
+ const content = { ...source,
15
+ steps: { ...source.steps, [stepId]: { ...step, narrationIds: ids } },
16
+ narrations: { ...source.narrations },
17
+ production: { ...source.production,
18
+ ...source.production.narrationOverrides ? { narrationOverrides: { ...source.production.narrationOverrides } } : {},
19
+ ...source.production.cueTimings ? { cueTimings: { ...source.production.cueTimings } } : {},
20
+ },
21
+ }
22
+ for (const narration of narrations) {
23
+ content.narrations[narration.id] = structuredClone(narration)
24
+ }
25
+ const used = new Set(Object.values(content.steps).flatMap(step => step.narrationIds))
26
+ for (const id of step.narrationIds) if (!used.has(id)) {
27
+ delete content.narrations[id]
28
+ if (content.production.narrationOverrides) delete content.production.narrationOverrides[id]
29
+ }
30
+ const cues = new Set(Object.values(content.narrations).flatMap(narration => narration.content.flatMap(node => node.type === 'cue' ? [node.id] : [])))
31
+ for (const id of Object.keys(content.production.cueTimings ?? {})) if (!cues.has(id)) delete content.production.cueTimings![id]
32
+ return content
33
+ }
34
+
35
+ /** An exact, unique text edit keeps the existing pronunciation and cue atoms intact. */
36
+ export function replaceStepNarrationText(source: TeachingDocument, stepId: string, find: string, replacement: string): TeachingDocument {
37
+ const step = source.steps[stepId]
38
+ if (!step || !find) throw new Error('document-narration-target')
39
+ const narrations = step.narrationIds.map(id => source.narrations[id]!)
40
+ const matches: { narration: string, node: number, offset: number }[] = []
41
+ for (const narration of narrations) for (const [node, value] of narration.content.entries()) {
42
+ if (value.type !== 'text') continue
43
+ for (let at = value.text.indexOf(find); at !== -1; at = value.text.indexOf(find, at + 1)) {
44
+ matches.push({ narration: narration.id, node, offset: at })
45
+ if (matches.length > 1) throw new Error('document-narration-text-ambiguous')
46
+ }
47
+ }
48
+ const found = matches[0]
49
+ if (!found) throw new Error('document-narration-text-missing')
50
+ return replaceStepNarrations(source, stepId, narrations.map(narration => narration.id !== found.narration ? narration : {
51
+ ...narration, content: narration.content.flatMap((node, index) => {
52
+ if (index !== found.node || node.type !== 'text') return [node]
53
+ const text = node.text.slice(0, found.offset) + replacement + node.text.slice(found.offset + find.length)
54
+ return text ? [{ ...node, text }] : []
55
+ }),
56
+ }).filter(narration => narration.content.length > 0))
57
+ }
@@ -1,9 +1,12 @@
1
+ import { isDocumentPlaceAnchor } from './contracts/document.ts'
2
+ import { degradeDocumentCommentAnchor } from './document-comments.ts'
3
+ import { replaceStepNarrations } from './document-narrations.ts'
1
4
  import type { DocumentBlock, DocumentEditOperation, TeachingDocument } from './contracts/document.ts'
2
5
 
3
6
  /** Operations describe author intent; the caller validates the resulting complete document before committing it. */
4
7
  export function applyDocumentOperations(source: TeachingDocument, operations: readonly DocumentEditOperation[]): TeachingDocument {
5
8
  if (!operations.length || operations.length > 1000) throw new Error('document-operation-count')
6
- const document = structuredClone(source)
9
+ let document = structuredClone(source)
7
10
  const block = (id: string): DocumentBlock => {
8
11
  if (!Object.hasOwn(document.blocks, id)) throw new Error('document-block-missing')
9
12
  return document.blocks[id]!
@@ -69,6 +72,14 @@ export function applyDocumentOperations(source: TeachingDocument, operations: re
69
72
  if (!targetSteps.has(value.id)) value.visuals = value.visuals.filter(visual => !moved.has(visual.blockId))
70
73
  else for (const id of moved) if (!value.visuals.some(visual => visual.blockId === id)) value.visuals.push({ blockId: id, visible: true })
71
74
  }
75
+ // A step belongs to one section; a place comment stays on the block when that step no longer renders it.
76
+ for (const thread of Object.values(document.comments ?? {})) {
77
+ const anchor = thread.anchor
78
+ if (!anchor || !isDocumentPlaceAnchor(anchor) || anchor.stepId === undefined || !moved.has(anchor.blockId)) continue
79
+ const degraded = degradeDocumentCommentAnchor(document, anchor)
80
+ if (degraded) thread.anchor = degraded
81
+ else delete thread.anchor
82
+ }
72
83
  break
73
84
  }
74
85
  case 'deleteBlock': {
@@ -82,7 +93,11 @@ export function applyDocumentOperations(source: TeachingDocument, operations: re
82
93
  }
83
94
  for (const id of removed) visit(block(id))
84
95
  // A deleted range becomes an unanchored thread; its discussion survives.
85
- for (const thread of Object.values(document.comments ?? {})) if (thread.anchor && (identities.has(thread.anchor.from.blockId) || identities.has(thread.anchor.to.blockId))) delete thread.anchor
96
+ for (const thread of Object.values(document.comments ?? {})) {
97
+ const anchor = thread.anchor
98
+ if (!anchor) continue
99
+ if (isDocumentPlaceAnchor(anchor) ? identities.has(anchor.blockId) : identities.has(anchor.from.blockId) || identities.has(anchor.to.blockId)) delete thread.anchor
100
+ }
86
101
  detach(operation.blockId)
87
102
  for (const id of removed) delete document.blocks[id]
88
103
  for (const value of Object.values(document.steps)) value.visuals = value.visuals.filter(visual => !removed.has(visual.blockId))
@@ -115,6 +130,21 @@ export function applyDocumentOperations(source: TeachingDocument, operations: re
115
130
  }
116
131
  break
117
132
  }
133
+ case 'removeNarration': {
134
+ const value = step(operation.stepId)
135
+ if (!value.narrationIds.includes(operation.narrationId)) throw new Error('document-narration-target')
136
+ document = replaceStepNarrations(document, value.id, value.narrationIds.filter(id => id !== operation.narrationId).map(id => document.narrations[id]!))
137
+ break
138
+ }
139
+ case 'setStepNarrations': {
140
+ step(operation.stepId)
141
+ const narrations = operation.narrationIds.map(id => {
142
+ if (!Object.hasOwn(document.narrations, id)) throw new Error('document-narration-target')
143
+ return document.narrations[id]!
144
+ })
145
+ document = replaceStepNarrations(document, operation.stepId, narrations)
146
+ break
147
+ }
118
148
  case 'setTiming':
119
149
  if (operation.stepId && operation.sectionId) throw new Error('document-timing-scope')
120
150
  if (operation.stepId) { step(operation.stepId); put(document.production.stepOverrides, operation.stepId, operation.value) }
@@ -1,3 +1,4 @@
1
+ import { isDocumentPlaceAnchor } from './contracts/document.ts'
1
2
  import type { ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
2
3
  import type { DocumentPageDeletionImpact, DocumentPageIds } from './contracts/authoring.ts'
3
4
  import type { PageDeletePlan } from './contracts/workspace.ts'
@@ -89,7 +90,13 @@ export function pageDeletionImpact(document: TeachingDocument, section: string):
89
90
  for (const id of blocks) { const block = document.blocks[id]; if (block?.type === 'text') block.content.forEach(rich) }
90
91
  return { sectionId: section, retainedEmpty: document.sectionOrder.length === 1, blocks: [...blocks], steps: [...steps], narrations: [...removed], retainedNarrations: [...candidates].filter(id => !removed.has(id)), cues,
91
92
  clips: document.production.mediaClips.filter(clip => steps.has(clip.attachment.stepId)).map(clip => clip.id),
92
- detachedComments: Object.values(document.comments ?? {}).filter(thread => thread.anchor && (targets.has(thread.anchor.from.blockId) || targets.has(thread.anchor.to.blockId))).map(thread => thread.id), references }
93
+ detachedComments: Object.values(document.comments ?? {}).filter(thread => {
94
+ const anchor = thread.anchor
95
+ if (!anchor) return false
96
+ return isDocumentPlaceAnchor(anchor)
97
+ ? targets.has(anchor.blockId) || Boolean(anchor.stepId && steps.has(anchor.stepId))
98
+ : targets.has(anchor.from.blockId) || targets.has(anchor.to.blockId)
99
+ }).map(thread => thread.id), references }
93
100
  }
94
101
 
95
102
  export function pageDeletion(document: TeachingDocument, directory: string, version: string, section: string): PageDeletePlan {
@@ -0,0 +1,92 @@
1
+ import { isDocumentPlaceAnchor, isDocumentTextAnchor } from './contracts/document.ts'
2
+ import type { DocumentThreadAnchor, InlineNode, RichTextNode, TeachingDocument } from './contracts/document.ts'
3
+
4
+ /** The stable places a discussion can point at, in document order. */
5
+ export interface DocumentPlacesVisitor {
6
+ /** A page title or a block. */
7
+ place(id: string): void
8
+ /** An addressable text identity: a rich-text node, a code block or a page title. */
9
+ text(id: string, text: string): void
10
+ }
11
+
12
+ /** Canonical anchor v1 expands only nonempty styled-text links; other inline values are atoms. */
13
+ export function isDocumentTextLink(node: InlineNode): node is Extract<InlineNode, { type: 'link' }> & { children: Extract<InlineNode, { type: 'text' | 'break' }>[] } {
14
+ return node.type === 'link' && node.children.length > 0 && node.children.every(child => child.type === 'text' || child.type === 'break')
15
+ }
16
+ function inlineText(nodes: readonly InlineNode[]): string {
17
+ return nodes.map(node => node.type === 'text' ? node.text : node.type === 'break' ? '\n' : isDocumentTextLink(node) ? inlineText(node.children) : '\uFFFC').join('')
18
+ }
19
+
20
+ /**
21
+ * One walk over the document's stable places. Only addressable canonical identities are visited; opaque plugin
22
+ * data is never traversed. A caller that only needs text targets can ignore `place`.
23
+ */
24
+ export function walkDocumentPlaces(document: TeachingDocument, visit: DocumentPlacesVisitor): void {
25
+ const rich = (node: RichTextNode): void => {
26
+ if (node.type === 'paragraph' || node.type === 'heading') visit.text(node.id, inlineText(node.children))
27
+ else if (node.type === 'code') visit.text(node.id, node.value)
28
+ else if (node.type === 'list') for (const item of node.children) {
29
+ const [first, ...rest] = item.children
30
+ visit.text(item.id, first?.type === 'paragraph' ? inlineText(first.children) : '')
31
+ ;(first?.type === 'paragraph' ? rest : item.children).forEach(rich)
32
+ }
33
+ else if (node.type === 'blockquote') {
34
+ const [first, ...rest] = node.children
35
+ if (first?.type === 'paragraph') { visit.text(node.id, inlineText(first.children)); rest.forEach(rich) }
36
+ else node.children.forEach(rich)
37
+ } else if (node.type === 'table') for (const row of node.children) for (const cell of row.children) visit.text(cell.id, inlineText(cell.children))
38
+ }
39
+ const block = (id: string): void => {
40
+ visit.place(id)
41
+ const value = document.blocks[id]
42
+ if (value?.type === 'text') value.content.forEach(rich)
43
+ else if (value?.type === 'code' && value.value !== undefined) visit.text(id, value.value)
44
+ else if (value?.type === 'container' || value?.type === 'component') value.children?.forEach(block)
45
+ }
46
+ for (const id of document.sectionOrder) {
47
+ const page = document.sections[id]
48
+ if (!page) continue
49
+ visit.place(`page:${id}`)
50
+ visit.text(`page:${id}`, page.title)
51
+ page.children.forEach(block)
52
+ }
53
+ }
54
+
55
+ /** Only addressable canonical text identities, in native document order; opaque data is never traversed. */
56
+ export function documentCommentTargets(document: TeachingDocument): Map<string, { order: number, text: string }> {
57
+ const targets = new Map<string, { order: number, text: string }>()
58
+ walkDocumentPlaces(document, { place() {}, text: (id, text) => { targets.set(id, { order: targets.size, text }) } })
59
+ return targets
60
+ }
61
+
62
+ /** Every anchorable place in document order: page titles, blocks and text identities on one scale. */
63
+ export function documentAnchorOrder(document: TeachingDocument): Map<string, number> {
64
+ const places = new Map<string, number>()
65
+ const add = (id: string) => { if (!places.has(id)) places.set(id, places.size) }
66
+ walkDocumentPlaces(document, { place: add, text: add })
67
+ return places
68
+ }
69
+
70
+ /** The section that owns a block, following container and component children. */
71
+ export function documentBlockSection(document: TeachingDocument, blockId: string): string | undefined {
72
+ for (const sectionId of document.sectionOrder) {
73
+ const pending = [...document.sections[sectionId]!.children], seen = new Set<string>()
74
+ while (pending.length) {
75
+ const id = pending.pop()!
76
+ if (id === blockId) return sectionId
77
+ if (seen.has(id)) continue
78
+ seen.add(id)
79
+ const block = document.blocks[id]
80
+ if (block?.type === 'container' || block?.type === 'component') pending.push(...block.children ?? [])
81
+ }
82
+ }
83
+ return undefined
84
+ }
85
+
86
+ /** A key-order independent identity for comparing a thread anchor with a draft target. */
87
+ export function documentAnchorKey(anchor: DocumentThreadAnchor | undefined): string | undefined {
88
+ if (!anchor) return undefined
89
+ if (isDocumentPlaceAnchor(anchor)) return JSON.stringify(['place', anchor.blockId, anchor.stepId ?? null])
90
+ if (!isDocumentTextAnchor(anchor)) return undefined
91
+ return JSON.stringify(['text', anchor.from.blockId, anchor.from.offset, anchor.to.blockId, anchor.to.offset])
92
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Schema } from '@cfworker/json-schema'
2
- import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_SCHEMA_VERSION } from './contracts/document.ts'
2
+ import { ASSET_TITLE_MAX_LENGTH, CAPTION_SCALE_MAX, CAPTION_SCALE_MIN, DOCUMENT_SCHEMA_VERSION } from './contracts/document.ts'
3
3
 
4
4
  const ref = (name: string): Schema => ({ $ref: `#/$defs/${name}` })
5
5
  const string: Schema = { type: 'string' }
@@ -77,9 +77,9 @@ export const DOCUMENT_JSON_SCHEMA: Schema = {
77
77
  StepProduction: object({ narrationStart: { enum: ['with-animation', 'after-animation'] }, minimumHoldMs: nonnegative, trailingPauseMs: nonnegative, voiceSource: ref('VoiceSource') }, []),
78
78
  MediaClip: object({ id, assetId: id, sourceRange: object({ startMs: nonnegative, endMs: nonnegative }), attachment: object({ stepId: id, offsetMs: nonnegative }), volume: { type: 'number', minimum: 0, maximum: 1 }, muted: { type: 'boolean' } }, ['id', 'assetId', 'sourceRange', 'attachment', 'volume']),
79
79
  CaptionTiming: object({ narrationIds: ids, sourceFingerprint: { type: 'string', pattern: '^[a-f0-9]{16}$' }, playbackFingerprint: { type: 'string', pattern: '^[a-f0-9]{16}$' }, durationMs: { type: 'integer', minimum: 1 }, segments: { type: 'array', minItems: 1, maxItems: 32, items: object({ id, from: integer, to: integer, startMs: integer, endMs: integer }) } }),
80
- Production: object({ defaults: ref('StepProduction'), sectionOverrides: record(ref('StepProduction')), stepOverrides: record(ref('StepProduction')), narrationOverrides: record(object({ narrationStart: { enum: ['with-animation', 'after-animation'] } })), cueTimings: record(object({ pauseMs: nonnegative })), captionTimings: record(ref('CaptionTiming')), mediaClips: list(ref('MediaClip')) }, ['defaults', 'stepOverrides', 'mediaClips']),
80
+ Production: object({ defaults: ref('StepProduction'), sectionOverrides: record(ref('StepProduction')), stepOverrides: record(ref('StepProduction')), narrationOverrides: record(object({ narrationStart: { enum: ['with-animation', 'after-animation'] } })), cueTimings: record(object({ pauseMs: nonnegative })), captionTimings: record(ref('CaptionTiming')), captions: object({ scale: { type: 'number', minimum: CAPTION_SCALE_MIN, maximum: CAPTION_SCALE_MAX } }), mediaClips: list(ref('MediaClip')) }, ['defaults', 'stepOverrides', 'mediaClips']),
81
81
  TextPoint: object({ blockId: { type: 'string', minLength: 1, maxLength: 205 }, offset: integer }),
82
82
  Comment: object({ id, type: tag('comment'), userId: id, createdAt: string, updatedAt: string, deletedAt: string, content: list(ref('RichTextNode')), metadata: ref('JsonObject'), reactions: list(object({ emoji: string, createdAt: string, userIds: ids })) }, ['id', 'type', 'userId', 'createdAt', 'updatedAt', 'reactions']),
83
- Thread: object({ id, type: tag('thread'), createdAt: string, updatedAt: string, resolved: { type: 'boolean' }, resolvedUpdatedAt: string, resolvedBy: id, metadata: ref('JsonObject'), deletedAt: string, anchor: object({ from: ref('TextPoint'), to: ref('TextPoint') }), comments: list(ref('Comment')) }, ['id', 'type', 'createdAt', 'updatedAt', 'resolved', 'comments']),
83
+ Thread: object({ id, type: tag('thread'), createdAt: string, updatedAt: string, resolved: { type: 'boolean' }, resolvedUpdatedAt: string, resolvedBy: id, metadata: ref('JsonObject'), deletedAt: string, anchor: { oneOf: [object({ from: ref('TextPoint'), to: ref('TextPoint') }), object({ blockId: id, stepId: id }, ['blockId'])] }, comments: list(ref('Comment')) }, ['id', 'type', 'createdAt', 'updatedAt', 'resolved', 'comments']),
84
84
  },
85
85
  }
package/src/document.ts CHANGED
@@ -3,6 +3,8 @@ import { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
3
3
  import { isRecord } from './errors.ts'
4
4
  import { captionSourceFingerprint, captionTimingProblem, stepCaptionText } from './document-caption-timings.ts'
5
5
  import { validateDocumentParameters } from './parameters.ts'
6
+ import { isDocumentPlaceAnchor } from './contracts/document.ts'
7
+ import { documentBlockSection } from './document-places.ts'
6
8
  import type { DocumentIssue, DocumentValidation, RichTextNode, TeachingDocument } from './contracts/document.ts'
7
9
 
8
10
  export { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
@@ -240,7 +242,17 @@ export function validateDocument(value: unknown): DocumentValidation {
240
242
  const path = at('/comments', id)
241
243
  if (id !== thread.id) issue(`${path}/id`, 'id.key', 'A thread ID must match its map key.')
242
244
  identify(thread.id, `${path}/id`)
243
- for (const edge of ['from', 'to'] as const) if (thread.anchor && !textTargets.has(thread.anchor[edge].blockId)) issue(`${path}/anchor/${edge}/blockId`, 'comment.target', 'A comment anchor must name a stable rich-text node or section title.')
245
+ const anchor = thread.anchor
246
+ if (anchor && isDocumentPlaceAnchor(anchor)) {
247
+ if (!Object.hasOwn(doc.blocks, anchor.blockId)) issue(`${path}/anchor/blockId`, 'comment.target', 'A place comment must name an existing block.')
248
+ else if (anchor.stepId !== undefined) {
249
+ const step = Object.hasOwn(doc.steps, anchor.stepId) ? doc.steps[anchor.stepId] : undefined
250
+ const section = step ? doc.sections[step.sectionId] : undefined
251
+ if (!step || !section || !section.stepOrder.includes(anchor.stepId) || step.sectionId !== documentBlockSection(doc, anchor.blockId)) issue(`${path}/anchor/stepId`, 'comment.target', 'A place comment must name a step of the block\'s own section.')
252
+ }
253
+ } else if (anchor) {
254
+ for (const edge of ['from', 'to'] as const) if (!textTargets.has(anchor[edge].blockId)) issue(`${path}/anchor/${edge}/blockId`, 'comment.target', 'A comment anchor must name a stable rich-text node or section title.')
255
+ }
244
256
  for (const [index, comment] of thread.comments.entries()) {
245
257
  identify(comment.id, `${path}/comments/${index}/id`)
246
258
  comment.content?.forEach((node, child) => rich(node, `${path}/comments/${index}/content/${child}`, new Set()))
package/src/embed.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * What a page tells the page that embeds it in a frame, as `postMessage` to its parent: whether its current slide is
3
+ * drawn (no component is still loading) and the state of its lecture. An embedding page (a site's home page playing a
4
+ * document's presentation) keeps its own cover until `drawn`, and offers Play when the lecture is `waiting`.
5
+ */
6
+ export const EMBED_MESSAGE = 'presmium:state'
7
+
8
+ export type EmbeddedLecture = 'loading' | 'waiting' | 'playing' | 'paused' | 'failed'
9
+
10
+ export interface EmbedState {
11
+ type: typeof EMBED_MESSAGE
12
+ drawn: boolean
13
+ section?: string
14
+ step?: number
15
+ /** Absent when the page plays no lecture. `waiting`: the browser refused autoplay; the reader's Play starts it. */
16
+ lecture?: EmbeddedLecture
17
+ }
18
+
19
+ let last: EmbedState = { type: EMBED_MESSAGE, drawn: false }
20
+
21
+ /** Sends the page's state, merged with what was sent before, to the embedding page; nothing when not in a frame. */
22
+ export function notifyEmbedder(change: Partial<Omit<EmbedState, 'type'>>): void {
23
+ if (typeof window === 'undefined' || window.parent === window) return
24
+ last = { ...last, ...change }
25
+ window.parent.postMessage(last, '*')
26
+ }
@@ -0,0 +1,4 @@
1
+ /** Text as it reads in HTML, in an element or an attribute's value; apart from `html.ts`, so that escaping loads no HTML parser. */
2
+ export function escapeHtml(text: string): string {
3
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
4
+ }
package/src/html.ts CHANGED
@@ -1,9 +1,6 @@
1
1
  import { parseFragment } from 'parse5'
2
2
  import type { DefaultTreeAdapterMap } from 'parse5'
3
-
4
- export function escapeHtml(text: string): string {
5
- return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
6
- }
3
+ import { escapeHtml } from './escape-html.ts'
7
4
 
8
5
  export interface HtmlAttribute {
9
6
  name: string
package/src/index.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  export * from './contracts.ts'
2
+ export { randomUUID } from './random-uuid.ts'
2
3
  export { applyDocumentOperations } from './document-operations.ts'
4
+ export { replaceStepNarrations, replaceStepNarrationText } from './document-narrations.ts'
3
5
  export { validateDocumentChange, DOCUMENT_CHANGE_JSON_SCHEMA } from './authoring.ts'
4
6
  export { allocateDocumentPage, createDocumentPage, documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, duplicateDocumentPage, moveDocumentPage, pageContents, pageDeletion, pageDeletionImpact, removeDocumentPage, renameDocumentPage } from './document-pages.ts'
5
7
  export { documentOutline, documentPart, DocumentReadError } from './document-reads.ts'
6
8
  export { changeDocumentVoice, documentVoiceStepIds, previewDocumentVoiceChange, resolveDocumentStepVoice } from './document-voices.ts'
7
9
  export { DOCUMENT_COLOR_NAMES, documentColorToken, documentColorValue } from './document-colors.ts'
8
10
  export type { DocumentColorKind, DocumentColorName } from './document-colors.ts'
9
- export { applyDocumentCommentAction, isDocumentTextLink, documentCommentTargets, validateDocumentCommentAnchor, DocumentCommentError } from './document-comments.ts'
10
- export { applyDocumentAuthoringAction } from './document-authoring-actions.ts'
11
+ export { applyDocumentCommentAction, degradeDocumentCommentAnchor, isDocumentTextLink, documentCommentTargets, validateDocumentCommentAnchor, DocumentCommentError } from './document-comments.ts'
12
+ export { documentAnchorKey, documentAnchorOrder, documentBlockSection, walkDocumentPlaces } from './document-places.ts'
13
+ export { applyDocumentAuthoringAction, enableDocumentProduction } from './document-authoring-actions.ts'
11
14
  export { applyDocumentComponentAction, effectiveComponentParameters, createDocumentParameterChanges, documentComponentSection, DocumentComponentError } from './document-components.ts'
12
15
  export type { DocumentStepVoice, DocumentVoiceImpact, DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
13
16
  export { prepareTranscriptionAdoption } from './transcription-adoption.ts'
@@ -25,12 +28,14 @@ export { errorMessage, isRecord, PreviewPreparing } from './errors.ts'
25
28
  export { createEventBus } from './events.ts'
26
29
  export { CREDENTIAL_VARIABLE, environmentExecutor, failedRun, languageId } from './execution.ts'
27
30
  export { gitConfigArgs, gitEnvironment } from './git.ts'
28
- export { escapeHtml, htmlAttributes, mapHtmlUrls, URL_ATTRIBUTES } from './html.ts'
31
+ export { escapeHtml } from './escape-html.ts'
32
+ export { htmlAttributes, mapHtmlUrls, URL_ATTRIBUTES } from './html.ts'
29
33
  export type { HtmlAttribute } from './html.ts'
30
34
  export { hostName, localRequestRefusal } from './requests.ts'
31
35
  export type { RequestHeaders } from './requests.ts'
32
36
  export { fingerprint, fnv1a64 } from './fingerprint.ts'
33
37
  export { applyDocumentCaptionTiming, captionSourceFingerprint, captionTimingProblem, stepCaptionText, narrationCaptionText, CAPTION_TIMING_MAX_SEGMENTS, DocumentCaptionTimingError } from './document-caption-timings.ts'
38
+ export { captionScale, changeDocumentCaptionScale } from './document-caption-scale.ts'
34
39
  export type { DocumentCaptionTimingAction } from './document-caption-timings.ts'
35
40
  export { backSection, followedPlace } from './follow.ts'
36
41
  export type { FollowAnchor } from './follow.ts'
@@ -39,9 +44,13 @@ export type { KernelOptions } from './kernel.ts'
39
44
  export { deckLocale, localeOf } from './locale.ts'
40
45
  export { ANCHOR_LOCK_PATH, AnchorLock } from './lock.ts'
41
46
  export { prefixedLogger } from './logging.ts'
42
- export { lowerMyst, roleMark } from './lower-myst.ts'
47
+ export { lowerMyst } from './lower-myst.ts'
43
48
  export type { LinkedType, LoweredMarkdown, LowerOptions } from './lower-myst.ts'
44
- export { connectPreviewFrame, isPreviewActive, isPreviewEmbedded, previewAppearance, previewFrameAncestors, reportPreview } from './preview-frame.ts'
49
+ export { isPreviewActive, isPreviewEmbedded, previewAppearance, reportPreview, siteFrameAncestors } from './preview-frame.ts'
50
+ export { connectPreviewFrame } from './preview-frame-connect.ts'
51
+ export { reportStaleModule, STALE_MODULE_EVENT, STALE_MODULE_PATTERN } from './stale-module.ts'
52
+ export { EMBED_MESSAGE, notifyEmbedder } from './embed.ts'
53
+ export type { EmbeddedLecture, EmbedState } from './embed.ts'
45
54
  export { keyBelongsToTarget, watchFocusSource } from './keyboard.ts'
46
55
  export type { PreviewFrame, PreviewPage, PreviewProblem, PreviewTextEdit, PreviewTextHandle } from './preview-frame.ts'
47
56
  export { previewEditBinding } from './preview-edit.ts'
@@ -65,7 +74,7 @@ export type { StepKeys } from './step-keys.ts'
65
74
  export { parseDuration } from './durations.ts'
66
75
  export { stepStateAt } from './steps.ts'
67
76
  export { ABSOLUTE_URL, NON_FILE_URL, urlSlug } from './urls.ts'
68
- export { isButton } from './lower-myst.ts'
77
+ export { isButton, roleMark } from './myst-marks.ts'
69
78
  export { componentProps, findComponentRenderer, hasRendererExtension, WEB_RENDERER_PACKAGE, withPublishedAssets } from './renderer-components.ts'
70
79
  export { htmlAsText, isProseRun } from './run-outputs.ts'
71
80
  export { safeDecodeURIComponent } from './uri-decoding.ts'
package/src/ir.ts CHANGED
@@ -168,46 +168,7 @@ export interface ComponentNode {
168
168
  layer?: 'overlay'
169
169
  durations?: number[]
170
170
  /** The authored code that defines this component instance, when supplied by its plugin. */
171
- definition?: { file: string, language: string, exportName?: string }
172
- }
173
-
174
- export type DirectiveOptionType = 'string' | 'number' | 'boolean' | 'list'
175
-
176
- export interface DirectiveInput {
177
- name: string
178
- arg?: string
179
- options: Record<string, unknown>
180
- body: string
181
- }
182
-
183
- export interface DirectiveContext {
184
- file: string
185
- deckDir: string
186
- workspaceRoot: string
187
- lang?: string
188
- config: Record<string, unknown>
189
- source: SourcePos
190
- parse(markdown: string): MdastNode
191
- report(finding: Finding): void
192
- watch(...files: string[]): void
193
- }
194
-
195
- export interface DirectiveResult {
196
- node: IRNode
197
- role?: BlockRole
198
- span?: number
199
- }
200
-
201
- export interface RoleInput {
202
- name: string
203
- value: string
204
- options: Record<string, unknown>
205
- }
206
-
207
- export interface RoleSpec {
208
- name: string
209
- options?: Record<string, DirectiveOptionType>
210
- children?(input: RoleInput, ctx: DirectiveContext): MdastNode[]
171
+ definition?: { file: string, language: string, exportName?: string, kind?: string }
211
172
  }
212
173
 
213
174
  export interface PresmiumRoleNode extends MdastNode {
@@ -218,14 +179,6 @@ export interface PresmiumRoleNode extends MdastNode {
218
179
  children: MdastNode[]
219
180
  }
220
181
 
221
- export interface DirectiveSpec {
222
- name: string
223
- arg?: boolean | 'anchor'
224
- body?: boolean
225
- options?: Record<string, DirectiveOptionType>
226
- toIR(input: DirectiveInput, ctx: DirectiveContext): DirectiveResult | Promise<DirectiveResult>
227
- }
228
-
229
182
  export interface RunCache {
230
183
  get(key: string): RecordedRun | undefined
231
184
  set(key: string, run: RecordedRun): void
@@ -318,6 +271,11 @@ export interface Renderer {
318
271
  dev?(doc: IRDocument, ctx: RenderContext): Promise<RenderDevServer>
319
272
  buildSite?(site: SiteSpec, ctx: RenderContext): Promise<RenderOutput>
320
273
  devSite?(site: SiteSpec, ctx: RenderContext, compile: (dir: string) => Promise<IRDocument>): Promise<SiteDevServer>
274
+ /**
275
+ * What would fail in its output of the whole document (every form's blocks), found ahead of a build: run with the
276
+ * document's checks (`presmium check`). The web renderer's: the document's own code that does not bundle.
277
+ */
278
+ check?(doc: IRDocument, ctx: RenderContext): Promise<Finding[]>
321
279
  }
322
280
 
323
281
  export interface SiteDocument {
@@ -326,11 +284,23 @@ export interface SiteDocument {
326
284
  description?: string
327
285
  lang?: string
328
286
  tags?: string[]
287
+ /** Whether it has a presentation, before its IR is compiled (`DocumentSummary.slides`). */
288
+ slides?: boolean
329
289
  doc?: IRDocument
330
290
  translations?: { lang: string, doc: IRDocument }[]
331
291
  nodeVitePlugins?: NodeVitePlugin[]
332
292
  }
333
293
 
294
+ /**
295
+ * A built site keeps its viewer apps below its path, each at `<APP_DIR>/<key>/` by its content. A presentation built as
296
+ * part of a site (renderer option `appBase`, the site's path) names its app there, so the site's pages and all its
297
+ * presentations load one app.
298
+ */
299
+ export const APP_DIR = '_app'
300
+
301
+ /** A site serves a document's presentation (`renderers.slides`) below the document's pages, at `<document>/<SLIDES_DIR>/`. */
302
+ export const SLIDES_DIR = 'slides'
303
+
334
304
  export interface SiteSpec {
335
305
  title: string
336
306
  documents: SiteDocument[]
@@ -352,6 +322,11 @@ export interface SiteDevServer {
352
322
  * With `wait`, a build still running after the wait rejects with `PreviewPreparing`; a failed build with its reason.
353
323
  */
354
324
  app?(dir: string, wait?: boolean): Promise<string | undefined>
325
+ /**
326
+ * The files of document `dir`'s own code that the bundle its pages load now leaves out, since they do not bundle:
327
+ * each module that imports one fails alone when the document shows it (`app` rejects when the whole does not bundle).
328
+ */
329
+ codeFindings?(dir: string): Finding[]
355
330
  close(): Promise<void>
356
331
  }
357
332