@peers-app/peers-sdk 0.28.1 → 0.28.2

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.
@@ -6,6 +6,7 @@ const user_context_singleton_1 = require("../context/user-context-singleton");
6
6
  const contract_ref_1 = require("../define/contract-ref");
7
7
  const lazy_members_1 = require("../define/lazy-members");
8
8
  const table_handle_1 = require("../define/table-handle");
9
+ const wire_value_1 = require("../define/wire-value");
9
10
  const observable_1 = require("../observable");
10
11
  const contract_proxy_1 = require("./contract-proxy");
11
12
  const host_contract_transport_1 = require("./host-contract-transport");
@@ -265,7 +266,8 @@ function createHostContractClient(ref, options, onDispose) {
265
266
  const next = await connect({ timeoutMs });
266
267
  return untilReplaced(Promise.resolve().then(() => send(next.members)), next.signal);
267
268
  };
268
- const tools = (0, lazy_members_1.lazyMembers)((toolName) => (...args) => call((members) => members.tool(toolName)(...args)));
269
+ // Arguments and values go as the bridge carries them: a field left undefined is omitted.
270
+ const tools = (0, lazy_members_1.lazyMembers)((toolName) => (...args) => call((members) => members.tool(toolName)(...args.map((arg) => (arg === undefined ? arg : (0, wire_value_1.snapshotPackageValue)(arg))))));
269
271
  const tables = (0, lazy_members_1.lazyMembers)((tableName) => ({
270
272
  ...(0, table_handle_1.packageTableMethods)((operation, args) => call((members) => members.table(tableName)[operation](...args))),
271
273
  dataChanged: {
@@ -317,7 +319,7 @@ function createHostContractClient(ref, options, onDispose) {
317
319
  if (next.signal.aborted)
318
320
  throw next.signal.reason;
319
321
  const before = remoteRevision;
320
- const result = await untilReplaced(next.members.setObservable(observableName, value), next.signal);
322
+ const result = await untilReplaced(next.members.setObservable(observableName, value === undefined ? value : (0, wire_value_1.snapshotPackageValue)(value)), next.signal);
321
323
  if (!disposed &&
322
324
  connection === next &&
323
325
  remoteRevision === before &&
@@ -1,3 +1,4 @@
1
+ import type { IDataChangedEvent } from "../data/orm/subscribable.data-source";
1
2
  import type { PersistentVarScope } from "../data/persistent-var-identity";
2
3
  import type { IsolatedContractTableOperation } from "../package-loader/isolated-runtime";
3
4
  /**
@@ -21,6 +22,11 @@ export interface IPackageProviderOptions {
21
22
  * events, and observables need none; use these directly only for what those don't cover yet.
22
23
  */
23
24
  export interface IPackageContext {
25
+ /**
26
+ * The device this worker runs on. It says where the code is running, not who is calling:
27
+ * never use it to decide what a caller may do.
28
+ */
29
+ readonly deviceId: string;
24
30
  /** Run a tool on a contract this package consumes (or provides), as this call's caller. */
25
31
  callConsumedTool(contractId: string, version: number, toolName: string, args?: unknown, options?: IPackageProviderOptions): Promise<unknown>;
26
32
  /** Run a tool on another device. The remote device authorizes the call. */
@@ -61,6 +67,12 @@ export interface IPackageContext {
61
67
  * read it again.
62
68
  */
63
69
  watchOwnedPersistentVar(scope: PersistentVarScope, name: string, handler: () => unknown): Promise<PackageUnsubscribe>;
70
+ /**
71
+ * Call `handler` with each change to one of this package's own tables, made here or synced
72
+ * from another device, until the returned function is called or the worker stops. Changes
73
+ * arrive in order, one at a time.
74
+ */
75
+ watchOwnedTable(tableName: string, handler: (event: IDataChangedEvent<unknown>) => unknown): Promise<PackageUnsubscribe>;
64
76
  /**
65
77
  * Set the value of an in-memory observable this package provides (one declared without a
66
78
  * `persistentVar`). The host checks it against the observable's `valueType`, keeps it for
@@ -140,12 +140,19 @@ export interface IPackageDefinition {
140
140
  readonly consumes: readonly IPackageConsumedContract[];
141
141
  /** Run when the package's worker starts, in the order they were added. */
142
142
  readonly startHooks: readonly PackageStartHook[];
143
+ /** Run when the package's worker stops, in the order they were added. */
144
+ readonly stopHooks: readonly PackageStopHook[];
143
145
  }
144
146
  /**
145
147
  * Background work for when the package's worker starts. Its `ctx` belongs to no call: it can use
146
148
  * the package's own tables and variables, but calls to other contracts are refused.
147
149
  */
148
150
  export type PackageStartHook = (ctx: IPackageContext) => unknown;
151
+ /**
152
+ * Local cleanup for when the package's worker stops: end child processes, close files. It gets
153
+ * no `ctx`: the worker's calls to Peers are refused by then.
154
+ */
155
+ export type PackageStopHook = () => unknown;
149
156
  /** The builder {@link definePackage} passes its callback. */
150
157
  export declare class PackageBuilder {
151
158
  /** The package's id, from `newid()`. */
@@ -163,6 +170,7 @@ export declare class PackageBuilder {
163
170
  private readonly provided;
164
171
  private readonly consumed;
165
172
  private readonly starts;
173
+ private readonly stops;
166
174
  /**
167
175
  * Run `fn` each time the package's worker starts, after the package's variables load and
168
176
  * before its in-memory observables publish, so a value set here is the first one readers
@@ -176,6 +184,19 @@ export declare class PackageBuilder {
176
184
  * @param fn - Called with the worker's `ctx`.
177
185
  */
178
186
  onStart(fn: PackageStartHook): void;
187
+ /**
188
+ * Run `fn` when the package's worker stops: when another version replaces this one, when the
189
+ * package is turned off or removed, and when Peers quits. Use it for local cleanup, such as
190
+ * ending child processes or closing files. It gets no `ctx`, because the worker's calls to
191
+ * Peers (its tables, variables, events) are refused once it is stopping.
192
+ *
193
+ * The worker gets 5 seconds for its stop hooks, then it is ended. A privileged package's child
194
+ * processes end with it, unless they detached from it on purpose (a daemon such as a tmux
195
+ * server); clean those up here. A crash or a forced kill runs no stop hooks.
196
+ *
197
+ * @param fn - Called with no arguments; the worker waits for a returned promise.
198
+ */
199
+ onStop(fn: PackageStopHook): void;
179
200
  /**
180
201
  * Provide a contract: this package serves its tools and holds its tables, observables, and
181
202
  * events.
@@ -172,6 +172,7 @@ class PackageBuilder {
172
172
  provided = [];
173
173
  consumed = [];
174
174
  starts = [];
175
+ stops = [];
175
176
  /**
176
177
  * Run `fn` each time the package's worker starts, after the package's variables load and
177
178
  * before its in-memory observables publish, so a value set here is the first one readers
@@ -190,6 +191,24 @@ class PackageBuilder {
190
191
  }
191
192
  this.starts.push(fn);
192
193
  }
194
+ /**
195
+ * Run `fn` when the package's worker stops: when another version replaces this one, when the
196
+ * package is turned off or removed, and when Peers quits. Use it for local cleanup, such as
197
+ * ending child processes or closing files. It gets no `ctx`, because the worker's calls to
198
+ * Peers (its tables, variables, events) are refused once it is stopping.
199
+ *
200
+ * The worker gets 5 seconds for its stop hooks, then it is ended. A privileged package's child
201
+ * processes end with it, unless they detached from it on purpose (a daemon such as a tmux
202
+ * server); clean those up here. A crash or a forced kill runs no stop hooks.
203
+ *
204
+ * @param fn - Called with no arguments; the worker waits for a returned promise.
205
+ */
206
+ onStop(fn) {
207
+ if (typeof fn !== "function") {
208
+ throw new Error("pkg.onStop takes a function");
209
+ }
210
+ this.stops.push(fn);
211
+ }
193
212
  /**
194
213
  * Provide a contract: this package serves its tools and holds its tables, observables, and
195
214
  * events.
@@ -271,6 +290,7 @@ class PackageBuilder {
271
290
  provides: Object.freeze(provides),
272
291
  consumes: Object.freeze(this.consumed.map((consumed) => Object.freeze({ ...consumed }))),
273
292
  startHooks: Object.freeze([...this.starts]),
293
+ stopHooks: Object.freeze([...this.stops]),
274
294
  });
275
295
  }
276
296
  }
@@ -11,6 +11,7 @@ export { AccessLevel } from "../data/access-level";
11
11
  export type { DataFilter, IDataQueryParams } from "../data/orm/data-query";
12
12
  export type { IDataChangedEvent } from "../data/orm/subscribable.data-source";
13
13
  export { type Observable, observable, type Subscription } from "../observable";
14
+ export type { IPackageSaveOptions } from "../package-loader/isolated-runtime";
14
15
  export { idFromKey, isid, newid } from "../peer-id";
15
16
  export { FieldType, type IField } from "../types/field-type";
16
17
  export { zodPeerId } from "../types/zod-types";
@@ -116,9 +116,12 @@ function fieldDetails(schema, shape, input, depth, path, event = false, wholeVal
116
116
  throw new Error(`Field "${path}" uses .nullable(); an empty field is a missing field in Peers, so use .optional() (a null sent for it is removed)`);
117
117
  }
118
118
  const details = nullable || (wholeValue && optional) ? { optional: true } : {};
119
+ // An object with no listed fields (`z.object({}).passthrough()`) is opaque: it gets no
120
+ // `fields`, as a `generatedField` copy of it has none.
119
121
  if (current._def.typeName === "ZodObject" &&
120
122
  type === field_type_1.FieldType.object &&
121
- depth < isolated_artifact_1.ISOLATED_MAX_FIELD_DEPTH) {
123
+ depth < isolated_artifact_1.ISOLATED_MAX_FIELD_DEPTH &&
124
+ Object.keys(current.shape).length > 0) {
122
125
  details.fields = event
123
126
  ? eventFields(current, depth + 1, path)
124
127
  : irFields(current, input, depth + 1, path);
@@ -10,12 +10,19 @@ import type { IPackageDefinition } from "./define-package";
10
10
  * @param ctx - The worker's context, bound to no call.
11
11
  */
12
12
  export declare function startPackage(definition: IPackageDefinition, ctx: IPackageContext): Promise<void>;
13
+ /**
14
+ * Run a package's `pkg.onStop` hooks in order. A hook that fails is logged, and the rest still
15
+ * run. `servePackage` runs this when the worker stops; call it yourself only in tests.
16
+ *
17
+ * @param definition - The package's default export from `src/package.ts`.
18
+ */
19
+ export declare function stopPackage(definition: IPackageDefinition): Promise<void>;
13
20
  /**
14
21
  * Register every provided tool's handler with the Runtime, serve each provided contract's
15
22
  * tables, observables, and events from the worker (guest API 3: every consumer call and
16
- * outgoing message goes through the package), and start the package's variables, events, and
17
- * observables when the worker starts, before any call. `peers-package build` generates the
18
- * call; packages don't call this themselves.
23
+ * outgoing message goes through the package), start the package's variables, events, and
24
+ * observables when the worker starts, before any call, and run its `pkg.onStop` hooks when the
25
+ * worker stops. `peers-package build` generates the call; packages don't call this themselves.
19
26
  *
20
27
  * @param definition - The package's default export from `src/package.ts`.
21
28
  */
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.startPackage = startPackage;
4
+ exports.stopPackage = stopPackage;
4
5
  exports.servePackage = servePackage;
5
6
  const events_1 = require("./events");
6
7
  const observables_1 = require("./observables");
@@ -30,12 +31,28 @@ async function startPackage(definition, ctx) {
30
31
  }
31
32
  await (0, observables_1.servePackageObservables)(definition.provides, ctx);
32
33
  }
34
+ /**
35
+ * Run a package's `pkg.onStop` hooks in order. A hook that fails is logged, and the rest still
36
+ * run. `servePackage` runs this when the worker stops; call it yourself only in tests.
37
+ *
38
+ * @param definition - The package's default export from `src/package.ts`.
39
+ */
40
+ async function stopPackage(definition) {
41
+ for (const hook of definition.stopHooks) {
42
+ try {
43
+ await hook();
44
+ }
45
+ catch (error) {
46
+ console.error("A pkg.onStop hook failed", error);
47
+ }
48
+ }
49
+ }
33
50
  /**
34
51
  * Register every provided tool's handler with the Runtime, serve each provided contract's
35
52
  * tables, observables, and events from the worker (guest API 3: every consumer call and
36
- * outgoing message goes through the package), and start the package's variables, events, and
37
- * observables when the worker starts, before any call. `peers-package build` generates the
38
- * call; packages don't call this themselves.
53
+ * outgoing message goes through the package), start the package's variables, events, and
54
+ * observables when the worker starts, before any call, and run its `pkg.onStop` hooks when the
55
+ * worker stops. `peers-package build` generates the call; packages don't call this themselves.
39
56
  *
40
57
  * @param definition - The package's default export from `src/package.ts`.
41
58
  */
@@ -43,12 +60,19 @@ function servePackage(definition) {
43
60
  const worker = globalThis;
44
61
  const register = worker.registerContractTool;
45
62
  const registerHandler = worker.registerHandler;
63
+ const onWorkerStop = worker.onWorkerStop;
64
+ const stops = definition.stopHooks.length > 0;
46
65
  if (typeof register !== "function" ||
47
66
  typeof registerHandler !== "function" ||
48
- typeof worker.onWorkerStart !== "function") {
67
+ typeof worker.onWorkerStart !== "function" ||
68
+ // Only a package with stop hooks needs the worker's stop.
69
+ (stops && typeof onWorkerStop !== "function")) {
49
70
  throw new Error("servePackage runs inside an isolated package worker");
50
71
  }
51
72
  worker.onWorkerStart((ctx) => startPackage(definition, ctx));
73
+ if (stops) {
74
+ onWorkerStop?.(() => stopPackage(definition));
75
+ }
52
76
  for (const contract of definition.provides) {
53
77
  for (const tool of contract.tools) {
54
78
  register(contract.contractId, contract.version, tool.definition.name, (args, ctx) => (0, tool_1.runPackageTool)(tool, args, ctx));
@@ -1,12 +1,21 @@
1
- import type { IsolatedContractTableOperation } from "../package-loader/isolated-runtime";
1
+ import { type IsolatedContractTableOperation } from "../package-loader/isolated-runtime";
2
2
  import type { IPackageTableHandle } from "./table";
3
+ /**
4
+ * A table call's arguments as the bridge carries them. In a filter, a field set to `undefined`
5
+ * matches an empty field, as `null` does, so it's sent as `null`; anywhere else (options, a
6
+ * record) it's left out.
7
+ *
8
+ * @param operation - The table operation.
9
+ * @param args - Its arguments, as the caller passed them.
10
+ */
11
+ export declare function bridgeTableArgs(operation: IsolatedContractTableOperation, args: unknown[]): unknown[];
3
12
  /** Sends one table operation with its arguments and resolves with the host's reply. */
4
13
  export type PackageTableCall = (operation: IsolatedContractTableOperation, args: unknown[]) => Promise<unknown>;
5
14
  /**
6
15
  * A consumer's table methods over one way of calling the host: a consumed contract's
7
16
  * (`News(ctx).tables.Feeds`) or a UI client's (`hostContract`). Replies are normalized the same
8
- * way for both: a missing row is `undefined`, a list is an array. Saved records are copied for
9
- * the bridge (undefined fields omitted); the providing package's table parses a `save`.
17
+ * way for both: a missing row is `undefined`, a list is an array. Arguments are copied for the
18
+ * bridge ({@link bridgeTableArgs}); the providing package's table parses a `save`.
10
19
  *
11
20
  * @param call - Sends an operation to the table.
12
21
  */
@@ -1,36 +1,54 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.bridgeTableArgs = bridgeTableArgs;
3
4
  exports.packageTableMethods = packageTableMethods;
5
+ const isolated_runtime_1 = require("../package-loader/isolated-runtime");
4
6
  const wire_value_1 = require("./wire-value");
7
+ /** Operations whose first argument is a filter. */
8
+ const FILTER_OPERATIONS = new Set(["list", "count", "findOne"]);
9
+ /**
10
+ * A table call's arguments as the bridge carries them. In a filter, a field set to `undefined`
11
+ * matches an empty field, as `null` does, so it's sent as `null`; anywhere else (options, a
12
+ * record) it's left out.
13
+ *
14
+ * @param operation - The table operation.
15
+ * @param args - Its arguments, as the caller passed them.
16
+ */
17
+ function bridgeTableArgs(operation, args) {
18
+ return args.map((arg, index) => (0, wire_value_1.snapshotPackageValue)(arg, {
19
+ undefinedFieldsAsNull: index === 0 && FILTER_OPERATIONS.has(operation),
20
+ }));
21
+ }
5
22
  /**
6
23
  * A consumer's table methods over one way of calling the host: a consumed contract's
7
24
  * (`News(ctx).tables.Feeds`) or a UI client's (`hostContract`). Replies are normalized the same
8
- * way for both: a missing row is `undefined`, a list is an array. Saved records are copied for
9
- * the bridge (undefined fields omitted); the providing package's table parses a `save`.
25
+ * way for both: a missing row is `undefined`, a list is an array. Arguments are copied for the
26
+ * bridge ({@link bridgeTableArgs}); the providing package's table parses a `save`.
10
27
  *
11
28
  * @param call - Sends an operation to the table.
12
29
  */
13
30
  function packageTableMethods(call) {
31
+ const send = (operation, args) => call(operation, bridgeTableArgs(operation, args));
14
32
  return {
15
33
  async get(recordId) {
16
- return ((await call("get", [recordId])) ?? undefined);
34
+ return ((await send("get", [recordId])) ?? undefined);
17
35
  },
18
36
  async list(filter = {}, options = {}) {
19
- const rows = await call("list", [filter, options]);
37
+ const rows = await send("list", [filter, options]);
20
38
  return (Array.isArray(rows) ? rows : []);
21
39
  },
22
40
  async count(filter = {}) {
23
- return Number(await call("count", [filter]));
41
+ return Number(await send("count", [filter]));
24
42
  },
25
43
  async findOne(filter = {}) {
26
- return ((await call("findOne", [filter])) ?? undefined);
44
+ return ((await send("findOne", [filter])) ?? undefined);
27
45
  },
28
- async save(record) {
29
- // A field left undefined is omitted (stored unset); the bridge carries no undefined.
30
- return (await call("save", [(0, wire_value_1.snapshotPackageValue)(record)]));
46
+ async save(record, options) {
47
+ const allowed = (0, isolated_runtime_1.isolatedSaveOptions)(options);
48
+ return (await send("save", allowed ? [record, allowed] : [record]));
31
49
  },
32
50
  async delete(recordId) {
33
- await call("delete", [recordId]);
51
+ await send("delete", [recordId]);
34
52
  },
35
53
  };
36
54
  }
@@ -1,7 +1,8 @@
1
1
  import type { z } from "zod";
2
2
  import type { DataFilter, IDataQueryParams } from "../data/orm/data-query";
3
3
  import type { IDataChangedEvent } from "../data/orm/subscribable.data-source";
4
- import type { IPackageContext } from "./context";
4
+ import { type IPackageSaveOptions } from "../package-loader/isolated-runtime";
5
+ import type { IPackageContext, PackageUnsubscribe } from "./context";
5
6
  /** What {@link defineTable} takes. */
6
7
  export interface IPackageTableDefinition<S extends z.AnyZodObject = z.AnyZodObject> {
7
8
  /** Table name, unique in the package. Other packages reach it only through a contract. */
@@ -53,8 +54,10 @@ export interface IPackageTableHandle<T extends Record<string, any>, TInput = T>
53
54
  /**
54
55
  * Insert or replace a row. It reaches the providing package's table, which parses it with the
55
56
  * schema first (so defaults and transforms apply), through any override its class makes.
57
+ * Pass `{ restoreIfDeleted: true }` to save a row whose id was deleted before; without it,
58
+ * that save is refused.
56
59
  */
57
- save(record: TInput): Promise<T>;
60
+ save(record: TInput, options?: IPackageSaveOptions): Promise<T>;
58
61
  /** Delete a row by id. */
59
62
  delete(recordId: string): Promise<void>;
60
63
  }
@@ -103,10 +106,29 @@ export declare class PackageTable<S extends z.AnyZodObject = z.AnyZodObject> imp
103
106
  * Insert or replace a row, parsed with the schema first so defaults and transforms apply. An
104
107
  * optional field that is `null` or `undefined` is left out, so it's stored unset; a field with
105
108
  * a default gets the default. Resolves to the row as stored.
109
+ *
110
+ * @param record - The row.
111
+ * @param options - `{ restoreIfDeleted: true }` saves a row whose id was deleted before;
112
+ * without it, that save is refused. An override that calls `super.save` passes it on.
106
113
  */
107
- save(record: z.input<S>): Promise<z.infer<S>>;
114
+ save(record: z.input<S>, options?: IPackageSaveOptions): Promise<z.infer<S>>;
108
115
  /** Delete a row by id. */
109
116
  delete(recordId: string): Promise<void>;
117
+ /**
118
+ * Call `handler` with each change to this table: inserts, updates, and deletes, made by this
119
+ * package, by a consumer, or synced from another device. Changes arrive in order, one at a
120
+ * time; the package's own writes from `handler` arrive too. A handler gets a tool call's
121
+ * deadline; past it, later changes stop waiting for it. Subscribe in `pkg.onStart`: it lasts
122
+ * until the returned function is called or the worker stops, and nothing is replayed from
123
+ * while the worker was stopped, so subscribe first, then read what's already there.
124
+ *
125
+ * Only the package itself can subscribe this way; consumers subscribe to `dataChanged`
126
+ * through a contract.
127
+ *
128
+ * @param handler - Gets each change, with the row as `list` returns it.
129
+ * @returns Stops the subscription.
130
+ */
131
+ subscribe(handler: (event: IDataChangedEvent<z.infer<S>>) => unknown): Promise<PackageUnsubscribe>;
110
132
  /**
111
133
  * One change on its way to one subscriber of the table's `dataChanged`, with `this.ctx`
112
134
  * carrying that subscriber. Return it to send it, a changed copy to send that instead, or
@@ -2,8 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PackageTable = void 0;
4
4
  exports.defineTable = defineTable;
5
+ const isolated_runtime_1 = require("../package-loader/isolated-runtime");
5
6
  const empty_fields_1 = require("./empty-fields");
6
- const wire_value_1 = require("./wire-value");
7
+ const table_handle_1 = require("./table-handle");
7
8
  /**
8
9
  * One of the package's tables, for one call: what `Feeds(ctx)` returns, and what answers a
9
10
  * consumer's call through a contract (from a UI or another package). It runs in the provider's
@@ -40,7 +41,7 @@ class PackageTable {
40
41
  }
41
42
  /** Send one operation to storage and clean rows before provider code receives them. */
42
43
  async store(operation, args) {
43
- const result = await this.ctx.callOwnedTable(this.definition.name, operation, args);
44
+ const result = await this.ctx.callOwnedTable(this.definition.name, operation, (0, table_handle_1.bridgeTableArgs)(operation, args));
44
45
  const { schema } = this.definition;
45
46
  if (operation === "list" && Array.isArray(result)) {
46
47
  return result.map((row) => (0, empty_fields_1.withoutEmptySchemaFields)(schema, row));
@@ -71,16 +72,42 @@ class PackageTable {
71
72
  * Insert or replace a row, parsed with the schema first so defaults and transforms apply. An
72
73
  * optional field that is `null` or `undefined` is left out, so it's stored unset; a field with
73
74
  * a default gets the default. Resolves to the row as stored.
75
+ *
76
+ * @param record - The row.
77
+ * @param options - `{ restoreIfDeleted: true }` saves a row whose id was deleted before;
78
+ * without it, that save is refused. An override that calls `super.save` passes it on.
74
79
  */
75
- async save(record) {
80
+ async save(record, options) {
76
81
  const { schema } = this.definition;
77
- const row = (0, wire_value_1.snapshotPackageValue)(schema.parse((0, empty_fields_1.withoutEmptySchemaFields)(schema, record)));
78
- return (await this.store("save", [row]));
82
+ const row = schema.parse((0, empty_fields_1.withoutEmptySchemaFields)(schema, record));
83
+ const allowed = (0, isolated_runtime_1.isolatedSaveOptions)(options);
84
+ return (await this.store("save", allowed ? [row, allowed] : [row]));
79
85
  }
80
86
  /** Delete a row by id. */
81
87
  async delete(recordId) {
82
88
  await this.store("delete", [recordId]);
83
89
  }
90
+ /**
91
+ * Call `handler` with each change to this table: inserts, updates, and deletes, made by this
92
+ * package, by a consumer, or synced from another device. Changes arrive in order, one at a
93
+ * time; the package's own writes from `handler` arrive too. A handler gets a tool call's
94
+ * deadline; past it, later changes stop waiting for it. Subscribe in `pkg.onStart`: it lasts
95
+ * until the returned function is called or the worker stops, and nothing is replayed from
96
+ * while the worker was stopped, so subscribe first, then read what's already there.
97
+ *
98
+ * Only the package itself can subscribe this way; consumers subscribe to `dataChanged`
99
+ * through a contract.
100
+ *
101
+ * @param handler - Gets each change, with the row as `list` returns it.
102
+ * @returns Stops the subscription.
103
+ */
104
+ async subscribe(handler) {
105
+ const { name, schema } = this.definition;
106
+ return this.ctx.watchOwnedTable(name, (event) => handler({
107
+ ...event,
108
+ dataObject: (0, empty_fields_1.withoutEmptySchemaFields)(schema, event.dataObject),
109
+ }));
110
+ }
84
111
  /**
85
112
  * One change on its way to one subscriber of the table's `dataChanged`, with `this.ctx`
86
113
  * carrying that subscriber. Return it to send it, a changed copy to send that instead, or
@@ -8,5 +8,10 @@
8
8
  * environments (jsdom) lack.
9
9
  *
10
10
  * @param value - The value to send: arguments, a result, a row, an event, or an observable value.
11
+ * @param options - `undefinedFieldsAsNull` sends a missing field as `null` instead of leaving it
12
+ * out, for a table filter: there `{ tag: undefined }` matches an empty field, as `null` does,
13
+ * and leaving it out would match every row.
11
14
  */
12
- export declare function snapshotPackageValue(value: unknown): unknown;
15
+ export declare function snapshotPackageValue(value: unknown, options?: {
16
+ undefinedFieldsAsNull?: boolean;
17
+ }): unknown;
@@ -11,8 +11,11 @@ exports.snapshotPackageValue = snapshotPackageValue;
11
11
  * environments (jsdom) lack.
12
12
  *
13
13
  * @param value - The value to send: arguments, a result, a row, an event, or an observable value.
14
+ * @param options - `undefinedFieldsAsNull` sends a missing field as `null` instead of leaving it
15
+ * out, for a table filter: there `{ tag: undefined }` matches an empty field, as `null` does,
16
+ * and leaving it out would match every row.
14
17
  */
15
- function snapshotPackageValue(value) {
18
+ function snapshotPackageValue(value, options = {}) {
16
19
  const ancestors = new Set();
17
20
  const copy = (current, path) => {
18
21
  if (current === null || typeof current === "string" || typeof current === "boolean") {
@@ -56,10 +59,10 @@ function snapshotPackageValue(value) {
56
59
  }
57
60
  const record = {};
58
61
  for (const [key, field] of Object.entries(current)) {
59
- if (field !== undefined) {
62
+ if (field !== undefined || options.undefinedFieldsAsNull) {
60
63
  // Define rather than assign, so a "__proto__" key stays a field.
61
64
  Object.defineProperty(record, key, {
62
- value: copy(field, `${path}.${key}`),
65
+ value: field === undefined ? null : copy(field, `${path}.${key}`),
63
66
  enumerable: true,
64
67
  writable: true,
65
68
  configurable: true,
@@ -27,9 +27,18 @@ export declare function extractCoreMessage(message: string): string;
27
27
  */
28
28
  export declare class Logger {
29
29
  private source;
30
+ private process;
30
31
  private pendingLogs;
31
32
  private waitingForConsoleLogsTable;
32
- constructor(source?: string);
33
+ /**
34
+ * @param source - What the lines are about, such as a module or package name. Defaults to the
35
+ * caller's file.
36
+ * @param options - `process` records the lines under another process's name (such as
37
+ * `"worker"` for a package worker's output) instead of this one's.
38
+ */
39
+ constructor(source?: string, options?: {
40
+ process?: string;
41
+ });
33
42
  /**
34
43
  * Log a debug message
35
44
  */
@@ -199,9 +199,11 @@ function extractSource(stackTrace) {
199
199
  return undefined;
200
200
  }
201
201
  /**
202
- * Write a log entry to the ConsoleLogs table with a specific source
202
+ * Write a log entry to the ConsoleLogs table with a specific source. `processName` names another
203
+ * process the line came from (such as a package worker); its stack is not this one's, so an
204
+ * error gets none.
203
205
  */
204
- async function writeLogToDatabaseWithSource(level, source, args) {
206
+ async function writeLogToDatabaseWithSource(level, source, args, processName) {
205
207
  try {
206
208
  const timestamp = (0, utils_1.getTimestamp)();
207
209
  // Format message from arguments
@@ -223,12 +225,12 @@ async function writeLogToDatabaseWithSource(level, source, args) {
223
225
  }
224
226
  const context = args.length === 0 ? undefined : args.length === 1 ? args[0] : args;
225
227
  // Get stack trace for errors
226
- const stackTrace = level === "error" ? getStackTrace() : undefined;
228
+ const stackTrace = level === "error" && !processName ? getStackTrace() : undefined;
227
229
  const logRecord = {
228
230
  logId: (0, utils_1.newid)(),
229
231
  timestamp,
230
232
  level,
231
- process: currentProcessName,
233
+ process: processName ?? currentProcessName,
232
234
  processInstanceId: currentProcessInstanceId,
233
235
  source,
234
236
  message,
@@ -254,15 +256,23 @@ async function writeLogToDatabaseWithSource(level, source, args) {
254
256
  */
255
257
  class Logger {
256
258
  source;
259
+ process;
257
260
  pendingLogs = [];
258
261
  waitingForConsoleLogsTable = true;
259
- constructor(source) {
262
+ /**
263
+ * @param source - What the lines are about, such as a module or package name. Defaults to the
264
+ * caller's file.
265
+ * @param options - `process` records the lines under another process's name (such as
266
+ * `"worker"` for a package worker's output) instead of this one's.
267
+ */
268
+ constructor(source, options = {}) {
260
269
  // If no source provided, try to extract from caller's location
261
270
  if (!source) {
262
271
  const stack = new Error().stack;
263
272
  source = extractSource(stack) || "unknown";
264
273
  }
265
274
  this.source = source;
275
+ this.process = options.process;
266
276
  (0, console_logs_table_1.ConsoleLogs)().then(() => {
267
277
  this.waitingForConsoleLogsTable = false;
268
278
  this.flushPendingLogs();
@@ -321,7 +331,7 @@ class Logger {
321
331
  return;
322
332
  }
323
333
  // System is initialized, write directly
324
- writeLogToDatabaseWithSource(level, this.source, args).catch((err) => {
334
+ writeLogToDatabaseWithSource(level, this.source, args, this.process).catch((err) => {
325
335
  originalConsole.error("[console-logger] Failed to write log:", err);
326
336
  });
327
337
  }
@@ -330,7 +340,7 @@ class Logger {
330
340
  this.pendingLogs.length = 0;
331
341
  for (const { level, args } of _pendingLogs) {
332
342
  await (0, utils_1.sleep)(10); // small delay to avoid stampede
333
- await writeLogToDatabaseWithSource(level, this.source, args).catch((err) => {
343
+ await writeLogToDatabaseWithSource(level, this.source, args, this.process).catch((err) => {
334
344
  originalConsole.error("[console-logger] Failed to flush pending log:", err);
335
345
  });
336
346
  }
@@ -10,6 +10,28 @@ import type { IPackageWorkerHealth } from "./package-runtime-state";
10
10
  export declare const ISOLATED_CONTRACT_TABLE_OPERATIONS: readonly ["get", "list", "count", "findOne", "save", "insert", "update", "delete"];
11
11
  /** Consumer-callable operation on an isolated contract table. */
12
12
  export type IsolatedContractTableOperation = (typeof ISOLATED_CONTRACT_TABLE_OPERATIONS)[number];
13
+ /** Options a package may pass with a table `save`. */
14
+ export interface IPackageSaveOptions {
15
+ /** Save a row whose id was deleted before. Without it, that save is refused. */
16
+ restoreIfDeleted?: boolean;
17
+ }
18
+ /**
19
+ * The save options a package may use, from whatever a caller passed: only `restoreIfDeleted`.
20
+ * The host's other save options (snapshots, weak inserts) stay out of package hands.
21
+ *
22
+ * @param options - A table `save`'s second argument, as received.
23
+ * @returns The allowed options, or `undefined` when none are set.
24
+ */
25
+ export declare function isolatedSaveOptions(options: unknown): IPackageSaveOptions | undefined;
26
+ /** One line a package worker wrote to its stdout or stderr. */
27
+ export interface IIsolatedWorkerOutput {
28
+ /** The worker's package. */
29
+ packageId: string;
30
+ /** Which stream the line came from. */
31
+ stream: "stdout" | "stderr";
32
+ /** The line, without its newline. */
33
+ line: string;
34
+ }
13
35
  /**
14
36
  * Trusted caller identity for an isolated tool call. Never read from guest
15
37
  * payloads — the host derives this from `DataContext` / workflow state.
@@ -303,6 +325,10 @@ export interface IIsolatedPackageRuntimeFactoryOptions {
303
325
  persistentVarGateway?: IIsolatedPackagePersistentVarGateway;
304
326
  /** Gateway for consumed calls to selected host/system providers. */
305
327
  providerGateway?: IIsolatedContractProviderGateway;
328
+ /** Receives each line package workers write; without it, lines go to this process's output. */
329
+ onWorkerOutput?: (output: IIsolatedWorkerOutput) => void;
330
+ /** This device's id, which package code reads as `ctx.deviceId`. */
331
+ getDeviceId?: () => string | undefined;
306
332
  }
307
333
  /**
308
334
  * Host callback that builds an {@link IIsolatedPackageRuntime} for one
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ISOLATED_CONTRACT_TABLE_EVENTS = exports.ISOLATED_CONTRACT_TABLE_OPERATIONS = void 0;
4
+ exports.isolatedSaveOptions = isolatedSaveOptions;
4
5
  exports.setIsolatedPackageRuntimeFactory = setIsolatedPackageRuntimeFactory;
5
6
  exports.getIsolatedPackageRuntimeFactory = getIsolatedPackageRuntimeFactory;
6
7
  /** Standard table methods exposed through isolated contract-table references. */
@@ -14,6 +15,18 @@ exports.ISOLATED_CONTRACT_TABLE_OPERATIONS = [
14
15
  "update",
15
16
  "delete",
16
17
  ];
18
+ /**
19
+ * The save options a package may use, from whatever a caller passed: only `restoreIfDeleted`.
20
+ * The host's other save options (snapshots, weak inserts) stay out of package hands.
21
+ *
22
+ * @param options - A table `save`'s second argument, as received.
23
+ * @returns The allowed options, or `undefined` when none are set.
24
+ */
25
+ function isolatedSaveOptions(options) {
26
+ return options?.restoreIfDeleted === true
27
+ ? { restoreIfDeleted: true }
28
+ : undefined;
29
+ }
17
30
  /** Table events consumers may subscribe to on an isolated contract table. */
18
31
  exports.ISOLATED_CONTRACT_TABLE_EVENTS = ["dataChanged"];
19
32
  let isolatedRuntimeFactory;
@@ -48,6 +48,10 @@ export declare class PackageLoader {
48
48
  private contractInstalledPackages;
49
49
  /** Packages installed through the isolated runtime (no host eval). */
50
50
  private isolatedPackageIds;
51
+ /** Each isolated package's name, for its worker's log lines. */
52
+ private isolatedPackageNames;
53
+ /** One logger per package whose worker wrote output, writing as process `worker`. */
54
+ private workerLoggers;
51
55
  /** Per-package counter bumped on every runtime-state change; lets slow unloads yield. */
52
56
  private runtimeStateSequences;
53
57
  /** Hash of the bundle each loaded package was built from, for `onlyIfChanged` loads. */
@@ -189,6 +193,11 @@ export declare class PackageLoader {
189
193
  * Dispose the isolated runtime for this data context.
190
194
  */
191
195
  dispose(): Promise<void>;
196
+ /**
197
+ * Record one line a package worker wrote, under process `worker` with the package's name as
198
+ * its source. It still reaches this process's output too.
199
+ */
200
+ private logWorkerOutput;
192
201
  private retireHostEndpoints;
193
202
  /**
194
203
  * Resolve and load every non-disabled package in this data context.
@@ -16,6 +16,7 @@ const package_version_resolver_1 = require("../data/package-version-resolver");
16
16
  const package_versions_1 = require("../data/package-versions");
17
17
  const packages_1 = require("../data/packages");
18
18
  const keys_1 = require("../keys");
19
+ const console_logger_1 = require("../logging/console-logger");
19
20
  const observable_1 = require("../observable");
20
21
  const contract_package_loader_1 = require("./contract-package-loader");
21
22
  const isolated_artifact_1 = require("./isolated-artifact");
@@ -63,6 +64,10 @@ class PackageLoader {
63
64
  contractInstalledPackages = new Set();
64
65
  /** Packages installed through the isolated runtime (no host eval). */
65
66
  isolatedPackageIds = new Set();
67
+ /** Each isolated package's name, for its worker's log lines. */
68
+ isolatedPackageNames = new Map();
69
+ /** One logger per package whose worker wrote output, writing as process `worker`. */
70
+ workerLoggers = new Map();
66
71
  /** Per-package counter bumped on every runtime-state change; lets slow unloads yield. */
67
72
  runtimeStateSequences = new Map();
68
73
  /** Hash of the bundle each loaded package was built from, for `onlyIfChanged` loads. */
@@ -120,6 +125,8 @@ class PackageLoader {
120
125
  resolverOnly: true,
121
126
  }),
122
127
  },
128
+ onWorkerOutput: (output) => this.logWorkerOutput(output),
129
+ getDeviceId: () => this.dataContext.userContext?.deviceId(),
123
130
  });
124
131
  this.unsubscribePackageHealth = this.isolatedRuntime.subscribePackageHealth?.((packageId) => {
125
132
  const previous = this.runtimeStates()[packageId];
@@ -623,9 +630,28 @@ class PackageLoader {
623
630
  this.contractInstalledPackages.clear();
624
631
  this.packageInstances = {};
625
632
  this.loadedBundleHashes.clear();
633
+ this.workerLoggers.clear();
634
+ this.isolatedPackageNames.clear();
626
635
  this.runtimeStateSequences.clear();
627
636
  this.runtimeStates({});
628
637
  }
638
+ /**
639
+ * Record one line a package worker wrote, under process `worker` with the package's name as
640
+ * its source. It still reaches this process's output too.
641
+ */
642
+ logWorkerOutput({ packageId, stream, line }) {
643
+ let logger = this.workerLoggers.get(packageId);
644
+ if (!logger) {
645
+ logger = new console_logger_1.Logger(this.isolatedPackageNames.get(packageId) ?? packageId, {
646
+ process: "worker",
647
+ });
648
+ this.workerLoggers.set(packageId, logger);
649
+ }
650
+ if (stream === "stderr")
651
+ logger.error(line);
652
+ else
653
+ logger.log(line);
654
+ }
629
655
  retireHostEndpoints(packageId) {
630
656
  this.hostActivationGenerations.set(packageId, (this.hostActivationGenerations.get(packageId) ?? 0) + 1);
631
657
  for (const router of this.consumedContractRouters)
@@ -935,6 +961,10 @@ class PackageLoader {
935
961
  return undefined;
936
962
  }
937
963
  assertCurrent();
964
+ if (this.isolatedPackageNames.get(pkg.packageId) !== pkg.name) {
965
+ this.workerLoggers.delete(pkg.packageId);
966
+ }
967
+ this.isolatedPackageNames.set(pkg.packageId, pkg.name);
938
968
  const installOptions = { ...isolatedContractLifecycle(selectedPackageVersion), assertCurrent };
939
969
  let installed;
940
970
  if (this.isolatedRuntime.isInstalled(pkg.packageId)) {
@@ -237,6 +237,8 @@ function mockProviderContext(contractId, tables) {
237
237
  get(_target, property) {
238
238
  if (property === "callOwnedTable")
239
239
  return callOwnedTable;
240
+ if (property === "deviceId")
241
+ return "mock-host-device";
240
242
  if (typeof property !== "string" || property === "then")
241
243
  return undefined;
242
244
  return () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peers-app/peers-sdk",
3
- "version": "0.28.1",
3
+ "version": "0.28.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/peers-app/peers-sdk.git"