@gmickel/gno 2.15.0 → 2.16.0

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 (198) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -44,27 +44,33 @@ const hasOnlyDigits = (value: string, hexadecimal: boolean): boolean => {
44
44
 
45
45
  /** Decode recognized entities from the original input exactly once. */
46
46
  export const decodeHtmlEntitiesOnce = (value: string): string => {
47
- let output = "";
47
+ let amp = value.indexOf("&");
48
+ if (amp === -1) return value;
49
+ const parts: string[] = [];
48
50
  let cursor = 0;
49
- while (cursor < value.length) {
50
- if (value[cursor] !== "&") {
51
- output += value[cursor];
52
- cursor += 1;
53
- continue;
51
+ while (amp !== -1) {
52
+ if (amp > cursor) {
53
+ parts.push(value.slice(cursor, amp));
54
+ }
55
+ const entityEnd = Math.min(value.length, amp + MAX_ENTITY_CHARS + 2);
56
+ let absoluteSemicolon = -1;
57
+ for (let i = amp + 1; i < entityEnd; i += 1) {
58
+ if (value.charCodeAt(i) === 59) {
59
+ absoluteSemicolon = i;
60
+ break;
61
+ }
54
62
  }
55
- const entityEnd = Math.min(value.length, cursor + MAX_ENTITY_CHARS + 2);
56
- const semicolon = value.slice(cursor + 1, entityEnd).indexOf(";");
57
- const absoluteSemicolon = semicolon < 0 ? -1 : cursor + semicolon + 1;
58
63
  if (
59
64
  absoluteSemicolon < 0 ||
60
- absoluteSemicolon - cursor - 1 <= 0 ||
61
- absoluteSemicolon - cursor - 1 > MAX_ENTITY_CHARS
65
+ absoluteSemicolon - amp - 1 <= 0 ||
66
+ absoluteSemicolon - amp - 1 > MAX_ENTITY_CHARS
62
67
  ) {
63
- output += "&";
64
- cursor += 1;
68
+ parts.push("&");
69
+ cursor = amp + 1;
70
+ amp = value.indexOf("&", cursor);
65
71
  continue;
66
72
  }
67
- const entity = value.slice(cursor + 1, absoluteSemicolon);
73
+ const entity = value.slice(amp + 1, absoluteSemicolon);
68
74
  const named = NAMED_ENTITIES.get(entity.toLowerCase());
69
75
  let decoded = named;
70
76
  if (!decoded && entity.startsWith("#")) {
@@ -84,14 +90,16 @@ export const decodeHtmlEntitiesOnce = (value: string): string => {
84
90
  decoded = String.fromCodePoint(codePoint);
85
91
  }
86
92
  }
87
- if (decoded === undefined) {
88
- output += value.slice(cursor, absoluteSemicolon + 1);
89
- } else {
90
- output += decoded;
91
- }
93
+ parts.push(
94
+ decoded === undefined ? value.slice(amp, absoluteSemicolon + 1) : decoded
95
+ );
92
96
  cursor = absoluteSemicolon + 1;
97
+ amp = value.indexOf("&", cursor);
98
+ }
99
+ if (cursor < value.length) {
100
+ parts.push(value.slice(cursor));
93
101
  }
94
- return output;
102
+ return parts.join("");
95
103
  };
96
104
 
97
105
  interface HtmlTag {
@@ -124,25 +132,30 @@ const readTag = (source: string, start: number): HtmlTag | undefined => {
124
132
  * Script/style contents and comments are discarded; entities decode once.
125
133
  */
126
134
  export const htmlFragmentToText = (source: string): string => {
127
- let output = "";
135
+ let lt = source.indexOf("<");
136
+ if (lt === -1) return decodeHtmlEntitiesOnce(source);
137
+ const parts: string[] = [];
128
138
  let cursor = 0;
129
139
  let blockedName: "script" | "style" | undefined;
130
140
  let blockedDepth = 0;
131
- while (cursor < source.length) {
132
- if (source[cursor] !== "<") {
133
- if (!blockedName) output += source[cursor];
134
- cursor += 1;
135
- continue;
141
+ while (lt !== -1) {
142
+ if (!blockedName && lt > cursor) {
143
+ parts.push(source.slice(cursor, lt));
136
144
  }
137
- if (source.startsWith("<!--", cursor)) {
138
- const commentEnd = source.indexOf("-->", cursor + 4);
139
- if (commentEnd < 0) break;
145
+ if (source.startsWith("<!--", lt)) {
146
+ const commentEnd = source.indexOf("-->", lt + 4);
147
+ if (commentEnd < 0) {
148
+ cursor = source.length;
149
+ break;
150
+ }
140
151
  cursor = commentEnd + 3;
152
+ lt = source.indexOf("<", cursor);
141
153
  continue;
142
154
  }
143
- const tag = readTag(source, cursor);
155
+ const tag = readTag(source, lt);
144
156
  if (!tag) {
145
- if (!blockedName) output += source.slice(cursor);
157
+ if (!blockedName) parts.push(source.slice(lt));
158
+ cursor = source.length;
146
159
  break;
147
160
  }
148
161
  cursor = tag.end + 1;
@@ -152,14 +165,19 @@ export const htmlFragmentToText = (source: string): string => {
152
165
  else blockedDepth += 1;
153
166
  if (blockedDepth === 0) blockedName = undefined;
154
167
  }
155
- continue;
156
- }
157
- if (!tag.closing && (tag.name === "script" || tag.name === "style")) {
168
+ } else if (
169
+ !tag.closing &&
170
+ (tag.name === "script" || tag.name === "style")
171
+ ) {
158
172
  blockedName = tag.name;
159
173
  blockedDepth = 1;
160
- continue;
174
+ } else if (!tag.closing && tag.name === "br") {
175
+ parts.push("\n");
161
176
  }
162
- if (!tag.closing && tag.name === "br") output += "\n";
177
+ lt = source.indexOf("<", cursor);
178
+ }
179
+ if (!blockedName && cursor < source.length) {
180
+ parts.push(source.slice(cursor));
163
181
  }
164
- return decodeHtmlEntitiesOnce(output);
182
+ return decodeHtmlEntitiesOnce(parts.join(""));
165
183
  };
@@ -33,19 +33,11 @@ export function includesBytes(bytes: Uint8Array, needle: Uint8Array): boolean {
33
33
  if (needle.length === 0 || bytes.length < needle.length) {
34
34
  return false;
35
35
  }
36
- outer: for (
37
- let index = 0;
38
- index <= bytes.length - needle.length;
39
- index += 1
40
- ) {
41
- for (let offset = 0; offset < needle.length; offset += 1) {
42
- if (bytes[index + offset] !== needle[offset]) {
43
- continue outer;
44
- }
45
- }
46
- return true;
47
- }
48
- return false;
36
+ return (
37
+ Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).indexOf(
38
+ needle
39
+ ) !== -1
40
+ );
49
41
  }
50
42
 
51
43
  /** An encrypted (password-protected) OOXML workbook: a CFB container. */
@@ -16,6 +16,9 @@ const BYTE_LF = 0x0a;
16
16
  const BYTE_CR = 0x0d;
17
17
  const UTF8_BOM = new Uint8Array([0xef, 0xbb, 0xbf]);
18
18
 
19
+ const createUtf8Decoder = (): TextDecoder =>
20
+ new TextDecoder("utf-8", { fatal: true });
21
+
19
22
  const concatenate = (
20
23
  parts: readonly Uint8Array[],
21
24
  byteLength: number
@@ -38,30 +41,37 @@ const stripLineEnvelope = (
38
41
  let end = bytes.byteLength;
39
42
  if (
40
43
  lineNumber === 1 &&
41
- end >= UTF8_BOM.byteLength &&
42
- UTF8_BOM.every((byte, index) => bytes[index] === byte)
44
+ end >= 3 &&
45
+ bytes[0] === UTF8_BOM[0] &&
46
+ bytes[1] === UTF8_BOM[1] &&
47
+ bytes[2] === UTF8_BOM[2]
43
48
  ) {
44
- start = UTF8_BOM.byteLength;
49
+ start = 3;
45
50
  }
46
51
  if (end > start && bytes[end - 1] === BYTE_CR) end -= 1;
47
- return bytes.subarray(start, end);
52
+ return start === 0 && end === bytes.byteLength
53
+ ? bytes
54
+ : bytes.subarray(start, end);
48
55
  };
49
56
 
50
- const decodeLine = (
51
- parts: readonly Uint8Array[],
52
- byteLength: number,
57
+ const decodeSingleBytes = (
58
+ rawBytes: Uint8Array,
53
59
  lineNumber: number,
54
- terminated: boolean
60
+ terminated: boolean,
61
+ decoderState: { decoder: TextDecoder }
55
62
  ): Utf8LineResult => {
56
- const bytes = stripLineEnvelope(concatenate(parts, byteLength), lineNumber);
63
+ const bytes = stripLineEnvelope(rawBytes, lineNumber);
57
64
  try {
58
65
  return {
59
66
  ok: true,
60
67
  lineNumber,
61
- text: new TextDecoder("utf-8", { fatal: true }).decode(bytes),
68
+ text: decoderState.decoder.decode(bytes),
62
69
  terminated,
63
70
  };
64
71
  } catch {
72
+ // Recreate the fatal decoder after an error so no runtime-specific error
73
+ // state can bleed into subsequent valid lines.
74
+ decoderState.decoder = createUtf8Decoder();
65
75
  return {
66
76
  ok: false,
67
77
  lineNumber,
@@ -71,6 +81,20 @@ const decodeLine = (
71
81
  }
72
82
  };
73
83
 
84
+ const decodeLine = (
85
+ parts: readonly Uint8Array[],
86
+ byteLength: number,
87
+ lineNumber: number,
88
+ terminated: boolean,
89
+ decoderState: { decoder: TextDecoder }
90
+ ): Utf8LineResult =>
91
+ decodeSingleBytes(
92
+ concatenate(parts, byteLength),
93
+ lineNumber,
94
+ terminated,
95
+ decoderState
96
+ );
97
+
74
98
  /**
75
99
  * Split an async byte source without retaining an unbounded physical line.
76
100
  * Invalid UTF-8 and oversized lines are isolated so later siblings can proceed.
@@ -80,6 +104,7 @@ export async function* readBoundedUtf8Lines(
80
104
  maxLineBytes: number
81
105
  ): AsyncGenerator<Utf8LineResult> {
82
106
  const safeMaxLineBytes = Math.max(1, Math.floor(maxLineBytes));
107
+ const decoderState = { decoder: createUtf8Decoder() };
83
108
  let parts: Uint8Array[] = [];
84
109
  let lineBytes = 0;
85
110
  let lineNumber = 1;
@@ -94,37 +119,50 @@ export async function* readBoundedUtf8Lines(
94
119
 
95
120
  for await (const chunk of source) {
96
121
  let segmentStart = 0;
97
- for (let index = 0; index < chunk.byteLength; index += 1) {
98
- if (chunk[index] !== BYTE_LF) continue;
99
- const segment = chunk.subarray(segmentStart, index);
100
- if (!oversized && lineBytes + segment.byteLength <= safeMaxLineBytes) {
101
- if (segment.byteLength > 0) parts.push(segment.slice());
102
- lineBytes += segment.byteLength;
122
+ while (segmentStart < chunk.byteLength) {
123
+ const nl = chunk.indexOf(BYTE_LF, segmentStart);
124
+ if (nl === -1) break;
125
+ const segmentLen = nl - segmentStart;
126
+ if (!oversized && lineBytes + segmentLen <= safeMaxLineBytes) {
127
+ if (parts.length === 0) {
128
+ yield decodeSingleBytes(
129
+ chunk.subarray(segmentStart, nl),
130
+ lineNumber,
131
+ true,
132
+ decoderState
133
+ );
134
+ } else {
135
+ if (segmentLen > 0) parts.push(chunk.subarray(segmentStart, nl));
136
+ yield decodeLine(
137
+ parts,
138
+ lineBytes + segmentLen,
139
+ lineNumber,
140
+ true,
141
+ decoderState
142
+ );
143
+ }
103
144
  } else {
104
- oversized = true;
105
- }
106
- if (oversized) {
107
145
  yield {
108
146
  ok: false,
109
147
  lineNumber,
110
148
  reason: "line_too_large",
111
149
  terminated: true,
112
150
  };
113
- } else {
114
- yield decodeLine(parts, lineBytes, lineNumber, true);
115
151
  }
116
152
  reset();
117
- segmentStart = index + 1;
153
+ segmentStart = nl + 1;
118
154
  }
119
155
 
120
- const remainder = chunk.subarray(segmentStart);
121
- if (!oversized && lineBytes + remainder.byteLength <= safeMaxLineBytes) {
122
- if (remainder.byteLength > 0) parts.push(remainder.slice());
123
- lineBytes += remainder.byteLength;
124
- } else if (remainder.byteLength > 0) {
125
- oversized = true;
126
- parts = [];
127
- lineBytes = 0;
156
+ const remainderLen = chunk.byteLength - segmentStart;
157
+ if (remainderLen > 0) {
158
+ if (!oversized && lineBytes + remainderLen <= safeMaxLineBytes) {
159
+ parts.push(chunk.subarray(segmentStart).slice());
160
+ lineBytes += remainderLen;
161
+ } else {
162
+ oversized = true;
163
+ parts = [];
164
+ lineBytes = 0;
165
+ }
128
166
  }
129
167
  }
130
168
 
@@ -136,6 +174,6 @@ export async function* readBoundedUtf8Lines(
136
174
  terminated: false,
137
175
  };
138
176
  } else if (lineBytes > 0) {
139
- yield decodeLine(parts, lineBytes, lineNumber, false);
177
+ yield decodeLine(parts, lineBytes, lineNumber, false, decoderState);
140
178
  }
141
179
  }
@@ -101,10 +101,11 @@ const localIdentity = (
101
101
 
102
102
  const segmentRecord = (
103
103
  segment: TranscriptSegment,
104
- input: RecordAdapterInput,
104
+ namespace: string,
105
+ defaultSessionTitle: string,
105
106
  occurrences: Map<string, number>
106
107
  ): RecordAdapterRecord => {
107
- const sessionTitle = segment.sessionTitle ?? fileTitle(input.relativePath);
108
+ const sessionTitle = segment.sessionTitle ?? defaultSessionTitle;
108
109
  const label = segment.speaker
109
110
  ? `${sessionTitle} — ${segment.speaker}`
110
111
  : sessionTitle;
@@ -143,10 +144,7 @@ const segmentRecord = (
143
144
  });
144
145
  }
145
146
  return {
146
- stableId: `transcript:${sourceNamespace(input)}:${localIdentity(
147
- segment,
148
- occurrences
149
- )}`,
147
+ stableId: `transcript:${namespace}:${localIdentity(segment, occurrences)}`,
150
148
  sourceLocator: segment.sourceLocator,
151
149
  sourceHash: hashRecordValue(
152
150
  "gno-transcript-segment-source-v1",
@@ -259,6 +257,8 @@ export const createTranscriptAdapter = (
259
257
  yield { type: "snapshot", state: "partial" };
260
258
  return;
261
259
  }
260
+ const namespace = sourceNamespace(input);
261
+ const defaultSessionTitle = fileTitle(input.relativePath);
262
262
  const occurrences = new Map<string, number>();
263
263
  let hadFailure = false;
264
264
  try {
@@ -270,7 +270,12 @@ export const createTranscriptAdapter = (
270
270
  }
271
271
  yield {
272
272
  type: "record",
273
- record: segmentRecord(event.segment, input, occurrences),
273
+ record: segmentRecord(
274
+ event.segment,
275
+ namespace,
276
+ defaultSessionTitle,
277
+ occurrences
278
+ ),
274
279
  };
275
280
  }
276
281
  } catch {
@@ -35,15 +35,18 @@ const SHORT_OUTPUT_MIN_BYTES = 1000;
35
35
  * normalized as markitdown-ts normalizes every result (line endings, outer
36
36
  * whitespace, at most one blank line).
37
37
  */
38
- export function workbookToMarkdown(workbook: XLSX.WorkBook): string {
39
- let markdown = "";
38
+ export async function workbookToMarkdown(
39
+ workbook: XLSX.WorkBook
40
+ ): Promise<string> {
41
+ const sections: string[] = [];
40
42
  for (const name of workbook.SheetNames) {
41
43
  const sheet = workbook.Sheets[name];
42
44
  if (sheet?.["!ref"]) {
43
- markdown += `## ${name}\n${sheetToMarkdown(sheet)}\n\n`;
45
+ sections.push(`## ${name}\n${await sheetToMarkdown(sheet)}\n\n`);
44
46
  }
45
47
  }
46
- return markdown
48
+ return sections
49
+ .join("")
47
50
  .replace(/\r\n|\r|\n/g, "\n")
48
51
  .trim()
49
52
  .replace(/\n{3,}/g, "\n\n");
@@ -58,11 +61,11 @@ export const xlsxAdapter: Converter = {
58
61
  },
59
62
 
60
63
  convert(input: ConvertInput): Promise<ConvertResult> {
61
- return Promise.resolve(convertWorkbook(input));
64
+ return convertWorkbook(input);
62
65
  },
63
66
  };
64
67
 
65
- function convertWorkbook(input: ConvertInput): ConvertResult {
68
+ async function convertWorkbook(input: ConvertInput): Promise<ConvertResult> {
66
69
  if (input.bytes.length > input.limits.maxBytes) {
67
70
  return { ok: false, error: tooLargeError(input, CONVERTER_ID) };
68
71
  }
@@ -104,7 +107,7 @@ function convertWorkbook(input: ConvertInput): ConvertResult {
104
107
  };
105
108
  }
106
109
 
107
- const markdown = workbookToMarkdown(workbook);
110
+ const markdown = await workbookToMarkdown(workbook);
108
111
  if (!markdown) {
109
112
  return {
110
113
  ok: false,
@@ -22,10 +22,6 @@
22
22
 
23
23
  import type { CellObject, WorkSheet } from "xlsx";
24
24
 
25
- // @ts-expect-error -- @joplin/turndown-plugin-gfm ships no types
26
- import turndownPluginGfm from "@joplin/turndown-plugin-gfm";
27
- // @ts-expect-error -- turndown ships no types
28
- import TurndownService from "turndown";
29
25
  import * as XLSX from "xlsx";
30
26
 
31
27
  /** The part of turndown's API this module uses. */
@@ -43,7 +39,7 @@ interface Turndown {
43
39
  }
44
40
  ): Turndown;
45
41
  }
46
- const TurndownConstructor = TurndownService as new (options: {
42
+ type TurndownConstructorType = new (options: {
47
43
  headingStyle: "atx";
48
44
  }) => Turndown;
49
45
 
@@ -101,40 +97,60 @@ const LINE_BREAK = " \n";
101
97
  * and trailing space dropped (cells and line breaks are block boundaries),
102
98
  * escaped on its own; every line break renders, empty lines included.
103
99
  */
100
+ const plainLineContent = (raw: string): string => {
101
+ // The HTML parser turns the escaped NUL (&#x0000;) into U+FFFD.
102
+ const line = raw
103
+ .replaceAll("\u0000", "\uFFFD")
104
+ .replace(/[ \r\n\t]+/g, " ")
105
+ .replace(/^ | $/g, "");
106
+ return line ? escapeMarkdown(line) : "";
107
+ };
108
+
104
109
  const plainCellContent = (text: string): string => {
110
+ if (!text.includes("\n")) {
111
+ return plainLineContent(text);
112
+ }
105
113
  const lines: string[] = [];
106
114
  for (const raw of text.split("\n")) {
107
- // The HTML parser turns the escaped NUL (&#x0000;) into U+FFFD.
108
- const line = raw
109
- .replaceAll("\u0000", "\uFFFD")
110
- .replace(/[ \r\n\t]+/g, " ")
111
- .replace(/^ | $/g, "");
112
- lines.push(line ? escapeMarkdown(line) : "");
115
+ lines.push(plainLineContent(raw));
113
116
  }
114
117
  return lines.join(LINE_BREAK);
115
118
  };
116
119
 
117
120
  let markupTurndown: Turndown | null = null;
121
+ let markupTurndownPromise: Promise<Turndown> | null = null;
118
122
  const markupCache = new Map<string, string>();
119
123
 
120
124
  /**
121
125
  * Cell HTML with markup (rich-text runs, a hyperlink), converted by turndown
122
- * with markitdown's rules. A paragraph gives the same block context as a
123
- * table cell.
126
+ * with markitdown's rules. Dynamically imports turndown + GFM plugin only when
127
+ * rich-text or hyperlink markup is actually encountered.
124
128
  */
125
- const markupCellContent = (html: string): string => {
129
+ const markupCellContent = async (html: string): Promise<string> => {
126
130
  const cached = markupCache.get(html);
127
131
  if (cached !== undefined) return cached;
128
- markupTurndown ??= createMarkitdownTurndown();
132
+ if (!markupTurndown) {
133
+ markupTurndownPromise ??= createMarkitdownTurndown();
134
+ markupTurndown = await markupTurndownPromise;
135
+ }
129
136
  const content = markupTurndown.turndown(`<p>${html}</p>`);
130
137
  markupCache.set(html, content);
131
138
  return content;
132
139
  };
133
140
 
134
141
  /** markitdown-ts `CustomTurnDown` configuration (vendored dist). */
135
- function createMarkitdownTurndown(): Turndown {
142
+ async function createMarkitdownTurndown(): Promise<Turndown> {
143
+ const [turndownMod, gfmMod] = await Promise.all([
144
+ // @ts-expect-error -- turndown ships no types
145
+ import("turndown"),
146
+ // @ts-expect-error -- @joplin/turndown-plugin-gfm ships no types
147
+ import("@joplin/turndown-plugin-gfm"),
148
+ ]);
149
+ const TurndownConstructor = (turndownMod.default ??
150
+ turndownMod) as TurndownConstructorType;
151
+ const turndownPluginGfm = (gfmMod.default ?? gfmMod) as { gfm: unknown };
136
152
  const service = new TurndownConstructor({ headingStyle: "atx" });
137
- service.use((turndownPluginGfm as { gfm: unknown }).gfm);
153
+ service.use(turndownPluginGfm.gfm);
138
154
  service.addRule("anchor tags", {
139
155
  filter: ["a"],
140
156
  replacement(content, node) {
@@ -190,33 +206,39 @@ const nonFiniteText = (value: number): string =>
190
206
  * the escaped text is rendered from the text; any other HTML goes through
191
207
  * turndown.
192
208
  */
193
- const cellContent = (cell: CellObject | undefined): string => {
209
+ const cellContent = (
210
+ cell: CellObject | undefined
211
+ ): string | Promise<string> => {
194
212
  if (!cell || cell.v == null) return "";
195
- let text: string;
196
- let html: string;
197
213
  if (cell.t === "n" && !Number.isFinite(cell.v as number)) {
198
214
  // SheetJS swaps in an error cell, which has no `h` and no hyperlink.
199
- text = nonFiniteText(cell.v as number);
215
+ const text = nonFiniteText(cell.v as number);
200
216
  return text ? plainCellContent(text) : "";
201
217
  }
218
+ const target = cell.l?.Target;
219
+ const hasExternalLink = Boolean(target && target.charAt(0) !== "#");
202
220
  if (cell.h) {
203
- html = cell.h;
204
- text = typeof cell.v === "string" ? cell.v : "";
205
- } else {
206
- text =
207
- cell.w ||
208
- (XLSX.utils.format_cell(cell), cell.w as string | undefined) ||
209
- "";
210
- html = escapeHtml(text);
221
+ const html = cell.h;
222
+ if (hasExternalLink) {
223
+ return markupCellContent(`<a href="${escapeHtml(target!)}">${html}</a>`);
224
+ }
225
+ const text = typeof cell.v === "string" ? cell.v : "";
226
+ return escapeHtml(text) === html
227
+ ? plainCellContent(text)
228
+ : markupCellContent(html);
211
229
  }
212
- if (!html) return "";
213
- const target = cell.l?.Target;
214
- if (target && target.charAt(0) !== "#") {
215
- return markupCellContent(`<a href="${escapeHtml(target)}">${html}</a>`);
230
+ const text =
231
+ cell.w ||
232
+ (XLSX.utils.format_cell(cell), cell.w as string | undefined) ||
233
+ "";
234
+ if (!text) return "";
235
+ if (hasExternalLink) {
236
+ return markupCellContent(
237
+ `<a href="${escapeHtml(target!)}">${escapeHtml(text)}</a>`
238
+ );
216
239
  }
217
- return escapeHtml(text) === html
218
- ? plainCellContent(text)
219
- : markupCellContent(html);
240
+ // Plain cell with no cell.h and no external link: skip escapeHtml completely.
241
+ return plainCellContent(text);
220
242
  };
221
243
 
222
244
  interface MergeSpan {
@@ -224,23 +246,37 @@ interface MergeSpan {
224
246
  colspan: number;
225
247
  }
226
248
 
249
+ interface MergeLookupIndex {
250
+ minRow: number;
251
+ maxRow: number;
252
+ byRow: Map<number, Map<number, MergeSpan | "covered">>;
253
+ }
254
+
227
255
  /**
228
256
  * Merge lookup as `make_html_row` resolves it: the first merge (in sheet
229
257
  * order) containing a cell decides; its top-left cell carries the span and
230
- * the other covered cells are skipped.
258
+ * the other covered cells are skipped. Keyed numerically by row -> col with
259
+ * a row-range bailout to avoid per-cell `${row}:${col}` string allocations.
231
260
  */
232
- const mergeLookup = (
233
- merges: XLSX.Range[]
234
- ): ((row: number, col: number) => MergeSpan | "covered" | undefined) => {
235
- if (merges.length === 0) return () => undefined;
236
- const byCell = new Map<string, MergeSpan | "covered">();
261
+ const buildMergeLookup = (merges: XLSX.Range[]): MergeLookupIndex | null => {
262
+ if (merges.length === 0) return null;
263
+ const byRow = new Map<number, Map<number, MergeSpan | "covered">>();
264
+ let minRow = Number.POSITIVE_INFINITY;
265
+ let maxRow = Number.NEGATIVE_INFINITY;
237
266
  for (let index = merges.length - 1; index >= 0; index -= 1) {
238
267
  const merge = merges[index];
239
268
  if (!merge) continue;
269
+ if (merge.s.r < minRow) minRow = merge.s.r;
270
+ if (merge.e.r > maxRow) maxRow = merge.e.r;
240
271
  for (let row = merge.s.r; row <= merge.e.r; row += 1) {
272
+ let rowMap = byRow.get(row);
273
+ if (!rowMap) {
274
+ rowMap = new Map();
275
+ byRow.set(row, rowMap);
276
+ }
241
277
  for (let col = merge.s.c; col <= merge.e.c; col += 1) {
242
- byCell.set(
243
- `${row}:${col}`,
278
+ rowMap.set(
279
+ col,
244
280
  row === merge.s.r && col === merge.s.c
245
281
  ? {
246
282
  rowspan: merge.e.r - merge.s.r + 1,
@@ -251,15 +287,15 @@ const mergeLookup = (
251
287
  }
252
288
  }
253
289
  }
254
- return (row, col) => byCell.get(`${row}:${col}`);
290
+ return byRow.size > 0 ? { minRow, maxRow, byRow } : null;
255
291
  };
256
292
 
257
293
  const readCell = (
258
294
  sheet: WorkSheet,
295
+ dense: CellObject[][] | undefined,
259
296
  row: number,
260
297
  col: number
261
298
  ): CellObject | undefined => {
262
- const dense = (sheet as { "!data"?: CellObject[][] })["!data"];
263
299
  if (dense) return dense[row]?.[col];
264
300
  return sheet[XLSX.utils.encode_cell({ r: row, c: col })] as
265
301
  | CellObject
@@ -270,23 +306,30 @@ const readCell = (
270
306
  * Markdown for one worksheet with a `!ref`, trimmed as markitdown trims it.
271
307
  * Output matches `turndown(sheet_to_html(sheet))` for the same sheet.
272
308
  */
273
- export function sheetToMarkdown(sheet: WorkSheet): string {
309
+ export async function sheetToMarkdown(sheet: WorkSheet): Promise<string> {
274
310
  // Memoized markup is per sheet: the file processor reuses one worker across
275
311
  // files, so a process-wide cache would retain every earlier workbook.
276
312
  markupCache.clear();
277
313
  const range = XLSX.utils.decode_range(sheet["!ref"] ?? "A1");
278
- const mergeAt = mergeLookup(sheet["!merges"] ?? []);
314
+ const merges = buildMergeLookup(sheet["!merges"] ?? []);
315
+ const dense = (sheet as { "!data"?: CellObject[][] })["!data"];
279
316
  const rows: string[] = [];
280
317
  let columnCount = 0;
281
318
  let onlyCell: string | null = null;
282
319
  let firstRowCells = 0;
283
320
  for (let row = range.s.r; row <= range.e.r; row += 1) {
321
+ const rowMerges =
322
+ merges && row >= merges.minRow && row <= merges.maxRow
323
+ ? merges.byRow.get(row)
324
+ : undefined;
284
325
  const cells: string[] = [];
285
326
  let cellCount = 0;
286
327
  for (let col = range.s.c; col <= range.e.c; col += 1) {
287
- const merge = mergeAt(row, col);
328
+ const merge = rowMerges?.get(col);
288
329
  if (merge === "covered") continue;
289
- const content = cellContent(readCell(sheet, row, col));
330
+ const rawContent = cellContent(readCell(sheet, dense, row, col));
331
+ const content =
332
+ typeof rawContent === "string" ? rawContent : await rawContent;
290
333
  cells.push(formatCell(content, cellCount === 0, merge?.colspan ?? 1));
291
334
  cellCount += 1;
292
335
  onlyCell = content;