@serfab/cadre-client 0.0.0-stage → 2.1.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.
Files changed (116) hide show
  1. package/ADOPTING.md +228 -0
  2. package/README.md +130 -3
  3. package/dist/address.d.ts +45 -0
  4. package/dist/address.js +109 -0
  5. package/dist/address.js.map +1 -0
  6. package/dist/app-link/index.d.ts +16 -0
  7. package/dist/app-link/index.js +17 -0
  8. package/dist/app-link/index.js.map +1 -0
  9. package/dist/app-link/join-response.d.ts +31 -0
  10. package/dist/app-link/join-response.js +87 -0
  11. package/dist/app-link/join-response.js.map +1 -0
  12. package/dist/app-link/known-apps.d.ts +32 -0
  13. package/dist/app-link/known-apps.js +51 -0
  14. package/dist/app-link/known-apps.js.map +1 -0
  15. package/dist/app-link/link-request-store.d.ts +50 -0
  16. package/dist/app-link/link-request-store.js +101 -0
  17. package/dist/app-link/link-request-store.js.map +1 -0
  18. package/dist/app-link/links.d.ts +47 -0
  19. package/dist/app-link/links.js +76 -0
  20. package/dist/app-link/links.js.map +1 -0
  21. package/dist/app-link/recommend-links.d.ts +30 -0
  22. package/dist/app-link/recommend-links.js +33 -0
  23. package/dist/app-link/recommend-links.js.map +1 -0
  24. package/dist/app-link/recommendation-store.d.ts +54 -0
  25. package/dist/app-link/recommendation-store.js +99 -0
  26. package/dist/app-link/recommendation-store.js.map +1 -0
  27. package/dist/bootstrap.d.ts +106 -0
  28. package/dist/bootstrap.js +106 -0
  29. package/dist/bootstrap.js.map +1 -0
  30. package/dist/inbox.d.ts +10 -0
  31. package/dist/inbox.js +28 -0
  32. package/dist/inbox.js.map +1 -0
  33. package/dist/index.d.ts +15 -0
  34. package/dist/index.js +16 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/invitation-text.d.ts +81 -0
  37. package/dist/invitation-text.js +80 -0
  38. package/dist/invitation-text.js.map +1 -0
  39. package/dist/lifecycle/background-runner.d.ts +94 -0
  40. package/dist/lifecycle/background-runner.js +278 -0
  41. package/dist/lifecycle/background-runner.js.map +1 -0
  42. package/dist/lifecycle/index.d.ts +9 -0
  43. package/dist/lifecycle/index.js +10 -0
  44. package/dist/lifecycle/index.js.map +1 -0
  45. package/dist/loader.d.ts +47 -0
  46. package/dist/loader.js +93 -0
  47. package/dist/loader.js.map +1 -0
  48. package/dist/model.d.ts +309 -0
  49. package/dist/model.js +22 -0
  50. package/dist/model.js.map +1 -0
  51. package/dist/node-code-text.d.ts +10 -0
  52. package/dist/node-code-text.js +30 -0
  53. package/dist/node-code-text.js.map +1 -0
  54. package/dist/result.d.ts +79 -0
  55. package/dist/result.js +84 -0
  56. package/dist/result.js.map +1 -0
  57. package/dist/sereus/client.d.ts +49 -0
  58. package/dist/sereus/client.js +420 -0
  59. package/dist/sereus/client.js.map +1 -0
  60. package/dist/sereus/edge-host.d.ts +22 -0
  61. package/dist/sereus/edge-host.js +61 -0
  62. package/dist/sereus/edge-host.js.map +1 -0
  63. package/dist/sereus/host.d.ts +57 -0
  64. package/dist/sereus/host.js +2 -0
  65. package/dist/sereus/host.js.map +1 -0
  66. package/dist/sereus/index.d.ts +8 -0
  67. package/dist/sereus/index.js +9 -0
  68. package/dist/sereus/index.js.map +1 -0
  69. package/dist/sereus/invitations.d.ts +16 -0
  70. package/dist/sereus/invitations.js +333 -0
  71. package/dist/sereus/invitations.js.map +1 -0
  72. package/dist/sereus/node-code.d.ts +52 -0
  73. package/dist/sereus/node-code.js +51 -0
  74. package/dist/sereus/node-code.js.map +1 -0
  75. package/dist/store.d.ts +27 -0
  76. package/dist/store.js +51 -0
  77. package/dist/store.js.map +1 -0
  78. package/dist/stores.d.ts +38 -0
  79. package/dist/stores.js +48 -0
  80. package/dist/stores.js.map +1 -0
  81. package/examples/README.md +20 -0
  82. package/examples/nativescript/cadrons-page.xml +24 -0
  83. package/examples/nativescript/cadrons-view-model.ts +68 -0
  84. package/examples/react-native/CadronList.tsx +204 -0
  85. package/examples/react-native/InvitationPanel.tsx +191 -0
  86. package/examples/react-native/useStore.ts +11 -0
  87. package/examples/svelte/CadronList.svelte +86 -0
  88. package/examples/svelte/InvitationPanel.svelte +97 -0
  89. package/package.json +65 -3
  90. package/src/address.ts +125 -0
  91. package/src/app-link/index.ts +45 -0
  92. package/src/app-link/join-response.ts +109 -0
  93. package/src/app-link/known-apps.ts +70 -0
  94. package/src/app-link/link-request-store.ts +129 -0
  95. package/src/app-link/links.ts +90 -0
  96. package/src/app-link/recommend-links.ts +49 -0
  97. package/src/app-link/recommendation-store.ts +132 -0
  98. package/src/bootstrap.ts +184 -0
  99. package/src/globals.d.ts +26 -0
  100. package/src/inbox.ts +36 -0
  101. package/src/index.ts +15 -0
  102. package/src/invitation-text.ts +156 -0
  103. package/src/lifecycle/background-runner.ts +363 -0
  104. package/src/lifecycle/index.ts +17 -0
  105. package/src/loader.ts +103 -0
  106. package/src/model.ts +327 -0
  107. package/src/node-code-text.ts +25 -0
  108. package/src/result.ts +131 -0
  109. package/src/sereus/client.ts +454 -0
  110. package/src/sereus/edge-host.ts +81 -0
  111. package/src/sereus/host.ts +56 -0
  112. package/src/sereus/index.ts +8 -0
  113. package/src/sereus/invitations.ts +359 -0
  114. package/src/sereus/node-code.ts +80 -0
  115. package/src/store.ts +61 -0
  116. package/src/stores.ts +62 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stores.js","sourceRoot":"","sources":["../src/stores.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,QAAQ,EAAiB,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAQlD;;;;;;;GAOG;AACH,MAAM,UAAU,UAAU,CAAC,IAAe,EAAE,OAAqB,EAAE;IAClE,OAAO,MAAM,CAAC;QACb,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;QAC/B,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;QACjD,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,MAAM;KAC7B,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAsB,EAAE,OAAqB,EAAE;IAChF,OAAO,MAAM,CAAC;QACb,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC;QACxD,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC;QACxD,UAAU,EAAE,GAAG;QACf,MAAM,EAAE,IAAI,CAAC,MAAM,IAAI,MAAM;KAC7B,CAAC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,wBAAwB,CAAC,IAAqB,EAAE,KAAa;IAC5E,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACrD,OAAO,QAAQ,CAAsB,IAAI,EAAE,EAAE,GAAG,CAAC,EAAE;QAClD,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QACZ,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,20 @@
1
+ # cadre-client examples
2
+
3
+ Screens to copy and adapt, one folder per UI framework. They are not built, tested or published;
4
+ each shows how to bind the client's stores and call its operations, with inline English strings
5
+ and plain styles an app replaces with its own.
6
+
7
+ | | React Native | Svelte 5 | NativeScript |
8
+ |---|---|---|---|
9
+ | The person's cadrons with a status dot, a name (else the host name) and what to match them by (host, short id) | [`CadronList.tsx`](react-native/CadronList.tsx) | [`CadronList.svelte`](svelte/CadronList.svelte) | [`cadrons-view-model.ts`](nativescript/cadrons-view-model.ts) + [`cadrons-page.xml`](nativescript/cadrons-page.xml) |
10
+ | Starring a cadron (preferred in invitations) | ✔ | ✔ | ✔ |
11
+ | Addresses per invitation | ✔ | ✔ | |
12
+ | Renaming, removal (with its plan), adding one by its code (named after its host) | ✔ | | |
13
+ | Beside a minted invitation: ready to hand out, the machines it names (each address a checkbox, the ones it could name unchecked), the QR code full screen | [`InvitationPanel.tsx`](react-native/InvitationPanel.tsx) | [`InvitationPanel.svelte`](svelte/InvitationPanel.svelte) | |
14
+ | Binding a store | [`useStore.ts`](react-native/useStore.ts) (`useSyncExternalStore`) | `$store` (the store contract) | `subscribe` into an `Observable` |
15
+
16
+ Each takes a `client`, `createCadreClient(...)` from `@serfab/cadre-client/sereus`. Wiring that
17
+ client into an app, and minting invitations through it, is in [ADOPTING.md](../ADOPTING.md).
18
+
19
+ Dependencies the examples assume, beyond the package: React Native and `react-native-qrcode-svg`;
20
+ Svelte 5 and `qrcode`; `@nativescript/core`.
@@ -0,0 +1,24 @@
1
+ <!--
2
+ Example (NativeScript): the page for cadrons-view-model.ts. In its code-behind:
3
+ navigatingTo: page.bindingContext = new CadronsViewModel(client)
4
+ navigatedFrom: (page.bindingContext as CadronsViewModel).dispose()
5
+ onStar: (page.bindingContext as CadronsViewModel).toggleStar(args.object.bindingContext.peerId)
6
+ -->
7
+ <Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" navigatedFrom="navigatedFrom">
8
+ <ActionBar title="My machines" />
9
+ <StackLayout>
10
+ <Label text="{{ message }}" visibility="{{ message ? 'visible' : 'collapsed' }}" />
11
+ <ListView items="{{ rows }}">
12
+ <ListView.itemTemplate>
13
+ <GridLayout columns="auto, *, auto" padding="8">
14
+ <Label col="0" width="8" height="8" borderRadius="4" backgroundColor="{{ dot }}" marginRight="10" />
15
+ <StackLayout col="1">
16
+ <Label text="{{ title }}" />
17
+ <Label text="{{ subtitle }}" fontSize="12" color="#666666" />
18
+ </StackLayout>
19
+ <Label col="2" text="{{ star }}" tap="onStar" visibility="{{ thisDevice ? 'collapsed' : 'visible' }}" />
20
+ </GridLayout>
21
+ </ListView.itemTemplate>
22
+ </ListView>
23
+ </StackLayout>
24
+ </Page>
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Example (NativeScript): a person's cadrons as a view model for `cadrons-page.xml`. Copy and
3
+ * adapt; it is not built or published. A cadre-client store is copied into an `Observable` from
4
+ * `subscribe`; unsubscribe when the page goes (`navigatedFrom`), so the store stops reading.
5
+ * `client` is `createCadreClient(...)` from `@serfab/cadre-client/sereus`.
6
+ */
7
+ import { Observable } from '@nativescript/core';
8
+ import { cadreStore, cadronPresence, shortPeerId, suggestedName, type CadreMachine, type CadronPresence } from '@serfab/cadre-client';
9
+ import type { CadreClient } from '@serfab/cadre-client/sereus';
10
+
11
+ const DOT: Record<CadronPresence, string> = { connected: '#2c8a3f', recent: '#c98a00', quiet: '#888888', unknown: '#dddddd' };
12
+ const PRESENCE: Record<CadronPresence, string> = {
13
+ connected: 'Connected', recent: 'Seen recently', quiet: 'Not seen lately', unknown: 'Not seen yet',
14
+ };
15
+
16
+ interface CadronRow {
17
+ peerId: string;
18
+ title: string;
19
+ subtitle: string;
20
+ dot: string;
21
+ star: string;
22
+ thisDevice: boolean;
23
+ }
24
+
25
+ function row(m: CadreMachine): CadronRow {
26
+ const presence = cadronPresence(m);
27
+ return {
28
+ peerId: m.peerId,
29
+ title: m.thisDevice ? 'This device' : m.name || suggestedName(m) || `Machine ${shortPeerId(m.peerId)}`,
30
+ subtitle: [
31
+ suggestedName(m), shortPeerId(m.peerId),
32
+ m.thisDevice ? null : m.trusted === false ? 'Not verified' : PRESENCE[presence],
33
+ m.alwaysOn ? 'Always on' : null,
34
+ ].filter(Boolean).join(' · '),
35
+ dot: DOT[presence],
36
+ star: m.preferred ? '★' : '☆',
37
+ thisDevice: m.thisDevice,
38
+ };
39
+ }
40
+
41
+ export class CadronsViewModel extends Observable {
42
+ rows: CadronRow[] = [];
43
+ message = 'Loading…';
44
+ private readonly unsubscribe: () => void;
45
+
46
+ constructor(private readonly client: CadreClient) {
47
+ super();
48
+ this.unsubscribe = cadreStore(client).subscribe(load => {
49
+ if (load.state === 'ready') {
50
+ this.set('rows', load.value.machines.map(row));
51
+ this.set('message', '');
52
+ } else {
53
+ this.set('message', load.state === 'failed' ? load.error.message : 'Loading…');
54
+ }
55
+ });
56
+ }
57
+
58
+ /** Bound to a row's star: name this cadron first in invitations, or stop. */
59
+ async toggleStar(peerId: string): Promise<void> {
60
+ const prefs = await this.client.invitations.preferences();
61
+ const preferred = prefs.preferred.includes(peerId) ? prefs.preferred.filter(id => id !== peerId) : [...prefs.preferred, peerId];
62
+ await this.client.invitations.setPreferences({ preferred });
63
+ }
64
+
65
+ dispose(): void {
66
+ this.unsubscribe();
67
+ }
68
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Example (React Native): a person's cadrons. Copy and adapt; it is not built or published.
3
+ *
4
+ * - Each cadron with a status dot (`cadronPresence`), the person's name for it (else its host name,
5
+ * `suggestedName`), the host and short id it can be matched by, a star to name it first in
6
+ * invitations, renaming, and removal.
7
+ * - Adding a cadron by its node code: read it, show which machine it is and which cadre it joins,
8
+ * claim only after the person approves (a code can arrive from anyone), and name it after its
9
+ * host.
10
+ * - How many addresses an invitation names.
11
+ *
12
+ * `client` is `createCadreClient(...)` from `@serfab/cadre-client/sereus`. Strings are inline
13
+ * English; an app maps each error `kind` to its own catalog instead of showing `message`.
14
+ */
15
+ import React, { useEffect, useMemo, useState } from 'react';
16
+ import { Alert, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
17
+ import {
18
+ cadreStore,
19
+ cadronPresence,
20
+ MAX_BOOTSTRAP_ADDRS,
21
+ shortPeerId,
22
+ suggestedName,
23
+ type CadreMachine,
24
+ type CadronPresence,
25
+ type CadronPreferences,
26
+ } from '@serfab/cadre-client';
27
+ import type { CadreClient } from '@serfab/cadre-client/sereus';
28
+ import { useStore } from './useStore';
29
+
30
+ const DOT: Record<CadronPresence, string> = { connected: '#2c8a3f', recent: '#c98a00', quiet: '#888888', unknown: '#dddddd' };
31
+ // "Seen recently", not "running": a cadron's record stays recent for up to 15 minutes after it stops.
32
+ const PRESENCE: Record<CadronPresence, string> = {
33
+ connected: 'Connected',
34
+ recent: 'Seen recently',
35
+ quiet: 'Not seen lately',
36
+ unknown: 'Not seen yet',
37
+ };
38
+
39
+ export function CadronList({ client }: { client: CadreClient }) {
40
+ // One store per client: create it once, not on every render.
41
+ const store = useMemo(() => cadreStore(client), [client]);
42
+ const load = useStore(store);
43
+ const prefs = usePreferences(client);
44
+
45
+ if (load.state === 'loading') return <Text>Loading…</Text>;
46
+ if (load.state === 'failed') return <Text onPress={() => store.reload()}>{load.error.message} — tap to retry</Text>;
47
+ const status = load.value;
48
+
49
+ const toggleStar = (m: CadreMachine) => {
50
+ if (!prefs) return;
51
+ const preferred = prefs.preferred.includes(m.peerId)
52
+ ? prefs.preferred.filter(id => id !== m.peerId)
53
+ : [...prefs.preferred, m.peerId];
54
+ void client.invitations.setPreferences({ preferred });
55
+ };
56
+ // Confirm with what the removal will do, then remove completely (record, invitations, closed-strand keys).
57
+ const remove = async (m: CadreMachine) => {
58
+ const plan = await client.cadre.planRemoval(m.peerId);
59
+ if (!plan.ok) { Alert.alert('Cannot check this removal', plan.error.message); return; }
60
+ if (plan.value.refusal) { Alert.alert('This machine cannot be removed here', plan.value.refusal === 'self' ? 'It is this device.' : 'This device holds no owner key.'); return; }
61
+ const also = [
62
+ plan.value.invitations ? `${plan.value.invitations} invitation(s) it could rejoin with are closed` : null,
63
+ plan.value.closedStrands.length ? `${plan.value.closedStrands.length} private conversation(s) get a new key it cannot read` : null,
64
+ ].filter(Boolean).join('; ');
65
+ Alert.alert('Remove this machine?', `It will no longer act for you.${also ? `\n\nAlso: ${also}.` : ''}`, [
66
+ { text: 'Cancel', style: 'cancel' },
67
+ {
68
+ text: 'Remove',
69
+ style: 'destructive',
70
+ onPress: async () => {
71
+ const done = await client.cadre.removeMachine(m.peerId);
72
+ if (!done.ok) Alert.alert('Could not remove the machine', done.error.message);
73
+ },
74
+ },
75
+ ]);
76
+ };
77
+
78
+ return (
79
+ <View style={styles.list}>
80
+ <Text style={styles.header}>{status.running ? 'Running' : 'Not running'} · {status.machines.length} machine(s)</Text>
81
+ {status.machines.map(m => {
82
+ const presence = cadronPresence(m);
83
+ const host = suggestedName(m);
84
+ return (
85
+ <View key={m.peerId} style={styles.row}>
86
+ <View style={[styles.dot, { backgroundColor: DOT[presence] }]} />
87
+ <View style={styles.grow}>
88
+ <Text style={styles.title}>{m.thisDevice ? 'This device' : m.name || host || `Machine ${shortPeerId(m.peerId)}`}</Text>
89
+ {/* What it can be matched by on its own host: its host name and short id. */}
90
+ <Text style={styles.subtitle}>{[host, shortPeerId(m.peerId)].filter(Boolean).join(' · ')}</Text>
91
+ {!m.thisDevice && (
92
+ <Text style={styles.subtitle}>
93
+ {[m.trusted === false ? 'Not verified' : PRESENCE[presence], m.alwaysOn ? 'Always on' : null, m.preferred ? 'Preferred' : null].filter(Boolean).join(' · ')}
94
+ </Text>
95
+ )}
96
+ </View>
97
+ {!m.thisDevice && <Rename client={client} machine={m} prefs={prefs} />}
98
+ {!m.thisDevice && <Pressable onPress={() => toggleStar(m)}><Text>{m.preferred ? '★' : '☆'}</Text></Pressable>}
99
+ {!m.thisDevice && <Pressable onPress={() => { void remove(m); }}><Text style={styles.danger}>Remove</Text></Pressable>}
100
+ </View>
101
+ );
102
+ })}
103
+ <AddCadron client={client} disabled={!status.ownerEnrolled} />
104
+ {prefs && <AddressCount client={client} prefs={prefs} />}
105
+ </View>
106
+ );
107
+ }
108
+
109
+ /** The cadron preferences, kept fresh: names and stars show in the list, the count below it. */
110
+ function usePreferences(client: CadreClient): CadronPreferences | null {
111
+ const [prefs, setPrefs] = useState<CadronPreferences | null>(null);
112
+ useEffect(() => {
113
+ const read = () => { void client.invitations.preferences().then(setPrefs); };
114
+ read();
115
+ return client.changes.invitations(read);
116
+ }, [client]);
117
+ return prefs;
118
+ }
119
+
120
+ /** Paste a node code, see what it says, approve, claim. A scanner would hand its text to `review` the same way. */
121
+ function AddCadron({ client, disabled }: { client: CadreClient; disabled: boolean }) {
122
+ const [code, setCode] = useState('');
123
+ const [busy, setBusy] = useState(false);
124
+ const review = async () => {
125
+ // Already in the network, or this device: the error says so (kind invalid-node-code).
126
+ const preview = await client.cadre.inspectNodeCode(code);
127
+ if (!preview.ok) { Alert.alert('That code cannot be used', preview.error.message); return; }
128
+ const p = preview.value;
129
+ const host = suggestedName(p);
130
+ const where = p.reach === 'home-network'
131
+ ? 'It can only be reached on its own network: be on the same Wi-Fi as it.'
132
+ : 'It can be reached from anywhere.';
133
+ // Which machine, and which cadre it joins: the network id and owner key match what the
134
+ // person's other devices (and the node's own host, once it joins) show.
135
+ const what = `${host ? `${host} (${shortPeerId(p.peerId)})` : `Machine ${shortPeerId(p.peerId)}`} will join your network`
136
+ + (p.partyId ? ` ${p.partyId}` : '') + (p.ownerFingerprint ? `, owned by your key ${p.ownerFingerprint}` : '') + '.';
137
+ Alert.alert('Add this machine?', `${what}\n\n${where}`, [
138
+ { text: 'Cancel', style: 'cancel' },
139
+ {
140
+ text: 'Add',
141
+ onPress: async () => {
142
+ setBusy(true);
143
+ const claimed = await client.cadre.claimNode(code); // can take up to two minutes
144
+ setBusy(false);
145
+ if (!claimed.ok) { Alert.alert('Could not add the machine', claimed.error.message); return; } // node-unreachable, claim-refused, claim-failed
146
+ setCode('');
147
+ // Named after its host straight away; the person can rename it in the list.
148
+ if (host) {
149
+ const prefs = await client.invitations.preferences();
150
+ void client.invitations.setPreferences({ names: { ...prefs.names, [p.peerId]: host } });
151
+ }
152
+ },
153
+ },
154
+ ]);
155
+ };
156
+ return (
157
+ <View style={styles.row}>
158
+ <TextInput style={[styles.input, styles.grow]} placeholder="sereus-join:…" value={code} onChangeText={setCode}
159
+ autoCapitalize="none" autoCorrect={false} editable={!busy && !disabled} />
160
+ <Pressable onPress={review} disabled={busy || disabled || !code.trim()}><Text>{busy ? 'Adding…' : 'Add'}</Text></Pressable>
161
+ </View>
162
+ );
163
+ }
164
+
165
+ /** Rename a cadron in place; an empty name clears it. Names are kept on this device. */
166
+ function Rename({ client, machine, prefs }: { client: CadreClient; machine: CadreMachine; prefs: CadronPreferences | null }) {
167
+ const [editing, setEditing] = useState(false);
168
+ const [text, setText] = useState('');
169
+ if (!prefs) return null;
170
+ if (!editing) {
171
+ return <Pressable onPress={() => { setText(machine.name ?? suggestedName(machine) ?? ''); setEditing(true); }}><Text>Rename</Text></Pressable>;
172
+ }
173
+ const save = () => {
174
+ const names = { ...prefs.names };
175
+ if (text.trim()) names[machine.peerId] = text.trim(); else delete names[machine.peerId];
176
+ void client.invitations.setPreferences({ names });
177
+ setEditing(false);
178
+ };
179
+ return <TextInput style={styles.input} value={text} onChangeText={setText} onSubmitEditing={save} onBlur={save} autoFocus />;
180
+ }
181
+
182
+ function AddressCount({ client, prefs }: { client: CadreClient; prefs: CadronPreferences }) {
183
+ const set = (maxAddrs: number) => { void client.invitations.setPreferences({ maxAddrs }); };
184
+ return (
185
+ <View style={styles.row}>
186
+ <Text style={styles.grow}>Addresses per invitation (fewer: a shorter link, a simpler QR code)</Text>
187
+ <Pressable onPress={() => set(prefs.maxAddrs - 1)} disabled={prefs.maxAddrs <= 1}><Text>−</Text></Pressable>
188
+ <Text>{prefs.maxAddrs}</Text>
189
+ <Pressable onPress={() => set(prefs.maxAddrs + 1)} disabled={prefs.maxAddrs >= MAX_BOOTSTRAP_ADDRS}><Text>+</Text></Pressable>
190
+ </View>
191
+ );
192
+ }
193
+
194
+ const styles = StyleSheet.create({
195
+ list: { gap: 8, padding: 16 },
196
+ header: { fontWeight: '600' },
197
+ row: { flexDirection: 'row', alignItems: 'center', gap: 10, paddingVertical: 6 },
198
+ dot: { width: 8, height: 8, borderRadius: 4 },
199
+ grow: { flex: 1 },
200
+ title: { fontSize: 15 },
201
+ subtitle: { fontSize: 12, color: '#666666' },
202
+ danger: { color: '#c4392f' },
203
+ input: { borderWidth: 1, borderColor: '#dddddd', borderRadius: 6, padding: 8 },
204
+ });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Example (React Native): beside an invitation the app has just minted. Copy and adapt; it is not
3
+ * built or published.
4
+ *
5
+ * - Whether it is ready to hand out: one of the machines the invitation names can answer a join
6
+ * through it while this phone sleeps (`invitationReadinessStore`), and what the machines are
7
+ * still missing while it cannot.
8
+ * - "What's in this invitation": the machines it names, as the cadre screen shows them, each
9
+ * address a checkbox. The other addresses it could name are unchecked; checking or unchecking
10
+ * one re-encodes this invitation (`invitations.rebootstrap`) and hands the app the new token.
11
+ * - The QR code, which a tap opens full screen (dark on white, the largest the screen allows).
12
+ *
13
+ * Props: `token` is what `node.encodeInvitation(...)` returned (after `invitations.withBootstrap`),
14
+ * `link` the text actually shared (the URL the QR code carries). `onRebootstrap`: the person changed
15
+ * its addresses; the app rebuilds its link and QR code from the new token, and keeps it with the
16
+ * invitation. A link already handed out still works, with the addresses it had.
17
+ */
18
+ import React, { useEffect, useMemo, useState } from 'react';
19
+ import { Modal, Pressable, StyleSheet, Text, useWindowDimensions, View } from 'react-native';
20
+ import QRCode from 'react-native-qrcode-svg';
21
+ import { invitationReadinessStore, type CadronPresence, type FormationReadinessGap, type InvitationReadiness, type InvitationText } from '@serfab/cadre-client';
22
+ import type { CadreClient } from '@serfab/cadre-client/sereus';
23
+ import { useStore } from './useStore';
24
+
25
+ interface Props {
26
+ client: CadreClient;
27
+ token: string;
28
+ link: string;
29
+ onRebootstrap(token: string): void;
30
+ }
31
+
32
+ const READINESS: Record<InvitationReadiness['state'], string> = {
33
+ ready: 'Ready to hand out: your machine can answer even while this phone sleeps.',
34
+ waiting: 'Not ready to hand out yet: no other machine of yours can let them in on its own.',
35
+ 'no-cadron': 'Only this phone can answer it: keep the app open until they join, or add a machine that stays on.',
36
+ spent: 'This invitation can no longer be used: it has expired, or it has been used up. Make a new one.',
37
+ };
38
+
39
+ // Each thing a machine can still be missing, as the step the person is waiting for. Showing these
40
+ // is the point of the record: "its own copy of the conversation" is progress, where a bare spinner
41
+ // is not. Phrased without a subject, because `missing` is the union over every machine the
42
+ // invitation names, not one machine's list.
43
+ const MISSING: Record<FormationReadinessGap, string> = {
44
+ 'invitation-record': 'being told about this invitation',
45
+ 'strand-record': 'being told about the conversation',
46
+ 'membership-key': 'a key for the conversation, to sign your guest in',
47
+ 'strand-runtime': 'running the conversation',
48
+ 'strand-database': 'its own copy of the conversation',
49
+ };
50
+
51
+ const KIND = {
52
+ public: 'public address', name: 'public name', relay: 'relayed', webrtc: 'relayed, then direct if possible',
53
+ private: 'home network only', loopback: 'this machine only',
54
+ } as const;
55
+ // As the cadre screen shows each cadron.
56
+ const DOT: Record<CadronPresence, string> = { connected: '#2c8a3f', recent: '#c98a00', quiet: '#888888', unknown: '#dddddd' };
57
+ const PRESENCE: Record<CadronPresence, string> = {
58
+ connected: 'connected now', recent: 'seen recently', quiet: 'not seen lately', unknown: 'not seen yet',
59
+ };
60
+
61
+ /** "in 7 days", "in 5 hours". */
62
+ function fromNow(iso: string): string {
63
+ const ms = new Date(iso).getTime() - Date.now();
64
+ if (ms <= 0) return 'expired';
65
+ const hours = Math.round(ms / 3_600_000);
66
+ return hours >= 48 ? `in ${Math.round(hours / 24)} days` : hours >= 1 ? `in ${hours} hours` : 'within the hour';
67
+ }
68
+
69
+ export function InvitationPanel({ client, token, link, onRebootstrap }: Props) {
70
+ const store = useMemo(() => invitationReadinessStore(client, token), [client, token]);
71
+ const readiness = useStore(store);
72
+ return (
73
+ <View style={styles.panel}>
74
+ <InvitationQr value={link} />
75
+ <Readiness readiness={readiness} />
76
+ <InvitationDetails client={client} token={token} link={link} onRebootstrap={onRebootstrap} />
77
+ </View>
78
+ );
79
+ }
80
+
81
+ /** Why it is not ready, when the machines said: a person waiting wants the reason, not a spinner. */
82
+ function waitingDetail(missing: InvitationReadiness['missing']): string {
83
+ return missing.length === 0
84
+ ? 'None of the machines it names has answered: one may be offline, or still starting.'
85
+ : `Still needed on the machines it names: ${missing.map(gap => MISSING[gap]).join('; ')}.`;
86
+ }
87
+
88
+ function Readiness({ readiness }: { readiness: InvitationReadiness }) {
89
+ const tone = readiness.state === 'ready' ? styles.ready : readiness.state === 'spent' ? styles.spent : styles.muted;
90
+ return (
91
+ <View>
92
+ <Text style={tone}>{READINESS[readiness.state]}</Text>
93
+ {readiness.state === 'waiting' && <Text style={styles.muted}>{waitingDetail(readiness.missing)}</Text>}
94
+ </View>
95
+ );
96
+ }
97
+
98
+ function InvitationDetails({ client, token, link, onRebootstrap }: Pick<Props, 'client' | 'token' | 'link' | 'onRebootstrap'>) {
99
+ const [open, setOpen] = useState(false);
100
+ const [text, setText] = useState<InvitationText | null>(null);
101
+ useEffect(() => {
102
+ if (!open) return;
103
+ let live = true;
104
+ void client.invitations.describe(token, link).then(r => { if (live && r.ok) setText(r.value); });
105
+ return () => { live = false; };
106
+ }, [open, client, token, link]);
107
+
108
+ // Check or uncheck one address: the same invitation, re-encoded with the new list.
109
+ const toggle = async (addr: string, include: boolean) => {
110
+ if (!text) return;
111
+ const now = text.addresses.map(a => a.addr);
112
+ const next = include ? [...now, addr] : now.filter(a => a !== addr);
113
+ if (next.length === 0) return; // it must name at least one
114
+ const r = await client.invitations.rebootstrap(token, next);
115
+ if (r.ok) onRebootstrap(r.value);
116
+ };
117
+
118
+ return (
119
+ <View>
120
+ <Pressable onPress={() => setOpen(o => !o)}><Text style={styles.link}>{open ? 'Hide the details' : "What's in this invitation"}</Text></Pressable>
121
+ {open && text && (
122
+ <View style={styles.details}>
123
+ {text.cadrons.map(c => (
124
+ <View key={c.peerId}>
125
+ <View style={styles.row}>
126
+ <View style={[styles.dot, { backgroundColor: c.presence ? DOT[c.presence] : 'transparent' }]} />
127
+ <Text style={styles.title}>{c.thisDevice ? 'This phone' : c.label}</Text>
128
+ </View>
129
+ <Text style={styles.muted}>
130
+ {[c.thisDevice ? null : c.yours === false ? 'Not one of your machines' : 'Your machine',
131
+ c.alwaysOn ? 'always on' : null, c.presence ? PRESENCE[c.presence] : null].filter(Boolean).join(' · ')}
132
+ </Text>
133
+ {c.addresses.map(a => (
134
+ <Pressable key={a.addr} style={styles.row} onPress={() => { void toggle(a.addr, !a.included); }}
135
+ accessibilityRole="checkbox" accessibilityState={{ checked: a.included }}>
136
+ <Text>{a.included ? '☑' : '☐'}</Text>
137
+ <Text style={a.reachesAnywhere ? undefined : styles.muted}>
138
+ {(a.kind ? KIND[a.kind] : 'not usable by a phone') + (a.via === 'wss' ? ', secure' : '') + ' · '
139
+ + (a.via === 'relay' ? `through relay ${a.host}` : `${a.host}, port ${a.port ?? '?'}`)}
140
+ </Text>
141
+ </Pressable>
142
+ ))}
143
+ </View>
144
+ ))}
145
+ <Text style={styles.muted}>
146
+ {`${text.addresses.length} address(es)` + (text.maxAddrs ? `; your setting names up to ${text.maxAddrs}` : '')
147
+ + (text.maxAddrs && text.addresses.length < text.maxAddrs && text.cadronAddrsLeftOut === 0
148
+ ? '. Your machines have no other address a phone can use.' : '.')}
149
+ </Text>
150
+ <Text style={styles.muted}>Expires {fromNow(text.expiresAt)} ({new Date(text.expiresAt).toLocaleString()})</Text>
151
+ <Text style={styles.muted}>
152
+ Link {text.linkLength} characters · {text.qrVersion ? `QR code size ${text.qrVersion}` : 'too long for one QR code'}
153
+ </Text>
154
+ </View>
155
+ )}
156
+ </View>
157
+ );
158
+ }
159
+
160
+ function InvitationQr({ value }: { value: string }) {
161
+ const { width, height } = useWindowDimensions();
162
+ const [full, setFull] = useState(false);
163
+ return (
164
+ <>
165
+ <Pressable onPress={() => setFull(true)} style={styles.center}>
166
+ <QRCode value={value} size={180} />
167
+ <Text style={styles.muted}>Tap the code to enlarge it</Text>
168
+ </Pressable>
169
+ <Modal visible={full} animationType="fade" onRequestClose={() => setFull(false)} supportedOrientations={['portrait', 'landscape']}>
170
+ <Pressable style={styles.full} onPress={() => setFull(false)}>
171
+ <QRCode value={value} size={Math.floor(Math.min(width, height) * 0.9)} backgroundColor="#ffffff" color="#000000" />
172
+ <Text style={styles.muted}>Close</Text>
173
+ </Pressable>
174
+ </Modal>
175
+ </>
176
+ );
177
+ }
178
+
179
+ const styles = StyleSheet.create({
180
+ panel: { gap: 10, padding: 16 },
181
+ center: { alignItems: 'center', gap: 6 },
182
+ full: { flex: 1, backgroundColor: '#ffffff', alignItems: 'center', justifyContent: 'center', gap: 16 },
183
+ details: { gap: 4 },
184
+ row: { flexDirection: 'row', alignItems: 'center', gap: 8 },
185
+ dot: { width: 8, height: 8, borderRadius: 4 },
186
+ title: { fontWeight: '600' },
187
+ ready: { color: '#2c8a3f' },
188
+ spent: { color: '#b3261e' },
189
+ muted: { color: '#777777' },
190
+ link: { color: '#0066cc' },
191
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Binding a cadre-client store in React (React Native or web): `useSyncExternalStore` over the
3
+ * store's `subscribe` and `get`. A store returns the same object until its value changes, so this
4
+ * re-renders only on a change.
5
+ */
6
+ import { useSyncExternalStore } from 'react';
7
+ import type { Readable } from '@serfab/cadre-client';
8
+
9
+ export function useStore<T>(store: Readable<T>): T {
10
+ return useSyncExternalStore(store.subscribe as (onChange: () => void) => () => void, store.get, store.get);
11
+ }
@@ -0,0 +1,86 @@
1
+ <!--
2
+ Example (Svelte 5): a person's cadrons, with a status dot each, a star to name it first in
3
+ invitations, and how many addresses an invitation names. Copy and adapt; it is not built or
4
+ published. A cadre-client store follows the Svelte store contract, so `$store` reads it.
5
+ `client` is `createCadreClient(...)` from `@serfab/cadre-client/sereus`.
6
+ -->
7
+ <script lang="ts">
8
+ import {
9
+ cadreStore,
10
+ cadronPresence,
11
+ MAX_BOOTSTRAP_ADDRS,
12
+ shortPeerId,
13
+ suggestedName,
14
+ type CadreMachine,
15
+ type CadronPresence,
16
+ type CadronPreferences,
17
+ } from '@serfab/cadre-client';
18
+ import type { CadreClient } from '@serfab/cadre-client/sereus';
19
+
20
+ const { client }: { client: CadreClient } = $props();
21
+
22
+ const machines = $derived(cadreStore(client));
23
+ let prefs = $state<CadronPreferences | null>(null);
24
+
25
+ $effect(() => {
26
+ const read = () => { void client.invitations.preferences().then(p => { prefs = p; }); };
27
+ read();
28
+ return client.changes.invitations(read);
29
+ });
30
+
31
+ const DOT: Record<CadronPresence, string> = { connected: '#2c8a3f', recent: '#c98a00', quiet: '#888888', unknown: '#dddddd' };
32
+ const PRESENCE: Record<CadronPresence, string> = {
33
+ connected: 'Connected', recent: 'Seen recently', quiet: 'Not seen lately', unknown: 'Not seen yet',
34
+ };
35
+
36
+ function toggleStar(m: CadreMachine) {
37
+ if (!prefs) return;
38
+ const preferred = prefs.preferred.includes(m.peerId)
39
+ ? prefs.preferred.filter(id => id !== m.peerId)
40
+ : [...prefs.preferred, m.peerId];
41
+ void client.invitations.setPreferences({ preferred });
42
+ }
43
+
44
+ function setCount(maxAddrs: number) {
45
+ void client.invitations.setPreferences({ maxAddrs });
46
+ }
47
+ </script>
48
+
49
+ {#if $machines.state === 'loading'}
50
+ <p>Loading…</p>
51
+ {:else if $machines.state === 'failed'}
52
+ <button onclick={() => machines.reload()}>{$machines.error.message} — retry</button>
53
+ {:else}
54
+ <ul>
55
+ {#each $machines.value.machines as m (m.peerId)}
56
+ {@const presence = cadronPresence(m)}
57
+ <li>
58
+ <span class="dot" style:background={DOT[presence]}></span>
59
+ <span class="grow">
60
+ {m.thisDevice ? 'This device' : m.name || suggestedName(m) || `Machine ${shortPeerId(m.peerId)}`}
61
+ <small>{[suggestedName(m), shortPeerId(m.peerId)].filter(Boolean).join(' · ')}</small>
62
+ {#if !m.thisDevice}<small>{m.trusted === false ? 'Not verified' : PRESENCE[presence]}{m.alwaysOn ? ' · Always on' : ''}</small>{/if}
63
+ </span>
64
+ {#if !m.thisDevice}
65
+ <button onclick={() => toggleStar(m)} aria-label="Preferred for invitations">{m.preferred ? '★' : '☆'}</button>
66
+ {/if}
67
+ </li>
68
+ {/each}
69
+ </ul>
70
+ {#if prefs}
71
+ <p>
72
+ Addresses per invitation:
73
+ <button onclick={() => setCount(prefs!.maxAddrs - 1)} disabled={prefs.maxAddrs <= 1}>−</button>
74
+ {prefs.maxAddrs}
75
+ <button onclick={() => setCount(prefs!.maxAddrs + 1)} disabled={prefs.maxAddrs >= MAX_BOOTSTRAP_ADDRS}>+</button>
76
+ </p>
77
+ {/if}
78
+ {/if}
79
+
80
+ <style>
81
+ ul { list-style: none; padding: 0; }
82
+ li { display: flex; align-items: center; gap: 0.6rem; padding: 0.3rem 0; }
83
+ .dot { width: 8px; height: 8px; border-radius: 50%; }
84
+ .grow { flex: 1; display: flex; flex-direction: column; }
85
+ small { color: #666; }
86
+ </style>