@arbidocs/react 0.4.8 → 0.4.10

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 (34) hide show
  1. package/README.md +9 -0
  2. package/dist/artifacts/index.cjs +155 -21
  3. package/dist/artifacts/index.cjs.map +1 -1
  4. package/dist/artifacts/index.d.cts +120 -8
  5. package/dist/artifacts/index.d.ts +120 -8
  6. package/dist/artifacts/index.js +129 -20
  7. package/dist/artifacts/index.js.map +1 -1
  8. package/dist/{chunk-YURJV3RS.cjs → chunk-K5TOB34Q.cjs} +4 -4
  9. package/dist/{chunk-YURJV3RS.cjs.map → chunk-K5TOB34Q.cjs.map} +1 -1
  10. package/dist/{chunk-CBJ3WOGD.cjs → chunk-KKSSTNJK.cjs} +123 -3
  11. package/dist/chunk-KKSSTNJK.cjs.map +1 -0
  12. package/dist/{chunk-U7RBOJK3.js → chunk-NVMQLJI4.js} +3 -3
  13. package/dist/{chunk-U7RBOJK3.js.map → chunk-NVMQLJI4.js.map} +1 -1
  14. package/dist/{chunk-77G7DSUW.js → chunk-TGGQGFS3.js} +57 -6
  15. package/dist/chunk-TGGQGFS3.js.map +1 -0
  16. package/dist/{chunk-KWCHIAQ5.js → chunk-UV5ZEUNV.js} +119 -5
  17. package/dist/chunk-UV5ZEUNV.js.map +1 -0
  18. package/dist/{chunk-FUPWPQGK.cjs → chunk-WBWXP2DN.cjs} +56 -5
  19. package/dist/chunk-WBWXP2DN.cjs.map +1 -0
  20. package/dist/index.cjs +395 -366
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +5 -1
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +16 -11
  25. package/dist/index.js.map +1 -1
  26. package/dist/stored-markdown-DMwFzWhc.d.cts +75 -0
  27. package/dist/stored-markdown-DMwFzWhc.d.ts +75 -0
  28. package/dist/ui/index.cjs +147 -147
  29. package/dist/ui/index.js +2 -2
  30. package/package.json +3 -3
  31. package/dist/chunk-77G7DSUW.js.map +0 -1
  32. package/dist/chunk-CBJ3WOGD.cjs.map +0 -1
  33. package/dist/chunk-FUPWPQGK.cjs.map +0 -1
  34. package/dist/chunk-KWCHIAQ5.js.map +0 -1
package/README.md CHANGED
@@ -124,6 +124,15 @@ compare), `useRedline` (diff with a pluggable, worker-capable `RedlineEngine`),
124
124
  and `versionLabel`. `useArtifactText`, `useArtifactVersions` and `useSaveArtifactVersion` are the
125
125
  SDK bindings.
126
126
 
127
+ `useArtifactText(docId)` returns clean markdown and a `status` (`loading`, `parsing`, `ready`,
128
+ `error`): a fresh upload is parsed for a few seconds, during which the backend answers 404, 422 or
129
+ 500, so it retries with a growing delay (bounded) and unescapes the backend's escaped markdown
130
+ (`unescapeMarkdown`; only for artifacts stored from markdown). `useStreamedArtifact({ artifacts,
131
+ workspaceId, settled })` covers the stream, persist, edit life of an agent draft (`phase`:
132
+ `streaming`, `persisting`, `parsing`, `ready`, `error`), cleaning the draft with
133
+ `cleanDraftMarkdown` (`unwrapCitationLinks`, `stripAgentPreamble`, `promoteBoldTitle`) before it is
134
+ stored.
135
+
127
136
  ## Streaming callbacks
128
137
 
129
138
  Pass these to `mutation.mutate()` alongside `question` and `docIds`:
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var chunkCBJ3WOGD_cjs = require('../chunk-CBJ3WOGD.cjs');
3
+ var chunkKKSSTNJK_cjs = require('../chunk-KKSSTNJK.cjs');
4
4
  var chunkVJWAP2HJ_cjs = require('../chunk-VJWAP2HJ.cjs');
5
- var chunkFUPWPQGK_cjs = require('../chunk-FUPWPQGK.cjs');
6
- require('../chunk-S6A6FSG7.cjs');
7
5
  var chunkZMTLGO3K_cjs = require('../chunk-ZMTLGO3K.cjs');
6
+ var chunkWBWXP2DN_cjs = require('../chunk-WBWXP2DN.cjs');
7
+ require('../chunk-S6A6FSG7.cjs');
8
8
  var react = require('react');
9
9
  var reactQuery = require('@tanstack/react-query');
10
10
  var jsxRuntime = require('react/jsx-runtime');
@@ -130,8 +130,9 @@ function versionLabel(versions, docId) {
130
130
  const index = versions.findIndex((v) => v.id === docId);
131
131
  return index === -1 ? null : `v${index + 1}`;
132
132
  }
133
- function flattenChunks(chunks) {
134
- return (chunks ?? []).map((c) => (c.content ?? "").trim()).join("\n\n");
133
+ function flattenChunks(chunks, options) {
134
+ const text = (chunks ?? []).map((c) => (c.content ?? "").trim()).join("\n\n");
135
+ return options?.unescape ? chunkKKSSTNJK_cjs.repairParsedTitle(chunkKKSSTNJK_cjs.unescapeMarkdown(text)) : text;
135
136
  }
136
137
  var DOC_ID = /^doc/;
137
138
  function isDocumentId(id) {
@@ -312,21 +313,73 @@ function useArtifactEditSession(options) {
312
313
  ]
313
314
  );
314
315
  }
316
+ var DEFAULT_ARTIFACT_TEXT_RETRY = {
317
+ attempts: 12,
318
+ baseDelayMs: 1e3,
319
+ maxDelayMs: 5e3
320
+ };
321
+ var NotParsedYetError = class extends Error {
322
+ constructor() {
323
+ super("The document has no parsed text yet");
324
+ }
325
+ };
326
+ var isRefusal = (error) => {
327
+ const status = error;
328
+ const code = status?.status ?? status?.response?.status;
329
+ return code === 401 || code === 403;
330
+ };
315
331
  function useArtifactText(docId, options) {
316
- const real = isDocumentId(docId);
317
- const { data, isLoading, isError } = chunkCBJ3WOGD_cjs.useParsedDocument(real ? docId : void 0, "marker", {
318
- enabled: (options?.enabled ?? true) && real
332
+ const arbi = chunkZMTLGO3K_cjs.useArbi();
333
+ const { attempts, baseDelayMs, maxDelayMs } = {
334
+ ...DEFAULT_ARTIFACT_TEXT_RETRY,
335
+ ...options?.retry
336
+ };
337
+ const enabled = (options?.enabled ?? true) && isDocumentId(docId) && arbi.hasWorkspace;
338
+ const query = reactQuery.useQuery({
339
+ // Under the shared `parsedDoc` key, so a document's invalidation reaches it too.
340
+ queryKey: [...chunkKKSSTNJK_cjs.arbiQueryKeys.parsedDoc(docId ?? "", "marker"), "artifact-text"],
341
+ queryFn: async () => {
342
+ const parsed = await arbi.documents.getParsedContent(docId, "marker");
343
+ if (!parsed.chunks?.some((c) => c.content?.trim())) throw new NotParsedYetError();
344
+ return flattenChunks(parsed.chunks, { unescape: true });
345
+ },
346
+ enabled,
347
+ retry: (failureCount, error) => !isRefusal(error) && failureCount < attempts,
348
+ retryDelay: (failureCount) => Math.min(baseDelayMs * 1.6 ** failureCount, maxDelayMs)
319
349
  });
320
- const text = react.useMemo(() => {
321
- if (!real) return void 0;
322
- if (isError) return null;
323
- if (!data) return void 0;
324
- return data.chunks?.length ? flattenChunks(data.chunks) : null;
325
- }, [real, data, isError]);
326
- return { text, isLoading: real && isLoading };
350
+ const { refetch } = query;
351
+ const retry = react.useCallback(() => void refetch(), [refetch]);
352
+ return react.useMemo(() => {
353
+ const error = query.error;
354
+ const neverParsed = error instanceof NotParsedYetError;
355
+ let status = "loading";
356
+ if (!enabled) status = "loading";
357
+ else if (query.isSuccess || query.isError && neverParsed) status = "ready";
358
+ else if (query.isError) status = "error";
359
+ else if (query.failureCount > 0) status = "parsing";
360
+ const text = !enabled ? void 0 : query.isSuccess ? query.data : status === "ready" || status === "error" ? null : void 0;
361
+ return {
362
+ text,
363
+ isLoading: enabled && (status === "loading" || status === "parsing"),
364
+ status,
365
+ error: status === "ready" ? null : error ?? query.failureReason ?? null,
366
+ retry
367
+ };
368
+ }, [
369
+ enabled,
370
+ query.isSuccess,
371
+ query.isError,
372
+ query.data,
373
+ query.error,
374
+ query.failureCount,
375
+ query.failureReason,
376
+ retry
377
+ ]);
327
378
  }
379
+
380
+ // src/artifacts/useArtifactSession.ts
328
381
  function useArtifactVersions(workspaceId, docId) {
329
- const { data: documents } = chunkCBJ3WOGD_cjs.useDocuments(workspaceId);
382
+ const { data: documents } = chunkKKSSTNJK_cjs.useDocuments(workspaceId);
330
383
  return react.useMemo(
331
384
  () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),
332
385
  [documents, docId]
@@ -348,7 +401,7 @@ function useSaveArtifactVersion() {
348
401
  }
349
402
  );
350
403
  if (workspaceId) {
351
- await queryClient.invalidateQueries({ queryKey: chunkCBJ3WOGD_cjs.arbiQueryKeys.documents(workspaceId) });
404
+ await queryClient.invalidateQueries({ queryKey: chunkKKSSTNJK_cjs.arbiQueryKeys.documents(workspaceId) });
352
405
  }
353
406
  return { docId: result.doc_ext_ids?.[0] };
354
407
  }
@@ -379,7 +432,7 @@ function useArtifactSession(options) {
379
432
  },
380
433
  [onCompareChange]
381
434
  );
382
- const { text, isLoading } = useArtifactText(docId);
435
+ const { text, isLoading, status, retry } = useArtifactText(docId);
383
436
  const versions = useArtifactVersions(workspaceId, isLocal ? null : docId);
384
437
  const { text: compareText, isLoading: compareLoading } = useArtifactText(activeCompareId, {
385
438
  enabled: !!activeCompareId
@@ -428,6 +481,7 @@ function useArtifactSession(options) {
428
481
  docId,
429
482
  isLocal,
430
483
  isLoading,
484
+ status,
431
485
  versions,
432
486
  labelOf: (id) => versionLabel(versions, id),
433
487
  view: {
@@ -446,7 +500,10 @@ function useArtifactSession(options) {
446
500
  onSave: () => void session.save(),
447
501
  onCompare: () => session.compare(),
448
502
  onStopCompare: session.stopCompare,
449
- onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges)
503
+ onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges),
504
+ // A local draft has its text already: it is ready.
505
+ status: isLocal ? "ready" : status,
506
+ onRetry: retry
450
507
  },
451
508
  editorProps: {
452
509
  markdown: session.content,
@@ -458,13 +515,88 @@ function useArtifactSession(options) {
458
515
  onRevert: (regionId) => void session.revertRegion(regionId)
459
516
  }
460
517
  }),
461
- [session, redline, isLoading, isLocal, versions, docId]
518
+ [session, redline, isLoading, status, retry, isLocal, versions, docId]
462
519
  );
463
520
  }
464
521
  function renderArtifactMarkdown(markdown, components) {
465
- return /* @__PURE__ */ jsxRuntime.jsx(chunkFUPWPQGK_cjs.MarkdownRenderer, { components, children: markdown });
522
+ return /* @__PURE__ */ jsxRuntime.jsx(chunkWBWXP2DN_cjs.MarkdownRenderer, { components, children: markdown });
523
+ }
524
+ function useStreamedArtifact({
525
+ artifacts,
526
+ workspaceId,
527
+ settled,
528
+ clean = chunkKKSSTNJK_cjs.cleanDraftMarkdown,
529
+ configId,
530
+ parseRetry
531
+ }) {
532
+ const artifact = artifacts.find((a) => a.is_complete);
533
+ const { mutateAsync } = useSaveArtifactVersion();
534
+ const [saved, setSaved] = react.useState(null);
535
+ const [saveError, setSaveError] = react.useState(null);
536
+ const [attempt, setAttempt] = react.useState(0);
537
+ const started = react.useRef(null);
538
+ const content = artifact?.content ?? "";
539
+ const title = artifact?.title ?? "Draft";
540
+ const passThrough = !!artifact && isDocumentId(artifact.doc_ext_id);
541
+ const needsSave = settled && !!artifact && !passThrough && !!content.trim() && !!workspaceId;
542
+ react.useEffect(() => {
543
+ const key = `${attempt}:${content}`;
544
+ if (!needsSave || started.current === key) return;
545
+ started.current = key;
546
+ setSaveError(null);
547
+ mutateAsync({
548
+ title,
549
+ content: clean(content),
550
+ workspaceId,
551
+ configId,
552
+ wpType: "artifact"
553
+ }).then((r) => {
554
+ if (r.docId) setSaved({ content, docId: r.docId });
555
+ else setSaveError(new Error("The draft was stored but the server returned no document id"));
556
+ }).catch((e) => setSaveError(e instanceof Error ? e : new Error(String(e))));
557
+ }, [needsSave, content, title, workspaceId, configId, attempt, mutateAsync]);
558
+ const docId = !artifact ? void 0 : passThrough ? artifact.doc_ext_id : saved?.content === content ? saved.docId : void 0;
559
+ const text = useArtifactText(docId, { enabled: settled, retry: parseRetry });
560
+ const { retry: retryText } = text;
561
+ const retry = react.useCallback(() => {
562
+ if (saveError) setAttempt((n) => n + 1);
563
+ else retryText();
564
+ }, [saveError, retryText]);
565
+ let phase;
566
+ if (!settled || !artifact) phase = "streaming";
567
+ else if (saveError) phase = "error";
568
+ else if (!docId) phase = needsSave ? "persisting" : "streaming";
569
+ else if (text.status === "ready" && text.text) phase = "ready";
570
+ else if (text.status === "error" || text.status === "ready") phase = "error";
571
+ else phase = "parsing";
572
+ const error = phase !== "error" ? null : saveError ?? text.error ?? new Error("The document has no text to edit");
573
+ return { phase, artifact, docId, error, retry };
466
574
  }
467
575
 
576
+ Object.defineProperty(exports, "cleanDraftMarkdown", {
577
+ enumerable: true,
578
+ get: function () { return chunkKKSSTNJK_cjs.cleanDraftMarkdown; }
579
+ });
580
+ Object.defineProperty(exports, "promoteBoldTitle", {
581
+ enumerable: true,
582
+ get: function () { return chunkKKSSTNJK_cjs.promoteBoldTitle; }
583
+ });
584
+ Object.defineProperty(exports, "repairParsedTitle", {
585
+ enumerable: true,
586
+ get: function () { return chunkKKSSTNJK_cjs.repairParsedTitle; }
587
+ });
588
+ Object.defineProperty(exports, "stripAgentPreamble", {
589
+ enumerable: true,
590
+ get: function () { return chunkKKSSTNJK_cjs.stripAgentPreamble; }
591
+ });
592
+ Object.defineProperty(exports, "unescapeMarkdown", {
593
+ enumerable: true,
594
+ get: function () { return chunkKKSSTNJK_cjs.unescapeMarkdown; }
595
+ });
596
+ Object.defineProperty(exports, "unwrapCitationLinks", {
597
+ enumerable: true,
598
+ get: function () { return chunkKKSSTNJK_cjs.unwrapCitationLinks; }
599
+ });
468
600
  Object.defineProperty(exports, "buildHybridRedlineMarkdown", {
469
601
  enumerable: true,
470
602
  get: function () { return chunkVJWAP2HJ_cjs.buildHybridRedlineMarkdown; }
@@ -477,6 +609,7 @@ Object.defineProperty(exports, "revertRedlineRegion", {
477
609
  enumerable: true,
478
610
  get: function () { return chunkVJWAP2HJ_cjs.revertRedlineRegion; }
479
611
  });
612
+ exports.DEFAULT_ARTIFACT_TEXT_RETRY = DEFAULT_ARTIFACT_TEXT_RETRY;
480
613
  exports.buildVersionChain = buildVersionChain;
481
614
  exports.flattenChunks = flattenChunks;
482
615
  exports.isDocumentId = isDocumentId;
@@ -489,6 +622,7 @@ exports.useArtifactText = useArtifactText;
489
622
  exports.useArtifactVersions = useArtifactVersions;
490
623
  exports.useRedline = useRedline;
491
624
  exports.useSaveArtifactVersion = useSaveArtifactVersion;
625
+ exports.useStreamedArtifact = useStreamedArtifact;
492
626
  exports.versionLabel = versionLabel;
493
627
  //# sourceMappingURL=index.cjs.map
494
628
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/artifacts/redline-engine.ts","../../src/artifacts/useRedline.ts","../../src/artifacts/versions.ts","../../src/artifacts/useArtifactEditSession.ts","../../src/artifacts/useArtifactSession.ts","../../src/artifacts/renderArtifactMarkdown.tsx"],"names":["buildHybridRedlineMarkdown","buildHybridRedlineWithRegions","revertRedlineRegion","useState","useRef","useEffect","useCallback","useMemo","content","useParsedDocument","useDocuments","useArbi","useQueryClient","useMutation","arbiQueryKeys","jsx","MarkdownRenderer"],"mappings":";;;;;;;;;;;;AAsBO,IAAM,uBAAA,GAAyC;AAAA,EACpD,YAAA,EAAcA,4CAAA;AAAA,EACd,uBAAA,EAAyBC,+CAAA;AAAA,EACzB,YAAA,EAAcC;AAChB;ACSO,SAAS,UAAA,CAAW;AAAA,EACzB,QAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA,GAAY,KAAA;AAAA,EACZ,WAAA,GAAc,KAAA;AAAA,EACd,MAAA,GAAS;AACX,CAAA,EAAwC;AACtC,EAAA,MAAM,CAAC,OAAO,QAAQ,CAAA,GAAIC,eAAuB,EAAE,IAAA,EAAM,QAAQ,CAAA;AACjE,EAAA,MAAM,YAAA,GAAeC,aAAO,CAAC,CAAA;AAE7B,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,QAAA,KAAa,MAAA,IAAa,WAAA,KAAgB,MAAA,EAAW;AACvD,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA;AACzB,MAAA;AAAA,IACF;AACA,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,WAAA,EAAa,CAAA;AAC9B,MAAA;AAAA,IACF;AACA,IAAA,IAAI,QAAA,KAAa,IAAA,IAAQ,WAAA,KAAgB,IAA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MAAA;AAAA,QAClB,MAAA,EAAQ,MAAM,KAAK,OAAA,CAAQ,IAAA,EAAK;AAAA,QAChC,SAAA,EAAW,MAAM,OAAA,CAAQ,OAAA,EAAQ;AAAA,QACjC,eAAe,OAAA,CAAQ,WAAA;AAAA,QACvB,sBAAsB,MAAM,OAAA,CAAQ,mBAAA,CAAoB,CAAC,QAAQ,gBAAgB;AAAA,OACnF;AAAA,MACA,WAAA,EAAa;AAAA,QACX,UAAU,OAAA,CAAQ,OAAA;AAAA,QAClB,UAAU,OAAA,CAAQ,MAAA;AAAA,QAClB,cAAc,OAAA,CAAQ;AAAA,OACxB;AAAA,MACA,YAAA,EAAc;AAAA,QACZ,OAAO,OAAA,CAAQ,KAAA;AAAA,QACf,UAAU,CAAC,QAAA,KAAa,KAAK,OAAA,CAAQ,aAAa,QAAQ;AAAA;AAC5D,KACF,CAAA;AAAA,IACA,CAAC,OAAA,EAAS,OAAA,EAAS,SAAA,EAAW,OAAA,EAAS,UAAU,KAAK;AAAA,GACxD;AACF;AC3RO,SAAS,sBAAA,CACd,UACA,UAAA,EACW;AACX,EAAA,uBAAOQ,cAAA,CAACC,kCAAA,EAAA,EAAiB,UAAA,EAAyB,QAAA,EAAA,QAAA,EAAS,CAAA;AAC7D","file":"index.cjs","sourcesContent":["import {\n buildHybridRedlineMarkdown,\n buildHybridRedlineWithRegions,\n revertRedlineRegion,\n type RedlineWithRegions,\n} from './redline-diff'\n\n/**\n * Where a redline is computed. The default runs on the calling thread; a host with large\n * documents passes an engine backed by a Web Worker (for example a Comlink proxy exposing the same\n * three functions) so typing never waits on a diff.\n */\nexport interface RedlineEngine {\n buildRedline(baseText: string, compareText: string): string | Promise<string>\n buildRedlineWithRegions(\n baseText: string,\n compareText: string\n ): RedlineWithRegions | Promise<RedlineWithRegions>\n revertRegion(baseText: string, compareText: string, regionId: string): string | Promise<string>\n}\n\n/** Main-thread engine: the pure functions of `redline-diff`. */\nexport const mainThreadRedlineEngine: RedlineEngine = {\n buildRedline: buildHybridRedlineMarkdown,\n buildRedlineWithRegions: buildHybridRedlineWithRegions,\n revertRegion: revertRedlineRegion,\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { RedlineRegion } from './redline-diff'\nimport { mainThreadRedlineEngine, type RedlineEngine } from './redline-engine'\n\n/** What a redline view can show. Mirrors the status parts of `@arbidocs/blocks/artifacts`. */\nexport type RedlineState =\n | { kind: 'idle' }\n | { kind: 'computing' }\n | { kind: 'ready'; markdown: string; regions: RedlineRegion[] }\n | { kind: 'identical' }\n | { kind: 'unavailable' }\n\nexport interface UseRedlineOptions {\n /** The older side. `null` means the text could not be loaded; `undefined` means not chosen. */\n baseText: string | null | undefined\n /** The newer side (a loaded version, or the live edit buffer). */\n compareText: string | null | undefined\n /** Either text is still being fetched. */\n isLoading?: boolean\n /** Tag every change with a stable id so a view can offer per-change undo. */\n withRegions?: boolean\n /** Defaults to the main thread; pass a worker-backed engine for big documents. */\n engine?: RedlineEngine\n}\n\nexport interface UseRedlineResult {\n state: RedlineState\n /** Undo one change: resolves with the compare text rebuilt without it (null if nothing changed). */\n revertRegion: (regionId: string) => Promise<string | null>\n}\n\n/**\n * Track-changes between two texts. Stale results are dropped when the inputs change mid-compute,\n * and a failed diff reports `unavailable` instead of throwing into the render.\n */\nexport function useRedline({\n baseText,\n compareText,\n isLoading = false,\n withRegions = false,\n engine = mainThreadRedlineEngine,\n}: UseRedlineOptions): UseRedlineResult {\n const [state, setState] = useState<RedlineState>({ kind: 'idle' })\n const requestIdRef = useRef(0)\n\n useEffect(() => {\n if (baseText === undefined || compareText === undefined) {\n setState({ kind: 'idle' })\n return\n }\n if (isLoading) {\n setState({ kind: 'computing' })\n return\n }\n if (baseText === null || compareText === null) {\n setState({ kind: 'unavailable' })\n return\n }\n if (baseText === compareText) {\n setState({ kind: 'identical' })\n return\n }\n\n const id = ++requestIdRef.current\n let cancelled = false\n setState({ kind: 'computing' })\n Promise.resolve(\n withRegions\n ? engine.buildRedlineWithRegions(baseText, compareText)\n : Promise.resolve(engine.buildRedline(baseText, compareText)).then((markdown) => ({\n markdown,\n regions: [] as RedlineRegion[],\n }))\n )\n .then((result) => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'ready', markdown: result.markdown, regions: result.regions })\n })\n .catch(() => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'unavailable' })\n })\n return () => {\n cancelled = true\n }\n }, [baseText, compareText, isLoading, withRegions, engine])\n\n // The latest texts, so `revertRegion` stays referentially stable while the user types.\n const latest = useRef({ baseText, compareText })\n useEffect(() => {\n latest.current = { baseText, compareText }\n }, [baseText, compareText])\n\n const revertRegion = useCallback(\n async (regionId: string): Promise<string | null> => {\n const { baseText: base, compareText: compare } = latest.current\n if (!base || !compare) return null\n try {\n const next = await engine.revertRegion(base, compare, regionId)\n return next !== compare ? next : null\n } catch {\n return null\n }\n },\n [engine]\n )\n\n return useMemo(() => ({ state, revertRegion }), [state, revertRegion])\n}\n","/**\n * Version lineage of an artifact. Every save creates a NEW document whose `parent_ext_id` is the\n * version it was saved from, so a lineage is a tree (a save from an old version is a deliberate\n * branch). Computed from a document list the host already has; no extra request.\n */\n\n/** The fields of a workspace document the lineage needs (structurally a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n parent_ext_id?: string | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n id: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** The version this one was saved from. */\n parentId?: string | null\n}\n\n/**\n * The whole lineage of `docId` (root first, then oldest to newest), or `[]` when the document is\n * not in `docs`. Cycle-safe.\n */\nexport function buildVersionChain<T extends VersionedDoc>(\n docs: readonly T[],\n docId: string | null | undefined\n): T[] {\n if (!docId) return []\n const byId = new Map<string, T>()\n for (const d of docs) if (d.external_id) byId.set(d.external_id, d)\n\n const current = byId.get(docId)\n if (!current) return []\n\n let root = current\n const up = new Set<string>()\n while (\n root.parent_ext_id &&\n byId.has(root.parent_ext_id) &&\n root.external_id &&\n !up.has(root.external_id)\n ) {\n up.add(root.external_id)\n root = byId.get(root.parent_ext_id) as T\n }\n\n const byParent = new Map<string, T[]>()\n for (const d of docs) {\n if (d.parent_ext_id) {\n const siblings = byParent.get(d.parent_ext_id) ?? []\n siblings.push(d)\n byParent.set(d.parent_ext_id, siblings)\n }\n }\n const out: T[] = []\n const visited = new Set<string>()\n const walk = (d: T): void => {\n if (!d.external_id || visited.has(d.external_id)) return\n visited.add(d.external_id)\n out.push(d)\n for (const child of byParent.get(d.external_id) ?? []) walk(child)\n }\n walk(root)\n\n out.sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? ''))\n return out\n}\n\n/** The lineage of `docId` as plain version rows. */\nexport function toArtifactVersions(chain: readonly VersionedDoc[]): ArtifactVersion[] {\n return chain.flatMap((d) =>\n d.external_id\n ? [\n {\n id: d.external_id,\n name: d.file_name ?? '',\n createdAt: d.created_at ?? '',\n parentId: d.parent_ext_id,\n },\n ]\n : []\n )\n}\n\n/**\n * \"v2\": the 1-based position of `docId` in its lineage. `null` when there is nothing to tell apart\n * (the lineage is just this document, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n docId: string | null | undefined\n): string | null {\n if (!docId || versions.length <= 1) return null\n const index = versions.findIndex((v) => v.id === docId)\n return index === -1 ? null : `v${index + 1}`\n}\n\n/** Join parsed chunks into one markdown text (blank line between chunks). */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined\n): string {\n return (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useRedline, type UseRedlineResult } from './useRedline'\nimport type { RedlineEngine } from './redline-engine'\n\n/** What a save reports back. `docId` is the new version when the backend already knows it. */\nexport interface ArtifactSaveResult {\n docId?: string\n /** 1-based number of the version that was just saved (1 for the first save of a draft). */\n version?: number\n}\n\nexport interface ArtifactEditSessionOptions {\n /** The artifact being edited. Changing it discards the buffer and any comparison. */\n docId: string | null | undefined\n /**\n * The saved text of the open version. `undefined` while it loads; whenever it changes the\n * baseline follows it (a version arriving from the realtime channel, a finished stream).\n */\n baseline: string | undefined\n /**\n * A new document the user types from scratch: open straight in the editor, seeded with\n * `initialContent`, instead of showing a read-only view. Read when `docId` changes.\n */\n startEditing?: boolean\n initialContent?: string\n /** The version this one was saved from. Offering \"compare with previous\" needs it. */\n parentId?: string | null\n /** Controlled comparison target. Omit for an uncontrolled one the session owns. */\n compareId?: string | null\n onCompareChange?: (id: string | null) => void\n /** The saved text of the compare target (the older side of the diff). */\n compareText?: string | null\n compareLoading?: boolean\n /** Starting a comparison opens the editor with track changes on (default true). */\n compareOpensEditor?: boolean\n /** Persist the buffer as a NEW version. Rejecting keeps the buffer so nothing is lost. */\n save: (content: string) => Promise<ArtifactSaveResult | void>\n onSaved?: (result: ArtifactSaveResult, content: string) => void\n onSaveError?: (error: unknown) => void\n /** Every buffer change (a host keeps a draft store in sync with it). */\n onContentChange?: (content: string) => void\n /** The unsaved-changes flag, for a host that warns before a panel is closed. */\n onDirtyChange?: (dirty: boolean) => void\n /** Where the diff runs. Defaults to the main thread. */\n redlineEngine?: RedlineEngine\n /** Typing is never debounced; the diff trails the buffer by this long. Default 300ms. */\n diffDelayMs?: number\n}\n\nexport interface ArtifactEditSession {\n isEditing: boolean\n /** The saved text of the open version. */\n baseline: string\n /** The text in the editor (the baseline until the first edit). */\n content: string\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n compareId: string | null\n showTrackChanges: boolean\n /** Track changes between the compare target and the (debounced) buffer. */\n redline: UseRedlineResult\n startEdit: () => void\n /** Discard the buffer and any comparison; back to the rendered view. */\n cancel: () => void\n /** Save the buffer as a new version. Resolves false when it failed (the buffer is kept). */\n save: () => Promise<boolean>\n /** The editor's `onChange`; also replaces the buffer (for example after an undo-this-change). */\n change: (markdown: string) => void\n /** The editor's `onNormalized`: adopt its canonical form as the baseline so Save does not fire. */\n normalized: (markdown: string) => void\n /** Compare with the previous version (when no id is given). */\n compare: (id?: string) => void\n stopCompare: () => void\n setShowTrackChanges: (show: boolean) => void\n /** Undo one tracked change in the buffer. */\n revertRegion: (regionId: string) => Promise<void>\n}\n\n/**\n * The state machine of an artifact edit session, with no SDK and no network: the edit buffer and\n * its baseline, the dirty flag, immutable-version saves and a track-changes comparison. A host\n * supplies the saved text and a `save` function (see `useArtifactSession` for the SDK binding).\n */\nexport function useArtifactEditSession(options: ArtifactEditSessionOptions): ArtifactEditSession {\n const {\n docId,\n baseline: loadedBaseline,\n startEditing = false,\n initialContent,\n parentId,\n compareId: controlledCompareId,\n onCompareChange,\n compareText,\n compareLoading = false,\n compareOpensEditor = true,\n save: persist,\n onSaved,\n onSaveError,\n onContentChange,\n onDirtyChange,\n redlineEngine,\n diffDelayMs = 300,\n } = options\n\n const [isEditing, setIsEditing] = useState(false)\n const [baseline, setBaseline] = useState('')\n const [buffer, setBuffer] = useState('')\n const [isSaving, setIsSaving] = useState(false)\n const [showTrackChanges, setShowTrackChanges] = useState(false)\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const controlled = controlledCompareId !== undefined\n const compareId = controlled ? controlledCompareId : ownCompareId\n\n const setCompareId = useCallback(\n (id: string | null) => {\n if (!controlled) setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [controlled, onCompareChange]\n )\n\n // The latest values for callbacks that must not change identity while the user types.\n const latest = useRef({ buffer, baseline, isEditing, initialContent })\n latest.current = { buffer, baseline, isEditing, initialContent }\n\n // The baseline follows the loaded text. A draft has none and seeds itself below.\n useEffect(() => {\n if (loadedBaseline !== undefined) setBaseline(loadedBaseline)\n }, [loadedBaseline])\n\n // Another artifact: drop stale edits and comparison. A new typed document starts in the editor.\n useEffect(() => {\n if (startEditing) {\n const seed = latest.current.initialContent ?? ''\n setIsEditing(true)\n setBaseline(seed)\n setBuffer(seed)\n } else {\n setIsEditing(false)\n setBuffer('')\n }\n setCompareId(null)\n setShowTrackChanges(false)\n // Only the identity of the artifact resets the session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [docId])\n\n const startEdit = useCallback(() => {\n setBuffer(latest.current.baseline)\n setIsEditing(true)\n }, [])\n\n const stopCompare = useCallback(() => {\n setCompareId(null)\n setShowTrackChanges(false)\n }, [setCompareId])\n\n const cancel = useCallback(() => {\n setIsEditing(false)\n setBuffer('')\n stopCompare()\n }, [stopCompare])\n\n const compare = useCallback(\n (id?: string) => {\n const target = id ?? parentId\n if (target) setCompareId(target)\n },\n [parentId, setCompareId]\n )\n\n // Comparing and editing are one surface: a comparison opens the editor with the diff showing,\n // like Word's Compare yields tracked changes you can keep typing through.\n const hasBaseline = baseline !== ''\n useEffect(() => {\n if (!compareId || !compareOpensEditor || !hasBaseline) return\n if (!latest.current.isEditing) startEdit()\n setShowTrackChanges(true)\n }, [compareId, compareOpensEditor, hasBaseline, startEdit])\n\n const save = useCallback(async (): Promise<boolean> => {\n const content = latest.current.buffer\n setIsSaving(true)\n try {\n const result = (await persist(content)) ?? {}\n setBaseline(content)\n setIsEditing(false)\n stopCompare()\n onSaved?.(result, content)\n return true\n } catch (error) {\n onSaveError?.(error)\n return false\n } finally {\n setIsSaving(false)\n }\n }, [persist, stopCompare, onSaved, onSaveError])\n\n const content = buffer || baseline\n const hasChanges = isEditing && !!buffer && buffer !== baseline\n useEffect(() => {\n onDirtyChange?.(hasChanges)\n return () => onDirtyChange?.(false)\n }, [hasChanges, onDirtyChange])\n\n const setContent = useCallback(\n (markdown: string) => {\n setBuffer(markdown)\n onContentChange?.(markdown)\n },\n [onContentChange]\n )\n const normalized = useCallback((markdown: string) => {\n setBaseline(markdown)\n setBuffer(markdown)\n }, [])\n\n // The diff trails the buffer so it runs on a settled text.\n const [diffContent, setDiffContent] = useState(content)\n useEffect(() => {\n const id = setTimeout(() => setDiffContent(content), diffDelayMs)\n return () => clearTimeout(id)\n }, [content, diffDelayMs])\n\n const redline = useRedline({\n baseText: compareId ? compareText : undefined,\n compareText: compareId ? diffContent || baseline : undefined,\n isLoading: compareLoading,\n withRegions: true,\n engine: redlineEngine,\n })\n const { revertRegion: revertInRedline } = redline\n const revertRegion = useCallback(\n async (regionId: string): Promise<void> => {\n const next = await revertInRedline(regionId)\n if (next !== null) setContent(next)\n },\n [revertInRedline, setContent]\n )\n\n return useMemo(\n () => ({\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n canCompare: !!parentId && !compareId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n change: setContent,\n normalized,\n compare,\n stopCompare,\n setShowTrackChanges,\n revertRegion,\n }),\n [\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n parentId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n setContent,\n normalized,\n compare,\n stopCompare,\n revertRegion,\n ]\n )\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useDocuments, useParsedDocument } from '../hooks'\nimport {\n buildVersionChain,\n isDocumentId,\n flattenChunks,\n toArtifactVersions,\n versionLabel,\n type ArtifactVersion,\n} from './versions'\nimport {\n useArtifactEditSession,\n type ArtifactEditSession,\n type ArtifactEditSessionOptions,\n type ArtifactSaveResult,\n} from './useArtifactEditSession'\n\n/** The saved markdown of a document (its parsed chunks, joined). */\nexport function useArtifactText(\n docId: string | null | undefined,\n options?: { enabled?: boolean }\n): { text: string | null | undefined; isLoading: boolean } {\n // A local draft has no backend document: asking for its text would be a 422.\n const real = isDocumentId(docId)\n const { data, isLoading, isError } = useParsedDocument(real ? docId : undefined, 'marker', {\n enabled: (options?.enabled ?? true) && real,\n })\n const text = useMemo(() => {\n if (!real) return undefined\n if (isError) return null\n if (!data) return undefined\n return data.chunks?.length ? flattenChunks(data.chunks) : null\n }, [real, data, isError])\n return { text, isLoading: real && isLoading }\n}\n\n/** The version lineage of an artifact in a workspace, oldest first. */\nexport function useArtifactVersions(\n workspaceId: string | undefined,\n docId: string | null | undefined\n): ArtifactVersion[] {\n const { data: documents } = useDocuments(workspaceId)\n return useMemo(\n () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),\n [documents, docId]\n )\n}\n\nexport interface SaveArtifactVersionInput {\n /** File name of the new version (`.md` is added when missing). */\n title: string\n content: string\n /** The version this one is saved from; omit for a first version. */\n parentId?: string | null\n /** The processing config (auto-title, parsing) to run the upload with. */\n configId?: string | null\n /** `artifact` (default) for AI-style drafts; `source` for a document the user typed. */\n wpType?: 'artifact' | 'source'\n}\n\n/**\n * Save markdown as a NEW immutable version (a child document of `parentId`) and refresh the\n * workspace document list so the version list picks it up. The id of the new version is often not\n * known yet (the document is parsed asynchronously); it then arrives through the list.\n */\nexport function useSaveArtifactVersion() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation<\n ArtifactSaveResult,\n Error,\n SaveArtifactVersionInput & { workspaceId?: string }\n >({\n mutationFn: async ({ title, content, parentId, configId, wpType, workspaceId }) => {\n // The backend classifies uploads by extension: a title without one is silently dropped.\n const fileName = /\\.md$/i.test(title) ? title : `${title}.md`\n const result = await arbi.documents.uploadFile(\n new Blob([content], { type: 'text/markdown' }),\n fileName,\n {\n wpType: wpType ?? 'artifact',\n parentExtId: parentId ?? undefined,\n configExtId: configId ?? undefined,\n }\n )\n if (workspaceId) {\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documents(workspaceId) })\n }\n return { docId: result.doc_ext_ids?.[0] }\n },\n })\n}\n\nexport interface ArtifactSessionOptions extends Pick<\n ArtifactEditSessionOptions,\n | 'onSaved'\n | 'onSaveError'\n | 'onCompareChange'\n | 'compareId'\n | 'compareOpensEditor'\n | 'redlineEngine'\n | 'onDirtyChange'\n> {\n workspaceId: string | undefined\n /**\n * The open version, or the placeholder id of an unsaved local draft (anything that is not a\n * backend document id, i.e. does not start with `doc`).\n */\n docId: string | null | undefined\n /**\n * The text of a local draft (nothing is fetched for it). The FIRST save uploads it as a real\n * document with no parent and the session switches to the new id; later saves chain from it.\n */\n draftContent?: string\n /** Name for saved versions. Defaults to the open version's file name, else \"Untitled\". */\n title?: string\n /** Processing config for saved versions. */\n configId?: string | null\n}\n\n/** Everything `ArtifactEditor` (`@arbidocs/blocks/artifacts`) takes from a session, flat. */\nexport interface ArtifactSessionView {\n content: string\n isEditing: boolean\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n comparing: boolean\n compareId: string | null\n showTrackChanges: boolean\n versions: ArtifactVersion[]\n currentVersionId: string\n onStartEdit: () => void\n onCancel: () => void\n onSave: () => void\n onCompare: () => void\n onStopCompare: () => void\n onToggleTrackChanges: () => void\n}\n\nexport interface ArtifactSession extends ArtifactEditSession {\n /** The open document: the new real id once a local draft has been saved. */\n docId: string | null | undefined\n /** The open version is an unsaved local draft (no backend document yet). */\n isLocal: boolean\n isLoading: boolean\n versions: ArtifactVersion[]\n /** \"v2\" for any version in the lineage. */\n labelOf: (id: string | null | undefined) => string | null\n /** Props for `<ArtifactEditor>`. */\n view: ArtifactSessionView\n /** Props for `<ArtifactMarkdownEditor>` (`@arbidocs/blocks/artifacts/editor`). */\n editorProps: {\n markdown: string\n onChange: (markdown: string) => void\n onNormalized: (markdown: string) => void\n }\n /** Props for `<ArtifactRedlineView>`. */\n redlineProps: {\n state: ArtifactEditSession['redline']['state']\n onRevert: (regionId: string) => void\n }\n}\n\n/**\n * Edit an artifact through the SDK: load it, edit it, save it as a new version, list its versions\n * and compare any two with track changes. Needs an `<ArbiProvider>` and a selected workspace.\n *\n * ```tsx\n * const session = useArtifactSession({ workspaceId, docId, onSaved: ({ docId }) => docId && open(docId) })\n * <ArtifactEditor {...session.view} onOpenVersion={open}\n * editor={<ArtifactMarkdownEditor {...session.editorProps} />}\n * redline={<ArtifactRedlineView {...session.redlineProps} />} />\n * ```\n */\nexport function useArtifactSession(options: ArtifactSessionOptions): ArtifactSession {\n const {\n workspaceId,\n docId: hostDocId,\n draftContent,\n title,\n configId,\n compareId,\n onCompareChange,\n onSaved,\n ...passthrough\n } = options\n // A saved local draft becomes this real document; another host docId resets it.\n const [saved, setSaved] = useState<{\n forId: string | null | undefined\n id: string\n text: string\n } | null>(null)\n const adopted = saved && saved.forId === hostDocId ? saved : null\n const docId = adopted?.id ?? hostDocId\n const isLocal = !isDocumentId(docId)\n\n // Owned here (not in the edit session) because the compare target's text must be loaded first.\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const activeCompareId = compareId === undefined ? ownCompareId : compareId\n const changeCompare = useCallback(\n (id: string | null) => {\n setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [onCompareChange]\n )\n\n const { text, isLoading } = useArtifactText(docId)\n const versions = useArtifactVersions(workspaceId, isLocal ? null : docId)\n const { text: compareText, isLoading: compareLoading } = useArtifactText(activeCompareId, {\n enabled: !!activeCompareId,\n })\n const saveVersion = useSaveArtifactVersion()\n const current = versions.find((v) => v.id === docId)\n\n const save = useCallback(\n async (content: string) => {\n const result = await saveVersion.mutateAsync({\n title: title ?? current?.name ?? 'Untitled',\n content,\n parentId: isLocal ? null : docId,\n configId,\n workspaceId,\n })\n return { ...result, version: isLocal ? 1 : versions.length + 1 }\n },\n [saveVersion, title, current?.name, isLocal, docId, configId, workspaceId, versions.length]\n )\n\n const handleSaved = useCallback(\n (result: ArtifactSaveResult, content: string) => {\n // A host that keeps passing the local draft's placeholder id: follow every save to the real\n // document it created (the first save creates version 1, later ones chain from it).\n if (!isDocumentId(hostDocId) && result.docId)\n setSaved({ forId: hostDocId, id: result.docId, text: content })\n onSaved?.(result, content)\n },\n [hostDocId, onSaved]\n )\n\n const session = useArtifactEditSession({\n ...passthrough,\n docId,\n // A local draft has only its own text; a just-saved one shows what was saved until the parsed\n // text of the new document arrives.\n baseline: text ?? (isLocal ? draftContent : adopted?.text),\n parentId: current?.parentId,\n compareId: activeCompareId,\n onCompareChange: changeCompare,\n compareText,\n compareLoading,\n save,\n onSaved: handleSaved,\n })\n\n const { redline } = session\n return useMemo<ArtifactSession>(\n () => ({\n ...session,\n docId,\n isLocal,\n isLoading,\n versions,\n labelOf: (id) => versionLabel(versions, id),\n view: {\n content: session.baseline,\n isEditing: session.isEditing,\n hasChanges: session.hasChanges,\n isSaving: session.isSaving,\n canCompare: session.canCompare,\n comparing: !!session.compareId,\n compareId: session.compareId,\n showTrackChanges: session.showTrackChanges,\n versions,\n currentVersionId: docId ?? '',\n onStartEdit: session.startEdit,\n onCancel: session.cancel,\n onSave: () => void session.save(),\n onCompare: () => session.compare(),\n onStopCompare: session.stopCompare,\n onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges),\n },\n editorProps: {\n markdown: session.content,\n onChange: session.change,\n onNormalized: session.normalized,\n },\n redlineProps: {\n state: redline.state,\n onRevert: (regionId) => void session.revertRegion(regionId),\n },\n }),\n [session, redline, isLoading, isLocal, versions, docId]\n )\n}\n","import type { ComponentPropsWithoutRef, FC, ReactNode } from 'react'\nimport { MarkdownRenderer } from '../ai/MarkdownRenderer'\n\n/** The `<del>` / `<ins>` renderers `ArtifactRedlineView` hands to a markdown renderer. */\nexport interface ArtifactRedlineComponents {\n del: FC<ComponentPropsWithoutRef<'del'> & { 'data-cid'?: string }>\n ins: FC<ComponentPropsWithoutRef<'ins'> & { 'data-cid'?: string }>\n}\n\n/**\n * The kit's markdown renderer as the `renderMarkdown` slot of `ArtifactEditor` and\n * `ArtifactRedlineView`: full markdown (tables, lists, code) plus the raw `<del>` / `<ins>` tags\n * of a redline.\n */\nexport function renderArtifactMarkdown(\n markdown: string,\n components?: ArtifactRedlineComponents\n): ReactNode {\n return <MarkdownRenderer components={components}>{markdown}</MarkdownRenderer>\n}\n"]}
1
+ {"version":3,"sources":["../../src/artifacts/redline-engine.ts","../../src/artifacts/useRedline.ts","../../src/artifacts/versions.ts","../../src/artifacts/useArtifactEditSession.ts","../../src/artifacts/useArtifactText.ts","../../src/artifacts/useArtifactSession.ts","../../src/artifacts/renderArtifactMarkdown.tsx","../../src/artifacts/useStreamedArtifact.ts"],"names":["buildHybridRedlineMarkdown","buildHybridRedlineWithRegions","revertRedlineRegion","useState","useRef","useEffect","useCallback","useMemo","repairParsedTitle","unescapeMarkdown","content","useArbi","useQuery","arbiQueryKeys","useDocuments","useQueryClient","useMutation","jsx","MarkdownRenderer","cleanDraftMarkdown"],"mappings":";;;;;;;;;;;;AAsBO,IAAM,uBAAA,GAAyC;AAAA,EACpD,YAAA,EAAcA,4CAAA;AAAA,EACd,uBAAA,EAAyBC,+CAAA;AAAA,EACzB,YAAA,EAAcC;AAChB;ACSO,SAAS,UAAA,CAAW;AAAA,EACzB,QAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA,GAAY,KAAA;AAAA,EACZ,WAAA,GAAc,KAAA;AAAA,EACd,MAAA,GAAS;AACX,CAAA,EAAwC;AACtC,EAAA,MAAM,CAAC,OAAO,QAAQ,CAAA,GAAIC,eAAuB,EAAE,IAAA,EAAM,QAAQ,CAAA;AACjE,EAAA,MAAM,YAAA,GAAeC,aAAO,CAAC,CAAA;AAE7B,EAAAC,eAAA,CAAU,MAAM;AACd,IAAA,IAAI,QAAA,KAAa,MAAA,IAAa,WAAA,KAAgB,MAAA,EAAW;AACvD,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA;AACzB,MAAA;AAAA,IACF;AACA,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,QAAA,CAAS,EAAE,IAAA,EAAM,WAAA,EAAa,CAAA;AAC9B,MAAA;AAAA,IACF;AACA,IAAA,IAAI,QAAA,KAAa,IAAA,IAAQ,WAAA,KAAgB,IAA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Regions,\n} from './redline-diff'\n\n/**\n * Where a redline is computed. The default runs on the calling thread; a host with large\n * documents passes an engine backed by a Web Worker (for example a Comlink proxy exposing the same\n * three functions) so typing never waits on a diff.\n */\nexport interface RedlineEngine {\n buildRedline(baseText: string, compareText: string): string | Promise<string>\n buildRedlineWithRegions(\n baseText: string,\n compareText: string\n ): RedlineWithRegions | Promise<RedlineWithRegions>\n revertRegion(baseText: string, compareText: string, regionId: string): string | Promise<string>\n}\n\n/** Main-thread engine: the pure functions of `redline-diff`. */\nexport const mainThreadRedlineEngine: RedlineEngine = {\n buildRedline: buildHybridRedlineMarkdown,\n buildRedlineWithRegions: buildHybridRedlineWithRegions,\n revertRegion: revertRedlineRegion,\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { RedlineRegion } from './redline-diff'\nimport { mainThreadRedlineEngine, type RedlineEngine } from './redline-engine'\n\n/** What a redline view can show. Mirrors the status parts of `@arbidocs/blocks/artifacts`. */\nexport type RedlineState =\n | { kind: 'idle' }\n | { kind: 'computing' }\n | { kind: 'ready'; markdown: string; regions: RedlineRegion[] }\n | { kind: 'identical' }\n | { kind: 'unavailable' }\n\nexport interface UseRedlineOptions {\n /** The older side. `null` means the text could not be loaded; `undefined` means not chosen. */\n baseText: string | null | undefined\n /** The newer side (a loaded version, or the live edit buffer). */\n compareText: string | null | undefined\n /** Either text is still being fetched. */\n isLoading?: boolean\n /** Tag every change with a stable id so a view can offer per-change undo. */\n withRegions?: boolean\n /** Defaults to the main thread; pass a worker-backed engine for big documents. */\n engine?: RedlineEngine\n}\n\nexport interface UseRedlineResult {\n state: RedlineState\n /** Undo one change: resolves with the compare text rebuilt without it (null if nothing changed). */\n revertRegion: (regionId: string) => Promise<string | null>\n}\n\n/**\n * Track-changes between two texts. Stale results are dropped when the inputs change mid-compute,\n * and a failed diff reports `unavailable` instead of throwing into the render.\n */\nexport function useRedline({\n baseText,\n compareText,\n isLoading = false,\n withRegions = false,\n engine = mainThreadRedlineEngine,\n}: UseRedlineOptions): UseRedlineResult {\n const [state, setState] = useState<RedlineState>({ kind: 'idle' })\n const requestIdRef = useRef(0)\n\n useEffect(() => {\n if (baseText === undefined || compareText === undefined) {\n setState({ kind: 'idle' })\n return\n }\n if (isLoading) {\n setState({ kind: 'computing' })\n return\n }\n if (baseText === null || compareText === null) {\n setState({ kind: 'unavailable' })\n return\n }\n if (baseText === compareText) {\n setState({ kind: 'identical' })\n return\n }\n\n const id = ++requestIdRef.current\n let cancelled = false\n setState({ kind: 'computing' })\n Promise.resolve(\n withRegions\n ? engine.buildRedlineWithRegions(baseText, compareText)\n : Promise.resolve(engine.buildRedline(baseText, compareText)).then((markdown) => ({\n markdown,\n regions: [] as RedlineRegion[],\n }))\n )\n .then((result) => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'ready', markdown: result.markdown, regions: result.regions })\n })\n .catch(() => {\n if (cancelled || id !== requestIdRef.current) return\n setState({ kind: 'unavailable' })\n })\n return () => {\n cancelled = true\n }\n }, [baseText, compareText, isLoading, withRegions, engine])\n\n // The latest texts, so `revertRegion` stays referentially stable while the user types.\n const latest = useRef({ baseText, compareText })\n useEffect(() => {\n latest.current = { baseText, compareText }\n }, [baseText, compareText])\n\n const revertRegion = useCallback(\n async (regionId: string): Promise<string | null> => {\n const { baseText: base, compareText: compare } = latest.current\n if (!base || !compare) return null\n try {\n const next = await engine.revertRegion(base, compare, regionId)\n return next !== compare ? next : null\n } catch {\n return null\n }\n },\n [engine]\n )\n\n return useMemo(() => ({ state, revertRegion }), [state, revertRegion])\n}\n","/**\n * Version lineage of an artifact. Every save creates a NEW document whose `parent_ext_id` is the\n * version it was saved from, so a lineage is a tree (a save from an old version is a deliberate\n * branch). Computed from a document list the host already has; no extra request.\n */\n\nimport { repairParsedTitle, unescapeMarkdown } from '../ai/stored-markdown'\n\n/** The fields of a workspace document the lineage needs (structurally a subset of the API type). */\nexport interface VersionedDoc {\n external_id?: string | null\n parent_ext_id?: string | null\n file_name?: string | null\n created_at?: string | null\n}\n\n/** One row of a version list. Matches `VersionEntry` of `@arbidocs/blocks/artifacts`. */\nexport interface ArtifactVersion {\n id: string\n /** File name as stored. */\n name: string\n /** ISO timestamp. */\n createdAt: string\n /** The version this one was saved from. */\n parentId?: string | null\n}\n\n/**\n * The whole lineage of `docId` (root first, then oldest to newest), or `[]` when the document is\n * not in `docs`. Cycle-safe.\n */\nexport function buildVersionChain<T extends VersionedDoc>(\n docs: readonly T[],\n docId: string | null | undefined\n): T[] {\n if (!docId) return []\n const byId = new Map<string, T>()\n for (const d of docs) if (d.external_id) byId.set(d.external_id, d)\n\n const current = byId.get(docId)\n if (!current) return []\n\n let root = current\n const up = new Set<string>()\n while (\n root.parent_ext_id &&\n byId.has(root.parent_ext_id) &&\n root.external_id &&\n !up.has(root.external_id)\n ) {\n up.add(root.external_id)\n root = byId.get(root.parent_ext_id) as T\n }\n\n const byParent = new Map<string, T[]>()\n for (const d of docs) {\n if (d.parent_ext_id) {\n const siblings = byParent.get(d.parent_ext_id) ?? []\n siblings.push(d)\n byParent.set(d.parent_ext_id, siblings)\n }\n }\n const out: T[] = []\n const visited = new Set<string>()\n const walk = (d: T): void => {\n if (!d.external_id || visited.has(d.external_id)) return\n visited.add(d.external_id)\n out.push(d)\n for (const child of byParent.get(d.external_id) ?? []) walk(child)\n }\n walk(root)\n\n out.sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? ''))\n return out\n}\n\n/** The lineage of `docId` as plain version rows. */\nexport function toArtifactVersions(chain: readonly VersionedDoc[]): ArtifactVersion[] {\n return chain.flatMap((d) =>\n d.external_id\n ? [\n {\n id: d.external_id,\n name: d.file_name ?? '',\n createdAt: d.created_at ?? '',\n parentId: d.parent_ext_id,\n },\n ]\n : []\n )\n}\n\n/**\n * \"v2\": the 1-based position of `docId` in its lineage. `null` when there is nothing to tell apart\n * (the lineage is just this document, or it is unknown), so unversioned documents stay unlabelled.\n */\nexport function versionLabel(\n versions: readonly ArtifactVersion[],\n docId: string | null | undefined\n): string | null {\n if (!docId || versions.length <= 1) return null\n const index = versions.findIndex((v) => v.id === docId)\n return index === -1 ? null : `v${index + 1}`\n}\n\n/**\n * Join parsed chunks into one markdown text (blank line between chunks).\n *\n * `unescape: true` for an artifact stored from markdown: the backend's parse of a `.md` escapes\n * markdown punctuation, which `unescapeMarkdown` undoes (see its rule), and mangles its title\n * (`repairParsedTitle`). Leave it off for the parse\n * of a PDF or Word file.\n */\nexport function flattenChunks(\n chunks: readonly { content?: string | null }[] | null | undefined,\n options?: { unescape?: boolean }\n): string {\n const text = (chunks ?? []).map((c) => (c.content ?? '').trim()).join('\\n\\n')\n return options?.unescape ? repairParsedTitle(unescapeMarkdown(text)) : text\n}\n\n/** The backend's pattern for a document id. Anything else (a streamed draft's placeholder) is local. */\nconst DOC_ID = /^doc/\n\n/** Is `id` a real, saved document id? Local drafts have placeholder ids and no backend document. */\nexport function isDocumentId(id: string | null | undefined): id is string {\n return !!id && DOC_ID.test(id)\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useRedline, type UseRedlineResult } from './useRedline'\nimport type { RedlineEngine } from './redline-engine'\n\n/** What a save reports back. `docId` is the new version when the backend already knows it. */\nexport interface ArtifactSaveResult {\n docId?: string\n /** 1-based number of the version that was just saved (1 for the first save of a draft). */\n version?: number\n}\n\nexport interface ArtifactEditSessionOptions {\n /** The artifact being edited. Changing it discards the buffer and any comparison. */\n docId: string | null | undefined\n /**\n * The saved text of the open version. `undefined` while it loads; whenever it changes the\n * baseline follows it (a version arriving from the realtime channel, a finished stream).\n */\n baseline: string | undefined\n /**\n * A new document the user types from scratch: open straight in the editor, seeded with\n * `initialContent`, instead of showing a read-only view. Read when `docId` changes.\n */\n startEditing?: boolean\n initialContent?: string\n /** The version this one was saved from. Offering \"compare with previous\" needs it. */\n parentId?: string | null\n /** Controlled comparison target. Omit for an uncontrolled one the session owns. */\n compareId?: string | null\n onCompareChange?: (id: string | null) => void\n /** The saved text of the compare target (the older side of the diff). */\n compareText?: string | null\n compareLoading?: boolean\n /** Starting a comparison opens the editor with track changes on (default true). */\n compareOpensEditor?: boolean\n /** Persist the buffer as a NEW version. Rejecting keeps the buffer so nothing is lost. */\n save: (content: string) => Promise<ArtifactSaveResult | void>\n onSaved?: (result: ArtifactSaveResult, content: string) => void\n onSaveError?: (error: unknown) => void\n /** Every buffer change (a host keeps a draft store in sync with it). */\n onContentChange?: (content: string) => void\n /** The unsaved-changes flag, for a host that warns before a panel is closed. */\n onDirtyChange?: (dirty: boolean) => void\n /** Where the diff runs. Defaults to the main thread. */\n redlineEngine?: RedlineEngine\n /** Typing is never debounced; the diff trails the buffer by this long. Default 300ms. */\n diffDelayMs?: number\n}\n\nexport interface ArtifactEditSession {\n isEditing: boolean\n /** The saved text of the open version. */\n baseline: string\n /** The text in the editor (the baseline until the first edit). */\n content: string\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n compareId: string | null\n showTrackChanges: boolean\n /** Track changes between the compare target and the (debounced) buffer. */\n redline: UseRedlineResult\n startEdit: () => void\n /** Discard the buffer and any comparison; back to the rendered view. */\n cancel: () => void\n /** Save the buffer as a new version. Resolves false when it failed (the buffer is kept). */\n save: () => Promise<boolean>\n /** The editor's `onChange`; also replaces the buffer (for example after an undo-this-change). */\n change: (markdown: string) => void\n /** The editor's `onNormalized`: adopt its canonical form as the baseline so Save does not fire. */\n normalized: (markdown: string) => void\n /** Compare with the previous version (when no id is given). */\n compare: (id?: string) => void\n stopCompare: () => void\n setShowTrackChanges: (show: boolean) => void\n /** Undo one tracked change in the buffer. */\n revertRegion: (regionId: string) => Promise<void>\n}\n\n/**\n * The state machine of an artifact edit session, with no SDK and no network: the edit buffer and\n * its baseline, the dirty flag, immutable-version saves and a track-changes comparison. A host\n * supplies the saved text and a `save` function (see `useArtifactSession` for the SDK binding).\n */\nexport function useArtifactEditSession(options: ArtifactEditSessionOptions): ArtifactEditSession {\n const {\n docId,\n baseline: loadedBaseline,\n startEditing = false,\n initialContent,\n parentId,\n compareId: controlledCompareId,\n onCompareChange,\n compareText,\n compareLoading = false,\n compareOpensEditor = true,\n save: persist,\n onSaved,\n onSaveError,\n onContentChange,\n onDirtyChange,\n redlineEngine,\n diffDelayMs = 300,\n } = options\n\n const [isEditing, setIsEditing] = useState(false)\n const [baseline, setBaseline] = useState('')\n const [buffer, setBuffer] = useState('')\n const [isSaving, setIsSaving] = useState(false)\n const [showTrackChanges, setShowTrackChanges] = useState(false)\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const controlled = controlledCompareId !== undefined\n const compareId = controlled ? controlledCompareId : ownCompareId\n\n const setCompareId = useCallback(\n (id: string | null) => {\n if (!controlled) setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [controlled, onCompareChange]\n )\n\n // The latest values for callbacks that must not change identity while the user types.\n const latest = useRef({ buffer, baseline, isEditing, initialContent })\n latest.current = { buffer, baseline, isEditing, initialContent }\n\n // The baseline follows the loaded text. A draft has none and seeds itself below.\n useEffect(() => {\n if (loadedBaseline !== undefined) setBaseline(loadedBaseline)\n }, [loadedBaseline])\n\n // Another artifact: drop stale edits and comparison. A new typed document starts in the editor.\n useEffect(() => {\n if (startEditing) {\n const seed = latest.current.initialContent ?? ''\n setIsEditing(true)\n setBaseline(seed)\n setBuffer(seed)\n } else {\n setIsEditing(false)\n setBuffer('')\n }\n setCompareId(null)\n setShowTrackChanges(false)\n // Only the identity of the artifact resets the session.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [docId])\n\n const startEdit = useCallback(() => {\n setBuffer(latest.current.baseline)\n setIsEditing(true)\n }, [])\n\n const stopCompare = useCallback(() => {\n setCompareId(null)\n setShowTrackChanges(false)\n }, [setCompareId])\n\n const cancel = useCallback(() => {\n setIsEditing(false)\n setBuffer('')\n stopCompare()\n }, [stopCompare])\n\n const compare = useCallback(\n (id?: string) => {\n const target = id ?? parentId\n if (target) setCompareId(target)\n },\n [parentId, setCompareId]\n )\n\n // Comparing and editing are one surface: a comparison opens the editor with the diff showing,\n // like Word's Compare yields tracked changes you can keep typing through.\n const hasBaseline = baseline !== ''\n useEffect(() => {\n if (!compareId || !compareOpensEditor || !hasBaseline) return\n if (!latest.current.isEditing) startEdit()\n setShowTrackChanges(true)\n }, [compareId, compareOpensEditor, hasBaseline, startEdit])\n\n const save = useCallback(async (): Promise<boolean> => {\n const content = latest.current.buffer\n setIsSaving(true)\n try {\n const result = (await persist(content)) ?? {}\n setBaseline(content)\n setIsEditing(false)\n stopCompare()\n onSaved?.(result, content)\n return true\n } catch (error) {\n onSaveError?.(error)\n return false\n } finally {\n setIsSaving(false)\n }\n }, [persist, stopCompare, onSaved, onSaveError])\n\n const content = buffer || baseline\n const hasChanges = isEditing && !!buffer && buffer !== baseline\n useEffect(() => {\n onDirtyChange?.(hasChanges)\n return () => onDirtyChange?.(false)\n }, [hasChanges, onDirtyChange])\n\n const setContent = useCallback(\n (markdown: string) => {\n setBuffer(markdown)\n onContentChange?.(markdown)\n },\n [onContentChange]\n )\n const normalized = useCallback((markdown: string) => {\n setBaseline(markdown)\n setBuffer(markdown)\n }, [])\n\n // The diff trails the buffer so it runs on a settled text.\n const [diffContent, setDiffContent] = useState(content)\n useEffect(() => {\n const id = setTimeout(() => setDiffContent(content), diffDelayMs)\n return () => clearTimeout(id)\n }, [content, diffDelayMs])\n\n const redline = useRedline({\n baseText: compareId ? compareText : undefined,\n compareText: compareId ? diffContent || baseline : undefined,\n isLoading: compareLoading,\n withRegions: true,\n engine: redlineEngine,\n })\n const { revertRegion: revertInRedline } = redline\n const revertRegion = useCallback(\n async (regionId: string): Promise<void> => {\n const next = await revertInRedline(regionId)\n if (next !== null) setContent(next)\n },\n [revertInRedline, setContent]\n )\n\n return useMemo(\n () => ({\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n canCompare: !!parentId && !compareId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n change: setContent,\n normalized,\n compare,\n stopCompare,\n setShowTrackChanges,\n revertRegion,\n }),\n [\n isEditing,\n baseline,\n content,\n hasChanges,\n isSaving,\n parentId,\n compareId,\n showTrackChanges,\n redline,\n startEdit,\n cancel,\n save,\n setContent,\n normalized,\n compare,\n stopCompare,\n revertRegion,\n ]\n )\n}\n","import { useCallback, useMemo } from 'react'\nimport { useQuery } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys } from '../hooks'\nimport { flattenChunks, isDocumentId } from './versions'\n\n/**\n * Where the text of a stored artifact is:\n * - `loading`: the first request is in flight (or there is no document yet);\n * - `parsing`: the backend has not finished parsing the upload (the endpoint answers 404, 422 or\n * 500, or an empty parse, for a few seconds after an upload) and the hook is retrying;\n * - `ready`: the text is here (an empty document is `ready` with `text: null`);\n * - `error`: the retries ran out, or the request was refused (401/403).\n */\nexport type ArtifactTextStatus = 'loading' | 'parsing' | 'ready' | 'error'\n\n/** How long `useArtifactText` keeps asking while a document is still being parsed. */\nexport interface ArtifactTextRetry {\n /** Retries after the first request. Default 12. */\n attempts?: number\n /** Delay before the first retry; it grows by 1.6x each time. Default 1000 ms. */\n baseDelayMs?: number\n /** Cap for one delay. Default 5000 ms (12 retries are about 50 s in all). */\n maxDelayMs?: number\n}\n\nexport const DEFAULT_ARTIFACT_TEXT_RETRY: Required<ArtifactTextRetry> = {\n attempts: 12,\n baseDelayMs: 1000,\n maxDelayMs: 5000,\n}\n\n/** Thrown inside the query when the parse has no text yet, so that it is retried like a 500. */\nclass NotParsedYetError extends Error {\n constructor() {\n super('The document has no parsed text yet')\n }\n}\n\nconst isRefusal = (error: unknown): boolean => {\n const status = error as { status?: number; response?: { status?: number } } | null\n const code = status?.status ?? status?.response?.status\n return code === 401 || code === 403\n}\n\nexport interface ArtifactText {\n /**\n * The markdown, clean: `undefined` while `loading` or `parsing`, `null` when there is none (an\n * empty document, or `error`).\n */\n text: string | null | undefined\n /** `status` is `loading` or `parsing`. */\n isLoading: boolean\n status: ArtifactTextStatus\n /** The last request error while `parsing` or after `error`. */\n error: Error | null\n /** Ask again now (after an `error`). */\n retry: () => void\n}\n\n/**\n * The saved markdown of an artifact version (its parsed chunks, joined and unescaped).\n *\n * A freshly uploaded document is parsed asynchronously, and for roughly 3 to 20 seconds the parsed\n * content endpoint answers 404, 422 or 500 (or an empty parse). The hook therefore retries with a\n * growing delay (see `ArtifactTextRetry`) and reports `status: 'parsing'` meanwhile, so a host can\n * show \"Preparing editor...\" instead of opening an editor on an empty baseline. After the last\n * retry the status is `error`; `retry()` starts a new round.\n *\n * The text is run through `unescapeMarkdown`: an artifact is always stored from markdown, and the\n * backend's parse of a `.md` escapes its punctuation.\n */\nexport function useArtifactText(\n docId: string | null | undefined,\n options?: { enabled?: boolean; retry?: ArtifactTextRetry }\n): ArtifactText {\n const arbi = useArbi()\n const { attempts, baseDelayMs, maxDelayMs } = {\n ...DEFAULT_ARTIFACT_TEXT_RETRY,\n ...options?.retry,\n }\n // A local draft (placeholder id) has no backend document: asking for its text would be a 422.\n const enabled = (options?.enabled ?? true) && isDocumentId(docId) && arbi.hasWorkspace\n const query = useQuery({\n // Under the shared `parsedDoc` key, so a document's invalidation reaches it too.\n queryKey: [...arbiQueryKeys.parsedDoc(docId ?? '', 'marker'), 'artifact-text'] as const,\n queryFn: async () => {\n const parsed = (await arbi.documents.getParsedContent(docId as string, 'marker')) as {\n chunks?: { content?: string | null }[]\n }\n if (!parsed.chunks?.some((c) => c.content?.trim())) throw new NotParsedYetError()\n return flattenChunks(parsed.chunks, { unescape: true })\n },\n enabled,\n retry: (failureCount, error) => !isRefusal(error) && failureCount < attempts,\n retryDelay: (failureCount) => Math.min(baseDelayMs * 1.6 ** failureCount, maxDelayMs),\n })\n\n const { refetch } = query\n const retry = useCallback(() => void refetch(), [refetch])\n\n return useMemo<ArtifactText>(() => {\n const error = query.error\n const neverParsed = error instanceof NotParsedYetError\n let status: ArtifactTextStatus = 'loading'\n if (!enabled) status = 'loading'\n else if (query.isSuccess || (query.isError && neverParsed)) status = 'ready'\n else if (query.isError) status = 'error'\n else if (query.failureCount > 0) status = 'parsing'\n const text = !enabled\n ? undefined\n : query.isSuccess\n ? query.data\n : status === 'ready' || status === 'error'\n ? null\n : undefined\n return {\n text,\n isLoading: enabled && (status === 'loading' || status === 'parsing'),\n status,\n error: status === 'ready' ? null : (error ?? query.failureReason ?? null),\n retry,\n }\n }, [\n enabled,\n query.isSuccess,\n query.isError,\n query.data,\n query.error,\n query.failureCount,\n query.failureReason,\n retry,\n ])\n}\n","import { useCallback, useMemo, useState } from 'react'\nimport { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useArbi } from '../useArbi'\nimport { arbiQueryKeys, useDocuments } from '../hooks'\nimport { useArtifactText, type ArtifactTextStatus } from './useArtifactText'\nimport {\n buildVersionChain,\n isDocumentId,\n toArtifactVersions,\n versionLabel,\n type ArtifactVersion,\n} from './versions'\nimport {\n useArtifactEditSession,\n type ArtifactEditSession,\n type ArtifactEditSessionOptions,\n type ArtifactSaveResult,\n} from './useArtifactEditSession'\n\n/** The version lineage of an artifact in a workspace, oldest first. */\nexport function useArtifactVersions(\n workspaceId: string | undefined,\n docId: string | null | undefined\n): ArtifactVersion[] {\n const { data: documents } = useDocuments(workspaceId)\n return useMemo(\n () => toArtifactVersions(buildVersionChain(documents ?? [], docId)),\n [documents, docId]\n )\n}\n\nexport interface SaveArtifactVersionInput {\n /** File name of the new version (`.md` is added when missing). */\n title: string\n content: string\n /** The version this one is saved from; omit for a first version. */\n parentId?: string | null\n /** The processing config (auto-title, parsing) to run the upload with. */\n configId?: string | null\n /** `artifact` (default) for AI-style drafts; `source` for a document the user typed. */\n wpType?: 'artifact' | 'source'\n}\n\n/**\n * Save markdown as a NEW immutable version (a child document of `parentId`) and refresh the\n * workspace document list so the version list picks it up. The id of the new version is often not\n * known yet (the document is parsed asynchronously); it then arrives through the list.\n */\nexport function useSaveArtifactVersion() {\n const arbi = useArbi()\n const queryClient = useQueryClient()\n return useMutation<\n ArtifactSaveResult,\n Error,\n SaveArtifactVersionInput & { workspaceId?: string }\n >({\n mutationFn: async ({ title, content, parentId, configId, wpType, workspaceId }) => {\n // The backend classifies uploads by extension: a title without one is silently dropped.\n const fileName = /\\.md$/i.test(title) ? title : `${title}.md`\n const result = await arbi.documents.uploadFile(\n new Blob([content], { type: 'text/markdown' }),\n fileName,\n {\n wpType: wpType ?? 'artifact',\n parentExtId: parentId ?? undefined,\n configExtId: configId ?? undefined,\n }\n )\n if (workspaceId) {\n await queryClient.invalidateQueries({ queryKey: arbiQueryKeys.documents(workspaceId) })\n }\n return { docId: result.doc_ext_ids?.[0] }\n },\n })\n}\n\nexport interface ArtifactSessionOptions extends Pick<\n ArtifactEditSessionOptions,\n | 'onSaved'\n | 'onSaveError'\n | 'onCompareChange'\n | 'compareId'\n | 'compareOpensEditor'\n | 'redlineEngine'\n | 'onDirtyChange'\n> {\n workspaceId: string | undefined\n /**\n * The open version, or the placeholder id of an unsaved local draft (anything that is not a\n * backend document id, i.e. does not start with `doc`).\n */\n docId: string | null | undefined\n /**\n * The text of a local draft (nothing is fetched for it). The FIRST save uploads it as a real\n * document with no parent and the session switches to the new id; later saves chain from it.\n */\n draftContent?: string\n /** Name for saved versions. Defaults to the open version's file name, else \"Untitled\". */\n title?: string\n /** Processing config for saved versions. */\n configId?: string | null\n}\n\n/** Everything `ArtifactEditor` (`@arbidocs/blocks/artifacts`) takes from a session, flat. */\nexport interface ArtifactSessionView {\n content: string\n isEditing: boolean\n hasChanges: boolean\n isSaving: boolean\n canCompare: boolean\n comparing: boolean\n compareId: string | null\n showTrackChanges: boolean\n versions: ArtifactVersion[]\n currentVersionId: string\n onStartEdit: () => void\n onCancel: () => void\n onSave: () => void\n onCompare: () => void\n onStopCompare: () => void\n onToggleTrackChanges: () => void\n /**\n * Whether the text is ready. `ArtifactEditor` renders \"Preparing editor...\" while it is\n * `loading` or `parsing` (a fresh upload is parsed for a few seconds) and an error with Retry.\n */\n status: ArtifactTextStatus\n /** Ask for the text again after an `error`. */\n onRetry: () => void\n}\n\nexport interface ArtifactSession extends ArtifactEditSession {\n /** The open document: the new real id once a local draft has been saved. */\n docId: string | null | undefined\n /** The open version is an unsaved local draft (no backend document yet). */\n isLocal: boolean\n isLoading: boolean\n /** See `ArtifactTextStatus`. */\n status: ArtifactTextStatus\n versions: ArtifactVersion[]\n /** \"v2\" for any version in the lineage. */\n labelOf: (id: string | null | undefined) => string | null\n /** Props for `<ArtifactEditor>`. */\n view: ArtifactSessionView\n /** Props for `<ArtifactMarkdownEditor>` (`@arbidocs/blocks/artifacts/editor`). */\n editorProps: {\n markdown: string\n onChange: (markdown: string) => void\n onNormalized: (markdown: string) => void\n }\n /** Props for `<ArtifactRedlineView>`. */\n redlineProps: {\n state: ArtifactEditSession['redline']['state']\n onRevert: (regionId: string) => void\n }\n}\n\n/**\n * Edit an artifact through the SDK: load it, edit it, save it as a new version, list its versions\n * and compare any two with track changes. Needs an `<ArbiProvider>` and a selected workspace.\n *\n * ```tsx\n * const session = useArtifactSession({ workspaceId, docId, onSaved: ({ docId }) => docId && open(docId) })\n * <ArtifactEditor {...session.view} onOpenVersion={open}\n * editor={<ArtifactMarkdownEditor {...session.editorProps} />}\n * redline={<ArtifactRedlineView {...session.redlineProps} />} />\n * ```\n */\nexport function useArtifactSession(options: ArtifactSessionOptions): ArtifactSession {\n const {\n workspaceId,\n docId: hostDocId,\n draftContent,\n title,\n configId,\n compareId,\n onCompareChange,\n onSaved,\n ...passthrough\n } = options\n // A saved local draft becomes this real document; another host docId resets it.\n const [saved, setSaved] = useState<{\n forId: string | null | undefined\n id: string\n text: string\n } | null>(null)\n const adopted = saved && saved.forId === hostDocId ? saved : null\n const docId = adopted?.id ?? hostDocId\n const isLocal = !isDocumentId(docId)\n\n // Owned here (not in the edit session) because the compare target's text must be loaded first.\n const [ownCompareId, setOwnCompareId] = useState<string | null>(null)\n const activeCompareId = compareId === undefined ? ownCompareId : compareId\n const changeCompare = useCallback(\n (id: string | null) => {\n setOwnCompareId(id)\n onCompareChange?.(id)\n },\n [onCompareChange]\n )\n\n const { text, isLoading, status, retry } = useArtifactText(docId)\n const versions = useArtifactVersions(workspaceId, isLocal ? null : docId)\n const { text: compareText, isLoading: compareLoading } = useArtifactText(activeCompareId, {\n enabled: !!activeCompareId,\n })\n const saveVersion = useSaveArtifactVersion()\n const current = versions.find((v) => v.id === docId)\n\n const save = useCallback(\n async (content: string) => {\n const result = await saveVersion.mutateAsync({\n title: title ?? current?.name ?? 'Untitled',\n content,\n parentId: isLocal ? null : docId,\n configId,\n workspaceId,\n })\n return { ...result, version: isLocal ? 1 : versions.length + 1 }\n },\n [saveVersion, title, current?.name, isLocal, docId, configId, workspaceId, versions.length]\n )\n\n const handleSaved = useCallback(\n (result: ArtifactSaveResult, content: string) => {\n // A host that keeps passing the local draft's placeholder id: follow every save to the real\n // document it created (the first save creates version 1, later ones chain from it).\n if (!isDocumentId(hostDocId) && result.docId)\n setSaved({ forId: hostDocId, id: result.docId, text: content })\n onSaved?.(result, content)\n },\n [hostDocId, onSaved]\n )\n\n const session = useArtifactEditSession({\n ...passthrough,\n docId,\n // A local draft has only its own text; a just-saved one shows what was saved until the parsed\n // text of the new document arrives.\n baseline: text ?? (isLocal ? draftContent : adopted?.text),\n parentId: current?.parentId,\n compareId: activeCompareId,\n onCompareChange: changeCompare,\n compareText,\n compareLoading,\n save,\n onSaved: handleSaved,\n })\n\n const { redline } = session\n return useMemo<ArtifactSession>(\n () => ({\n ...session,\n docId,\n isLocal,\n isLoading,\n status,\n versions,\n labelOf: (id) => versionLabel(versions, id),\n view: {\n content: session.baseline,\n isEditing: session.isEditing,\n hasChanges: session.hasChanges,\n isSaving: session.isSaving,\n canCompare: session.canCompare,\n comparing: !!session.compareId,\n compareId: session.compareId,\n showTrackChanges: session.showTrackChanges,\n versions,\n currentVersionId: docId ?? '',\n onStartEdit: session.startEdit,\n onCancel: session.cancel,\n onSave: () => void session.save(),\n onCompare: () => session.compare(),\n onStopCompare: session.stopCompare,\n onToggleTrackChanges: () => session.setShowTrackChanges(!session.showTrackChanges),\n // A local draft has its text already: it is ready.\n status: isLocal ? 'ready' : status,\n onRetry: retry,\n },\n editorProps: {\n markdown: session.content,\n onChange: session.change,\n onNormalized: session.normalized,\n },\n redlineProps: {\n state: redline.state,\n onRevert: (regionId) => void session.revertRegion(regionId),\n },\n }),\n [session, redline, isLoading, status, retry, isLocal, versions, docId]\n )\n}\n","import type { ComponentPropsWithoutRef, FC, ReactNode } from 'react'\nimport { MarkdownRenderer } from '../ai/MarkdownRenderer'\n\n/** The `<del>` / `<ins>` renderers `ArtifactRedlineView` hands to a markdown renderer. */\nexport interface ArtifactRedlineComponents {\n del: FC<ComponentPropsWithoutRef<'del'> & { 'data-cid'?: string }>\n ins: FC<ComponentPropsWithoutRef<'ins'> & { 'data-cid'?: string }>\n}\n\n/**\n * The kit's markdown renderer as the `renderMarkdown` slot of `ArtifactEditor` and\n * `ArtifactRedlineView`: full markdown (tables, lists, code) plus the raw `<del>` / `<ins>` tags\n * of a redline.\n */\nexport function renderArtifactMarkdown(\n markdown: string,\n components?: ArtifactRedlineComponents\n): ReactNode {\n return <MarkdownRenderer components={components}>{markdown}</MarkdownRenderer>\n}\n","import { useCallback, useEffect, useRef, useState } from 'react'\nimport type { ArtifactEvent } from '../ai/engine'\nimport { cleanDraftMarkdown } from '../ai/stored-markdown'\nimport { useSaveArtifactVersion } from './useArtifactSession'\nimport { isDocumentId } from './versions'\nimport { useArtifactText, type ArtifactTextRetry } from './useArtifactText'\n\n/**\n * Where a drafted artifact is in its STREAM -> PERSIST -> EDIT life:\n * - `streaming`: the agent is still working (or has produced nothing final): show the live canvas;\n * - `persisting`: the finished draft is being stored as version 1 of the artifact;\n * - `parsing`: stored; the backend is still parsing it, so there is no editable text yet;\n * - `ready`: the text is readable: mount the editor on `docId`;\n * - `error`: storing failed or the parse never produced text (`retry()` starts over).\n */\nexport type StreamedArtifactPhase = 'streaming' | 'persisting' | 'parsing' | 'ready' | 'error'\n\nexport interface UseStreamedArtifactOptions {\n /** The artifacts of the agent run (`useConnectedAiTask().artifacts`). */\n artifacts: ArtifactEvent[]\n workspaceId: string | undefined\n /**\n * The run has stopped: not busy and not failed. Nothing is stored before this, so a draft that\n * is still streaming is never persisted half-written.\n */\n settled: boolean\n /** Make the stored markdown from the streamed content. Defaults to `cleanDraftMarkdown`. */\n clean?: (streamed: string) => string\n /** Processing config for the stored version. */\n configId?: string | null\n /** How long to wait for the parse (see `useArtifactText`). */\n parseRetry?: ArtifactTextRetry\n}\n\nexport interface StreamedArtifact {\n phase: StreamedArtifactPhase\n /** The finished streamed artifact (its `title` names the stored versions). */\n artifact: ArtifactEvent | undefined\n /** The backend document to edit, once there is one (while `parsing` and `ready`). */\n docId: string | undefined\n error: Error | null\n /** After an `error`: store again or ask for the parse again. */\n retry: () => void\n}\n\n/**\n * The lifecycle of an agent-drafted artifact, so a host passes the stream and renders the phase.\n *\n * While the agent streams, the draft lives only on the canvas. Once the run is `settled` and the\n * draft is complete, a draft that is not yet a backend document is cleaned (`cleanDraftMarkdown`)\n * and stored ONCE as the artifact's first version (`wpType: 'artifact'`); a draft that already is a\n * backend document passes through. The hook then waits for the parse (`useArtifactText`, which\n * retries) and reports `ready` with the `docId` to open in an editor.\n *\n * Needs an `<ArbiProvider>` and a workspace. `@arbidocs/blocks/connect` has the whole thing as a\n * component (`StreamedArtifact`).\n */\nexport function useStreamedArtifact({\n artifacts,\n workspaceId,\n settled,\n clean = cleanDraftMarkdown,\n configId,\n parseRetry,\n}: UseStreamedArtifactOptions): StreamedArtifact {\n const artifact = artifacts.find((a) => a.is_complete)\n const { mutateAsync } = useSaveArtifactVersion()\n const [saved, setSaved] = useState<{ content: string; docId: string } | null>(null)\n const [saveError, setSaveError] = useState<Error | null>(null)\n const [attempt, setAttempt] = useState(0)\n const started = useRef<string | null>(null)\n\n const content = artifact?.content ?? ''\n const title = artifact?.title ?? 'Draft'\n const passThrough = !!artifact && isDocumentId(artifact.doc_ext_id)\n const needsSave = settled && !!artifact && !passThrough && !!content.trim() && !!workspaceId\n\n useEffect(() => {\n const key = `${attempt}:${content}`\n if (!needsSave || started.current === key) return\n started.current = key\n setSaveError(null)\n mutateAsync({\n title,\n content: clean(content),\n workspaceId,\n configId,\n wpType: 'artifact',\n })\n .then((r) => {\n if (r.docId) setSaved({ content, docId: r.docId })\n else setSaveError(new Error('The draft was stored but the server returned no document id'))\n })\n .catch((e: unknown) => setSaveError(e instanceof Error ? e : new Error(String(e))))\n // `clean` is deliberately not a dependency: a new function identity must not store twice.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [needsSave, content, title, workspaceId, configId, attempt, mutateAsync])\n\n const docId = !artifact\n ? undefined\n : passThrough\n ? artifact.doc_ext_id\n : saved?.content === content\n ? saved.docId\n : undefined\n\n const text = useArtifactText(docId, { enabled: settled, retry: parseRetry })\n const { retry: retryText } = text\n\n const retry = useCallback(() => {\n if (saveError) setAttempt((n) => n + 1)\n else retryText()\n }, [saveError, retryText])\n\n let phase: StreamedArtifactPhase\n if (!settled || !artifact) phase = 'streaming'\n else if (saveError) phase = 'error'\n else if (!docId) phase = needsSave ? 'persisting' : 'streaming'\n else if (text.status === 'ready' && text.text) phase = 'ready'\n else if (text.status === 'error' || text.status === 'ready') phase = 'error'\n else phase = 'parsing'\n\n const error =\n phase !== 'error'\n ? null\n : (saveError ?? text.error ?? new Error('The document has no text to edit'))\n return { phase, artifact, docId, error, retry }\n}\n"]}