@deepseek-ai/libreoffice-kit 0.1.5 → 0.2.0-alpha6

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 (77) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +44 -8
  3. package/README.zh.md +45 -9
  4. package/frame-forwarding/CMakeLists.txt +40 -0
  5. package/frame-forwarding/LICENSE +21 -0
  6. package/frame-forwarding/README.md +83 -0
  7. package/frame-forwarding/README.zh.md +83 -0
  8. package/frame-forwarding/include/dsh_frame_forwarding.h +101 -0
  9. package/frame-forwarding/include/dsh_frame_forwarding_engine.h +66 -0
  10. package/frame-forwarding/include/dsh_frame_forwarding_node.h +27 -0
  11. package/frame-forwarding/include/dsh_webgpu.h +52 -0
  12. package/frame-forwarding/index.d.ts +145 -0
  13. package/frame-forwarding/index.mjs +71 -0
  14. package/frame-forwarding/lib/browser/display.d.ts +46 -0
  15. package/frame-forwarding/lib/browser/display.js +128 -0
  16. package/frame-forwarding/lib/browser/index.d.ts +4 -0
  17. package/frame-forwarding/lib/browser/index.js +3 -0
  18. package/frame-forwarding/lib/browser/painters.d.ts +9 -0
  19. package/frame-forwarding/lib/browser/painters.js +180 -0
  20. package/frame-forwarding/lib/browser/types.d.ts +51 -0
  21. package/frame-forwarding/lib/browser/types.js +1 -0
  22. package/frame-forwarding/lib/electron/adapter.d.ts +9 -0
  23. package/frame-forwarding/lib/electron/adapter.js +118 -0
  24. package/frame-forwarding/lib/electron/index.d.ts +3 -0
  25. package/frame-forwarding/lib/electron/index.js +3 -0
  26. package/frame-forwarding/lib/electron/preload.d.ts +13 -0
  27. package/frame-forwarding/lib/electron/preload.js +47 -0
  28. package/frame-forwarding/lib/electron/transfer.d.ts +15 -0
  29. package/frame-forwarding/lib/electron/transfer.js +36 -0
  30. package/frame-forwarding/prebuilds/darwin-arm64/frame-forwarding.node +0 -0
  31. package/frame-forwarding/prebuilds/darwin-arm64/libdsh_frame_forwarding_sdk.a +0 -0
  32. package/frame-forwarding/prebuilds/darwin-arm64/manifest.json +34 -0
  33. package/frame-forwarding/prebuilds/darwin-x64/frame-forwarding.node +0 -0
  34. package/frame-forwarding/prebuilds/darwin-x64/libdsh_frame_forwarding_sdk.a +0 -0
  35. package/frame-forwarding/prebuilds/darwin-x64/manifest.json +34 -0
  36. package/frame-forwarding/prebuilds/win32-arm64/dsh_frame_forwarding_sdk.lib +0 -0
  37. package/frame-forwarding/prebuilds/win32-arm64/frame-forwarding.node +0 -0
  38. package/frame-forwarding/prebuilds/win32-arm64/manifest.json +34 -0
  39. package/frame-forwarding/prebuilds/win32-x64/dsh_frame_forwarding_sdk.lib +0 -0
  40. package/frame-forwarding/prebuilds/win32-x64/frame-forwarding.node +0 -0
  41. package/frame-forwarding/prebuilds/win32-x64/manifest.json +34 -0
  42. package/frame-forwarding/receipt.json +23 -0
  43. package/frame-forwarding/scripts/build-webgpu.mjs +197 -0
  44. package/frame-forwarding/scripts/build.mjs +43 -0
  45. package/frame-forwarding/scripts/metadata.mjs +47 -0
  46. package/frame-forwarding/scripts/source-identity.mjs +15 -0
  47. package/frame-forwarding/scripts/verify-prebuilds.mjs +14 -0
  48. package/frame-forwarding/sdk.json +45 -0
  49. package/frame-forwarding/src/node-producer.cc +595 -0
  50. package/frame-forwarding/src/producer-internal.h +8 -0
  51. package/frame-forwarding/src/producer.cc +306 -0
  52. package/frame-forwarding/src/receiver.cc +1050 -0
  53. package/frame-forwarding/src/relay-transport.inc +293 -0
  54. package/frame-forwarding/src/transport.cc +405 -0
  55. package/frame-forwarding/src/transport.h +80 -0
  56. package/frame-forwarding/src/webgpu.cc +214 -0
  57. package/frame-forwarding/src/win-delay-load.LICENSE +24 -0
  58. package/frame-forwarding/src/win-delay-load.cc +43 -0
  59. package/frame-forwarding/verify.d.mts +4 -0
  60. package/frame-forwarding/verify.mjs +101 -0
  61. package/frame-forwarding/webgpu-dependencies.json +51 -0
  62. package/lib/cli.js +109 -46
  63. package/lib/editor.js +2061 -0
  64. package/lib/index.js +109 -46
  65. package/lib/types/editor-protocol.d.ts +29 -0
  66. package/lib/types/editor-transport.d.ts +36 -0
  67. package/lib/types/editor-types.d.ts +119 -0
  68. package/lib/types/editor.d.ts +105 -0
  69. package/lib/types/engine.d.ts +4 -2
  70. package/lib/types/fonts.d.ts +4 -8
  71. package/lib/types/native-image-renderer.d.ts +0 -1
  72. package/lib/types/native-process.d.ts +1 -0
  73. package/lib/types/native.d.ts +30 -2
  74. package/lib/types/runtime.d.ts +2 -0
  75. package/lib/types/worker.d.ts +2 -2
  76. package/lib/worker.js +38 -31
  77. package/package.json +94 -9
@@ -0,0 +1,101 @@
1
+ #ifndef DSH_FRAME_FORWARDING_H
2
+ #define DSH_FRAME_FORWARDING_H
3
+ #include <stddef.h>
4
+ #include <stdint.h>
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+ #define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 1
9
+ #define DSH_FRAME_FORWARDING_TEXT_CAPACITY 16384
10
+ /** Opaque connected producer. One thread may poll while another acquires, writes,
11
+ * submits or discards. Callers must serialize use of the same graphics context.
12
+ */
13
+ typedef struct dsh_frame_forwarding_client dsh_frame_forwarding_client;
14
+ /** Pool-owned surface. Borrowed resources and imported objects are usable only
15
+ * during the acquisition; never destroy the SDK-owned resource.
16
+ */
17
+ typedef struct dsh_frame_forwarding_surface dsh_frame_forwarding_surface;
18
+ /** kind: 0 credit/timeout, 1 incoming JSON, -1 closed/error.
19
+ * Terminal events carry diagnostic text when available.
20
+ */
21
+ typedef struct dsh_frame_forwarding_event { int kind; char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY]; } dsh_frame_forwarding_event;
22
+ /** Connect to a private receiver. Blocks until the receiver binds this process. */
23
+ dsh_frame_forwarding_client* dsh_frame_forwarding_connect(const char* endpoint, char* error, size_t error_size);
24
+ /** Connect using the application's ID3D11Device on Windows; NULL selects the default
25
+ * device. The client retains a device reference until close. macOS requires NULL.
26
+ * Serialize the device's immediate context with all SDK writes.
27
+ */
28
+ dsh_frame_forwarding_client* dsh_frame_forwarding_connect_with_device(const char* endpoint, void* device, char* error, size_t error_size);
29
+ /** Bounded connection options. cancelled is optional and runs on the connecting
30
+ * thread; its context must remain alive until connect_with_options returns.
31
+ */
32
+ typedef struct dsh_frame_forwarding_connect_options {
33
+ void* device;
34
+ uint32_t timeout_ms;
35
+ void* cancellation_context;
36
+ int (*cancelled)(void*);
37
+ } dsh_frame_forwarding_connect_options;
38
+ /** Connect with a positive timeout and optional cancellation, including PID bind
39
+ * waiting. Device ownership and platform rules match connect_with_device.
40
+ */
41
+ dsh_frame_forwarding_client* dsh_frame_forwarding_connect_with_options(const char* endpoint,
42
+ const dsh_frame_forwarding_connect_options* options, char* error, size_t error_size);
43
+ /** Acquire BGRA8 premultiplied top-left pixels; NULL means allocation pending or no credit; poll reports terminal allocation errors. */
44
+ dsh_frame_forwarding_surface* dsh_frame_forwarding_acquire(dsh_frame_forwarding_client* client, uint32_t width, uint32_t height);
45
+ /** Borrow an IOSurfaceRef (macOS) or ID3D11Texture2D* (Windows) while acquired.
46
+ * Windows external writers acquire/release key 0 around GPU commands (see
47
+ * surface_keyed_mutex); macOS writers complete GPU writes before submit/discard.
48
+ * Release imported objects/views before ending the acquisition.
49
+ */
50
+ void* dsh_frame_forwarding_surface_native(dsh_frame_forwarding_surface* surface);
51
+ /** Borrow the Windows shared NT handle while this surface is acquired; NULL on macOS.
52
+ * Do not close the borrowed handle. External imports must synchronize with key 0
53
+ * and release access and imported objects before submit/discard.
54
+ */
55
+ void* dsh_frame_forwarding_surface_shared_handle(dsh_frame_forwarding_surface* surface);
56
+ /** Return the ID3D11Device* borrowed until client close, or NULL on macOS.
57
+ * External GPU imports must use the same adapter as this device.
58
+ */
59
+ void* dsh_frame_forwarding_device(dsh_frame_forwarding_client* client);
60
+ /** Borrow the acquired Windows surface's IDXGIKeyedMutex, or NULL on macOS.
61
+ * acquire itself never locks. External writers acquire key 0 before issuing GPU
62
+ * commands and release key 0 before submit/discard, without waiting for completion.
63
+ * SDK write_bgra and engine render own this lock; do not lock around those calls.
64
+ * Do not release the borrowed COM reference. AcquireSync may block the CPU.
65
+ */
66
+ void* dsh_frame_forwarding_surface_keyed_mutex(dsh_frame_forwarding_surface* surface);
67
+ /** Copy CPU BGRA rows; return 1 on success, 0 on failure.
68
+ * Windows acquires key 0 with a 1000 ms timeout and releases it after enqueueing
69
+ * the upload. Input memory may be reused on return; GPU completion is asynchronous.
70
+ */
71
+ int dsh_frame_forwarding_write_bgra(dsh_frame_forwarding_surface* surface, const void* pixels, size_t stride);
72
+ /** CPU upload with a positive keyed-mutex acquisition timeout. Failure leaves completion
73
+ * uncertain; close the client without discarding or reusing the acquisition.
74
+ */
75
+ int dsh_frame_forwarding_write_bgra_with_timeout(dsh_frame_forwarding_surface* surface, const void* pixels, size_t stride, uint32_t timeout_ms);
76
+ /** Submit after Windows GPU writes are queued and the writer released key 0;
77
+ * macOS GPU writes must be complete. Release all imported objects/views first.
78
+ * frame_id must be 1..9007199254740991 and unique among outstanding submissions.
79
+ * Return 1 on submission; the surface cannot be reused until it is reacquired.
80
+ * Return 0 on failure; a valid acquisition stays with the caller for retry or discard.
81
+ */
82
+ int dsh_frame_forwarding_submit(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json);
83
+ /** Return an acquired, unsubmitted surface under the same GPU ownership rules as
84
+ * submit. If releasing GPU access failed, terminate the connection instead of
85
+ * discarding. The next writer must acquire key 0 even after a discard.
86
+ */
87
+ void dsh_frame_forwarding_discard(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface);
88
+ /** Poll and apply credits; return event->kind. Only one thread may poll at a time.
89
+ * A negative result ends processing; preserve any diagnostic text before closing.
90
+ */
91
+ int dsh_frame_forwarding_poll(dsh_frame_forwarding_client* client, uint32_t timeout_ms, dsh_frame_forwarding_event* event);
92
+ /** Send application JSON to the receiver; never sends pixel bytes. */
93
+ int dsh_frame_forwarding_send(dsh_frame_forwarding_client* client, const char* json);
94
+ /** Interrupt polling without freeing client. Join polling thread before close. */
95
+ void dsh_frame_forwarding_interrupt(dsh_frame_forwarding_client* client);
96
+ /** Destroy producer after all its API calls have returned. Receiver references stay valid. */
97
+ void dsh_frame_forwarding_close(dsh_frame_forwarding_client* client);
98
+ #ifdef __cplusplus
99
+ }
100
+ #endif
101
+ #endif
@@ -0,0 +1,66 @@
1
+ #ifndef DSH_FRAME_FORWARDING_ENGINE_H
2
+ #define DSH_FRAME_FORWARDING_ENGINE_H
3
+ #include <stddef.h>
4
+ #include <stdint.h>
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+ /** A borrowed GPU target valid only during render(). Native objects never enter JS. */
9
+ typedef struct dsh_frame_forwarding_target {
10
+ void* texture; /* IOSurfaceRef on macOS; ID3D11Texture2D* on Windows. */
11
+ void* shared_handle; /* Borrowed Windows NT handle; NULL on macOS. */
12
+ void* device; /* Borrowed ID3D11Device*; NULL on macOS. */
13
+ uint32_t width, height;
14
+ uint64_t frame_id, input_sequence;
15
+ double time_seconds; /* Monotonic time since this producer was created. */
16
+ void* cancellation_context;
17
+ int (*cancelled)(void*); /* Close or operation deadline; callable from this worker. */
18
+ } dsh_frame_forwarding_target;
19
+ /** Native engine adapter ABI v1. The factory and its configuration outlive the
20
+ * producer. Every callback runs serially on that producer's native worker.
21
+ * create/destroy own one engine instance; device returns its borrowed D3D11
22
+ * device (or NULL for default/macOS). update receives bounded application JSON.
23
+ * On Windows the SDK owns key 0 around render: queue commands on target.device's
24
+ * immediate context without acquiring the mutex again. Release imported views
25
+ * before returning 1; no completion wait is required. On macOS GPU writes must
26
+ * be complete on return. External devices/import APIs that acquire their own lock
27
+ * use the C surface API instead of this callback. Return 0 with diagnostic text on failure; the producer closes
28
+ * instead of reusing a target whose completion is uncertain. Long-running work
29
+ * must observe target.cancelled. No callback may throw across this C ABI.
30
+ */
31
+ typedef struct dsh_frame_forwarding_engine_v1 {
32
+ uint32_t version, size;
33
+ void* configuration;
34
+ void* (*create)(void* configuration, char* error, size_t error_size);
35
+ void (*destroy)(void* engine);
36
+ void* (*device)(void* engine);
37
+ int (*update)(void* engine, const char* json, char* error, size_t error_size);
38
+ int (*render)(void* engine, const dsh_frame_forwarding_target* target, char* error, size_t error_size);
39
+ } dsh_frame_forwarding_engine_v1;
40
+ /** Surface-free frame information borrowed during prepare(). */
41
+ typedef struct dsh_frame_forwarding_frame_info {
42
+ uint32_t width, height;
43
+ uint64_t input_sequence;
44
+ double time_seconds;
45
+ void* cancellation_context;
46
+ int (*cancelled)(void*);
47
+ } dsh_frame_forwarding_frame_info;
48
+ /** Engine ABI v2: base.version is 2 and base.size is sizeof(dsh_frame_forwarding_engine_v2).
49
+ * The v1 callbacks and ownership rules are unchanged. prepare runs on the same
50
+ * worker before acquiring a surface: 1 declares a changed frame, 0 declares no
51
+ * change, and -1 reports failure with diagnostic text. It must honor cancelled
52
+ * and must not acquire or access a transport surface. A declared change remains
53
+ * pending across credit waits; update may replace that pending application state
54
+ * before render. prepare continues at the stream cadence while credit is held.
55
+ * A successful render consumes the prepared state. Starting or
56
+ * resizing a stream forces one render even when prepare reports no change.
57
+ * Manual surface.render() invokes base.render directly, without prepare.
58
+ */
59
+ typedef struct dsh_frame_forwarding_engine_v2 {
60
+ dsh_frame_forwarding_engine_v1 base;
61
+ int (*prepare)(void* engine, const dsh_frame_forwarding_frame_info* frame, char* error, size_t error_size);
62
+ } dsh_frame_forwarding_engine_v2;
63
+ #ifdef __cplusplus
64
+ }
65
+ #endif
66
+ #endif
@@ -0,0 +1,27 @@
1
+ #ifndef DSH_FRAME_FORWARDING_NODE_H
2
+ #define DSH_FRAME_FORWARDING_NODE_H
3
+ #include <node_api.h>
4
+ #include "dsh_frame_forwarding_engine.h"
5
+ /** Shared type tag for engine objects produced by cooperating native addons. */
6
+ static const napi_type_tag dsh_frame_forwarding_engine_tag = {0xe1910c31bb654d4aULL, 0x9c30d42b2c88ee15ULL};
7
+ /** Export a native engine factory as an opaque JS object. The descriptor and its
8
+ * configuration must remain alive until finalize runs. The producer retains the
9
+ * object through native teardown. The addon supplying callbacks must remain
10
+ * loaded for the object's lifetime. No graphics work runs in this helper.
11
+ */
12
+ static inline napi_status dsh_frame_forwarding_export_engine(napi_env env, dsh_frame_forwarding_engine_v1* factory,
13
+ napi_finalize finalize, void* hint, napi_value* result) {
14
+ napi_status status = napi_create_object(env, result);
15
+ if (status == napi_ok) status = napi_wrap(env, *result, factory, finalize, hint, NULL);
16
+ if (status == napi_ok) {
17
+ status = napi_type_tag_object(env, *result, &dsh_frame_forwarding_engine_tag);
18
+ if (status != napi_ok) { void* removed = NULL; napi_remove_wrap(env, *result, &removed); }
19
+ }
20
+ return status;
21
+ }
22
+ /** Export v2 with the same descriptor, configuration, and addon lifetime as v1. */
23
+ static inline napi_status dsh_frame_forwarding_export_engine_v2(napi_env env, dsh_frame_forwarding_engine_v2* factory,
24
+ napi_finalize finalize, void* hint, napi_value* result) {
25
+ return dsh_frame_forwarding_export_engine(env, &factory->base, finalize, hint, result);
26
+ }
27
+ #endif
@@ -0,0 +1,52 @@
1
+ #ifndef DSH_WEBGPU_H
2
+ #define DSH_WEBGPU_H
3
+ #include "dsh_frame_forwarding.h"
4
+ #include <webgpu/webgpu.h>
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+ typedef struct DshWebGPUContext DshWebGPUContext;
9
+ typedef struct DshWebGPUFrame DshWebGPUFrame;
10
+ /** Borrowed native Dawn objects. Release producer-owned references before destroying
11
+ * the context; the SDK owns these references. No object crosses a process boundary. */
12
+ typedef struct DshWebGPUObjects {
13
+ WGPUInstance instance;
14
+ WGPUAdapter adapter;
15
+ WGPUDevice device;
16
+ WGPUQueue queue;
17
+ } DshWebGPUObjects;
18
+ /** Create a hardware Metal/D3D12 context independently of a display connection.
19
+ * descriptor may be NULL. Required shared-memory features are added by the SDK.
20
+ * Caller callbacks retain their ordinary WebGPU semantics. Returns NULL on error. */
21
+ DshWebGPUContext* dsh_webgpu_create_context(const WGPUDeviceDescriptor* descriptor,
22
+ DshWebGPUObjects* objects, char* error, size_t error_size);
23
+ /** Borrow an exclusive BGRA8 premultiplied display texture. Returns 1 when ready,
24
+ * 0 while credits are pending, -1 on error. Poll client through dsh_frame_forwarding_poll;
25
+ * this adapter never consumes application control messages. Serialize context calls.
26
+ * client must outlive every frame acquired from it. */
27
+ int dsh_webgpu_acquire(DshWebGPUContext* context, dsh_frame_forwarding_client* client,
28
+ uint32_t width, uint32_t height, DshWebGPUFrame** frame, char* error, size_t error_size);
29
+ /** Borrow the current texture; NULL after publish/discard. Supports RenderAttachment,
30
+ * TextureBinding, CopySrc and CopyDst. Retained texture/views expire at handoff. */
31
+ WGPUTexture dsh_webgpu_texture(DshWebGPUFrame* frame);
32
+ /** Publish submitted GPU writes, consuming texture access even on failure.
33
+ * Windows uses Dawn's keyed-mutex submission and closes shared access without an
34
+ * explicit completion wait. macOS waits for GPU completion. Submit all recordings
35
+ * and release renderer wrappers before calling. Dawn queue submission may block
36
+ * while acquiring a texture still used by another device.
37
+ * Returns 1 on success, 0 on failure; release_frame remains required. */
38
+ int dsh_webgpu_publish(DshWebGPUFrame* frame, uint64_t frame_id,
39
+ const char* metadata_json, char* error, size_t error_size);
40
+ /** Cancel shared access using the same synchronization as publish.
41
+ * Returns 1 on success, 0 on failure. Failed handoff or device loss quarantines the
42
+ * allocation until the client is closed. */
43
+ int dsh_webgpu_discard(DshWebGPUFrame* frame, char* error, size_t error_size);
44
+ /** Dispose the lease; an active lease is cancelled. No context/client call may race. */
45
+ void dsh_webgpu_release_frame(DshWebGPUFrame* frame);
46
+ /** Release SDK context ownership. Outstanding frames retain the device; consumers'
47
+ * imported images are owned by the existing DSH release protocol. */
48
+ void dsh_webgpu_destroy_context(DshWebGPUContext* context);
49
+ #ifdef __cplusplus
50
+ }
51
+ #endif
52
+ #endif
@@ -0,0 +1,145 @@
1
+ /** Adapter identity valid for the current OS GPU devices. */
2
+ export type FrameForwardingAdapterId = string & { readonly __frameForwardingAdapterId: unique symbol };
3
+ /** Receiver-owned delivery identity; independent of reusable producer frame IDs. */
4
+ export type FrameForwardingDeliveryId = number & { readonly __frameForwardingDeliveryId: unique symbol };
5
+ /** Messages delivered by an authenticated producer on the JavaScript thread. */
6
+ export type FrameForwardingEvent =
7
+ | { type: 'connected'; pid: number }
8
+ | { type: 'frame'; frameId: number; deliveryId: FrameForwardingDeliveryId; width: number; height: number; stride: number; metadata: string; adapterId: FrameForwardingAdapterId;
9
+ transport: 'shared-texture'; handle: Buffer;
10
+ /** Actual source descriptor declares key-0 synchronization; false for legacy producers and macOS. */
11
+ sourceKeyedMutex: boolean;
12
+ /** Windows adapter owning the output texture; null for macOS IOSurface. */
13
+ presentationAdapterId: FrameForwardingAdapterId | null }
14
+ | { type: 'message' | 'error'; text: string }
15
+ | { type: 'disconnected' };
16
+ /** Private receiver whose frame resources remain retained until explicit release. GC and Worker termination request asynchronous native cleanup. */
17
+ export interface FrameForwardingReceiver {
18
+ /** Private endpoint credential: pass only to the authorized producer. */
19
+ readonly endpoint: string;
20
+ /** Bind once to the process started by the owning plugin, before accepting frames. */
21
+ bindProducer(pid: number): void;
22
+ /** Send application JSON; throws if disconnected or larger than 16383 UTF-8 bytes. */
23
+ send(json: string): void;
24
+ /** Release after Electron allReferencesReleased; duplicate releases return false. */
25
+ release(deliveryId: FrameForwardingDeliveryId): boolean;
26
+ /**
27
+ * Stop delivery and asynchronously await GPU completion or confirmed device removal and worker exit.
28
+ * Outstanding delivered frames remain owned until release(). Unfinished copies retain their resource and budget reservations.
29
+ * A stalled driver can leave this promise and Worker termination pending; operation deadlines do not establish GPU completion.
30
+ */
31
+ close(): Promise<void>;
32
+ }
33
+ /** Opaque shared allocation budget, including producer idle surface pools. */
34
+ export interface FrameForwardingBudget { readonly __frameForwardingBudget: unique symbol }
35
+ /** Create one budget per window and share it among that window's receivers. */
36
+ export function createBudget(maxBytes: number): FrameForwardingBudget;
37
+ /** Create a receiver whose producer allocations reserve bytes from the shared budget. */
38
+ export function createReceiver(options: {
39
+ maxFrames: number; maxBytes: number; budget: FrameForwardingBudget;
40
+ /** Electron's actual adapter for shared-texture on Windows; null on macOS. */
41
+ displayAdapter: FrameForwardingAdapterId | null;
42
+ /** Total queued GPU readback/upload deadline. Expiry stops delivery; safe resource retirement may take longer. */
43
+ readbackTimeoutMs: number;
44
+ /** Ordered by default; latest permits replacing pending full-frame images. */
45
+ framePolicy?: 'ordered' | 'latest';
46
+ }, onEvent: (event: FrameForwardingEvent) => void): FrameForwardingReceiver;
47
+ /** Identify the GPU owning a borrowed native texture handle; null means unavailable. */
48
+ export function getAdapter(handle: Buffer): FrameForwardingAdapterId | null;
49
+
50
+ /** Opaque engine descriptor exported by a Node addon with dsh_frame_forwarding_export_engine(). */
51
+ export interface FrameForwardingEngine { readonly __frameForwardingEngine: unique symbol }
52
+ /** Native worker notifications delivered serially on the creating JavaScript thread. */
53
+ export type FrameForwardingProducerEvent = { type: 'message' | 'error'; text: string } | { type: 'closed' };
54
+ /** An acquired surface remains owned until submit, discard, or producer close; GC never releases it. */
55
+ export interface FrameForwardingProducerSurface {
56
+ readonly width: number;
57
+ readonly height: number;
58
+ /**
59
+ * Upload premultiplied BGRA8 pixels on the native worker. Concurrent surface operations reject.
60
+ * @param pixels Non-shared Buffer retained until settlement; do not modify, detach, or transfer its backing store meanwhile.
61
+ * @param stride Bytes between rows, at least width * 4; the buffer must cover the last complete row.
62
+ * @returns Resolves when input bytes are copied and may be reused; Windows GPU completion is asynchronous. Failure may close the producer.
63
+ */
64
+ writeBgra(pixels: Buffer, stride: number): Promise<void>;
65
+ /**
66
+ * Invoke the configured native engine on this acquired texture, without the streaming prepare callback.
67
+ * @returns Resolves after Windows commands are queued and keyed access released, or macOS GPU writes complete. A missing engine rejects without consuming the surface.
68
+ */
69
+ render(): Promise<void>;
70
+ /**
71
+ * Transfer the frame to the receiver; a successful call consumes this lease.
72
+ * @param frameId Positive safe integer, unique among outstanding frames.
73
+ * @param metadata Application JSON, at most 16383 UTF-8 bytes with no NUL.
74
+ * @returns Resolves on native submission, not display or receiver release.
75
+ */
76
+ submit(frameId: number, metadata: string): Promise<void>;
77
+ /** @returns Resolves after returning an unsubmitted, idle surface to the pool; busy or consumed leases reject. */
78
+ discard(): Promise<void>;
79
+ /** @returns The same explicit release as discard(); busy or consumed leases reject. */
80
+ close(): Promise<void>;
81
+ }
82
+ /** Options for a bounded producer worker. Application configuration supplies every limit. */
83
+ export interface FrameForwardingProducerOptions {
84
+ /** Private receiver endpoint, never a renderer-facing value or log field. */
85
+ endpoint: string;
86
+ /** Maximum ordinary operations awaiting completion, including acquisitions; 1–65536. Discard has one reserved slot per owned lease. */
87
+ maxPendingOperations: number;
88
+ /** Positive connection, queue/acquisition, and GPU-wait deadline in milliseconds. */
89
+ operationTimeoutMs: number;
90
+ /** Retained through native teardown; callbacks share one native worker and must honor cancellation. */
91
+ engine?: FrameForwardingEngine;
92
+ }
93
+ /** Native continuous rendering avoids per-frame JavaScript work and obeys receiver credits. */
94
+ export interface FrameForwardingProducerStreamOptions {
95
+ width: number;
96
+ height: number;
97
+ /** Viewport generation written into each frame's metadata. */
98
+ generation: number;
99
+ /** Target frame interval in milliseconds, at least 1; fractions such as 1000 / 60 are accepted. Rendering time is included, and elapsed deadlines are skipped without catch-up bursts. */
100
+ frameIntervalMs: number;
101
+ }
102
+ /** Producer backed by the C SDK, with explicit asynchronous teardown. */
103
+ export interface FrameForwardingProducer {
104
+ /** Resolves after engine creation and authenticated connection; queued operations may precede it. */
105
+ readonly ready: Promise<void>;
106
+ /** Resolves after worker exit, C client close, engine destruction, and pending operation settlement. */
107
+ readonly closed: Promise<void>;
108
+ /**
109
+ * Wait for native allocation credit without blocking the worker. Discard remains admissible at queue capacity.
110
+ * @param width Positive pixel width, at most 16384.
111
+ * @param height Positive pixel height, at most 16384.
112
+ * @returns An owned surface; acquisition timeout rejects this request and leaves the producer usable.
113
+ */
114
+ acquire(width: number, height: number): Promise<FrameForwardingProducerSurface>;
115
+ /**
116
+ * Queue application control independently of pending acquisitions.
117
+ * @param json Message of at most 16383 UTF-8 bytes with no NUL.
118
+ * @returns Resolves after the native send.
119
+ */
120
+ send(json: string): Promise<void>;
121
+ /**
122
+ * Start or resize native rendering and force its first frame; no acquired manual surface or pending acquisition may remain. ABI v2 engines skip unchanged frames before acquisition.
123
+ * @param options Dimensions, viewport generation, and explicit pacing.
124
+ * @returns Resolves when the worker applies the stream settings, before the first frame displays.
125
+ */
126
+ start(options: FrameForwardingProducerStreamOptions): Promise<void>;
127
+ /**
128
+ * Apply a batch of engine state before subsequent frames on the same native worker and make the next change check immediately eligible.
129
+ * @param json Engine-specific JSON of at most 16383 UTF-8 bytes with no NUL.
130
+ * @param inputSequence Nondecreasing safe integer echoed in subsequent frame metadata.
131
+ * @returns Resolves after the engine applies the update.
132
+ */
133
+ update(json: string, inputSequence: number): Promise<void>;
134
+ /** @returns Resolves once streaming stops; receiver-owned frames retain their credits until released. */
135
+ stop(): Promise<void>;
136
+ /** @returns Idempotent closed promise after interrupting connect/poll and cancellable engine waits. */
137
+ close(): Promise<void>;
138
+ }
139
+ /**
140
+ * Create a C-SDK producer worker without blocking the JavaScript event loop.
141
+ * @param options Endpoint, explicit limits, and optional native engine descriptor.
142
+ * @param onEvent Message/error/closed listener; listener exceptions are contained so teardown can complete.
143
+ * @returns A producer requiring explicit close; its native worker keeps the process alive.
144
+ */
145
+ export function createProducer(options: FrameForwardingProducerOptions, onEvent: (event: FrameForwardingProducerEvent) => void): FrameForwardingProducer;
@@ -0,0 +1,71 @@
1
+ /** Electron-independent Node-API producer and receiver for native rendering. */
2
+ import { createRequire } from 'node:module';
3
+ import { fileURLToPath } from 'node:url';
4
+ const require = createRequire(import.meta.url);
5
+ let binding;
6
+ const budgets = new WeakMap();
7
+ function loadBinding() {
8
+ return binding ??= require(fileURLToPath(new URL(`./prebuilds/${process.platform}-${process.arch}/frame-forwarding.node`, import.meta.url)));
9
+ }
10
+ /** Share one allocation budget across all native views in a window. */
11
+ export function createBudget(maxBytes) {
12
+ const budget = Object.freeze({});
13
+ budgets.set(budget, loadBinding().createBudget(maxBytes));
14
+ return budget;
15
+ }
16
+ /** Create a private native receiver. Calls onEvent only on the JavaScript thread. */
17
+ export function createReceiver({ maxFrames, maxBytes, budget, displayAdapter, readbackTimeoutMs, framePolicy = 'ordered' }, onEvent) {
18
+ loadBinding();
19
+ const allocationBudget = budgets.get(budget);
20
+ if (!allocationBudget) throw new TypeError("Receiver requires a budget from createBudget()");
21
+ if (framePolicy !== 'ordered' && framePolicy !== 'latest') throw new TypeError('Invalid native frame policy');
22
+ const { native, endpoint } = binding.create(maxFrames, maxBytes, onEvent, allocationBudget, displayAdapter === null ? '' : displayAdapter,
23
+ readbackTimeoutMs, framePolicy === 'latest');
24
+ let closed;
25
+ return {
26
+ endpoint,
27
+ bindProducer(pid) { binding.bind(native, pid); },
28
+ send(json) { binding.send(native, json); },
29
+ release(deliveryId) { return binding.release(native, deliveryId); },
30
+ close() { return closed ??= binding.close(native); },
31
+ };
32
+ }
33
+ /** Identify the adapter owning a native texture, or null when unavailable. */
34
+ export function getAdapter(handle) {
35
+ return loadBinding().getAdapter(handle) || null;
36
+ }
37
+
38
+ /** Create a producer whose transport and engine callbacks run on one native thread. */
39
+ export function createProducer({ endpoint, maxPendingOperations, operationTimeoutMs, engine }, onEvent) {
40
+ const api = loadBinding();
41
+ const { native, ready, closed } = api.createProducer(endpoint, maxPendingOperations, operationTimeoutMs, engine, onEvent);
42
+ const command = (kind, ...args) => api.producerCommand(native, kind, ...args);
43
+ return Object.freeze({
44
+ ready,
45
+ closed,
46
+ async acquire(width, height) {
47
+ const surface = await command(0, width, height);
48
+ const discard = async () => command(4, surface);
49
+ return Object.freeze({
50
+ width, height,
51
+ async writeBgra(pixels, stride) {
52
+ if (!Buffer.isBuffer(pixels) || pixels.buffer instanceof SharedArrayBuffer) {
53
+ throw new TypeError('CPU pixels require a Buffer backed by a non-shared ArrayBuffer');
54
+ }
55
+ await command(1, surface, pixels, stride);
56
+ },
57
+ async render() { await command(2, surface); },
58
+ async submit(frameId, metadata) { await command(3, surface, frameId, metadata); },
59
+ discard,
60
+ close: discard,
61
+ });
62
+ },
63
+ async send(json) { await command(5, json); },
64
+ async start({ width, height, generation, frameIntervalMs }) {
65
+ await command(6, width, height, generation, frameIntervalMs);
66
+ },
67
+ async update(json, inputSequence) { await command(7, json, inputSequence); },
68
+ async stop() { await command(8); },
69
+ close() { api.closeProducer(native); return closed; },
70
+ });
71
+ }
@@ -0,0 +1,46 @@
1
+ import type { FrameForwardingCapture, FrameForwardingDisplayBackend, FrameForwardingFrameLease, FrameForwardingFramePainter, FrameForwardingViewport } from './types.ts';
2
+ /** Serialized canvas presenter; accepts ownership of every submitted lease. */
3
+ export declare class FrameForwardingFrameDisplay<Id extends string = string> {
4
+ private readonly painter;
5
+ private queue;
6
+ private closed;
7
+ private displayed;
8
+ private generation;
9
+ private revision;
10
+ private waiting;
11
+ private disposal;
12
+ private constructor();
13
+ /**
14
+ * Allocate a display canvas using the requested backend.
15
+ * @param backend - Auto uses Canvas2D; explicit GPU backends support comparative measurements.
16
+ * @param replaceCanvas - Mount a newly allocated canvas, replacing any previous one.
17
+ * @param makeCanvas - Canvas allocator; each backend attempt needs a fresh element.
18
+ * @returns Presenter whose dispose method must be called on unmount.
19
+ */
20
+ static create<Id extends string = string>(backend: FrameForwardingDisplayBackend, replaceCanvas: (canvas: HTMLCanvasElement) => void, makeCanvas?: () => HTMLCanvasElement): Promise<FrameForwardingFrameDisplay<Id>>;
21
+ /** Active display backend. */
22
+ get backend(): FrameForwardingFramePainter['backend'];
23
+ /**
24
+ * Reject older viewport images while retaining the visible canvas until a replacement arrives.
25
+ * @param version - Current viewport generation.
26
+ */
27
+ setGeneration(version: number): void;
28
+ private waitUntilVisible;
29
+ /**
30
+ * Paint in submission order and release the lease, including stale and failed images.
31
+ * Hidden documents wait for visibility; the view owner must separately stop production through its viewport.
32
+ * @param lease - Transferred ownership of a single frame.
33
+ * @returns Whether the image became current; viewport changes or disposal cancel visibility waits.
34
+ */
35
+ present(lease: FrameForwardingFrameLease<Id>): Promise<boolean>;
36
+ /**
37
+ * Capture after earlier submissions, with their exact displayed identity.
38
+ * @param viewport - Viewport associated with the requested observation.
39
+ * @returns PNG pixels, displayed metadata, and viewport; rejects stale/empty views.
40
+ */
41
+ capture(viewport: FrameForwardingViewport): Promise<FrameForwardingCapture<Id>>;
42
+ /** Release every queued frame and dispose graphics resources.
43
+ * @returns Completion after all owned frames and graphics resources are released.
44
+ */
45
+ dispose(): Promise<void>;
46
+ }
@@ -0,0 +1,128 @@
1
+ /** Ordered presentation and capture of imported native images. */
2
+ import { createFrameForwardingFramePainter } from "./painters.js";
3
+ /** Serialized canvas presenter; accepts ownership of every submitted lease. */
4
+ export class FrameForwardingFrameDisplay {
5
+ painter;
6
+ queue = Promise.resolve();
7
+ closed = false;
8
+ displayed;
9
+ generation = 0;
10
+ revision = -1;
11
+ waiting = new AbortController();
12
+ disposal;
13
+ constructor(painter) {
14
+ this.painter = painter;
15
+ }
16
+ /**
17
+ * Allocate a display canvas using the requested backend.
18
+ * @param backend - Auto uses Canvas2D; explicit GPU backends support comparative measurements.
19
+ * @param replaceCanvas - Mount a newly allocated canvas, replacing any previous one.
20
+ * @param makeCanvas - Canvas allocator; each backend attempt needs a fresh element.
21
+ * @returns Presenter whose dispose method must be called on unmount.
22
+ */
23
+ static async create(backend, replaceCanvas, makeCanvas = () => document.createElement('canvas')) {
24
+ const painter = await createFrameForwardingFramePainter(backend, makeCanvas);
25
+ try {
26
+ replaceCanvas(painter.canvas);
27
+ }
28
+ catch (error) {
29
+ painter.dispose();
30
+ throw error;
31
+ }
32
+ return new FrameForwardingFrameDisplay(painter);
33
+ }
34
+ /** Active display backend. */
35
+ get backend() { return this.painter.backend; }
36
+ /**
37
+ * Reject older viewport images while retaining the visible canvas until a replacement arrives.
38
+ * @param version - Current viewport generation.
39
+ */
40
+ setGeneration(version) {
41
+ if (version < this.generation)
42
+ throw new Error('Native display generation cannot decrease.');
43
+ if (version === this.generation)
44
+ return;
45
+ this.waiting.abort();
46
+ this.waiting = new AbortController();
47
+ this.generation = version;
48
+ this.revision = -1;
49
+ }
50
+ waitUntilVisible(signal) {
51
+ return new Promise((resolve) => {
52
+ const finish = (visible) => {
53
+ document.removeEventListener('visibilitychange', changed);
54
+ signal.removeEventListener('abort', aborted);
55
+ resolve(visible);
56
+ };
57
+ const changed = () => { if (!document.hidden)
58
+ finish(true); };
59
+ const aborted = () => { finish(false); };
60
+ document.addEventListener('visibilitychange', changed);
61
+ signal.addEventListener('abort', aborted, { once: true });
62
+ });
63
+ }
64
+ /**
65
+ * Paint in submission order and release the lease, including stale and failed images.
66
+ * Hidden documents wait for visibility; the view owner must separately stop production through its viewport.
67
+ * @param lease - Transferred ownership of a single frame.
68
+ * @returns Whether the image became current; viewport changes or disposal cancel visibility waits.
69
+ */
70
+ present(lease) {
71
+ const operation = this.queue.then(async () => {
72
+ try {
73
+ if (this.closed || lease.metadata.generation !== this.generation || lease.metadata.revision < this.revision)
74
+ return false;
75
+ const signal = this.waiting.signal;
76
+ if (document.hidden && !await this.waitUntilVisible(signal))
77
+ return false;
78
+ if (signal.aborted)
79
+ return false;
80
+ await this.painter.paint(lease.frame);
81
+ if (this.closed || lease.metadata.generation !== this.generation)
82
+ return false;
83
+ this.displayed = { ...lease.metadata };
84
+ this.revision = lease.metadata.revision;
85
+ return true;
86
+ }
87
+ finally {
88
+ lease.release();
89
+ }
90
+ });
91
+ this.queue = operation.then(() => { }, () => { });
92
+ return operation;
93
+ }
94
+ /**
95
+ * Capture after earlier submissions, with their exact displayed identity.
96
+ * @param viewport - Viewport associated with the requested observation.
97
+ * @returns PNG pixels, displayed metadata, and viewport; rejects stale/empty views.
98
+ */
99
+ capture(viewport) {
100
+ const operation = this.queue.then(async () => {
101
+ const metadata = this.displayed;
102
+ if (this.closed || metadata === undefined || metadata.generation !== viewport.version || this.generation !== viewport.version)
103
+ throw new Error('No native frame for the requested viewport.');
104
+ const image = await new Promise((resolve, reject) => {
105
+ this.painter.canvas.toBlob((blob) => {
106
+ if (blob === null)
107
+ reject(new Error('Native frame capture failed.'));
108
+ else
109
+ resolve(blob);
110
+ }, 'image/png');
111
+ });
112
+ return { image, metadata: { ...metadata }, viewport: { ...viewport } };
113
+ });
114
+ this.queue = operation.then(() => { }, () => { });
115
+ return operation;
116
+ }
117
+ /** Release every queued frame and dispose graphics resources.
118
+ * @returns Completion after all owned frames and graphics resources are released.
119
+ */
120
+ async dispose() {
121
+ if (this.disposal !== undefined)
122
+ return this.disposal;
123
+ this.closed = true;
124
+ this.waiting.abort();
125
+ this.disposal = this.queue.then(() => this.painter.dispose());
126
+ return this.disposal;
127
+ }
128
+ }
@@ -0,0 +1,4 @@
1
+ /** Browser-only native image presentation; importing this entry allocates no graphics resources. */
2
+ export { FrameForwardingFrameDisplay } from './display.ts';
3
+ export { createFrameForwardingFramePainter } from './painters.ts';
4
+ export type * from './types.ts';
@@ -0,0 +1,3 @@
1
+ /** Browser-only native image presentation; importing this entry allocates no graphics resources. */
2
+ export { FrameForwardingFrameDisplay } from "./display.js";
3
+ export { createFrameForwardingFramePainter } from "./painters.js";