@ekrooh/bare 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -206,6 +206,24 @@ npm run build # core bundle + web assets
206
206
 
207
207
  `./gradlew build` additionally runs the host library's JUnit tests.
208
208
 
209
+ ### Consuming the published AAR
210
+
211
+ `io.github.anderscan.ekrooh:bare-host` is published to **Maven Central** (no auth) on the same
212
+ tag as the npm package — pin it to your `@ekrooh/bare` version:
213
+
214
+ ```gradle
215
+ repositories {
216
+ mavenCentral() // default in modern Gradle; no credentials needed
217
+ }
218
+
219
+ dependencies {
220
+ implementation "io.github.anderscan.ekrooh:bare-host:<version>"
221
+ }
222
+ ```
223
+
224
+ GitHub Packages (`maven.pkg.github.com/AndersCan/ekrooh`) remains a fallback
225
+ but requires a `read:packages` PAT — prefer Maven Central.
226
+
209
227
  ## iOS build
210
228
 
211
229
  Prerequisites: Xcode (macOS), Bare Kit prebuilds, and `xcodegen`.
@@ -1,5 +1,5 @@
1
1
  import { A as CapabilityDescriptor, G as PluginInvokeRequestHeader, K as PluginInvokeResponseHeader, Y as RuntimeTarget, q as PluginManifest } from "./index-DjulYFJL.mjs";
2
- import { t as LoopbackServer } from "./static-file-server-CxeI_mQr.mjs";
2
+ import { n as LoopbackServer } from "./static-file-server-DY9EKEVf.mjs";
3
3
  //#region plugins/discovery/plugin.d.ts
4
4
  type DiscoveryPluginDeps = {
5
5
  listBareCapabilities: () => Array<{
@@ -1,5 +1,5 @@
1
- import { A as CapabilityDescriptor, G as PluginInvokeRequestHeader, K as PluginInvokeResponseHeader, d as MessageProtocol, t as BareRuntimeContext, v as createPluginRegistry, y as createPluginRouter } from "./index-DjulYFJL.mjs";
2
- import { n as createLoopbackServer, t as LoopbackServer } from "./static-file-server-CxeI_mQr.mjs";
1
+ import { A as CapabilityDescriptor, G as PluginInvokeRequestHeader, K as PluginInvokeResponseHeader, V as MessageHeader, d as MessageProtocol, q as PluginManifest, t as BareRuntimeContext, v as createPluginRegistry, y as createPluginRouter } from "./index-DjulYFJL.mjs";
2
+ import { i as createLoopbackServer, n as LoopbackServer, r as collectRequestBody, t as LoopbackRouteHandler } from "./static-file-server-DY9EKEVf.mjs";
3
3
  //#region core/messages/host-ipc.d.ts
4
4
  type BareIpcLike = {
5
5
  write(data: Uint8Array | Buffer | string): boolean;
@@ -14,6 +14,13 @@ declare function createHostIpcBridge(config: {
14
14
  };
15
15
  //#endregion
16
16
  //#region core/server/websocket-server.d.ts
17
+ /** Envelope encoder bound to a loopback server's connected protocol socket —
18
+ * the server-initiated (backend → web) push seam. */
19
+ type LoopbackPush = (header: MessageHeader, payload?: Uint8Array | ArrayBuffer | null) => boolean;
20
+ /** Builds the push seam for the server's connected protocol socket: encodes a
21
+ * `DISPATCH`-style envelope and writes it, mirroring how `attachWebSocketProtocol`
22
+ * writes responses. Returns false when no socket is connected. */
23
+ declare function createLoopbackPush(server: LoopbackServer, protocol: MessageProtocol): LoopbackPush;
17
24
  /**
18
25
  * Attaches the framed-protocol socket to the unified loopback server. The
19
26
  * server owns the WebSocket upgrade (origin check, cookie/token auth, single
@@ -44,8 +51,23 @@ declare function getIPC(): BareIPC;
44
51
  * arguments. On-device hosts pass `["<webAssets>", "<storage>", "<cache>"]`,
45
52
  * landing at `Bare.argv[0..2]`; the Bare CLI (dev) passes the binary and the
46
53
  * script path instead, so a missing/absent config means dev mode (auth off,
47
- * fixed port, no handoff file). */
54
+ * fixed port, no handoff file). Falls back to the labeled CLI token syntax
55
+ * (see `resolveCliConfig`) when the positional shape doesn't match, so the
56
+ * same entry works for both device and dev runs. */
48
57
  declare function resolveWorkletConfig(): WorkletRuntimeOptions;
58
+ /**
59
+ * Parses the dev/CLI labeled-token configuration from bare CLI arguments:
60
+ * `webassets=<dir>`, `storage=<dir>`, `cache=<dir>`, `host=<addr>`,
61
+ * `port=<n>`, `auth=<on|off|true|false|1|0>` — a single `key=value` separator.
62
+ * Unknown labels (e.g. `bootstrap=127.0.0.1:49737`) are ignored and stay
63
+ * consumer-owned.
64
+ *
65
+ * Returns the equivalent `WorkletRuntimeOptions` in **dev mode**: `deviceMode:
66
+ * false` (so a `storage=` token does not flip auth on or make the port
67
+ * ephemeral), `auth: false`, `port: 8080`, each overridable by a token. When
68
+ * no labeled tokens are present it returns `{}` (plain dev defaults).
69
+ */
70
+ declare function resolveCliConfig(argv?: readonly string[]): WorkletRuntimeOptions;
49
71
  type WorkletRuntimeOptions = {
50
72
  /** Directory to serve at `/` (the built web app). */
51
73
  webAssets?: string;
@@ -60,6 +82,13 @@ type WorkletRuntimeOptions = {
60
82
  port?: number;
61
83
  /** Require the per-session token/cookie. Defaults to on in device mode. */
62
84
  auth?: boolean;
85
+ /** Explicit device-mode override. Defaults to on whenever `storage` is set
86
+ * (the on-device 3-arg contract); `resolveCliConfig` resolves it to false so
87
+ * a dev backend keeps auth off + fixed port even with a storage dir. */
88
+ deviceMode?: boolean;
89
+ /** Additional plugin manifests to register after the canonical defaults
90
+ * (consumer product plugins, e.g. `app.photos`). */
91
+ plugins?: PluginManifest[];
63
92
  /** Idle timeout (ms) after which an authenticated WebSocket is dropped. */
64
93
  wsIdleTimeoutMs?: number;
65
94
  };
@@ -93,4 +122,4 @@ interface WorkletRuntime {
93
122
  */
94
123
  declare function createWorkletRuntime(options?: WorkletRuntimeOptions): WorkletRuntime;
95
124
  //#endregion
96
- export { type LoopbackServer, WorkletRuntime, WorkletRuntimeConfig, WorkletRuntimeOptions, attachWebSocketProtocol, createLoopbackServer, createWorkletRuntime, getIPC, resolveWorkletConfig };
125
+ export { type LoopbackPush, type LoopbackRouteHandler, type LoopbackServer, WorkletRuntime, WorkletRuntimeConfig, WorkletRuntimeOptions, attachWebSocketProtocol, collectRequestBody, createLoopbackPush, createLoopbackServer, createWorkletRuntime, getIPC, resolveCliConfig, resolveWorkletConfig };
package/dist/runtime.mjs CHANGED
@@ -13,7 +13,7 @@ import crypto from "bare-crypto";
13
13
  * In Bare (Sidecar), it uses Bare.IPC.
14
14
  */
15
15
  function getIPC() {
16
- const IPC = typeof BareKit !== "undefined" ? BareKit.IPC : Bare.IPC;
16
+ const IPC = typeof BareKit !== "undefined" ? BareKit.IPC : typeof Bare !== "undefined" ? Bare.IPC : void 0;
17
17
  if (IPC && typeof IPC.resume === "function") IPC.resume();
18
18
  return IPC;
19
19
  }
@@ -219,6 +219,7 @@ function createLoopbackServer(options = {}) {
219
219
  const wsIdleTimeoutMs = options.wsIdleTimeoutMs ?? 6e4;
220
220
  const fileMounts = /* @__PURE__ */ new Map();
221
221
  const dirMounts = /* @__PURE__ */ new Map();
222
+ const routeHandlers = /* @__PURE__ */ new Map();
222
223
  const connectionHandlers = [];
223
224
  let token = options.token ?? null;
224
225
  let boundOrigin = "";
@@ -375,6 +376,19 @@ function createLoopbackServer(options = {}) {
375
376
  writeError(res, 400, "Bad request");
376
377
  return;
377
378
  }
379
+ const route = routeHandlers.get(`${req.method} ${cleanPath}`);
380
+ if (route) {
381
+ if (!isAuthorized(headers, query)) {
382
+ writeError(res, 401, "Unauthorized");
383
+ return;
384
+ }
385
+ try {
386
+ route(req, res);
387
+ } catch (err) {
388
+ writeError(res, 500, err instanceof Error ? err.message : String(err));
389
+ }
390
+ return;
391
+ }
378
392
  const mount = resolveMount(cleanPath);
379
393
  if (!(mount !== null && mount.kind === "dir") && !isAuthorized(headers, query)) {
380
394
  writeError(res, 401, "Unauthorized");
@@ -471,6 +485,18 @@ function createLoopbackServer(options = {}) {
471
485
  onConnection(handler) {
472
486
  connectionHandlers.push(handler);
473
487
  },
488
+ registerRoute(method, path, handler) {
489
+ routeHandlers.set(`${method.toUpperCase()} ${path}`, handler);
490
+ },
491
+ push(frame) {
492
+ if (!activeSocket) return false;
493
+ try {
494
+ activeSocket.write(frame);
495
+ return true;
496
+ } catch {
497
+ return false;
498
+ }
499
+ },
474
500
  close(cb) {
475
501
  if (activeSocket) try {
476
502
  activeSocket.destroy();
@@ -486,6 +512,15 @@ function toUint8Array$1(data) {
486
512
  if (data instanceof ArrayBuffer) return new Uint8Array(data);
487
513
  throw new Error("Expected Uint8Array or ArrayBuffer from socket data");
488
514
  }
515
+ /** Builds the push seam for the server's connected protocol socket: encodes a
516
+ * `DISPATCH`-style envelope and writes it, mirroring how `attachWebSocketProtocol`
517
+ * writes responses. Returns false when no socket is connected. */
518
+ function createLoopbackPush(server, protocol) {
519
+ return (header, payload = null) => {
520
+ const frame = protocol.encode(MessageType.ENVELOPE, header, payload);
521
+ return server.push(frame);
522
+ };
523
+ }
489
524
  /**
490
525
  * Attaches the framed-protocol socket to the unified loopback server. The
491
526
  * server owns the WebSocket upgrade (origin check, cookie/token auth, single
@@ -512,13 +547,18 @@ function attachWebSocketProtocol(server, context) {
512
547
  }
513
548
  //#endregion
514
549
  //#region core/runtime.ts
550
+ function readBareArgv() {
551
+ return typeof Bare !== "undefined" && Array.isArray(Bare.argv) ? Bare.argv : [];
552
+ }
515
553
  /** Resolves the host-provided worklet configuration from `start(...)`
516
554
  * arguments. On-device hosts pass `["<webAssets>", "<storage>", "<cache>"]`,
517
555
  * landing at `Bare.argv[0..2]`; the Bare CLI (dev) passes the binary and the
518
556
  * script path instead, so a missing/absent config means dev mode (auth off,
519
- * fixed port, no handoff file). */
557
+ * fixed port, no handoff file). Falls back to the labeled CLI token syntax
558
+ * (see `resolveCliConfig`) when the positional shape doesn't match, so the
559
+ * same entry works for both device and dev runs. */
520
560
  function resolveWorkletConfig() {
521
- const argv = typeof Bare !== "undefined" && Array.isArray(Bare.argv) ? Bare.argv : [];
561
+ const argv = readBareArgv();
522
562
  const webAssets = argv[0];
523
563
  const storage = argv[1];
524
564
  const cache = argv[2];
@@ -534,7 +574,57 @@ function resolveWorkletConfig() {
534
574
  };
535
575
  }
536
576
  } catch {}
537
- return {};
577
+ return resolveCliConfig(argv);
578
+ }
579
+ /**
580
+ * Parses the dev/CLI labeled-token configuration from bare CLI arguments:
581
+ * `webassets=<dir>`, `storage=<dir>`, `cache=<dir>`, `host=<addr>`,
582
+ * `port=<n>`, `auth=<on|off|true|false|1|0>` — a single `key=value` separator.
583
+ * Unknown labels (e.g. `bootstrap=127.0.0.1:49737`) are ignored and stay
584
+ * consumer-owned.
585
+ *
586
+ * Returns the equivalent `WorkletRuntimeOptions` in **dev mode**: `deviceMode:
587
+ * false` (so a `storage=` token does not flip auth on or make the port
588
+ * ephemeral), `auth: false`, `port: 8080`, each overridable by a token. When
589
+ * no labeled tokens are present it returns `{}` (plain dev defaults).
590
+ */
591
+ function resolveCliConfig(argv = readBareArgv()) {
592
+ const parsed = {};
593
+ let matched = false;
594
+ for (const token of argv) {
595
+ const m = /^([A-Za-z][A-Za-z0-9]*)=(.*)$/.exec(token);
596
+ if (!m) continue;
597
+ const [, key, value] = m;
598
+ matched = true;
599
+ switch (key) {
600
+ case "webassets":
601
+ parsed.webAssets = value;
602
+ break;
603
+ case "storage":
604
+ parsed.storage = value;
605
+ break;
606
+ case "cache":
607
+ parsed.cache = value;
608
+ break;
609
+ case "host":
610
+ parsed.host = value;
611
+ break;
612
+ case "port": {
613
+ const n = Number(value);
614
+ if (Number.isInteger(n) && n >= 0 && n <= 65535) parsed.port = n;
615
+ else console.warn(`[bare] ignoring invalid port= token: "${value}"`);
616
+ break;
617
+ }
618
+ case "auth": parsed.auth = value !== "off" && value !== "false" && value !== "0";
619
+ }
620
+ }
621
+ if (!matched) return {};
622
+ return {
623
+ deviceMode: false,
624
+ auth: false,
625
+ port: 8080,
626
+ ...parsed
627
+ };
538
628
  }
539
629
  function toUint8Array(data) {
540
630
  if (data instanceof Uint8Array) return data;
@@ -552,7 +642,7 @@ function writeIpc(ipc, bytes) {
552
642
  * wire p2p". Mirrors the reference wiring in `core/main.core.ts`.
553
643
  */
554
644
  function createWorkletRuntime(options = {}) {
555
- const deviceMode = options.storage !== void 0;
645
+ const deviceMode = options.deviceMode ?? options.storage !== void 0;
556
646
  const auth = options.auth ?? deviceMode;
557
647
  const port = options.port ?? (deviceMode ? 0 : 8080);
558
648
  const protocol = new MessageProtocol({
@@ -582,6 +672,7 @@ function createWorkletRuntime(options = {}) {
582
672
  staticServer: server,
583
673
  invokeOnHost: (header, payload) => hostBridge?.invokeOnHost(header, payload) ?? Promise.resolve(null)
584
674
  })) pluginRegistry.register(plugin);
675
+ for (const plugin of options.plugins ?? []) pluginRegistry.register(plugin);
585
676
  const pluginRouter = createPluginRouter(pluginRegistry, "bare", { delegateToHost: (header, payload) => hostBridge?.invokeOnHost(header, payload) ?? Promise.resolve(null) });
586
677
  if (ipc) ipc.on("data", async (data) => {
587
678
  try {
@@ -607,7 +698,7 @@ function createWorkletRuntime(options = {}) {
607
698
  pluginRouter
608
699
  });
609
700
  const credentials = await server.credentials();
610
- if (deviceMode && options.storage) try {
701
+ if (auth && options.storage) try {
611
702
  fs.writeFileSync(path.join(options.storage, "handoff.json"), JSON.stringify(credentials));
612
703
  } catch (err) {
613
704
  const message = err instanceof Error ? err.message : String(err);
@@ -634,4 +725,4 @@ function createWorkletRuntime(options = {}) {
634
725
  };
635
726
  }
636
727
  //#endregion
637
- export { attachWebSocketProtocol, createLoopbackServer, createWorkletRuntime, getIPC, resolveWorkletConfig };
728
+ export { attachWebSocketProtocol, collectRequestBody, createLoopbackPush, createLoopbackServer, createWorkletRuntime, getIPC, resolveCliConfig, resolveWorkletConfig };
@@ -1,5 +1,10 @@
1
- import "bare-http1";
1
+ import { HTTPIncomingMessage, HTTPServerResponse } from "bare-http1";
2
2
  //#region core/server/static-file-server.d.ts
3
+ /** Accumulates an HTTP request body into a UTF-8 string. Node http emits
4
+ * Buffers, bare-http1 emits Uint8Arrays, and a setEncoding'd stream emits
5
+ * strings — `String(uint8array)` would join bytes with commas, so decode
6
+ * explicitly (the `/login` token body must match byte-for-byte). */
7
+ declare function collectRequestBody(req: HTTPIncomingMessage): Promise<string>;
3
8
  type WebSocketLike = {
4
9
  on(event: 'data', listener: (chunk: unknown) => void): unknown;
5
10
  on(event: 'close', listener: () => void): unknown;
@@ -7,6 +12,8 @@ type WebSocketLike = {
7
12
  write(data: unknown): boolean;
8
13
  destroy(): void;
9
14
  };
15
+ /** Handler for a registered HTTP route on the loopback server. */
16
+ type LoopbackRouteHandler = (req: HTTPIncomingMessage, res: HTTPServerResponse) => void;
10
17
  /** Minimal shape of the HTTP request object handed to WS upgrade handlers. */
11
18
  type LoopbackRequest = {
12
19
  url?: string;
@@ -54,6 +61,13 @@ interface LoopbackServer {
54
61
  /** Registers a handler for authenticated, handshaken WebSocket connections
55
62
  * (the protocol socket). */
56
63
  onConnection(handler: LoopbackConnectionHandler): void;
64
+ /** Registers an HTTP route. `handler` runs before mount resolution, after
65
+ * the auth gate (device mode requires the session cookie/token). The route
66
+ * body is read with `collectRequestBody`. */
67
+ registerRoute(method: string, path: string, handler: LoopbackRouteHandler): void;
68
+ /** Writes a raw frame to the connected protocol socket (if any) — the
69
+ * server-initiated push seam (e.g. a `photos.changed` dispatch). */
70
+ push(frame: Uint8Array): boolean;
57
71
  /** Stops accepting connections and closes the server. */
58
72
  close(cb?: (err?: Error | null) => void): void;
59
73
  }
@@ -71,4 +85,4 @@ interface LoopbackServer {
71
85
  */
72
86
  declare function createLoopbackServer(options?: LoopbackServerOptions): LoopbackServer;
73
87
  //#endregion
74
- export { createLoopbackServer as n, LoopbackServer as t };
88
+ export { createLoopbackServer as i, LoopbackServer as n, collectRequestBody as r, LoopbackRouteHandler as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ekrooh/bare",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
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
6
  "license": "MIT",
@@ -10,7 +10,9 @@
10
10
  },
11
11
  "workspaces": [
12
12
  "examples/*",
13
- "e2e"
13
+ "examples/consumer-basic",
14
+ "e2e",
15
+ "apps/*"
14
16
  ],
15
17
  "exports": {
16
18
  ".": "./dist/index.mjs",
@@ -30,10 +32,15 @@
30
32
  "scripts": {
31
33
  "check": "vp check",
32
34
  "lint": "vp fmt . --fix",
35
+ "docs:dev": "vp run docs#dev",
36
+ "docs:build": "vp run docs#build",
37
+ "docs:preview": "vp run docs#preview",
38
+ "docs:check": "node scripts/docs-check.mjs",
33
39
  "typecheck": "tsc --noEmit",
34
- "test": "vp test && npm run test:e2e:web && npm run test:e2e:harness",
40
+ "test": "vp test && npm run test:e2e:web && npm run test:e2e:harness && npm run test:e2e:consumer",
35
41
  "test:unit": "vp test",
36
42
  "test:e2e:web": "node scripts/playwright-local-browsers.mjs test",
43
+ "test:e2e:consumer": "node scripts/playwright-local-browsers.mjs test --config examples/consumer-basic/playwright.config.ts",
37
44
  "dev": "concurrently \"vp -C examples/web dev\" \"npm run dev:bare\"",
38
45
  "predev": "npm run build:pkg",
39
46
  "dev:bare": "node scripts/dev-bare.mjs",
@@ -82,7 +89,7 @@
82
89
  },
83
90
  "dependencies": {
84
91
  "@mantaq/core": "^0.2.0",
85
- "@mantaq/sugar": "^0.2.0",
92
+ "@mantaq/sugar": "^0.3.0",
86
93
  "bare-crypto": "^1.15.3",
87
94
  "bare-encoding": "^1.0.3",
88
95
  "bare-env": "^3.0.0",