@ekrooh/bare 0.6.1 → 0.7.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.
@@ -0,0 +1,152 @@
1
+ declare const VERSION = 1;
2
+ declare const MessageType: {
3
+ readonly ENVELOPE: 1;
4
+ };
5
+ type MessageTypeValue = (typeof MessageType)[keyof typeof MessageType];
6
+ /** Canonical error codes. Everything the framework throws uses these; peers
7
+ * may carry arbitrary codes over the wire, and consumers may return app-scoped
8
+ * codes (e.g. `app.photos/not-found`) which are preserved verbatim. Keep
9
+ * `android/src/main/.../ErrorCodes.kt` in sync with the canonical union. */
10
+ declare const ErrorCode: {
11
+ readonly UNSUPPORTED_CAPABILITY: 'UNSUPPORTED_CAPABILITY';
12
+ readonly UNSUPPORTED_EVENT: 'UNSUPPORTED_EVENT';
13
+ readonly HOST_ERROR: 'HOST_ERROR';
14
+ readonly TRANSPORT_ERROR: 'TRANSPORT_ERROR';
15
+ readonly PLUGIN_ERROR: 'PLUGIN_ERROR';
16
+ readonly INVALID_RESPONSE: 'INVALID_RESPONSE';
17
+ readonly FRAME_TOO_LARGE: 'FRAME_TOO_LARGE';
18
+ readonly FRAME_INVALID: 'FRAME_INVALID';
19
+ readonly TIMEOUT: 'TIMEOUT';
20
+ };
21
+ type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
22
+ /** A JSON header must fit a 16-bit big-endian length field. */
23
+ declare const MAX_HEADER_BYTES = 65535;
24
+ /** Upper bound on one encoded frame. Large binary transfers are a plugin-level
25
+ * concern (out-of-band handles), not an in-band payload. */
26
+ declare const MAX_FRAME_BYTES: number;
27
+ /** Decoded binary frame (version byte stripped); used by WebSocket and other transports. */
28
+ interface WireMessage {
29
+ type: MessageTypeValue;
30
+ header: MessageHeader;
31
+ payload: Uint8Array;
32
+ }
33
+ type HeaderBase = {
34
+ type: string;
35
+ requestId?: string;
36
+ };
37
+ /** Canonical wire codes plus any app-scoped code consumers define (e.g.
38
+ * `app.photos/not-found`). Framework plugins use the canonical union;
39
+ * arbitrary codes ride the wire verbatim and are never flattened. */
40
+ type ErrorCodeOrString = ErrorCode | (string & {});
41
+ declare class CoreError extends Error {
42
+ code: ErrorCodeOrString;
43
+ constructor(code: ErrorCodeOrString, message: string);
44
+ }
45
+ type CoreErrorWire = {
46
+ code: string;
47
+ message: string;
48
+ };
49
+ type RuntimeTarget = 'web' | 'android' | 'ios' | 'bare';
50
+ type Either<E, A> = [E, null] | [null, A];
51
+ type DispatchEnvelope<TEvent extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>> = {
52
+ kind: 'dispatch';
53
+ pluginId: string;
54
+ event: TEvent;
55
+ args: TArgs;
56
+ payload?: Uint8Array | ArrayBuffer | string | null;
57
+ };
58
+ type InvokeEnvelope<TEvent extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>, TResult = unknown> = {
59
+ kind: 'invoke';
60
+ pluginId: string;
61
+ event: TEvent;
62
+ args: TArgs;
63
+ payload?: Uint8Array | ArrayBuffer | string | null;
64
+ timeoutMs?: number;
65
+ __result?: TResult;
66
+ };
67
+ type PluginInvokeRequestHeader = HeaderBase & {
68
+ type: 'INVOKE_REQUEST';
69
+ pluginId: string;
70
+ event: string;
71
+ args?: Record<string, unknown>;
72
+ };
73
+ type PluginInvokeResponseHeader = HeaderBase & {
74
+ type: 'INVOKE_RESPONSE';
75
+ pluginId: string;
76
+ event: string;
77
+ result?: unknown;
78
+ error?: CoreErrorWire;
79
+ };
80
+ type PluginDispatchHeader = HeaderBase & {
81
+ type: 'DISPATCH';
82
+ pluginId: string;
83
+ event: string;
84
+ args?: Record<string, unknown>;
85
+ };
86
+ type PluginHeader = PluginInvokeRequestHeader | PluginInvokeResponseHeader | PluginDispatchHeader;
87
+ /** Worklet → host: ask for merged capability list (host registry + static knowledge). */
88
+ type HostCapabilitiesQueryHeader = {
89
+ type: 'HOST_CAPABILITIES_QUERY';
90
+ requestId: string;
91
+ };
92
+ /** Host → worklet: capability rows contributed by the host. */
93
+ type HostCapabilitiesResponseHeader = {
94
+ type: 'HOST_CAPABILITIES_RESPONSE';
95
+ requestId: string;
96
+ capabilities: CapabilityDescriptor[];
97
+ /** Set when the host's answer could not be used (e.g. it failed to decode);
98
+ * the query then rejects with this error. */
99
+ error?: CoreErrorWire;
100
+ };
101
+ /** Worklet → host: run a host-registered handler (same pluginId/event as frontend invokes). */
102
+ type HostInvokeRequestHeader = {
103
+ type: 'HOST_INVOKE_REQUEST';
104
+ requestId: string;
105
+ pluginId: string;
106
+ event: string;
107
+ args?: Record<string, unknown>;
108
+ };
109
+ /** Host → worklet: result for {@link HostInvokeRequestHeader}. */
110
+ type HostInvokeResponseHeader = {
111
+ type: 'HOST_INVOKE_RESPONSE';
112
+ requestId: string;
113
+ pluginId: string;
114
+ event: string;
115
+ result?: unknown;
116
+ error?: CoreErrorWire;
117
+ };
118
+ /** Serializable row for discovery and host registry listing. */
119
+ type CapabilityDescriptor = {
120
+ pluginId: string;
121
+ capabilities: string[];
122
+ events: string[];
123
+ runtimes: RuntimeTarget[];
124
+ };
125
+ type MessageHeader = PluginHeader | HostCapabilitiesQueryHeader | HostCapabilitiesResponseHeader | HostInvokeRequestHeader | HostInvokeResponseHeader;
126
+ interface PluginContext {
127
+ runtime: RuntimeTarget;
128
+ payload: Uint8Array;
129
+ /** The registry-validated sender of the envelope. Always equals the
130
+ * wire `pluginId` once the router has matched a manifest — adapters can trust
131
+ * it without re-validating against the wire. */
132
+ sender?: {
133
+ pluginId: string;
134
+ };
135
+ }
136
+ interface PluginRuntimeAdapter {
137
+ dispatch?: (event: string, args: Record<string, unknown> | undefined, context: PluginContext) => void | Promise<void>;
138
+ invoke?: (event: string, args: Record<string, unknown> | undefined, context: PluginContext) => Either<CoreError, unknown> | Promise<Either<CoreError, unknown>>;
139
+ }
140
+ interface PluginManifest {
141
+ id: string;
142
+ version?: string;
143
+ capabilities?: string[];
144
+ events?: string[];
145
+ /** Per-event deadline (ms) for an invoke the router delegates to the host,
146
+ * keyed by event name. A user-mediated host call (a permission prompt, a
147
+ * picker) needs far longer than the default host timeout. Read as own
148
+ * properties only. */
149
+ hostTimeoutsMs?: Readonly<Record<string, number>>;
150
+ runtimes: Partial<Record<RuntimeTarget, PluginRuntimeAdapter>>;
151
+ }
152
+ export { MAX_FRAME_BYTES as C, VERSION as D, MessageTypeValue as E, ErrorCode as S, MessageType as T, PluginInvokeResponseHeader as _, Either as a, RuntimeTarget as b, HostCapabilitiesResponseHeader as c, InvokeEnvelope as d, MessageHeader as f, PluginInvokeRequestHeader as g, PluginHeader as h, DispatchEnvelope as i, HostInvokeRequestHeader as l, PluginDispatchHeader as m, CoreError as n, ErrorCodeOrString as o, PluginContext as p, CoreErrorWire as r, HostCapabilitiesQueryHeader as s, CapabilityDescriptor as t, HostInvokeResponseHeader as u, PluginManifest as v, MAX_HEADER_BYTES as w, WireMessage as x, PluginRuntimeAdapter as y };
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@ekrooh/bare",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
- "description": "One soul, many platforms \u2014 the boring bootstrap for cross-platform apps on the Bare runtime: wire protocol, plugin kernel, RPC messenger, transports, and native host bridges.",
6
- "license": "MIT",
5
+ "description": "One soul, many platforms — the boring bootstrap for cross-platform apps on the Bare runtime: wire protocol, plugin kernel, RPC messenger, transports, and native host bridges.",
6
+ "license": "Apache-2.0",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "https://github.com/AndersCan/ekrooh.git"
10
10
  },
11
11
  "workspaces": [
12
- "examples/*",
12
+ "examples/web",
13
13
  "examples/consumer-basic",
14
14
  "e2e",
15
15
  "apps/*"
@@ -25,6 +25,7 @@
25
25
  "./plugins/media/events": "./dist/plugins-media-events.mjs",
26
26
  "./plugins/logs/events": "./dist/plugins-logs-events.mjs",
27
27
  "./transports": "./dist/transports.mjs",
28
+ "./sync": "./dist/sync.mjs",
28
29
  "./package.json": "./package.json"
29
30
  },
30
31
  "files": [
@@ -69,9 +70,12 @@
69
70
  "test:e2e:harness": "node scripts/playwright-local-browsers.mjs test --config playwright.harness.config.ts",
70
71
  "playwright:install": "node scripts/playwright-local-browsers.mjs install chromium",
71
72
  "smoke:loopback": "esbuild scripts/smoke-loopback.mjs --bundle --packages=external --platform=node --format=esm --outfile=scripts/smoke-loopback.gen.mjs && bare scripts/smoke-loopback.gen.mjs",
72
- "smoke:p2p": "npm run build:p2p-verify && rm -rf .p2p-smoke && mkdir .p2p-smoke && bare core/p2p-verify.core.gen.js .p2p-smoke",
73
+ "smoke:p2p": "npm run build:p2p-verify && rm -rf .p2p-smoke && mkdir .p2p-smoke && bare core/p2p-verify.core.gen.js .p2p-smoke && npm run smoke:sync",
74
+ "smoke:sync": "npm run build:sync-smoke && rm -rf .sync-smoke && mkdir -p .sync-smoke/a .sync-smoke/b && PATH=\"$PWD/node_modules/bare/bin:$PATH\" bare core/sync-smoke.core.gen.js .sync-smoke",
73
75
  "build:p2p-verify": "esbuild core/p2p-verify.core.ts --bundle --packages=external --platform=node --format=esm --outfile=core/p2p-verify.core.gen.js",
76
+ "build:sync-smoke": "esbuild core/sync-smoke.core.ts --bundle --packages=external --platform=node --format=esm --outfile=core/sync-smoke.core.gen.js",
74
77
  "prebuilds": "node scripts/fetch-prebuilds.mjs",
78
+ "api:snapshot": "node scripts/api-snapshot.mjs --update",
75
79
  "prepare": "vp config"
76
80
  },
77
81
  "devDependencies": {
@@ -86,10 +90,10 @@
86
90
  "corestore": "^7.12.0",
87
91
  "esbuild": "^0.28.0",
88
92
  "hyperdrive": "^13.3.3",
89
- "hyperswarm": "^4.17.0",
90
93
  "typescript": "^7.0.2",
91
94
  "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
92
- "vite-plus": "1.4.0"
95
+ "vite-plus": "1.4.0",
96
+ "yaml": "^2.9.1"
93
97
  },
94
98
  "dependencies": {
95
99
  "@mantaq/core": "^0.2.0",
@@ -103,6 +107,7 @@
103
107
  "bare-tcp": "^2.2.7",
104
108
  "bare-ws": "^3.1.0",
105
109
  "fs-native-extensions": "1.5.0",
110
+ "hyperswarm": "^4.17.0",
106
111
  "quickbit-native": "2.4.8",
107
112
  "rabin-native": "2.0.0",
108
113
  "rocksdb-native": "3.19.1",
@@ -1,156 +0,0 @@
1
- import { g as ErrorCode, m as ok, p as err, r as definePlugin } from "./messages-CMNIFMFY.mjs";
2
- import { discoverySpecs } from "./plugins-discovery-events.mjs";
3
- import { healthSpecs } from "./plugins-health-events.mjs";
4
- import { logsSpecs } from "./plugins-logs-events.mjs";
5
- import { mediaSpecs } from "./plugins-media-events.mjs";
6
- import { permissionSpecs } from "./plugins-permissions-events.mjs";
7
- import crypto from "bare-crypto";
8
- // plugins/discovery/plugin.ts
9
- function mergeCapabilityRows(a, b) {
10
- const map = /* @__PURE__ */ new Map();
11
- for (const row of [...a, ...b]) {
12
- const existing = map.get(row.pluginId);
13
- if (!existing) map.set(row.pluginId, {
14
- pluginId: row.pluginId,
15
- capabilities: [...row.capabilities],
16
- events: [...row.events],
17
- runtimes: [...row.runtimes]
18
- });
19
- else {
20
- const ev = /* @__PURE__ */ new Set([...existing.events, ...row.events]);
21
- const rt = /* @__PURE__ */ new Set([...existing.runtimes, ...row.runtimes]);
22
- const caps = /* @__PURE__ */ new Set([...existing.capabilities, ...row.capabilities]);
23
- map.set(row.pluginId, {
24
- pluginId: row.pluginId,
25
- capabilities: [...caps],
26
- events: [...ev],
27
- runtimes: [...rt]
28
- });
29
- }
30
- }
31
- return [...map.values()];
32
- }
33
- function createDiscoveryPlugin(deps) {
34
- return definePlugin("core.discovery", discoverySpecs, {
35
- capabilities: ["discovery"],
36
- invoke: { list: async () => {
37
- const merged = mergeCapabilityRows(deps.listBareCapabilities(), await deps.queryHostCapabilities());
38
- return ok({
39
- schemaVersion: 1,
40
- capabilities: merged
41
- });
42
- } }
43
- });
44
- }
45
- // plugins/health/plugin.ts
46
- function createHealthPlugin() {
47
- return definePlugin("core.health", healthSpecs, {
48
- capabilities: ["health"],
49
- invoke: {
50
- ping: (args) => ok({
51
- message: args?.message ?? "pong",
52
- ts: Date.now()
53
- }),
54
- payloadEcho: (args, context) => ok({
55
- label: args?.label ?? "payload",
56
- payloadSize: context.payload.byteLength
57
- }),
58
- roundtrip: () => ok({
59
- pong: true,
60
- ts: Date.now()
61
- })
62
- }
63
- });
64
- }
65
- const LOGS_VIEW_DEFAULT_TAIL = 20;
66
- function createLogsPlugin(deps) {
67
- return definePlugin("core.logs", logsSpecs, {
68
- capabilities: ["logs"],
69
- invoke: {
70
- view: (args) => {
71
- const tail = args?.tail === void 0 ? LOGS_VIEW_DEFAULT_TAIL : Math.max(0, Math.min(args.tail, 100));
72
- return ok({ entries: deps.store.view({
73
- tail,
74
- level: args?.level,
75
- source: args?.source
76
- }) });
77
- },
78
- clear: () => ok({ cleared: deps.store.clear() })
79
- }
80
- });
81
- }
82
- // plugins/media/plugin.ts
83
- /** Most media mounts are consumed once and then linger. Cap how many stay
84
- * mounted at once and evict the least-recently-used so picked/captured files
85
- * do not accumulate on the loopback server for the whole session. */
86
- const MEDIA_MOUNT_CAP = 4;
87
- const MEDIA_KINDS = ["image", "video"];
88
- function newRequestId() {
89
- const rand = crypto.randomBytes(16).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
90
- return `${Date.now().toString(36)}-${rand}`;
91
- }
92
- /**
93
- * `vendor.media` — reference plugin demonstrating out-of-band binary transfer.
94
- * The native host picks/captures a file (returns its path); the worklet mounts
95
- * it on its loopback HTTP server and hands the web layer a plain URL. No media
96
- * bytes ever cross the wire protocol or a WebView bridge, and the serving code
97
- * is identical on every runtime.
98
- */
99
- function createMediaPlugin(deps) {
100
- const mounted = /* @__PURE__ */ new Map();
101
- const mountMedia = (id, path) => {
102
- deps.staticServer.mount(`/media/${id}`, path);
103
- mounted.set(id, path);
104
- while (mounted.size > MEDIA_MOUNT_CAP) {
105
- const oldestId = mounted.keys().next().value;
106
- const oldestPath = mounted.get(oldestId);
107
- mounted.delete(oldestId);
108
- if (oldestPath !== void 0) deps.staticServer.unmount(`/media/${oldestId}`);
109
- }
110
- };
111
- const serve = async (event, args) => {
112
- const kind = args?.kind;
113
- if (kind !== void 0 && !MEDIA_KINDS.includes(kind)) return err(ErrorCode.PLUGIN_ERROR, `Unknown media kind for ${event}`);
114
- const host = await deps.invokeOnHost({
115
- type: "INVOKE_REQUEST",
116
- pluginId: "vendor.media",
117
- event,
118
- requestId: newRequestId(),
119
- args: kind === void 0 ? {} : { kind }
120
- }, /* @__PURE__ */ new Uint8Array(0));
121
- if (!host) return err(ErrorCode.HOST_ERROR, `Host did not answer ${event}`);
122
- if (host.error) return err(host.error.code || ErrorCode.HOST_ERROR, host.error.message ?? `Host failed ${event}`);
123
- const path = host.result?.path;
124
- if (!path) return err(ErrorCode.HOST_ERROR, `Host returned no path for ${event}`);
125
- const id = `${kind ?? "media"}-${newRequestId()}`;
126
- mountMedia(id, path);
127
- const url = await deps.staticServer.url(`/media/${id}`);
128
- return ok({ url });
129
- };
130
- return definePlugin("vendor.media", mediaSpecs, {
131
- capabilities: ["media"],
132
- invoke: {
133
- pick: async (args) => serve("media.pick", args),
134
- capture: async (args) => serve("media.capture", args)
135
- }
136
- });
137
- }
138
- // plugins/permissions/plugin.ts
139
- /**
140
- * Declares host-only permission events. Handlers are registered on the Android host
141
- * via {@code HostPluginRegistry}; the worklet delegates invokes here over IPC.
142
- */
143
- function createPermissionsPluginStub() {
144
- return definePlugin("core.permissions", permissionSpecs, { capabilities: ["permissions"] });
145
- }
146
- // plugins/index.ts
147
- function createDefaultPlugins(deps) {
148
- return [
149
- createHealthPlugin(),
150
- createDiscoveryPlugin(deps),
151
- createPermissionsPluginStub(),
152
- createMediaPlugin(deps),
153
- createLogsPlugin(deps)
154
- ];
155
- }
156
- export { createDefaultPlugins as t };