@peers-app/peers-ui 0.33.12 → 0.33.14

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 (51) hide show
  1. package/dist/apps-home/app-menu.d.ts +3 -1
  2. package/dist/apps-home/app-menu.js +2 -2
  3. package/dist/apps-home/app-status.d.ts +7 -0
  4. package/dist/apps-home/app-status.js +16 -0
  5. package/dist/apps-home/app-tile.d.ts +3 -1
  6. package/dist/apps-home/app-tile.js +10 -5
  7. package/dist/apps-home/apps-home.js +5 -13
  8. package/dist/apps-home/current-group-name.d.ts +5 -0
  9. package/dist/apps-home/current-group-name.js +19 -0
  10. package/dist/components/group-switcher.js +1 -1
  11. package/dist/components/markdown-editor/editor.d.ts +11 -5
  12. package/dist/components/markdown-editor/editor.js +4 -3
  13. package/dist/components/markdown-editor/mentions-plugin.d.ts +29 -10
  14. package/dist/components/markdown-editor/mentions-plugin.js +108 -92
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +2 -0
  17. package/dist/mentions/mention-chip.d.ts +1 -1
  18. package/dist/mentions/mention-chip.js +2 -1
  19. package/dist/mentions/mentions-client.d.ts +17 -3
  20. package/dist/mentions/mentions-client.js +36 -6
  21. package/dist/screens/packages/package-info.js +1 -1
  22. package/dist/screens/packages/package-runtime-status.d.ts +2 -2
  23. package/dist/screens/packages/package-runtime-status.js +3 -3
  24. package/dist/screens/packages/package-waiting.d.ts +31 -0
  25. package/dist/screens/packages/package-waiting.js +173 -0
  26. package/dist/screens/packages/packages-ipc.d.ts +62 -1
  27. package/dist/screens/packages/packages-ipc.js +105 -4
  28. package/dist/screens/setup-user.js +2 -2
  29. package/dist/theme.css +197 -0
  30. package/dist/ui-contracts/host-ui-contract.d.ts +28 -0
  31. package/dist/ui-contracts/host-ui-contract.js +45 -0
  32. package/dist/ui-contracts/implement-piece.d.ts +24 -0
  33. package/dist/ui-contracts/implement-piece.js +44 -0
  34. package/dist/ui-contracts/index.d.ts +6 -0
  35. package/dist/ui-contracts/index.js +17 -0
  36. package/dist/ui-contracts/mock-piece.d.ts +36 -0
  37. package/dist/ui-contracts/mock-piece.js +56 -0
  38. package/dist/ui-contracts/piece-host.d.ts +99 -0
  39. package/dist/ui-contracts/piece-host.js +266 -0
  40. package/dist/ui-contracts/piece-resolution.d.ts +55 -0
  41. package/dist/ui-contracts/piece-resolution.js +186 -0
  42. package/dist/ui-contracts/piece.d.ts +77 -0
  43. package/dist/ui-contracts/piece.js +358 -0
  44. package/dist/ui-contracts/popover-surface.d.ts +21 -0
  45. package/dist/ui-contracts/popover-surface.js +169 -0
  46. package/dist/ui-contracts/types.d.ts +113 -0
  47. package/dist/ui-contracts/types.js +2 -0
  48. package/dist/ui-router/runnable-version.d.ts +4 -1
  49. package/dist/ui-router/runnable-version.js +6 -3
  50. package/dist/ui-router/ui-loader.js +127 -37
  51. package/package.json +3 -3
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hostUIContract = hostUIContract;
4
+ exports.pieceHandleKey = pieceHandleKey;
5
+ function hostUIContract(contractOrId, versionOrOptions, maybeOptions) {
6
+ const declared = typeof contractOrId === "object" ? contractOrId : undefined;
7
+ const contractId = declared ? declared.contractId : contractOrId;
8
+ const version = declared ? declared.version : versionOrOptions;
9
+ const options = (declared ? versionOrOptions : maybeOptions);
10
+ if (typeof contractId !== "string" || !Number.isInteger(version) || version < 1) {
11
+ throw new Error("hostUIContract takes a UI contract's id and version, or its declaration");
12
+ }
13
+ const handles = new Map();
14
+ const handle = (name) => {
15
+ let found = handles.get(name);
16
+ if (!found) {
17
+ found = Object.freeze({
18
+ kind: "piece-handle",
19
+ contractId,
20
+ version,
21
+ name,
22
+ ...(options?.dataContextId === undefined ? {} : { dataContextId: options.dataContextId }),
23
+ ...(options?.providerPackageId ? { providerPackageId: options.providerPackageId } : {}),
24
+ });
25
+ handles.set(name, found);
26
+ }
27
+ return found;
28
+ };
29
+ // Piece names come from the declaration's type, so any name gets a handle; a piece the
30
+ // provider doesn't declare shows the `failed` fallback.
31
+ const pieces = new Proxy({}, {
32
+ get: (_target, name) => (typeof name === "string" ? handle(name) : undefined),
33
+ });
34
+ return Object.freeze({ contractId, version, pieces });
35
+ }
36
+ /**
37
+ * A stable string for a handle, for effects and caches: its UI contract version, piece, provider
38
+ * and named group.
39
+ *
40
+ * @param handle - A piece handle.
41
+ */
42
+ function pieceHandleKey(handle) {
43
+ const group = typeof handle.dataContextId === "string" ? handle.dataContextId : "";
44
+ return `${handle.contractId}@${handle.version}/${handle.name}|${handle.providerPackageId ?? ""}|${group}`;
45
+ }
@@ -0,0 +1,24 @@
1
+ import type { IPieceImplementation, IUIContractDeclaration, UIContractPieceNamesOf } from "@peers-app/peers-sdk";
2
+ import type React from "react";
3
+ import type { PieceComponentProps } from "./types";
4
+ /**
5
+ * Implement one piece of a UI contract the package provides, for its UI bundle. Pass the result
6
+ * in `exportUIs({ uis, pieces: [...] })` in `src/uis.ts`; the package's own screens can render
7
+ * the same component directly, so there's one copy.
8
+ *
9
+ * ```tsx
10
+ * import type { LabelPickerUI } from "../ui-contracts"; // types only
11
+ * function LabelPicker({ props, emit, close, groupId }: PieceComponentProps<typeof LabelPickerUI, "picker">) { … }
12
+ * export const PickerPiece = implementPiece<typeof LabelPickerUI, "picker">(labelPickerUIId, 1, "picker", LabelPicker);
13
+ * ```
14
+ *
15
+ * Import the UI contract's declaration as a type only, so its code stays out of the UI bundle.
16
+ *
17
+ * @param contractId - The UI contract's id.
18
+ * @param version - The UI contract version this implements (the one the package provides).
19
+ * @param name - The piece's name.
20
+ * @param component - The component: it gets the embedder's props, `emit`, `close`, and the group.
21
+ */
22
+ export declare function implementPiece<T extends IUIContractDeclaration<any, any, any>, N extends UIContractPieceNamesOf<T> = UIContractPieceNamesOf<T>>(contractId: string, version: number, name: N, component: React.ComponentType<PieceComponentProps<T, N>>): IPieceImplementation;
23
+ /** The key a piece's component is registered under: its UI contract version and its name. */
24
+ export declare function pieceKey(contractId: string, version: number, name: string): string;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.implementPiece = implementPiece;
4
+ exports.pieceKey = pieceKey;
5
+ /**
6
+ * Implement one piece of a UI contract the package provides, for its UI bundle. Pass the result
7
+ * in `exportUIs({ uis, pieces: [...] })` in `src/uis.ts`; the package's own screens can render
8
+ * the same component directly, so there's one copy.
9
+ *
10
+ * ```tsx
11
+ * import type { LabelPickerUI } from "../ui-contracts"; // types only
12
+ * function LabelPicker({ props, emit, close, groupId }: PieceComponentProps<typeof LabelPickerUI, "picker">) { … }
13
+ * export const PickerPiece = implementPiece<typeof LabelPickerUI, "picker">(labelPickerUIId, 1, "picker", LabelPicker);
14
+ * ```
15
+ *
16
+ * Import the UI contract's declaration as a type only, so its code stays out of the UI bundle.
17
+ *
18
+ * @param contractId - The UI contract's id.
19
+ * @param version - The UI contract version this implements (the one the package provides).
20
+ * @param name - The piece's name.
21
+ * @param component - The component: it gets the embedder's props, `emit`, `close`, and the group.
22
+ */
23
+ function implementPiece(contractId, version, name, component) {
24
+ if (typeof contractId !== "string" || !Number.isInteger(version) || version < 1) {
25
+ throw new Error("implementPiece takes a UI contract's id and a positive integer version");
26
+ }
27
+ if (typeof name !== "string" || !name) {
28
+ throw new Error("implementPiece takes the piece's name");
29
+ }
30
+ if (typeof component !== "function" && typeof component !== "object") {
31
+ throw new Error(`implementPiece: piece "${name}" needs a component`);
32
+ }
33
+ return Object.freeze({
34
+ kind: "piece-implementation",
35
+ contractId,
36
+ version,
37
+ name,
38
+ component: component,
39
+ });
40
+ }
41
+ /** The key a piece's component is registered under: its UI contract version and its name. */
42
+ function pieceKey(contractId, version, name) {
43
+ return `${contractId}@${version}/${name}`;
44
+ }
@@ -0,0 +1,6 @@
1
+ export { hostUIContract } from "./host-ui-contract";
2
+ export { implementPiece } from "./implement-piece";
3
+ export { type IMockPiece, mockPiece } from "./mock-piece";
4
+ export { type IPieceProps, type IPieceSize, Piece, type PieceState, usePiece, usePieceSize, } from "./piece";
5
+ export type { PopoverAnchor } from "./popover-surface";
6
+ export type { IHostUIContractClient, IHostUIContractOptions, IPieceHandle, IPieceOpenTarget, IPieceUnavailable, PieceComponentProps, PieceEmitters, PieceHandlers, PieceUnavailableReason, } from "./types";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.usePieceSize = exports.usePiece = exports.Piece = exports.mockPiece = exports.implementPiece = exports.hostUIContract = void 0;
4
+ // UI contracts: a package's screens embed another package's UI pieces by contract, not by
5
+ // component id. The provider implements its pieces in its UI bundle (`implementPiece`); a
6
+ // consumer embeds them (`hostUIContract`, `<Piece>`) and gets a fallback when they can't show.
7
+ // See docs/Packages/ui-contracts.md.
8
+ var host_ui_contract_1 = require("./host-ui-contract");
9
+ Object.defineProperty(exports, "hostUIContract", { enumerable: true, get: function () { return host_ui_contract_1.hostUIContract; } });
10
+ var implement_piece_1 = require("./implement-piece");
11
+ Object.defineProperty(exports, "implementPiece", { enumerable: true, get: function () { return implement_piece_1.implementPiece; } });
12
+ var mock_piece_1 = require("./mock-piece");
13
+ Object.defineProperty(exports, "mockPiece", { enumerable: true, get: function () { return mock_piece_1.mockPiece; } });
14
+ var piece_1 = require("./piece");
15
+ Object.defineProperty(exports, "Piece", { enumerable: true, get: function () { return piece_1.Piece; } });
16
+ Object.defineProperty(exports, "usePiece", { enumerable: true, get: function () { return piece_1.usePiece; } });
17
+ Object.defineProperty(exports, "usePieceSize", { enumerable: true, get: function () { return piece_1.usePieceSize; } });
@@ -0,0 +1,36 @@
1
+ import type { ContractPieceKind, IField } from "@peers-app/peers-sdk";
2
+ import type { IPieceHandle, PieceComponent } from "./types";
3
+ /** What a test can do with a stand-in piece from {@link mockPiece}. */
4
+ export interface IMockPiece {
5
+ /** The props it was last drawn with, or undefined before it drew. */
6
+ readonly props: Record<string, unknown> | undefined;
7
+ /** How many times it has drawn. */
8
+ readonly renders: number;
9
+ /** Send one of its emits to the embedder, as the real piece would. */
10
+ emit(name: string, payload?: unknown): void;
11
+ /** Ask the embedder to close it (a popover's `close`). */
12
+ close(): void;
13
+ /** Remove the stand-in. */
14
+ restore(): void;
15
+ }
16
+ /**
17
+ * Stand in for a piece in a consumer's tests: `<Piece of={handle}>` draws a small placeholder
18
+ * (`data-testid="mock-piece-<name>"`) instead of loading a provider, and the test sends the
19
+ * piece's emits and reads the props it got. Declare the emits the test sends, and the props to
20
+ * check, as the real UI contract declares them.
21
+ *
22
+ * ```tsx
23
+ * const picker = mockPiece(labelPicker.pieces.picker, { kind: "popover", emits: ["chosen"] });
24
+ * render(<TaskRow task={task} />);
25
+ * picker.emit("chosen", { labelId: "l1" });
26
+ * ```
27
+ *
28
+ * @param handle - The piece, from the consumer's UI contract client.
29
+ * @param options - Its kind, props fields, emit names, and an optional component to draw.
30
+ */
31
+ export declare function mockPiece(handle: IPieceHandle, options?: {
32
+ kind?: ContractPieceKind;
33
+ propsFields?: IField[];
34
+ emits?: string[];
35
+ component?: PieceComponent;
36
+ }): IMockPiece;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mockPiece = mockPiece;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const piece_resolution_1 = require("./piece-resolution");
6
+ /**
7
+ * Stand in for a piece in a consumer's tests: `<Piece of={handle}>` draws a small placeholder
8
+ * (`data-testid="mock-piece-<name>"`) instead of loading a provider, and the test sends the
9
+ * piece's emits and reads the props it got. Declare the emits the test sends, and the props to
10
+ * check, as the real UI contract declares them.
11
+ *
12
+ * ```tsx
13
+ * const picker = mockPiece(labelPicker.pieces.picker, { kind: "popover", emits: ["chosen"] });
14
+ * render(<TaskRow task={task} />);
15
+ * picker.emit("chosen", { labelId: "l1" });
16
+ * ```
17
+ *
18
+ * @param handle - The piece, from the consumer's UI contract client.
19
+ * @param options - Its kind, props fields, emit names, and an optional component to draw.
20
+ */
21
+ function mockPiece(handle, options = {}) {
22
+ const piece = {
23
+ name: handle.name,
24
+ kind: options.kind ?? "view",
25
+ description: "A stand-in for tests.",
26
+ propsFields: options.propsFields ?? [],
27
+ emits: (options.emits ?? []).map((name) => ({ name, description: "", payloadFields: [] })),
28
+ };
29
+ const state = { renders: 0 };
30
+ const Custom = options.component;
31
+ const Stand = (props) => {
32
+ state.props = props.props;
33
+ state.renders += 1;
34
+ state.emit = props.emit;
35
+ state.close = props.close;
36
+ return Custom ? ((0, jsx_runtime_1.jsx)(Custom, { ...props })) : ((0, jsx_runtime_1.jsx)("div", { "data-testid": `mock-piece-${handle.name}`, children: handle.name }));
37
+ };
38
+ const restore = (0, piece_resolution_1.setPieceMock)(handle.contractId, handle.version, piece, Stand);
39
+ return {
40
+ get props() {
41
+ return state.props;
42
+ },
43
+ get renders() {
44
+ return state.renders;
45
+ },
46
+ emit(name, payload) {
47
+ if (!state.emit)
48
+ throw new Error(`Piece "${handle.name}" hasn't drawn yet`);
49
+ state.emit[name]?.(payload);
50
+ },
51
+ close() {
52
+ state.close?.();
53
+ },
54
+ restore,
55
+ };
56
+ }
@@ -0,0 +1,99 @@
1
+ import { type IContractDefinition, type IContractProviderInfo, type IPeersPackageUIs } from "@peers-app/peers-sdk";
2
+ import type { PieceComponent } from "./types";
3
+ /** The active group's id, or the user's for Personal: where a piece shows when none is named. */
4
+ export declare function defaultDataContextId(): Promise<string>;
5
+ /**
6
+ * The registered providers of a contract version in a group, with which one is active and, for
7
+ * one that serves it through `alsoImplements`, the version it implements.
8
+ *
9
+ * @param dataContextId - The group, or the user's id for Personal.
10
+ * @param contractId - The UI contract's id.
11
+ * @param version - Its version.
12
+ */
13
+ export declare function listProviders(dataContextId: string, contractId: string, version: number): Promise<IContractProviderInfo[]>;
14
+ /**
15
+ * A contract version's definition as the group registered it: for a UI contract, its pieces.
16
+ *
17
+ * @param dataContextId - The group.
18
+ * @param contractId - The contract's id.
19
+ * @param version - Its version.
20
+ */
21
+ export declare function contractDefinition(dataContextId: string, contractId: string, version: number): Promise<IContractDefinition>;
22
+ /** A provider's runtime in a group, on this device: running (with its version) or why not. */
23
+ export type ProviderRuntime = {
24
+ running: true;
25
+ packageVersionId: string;
26
+ } | {
27
+ running: false;
28
+ reason: string;
29
+ };
30
+ /**
31
+ * Whether a provider runs in a group on this device, and which version. Pieces draw with the
32
+ * version that registered their UI contract there.
33
+ *
34
+ * @param dataContextId - The group.
35
+ * @param packageId - The provider.
36
+ */
37
+ export declare function providerRuntime(dataContextId: string, packageId: string): Promise<ProviderRuntime>;
38
+ /**
39
+ * Call `onChange` when which packages run in a group, or which versions, changes on this device:
40
+ * a package starting at startup registers its UI contracts, so a piece looked up before it
41
+ * was missing then. Changes that leave every package's status and version as they were are
42
+ * ignored. A new connection to the host (Electron's reconnects after sleep) ends the old
43
+ * subscription, so watching starts again on it.
44
+ *
45
+ * @param dataContextId - The group.
46
+ * @param onChange - Called after each such change.
47
+ */
48
+ export declare function watchProviders(dataContextId: string, onChange: () => void): void;
49
+ /** A package that provides a UI contract version in a group but doesn't serve it here. */
50
+ export interface IInstalledProvider {
51
+ /** Its id. */
52
+ packageId: string;
53
+ /** Its name. */
54
+ name: string;
55
+ /** Why it doesn't serve the contract here. */
56
+ reason: string;
57
+ /** Set when it provides only older versions of the UI contract. */
58
+ older?: true;
59
+ }
60
+ /**
61
+ * A package installed in a group that provides a UI contract version but doesn't run on this
62
+ * device: it waits for a contract it requires, is turned off, isn't approved here, or can't run
63
+ * on this host. Only a running package registers its UI contracts, so the catalog doesn't list
64
+ * it. This reads the group's packages and, for each one not running, the manifest this device
65
+ * stored for its selected version; a version this device never read has none, and isn't found.
66
+ * One that provides the version comes first; else one that provides an older version, marked
67
+ * `older`.
68
+ *
69
+ * @param dataContextId - The group.
70
+ * @param contractId - The UI contract's id.
71
+ * @param version - Its version.
72
+ * @param providerPackageId - Look at this package only, as a handle that names one does.
73
+ */
74
+ export declare function installedProvider(dataContextId: string, contractId: string, version: number, providerPackageId?: string): Promise<IInstalledProvider | undefined>;
75
+ /** The pieces a UI bundle's `exportUIs` call registered, by piece key. */
76
+ export declare function piecesFromExport(exported: IPeersPackageUIs | undefined): Map<string, PieceComponent>;
77
+ /**
78
+ * Record the pieces a screen's load of a UI bundle registered, so a piece of the same version
79
+ * doesn't run the bundle again. Called by the UI loader, which runs a package's bundle for the
80
+ * active group's screens.
81
+ *
82
+ * @param packageVersionId - The version whose bundle ran.
83
+ * @param uiBundleFileId - Its UI bundle's file.
84
+ * @param exported - What the bundle passed `exportUIs`.
85
+ */
86
+ export declare function recordLoadedPieces(packageVersionId: string, uiBundleFileId: string, exported: IPeersPackageUIs | undefined): void;
87
+ /**
88
+ * The pieces a package version's UI bundle registers, running the bundle once per version and
89
+ * file when no screen already did. The version's row is read in the piece's group, and in a group
90
+ * the bundle must match its hash. A bundle run for pieces registers no screens, so another
91
+ * version's pieces never replace what a screen shows.
92
+ *
93
+ * @param dataContextId - The group the piece is embedded for.
94
+ * @param packageId - The provider.
95
+ * @param packageVersionId - The version it runs there.
96
+ */
97
+ export declare function loadVersionPieces(dataContextId: string, packageId: string, packageVersionId: string): Promise<Map<string, PieceComponent>>;
98
+ /** Forget loaded bundles: for tests. */
99
+ export declare function resetPieceBundles(): void;
@@ -0,0 +1,266 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultDataContextId = defaultDataContextId;
4
+ exports.listProviders = listProviders;
5
+ exports.contractDefinition = contractDefinition;
6
+ exports.providerRuntime = providerRuntime;
7
+ exports.watchProviders = watchProviders;
8
+ exports.installedProvider = installedProvider;
9
+ exports.piecesFromExport = piecesFromExport;
10
+ exports.recordLoadedPieces = recordLoadedPieces;
11
+ exports.loadVersionPieces = loadVersionPieces;
12
+ exports.resetPieceBundles = resetPieceBundles;
13
+ const peers_sdk_1 = require("@peers-app/peers-sdk");
14
+ const packages_ipc_1 = require("../screens/packages/packages-ipc");
15
+ const bundle_files_1 = require("../ui-router/bundle-files");
16
+ const implement_piece_1 = require("./implement-piece");
17
+ // What resolving a piece needs from the host, kept in one module: the catalog of a group's UI
18
+ // contract providers, the version of a provider this device runs there, and that version's UI
19
+ // bundle. Tests replace this module.
20
+ const catalogs = new Map();
21
+ function catalogFor(dataContextId) {
22
+ let catalog = catalogs.get(dataContextId);
23
+ if (!catalog) {
24
+ catalog = (0, peers_sdk_1.hostContractConsumer)((0, peers_sdk_1.getContractCatalogDefinition)(), {
25
+ dataContextId: async () => dataContextId,
26
+ });
27
+ catalogs.set(dataContextId, catalog);
28
+ }
29
+ return catalog;
30
+ }
31
+ /** The active group's id, or the user's for Personal: where a piece shows when none is named. */
32
+ async function defaultDataContextId() {
33
+ return (await (0, peers_sdk_1.getDefaultDataContext)()).dataContextId;
34
+ }
35
+ /**
36
+ * The registered providers of a contract version in a group, with which one is active and, for
37
+ * one that serves it through `alsoImplements`, the version it implements.
38
+ *
39
+ * @param dataContextId - The group, or the user's id for Personal.
40
+ * @param contractId - The UI contract's id.
41
+ * @param version - Its version.
42
+ */
43
+ async function listProviders(dataContextId, contractId, version) {
44
+ const consumer = await catalogFor(dataContextId).get();
45
+ return (await consumer.tools.listContractProviders({ contractId, version })).providers;
46
+ }
47
+ /**
48
+ * A contract version's definition as the group registered it: for a UI contract, its pieces.
49
+ *
50
+ * @param dataContextId - The group.
51
+ * @param contractId - The contract's id.
52
+ * @param version - Its version.
53
+ */
54
+ async function contractDefinition(dataContextId, contractId, version) {
55
+ const consumer = await catalogFor(dataContextId).get();
56
+ return (await consumer.tools.getContractDefinition({ contractId, version })).definition;
57
+ }
58
+ /**
59
+ * Whether a provider runs in a group on this device, and which version. Pieces draw with the
60
+ * version that registered their UI contract there.
61
+ *
62
+ * @param dataContextId - The group.
63
+ * @param packageId - The provider.
64
+ */
65
+ async function providerRuntime(dataContextId, packageId) {
66
+ const consumer = await (0, packages_ipc_1.packagesContractFor)(dataContextId).get();
67
+ const { package: details } = await consumer.tools.getPackage({ packageId });
68
+ const runtime = details.runtime;
69
+ // A waiting or failed update can leave the previous version serving.
70
+ if (runtime.running?.packageVersionId) {
71
+ return { running: true, packageVersionId: runtime.running.packageVersionId };
72
+ }
73
+ return {
74
+ running: false,
75
+ reason: runtime.reason || `${details.name} is ${runtime.status} on this device`,
76
+ };
77
+ }
78
+ /**
79
+ * Call `onChange` when which packages run in a group, or which versions, changes on this device:
80
+ * a package starting at startup registers its UI contracts, so a piece looked up before it
81
+ * was missing then. Changes that leave every package's status and version as they were are
82
+ * ignored. A new connection to the host (Electron's reconnects after sleep) ends the old
83
+ * subscription, so watching starts again on it.
84
+ *
85
+ * @param dataContextId - The group.
86
+ * @param onChange - Called after each such change.
87
+ */
88
+ function watchProviders(dataContextId, onChange) {
89
+ const watch = () => (0, packages_ipc_1.packagesContractFor)(dataContextId)
90
+ .get()
91
+ .then((consumer) => {
92
+ const states = consumer.observables.runtimeStates;
93
+ const summary = (value) => JSON.stringify(Object.entries(value ?? {})
94
+ .map(([packageId, state]) => [
95
+ packageId,
96
+ state?.status,
97
+ state?.running?.packageVersionId,
98
+ ])
99
+ .sort());
100
+ let last = summary(states());
101
+ states.subscribe((value) => {
102
+ const next = summary(value);
103
+ if (next === last)
104
+ return;
105
+ last = next;
106
+ onChange();
107
+ });
108
+ // A provider may have started between the lookup that began watching and this first
109
+ // reading, so it's no change here: look again once.
110
+ onChange();
111
+ })
112
+ .catch((error) => console.warn(`Can't follow packages in ${dataContextId}`, error));
113
+ void watch();
114
+ (0, peers_sdk_1.subscribeHostContractTransport)((transport) => {
115
+ if (transport)
116
+ void watch();
117
+ }, { emitCurrent: false });
118
+ }
119
+ /**
120
+ * A package installed in a group that provides a UI contract version but doesn't run on this
121
+ * device: it waits for a contract it requires, is turned off, isn't approved here, or can't run
122
+ * on this host. Only a running package registers its UI contracts, so the catalog doesn't list
123
+ * it. This reads the group's packages and, for each one not running, the manifest this device
124
+ * stored for its selected version; a version this device never read has none, and isn't found.
125
+ * One that provides the version comes first; else one that provides an older version, marked
126
+ * `older`.
127
+ *
128
+ * @param dataContextId - The group.
129
+ * @param contractId - The UI contract's id.
130
+ * @param version - Its version.
131
+ * @param providerPackageId - Look at this package only, as a handle that names one does.
132
+ */
133
+ async function installedProvider(dataContextId, contractId, version, providerPackageId) {
134
+ const consumer = await (0, packages_ipc_1.packagesContractFor)(dataContextId).get();
135
+ const { packages } = await consumer.tools.listPackages();
136
+ const idle = packages.filter((pkg) => !pkg.runtime.running?.packageVersionId &&
137
+ (!providerPackageId || pkg.packageId === providerPackageId));
138
+ if (!idle.length)
139
+ return undefined;
140
+ const manifests = (0, peers_sdk_1.PackageVersionManifests)((await (0, peers_sdk_1.getUserContext)()).getDataContext(dataContextId));
141
+ let older;
142
+ for (const pkg of idle) {
143
+ const packageVersionId = pkg.requested.effectivePackageVersionId;
144
+ if (!packageVersionId)
145
+ continue;
146
+ const row = await manifests.get(packageVersionId).catch(() => undefined);
147
+ if (!row || row.packageId !== pkg.packageId)
148
+ continue;
149
+ let uiProvides;
150
+ try {
151
+ uiProvides = JSON.parse(row.manifest).uiProvides;
152
+ }
153
+ catch {
154
+ continue;
155
+ }
156
+ if (!Array.isArray(uiProvides))
157
+ continue;
158
+ const provided = (0, peers_sdk_1.providedContracts)(uiProvides);
159
+ const found = {
160
+ packageId: pkg.packageId,
161
+ name: pkg.name,
162
+ reason: pkg.runtime.reason ||
163
+ (pkg.disabled
164
+ ? `it's turned off in this group`
165
+ : `it's ${pkg.runtime.status} on this device`),
166
+ };
167
+ if ((0, peers_sdk_1.providesContract)(provided, contractId, version))
168
+ return found;
169
+ if (!older && provided.some((p) => p.contractId === contractId && p.version < version)) {
170
+ older = { ...found, older: true };
171
+ }
172
+ }
173
+ return older;
174
+ }
175
+ /**
176
+ * Each UI bundle's pieces, by version and bundle file: `<packageVersionId>:<fileId>`. A load in
177
+ * progress is its promise; a finished one is its pieces, which a later run of the same file (a
178
+ * screen opened after a piece showed) doesn't replace, so a mounted piece keeps its component
179
+ * when its resolution refreshes. A rebuilt bundle is another file, so it loads anew.
180
+ */
181
+ const bundles = new Map();
182
+ /** The pieces a UI bundle's `exportUIs` call registered, by piece key. */
183
+ function piecesFromExport(exported) {
184
+ const pieces = new Map();
185
+ for (const piece of exported?.pieces ?? []) {
186
+ if (piece?.kind !== "piece-implementation")
187
+ continue;
188
+ pieces.set((0, implement_piece_1.pieceKey)(piece.contractId, piece.version, piece.name), piece.component);
189
+ }
190
+ return pieces;
191
+ }
192
+ /**
193
+ * Record the pieces a screen's load of a UI bundle registered, so a piece of the same version
194
+ * doesn't run the bundle again. Called by the UI loader, which runs a package's bundle for the
195
+ * active group's screens.
196
+ *
197
+ * @param packageVersionId - The version whose bundle ran.
198
+ * @param uiBundleFileId - Its UI bundle's file.
199
+ * @param exported - What the bundle passed `exportUIs`.
200
+ */
201
+ function recordLoadedPieces(packageVersionId, uiBundleFileId, exported) {
202
+ const key = `${packageVersionId}:${uiBundleFileId}`;
203
+ // The same file already ran for pieces, which may be drawn now: keep their components.
204
+ if (bundles.get(key) instanceof Map)
205
+ return;
206
+ bundles.set(key, piecesFromExport(exported));
207
+ }
208
+ /**
209
+ * The pieces a package version's UI bundle registers, running the bundle once per version and
210
+ * file when no screen already did. The version's row is read in the piece's group, and in a group
211
+ * the bundle must match its hash. A bundle run for pieces registers no screens, so another
212
+ * version's pieces never replace what a screen shows.
213
+ *
214
+ * @param dataContextId - The group the piece is embedded for.
215
+ * @param packageId - The provider.
216
+ * @param packageVersionId - The version it runs there.
217
+ */
218
+ async function loadVersionPieces(dataContextId, packageId, packageVersionId) {
219
+ const dataContext = (await (0, peers_sdk_1.getUserContext)()).getDataContext(dataContextId);
220
+ const pv = await (0, peers_sdk_1.PackageVersions)(dataContext).get(packageVersionId);
221
+ if (!pv)
222
+ throw new Error(`Version ${packageVersionId} of ${packageId} isn't on this device`);
223
+ if (!pv.uiBundleFileId)
224
+ throw new Error(`Version ${pv.version} of ${packageId} has no UI bundle`);
225
+ const key = `${packageVersionId}:${pv.uiBundleFileId}`;
226
+ const known = bundles.get(key);
227
+ if (known)
228
+ return known;
229
+ const pieces = (async () => {
230
+ const stored = await (0, peers_sdk_1.Packages)(dataContext).get(packageId);
231
+ if (!stored)
232
+ throw new Error(`${packageId} isn't installed in this group`);
233
+ await (0, peers_sdk_1.assertPackageVersionRunnable)(stored, pv, dataContext);
234
+ const code = await (0, bundle_files_1.readBundleText)(dataContextId, pv.uiBundleFileId);
235
+ if (!code)
236
+ throw new Error(`Version ${pv.version} of ${packageId} has an empty UI bundle`);
237
+ if (dataContext.groupId)
238
+ (0, peers_sdk_1.assertPackageBundleIntegrity)(pv, "ui", code);
239
+ // A screen may have run this bundle while its file was being read.
240
+ const recorded = bundles.get(key);
241
+ if (recorded instanceof Map)
242
+ return recorded;
243
+ let exported;
244
+ const exportUIs = (value) => {
245
+ exported = value;
246
+ };
247
+ await new Function("exportUIs", code)(exportUIs);
248
+ return piecesFromExport(exported);
249
+ })();
250
+ bundles.set(key, pieces);
251
+ pieces.then((loaded) => {
252
+ if (bundles.get(key) === pieces)
253
+ bundles.set(key, loaded);
254
+ },
255
+ // A failed load is tried again next time, after a retry or a change.
256
+ () => {
257
+ if (bundles.get(key) === pieces)
258
+ bundles.delete(key);
259
+ });
260
+ return pieces;
261
+ }
262
+ /** Forget loaded bundles: for tests. */
263
+ function resetPieceBundles() {
264
+ bundles.clear();
265
+ catalogs.clear();
266
+ }
@@ -0,0 +1,55 @@
1
+ import { type IContractPiece } from "@peers-app/peers-sdk";
2
+ import type { IPieceHandle, IPieceUnavailable, PieceComponent } from "./types";
3
+ /** A piece that can show: where it comes from, and its declaration for the embedder's version. */
4
+ export interface IPieceAvailable {
5
+ /** The group it shows for. */
6
+ dataContextId: string;
7
+ /** The provider that draws it. */
8
+ providerPackageId: string;
9
+ /** The provider's version this device runs in that group. */
10
+ packageVersionId: string;
11
+ /** The UI contract version whose component draws it: the embedder's, or the one the provider implements. */
12
+ implementation: {
13
+ contractId: string;
14
+ version: number;
15
+ };
16
+ /** The piece as the embedder's version declares it: its kind, props, and emits. */
17
+ piece: IContractPiece;
18
+ }
19
+ /** Where a piece stands: found (and so available), or unavailable with a reason. */
20
+ export type PieceResolution = ({
21
+ status: "available";
22
+ } & IPieceAvailable) | ({
23
+ status: "unavailable";
24
+ dataContextId: string;
25
+ } & IPieceUnavailable);
26
+ /**
27
+ * Bumps when anything a resolution depends on may have changed: a package reload, a change to
28
+ * the Packages or PackageVersions rows of a group a piece was resolved for, or a package there
29
+ * starting, stopping, or changing version on this device.
30
+ */
31
+ export declare const pieceRevision: import("@peers-app/peers-sdk").Observable<number>;
32
+ /** @internal Register a stand-in for a piece; see `mockPiece`. */
33
+ export declare function setPieceMock(contractId: string, version: number, piece: IContractPiece, component: PieceComponent): () => void;
34
+ /** The group a handle's piece shows for: the one it names, else the active group. */
35
+ export declare function handleDataContextId(handle: IPieceHandle): Promise<string>;
36
+ /**
37
+ * Find who draws a piece in a group, without loading any UI code: the provider (the one the
38
+ * handle names, else the group's active one), the version this device runs, and the piece's
39
+ * declaration for the embedder's version. This is the one place a provider is chosen; the
40
+ * admin's default and users' overrides belong here.
41
+ *
42
+ * @param handle - The piece.
43
+ * @param dataContextId - The group, from {@link handleDataContextId}.
44
+ */
45
+ export declare function resolvePiece(handle: IPieceHandle, dataContextId: string): Promise<PieceResolution>;
46
+ /**
47
+ * The component that draws an available piece: from its provider's UI bundle (loaded once per
48
+ * version), under the UI contract version the provider implements.
49
+ *
50
+ * @param available - From {@link resolvePiece}.
51
+ * @param name - The piece's name.
52
+ */
53
+ export declare function loadPieceComponent(available: IPieceAvailable, name: string): Promise<PieceComponent>;
54
+ /** Forget every resolution and stand-in: for tests. */
55
+ export declare function resetPieceResolutions(): void;