@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.1

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 (81) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +73 -2
  3. package/dist/index.js +97 -0
  4. package/package.json +53 -4
  5. package/template/Dockerfile +35 -0
  6. package/template/README.md +134 -0
  7. package/template/_dockerignore +6 -0
  8. package/template/_env.example +53 -0
  9. package/template/_github/workflows/ci.yml +23 -0
  10. package/template/_gitignore +8 -0
  11. package/template/_prettierrc +6 -0
  12. package/template/apps/api/API.md +49 -0
  13. package/template/apps/api/package.json +34 -0
  14. package/template/apps/api/src/auth.ts +55 -0
  15. package/template/apps/api/src/claims.ts +85 -0
  16. package/template/apps/api/src/cli.ts +42 -0
  17. package/template/apps/api/src/config.ts +66 -0
  18. package/template/apps/api/src/custody.ts +186 -0
  19. package/template/apps/api/src/dev-index.ts +71 -0
  20. package/template/apps/api/src/env.ts +14 -0
  21. package/template/apps/api/src/identifiers.ts +57 -0
  22. package/template/apps/api/src/index-client.ts +136 -0
  23. package/template/apps/api/src/main.ts +50 -0
  24. package/template/apps/api/src/parties.ts +68 -0
  25. package/template/apps/api/src/platform.ts +121 -0
  26. package/template/apps/api/src/profiles.ts +100 -0
  27. package/template/apps/api/src/reader.ts +96 -0
  28. package/template/apps/api/src/server.ts +420 -0
  29. package/template/apps/api/src/store.ts +249 -0
  30. package/template/apps/api/src/wallet.ts +346 -0
  31. package/template/apps/api/src/worker.ts +106 -0
  32. package/template/apps/api/src/writer.ts +351 -0
  33. package/template/apps/api/test/config.test.ts +15 -0
  34. package/template/apps/api/test/external-index.test.ts +31 -0
  35. package/template/apps/api/test/lifecycle.test.ts +136 -0
  36. package/template/apps/api/tsconfig.json +9 -0
  37. package/template/apps/api/vitest.config.ts +9 -0
  38. package/template/apps/web/components.json +21 -0
  39. package/template/apps/web/index.html +12 -0
  40. package/template/apps/web/package.json +33 -0
  41. package/template/apps/web/src/app.tsx +51 -0
  42. package/template/apps/web/src/components/bits.tsx +188 -0
  43. package/template/apps/web/src/components/layout.tsx +118 -0
  44. package/template/apps/web/src/components/passport-form.tsx +244 -0
  45. package/template/apps/web/src/components/read-passport.tsx +48 -0
  46. package/template/apps/web/src/components/reading.tsx +157 -0
  47. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  48. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  49. package/template/apps/web/src/components/ui/button.tsx +63 -0
  50. package/template/apps/web/src/components/ui/card.tsx +91 -0
  51. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  52. package/template/apps/web/src/components/ui/input.tsx +20 -0
  53. package/template/apps/web/src/components/ui/label.tsx +21 -0
  54. package/template/apps/web/src/components/ui/select.tsx +189 -0
  55. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  56. package/template/apps/web/src/components/ui/table.tsx +115 -0
  57. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  58. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  59. package/template/apps/web/src/index.css +81 -0
  60. package/template/apps/web/src/lib/api.ts +286 -0
  61. package/template/apps/web/src/lib/auth.ts +10 -0
  62. package/template/apps/web/src/lib/format.ts +64 -0
  63. package/template/apps/web/src/lib/session.tsx +92 -0
  64. package/template/apps/web/src/lib/use-load.ts +46 -0
  65. package/template/apps/web/src/main.tsx +18 -0
  66. package/template/apps/web/src/pages/accept.tsx +108 -0
  67. package/template/apps/web/src/pages/brand.tsx +94 -0
  68. package/template/apps/web/src/pages/brands.tsx +104 -0
  69. package/template/apps/web/src/pages/home.tsx +51 -0
  70. package/template/apps/web/src/pages/new-passport.tsx +114 -0
  71. package/template/apps/web/src/pages/operations.tsx +150 -0
  72. package/template/apps/web/src/pages/passport.tsx +568 -0
  73. package/template/apps/web/src/pages/public-passport.tsx +24 -0
  74. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  75. package/template/apps/web/src/pages/verify.tsx +30 -0
  76. package/template/apps/web/src/pages/wallet.tsx +141 -0
  77. package/template/apps/web/tsconfig.json +29 -0
  78. package/template/apps/web/vite.config.ts +15 -0
  79. package/template/deploy/compose.yml +26 -0
  80. package/template/package.json +42 -0
  81. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,286 @@
1
+ // The API client: one fetch wrapper that turns the API's { error, description }
2
+ // answer into an Error, and a typed helper for every route in apps/api/API.md.
3
+ // Reads are open; writes carry the session cookie, which a same-origin fetch
4
+ // sends by itself.
5
+
6
+ export class ApiError extends Error {
7
+ readonly code: string
8
+ readonly status: number
9
+
10
+ constructor(message: string, code: string, status: number) {
11
+ super(message)
12
+ this.name = 'ApiError'
13
+ this.code = code
14
+ this.status = status
15
+ }
16
+ }
17
+
18
+ export const isNotFound = (error: unknown): boolean => error instanceof ApiError && error.status === 404
19
+
20
+ async function request<T>(path: string, method: 'GET' | 'POST' = 'GET', body?: unknown): Promise<T> {
21
+ const init: RequestInit = { method, headers: { accept: 'application/json' } }
22
+ if (body !== undefined) {
23
+ init.headers = { ...init.headers, 'content-type': 'application/json' }
24
+ init.body = JSON.stringify(body)
25
+ }
26
+ const response = await fetch(path, init)
27
+ const text = await response.text()
28
+ let parsed: unknown
29
+ try {
30
+ parsed = text === '' ? undefined : JSON.parse(text)
31
+ } catch {
32
+ parsed = undefined
33
+ }
34
+ if (!response.ok) {
35
+ const failure = (parsed ?? {}) as { error?: string; description?: string }
36
+ throw new ApiError(failure.description ?? `the API answered HTTP ${response.status}`, failure.error ?? `http-${response.status}`, response.status)
37
+ }
38
+ if (parsed === undefined) throw new ApiError('the API answered with something that is not JSON', 'not-json', response.status)
39
+ return parsed as T
40
+ }
41
+
42
+ const get = <T>(path: string): Promise<T> => request<T>(path)
43
+ const post = <T>(path: string, body: unknown = {}): Promise<T> => request<T>(path, 'POST', body)
44
+
45
+ /** A passport reference for a URL: the identifier, URL-encoded once. */
46
+ export const passportRef = (passportId: string): string => encodeURIComponent(passportId)
47
+
48
+ // ------------------------------------------------------------------ shapes
49
+
50
+ export interface Health {
51
+ ok: boolean
52
+ network: 'main' | 'test'
53
+ index?: string
54
+ publisherKey: string
55
+ wallet: 'toolbox' | 'test'
56
+ livePublishing: boolean
57
+ identifiers: { host: string; prefix: string; demonstration: boolean }
58
+ signIn: boolean
59
+ devSession?: { name: string; brandIds: string[] }
60
+ }
61
+
62
+ export interface ProfileSummary {
63
+ id: string
64
+ title: string
65
+ description?: string
66
+ }
67
+
68
+ export interface CodeList {
69
+ closed: boolean
70
+ options: Array<{ value: string; label: string }>
71
+ }
72
+
73
+ export interface Constraints {
74
+ minimum?: number
75
+ maximum?: number
76
+ step?: number
77
+ pattern?: string
78
+ patternHint?: string
79
+ maxLength?: number
80
+ }
81
+
82
+ export interface ProfileField {
83
+ key: string
84
+ label: string
85
+ valueType: string
86
+ unit?: string
87
+ accessTier: string
88
+ obligation: 'required' | 'recommended' | 'optional'
89
+ codeList?: CodeList
90
+ constraints?: Constraints
91
+ note?: string
92
+ group?: string
93
+ /** Not sent by the API today; read when present. */
94
+ cardinality?: 'one' | 'many'
95
+ }
96
+
97
+ export interface Profile extends ProfileSummary {
98
+ fields: ProfileField[]
99
+ publicSchema: unknown
100
+ restrictedSchema: unknown
101
+ sample: Record<string, unknown>
102
+ }
103
+
104
+ export type CheckStatus = 'pass' | 'fail' | 'unknown' | 'not-applicable'
105
+
106
+ export interface Check {
107
+ name: string
108
+ label: string
109
+ status: CheckStatus
110
+ reasonCode?: string
111
+ }
112
+
113
+ export interface LineageEntry {
114
+ op: string
115
+ txid: string
116
+ timestamp: string
117
+ controllerKey: string
118
+ actorIdentityKey: string
119
+ payloadPublic: unknown
120
+ }
121
+
122
+ export interface Verification {
123
+ passportId: string
124
+ lineage: LineageEntry[]
125
+ checks: Check[]
126
+ report: { checkedAt?: string; limits?: string[]; [key: string]: unknown }
127
+ publisherKeys: string[]
128
+ }
129
+
130
+ export type Op = 'ISSUE' | 'UPDATE' | 'TRANSFER' | 'RETIRE'
131
+
132
+ export interface StateView {
133
+ op: Op
134
+ txid: string
135
+ timestamp: string
136
+ actor: string
137
+ index: string
138
+ refusal?: string
139
+ network: string
140
+ proven: boolean
141
+ proofPushed: boolean
142
+ blockHeight?: number
143
+ }
144
+
145
+ export interface JournalSummary {
146
+ states: number
147
+ proven: number
148
+ pending: number
149
+ status: string
150
+ }
151
+
152
+ export interface PassportView {
153
+ passportId: string
154
+ brandId: string
155
+ profile: string
156
+ status: 'active' | 'retired'
157
+ demonstration: boolean
158
+ holder: { party: string; controllerKey: string }
159
+ createdAt: string
160
+ payload: unknown
161
+ journal: JournalSummary
162
+ states: StateView[]
163
+ acceptanceRecords: unknown[]
164
+ }
165
+
166
+ export interface ClaimView {
167
+ id: string
168
+ passportId: string
169
+ issuer: string
170
+ issuedBy: string
171
+ claim: { eventType: string; timestamp: string; recordId?: string; [key: string]: unknown }
172
+ registry?: { url: string; status: number; accepted: boolean; attestationId?: string; detail?: string }
173
+ createdAt: string
174
+ /** The signature check, on the list route only; the record a POST returns has none, and was refused if it did not verify. */
175
+ verified?: string
176
+ }
177
+
178
+ export type OfferStatus = 'open' | 'accepted' | 'transferred' | 'declined' | 'withdrawn' | 'expired'
179
+
180
+ export interface OfferPreview {
181
+ requestId: string
182
+ passportId: string
183
+ terms: Record<string, unknown>
184
+ expiresAt: string
185
+ status: OfferStatus
186
+ }
187
+
188
+ export interface OfferView {
189
+ requestId: string
190
+ passportId: string
191
+ brandId: string
192
+ mechanism: 'claim-code' | 'named-recipient'
193
+ terms: Record<string, unknown>
194
+ createdAt: string
195
+ expiresAt: string
196
+ status: OfferStatus
197
+ transferTxid?: string
198
+ }
199
+
200
+ export interface AcceptResult {
201
+ offer: OfferView
202
+ record: unknown
203
+ transferTxid: string
204
+ }
205
+
206
+ export interface Brand {
207
+ id: string
208
+ name: string
209
+ identityKey: string
210
+ did: string
211
+ createdAt: string
212
+ }
213
+
214
+ export interface Me {
215
+ userId: string
216
+ email: string
217
+ name: string
218
+ brandIds: string[]
219
+ brands: Brand[]
220
+ }
221
+
222
+ export interface Duty {
223
+ passportId: string
224
+ txid: string
225
+ op: string
226
+ duty: 'announce' | 'prove' | 'push-proof'
227
+ since: string
228
+ }
229
+
230
+ export interface Operations {
231
+ duties: Duty[]
232
+ passports: Array<{ passportId: string; brandId: string; status: string; journal: JournalSummary }>
233
+ }
234
+
235
+ export interface WalletView {
236
+ kind: 'toolbox' | 'test'
237
+ network: string
238
+ identityKey: string
239
+ balance: number
240
+ livePublishing: boolean
241
+ }
242
+
243
+ export interface FundingAddress {
244
+ address: string
245
+ derivationPrefix: string
246
+ derivationSuffix: string
247
+ senderIdentityKey: string
248
+ }
249
+
250
+ export type EventType = 'Origin' | 'Transfer' | 'Transformation' | 'Disposition'
251
+ export const EVENT_TYPES: EventType[] = ['Origin', 'Transfer', 'Transformation', 'Disposition']
252
+
253
+ // ------------------------------------------------------------------ routes
254
+
255
+ export const api = {
256
+ health: () => get<Health>('/api/health'),
257
+ profiles: () => get<ProfileSummary[]>('/api/profiles'),
258
+ profile: (id: string) => get<Profile>(`/api/profiles/${encodeURIComponent(id)}`),
259
+ verify: (passportId: string) => get<Verification>(`/api/verify?passportId=${encodeURIComponent(passportId)}`),
260
+ passport: (passportId: string) => get<PassportView>(`/api/passports/${passportRef(passportId)}`),
261
+ passportClaims: (passportId: string) => get<ClaimView[]>(`/api/passports/${passportRef(passportId)}/claims`),
262
+ offer: (requestId: string) => get<OfferPreview>(`/api/offers/${encodeURIComponent(requestId)}`),
263
+ acceptOffer: (requestId: string, claimCode: string) => post<AcceptResult>(`/api/offers/${encodeURIComponent(requestId)}/accept`, { claimCode }),
264
+ declineOffer: (requestId: string, claimCode: string) => post<OfferView>(`/api/offers/${encodeURIComponent(requestId)}/decline`, { claimCode }),
265
+
266
+ me: () => get<Me>('/api/me'),
267
+ brands: () => get<Brand[]>('/api/brands'),
268
+ createBrand: (name: string) => post<Brand>('/api/brands', { name }),
269
+ brandPassports: (brandId: string) => get<PassportView[]>(`/api/brands/${encodeURIComponent(brandId)}/passports`),
270
+ issuePassport: (brandId: string, body: { profile: string; itemReference: string; serial: string; payload: Record<string, unknown>; ownerFields: Record<string, unknown> }) =>
271
+ post<PassportView>(`/api/brands/${encodeURIComponent(brandId)}/passports`, body),
272
+ updatePassport: (passportId: string, body: { payload: Record<string, unknown>; ownerFields: Record<string, unknown>; eventData?: Record<string, unknown>; claimCode?: string }) =>
273
+ post<PassportView>(`/api/passports/${passportRef(passportId)}/update`, body),
274
+ offerPassport: (passportId: string, body: { terms: { word: string; note?: string }; claimCode?: string }) =>
275
+ post<{ offer: OfferView; claimCode?: string }>(`/api/passports/${passportRef(passportId)}/offer`, body),
276
+ passportOffers: (passportId: string) => get<OfferView[]>(`/api/passports/${passportRef(passportId)}/offers`),
277
+ withdrawOffer: (requestId: string, claimCode?: string) => post<OfferView>(`/api/offers/${encodeURIComponent(requestId)}/withdraw`, claimCode == null ? {} : { claimCode }),
278
+ retirePassport: (passportId: string, body: { reason: string; claimCode?: string }) => post<PassportView>(`/api/passports/${passportRef(passportId)}/retire`, body),
279
+ addClaim: (passportId: string, body: { eventType: EventType; submit?: boolean }) => post<ClaimView>(`/api/passports/${passportRef(passportId)}/claims`, body),
280
+
281
+ operations: () => get<Operations>('/api/operations'),
282
+ runOperations: () => post<{ done: string[] }>('/api/operations/run'),
283
+ wallet: () => get<WalletView>('/api/wallet'),
284
+ fundingAddress: () => post<FundingAddress>('/api/wallet/funding-address'),
285
+ internalize: (txid: string, funding: FundingAddress) => post<{ satoshis: number }>('/api/wallet/internalize', { txid, funding }),
286
+ }
@@ -0,0 +1,10 @@
1
+ // The Better Auth client. The API mounts Better Auth under /api/auth on the
2
+ // same origin, so the session cookie travels with every API call by itself.
3
+ import { createAuthClient } from 'better-auth/react'
4
+ import { organizationClient } from 'better-auth/client/plugins'
5
+
6
+ export const authClient = createAuthClient({
7
+ baseURL: window.location.origin,
8
+ basePath: '/api/auth',
9
+ plugins: [organizationClient()],
10
+ })
@@ -0,0 +1,64 @@
1
+ // Small presentation helpers shared by the pages.
2
+
3
+ export const shortTxid = (txid: string): string => (txid.length <= 20 ? txid : `${txid.slice(0, 10)}...${txid.slice(-6)}`)
4
+
5
+ export const shortKey = (key: string): string => (key.length <= 16 ? key : `${key.slice(0, 8)}...${key.slice(-6)}`)
6
+
7
+ export function formatTime(iso: string | undefined): string {
8
+ if (iso == null || iso === '') return ''
9
+ const date = new Date(iso)
10
+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString()
11
+ }
12
+
13
+ /** `endOfLife` becomes `End of life`; `profile_version` becomes `Profile version`. */
14
+ export const humanise = (key: string): string =>
15
+ key
16
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
17
+ .replace(/[_-]+/g, ' ')
18
+ .toLowerCase()
19
+ .replace(/^./, (c) => c.toUpperCase())
20
+
21
+ /** The identifier's own path, `/01/<gtin>/21/<serial>`, which this app serves as the public page. */
22
+ export function publicPathOf(passportId: string): string | undefined {
23
+ try {
24
+ return new URL(passportId).pathname
25
+ } catch {
26
+ return undefined
27
+ }
28
+ }
29
+
30
+ /** The GTIN and serial an identifier names, when it is a GS1 Digital Link of the form this app serves. */
31
+ export function parseIdentifier(passportId: string): { gtin: string; serial: string } | undefined {
32
+ const match = publicPathOf(passportId)?.match(/^\/01\/(\d+)\/21\/([^/]+)$/)
33
+ if (match == null) return undefined
34
+ let serial = match[2]
35
+ try {
36
+ serial = decodeURIComponent(serial)
37
+ } catch {
38
+ // Left as written.
39
+ }
40
+ return { gtin: match[1], serial }
41
+ }
42
+
43
+ /** The route parameter back to an identifier: React Router decodes it once; a still-encoded value is decoded here. */
44
+ export function passportIdFromRef(ref: string): string {
45
+ if (ref.includes('://')) return ref
46
+ try {
47
+ return decodeURIComponent(ref)
48
+ } catch {
49
+ return ref
50
+ }
51
+ }
52
+
53
+ export const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
54
+
55
+ /** Payload keys that are stamps or the demonstration marker, not product data. */
56
+ export const STAMP_KEYS = new Set(['notice', 'profile', 'profile_version'])
57
+
58
+ export const holderLabel = (party: string): string => {
59
+ const [scope, id] = party.split(':', 2)
60
+ if (scope === 'brand') return `Brand ${id}`
61
+ if (scope === 'recipient') return `Recipient of offer ${id}`
62
+ if (scope === 'member') return `Member ${id}`
63
+ return party
64
+ }
@@ -0,0 +1,92 @@
1
+ // Who is looking: the API's health answer (sign-in on or off, the development
2
+ // session) and, when sign-in is on, the Better Auth session. Pages read both
3
+ // through two hooks and never call the auth client when sign-in is off.
4
+ import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
5
+ import { api, type Health } from './api'
6
+ import { authClient } from './auth'
7
+ import { toError } from './use-load'
8
+
9
+ interface HealthState {
10
+ health: Health | undefined
11
+ error: Error | undefined
12
+ loading: boolean
13
+ reload: () => void
14
+ }
15
+
16
+ const HealthContext = createContext<HealthState>({ health: undefined, error: undefined, loading: true, reload: () => {} })
17
+
18
+ export function HealthProvider({ children }: { children: ReactNode }) {
19
+ const [health, setHealth] = useState<Health>()
20
+ const [error, setError] = useState<Error>()
21
+ const [loading, setLoading] = useState(true)
22
+ const [tick, setTick] = useState(0)
23
+
24
+ useEffect(() => {
25
+ let cancelled = false
26
+ setLoading(true)
27
+ api.health().then(
28
+ (answer) => {
29
+ if (cancelled) return
30
+ setHealth(answer)
31
+ setError(undefined)
32
+ setLoading(false)
33
+ },
34
+ (cause: unknown) => {
35
+ if (cancelled) return
36
+ setError(toError(cause))
37
+ setLoading(false)
38
+ }
39
+ )
40
+ return () => {
41
+ cancelled = true
42
+ }
43
+ }, [tick])
44
+
45
+ return <HealthContext.Provider value={{ health, error, loading, reload: () => setTick((t) => t + 1) }}>{children}</HealthContext.Provider>
46
+ }
47
+
48
+ export const useHealth = (): HealthState => useContext(HealthContext)
49
+
50
+ export interface Account {
51
+ /** Someone may act for a brand: a signed-in user, or the development session. */
52
+ signedIn: boolean
53
+ pending: boolean
54
+ name?: string
55
+ email?: string
56
+ /** Sign-in is on: MongoDB is configured and Better Auth is mounted. */
57
+ canSignIn: boolean
58
+ devSession: boolean
59
+ signOut?: () => Promise<void>
60
+ }
61
+
62
+ const nobody: Account = { signedIn: false, pending: true, canSignIn: false, devSession: false }
63
+ const AccountContext = createContext<Account>(nobody)
64
+
65
+ export function AccountProvider({ children }: { children: ReactNode }) {
66
+ const { health, loading } = useHealth()
67
+ if (loading) return <AccountContext.Provider value={nobody}>{children}</AccountContext.Provider>
68
+ if (health?.signIn) return <AuthAccountProvider>{children}</AuthAccountProvider>
69
+ const dev = health?.devSession
70
+ const value: Account = { signedIn: dev != null, pending: false, name: dev?.name, canSignIn: false, devSession: dev != null }
71
+ return <AccountContext.Provider value={value}>{children}</AccountContext.Provider>
72
+ }
73
+
74
+ function AuthAccountProvider({ children }: { children: ReactNode }) {
75
+ const session = authClient.useSession()
76
+ const user = session.data?.user
77
+ const value: Account = {
78
+ signedIn: user != null,
79
+ pending: session.isPending,
80
+ name: user?.name,
81
+ email: user?.email,
82
+ canSignIn: true,
83
+ devSession: false,
84
+ signOut: async () => {
85
+ await authClient.signOut()
86
+ await session.refetch()
87
+ },
88
+ }
89
+ return <AccountContext.Provider value={value}>{children}</AccountContext.Provider>
90
+ }
91
+
92
+ export const useAccount = (): Account => useContext(AccountContext)
@@ -0,0 +1,46 @@
1
+ // One hook for "load this when these change": data, error, loading and a
2
+ // reload, with a stale answer from an earlier run never overwriting a newer one.
3
+ import { useCallback, useEffect, useState } from 'react'
4
+
5
+ export interface Loaded<T> {
6
+ data: T | undefined
7
+ error: Error | undefined
8
+ loading: boolean
9
+ reload: () => void
10
+ setData: (data: T) => void
11
+ }
12
+
13
+ export const toError = (cause: unknown): Error => (cause instanceof Error ? cause : new Error(String(cause)))
14
+
15
+ export function useLoad<T>(load: () => Promise<T>, deps: readonly unknown[]): Loaded<T> {
16
+ const [data, setData] = useState<T>()
17
+ const [error, setError] = useState<Error>()
18
+ const [loading, setLoading] = useState(true)
19
+ const [tick, setTick] = useState(0)
20
+
21
+ useEffect(() => {
22
+ let cancelled = false
23
+ setLoading(true)
24
+ setError(undefined)
25
+ load().then(
26
+ (result) => {
27
+ if (cancelled) return
28
+ setData(result)
29
+ setLoading(false)
30
+ },
31
+ (cause: unknown) => {
32
+ if (cancelled) return
33
+ setError(toError(cause))
34
+ setLoading(false)
35
+ }
36
+ )
37
+ return () => {
38
+ cancelled = true
39
+ }
40
+ // The caller names the inputs; the loader itself is recreated on every render.
41
+ // eslint-disable-next-line react-hooks/exhaustive-deps
42
+ }, [...deps, tick])
43
+
44
+ const reload = useCallback(() => setTick((t) => t + 1), [])
45
+ return { data, error, loading, reload, setData }
46
+ }
@@ -0,0 +1,18 @@
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import { BrowserRouter } from 'react-router'
4
+ import { App } from '@/app'
5
+ import { AccountProvider, HealthProvider } from '@/lib/session'
6
+ import './index.css'
7
+
8
+ createRoot(document.getElementById('root')!).render(
9
+ <StrictMode>
10
+ <BrowserRouter>
11
+ <HealthProvider>
12
+ <AccountProvider>
13
+ <App />
14
+ </AccountProvider>
15
+ </HealthProvider>
16
+ </BrowserRouter>
17
+ </StrictMode>
18
+ )
@@ -0,0 +1,108 @@
1
+ import { useState, type ReactNode } from 'react'
2
+ import { Link, useParams } from 'react-router'
3
+ import { Button } from '@/components/ui/button'
4
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
5
+ import { Input } from '@/components/ui/input'
6
+ import { CopyButton, DefinitionList, ErrorNotice, Field, Loading, Mono, PageTitle, ToneBadge, ValueView, statusTone } from '@/components/bits'
7
+ import { api, type AcceptResult, type OfferView } from '@/lib/api'
8
+ import { formatTime, humanise, publicPathOf } from '@/lib/format'
9
+ import { useLoad } from '@/lib/use-load'
10
+
11
+ export function Accept() {
12
+ const { requestId = '' } = useParams()
13
+ const offer = useLoad(() => api.offer(requestId), [requestId])
14
+ const [claimCode, setClaimCode] = useState('')
15
+ const [busy, setBusy] = useState<'accept' | 'decline'>()
16
+ const [error, setError] = useState<unknown>()
17
+ const [accepted, setAccepted] = useState<AcceptResult>()
18
+ const [declined, setDeclined] = useState<OfferView>()
19
+
20
+ if (offer.loading) return <Loading what="Loading the offer" />
21
+ if (offer.error != null || offer.data == null) return <ErrorNotice error={offer.error ?? new Error('no answer')} title="Could not load the offer" />
22
+ const preview = offer.data
23
+ const publicPath = publicPathOf(preview.passportId)
24
+ const open = preview.status === 'open' && accepted == null && declined == null
25
+ const { word, note, ...otherTerms } = preview.terms
26
+
27
+ async function act(kind: 'accept' | 'decline') {
28
+ setBusy(kind)
29
+ setError(undefined)
30
+ try {
31
+ if (kind === 'accept') setAccepted(await api.acceptOffer(requestId, claimCode.trim()))
32
+ else setDeclined(await api.declineOffer(requestId, claimCode.trim()))
33
+ offer.reload()
34
+ } catch (cause) {
35
+ setError(cause)
36
+ } finally {
37
+ setBusy(undefined)
38
+ }
39
+ }
40
+
41
+ return (
42
+ <div className="mx-auto max-w-xl space-y-8">
43
+ <PageTitle title="A passport is offered to you" description={<Mono>{preview.passportId}</Mono>} />
44
+ <DefinitionList
45
+ entries={[
46
+ ['Terms', <span key="w" className="font-medium">{String(word ?? '')}</span>],
47
+ ...(typeof note === 'string' && note !== '' ? [['Note', note] as [string, string]] : []),
48
+ ...Object.entries(otherTerms).map(([k, v]) => [humanise(k), <ValueView key={k} value={v} />] as [string, ReactNode]),
49
+ ['Expires', formatTime(preview.expiresAt)],
50
+ ['Status', <ToneBadge key="s" tone={statusTone(preview.status)}>{preview.status}</ToneBadge>],
51
+ ]}
52
+ />
53
+
54
+ {accepted != null ? (
55
+ <Card className="border-emerald-300 dark:border-emerald-800">
56
+ <CardHeader>
57
+ <CardTitle>Accepted</CardTitle>
58
+ <CardDescription>The transfer was written.</CardDescription>
59
+ </CardHeader>
60
+ <CardContent className="space-y-4">
61
+ <Field label="Transfer txid">
62
+ <span className="flex items-center gap-2">
63
+ <Mono>{accepted.transferTxid}</Mono>
64
+ <CopyButton text={accepted.transferTxid} label="Copy the txid" />
65
+ </span>
66
+ </Field>
67
+ <p className="text-sm">You now hold this passport. Keep your claim code: it is how you act on the passport from here, including handing it on or retiring it.</p>
68
+ {publicPath == null ? null : (
69
+ <Button asChild variant="outline">
70
+ <Link to={publicPath}>Open the passport page</Link>
71
+ </Button>
72
+ )}
73
+ </CardContent>
74
+ </Card>
75
+ ) : declined != null ? (
76
+ <Card>
77
+ <CardHeader>
78
+ <CardTitle>Declined</CardTitle>
79
+ <CardDescription>Nothing was written. The offer is closed.</CardDescription>
80
+ </CardHeader>
81
+ </Card>
82
+ ) : !open ? (
83
+ <p className="text-sm text-muted-foreground">This offer is {preview.status}; nothing can be done with it.</p>
84
+ ) : (
85
+ <Card>
86
+ <CardHeader>
87
+ <CardTitle>Your claim code</CardTitle>
88
+ <CardDescription>The code the current holder gave you. Accepting writes the transfer to you; declining writes nothing.</CardDescription>
89
+ </CardHeader>
90
+ <CardContent className="space-y-4">
91
+ <Field label="Claim code" htmlFor="claimCode" required>
92
+ <Input id="claimCode" value={claimCode} onChange={(e) => setClaimCode(e.target.value)} autoComplete="off" spellCheck={false} />
93
+ </Field>
94
+ {error == null ? null : <ErrorNotice error={error} title="Refused" />}
95
+ <div className="flex gap-2">
96
+ <Button onClick={() => act('accept')} disabled={busy != null || claimCode.trim() === ''}>
97
+ {busy === 'accept' ? 'Working' : 'Accept'}
98
+ </Button>
99
+ <Button variant="outline" onClick={() => act('decline')} disabled={busy != null || claimCode.trim() === ''}>
100
+ {busy === 'decline' ? 'Working' : 'Decline'}
101
+ </Button>
102
+ </div>
103
+ </CardContent>
104
+ </Card>
105
+ )}
106
+ </div>
107
+ )
108
+ }