@outkit-dev/react 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Outkit, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -22,11 +22,12 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AIRenderer: () => AIRenderer,
24
24
  OUTKIT_TOKENS: () => import_renderer2.OUTKIT_TOKENS,
25
- completePartialJson: () => completePartialJson,
26
- expandWireBlock: () => expandWireBlock,
27
- extractCompleteBlocks: () => extractCompleteBlocks,
28
- isRenderableBlock: () => isRenderableBlock,
29
- parseStreamingBlocks: () => parseStreamingBlocks,
25
+ OutkitStream: () => import_core2.OutkitStream,
26
+ completePartialJson: () => import_core3.completePartialJson,
27
+ expandWireBlock: () => import_core3.expandWireBlock,
28
+ extractCompleteBlocks: () => import_core3.extractCompleteBlocks,
29
+ isRenderableBlock: () => import_core3.isRenderableBlock,
30
+ parseStreamingBlocks: () => import_core3.parseStreamingBlocks,
30
31
  useBlockStream: () => useBlockStream
31
32
  });
32
33
  module.exports = __toCommonJS(index_exports);
@@ -227,150 +228,8 @@ var SingleComponent = (0, import_react.memo)(function SingleComponent2({
227
228
  });
228
229
 
229
230
  // src/use-block-stream.ts
231
+ var import_core = require("@outkit-dev/core");
230
232
  var import_react2 = require("react");
231
-
232
- // src/streaming/complete-partial-json.ts
233
- function completePartialJson(partial) {
234
- let inString = false;
235
- let escaped = false;
236
- const stack = [];
237
- for (let i = 0; i < partial.length; i++) {
238
- const ch = partial[i];
239
- if (escaped) {
240
- escaped = false;
241
- continue;
242
- }
243
- if (ch === "\\" && inString) {
244
- escaped = true;
245
- continue;
246
- }
247
- if (ch === '"') {
248
- inString = !inString;
249
- continue;
250
- }
251
- if (inString) continue;
252
- if (ch === "{") stack.push("}");
253
- else if (ch === "[") stack.push("]");
254
- else if ((ch === "}" || ch === "]") && stack.length > 0 && stack[stack.length - 1] === ch) {
255
- stack.pop();
256
- }
257
- }
258
- let result = partial;
259
- if (inString) {
260
- if (escaped) result = result.slice(0, -1);
261
- const trailingUnicode = result.match(/\\u[0-9a-fA-F]{0,3}$/);
262
- if (trailingUnicode) {
263
- result = result.slice(0, -trailingUnicode[0].length);
264
- }
265
- result += '"';
266
- }
267
- while (stack.length > 0) {
268
- result += stack.pop();
269
- }
270
- return result;
271
- }
272
-
273
- // src/streaming/parse-streaming-blocks.ts
274
- function expandWireBlock(block) {
275
- if ("type" in block && "component" in block) return block;
276
- if ("type" in block && block.type === "text") return block;
277
- if (typeof block.c === "string" && typeof block.p === "object" && block.p !== null) {
278
- return {
279
- type: "component",
280
- component: block.c,
281
- version: block.v ?? "1.0",
282
- props: block.p,
283
- ...block.f !== void 0 ? { fallback: block.f } : {},
284
- ...block.m ? { meta: block.m } : {}
285
- };
286
- }
287
- return block;
288
- }
289
- function isRenderableBlock(block) {
290
- if (!block || typeof block !== "object") return false;
291
- const b = block;
292
- if (b.type === "text" && typeof b.content === "string" && b.content.length > 0)
293
- return true;
294
- if (b.type === "component" && typeof b.component === "string" && b.component.length >= 2 && typeof b.props === "object" && b.props !== null)
295
- return true;
296
- return false;
297
- }
298
- function extractCompleteBlocks(accumulated) {
299
- const blocksIdx = accumulated.indexOf('"blocks"');
300
- let arrayStart = -1;
301
- if (blocksIdx !== -1) {
302
- arrayStart = accumulated.indexOf("[", blocksIdx);
303
- } else {
304
- arrayStart = accumulated.indexOf("[");
305
- }
306
- if (arrayStart === -1) return [];
307
- const content = accumulated.slice(arrayStart + 1);
308
- const blocks = [];
309
- let depth = 0;
310
- let blockStart = -1;
311
- let inString = false;
312
- let escaped = false;
313
- for (let i = 0; i < content.length; i++) {
314
- const ch = content[i];
315
- if (escaped) {
316
- escaped = false;
317
- continue;
318
- }
319
- if (ch === "\\" && inString) {
320
- escaped = true;
321
- continue;
322
- }
323
- if (ch === '"') {
324
- inString = !inString;
325
- continue;
326
- }
327
- if (inString) continue;
328
- if (ch === "{") {
329
- if (depth === 0) blockStart = i;
330
- depth++;
331
- } else if (ch === "}") {
332
- depth--;
333
- if (depth === 0 && blockStart !== -1) {
334
- try {
335
- const parsed = JSON.parse(content.slice(blockStart, i + 1));
336
- const expanded = expandWireBlock(parsed);
337
- if (isRenderableBlock(expanded)) blocks.push(expanded);
338
- } catch {
339
- }
340
- blockStart = -1;
341
- }
342
- }
343
- }
344
- return blocks;
345
- }
346
- function parseStreamingBlocks(accumulated) {
347
- if (!accumulated.trim()) return [];
348
- let target = accumulated;
349
- const blocksIdx = accumulated.indexOf('"blocks"');
350
- if (blocksIdx > 0) {
351
- let braceIdx = blocksIdx - 1;
352
- while (braceIdx >= 0 && accumulated[braceIdx] !== "{") braceIdx--;
353
- if (braceIdx > 0) target = accumulated.slice(braceIdx);
354
- }
355
- const patched = completePartialJson(target);
356
- try {
357
- const parsed = JSON.parse(patched);
358
- const rawBlocks = parsed?.blocks ?? (Array.isArray(parsed) ? parsed : []);
359
- return rawBlocks.map((b) => {
360
- if (!b || typeof b !== "object") return b;
361
- return expandWireBlock(b);
362
- }).filter(isRenderableBlock).map((block) => {
363
- if (!("version" in block)) {
364
- return Object.assign({}, block, { version: "1.0" });
365
- }
366
- return block;
367
- });
368
- } catch {
369
- return extractCompleteBlocks(accumulated);
370
- }
371
- }
372
-
373
- // src/use-block-stream.ts
374
233
  function useBlockStream() {
375
234
  const [blocks, setBlocks] = (0, import_react2.useState)([]);
376
235
  const [isStreaming, setIsStreaming] = (0, import_react2.useState)(false);
@@ -378,7 +237,6 @@ function useBlockStream() {
378
237
  const pendingRef = (0, import_react2.useRef)(null);
379
238
  const rafRef = (0, import_react2.useRef)(0);
380
239
  const streamingRef = (0, import_react2.useRef)(false);
381
- const accumulatedRef = (0, import_react2.useRef)("");
382
240
  const flush = (0, import_react2.useCallback)(() => {
383
241
  rafRef.current = 0;
384
242
  if (pendingRef.current !== null) {
@@ -386,7 +244,7 @@ function useBlockStream() {
386
244
  pendingRef.current = null;
387
245
  }
388
246
  }, []);
389
- const push = (0, import_react2.useCallback)(
247
+ const batchBlocks = (0, import_react2.useCallback)(
390
248
  (newBlocks) => {
391
249
  if (!streamingRef.current) {
392
250
  streamingRef.current = true;
@@ -399,10 +257,7 @@ function useBlockStream() {
399
257
  },
400
258
  [flush]
401
259
  );
402
- const setDesign = (0, import_react2.useCallback)((tokens) => {
403
- setDesignState(tokens);
404
- }, []);
405
- const complete = (0, import_react2.useCallback)(() => {
260
+ const handleComplete = (0, import_react2.useCallback)(() => {
406
261
  if (rafRef.current) {
407
262
  cancelAnimationFrame(rafRef.current);
408
263
  rafRef.current = 0;
@@ -414,60 +269,68 @@ function useBlockStream() {
414
269
  streamingRef.current = false;
415
270
  setIsStreaming(false);
416
271
  }, []);
272
+ const streamRef = (0, import_react2.useRef)(null);
273
+ if (streamRef.current === null) {
274
+ streamRef.current = new import_core.OutkitStream({
275
+ onBlocks: (b) => batchBlocks(b),
276
+ onDesign: (d) => setDesignState(d),
277
+ onComplete: () => handleComplete()
278
+ });
279
+ }
280
+ const stream = streamRef.current;
281
+ (0, import_react2.useEffect)(() => {
282
+ return () => {
283
+ if (rafRef.current) cancelAnimationFrame(rafRef.current);
284
+ stream.destroy();
285
+ };
286
+ }, [stream]);
417
287
  const reset = (0, import_react2.useCallback)(() => {
418
288
  if (rafRef.current) {
419
289
  cancelAnimationFrame(rafRef.current);
420
290
  rafRef.current = 0;
421
291
  }
422
292
  pendingRef.current = null;
423
- accumulatedRef.current = "";
424
293
  streamingRef.current = false;
294
+ stream.reset();
425
295
  setBlocks([]);
426
296
  setIsStreaming(false);
427
297
  setDesignState(void 0);
428
- }, []);
429
- const feedChunk = (0, import_react2.useCallback)(
430
- (data) => {
431
- accumulatedRef.current += data;
432
- const parsed = parseStreamingBlocks(accumulatedRef.current);
433
- if (parsed.length > 0) {
434
- push(parsed);
435
- }
436
- },
437
- [push]
298
+ }, [stream]);
299
+ const push = (0, import_react2.useCallback)(
300
+ (newBlocks) => batchBlocks(newBlocks),
301
+ [batchBlocks]
438
302
  );
439
- const feedMeta = (0, import_react2.useCallback)(
440
- (tokens) => {
441
- setDesignState(tokens);
442
- },
443
- []
303
+ const setDesign = (0, import_react2.useCallback)(
304
+ (tokens) => stream.feedMeta(tokens),
305
+ [stream]
444
306
  );
445
- const feedDone = (0, import_react2.useCallback)(() => {
446
- if (accumulatedRef.current) {
447
- const parsed = parseStreamingBlocks(accumulatedRef.current);
448
- if (parsed.length > 0) {
449
- pendingRef.current = parsed;
450
- }
451
- }
452
- accumulatedRef.current = "";
453
- complete();
454
- }, [complete]);
455
- (0, import_react2.useEffect)(() => {
456
- return () => {
457
- if (rafRef.current) {
458
- cancelAnimationFrame(rafRef.current);
459
- }
460
- };
461
- }, []);
462
- return { blocks, isStreaming, design, feedChunk, feedMeta, feedDone, push, setDesign, complete, reset };
307
+ const complete = (0, import_react2.useCallback)(() => stream.feedDone(), [stream]);
308
+ return {
309
+ blocks,
310
+ isStreaming,
311
+ design,
312
+ feedResponse: stream.feedResponse.bind(stream),
313
+ feedSSE: stream.feedSSE.bind(stream),
314
+ feedEvent: stream.feedEvent.bind(stream),
315
+ feedChunk: stream.feedChunk.bind(stream),
316
+ feedMeta: stream.feedMeta.bind(stream),
317
+ feedDone: stream.feedDone.bind(stream),
318
+ push,
319
+ setDesign,
320
+ complete,
321
+ reset
322
+ };
463
323
  }
464
324
 
465
325
  // src/index.ts
326
+ var import_core2 = require("@outkit-dev/core");
327
+ var import_core3 = require("@outkit-dev/core");
466
328
  var import_renderer2 = require("@outkit-dev/renderer");
467
329
  // Annotate the CommonJS export names for ESM import in node:
468
330
  0 && (module.exports = {
469
331
  AIRenderer,
470
332
  OUTKIT_TOKENS,
333
+ OutkitStream,
471
334
  completePartialJson,
472
335
  expandWireBlock,
473
336
  extractCompleteBlocks,
package/dist/index.d.cts CHANGED
@@ -2,6 +2,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ContentBlock, ComponentBlock, OutkitInteractionEvent } from '@outkit-dev/renderer';
3
3
  export { ComponentBlock, ContentBlock, InlineAnnotation, OUTKIT_TOKENS, OutkitEnhanceResult, OutkitInteractionEvent } from '@outkit-dev/renderer';
4
4
  import React from 'react';
5
+ export { OutkitStream, OutkitStreamCallbacks, OutkitStreamState, completePartialJson, expandWireBlock, extractCompleteBlocks, isRenderableBlock, parseStreamingBlocks } from '@outkit-dev/core';
5
6
 
6
7
  interface AIRendererProps {
7
8
  /** Array of content blocks from outkit_enhance */
@@ -43,69 +44,36 @@ interface UseBlockStreamReturn {
43
44
  isStreaming: boolean;
44
45
  /** Design tokens received from the stream's meta event. Pass to <AIRenderer design={design} />. */
45
46
  design: Record<string, string> | undefined;
46
- /** Append a raw SSE data chunk. Parses accumulated buffer and updates blocks. */
47
+ /** Feed a raw fetch Response. Handles SSE parsing, meta detection, and completion. */
48
+ feedResponse: (response: Response) => Promise<void>;
49
+ /** Feed raw SSE-formatted text. Handles splitting, data: stripping, and routing. */
50
+ feedSSE: (rawText: string) => void;
51
+ /** Feed one unwrapped event payload. Handles [DONE], meta detection, and chunks. */
52
+ feedEvent: (data: string) => void;
53
+ /** Append a raw LLM data chunk. Parses accumulated buffer and updates blocks. */
47
54
  feedChunk: (data: string) => void;
48
- /** Set design tokens from a meta SSE event. Alias for setDesign. */
55
+ /** Set design tokens from a meta SSE event. */
49
56
  feedMeta: (tokens: Record<string, string>) => void;
50
57
  /** Signal end of stream. Final parse + flush + mark complete. */
51
58
  feedDone: () => void;
52
- /** Push a new full blocks array (the latest snapshot). Batched at 60fps. */
59
+ /** @deprecated Use feedChunk/feedResponse instead. Direct block snapshot setter. */
53
60
  push: (blocks: ContentBlock[]) => void;
54
- /** Set design tokens (typically from a meta SSE event). */
61
+ /** @deprecated Use feedMeta instead. */
55
62
  setDesign: (tokens: Record<string, string>) => void;
56
- /** Signal that streaming is complete. Flushes any pending update. */
63
+ /** @deprecated Use feedDone instead. */
57
64
  complete: () => void;
58
- /** Reset to empty state. */
65
+ /** Reset to empty state. Aborts any in-flight feedResponse. */
59
66
  reset: () => void;
60
67
  }
61
68
  /**
62
- * Hook that batches rapid block updates to 60fps via requestAnimationFrame.
69
+ * React hook for streaming Outkit blocks with rAF-batched updates at 60fps.
63
70
  *
64
- * Usage:
65
- * ```tsx
66
- * const { blocks, isStreaming, push, complete } = useBlockStream();
67
- *
68
- * useEffect(() => {
69
- * const es = new EventSource("/stream");
70
- * es.onmessage = (e) => push(JSON.parse(e.data).blocks);
71
- * es.addEventListener("done", () => complete());
72
- * return () => es.close();
73
- * }, [push, complete]);
74
- *
75
- * return <AIRenderer blocks={blocks} streaming={isStreaming} />;
76
- * ```
71
+ * Four-tier API — pick the tier that matches your transport:
72
+ * - `feedResponse(res)` — fetch proxy (most common, handles everything)
73
+ * - `feedSSE(text)` raw SSE bytes (manual reader)
74
+ * - `feedEvent(data)` — one unwrapped payload (WebSocket, Socket.IO)
75
+ * - `feedChunk/feedMeta/feedDone` — full manual control
77
76
  */
78
77
  declare function useBlockStream(): UseBlockStreamReturn;
79
78
 
80
- /**
81
- * Close unclosed strings, arrays, and objects so partial JSON can be parsed.
82
- *
83
- * As the LLM streams a JSON structure token by token, this function patches
84
- * the accumulated buffer into valid JSON at every chunk boundary. This lets
85
- * content stream character-by-character while remaining parseable.
86
- */
87
- declare function completePartialJson(partial: string): string;
88
-
89
- /** Expand a compact wire-format block (c/v/p/f/m) into the full ContentBlock shape. */
90
- declare function expandWireBlock(block: Record<string, unknown>): Record<string, unknown>;
91
- /** Check if a parsed object is a renderable block. */
92
- declare function isRenderableBlock(block: unknown): block is ContentBlock;
93
- /** Fallback: extract only fully brace-matched block objects from accumulated data. */
94
- declare function extractCompleteBlocks(accumulated: string): ContentBlock[];
95
- /**
96
- * Parse streaming LLM JSON into renderable blocks.
97
- *
98
- * Call this with the full accumulated buffer on every chunk. It closes
99
- * unclosed strings/arrays/objects via `completePartialJson`, parses the
100
- * result, and returns all currently renderable blocks.
101
- *
102
- * Handles both wire format (`{ c, v, p }`) and expanded format
103
- * (`{ type, component, version, props }`). The renderer's `normalizeBlock()`
104
- * also handles wire format at render time as a further safety net.
105
- *
106
- * @param accumulated - The full accumulated raw LLM output so far
107
- * @returns Array of renderable ContentBlock objects
108
- */
109
- declare function parseStreamingBlocks(accumulated: string): ContentBlock[];
110
-
111
- export { AIRenderer, type AIRendererProps, type UseBlockStreamReturn, completePartialJson, expandWireBlock, extractCompleteBlocks, isRenderableBlock, parseStreamingBlocks, useBlockStream };
79
+ export { AIRenderer, type AIRendererProps, type UseBlockStreamReturn, useBlockStream };
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ContentBlock, ComponentBlock, OutkitInteractionEvent } from '@outkit-dev/renderer';
3
3
  export { ComponentBlock, ContentBlock, InlineAnnotation, OUTKIT_TOKENS, OutkitEnhanceResult, OutkitInteractionEvent } from '@outkit-dev/renderer';
4
4
  import React from 'react';
5
+ export { OutkitStream, OutkitStreamCallbacks, OutkitStreamState, completePartialJson, expandWireBlock, extractCompleteBlocks, isRenderableBlock, parseStreamingBlocks } from '@outkit-dev/core';
5
6
 
6
7
  interface AIRendererProps {
7
8
  /** Array of content blocks from outkit_enhance */
@@ -43,69 +44,36 @@ interface UseBlockStreamReturn {
43
44
  isStreaming: boolean;
44
45
  /** Design tokens received from the stream's meta event. Pass to <AIRenderer design={design} />. */
45
46
  design: Record<string, string> | undefined;
46
- /** Append a raw SSE data chunk. Parses accumulated buffer and updates blocks. */
47
+ /** Feed a raw fetch Response. Handles SSE parsing, meta detection, and completion. */
48
+ feedResponse: (response: Response) => Promise<void>;
49
+ /** Feed raw SSE-formatted text. Handles splitting, data: stripping, and routing. */
50
+ feedSSE: (rawText: string) => void;
51
+ /** Feed one unwrapped event payload. Handles [DONE], meta detection, and chunks. */
52
+ feedEvent: (data: string) => void;
53
+ /** Append a raw LLM data chunk. Parses accumulated buffer and updates blocks. */
47
54
  feedChunk: (data: string) => void;
48
- /** Set design tokens from a meta SSE event. Alias for setDesign. */
55
+ /** Set design tokens from a meta SSE event. */
49
56
  feedMeta: (tokens: Record<string, string>) => void;
50
57
  /** Signal end of stream. Final parse + flush + mark complete. */
51
58
  feedDone: () => void;
52
- /** Push a new full blocks array (the latest snapshot). Batched at 60fps. */
59
+ /** @deprecated Use feedChunk/feedResponse instead. Direct block snapshot setter. */
53
60
  push: (blocks: ContentBlock[]) => void;
54
- /** Set design tokens (typically from a meta SSE event). */
61
+ /** @deprecated Use feedMeta instead. */
55
62
  setDesign: (tokens: Record<string, string>) => void;
56
- /** Signal that streaming is complete. Flushes any pending update. */
63
+ /** @deprecated Use feedDone instead. */
57
64
  complete: () => void;
58
- /** Reset to empty state. */
65
+ /** Reset to empty state. Aborts any in-flight feedResponse. */
59
66
  reset: () => void;
60
67
  }
61
68
  /**
62
- * Hook that batches rapid block updates to 60fps via requestAnimationFrame.
69
+ * React hook for streaming Outkit blocks with rAF-batched updates at 60fps.
63
70
  *
64
- * Usage:
65
- * ```tsx
66
- * const { blocks, isStreaming, push, complete } = useBlockStream();
67
- *
68
- * useEffect(() => {
69
- * const es = new EventSource("/stream");
70
- * es.onmessage = (e) => push(JSON.parse(e.data).blocks);
71
- * es.addEventListener("done", () => complete());
72
- * return () => es.close();
73
- * }, [push, complete]);
74
- *
75
- * return <AIRenderer blocks={blocks} streaming={isStreaming} />;
76
- * ```
71
+ * Four-tier API — pick the tier that matches your transport:
72
+ * - `feedResponse(res)` — fetch proxy (most common, handles everything)
73
+ * - `feedSSE(text)` raw SSE bytes (manual reader)
74
+ * - `feedEvent(data)` — one unwrapped payload (WebSocket, Socket.IO)
75
+ * - `feedChunk/feedMeta/feedDone` — full manual control
77
76
  */
78
77
  declare function useBlockStream(): UseBlockStreamReturn;
79
78
 
80
- /**
81
- * Close unclosed strings, arrays, and objects so partial JSON can be parsed.
82
- *
83
- * As the LLM streams a JSON structure token by token, this function patches
84
- * the accumulated buffer into valid JSON at every chunk boundary. This lets
85
- * content stream character-by-character while remaining parseable.
86
- */
87
- declare function completePartialJson(partial: string): string;
88
-
89
- /** Expand a compact wire-format block (c/v/p/f/m) into the full ContentBlock shape. */
90
- declare function expandWireBlock(block: Record<string, unknown>): Record<string, unknown>;
91
- /** Check if a parsed object is a renderable block. */
92
- declare function isRenderableBlock(block: unknown): block is ContentBlock;
93
- /** Fallback: extract only fully brace-matched block objects from accumulated data. */
94
- declare function extractCompleteBlocks(accumulated: string): ContentBlock[];
95
- /**
96
- * Parse streaming LLM JSON into renderable blocks.
97
- *
98
- * Call this with the full accumulated buffer on every chunk. It closes
99
- * unclosed strings/arrays/objects via `completePartialJson`, parses the
100
- * result, and returns all currently renderable blocks.
101
- *
102
- * Handles both wire format (`{ c, v, p }`) and expanded format
103
- * (`{ type, component, version, props }`). The renderer's `normalizeBlock()`
104
- * also handles wire format at render time as a further safety net.
105
- *
106
- * @param accumulated - The full accumulated raw LLM output so far
107
- * @returns Array of renderable ContentBlock objects
108
- */
109
- declare function parseStreamingBlocks(accumulated: string): ContentBlock[];
110
-
111
- export { AIRenderer, type AIRendererProps, type UseBlockStreamReturn, completePartialJson, expandWireBlock, extractCompleteBlocks, isRenderableBlock, parseStreamingBlocks, useBlockStream };
79
+ export { AIRenderer, type AIRendererProps, type UseBlockStreamReturn, useBlockStream };
package/dist/index.js CHANGED
@@ -194,150 +194,8 @@ var SingleComponent = memo(function SingleComponent2({
194
194
  });
195
195
 
196
196
  // src/use-block-stream.ts
197
+ import { OutkitStream } from "@outkit-dev/core";
197
198
  import { useCallback, useEffect as useEffect2, useRef as useRef2, useState } from "react";
198
-
199
- // src/streaming/complete-partial-json.ts
200
- function completePartialJson(partial) {
201
- let inString = false;
202
- let escaped = false;
203
- const stack = [];
204
- for (let i = 0; i < partial.length; i++) {
205
- const ch = partial[i];
206
- if (escaped) {
207
- escaped = false;
208
- continue;
209
- }
210
- if (ch === "\\" && inString) {
211
- escaped = true;
212
- continue;
213
- }
214
- if (ch === '"') {
215
- inString = !inString;
216
- continue;
217
- }
218
- if (inString) continue;
219
- if (ch === "{") stack.push("}");
220
- else if (ch === "[") stack.push("]");
221
- else if ((ch === "}" || ch === "]") && stack.length > 0 && stack[stack.length - 1] === ch) {
222
- stack.pop();
223
- }
224
- }
225
- let result = partial;
226
- if (inString) {
227
- if (escaped) result = result.slice(0, -1);
228
- const trailingUnicode = result.match(/\\u[0-9a-fA-F]{0,3}$/);
229
- if (trailingUnicode) {
230
- result = result.slice(0, -trailingUnicode[0].length);
231
- }
232
- result += '"';
233
- }
234
- while (stack.length > 0) {
235
- result += stack.pop();
236
- }
237
- return result;
238
- }
239
-
240
- // src/streaming/parse-streaming-blocks.ts
241
- function expandWireBlock(block) {
242
- if ("type" in block && "component" in block) return block;
243
- if ("type" in block && block.type === "text") return block;
244
- if (typeof block.c === "string" && typeof block.p === "object" && block.p !== null) {
245
- return {
246
- type: "component",
247
- component: block.c,
248
- version: block.v ?? "1.0",
249
- props: block.p,
250
- ...block.f !== void 0 ? { fallback: block.f } : {},
251
- ...block.m ? { meta: block.m } : {}
252
- };
253
- }
254
- return block;
255
- }
256
- function isRenderableBlock(block) {
257
- if (!block || typeof block !== "object") return false;
258
- const b = block;
259
- if (b.type === "text" && typeof b.content === "string" && b.content.length > 0)
260
- return true;
261
- if (b.type === "component" && typeof b.component === "string" && b.component.length >= 2 && typeof b.props === "object" && b.props !== null)
262
- return true;
263
- return false;
264
- }
265
- function extractCompleteBlocks(accumulated) {
266
- const blocksIdx = accumulated.indexOf('"blocks"');
267
- let arrayStart = -1;
268
- if (blocksIdx !== -1) {
269
- arrayStart = accumulated.indexOf("[", blocksIdx);
270
- } else {
271
- arrayStart = accumulated.indexOf("[");
272
- }
273
- if (arrayStart === -1) return [];
274
- const content = accumulated.slice(arrayStart + 1);
275
- const blocks = [];
276
- let depth = 0;
277
- let blockStart = -1;
278
- let inString = false;
279
- let escaped = false;
280
- for (let i = 0; i < content.length; i++) {
281
- const ch = content[i];
282
- if (escaped) {
283
- escaped = false;
284
- continue;
285
- }
286
- if (ch === "\\" && inString) {
287
- escaped = true;
288
- continue;
289
- }
290
- if (ch === '"') {
291
- inString = !inString;
292
- continue;
293
- }
294
- if (inString) continue;
295
- if (ch === "{") {
296
- if (depth === 0) blockStart = i;
297
- depth++;
298
- } else if (ch === "}") {
299
- depth--;
300
- if (depth === 0 && blockStart !== -1) {
301
- try {
302
- const parsed = JSON.parse(content.slice(blockStart, i + 1));
303
- const expanded = expandWireBlock(parsed);
304
- if (isRenderableBlock(expanded)) blocks.push(expanded);
305
- } catch {
306
- }
307
- blockStart = -1;
308
- }
309
- }
310
- }
311
- return blocks;
312
- }
313
- function parseStreamingBlocks(accumulated) {
314
- if (!accumulated.trim()) return [];
315
- let target = accumulated;
316
- const blocksIdx = accumulated.indexOf('"blocks"');
317
- if (blocksIdx > 0) {
318
- let braceIdx = blocksIdx - 1;
319
- while (braceIdx >= 0 && accumulated[braceIdx] !== "{") braceIdx--;
320
- if (braceIdx > 0) target = accumulated.slice(braceIdx);
321
- }
322
- const patched = completePartialJson(target);
323
- try {
324
- const parsed = JSON.parse(patched);
325
- const rawBlocks = parsed?.blocks ?? (Array.isArray(parsed) ? parsed : []);
326
- return rawBlocks.map((b) => {
327
- if (!b || typeof b !== "object") return b;
328
- return expandWireBlock(b);
329
- }).filter(isRenderableBlock).map((block) => {
330
- if (!("version" in block)) {
331
- return Object.assign({}, block, { version: "1.0" });
332
- }
333
- return block;
334
- });
335
- } catch {
336
- return extractCompleteBlocks(accumulated);
337
- }
338
- }
339
-
340
- // src/use-block-stream.ts
341
199
  function useBlockStream() {
342
200
  const [blocks, setBlocks] = useState([]);
343
201
  const [isStreaming, setIsStreaming] = useState(false);
@@ -345,7 +203,6 @@ function useBlockStream() {
345
203
  const pendingRef = useRef2(null);
346
204
  const rafRef = useRef2(0);
347
205
  const streamingRef = useRef2(false);
348
- const accumulatedRef = useRef2("");
349
206
  const flush = useCallback(() => {
350
207
  rafRef.current = 0;
351
208
  if (pendingRef.current !== null) {
@@ -353,7 +210,7 @@ function useBlockStream() {
353
210
  pendingRef.current = null;
354
211
  }
355
212
  }, []);
356
- const push = useCallback(
213
+ const batchBlocks = useCallback(
357
214
  (newBlocks) => {
358
215
  if (!streamingRef.current) {
359
216
  streamingRef.current = true;
@@ -366,10 +223,7 @@ function useBlockStream() {
366
223
  },
367
224
  [flush]
368
225
  );
369
- const setDesign = useCallback((tokens) => {
370
- setDesignState(tokens);
371
- }, []);
372
- const complete = useCallback(() => {
226
+ const handleComplete = useCallback(() => {
373
227
  if (rafRef.current) {
374
228
  cancelAnimationFrame(rafRef.current);
375
229
  rafRef.current = 0;
@@ -381,59 +235,73 @@ function useBlockStream() {
381
235
  streamingRef.current = false;
382
236
  setIsStreaming(false);
383
237
  }, []);
238
+ const streamRef = useRef2(null);
239
+ if (streamRef.current === null) {
240
+ streamRef.current = new OutkitStream({
241
+ onBlocks: (b) => batchBlocks(b),
242
+ onDesign: (d) => setDesignState(d),
243
+ onComplete: () => handleComplete()
244
+ });
245
+ }
246
+ const stream = streamRef.current;
247
+ useEffect2(() => {
248
+ return () => {
249
+ if (rafRef.current) cancelAnimationFrame(rafRef.current);
250
+ stream.destroy();
251
+ };
252
+ }, [stream]);
384
253
  const reset = useCallback(() => {
385
254
  if (rafRef.current) {
386
255
  cancelAnimationFrame(rafRef.current);
387
256
  rafRef.current = 0;
388
257
  }
389
258
  pendingRef.current = null;
390
- accumulatedRef.current = "";
391
259
  streamingRef.current = false;
260
+ stream.reset();
392
261
  setBlocks([]);
393
262
  setIsStreaming(false);
394
263
  setDesignState(void 0);
395
- }, []);
396
- const feedChunk = useCallback(
397
- (data) => {
398
- accumulatedRef.current += data;
399
- const parsed = parseStreamingBlocks(accumulatedRef.current);
400
- if (parsed.length > 0) {
401
- push(parsed);
402
- }
403
- },
404
- [push]
264
+ }, [stream]);
265
+ const push = useCallback(
266
+ (newBlocks) => batchBlocks(newBlocks),
267
+ [batchBlocks]
405
268
  );
406
- const feedMeta = useCallback(
407
- (tokens) => {
408
- setDesignState(tokens);
409
- },
410
- []
269
+ const setDesign = useCallback(
270
+ (tokens) => stream.feedMeta(tokens),
271
+ [stream]
411
272
  );
412
- const feedDone = useCallback(() => {
413
- if (accumulatedRef.current) {
414
- const parsed = parseStreamingBlocks(accumulatedRef.current);
415
- if (parsed.length > 0) {
416
- pendingRef.current = parsed;
417
- }
418
- }
419
- accumulatedRef.current = "";
420
- complete();
421
- }, [complete]);
422
- useEffect2(() => {
423
- return () => {
424
- if (rafRef.current) {
425
- cancelAnimationFrame(rafRef.current);
426
- }
427
- };
428
- }, []);
429
- return { blocks, isStreaming, design, feedChunk, feedMeta, feedDone, push, setDesign, complete, reset };
273
+ const complete = useCallback(() => stream.feedDone(), [stream]);
274
+ return {
275
+ blocks,
276
+ isStreaming,
277
+ design,
278
+ feedResponse: stream.feedResponse.bind(stream),
279
+ feedSSE: stream.feedSSE.bind(stream),
280
+ feedEvent: stream.feedEvent.bind(stream),
281
+ feedChunk: stream.feedChunk.bind(stream),
282
+ feedMeta: stream.feedMeta.bind(stream),
283
+ feedDone: stream.feedDone.bind(stream),
284
+ push,
285
+ setDesign,
286
+ complete,
287
+ reset
288
+ };
430
289
  }
431
290
 
432
291
  // src/index.ts
292
+ import { OutkitStream as OutkitStream2 } from "@outkit-dev/core";
293
+ import {
294
+ parseStreamingBlocks,
295
+ completePartialJson,
296
+ expandWireBlock,
297
+ isRenderableBlock,
298
+ extractCompleteBlocks
299
+ } from "@outkit-dev/core";
433
300
  import { OUTKIT_TOKENS } from "@outkit-dev/renderer";
434
301
  export {
435
302
  AIRenderer,
436
303
  OUTKIT_TOKENS,
304
+ OutkitStream2 as OutkitStream,
437
305
  completePartialJson,
438
306
  expandWireBlock,
439
307
  extractCompleteBlocks,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outkit-dev/react",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -15,15 +15,9 @@
15
15
  "files": [
16
16
  "dist"
17
17
  ],
18
- "scripts": {
19
- "build": "tsup src/index.ts --format esm,cjs --dts --clean --external react",
20
- "dev": "tsup src/index.ts --format esm,cjs --dts --watch --external react",
21
- "typecheck": "tsc --noEmit",
22
- "test": "echo 'no tests configured' && exit 1",
23
- "clean": "rm -rf dist .turbo"
24
- },
25
18
  "dependencies": {
26
- "@outkit-dev/renderer": "workspace:*"
19
+ "@outkit-dev/renderer": "0.0.5",
20
+ "@outkit-dev/core": "0.0.6"
27
21
  },
28
22
  "peerDependencies": {
29
23
  "react": "^18.0.0 || ^19.0.0"
@@ -33,5 +27,12 @@
33
27
  "react": "^19.0.0",
34
28
  "tsup": "^8.3.0",
35
29
  "typescript": "^5.7.0"
30
+ },
31
+ "scripts": {
32
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --external react",
33
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch --external react",
34
+ "typecheck": "tsc --noEmit",
35
+ "test": "echo 'no tests configured' && exit 1",
36
+ "clean": "rm -rf dist .turbo"
36
37
  }
37
- }
38
+ }