@vdatacloud/cx-commons 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,9 +42,45 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
42
42
  ├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
43
43
  ├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
44
44
  ├── /components/* --> exports shared Astro UI components (Nav, Footer)
45
- └── /sdk/* --> exports optional browser/identity SDK helpers
45
+ ├── /sdk/* --> exports optional browser/identity SDK helpers
46
+ └── /schema/api-error.json --> the canonical API error JSON Schema
46
47
  ```
47
48
 
49
+ ### Canonical API errors (`sdk/api-error`, `sdk/api-error-notice`, `components/ApiErrorNotice`)
50
+
51
+ Every platform service answers a refusal with one envelope, defined in Go by
52
+ [`daml-escrow-commons/apierror`](https://github.com/vdatacloud/daml-escrow-commons/tree/main/apierror)
53
+ and mirrored here byte for byte:
54
+
55
+ ```json
56
+ {"error":"…","code":"LEDGER_SIGNATURE_REJECTED","status":422,"stage":"execute","hint":"…","requestId":"…",
57
+ "upstream":{"service":"canton","grpcCode":"INVALID_ARGUMENT","cause":"…","traceId":"…","node":"…"},
58
+ "details":{"expectedHash":"…full value…"}}
59
+ ```
60
+
61
+ - **Parse anything:** `parseApiError(status, body)` / `apiErrorFromResponse(res)` read the envelope, legacy `{"error"}` bodies or plain text.
62
+ - **Canonical JSON:** `canonicalApiError(e, 'full' | 'summary')` gives the same bytes as Go. `summary` drops `details` and `upstream.cause`.
63
+ - **Display and logs:** `formatApiError(e)` gives a one-line message, `logFields(e)` gives log pairs with short ids only, and `shortId` is the shared short form (`relaytest::1220ebb7…4288`).
64
+ - **Direct Canton calls:** `fromCantonError(status, body, stage)` classifies a JSON Ledger API refusal exactly as Go's `canton.FromLedgerError` does. `apiErrorFromUnknown(err, {stage, service})` normalizes whatever a wallet SDK or direct call throws.
65
+ - **UI:**
66
+ - `renderApiErrorNotice(e)` / `mountApiErrorNotice(el, e)` are framework-free DOM renderers. Text is set via `textContent` only, with `dark:` coverage and copy buttons.
67
+ - `<ApiErrorNotice error={e} level="summary" />` renders the same thing server-side.
68
+
69
+ ### Canton ids (`sdk/canton-id`, `sdk/canton-id-view`, `components/CantonId`)
70
+
71
+ There are three kinds of Canton id. Each has one parser and one short form, mirroring daml-escrow-commons `cantonid`:
72
+
73
+ | Kind | Format | Short form |
74
+ |---|---|---|
75
+ | fingerprint (a key) | `1220`+64 hex | `1220ebb7…4288` |
76
+ | party | `hint::fingerprint` | `relaytest::1220ebb7…4288`; the namespace is the controlling key for an external party, or the hosting participant's (shared) otherwise |
77
+ | hash | same as fingerprint | same as fingerprint |
78
+
79
+ - `parsePartyId`, `classifyCantonId`, `shortCantonId`, `isFingerprint` and `partyControlledBy` are the helpers. `api-error`'s `shortId` is `shortCantonId`.
80
+ - `renderCantonId(value, {label, copy})` / `<CantonId value={…} label="Joey Depositor" />` give one display everywhere: the short form or a label, the full value on hover, and a copy button that copies the full value. Prefer a T1 `label` over a raw party id in UX. The error notice shows every id this way.
81
+
82
+ `test/fixtures/api-error` and `test/fixtures/canton-id` hold copies of the Go goldens, from the commit in `SOURCE`. After changing the Go package, run `npm run sync:api-error-fixtures`; CI fails if the copies drift.
83
+
48
84
  ---
49
85
 
50
86
  ## 5. Quick Start & Integration Guide
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vdatacloud/cx-commons",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,7 +15,8 @@
15
15
  },
16
16
  "./styles/global.css": "./src/styles/global.css",
17
17
  "./components/*": "./src/components/*.astro",
18
- "./sdk/*": "./src/sdk/*.ts"
18
+ "./sdk/*": "./src/sdk/*.ts",
19
+ "./schema/api-error.json": "./src/schema/api-error.schema.json"
19
20
  },
20
21
  "files": [
21
22
  "index.ts",
@@ -27,7 +28,9 @@
27
28
  "access": "public"
28
29
  },
29
30
  "scripts": {
30
- "build": "tsc"
31
+ "build": "tsc",
32
+ "test": "vitest run",
33
+ "sync:api-error-fixtures": "scripts/sync-api-error-fixtures.sh"
31
34
  },
32
35
  "peerDependencies": {
33
36
  "@tailwindcss/typography": "^0.5.0",
@@ -37,7 +40,9 @@
37
40
  "devDependencies": {
38
41
  "@tailwindcss/typography": "^0.5.20",
39
42
  "astro": "^7.3.2",
40
- "typescript": "^5.7.0"
43
+ "happy-dom": "^20.14.5",
44
+ "typescript": "^5.7.0",
45
+ "vitest": "^5.0.3"
41
46
  },
42
47
  "overrides": {
43
48
  "nanoid": "3.3.18"
@@ -0,0 +1,28 @@
1
+ ---
2
+ // The platform-wide error notice for a canonical ApiError
3
+ // (daml-escrow-commons apierror / sdk/api-error). Server-renders a plain
4
+ // fallback line, then hydrates through sdk/api-error-notice's DOM renderer
5
+ // -- the same one client code uses for errors it catches itself, so both
6
+ // look identical. Pass the error a service returned (or fromCantonError's
7
+ // result); `level="summary"` hides details and the upstream cause.
8
+ import { canonicalApiError, formatApiError, type ApiError, type ApiErrorDetail } from '../sdk/api-error';
9
+
10
+ export interface Props {
11
+ error: ApiError;
12
+ level?: ApiErrorDetail;
13
+ class?: string;
14
+ }
15
+
16
+ const { error, level = 'full', class: className = '' } = Astro.props;
17
+ ---
18
+
19
+ <div data-api-error={canonicalApiError(error, level)} data-api-error-level={level} class={className}>
20
+ <p role="alert" class="rounded-2xl border border-status-disputed/30 bg-status-disputed/5 p-4 text-sm text-slate-800 dark:border-status-disputed/20 dark:bg-status-disputed/10 dark:text-slate-100">
21
+ {formatApiError(error)}
22
+ </p>
23
+ </div>
24
+
25
+ <script>
26
+ import { hydrateApiErrorNotices } from '../sdk/api-error-notice';
27
+ hydrateApiErrorNotices();
28
+ </script>
@@ -0,0 +1,32 @@
1
+ ---
2
+ // A Canton id (party, key fingerprint, hash) shown the one platform way:
3
+ // short form -- or `label`, e.g. the party's T1 display name, which UX
4
+ // should prefer over a raw party id -- with the full value on hover and a
5
+ // copy button. Server-renders the short form with the hover already in
6
+ // place (works without JS); hydrates through sdk/canton-id-view to add
7
+ // copy, the same renderer client code and the error notice use.
8
+ import { shortCantonId } from '../sdk/canton-id';
9
+ import { cantonIdTitle, CANTON_ID_CLASS, CANTON_ID_TEXT_CLASS, CANTON_ID_LABEL_CLASS } from '../sdk/canton-id-view';
10
+
11
+ export interface Props {
12
+ value: string;
13
+ label?: string;
14
+ copy?: boolean;
15
+ }
16
+
17
+ const { value, label, copy = true } = Astro.props;
18
+ ---
19
+
20
+ <span
21
+ class={CANTON_ID_CLASS}
22
+ data-canton-id={value}
23
+ data-canton-id-label={label}
24
+ data-canton-id-copy={copy ? 'true' : 'false'}
25
+ >
26
+ <span class={label ? CANTON_ID_LABEL_CLASS : CANTON_ID_TEXT_CLASS} title={cantonIdTitle(value, label)}>{label || shortCantonId(value)}</span>
27
+ </span>
28
+
29
+ <script>
30
+ import { hydrateCantonIds } from '../sdk/canton-id-view';
31
+ hydrateCantonIds();
32
+ </script>
@@ -0,0 +1,170 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://github.com/vdatacloud/daml-escrow-commons/apierror/schema/error.schema.json",
4
+ "title": "ApiError",
5
+ "description": "The platform's canonical API error envelope (daml-escrow-commons apierror; TypeScript mirror in @vdatacloud/cx-commons sdk/api-error). Canonical serialization: compact JSON, properties in the order listed, details keys sorted, absent properties omitted. At Summary detail level, details and upstream.cause are omitted.",
6
+ "type": "object",
7
+ "required": [
8
+ "error",
9
+ "code"
10
+ ],
11
+ "additionalProperties": false,
12
+ "properties": {
13
+ "error": {
14
+ "type": "string",
15
+ "minLength": 1,
16
+ "description": "Human-readable message; long identifiers shortened (ShortID)."
17
+ },
18
+ "code": {
19
+ "type": "string",
20
+ "pattern": "^[A-Z][A-Z0-9_]*$",
21
+ "description": "Stable machine-readable reason."
22
+ },
23
+ "status": {
24
+ "type": "integer",
25
+ "minimum": 100,
26
+ "maximum": 599,
27
+ "description": "HTTP status the error is sent with."
28
+ },
29
+ "stage": {
30
+ "type": "string",
31
+ "description": "The step of a multi-step flow that failed."
32
+ },
33
+ "hint": {
34
+ "type": "string",
35
+ "description": "What to check or do next; long identifiers shortened."
36
+ },
37
+ "requestId": {
38
+ "type": "string",
39
+ "pattern": "^[A-Za-z0-9._:-]{1,128}$"
40
+ },
41
+ "upstream": {
42
+ "$ref": "#/definitions/upstream"
43
+ },
44
+ "details": {
45
+ "type": "object",
46
+ "description": "Full-length values behind shortened identifiers; shape per code (see allOf)."
47
+ }
48
+ },
49
+ "allOf": [
50
+ {
51
+ "if": {
52
+ "properties": {
53
+ "code": {
54
+ "enum": [
55
+ "LEDGER_SIGNATURE_REJECTED",
56
+ "LEDGER_PERMISSION_DENIED",
57
+ "KEY_DOES_NOT_CONTROL_PARTY",
58
+ "INVALID_SIGNATURE"
59
+ ]
60
+ }
61
+ },
62
+ "required": [
63
+ "code"
64
+ ]
65
+ },
66
+ "then": {
67
+ "properties": {
68
+ "details": {
69
+ "$ref": "#/definitions/signingDetails"
70
+ }
71
+ }
72
+ }
73
+ }
74
+ ],
75
+ "definitions": {
76
+ "upstream": {
77
+ "type": "object",
78
+ "required": [
79
+ "service"
80
+ ],
81
+ "additionalProperties": false,
82
+ "properties": {
83
+ "service": {
84
+ "type": "string",
85
+ "minLength": 1,
86
+ "description": "Backing service: canton, identity, circle, ..."
87
+ },
88
+ "status": {
89
+ "type": "integer"
90
+ },
91
+ "code": {
92
+ "type": "string",
93
+ "description": "The service's own error id."
94
+ },
95
+ "grpcCode": {
96
+ "type": "string",
97
+ "pattern": "^[A-Z_0-9]+$"
98
+ },
99
+ "cause": {
100
+ "type": "string",
101
+ "maxLength": 603
102
+ },
103
+ "traceId": {
104
+ "type": "string"
105
+ },
106
+ "node": {
107
+ "type": "string",
108
+ "description": "The instance that answered, e.g. a Canton participant."
109
+ }
110
+ }
111
+ },
112
+ "signingDetails": {
113
+ "type": "object",
114
+ "additionalProperties": false,
115
+ "description": "Canton signing/authorization details (apierror/canton.SigningDetails).",
116
+ "properties": {
117
+ "actAs": {
118
+ "type": "array",
119
+ "items": {
120
+ "type": "string"
121
+ },
122
+ "description": "The refused command's actAs as the caller sent it (raw: may not be valid party ids)."
123
+ },
124
+ "expectedHash": {
125
+ "$ref": "#/definitions/hash"
126
+ },
127
+ "ledgerUser": {
128
+ "type": "string",
129
+ "description": "Ledger API user the request was submitted as."
130
+ },
131
+ "party": {
132
+ "$ref": "#/definitions/partyId"
133
+ },
134
+ "partyFingerprint": {
135
+ "$ref": "#/definitions/fingerprint"
136
+ },
137
+ "publicKeyFingerprint": {
138
+ "$ref": "#/definitions/fingerprint"
139
+ },
140
+ "signatureReceived": {
141
+ "type": "string",
142
+ "pattern": "^[0-9a-f]*$",
143
+ "description": "The signature as received (lowercase hex)."
144
+ },
145
+ "signedBy": {
146
+ "$ref": "#/definitions/fingerprint"
147
+ },
148
+ "signedMessage": {
149
+ "type": "string",
150
+ "description": "What the signature had to cover (nonce, or a base64 multi-hash)."
151
+ }
152
+ }
153
+ },
154
+ "fingerprint": {
155
+ "type": "string",
156
+ "pattern": "^1220[0-9a-f]{64}$",
157
+ "description": "A Canton key fingerprint (cantonid.Fingerprint): 1220 + 64 lowercase hex."
158
+ },
159
+ "hash": {
160
+ "type": "string",
161
+ "pattern": "^1220[0-9a-f]{64}$",
162
+ "description": "A Canton transaction/topology hash (cantonid.Hash)."
163
+ },
164
+ "partyId": {
165
+ "type": "string",
166
+ "pattern": "^[A-Za-z0-9_\\- :]{1,185}::1220[0-9a-f]{64}$",
167
+ "description": "A Canton party id (cantonid.PartyID): hint::fingerprint, full length."
168
+ }
169
+ }
170
+ }
@@ -0,0 +1,170 @@
1
+ // One rendering of an ApiError for every app (PLAN: platform-wide error
2
+ // UX). Framework-free DOM, so it serves both client-side errors (a failed
3
+ // fetch, a wallet or direct-Canton refusal) and server-rendered ones
4
+ // (ApiErrorNotice.astro hydrates through it). Every value is set with
5
+ // textContent -- error text can never inject markup.
6
+
7
+ import { canonicalApiError, atDetail, type ApiError, type ApiErrorDetail } from './api-error';
8
+ import { renderCantonId } from './canton-id-view';
9
+
10
+ export interface ApiErrorNoticeOptions {
11
+ /** 'full' (default) shows details in a collapsed section; 'summary' omits them. */
12
+ level?: ApiErrorDetail;
13
+ /** Adds a dismiss button that calls this. */
14
+ onDismiss?: () => void;
15
+ }
16
+
17
+ // Retryable/transient failures render in the warning tone, the rest in the
18
+ // error tone. Class strings are spelled out in full for Tailwind's scanner.
19
+ const TRANSIENT = new Set(['RATE_LIMITED', 'UNAVAILABLE', 'TIMEOUT', 'LEDGER_UNAVAILABLE', 'LEDGER_CONFLICT', 'CONFLICT']);
20
+ const TONE = {
21
+ error: {
22
+ box: 'border-status-disputed/30 bg-status-disputed/5 dark:border-status-disputed/20 dark:bg-status-disputed/10',
23
+ dot: 'bg-status-disputed',
24
+ chip: 'text-status-disputed bg-status-disputed/10 border-status-disputed/20 dark:bg-status-disputed/5 dark:border-status-disputed/10',
25
+ },
26
+ warning: {
27
+ box: 'border-status-proposed/30 bg-status-proposed/5 dark:border-status-proposed/20 dark:bg-status-proposed/10',
28
+ dot: 'bg-status-proposed',
29
+ chip: 'text-status-proposed bg-status-proposed/10 border-status-proposed/20 dark:bg-status-proposed/5 dark:border-status-proposed/10',
30
+ },
31
+ };
32
+ const CHIP_BASE = 'inline-flex items-center rounded-full border px-2 py-0.5 font-mono text-[10px] font-black tracking-widest uppercase';
33
+ const NEUTRAL_CHIP = 'text-slate-600 bg-slate-100 border-slate-200 dark:text-slate-300 dark:bg-slate-800 dark:border-slate-700';
34
+ const MONO = 'font-mono text-xs break-all text-slate-700 dark:text-slate-200';
35
+ const LABEL = 'text-[10px] font-bold uppercase tracking-widest text-slate-500 dark:text-slate-400';
36
+ const BUTTON = 'rounded-md border border-slate-200 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
37
+
38
+ function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?: string): HTMLElementTagNameMap[K] {
39
+ const n = document.createElement(tag);
40
+ if (className) n.className = className;
41
+ if (text !== undefined) n.textContent = text;
42
+ return n;
43
+ }
44
+
45
+ function copyButton(label: string, value: () => string): HTMLButtonElement {
46
+ const b = el('button', BUTTON, label);
47
+ b.type = 'button';
48
+ b.addEventListener('click', async () => {
49
+ try {
50
+ await navigator.clipboard.writeText(value());
51
+ b.textContent = 'Copied';
52
+ } catch {
53
+ b.textContent = 'Copy failed';
54
+ }
55
+ setTimeout(() => (b.textContent = label), 1500);
56
+ });
57
+ return b;
58
+ }
59
+
60
+ // row is a labeled value: ids through the shared CantonId display (short,
61
+ // full on hover, copy); plain values as-is with a copy button.
62
+ function row(label: string, value: string, asId = true): HTMLElement {
63
+ const r = el('div', 'flex flex-wrap items-center gap-2');
64
+ r.append(el('dt', LABEL, label));
65
+ const dd = el('dd', 'min-w-0');
66
+ if (asId) {
67
+ dd.append(renderCantonId(value));
68
+ } else {
69
+ dd.append(el('span', MONO, value), document.createTextNode(' '), copyButton('Copy', () => value));
70
+ }
71
+ r.append(dd);
72
+ return r;
73
+ }
74
+
75
+ function detailValue(v: unknown): string {
76
+ if (typeof v === 'string') return v;
77
+ if (Array.isArray(v)) return v.map(detailValue).join(', ');
78
+ return JSON.stringify(v);
79
+ }
80
+
81
+ /** Renders e as a notice element (not attached). */
82
+ export function renderApiErrorNotice(e: ApiError, opts: ApiErrorNoticeOptions = {}): HTMLElement {
83
+ const level = opts.level ?? 'full';
84
+ const shown = atDetail(e, level);
85
+ const tone = TRANSIENT.has(e.code) ? TONE.warning : TONE.error;
86
+
87
+ const root = el('div', `rounded-2xl border p-4 text-sm text-slate-800 dark:text-slate-100 ${tone.box}`);
88
+ root.setAttribute('role', 'alert');
89
+ root.dataset.apiErrorCode = e.code;
90
+
91
+ const layout = el('div', 'flex items-start gap-3');
92
+ layout.append(el('span', `mt-1.5 inline-flex h-2 w-2 shrink-0 rounded-full ${tone.dot}`));
93
+ const body = el('div', 'min-w-0 flex-1 space-y-2');
94
+ layout.append(body);
95
+ root.append(layout);
96
+
97
+ const head = el('div', 'flex items-start justify-between gap-2');
98
+ head.append(el('p', 'font-semibold', e.error));
99
+ if (opts.onDismiss) {
100
+ const close = el('button', BUTTON, 'Dismiss');
101
+ close.type = 'button';
102
+ close.addEventListener('click', () => opts.onDismiss?.());
103
+ head.append(close);
104
+ }
105
+ body.append(head);
106
+
107
+ const chips = el('div', 'flex flex-wrap gap-1.5');
108
+ chips.append(el('span', `${CHIP_BASE} ${tone.chip}`, e.code));
109
+ if (e.stage) chips.append(el('span', `${CHIP_BASE} ${NEUTRAL_CHIP}`, e.stage));
110
+ if (e.upstream && (e.upstream.grpcCode || e.upstream.code)) {
111
+ chips.append(el('span', `${CHIP_BASE} ${NEUTRAL_CHIP}`, `${e.upstream.service} ${e.upstream.grpcCode || e.upstream.code}`));
112
+ }
113
+ body.append(chips);
114
+
115
+ if (e.hint) body.append(el('p', 'text-slate-600 dark:text-slate-300', e.hint));
116
+
117
+ const meta = el('dl', 'space-y-1');
118
+ if (e.requestId) meta.append(row('Request', e.requestId));
119
+ if (e.upstream?.traceId) meta.append(row('Trace', e.upstream.traceId));
120
+ if (e.upstream?.node) meta.append(row('Node', e.upstream.node, false));
121
+ if (meta.childElementCount) body.append(meta);
122
+
123
+ const hasDetails = shown.details && Object.keys(shown.details).length > 0;
124
+ if (hasDetails || shown.upstream?.cause) {
125
+ const det = el('details', 'rounded-lg border border-slate-200 p-2 dark:border-slate-700');
126
+ det.append(el('summary', `${LABEL} cursor-pointer select-none`, 'Details'));
127
+ const dl = el('dl', 'mt-2 space-y-1');
128
+ if (shown.upstream?.cause) dl.append(row(`${shown.upstream.service} cause`, shown.upstream.cause, false));
129
+ for (const k of Object.keys(shown.details ?? {}).sort()) {
130
+ const v = shown.details![k];
131
+ if (Array.isArray(v) && v.every((x) => typeof x === 'string')) {
132
+ v.forEach((x, i) => dl.append(row(v.length > 1 ? `${k}[${i}]` : k, x)));
133
+ } else {
134
+ dl.append(row(k, detailValue(v), typeof v === 'string'));
135
+ }
136
+ }
137
+ det.append(dl);
138
+ body.append(det);
139
+ }
140
+
141
+ const actions = el('div', 'flex gap-2');
142
+ actions.append(copyButton('Copy error JSON', () => canonicalApiError(e, level)));
143
+ body.append(actions);
144
+ return root;
145
+ }
146
+
147
+ /** Replaces container's content with a notice for e. */
148
+ export function mountApiErrorNotice(container: HTMLElement, e: ApiError, opts: ApiErrorNoticeOptions = {}): HTMLElement {
149
+ const notice = renderApiErrorNotice(e, opts);
150
+ container.replaceChildren(notice);
151
+ return notice;
152
+ }
153
+
154
+ /**
155
+ * Renders every [data-api-error] element under root (ApiErrorNotice.astro's
156
+ * server output): its attribute holds the canonical JSON, and
157
+ * data-api-error-level the detail level. Already-rendered ones are skipped.
158
+ */
159
+ export function hydrateApiErrorNotices(root: ParentNode = document): void {
160
+ root.querySelectorAll<HTMLElement>('[data-api-error]:not([data-api-error-rendered])').forEach((host) => {
161
+ try {
162
+ const e = JSON.parse(host.dataset.apiError ?? '') as ApiError;
163
+ const level = host.dataset.apiErrorLevel === 'summary' ? 'summary' : 'full';
164
+ mountApiErrorNotice(host, e, { level });
165
+ host.dataset.apiErrorRendered = '';
166
+ } catch {
167
+ // leave the server-rendered fallback text in place
168
+ }
169
+ });
170
+ }
@@ -0,0 +1,453 @@
1
+ // The platform's canonical API error -- the TypeScript mirror of
2
+ // daml-escrow-commons `apierror` (Go). Same envelope, same canonical JSON
3
+ // bytes, same Canton classification: test/fixtures/api-error holds copies
4
+ // of the Go package's golden fixtures, and this module is tested against
5
+ // them (scripts/sync-api-error-fixtures.sh re-syncs them).
6
+ //
7
+ // {"error":"human message","code":"LEDGER_SIGNATURE_REJECTED","status":422,
8
+ // "stage":"execute","hint":"what to do next","requestId":"…",
9
+ // "upstream":{"service":"canton","status":400,"code":"…","grpcCode":"…","cause":"…","traceId":"…","node":"…"},
10
+ // "details":{…full values…}}
11
+ //
12
+ // Long ids are shortened (shortId) in error, hint and logs; full values
13
+ // live in details. Two detail levels: 'full', and 'summary' (no details,
14
+ // no upstream cause). Use fromCantonError when the UI talks to a Canton
15
+ // participant or wallet gateway directly, so those refusals look exactly
16
+ // like ones relayed through a platform service.
17
+
18
+ import { shortCantonId, isFingerprint } from './canton-id';
19
+
20
+ export type ApiErrorDetail = 'full' | 'summary';
21
+
22
+ export interface ApiErrorUpstream {
23
+ service: string;
24
+ status?: number;
25
+ code?: string;
26
+ grpcCode?: string;
27
+ cause?: string;
28
+ traceId?: string;
29
+ node?: string;
30
+ }
31
+
32
+ export interface ApiError {
33
+ /** Human-readable message. */
34
+ error: string;
35
+ /** Stable machine-readable reason, UPPER_SNAKE_CASE. */
36
+ code: string;
37
+ status?: number;
38
+ stage?: string;
39
+ hint?: string;
40
+ requestId?: string;
41
+ upstream?: ApiErrorUpstream;
42
+ /** Full values behind shortened ids; shape per code (e.g. SigningDetails). */
43
+ details?: Record<string, unknown>;
44
+ }
45
+
46
+ /** Canton signing/authorization details (apierror/canton.SigningDetails). */
47
+ export interface SigningDetails {
48
+ party?: string;
49
+ partyFingerprint?: string;
50
+ publicKeyFingerprint?: string;
51
+ signatureReceived?: string;
52
+ signedBy?: string;
53
+ signedMessage?: string;
54
+ expectedHash?: string;
55
+ actAs?: string[];
56
+ ledgerUser?: string;
57
+ }
58
+
59
+ export const MAX_CAUSE = 600;
60
+
61
+ export const ApiErrorCodes = {
62
+ INVALID_REQUEST: 'INVALID_REQUEST',
63
+ UNAUTHENTICATED: 'UNAUTHENTICATED',
64
+ FORBIDDEN: 'FORBIDDEN',
65
+ NOT_FOUND: 'NOT_FOUND',
66
+ CONFLICT: 'CONFLICT',
67
+ UNPROCESSABLE: 'UNPROCESSABLE',
68
+ RATE_LIMITED: 'RATE_LIMITED',
69
+ INTERNAL: 'INTERNAL',
70
+ NOT_IMPLEMENTED: 'NOT_IMPLEMENTED',
71
+ UPSTREAM_ERROR: 'UPSTREAM_ERROR',
72
+ UNAVAILABLE: 'UNAVAILABLE',
73
+ TIMEOUT: 'TIMEOUT',
74
+ } as const;
75
+
76
+ export const CantonCodes = {
77
+ LEDGER_PERMISSION_DENIED: 'LEDGER_PERMISSION_DENIED',
78
+ LEDGER_UNAUTHENTICATED: 'LEDGER_UNAUTHENTICATED',
79
+ LEDGER_SIGNATURE_REJECTED: 'LEDGER_SIGNATURE_REJECTED',
80
+ LEDGER_INVALID_ARGUMENT: 'LEDGER_INVALID_ARGUMENT',
81
+ LEDGER_NOT_FOUND: 'LEDGER_NOT_FOUND',
82
+ LEDGER_CONFLICT: 'LEDGER_CONFLICT',
83
+ LEDGER_REJECTED: 'LEDGER_REJECTED',
84
+ LEDGER_UNAVAILABLE: 'LEDGER_UNAVAILABLE',
85
+ LEDGER_UNREACHABLE: 'LEDGER_UNREACHABLE',
86
+ KEY_DOES_NOT_CONTROL_PARTY: 'KEY_DOES_NOT_CONTROL_PARTY',
87
+ INVALID_SIGNATURE: 'INVALID_SIGNATURE',
88
+ INVALID_PUBLIC_KEY: 'INVALID_PUBLIC_KEY',
89
+ } as const;
90
+
91
+ /** The generic code for an HTTP status (Go: CodeForStatus). */
92
+ export function codeForStatus(status: number): string {
93
+ switch (status) {
94
+ case 400: return ApiErrorCodes.INVALID_REQUEST;
95
+ case 401: return ApiErrorCodes.UNAUTHENTICATED;
96
+ case 403: return ApiErrorCodes.FORBIDDEN;
97
+ case 404: return ApiErrorCodes.NOT_FOUND;
98
+ case 409: return ApiErrorCodes.CONFLICT;
99
+ case 422: return ApiErrorCodes.UNPROCESSABLE;
100
+ case 429: return ApiErrorCodes.RATE_LIMITED;
101
+ case 501: return ApiErrorCodes.NOT_IMPLEMENTED;
102
+ case 502: return ApiErrorCodes.UPSTREAM_ERROR;
103
+ case 503: return ApiErrorCodes.UNAVAILABLE;
104
+ case 504: return ApiErrorCodes.TIMEOUT;
105
+ }
106
+ return status >= 400 && status < 500 ? ApiErrorCodes.INVALID_REQUEST : ApiErrorCodes.INTERNAL;
107
+ }
108
+
109
+ export function isValidCode(code: string): boolean {
110
+ return /^[A-Z][A-Z0-9_]*$/.test(code);
111
+ }
112
+
113
+ // ---- short ids ------------------------------------------------------------
114
+
115
+ /**
116
+ * The one short form for long ids in messages, hints and logs
117
+ * (sdk/canton-id shortCantonId; Go: apierror.ShortID / cantonid.Short).
118
+ */
119
+ export function shortId(s: string): string {
120
+ return shortCantonId(s);
121
+ }
122
+
123
+ export function shortIds(ids: string[]): string[] {
124
+ return ids.map(shortId);
125
+ }
126
+
127
+ // ---- canonical JSON -------------------------------------------------------
128
+
129
+ // Go's string encoding (SetEscapeHTML(false)): JSON.stringify plus
130
+ // escaping U+2028/U+2029, which Go always escapes.
131
+ const LINE_SEPARATOR = String.fromCharCode(0x2028);
132
+ const PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);
133
+
134
+ function quote(s: string): string {
135
+ return JSON.stringify(s).split(LINE_SEPARATOR).join('\\u2028').split(PARAGRAPH_SEPARATOR).join('\\u2029');
136
+ }
137
+
138
+ // Generic JSON value with object keys sorted at every level (Go encodes
139
+ // maps sorted).
140
+ function encodeSorted(v: unknown): string {
141
+ if (v === null || v === undefined) return 'null';
142
+ if (typeof v === 'string') return quote(v);
143
+ if (typeof v === 'number' || typeof v === 'boolean') return JSON.stringify(v);
144
+ if (Array.isArray(v)) return '[' + v.map(encodeSorted).join(',') + ']';
145
+ if (typeof v === 'object') {
146
+ const obj = v as Record<string, unknown>;
147
+ return '{' + Object.keys(obj).sort().filter((k) => obj[k] !== undefined)
148
+ .map((k) => quote(k) + ':' + encodeSorted(obj[k])).join(',') + '}';
149
+ }
150
+ return 'null';
151
+ }
152
+
153
+ // An already-encoded JSON value, written as-is.
154
+ class Raw {
155
+ constructor(readonly json: string) {}
156
+ }
157
+
158
+ // Ordered fields, omitting absent ones as Go's omitempty does ("", 0,
159
+ // null/undefined) unless the field is required (always written).
160
+ function encodeFields(fields: [key: string, value: string | number | Raw | undefined, required?: boolean][]): string {
161
+ const out: string[] = [];
162
+ for (const [k, v, required] of fields) {
163
+ if (!required && (v === undefined || v === '' || v === 0)) continue;
164
+ const val = v instanceof Raw ? v.json : typeof v === 'number' ? JSON.stringify(v) : quote(v ?? '');
165
+ out.push(quote(k) + ':' + val);
166
+ }
167
+ return '{' + out.join(',') + '}';
168
+ }
169
+
170
+ /** A copy of e at detail level `level` (summary drops details and upstream cause). */
171
+ export function atDetail(e: ApiError, level: ApiErrorDetail): ApiError {
172
+ if (level === 'full') return e;
173
+ const { details: _details, ...rest } = e;
174
+ if (rest.upstream) {
175
+ const { cause: _cause, ...up } = rest.upstream;
176
+ rest.upstream = up;
177
+ }
178
+ return rest;
179
+ }
180
+
181
+ /** Summary-level copy: no details, no upstream cause. */
182
+ export function summarizeApiError(e: ApiError): ApiError {
183
+ return atDetail(e, 'summary');
184
+ }
185
+
186
+ /**
187
+ * e's canonical JSON -- byte-identical to Go's apierror Canonical: compact,
188
+ * envelope fields in order, details keys sorted, absent fields omitted.
189
+ */
190
+ export function canonicalApiError(e: ApiError, level: ApiErrorDetail = 'full'): string {
191
+ const x = atDetail(e, level);
192
+ const up = x.upstream
193
+ ? new Raw(encodeFields([
194
+ ['service', x.upstream.service, true], ['status', x.upstream.status], ['code', x.upstream.code],
195
+ ['grpcCode', x.upstream.grpcCode], ['cause', x.upstream.cause], ['traceId', x.upstream.traceId], ['node', x.upstream.node],
196
+ ]))
197
+ : undefined;
198
+ const details = x.details === undefined || x.details === null ? undefined : new Raw(encodeSorted(x.details));
199
+ return encodeFields([
200
+ ['error', x.error, true], ['code', x.code, true], ['status', x.status], ['stage', x.stage], ['hint', x.hint],
201
+ ['requestId', x.requestId], ['upstream', up], ['details', details],
202
+ ]);
203
+ }
204
+
205
+ // ---- parsing --------------------------------------------------------------
206
+
207
+ const STATUS_TEXT: Record<number, string> = {
208
+ 400: 'Bad Request', 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed',
209
+ 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 413: 'Request Entity Too Large', 415: 'Unsupported Media Type',
210
+ 418: "I'm a teapot", 422: 'Unprocessable Entity', 429: 'Too Many Requests', 500: 'Internal Server Error',
211
+ 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout',
212
+ };
213
+
214
+ function str(v: unknown): string | undefined {
215
+ return typeof v === 'string' && v !== '' ? v : undefined;
216
+ }
217
+ function int(v: unknown): number | undefined {
218
+ return typeof v === 'number' && Number.isInteger(v) && v !== 0 ? v : undefined;
219
+ }
220
+
221
+ // wellTyped: every known field present has the type Go's decoder needs --
222
+ // otherwise Go's Parse falls back to plain text, and so does this.
223
+ function wellTyped(p: Record<string, any>): boolean {
224
+ const isStr = (v: unknown) => v === undefined || v === null || typeof v === 'string';
225
+ const isInt = (v: unknown) => v === undefined || v === null || (typeof v === 'number' && Number.isInteger(v));
226
+ if (![p.code, p.stage, p.hint, p.requestId].every(isStr) || !isInt(p.status)) return false;
227
+ const u = p.upstream;
228
+ if (u === undefined || u === null) return true;
229
+ if (typeof u !== 'object' || Array.isArray(u)) return false;
230
+ return [u.service, u.code, u.grpcCode, u.cause, u.traceId, u.node].every(isStr) && isInt(u.status);
231
+ }
232
+
233
+ /**
234
+ * Reads any error body: the canonical envelope, a legacy {"error":"..."}
235
+ * body, or plain text (the last two get codeForStatus). Unknown fields are
236
+ * dropped. Never throws. (Go: Parse.)
237
+ */
238
+ export function parseApiError(status: number, body: string): ApiError {
239
+ const text = body.trim();
240
+ try {
241
+ const p = JSON.parse(text);
242
+ if (p && typeof p === 'object' && !Array.isArray(p) && typeof p.error === 'string' && p.error !== '' && wellTyped(p)) {
243
+ const e: ApiError = { error: p.error, code: str(p.code) ?? codeForStatus(status) };
244
+ const st = int(p.status) ?? status;
245
+ if (st) e.status = st;
246
+ if (str(p.stage)) e.stage = p.stage;
247
+ if (str(p.hint)) e.hint = p.hint;
248
+ if (str(p.requestId)) e.requestId = p.requestId;
249
+ if (p.upstream && typeof p.upstream === 'object') {
250
+ const u = p.upstream;
251
+ const up: ApiErrorUpstream = { service: typeof u.service === 'string' ? u.service : '' };
252
+ if (int(u.status)) up.status = u.status;
253
+ for (const k of ['code', 'grpcCode', 'cause', 'traceId', 'node'] as const) {
254
+ if (str(u[k])) up[k] = u[k];
255
+ }
256
+ e.upstream = up;
257
+ }
258
+ if (p.details !== undefined && p.details !== null) e.details = p.details;
259
+ return e;
260
+ }
261
+ } catch {
262
+ // not JSON -- plain text below
263
+ }
264
+ return { error: text || STATUS_TEXT[status] || 'Error', code: codeForStatus(status), status };
265
+ }
266
+
267
+ /** Reads a failed fetch Response into an ApiError (request id from the header if the body has none). */
268
+ export async function apiErrorFromResponse(res: Response): Promise<ApiError> {
269
+ const text = await res.text().catch(() => '');
270
+ const e = parseApiError(res.status, text);
271
+ const id = res.headers.get('X-Request-Id');
272
+ if (!e.requestId && id && /^[A-Za-z0-9._:-]{1,128}$/.test(id)) e.requestId = id;
273
+ return e;
274
+ }
275
+
276
+ /** True if v looks like a canonical ApiError. */
277
+ export function isApiError(v: unknown): v is ApiError {
278
+ return !!v && typeof v === 'object' && typeof (v as ApiError).error === 'string' && typeof (v as ApiError).code === 'string';
279
+ }
280
+
281
+ // ---- display & logging ----------------------------------------------------
282
+
283
+ /** "message [CODE at stage, canton PERMISSION_DENIED, trace 201bbde3…aa7f]" */
284
+ export function formatApiError(e: ApiError): string {
285
+ const tags = [e.stage ? `${e.code} at ${e.stage}` : e.code];
286
+ const u = e.upstream;
287
+ if (u && (u.grpcCode || u.code)) tags.push(`${u.service} ${u.grpcCode || u.code}`);
288
+ if (u?.traceId) tags.push(`trace ${shortId(u.traceId)}`);
289
+ else if (e.requestId) tags.push(`request ${shortId(e.requestId)}`);
290
+ return `${e.error} [${tags.join(', ')}]`;
291
+ }
292
+
293
+ function shortValue(v: unknown): string {
294
+ if (typeof v === 'string') return shortId(v);
295
+ if (Array.isArray(v)) return v.map(shortValue).join(',');
296
+ if (v === null || v === undefined) return '';
297
+ return shortId(encodeSorted(v));
298
+ }
299
+
300
+ /**
301
+ * e's fields for a log line, short forms only (Go: LogFields): code,
302
+ * status, stage, requestId, upstream.*, then details.<key> sorted.
303
+ */
304
+ export function logFields(e: ApiError): [string, string][] {
305
+ const f: [string, string][] = [['code', e.code]];
306
+ const add = (k: string, v: string | undefined) => {
307
+ if (v) f.push([k, v]);
308
+ };
309
+ if (e.status) add('status', String(e.status));
310
+ add('stage', e.stage);
311
+ add('requestId', e.requestId);
312
+ if (e.upstream) {
313
+ add('upstream.service', e.upstream.service);
314
+ add('upstream.code', e.upstream.code);
315
+ add('upstream.grpcCode', e.upstream.grpcCode);
316
+ add('upstream.traceId', e.upstream.traceId);
317
+ add('upstream.node', e.upstream.node);
318
+ }
319
+ if (e.details && typeof e.details === 'object') {
320
+ for (const k of Object.keys(e.details).sort()) add('details.' + k, shortValue(e.details[k]));
321
+ }
322
+ return f;
323
+ }
324
+
325
+ // ---- Canton ---------------------------------------------------------------
326
+
327
+ const GRPC_CODE_NAMES = [
328
+ 'OK', 'CANCELLED', 'UNKNOWN', 'INVALID_ARGUMENT', 'DEADLINE_EXCEEDED', 'NOT_FOUND', 'ALREADY_EXISTS',
329
+ 'PERMISSION_DENIED', 'RESOURCE_EXHAUSTED', 'FAILED_PRECONDITION', 'ABORTED', 'OUT_OF_RANGE',
330
+ 'UNIMPLEMENTED', 'INTERNAL', 'UNAVAILABLE', 'DATA_LOSS', 'UNAUTHENTICATED',
331
+ ];
332
+
333
+ export function grpcCodeName(code: number): string {
334
+ return code >= 0 && code < GRPC_CODE_NAMES.length ? GRPC_CODE_NAMES[code] : `CODE_${code}`;
335
+ }
336
+
337
+ /** The transaction hash a Canton signature refusal names (well-formed only), or ''. */
338
+ export function expectedHash(cause: string): string {
339
+ const m = /hash to be signed: ([0-9a-fA-F]+)/.exec(cause);
340
+ if (!m) return '';
341
+ const h = m[1].toLowerCase();
342
+ return isFingerprint(h) ? h : ''; // only a well-formed hash, as in Go
343
+ }
344
+
345
+ function bounded(cause: string): string {
346
+ const cps = Array.from(cause);
347
+ return cps.length > MAX_CAUSE ? cps.slice(0, MAX_CAUSE).join('') + '...' : cause;
348
+ }
349
+
350
+ /**
351
+ * Classifies a Canton JSON Ledger API refusal (status + body) at `stage`
352
+ * into an ApiError -- identical to Go's canton.FromLedgerError, for a UI
353
+ * that talks to a participant or wallet gateway directly.
354
+ */
355
+ export function fromCantonError(status: number, body: string | Record<string, unknown>, stage = ''): ApiError {
356
+ const raw = typeof body === 'string' ? body : JSON.stringify(body);
357
+ let b: Record<string, any> = {};
358
+ try {
359
+ const p = typeof body === 'string' ? JSON.parse(body) : body;
360
+ if (p && typeof p === 'object' && !Array.isArray(p)) b = p;
361
+ } catch {
362
+ // non-JSON body
363
+ }
364
+ const code = typeof b.code === 'string' ? b.code : '';
365
+ const cause = typeof b.cause === 'string' ? b.cause : '';
366
+ const grpc = typeof b.grpcCodeValue === 'number' ? b.grpcCodeValue : 0;
367
+ const up: ApiErrorUpstream = { service: 'canton' };
368
+ if (status) up.status = status;
369
+ if (code) up.code = code;
370
+ if (grpc) up.grpcCode = grpcCodeName(grpc);
371
+ if (cause) up.cause = bounded(cause);
372
+ if (typeof b.traceId === 'string' && b.traceId) up.traceId = b.traceId;
373
+ const participant = b.context && typeof b.context === 'object' ? b.context.participant : undefined;
374
+ if (typeof participant === 'string' && participant) up.node = participant;
375
+
376
+ const make = (st: number, c: string, msg: string, hint: string): ApiError => {
377
+ const e: ApiError = { error: msg, code: c, status: st };
378
+ if (stage) e.stage = stage;
379
+ e.hint = hint;
380
+ e.upstream = up;
381
+ return e;
382
+ };
383
+
384
+ if (!code && !grpc) {
385
+ const c = raw.trim();
386
+ if (c) up.cause = bounded(c);
387
+ return make(502, CantonCodes.LEDGER_REJECTED, 'the ledger endpoint answered with a non-Canton error',
388
+ 'check the JSON Ledger API URL and version, and any proxy in front of it -- see upstream.cause');
389
+ }
390
+ const expected = expectedHash(cause);
391
+ let e: ApiError;
392
+ if (grpc === 7 || status === 403) {
393
+ e = make(403, CantonCodes.LEDGER_PERMISSION_DENIED, 'the ledger denied the submitting ledger user',
394
+ 'the ledger user needs the right this command requires (CanActAs, CanExecuteAs or CanReadAs) on the acting party');
395
+ } else if (grpc === 16 || status === 401) {
396
+ e = make(502, CantonCodes.LEDGER_UNAUTHENTICATED, 'the ledger rejected the submitting token',
397
+ "ledger auth is misconfigured (token issuer, audience or secret) -- an operator problem, not the user's");
398
+ } else if (expected || cause.includes('valid signature')) {
399
+ let hint = "sign the prepared transaction's hash, recomputed from the unmodified prepared transaction, with the party's key";
400
+ if (expected) hint += `; the participant expected hash ${shortId(expected)} (details.expectedHash)`;
401
+ e = make(422, CantonCodes.LEDGER_SIGNATURE_REJECTED, "the participant found no valid signature from the party's key", hint);
402
+ } else if (grpc === 3) {
403
+ e = make(400, CantonCodes.LEDGER_INVALID_ARGUMENT, "the ledger rejected the request's arguments",
404
+ "see upstream.cause for the field; a command may reference a package or template this participant doesn't have");
405
+ } else if (grpc === 5) {
406
+ e = make(409, CantonCodes.LEDGER_NOT_FOUND, "the ledger couldn't find something the request needs",
407
+ 'a referenced contract may already be archived (stale contract id) or not visible to the acting party -- refresh and retry');
408
+ } else if (grpc === 6 || grpc === 10) {
409
+ e = make(409, CantonCodes.LEDGER_CONFLICT, "the request conflicts with the ledger's current state",
410
+ 'a duplicate or concurrent submission -- refresh and retry');
411
+ } else if (grpc === 9) {
412
+ e = make(422, CantonCodes.LEDGER_REJECTED, 'the ledger rejected the command (a contract precondition failed)',
413
+ 'see upstream.cause: usually a Daml assertion in the choice');
414
+ } else if (grpc === 14 || grpc === 4 || status === 503) {
415
+ e = make(503, CantonCodes.LEDGER_UNAVAILABLE, 'the ledger is unavailable or timed out',
416
+ 'retry shortly; if it persists, check the participant and synchronizer');
417
+ } else {
418
+ e = make(502, CantonCodes.LEDGER_REJECTED, 'the ledger refused the request', 'see upstream.cause');
419
+ }
420
+ if (expected) e.details = { expectedHash: expected } satisfies SigningDetails;
421
+ return e;
422
+ }
423
+
424
+ /**
425
+ * Normalizes anything thrown by a call the UI made itself -- a wallet SDK,
426
+ * a direct ledger call, fetch -- into an ApiError: an ApiError passes
427
+ * through; an error carrying a Canton error body (as JSON in its message,
428
+ * or a {status, body} pair) goes through fromCantonError; anything else
429
+ * becomes `fallbackCode` (UPSTREAM_ERROR) for `service`.
430
+ */
431
+ export function apiErrorFromUnknown(err: unknown, opts: { stage?: string; service?: string; fallbackCode?: string } = {}): ApiError {
432
+ if (isApiError(err)) return err;
433
+ const o = (err && typeof err === 'object' ? err : {}) as Record<string, any>;
434
+ if (typeof o.status === 'number' && (typeof o.body === 'string' || (o.body && typeof o.body === 'object'))) {
435
+ return fromCantonError(o.status, o.body, opts.stage);
436
+ }
437
+ const message = err instanceof Error ? err.message : typeof err === 'string' ? err : String(o.message ?? 'unknown error');
438
+ const brace = message.indexOf('{');
439
+ if (brace >= 0) {
440
+ try {
441
+ const body = JSON.parse(message.slice(brace));
442
+ if (body && typeof body === 'object' && ('grpcCodeValue' in body || 'cause' in body)) {
443
+ return fromCantonError(typeof o.status === 'number' ? o.status : 0, body, opts.stage);
444
+ }
445
+ } catch {
446
+ // not an embedded Canton body
447
+ }
448
+ }
449
+ const e: ApiError = { error: message, code: opts.fallbackCode ?? ApiErrorCodes.UPSTREAM_ERROR, status: 502 };
450
+ if (opts.stage) e.stage = opts.stage;
451
+ if (opts.service) e.upstream = { service: opts.service };
452
+ return e;
453
+ }
@@ -0,0 +1,74 @@
1
+ // One display for every Canton id (party, fingerprint, hash): the short
2
+ // form (or a human label, e.g. the party's T1 display name), the full value
3
+ // on hover, and a copy button that copies the full value. Framework-free
4
+ // DOM; components/CantonId.astro hydrates through it and the error notice
5
+ // uses it, so ids look and behave the same everywhere. Values are set with
6
+ // textContent only.
7
+
8
+ import { shortCantonId, classifyCantonId, type CantonIdKind } from './canton-id';
9
+
10
+ export interface CantonIdOptions {
11
+ /** A human label shown instead of the short id (e.g. "Joey Depositor"); hover then shows both. */
12
+ label?: string;
13
+ /** Adds a copy button (default true). */
14
+ copy?: boolean;
15
+ }
16
+
17
+ export const CANTON_ID_CLASS = 'inline-flex max-w-full items-center gap-1.5 align-middle';
18
+ export const CANTON_ID_TEXT_CLASS = 'font-mono text-xs break-all text-slate-700 dark:text-slate-200';
19
+ export const CANTON_ID_LABEL_CLASS = 'text-xs font-semibold text-slate-800 dark:text-slate-100';
20
+ export const CANTON_ID_COPY_CLASS =
21
+ 'rounded-md border border-slate-200 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
22
+
23
+ /** The hover text: the full value, under the label and short form when labeled. */
24
+ export function cantonIdTitle(value: string, label?: string): string {
25
+ return label ? `${label}\n${shortCantonId(value)}\n${value}` : value;
26
+ }
27
+
28
+ /** Renders value as a short id with full-value hover and copy. */
29
+ export function renderCantonId(value: string, opts: CantonIdOptions = {}): HTMLElement {
30
+ const kind: CantonIdKind = classifyCantonId(value);
31
+ const root = document.createElement('span');
32
+ root.className = CANTON_ID_CLASS;
33
+ root.dataset.cantonId = value;
34
+ root.dataset.cantonIdKind = kind;
35
+
36
+ const text = document.createElement('span');
37
+ text.className = opts.label ? CANTON_ID_LABEL_CLASS : CANTON_ID_TEXT_CLASS;
38
+ text.textContent = opts.label || shortCantonId(value);
39
+ text.title = cantonIdTitle(value, opts.label);
40
+ text.setAttribute('aria-label', opts.label ? `${opts.label} (${value})` : value);
41
+ root.append(text);
42
+
43
+ if (opts.copy !== false) {
44
+ const b = document.createElement('button');
45
+ b.type = 'button';
46
+ b.className = CANTON_ID_COPY_CLASS;
47
+ b.textContent = 'Copy';
48
+ b.setAttribute('aria-label', `Copy ${kind === 'party' ? 'party id' : kind === 'fingerprint' ? 'fingerprint' : 'value'}`);
49
+ b.addEventListener('click', async () => {
50
+ try {
51
+ await navigator.clipboard.writeText(value);
52
+ b.textContent = 'Copied';
53
+ } catch {
54
+ b.textContent = 'Copy failed';
55
+ }
56
+ setTimeout(() => (b.textContent = 'Copy'), 1500);
57
+ });
58
+ root.append(b);
59
+ }
60
+ return root;
61
+ }
62
+
63
+ /**
64
+ * Renders every [data-canton-id] element under root (CantonId.astro's
65
+ * server output) that hasn't been rendered yet.
66
+ */
67
+ export function hydrateCantonIds(root: ParentNode = document): void {
68
+ root.querySelectorAll<HTMLElement>('[data-canton-id]:not([data-canton-id-rendered])').forEach((host) => {
69
+ const value = host.dataset.cantonId ?? '';
70
+ const rendered = renderCantonId(value, { label: host.dataset.cantonIdLabel || undefined, copy: host.dataset.cantonIdCopy !== 'false' });
71
+ rendered.dataset.cantonIdRendered = '';
72
+ host.replaceWith(rendered);
73
+ });
74
+ }
@@ -0,0 +1,81 @@
1
+ // Typed Canton identifiers -- the TypeScript mirror of daml-escrow-commons
2
+ // `cantonid` (Go), held to it by test/fixtures/canton-id/parse.json.
3
+ //
4
+ // fingerprint 1220<64 hex> a key ("1220" = multihash sha-256, 32 bytes)
5
+ // party <hint>::<fingerprint> the namespace IS a fingerprint: the controlling
6
+ // key's for an external party, the hosting
7
+ // participant's (shared by its parties) otherwise
8
+ // hash 1220<64 hex> a transaction or topology hash (same format)
9
+ //
10
+ // The short form ("relaytest::1220ebb7…4288") is for humans only -- lossy,
11
+ // never parsed back or used to look anything up. Show it with the full
12
+ // value on hover (sdk/canton-id-view, components/CantonId).
13
+
14
+ export type CantonIdKind = 'party' | 'fingerprint' | 'other';
15
+
16
+ export interface PartyId {
17
+ hint: string;
18
+ /** The party's namespace: a key fingerprint. */
19
+ namespace: string;
20
+ /** hint::namespace, full length. */
21
+ full: string;
22
+ short: string;
23
+ }
24
+
25
+ const MULTIHASH = /^1220[0-9a-f]{64}$/;
26
+ // Canton's party-hint alphabet: letters, digits, '-', '_', ':' and ' ',
27
+ // never the "::" delimiter, up to 185 characters.
28
+ const HINT = /^[A-Za-z0-9_\- :]{1,185}$/;
29
+ const SHORT_HEAD = 8; // includes the 1220 prefix
30
+ const SHORT_TAIL = 4;
31
+
32
+ function shortHex(s: string): string {
33
+ return s.length <= SHORT_HEAD + SHORT_TAIL ? s : s.slice(0, SHORT_HEAD) + '…' + s.slice(-SHORT_TAIL);
34
+ }
35
+
36
+ function shortRunes(s: string): string {
37
+ const cps = Array.from(s); // code points, like Go runes
38
+ if (cps.length <= SHORT_HEAD + SHORT_TAIL + 4) return s;
39
+ return cps.slice(0, SHORT_HEAD).join('') + '…' + cps.slice(cps.length - SHORT_TAIL).join('');
40
+ }
41
+
42
+ /** True if s is a key fingerprint (or hash): 1220 + 64 lowercase hex. */
43
+ export function isFingerprint(s: string): boolean {
44
+ return MULTIHASH.test(s);
45
+ }
46
+
47
+ /** Parses hint::fingerprint, or null. */
48
+ export function parsePartyId(s: string): PartyId | null {
49
+ const i = s.indexOf('::');
50
+ if (i < 0) return null;
51
+ const hint = s.slice(0, i);
52
+ const namespace = s.slice(i + 2);
53
+ if (!HINT.test(hint) || hint.includes('::') || !MULTIHASH.test(namespace)) return null;
54
+ return { hint, namespace, full: s, short: hint + '::' + shortHex(namespace) };
55
+ }
56
+
57
+ /** What s is: a party id, a fingerprint/hash, or something else. */
58
+ export function classifyCantonId(s: string): CantonIdKind {
59
+ if (parsePartyId(s)) return 'party';
60
+ if (MULTIHASH.test(s)) return 'fingerprint';
61
+ return 'other';
62
+ }
63
+
64
+ /**
65
+ * The one short form of any string (Go: cantonid.Short): a party keeps its
66
+ * hint and shortens its namespace; a fingerprint or hash keeps 8…4; an
67
+ * unparseable "x::y" keeps x; any other long value keeps 8…4 characters.
68
+ */
69
+ export function shortCantonId(s: string): string {
70
+ const party = parsePartyId(s);
71
+ if (party) return party.short;
72
+ if (MULTIHASH.test(s)) return shortHex(s);
73
+ const i = s.indexOf('::');
74
+ if (i >= 0) return s.slice(0, i) + '::' + shortRunes(s.slice(i + 2));
75
+ return shortRunes(s);
76
+ }
77
+
78
+ /** True if key fingerprint fp alone controls party (an external party whose namespace is fp). */
79
+ export function partyControlledBy(party: PartyId, fp: string): boolean {
80
+ return fp !== '' && party.namespace === fp;
81
+ }
@@ -1,5 +1,6 @@
1
1
  @import "tailwindcss";
2
2
  @source "../components";
3
+ @source "../sdk";
3
4
  @plugin "@tailwindcss/typography";
4
5
 
5
6
  /*