markdown-worker-protocol.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import type { ThemeRegistrationResolved } from "shiki"
  2. export type MarkdownToken = [content: string, style: string]
  3. export type MarkdownWorkerRequest =
  4. | { type: "init"; theme: ThemeRegistrationResolved }
  5. | { type: "highlight"; id: number; key: string; text: string; language: string; complete?: boolean }
  6. | { type: "dispose"; key: string }
  7. export type MarkdownWorkerResponse =
  8. | {
  9. type: "highlight"
  10. id: number
  11. key: string
  12. reset: boolean
  13. stable: MarkdownToken[]
  14. unstable: MarkdownToken[]
  15. }
  16. | { type: "error"; id: number; key: string; message: string }
  17. | { type: "superseded"; id: number; key: string }
  18. export type MarkdownWorkerState = {
  19. id: number
  20. generation: number
  21. stable: MarkdownToken[]
  22. unstable: MarkdownToken[]
  23. }
  24. export function shouldReleaseMarkdownWorkerState(complete: boolean, latestID: number | undefined, responseID: number) {
  25. return complete && latestID === responseID
  26. }
  27. export function markdownBlockKey(owner: string, cacheKey: string | undefined, index: number, mode: string) {
  28. return `${owner}:${cacheKey ? `${cacheKey}:${index}:${mode}` : `block:${index}`}`
  29. }
  30. export function applyMarkdownWorkerResponse(
  31. state: MarkdownWorkerState | undefined,
  32. response: Extract<MarkdownWorkerResponse, { type: "highlight" }>,
  33. ) {
  34. if (state && response.id <= state.id) return state
  35. return {
  36. id: response.id,
  37. generation: (state?.generation ?? 0) + (response.reset ? 1 : 0),
  38. stable: response.reset ? response.stable : [...(state?.stable ?? []), ...response.stable],
  39. unstable: response.unstable,
  40. }
  41. }