@object-ui/data-objectstack 17.3.0 → 17.6.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 (40) hide show
  1. package/CHANGELOG.md +888 -0
  2. package/README.md +3 -11
  3. package/dist/index.cjs +1511 -1115
  4. package/dist/index.d.cts +1222 -824
  5. package/dist/index.d.ts +1222 -824
  6. package/dist/index.js +1503 -1111
  7. package/package.json +5 -6
  8. package/src/aggregate-capability.test.ts +0 -177
  9. package/src/bulkDelete.test.ts +0 -75
  10. package/src/bulkUpdate.test.ts +0 -93
  11. package/src/cache/MetadataCache.test.ts +0 -477
  12. package/src/cache/MetadataCache.ts +0 -289
  13. package/src/cloud.ts +0 -109
  14. package/src/connection.test.ts +0 -188
  15. package/src/contracts.ts +0 -115
  16. package/src/errors.test.ts +0 -426
  17. package/src/errors.ts +0 -293
  18. package/src/exportDownload.test.ts +0 -141
  19. package/src/filter-entry-translation.test.ts +0 -360
  20. package/src/filter-operator-ast-parity.test.ts +0 -71
  21. package/src/getObjectSchema.test.ts +0 -145
  22. package/src/importJob.test.ts +0 -71
  23. package/src/index.ts +0 -3658
  24. package/src/integration.ts +0 -200
  25. package/src/listViews.test.ts +0 -175
  26. package/src/metadata-client.test.ts +0 -303
  27. package/src/metadata-client.ts +0 -849
  28. package/src/occ.test.ts +0 -101
  29. package/src/onMutation.test.ts +0 -562
  30. package/src/onWriteWarning.test.ts +0 -273
  31. package/src/orderby-serialization.test.ts +0 -115
  32. package/src/queryDataset.test.ts +0 -132
  33. package/src/searchAll.test.ts +0 -120
  34. package/src/security.ts +0 -243
  35. package/src/spec-symbol-batch6.test.ts +0 -306
  36. package/src/studio.ts +0 -152
  37. package/src/userState.test.ts +0 -315
  38. package/src/userState.ts +0 -238
  39. package/src/v3-compat.test.ts +0 -240
  40. package/src/validation-error.test.ts +0 -94
@@ -1,849 +0,0 @@
1
- /**
2
- * ObjectUI
3
- * Copyright (c) 2024-present ObjectStack Inc.
4
- *
5
- * This source code is licensed under the MIT license found in the
6
- * LICENSE file in the root directory of this source tree.
7
- */
8
-
9
- /**
10
- * MetadataClient
11
- *
12
- * Thin, framework-agnostic HTTP client for the ObjectStack metadata
13
- * API (`/api/v1/meta/*`). Used by the platform Setup app surfaces in
14
- * `@object-ui/plugin-designer` (Object Manager, Field Designer, etc.)
15
- * so they can read and write protocol metadata without depending on
16
- * `ObjectStackAdapter` (which is a generic data-source binding and
17
- * carries a lot of view/dashboard-specific behaviour we don't need
18
- * here).
19
- *
20
- * Endpoints (see `packages/rest/src/rest-server.ts`):
21
- * GET /api/v1/meta — list all metadata types
22
- * GET /api/v1/meta/:type — list items of a type
23
- * GET /api/v1/meta/:type/:name — get one item (returns the
24
- * unwrapped item content)
25
- * PUT /api/v1/meta/:type/:name — save (overlay) one item
26
- * honours `If-Match` for OCC
27
- * DELETE /api/v1/meta/:type/:name — reset overlay to artifact
28
- * GET /api/v1/meta/:type/:name/history — durable change log
29
- *
30
- * The client deliberately keeps the response shape opaque (typed as
31
- * `unknown`/generic `T`) so callers explicitly narrow per-metadata-
32
- * type, mirroring the framework's "single Zod source per type" rule.
33
- */
34
-
35
- export interface MetadataClientConfig {
36
- /** Base URL of the ObjectStack server (no trailing slash needed). */
37
- baseUrl: string;
38
- /**
39
- * Optional environment ID to scope reads/writes to a tenant. When
40
- * provided, requests use the scoped path
41
- * `/api/v1/environments/:environmentId/meta/...` and overlays are
42
- * persisted in the environment's own metadata store.
43
- */
44
- environmentId?: string;
45
- /** Optional custom fetch implementation (defaults to `globalThis.fetch`). */
46
- fetch?: typeof fetch;
47
- /** Additional headers (e.g. auth) included on every request. */
48
- headers?: Record<string, string>;
49
- /**
50
- * ADR-0037 Live Canvas — render the world **as-if-published**. When true,
51
- * `list()` and `get()` append `?preview=draft`, which the framework
52
- * dispatcher maps to `getMetaItems/getMetaItem({ previewDrafts: true })`:
53
- * pending ADR-0033 drafts overlay the active registry (draft wins by name,
54
- * draft-only items surface). Reads only — writes are unaffected, and
55
- * nothing the preview shows is live until Publish.
56
- */
57
- previewDrafts?: boolean;
58
- }
59
-
60
- export interface MetadataListOptions {
61
- /** Filter by source package id (matches the `package` query param). */
62
- packageId?: string;
63
- }
64
-
65
- /**
66
- * A pending DRAFT metadata item (ADR-0033), as returned by {@link MetadataClient.listDrafts}.
67
- * Light header — no body — carrying the owning package so the console can group
68
- * pending changes by app package.
69
- */
70
- export interface MetadataDraftHeader {
71
- type: string;
72
- name: string;
73
- packageId: string | null;
74
- updatedAt: string | null;
75
- updatedBy: string | null;
76
- }
77
-
78
- /**
79
- * Options for {@link MetadataClient.save} — a WRITE OVER HTTP to
80
- * `/api/v1/meta/:type/:name`.
81
- *
82
- * NOT the spec's `MetadataSaveOptions` (`@objectstack/spec/system` and
83
- * `/kernel`), whose name this interface wore until objectui#3160
84
- * (objectstack#4115 ledger batch 6). Both spec copies describe writing a
85
- * metadata item to a FILE — `format: json|yaml|ts`, `path`, `indent`,
86
- * `prettify`, `sortKeys`, `backup`, `atomic`, `loader`. Not one of those keys
87
- * exists here, and not one of these exists there: this is the REST client's
88
- * request envelope — optimistic concurrency (`ifMatch` → `If-Match`), actor
89
- * attribution, the destructive-change override, the ADR-0033 draft/publish
90
- * mode, and the owning package. Same words, different layer.
91
- */
92
- export interface MetadataClientSaveOptions {
93
- /**
94
- * Optimistic concurrency token (the `checksum` returned by the last
95
- * read). When present, sent as the `If-Match` header so concurrent
96
- * edits get a 409 instead of overwriting each other.
97
- */
98
- ifMatch?: string;
99
- /** Optional actor id, sent as `X-Actor` for history attribution. */
100
- actor?: string;
101
- /**
102
- * Bypass destructive-change protection (Phase 3a). The server returns
103
- * `409 destructive_change` with `issues[]` if a write would drop or
104
- * narrow data; setting `force: true` adds `?force=true` to the request
105
- * so the operator can confirm and proceed.
106
- */
107
- force?: boolean;
108
- /**
109
- * Save mode — `'draft'` writes a pending draft row (invisible to the
110
- * runtime until `publish()` is called); `'publish'` writes directly
111
- * to the active overlay. Omit (or set `'publish'`) for the legacy
112
- * "save = live" behaviour.
113
- */
114
- mode?: 'draft' | 'publish';
115
- /**
116
- * Software-package id to bind the saved row to (sent as the `package`
117
- * query param → `sys_metadata.package_id`). Set when authoring inside a
118
- * Studio package workspace. Omit for an env-local overlay.
119
- */
120
- packageId?: string;
121
- }
122
-
123
- export interface MetadataGetOptions {
124
- /**
125
- * Read a specific overlay state. `'draft'` returns the pending draft
126
- * body (no fallback to the published overlay or the registry); omit
127
- * to read the active (published) value.
128
- */
129
- state?: 'active' | 'draft';
130
- /**
131
- * Software-package id to scope resolution (sent as the `package` query
132
- * param → server prefer-local, ADR-0048). Set when reading one item that
133
- * may collide by name across installed packages (e.g. the Studio editor
134
- * passes the edited item's owning package). Omit for context-free reads.
135
- */
136
- packageId?: string;
137
- }
138
-
139
- export interface MetadataDeleteOptions extends MetadataClientSaveOptions {
140
- /**
141
- * Target state. `'draft'` discards the pending draft (keeps the
142
- * published overlay intact). Omit to reset the active overlay back
143
- * to the artifact default (the legacy behaviour).
144
- */
145
- state?: 'active' | 'draft';
146
- }
147
-
148
- /** Layered view of a metadata item — Phase 3a `?layers=true`. */
149
- export interface MetadataLayered<T = unknown> {
150
- /** Code-level (artifact) item; null if the item only exists as an overlay. */
151
- code: T | null;
152
- /** Org/environment overlay (just the saved delta or full overlay row). */
153
- overlay: T | null;
154
- /** Overlay scope (`organization` | `environment` | `package` | null). */
155
- overlayScope: string | null;
156
- /** Merged effective view — what the runtime actually sees. */
157
- effective: T | null;
158
- /**
159
- * Load-time validation result for `effective` (server-computed via
160
- * the same Zod registry used at save time). Undefined for types
161
- * without a registered Zod schema. Surfaced by the Studio as a
162
- * banner + inline field errors so operators can spot bad metadata
163
- * without having to hit Save.
164
- */
165
- _diagnostics?: MetadataDiagnostics;
166
- // ── ADR-0010 Phase 1 — protection envelope ──
167
- /** 4-state lock: `none` / `no-overlay` / `no-delete` / `full`. */
168
- lock?: 'none' | 'no-overlay' | 'no-delete' | 'full';
169
- /** Human-readable reason for the lock (tooltip text). */
170
- lockReason?: string;
171
- /** Which layer set the lock: artifact / package / overlay / env-forced. */
172
- lockSource?: 'artifact' | 'package' | 'overlay' | 'env-forced';
173
- /** Optional docs URL for the lock reason (rendered as "View docs →"). */
174
- lockDocsUrl?: string;
175
- /** Origin of the item: `package` (loader) | `org` (tenant) | `env-forced`. */
176
- provenance?: 'package' | 'org' | 'env-forced';
177
- /** Owning package id (denormalised from the loader tag). */
178
- packageId?: string;
179
- /** Owning package version. */
180
- packageVersion?: string;
181
- /** True when the editor should allow Save (PUT). */
182
- editable?: boolean;
183
- /** True when the editor should allow Delete. */
184
- deletable?: boolean;
185
- /** True when "Reset to package default" applies (has overlay + artifact). */
186
- resettable?: boolean;
187
- }
188
-
189
- /**
190
- * One row in the metadata protection-audit trail
191
- * (ADR-0010 §3.6 / Phase 4.1). Mirrors `sys_metadata_audit` columns
192
- * the API exposes.
193
- */
194
- export interface MetadataAuditEntry {
195
- /** Stable audit-row id (uuid). */
196
- id: unknown;
197
- /** ISO timestamp when the attempt happened. */
198
- occurredAt: string;
199
- /** Who attempted the operation (`x-actor` header or `'system'`). */
200
- actor: string;
201
- /** Code path that recorded the row (e.g. `protocol.saveMetaItem`). */
202
- source: string | null;
203
- /** Which lifecycle op was attempted. */
204
- operation: 'save' | 'publish' | 'rollback' | 'delete' | 'reset';
205
- /** Decision: allowed / denied / forced (admin override). */
206
- outcome: 'allowed' | 'denied' | 'forced';
207
- /** Machine-readable reason code (`item_locked`, `ok`, …). */
208
- code: string;
209
- /** Effective lock at the moment of the attempt. */
210
- lockState: 'none' | 'no-overlay' | 'no-delete' | 'full' | null;
211
- /** True when admin forced the write through despite the lock. */
212
- lockOverridden: boolean;
213
- /** Request-id for trace correlation (if propagated). */
214
- requestId: string | null;
215
- /** Free-text note (often the lock reason). */
216
- note: string | null;
217
- }
218
-
219
- /** Response shape for `MetadataClient.audit()`. */
220
- export interface MetadataAuditResponse {
221
- events: MetadataAuditEntry[];
222
- }
223
-
224
- /**
225
- * Load-time validation envelope attached to metadata items by the
226
- * framework. Mirrors `MetadataValidationResult` in the kernel spec.
227
- */
228
- export interface MetadataDiagnostics {
229
- valid: boolean;
230
- errors?: Array<{ path: string; message: string; code?: string }>;
231
- warnings?: Array<{ path: string; message: string }>;
232
- }
233
-
234
- /** Options for the cross-type `/meta/diagnostics` sweep call. */
235
- export interface MetadataDiagnosticsOptions {
236
- /** Restrict the sweep to a single metadata type (e.g. `'view'`). */
237
- type?: string;
238
- /**
239
- * `'error'` (default) returns only items that fail validation.
240
- * `'warning'` also includes items whose only diagnostics are warnings.
241
- */
242
- severity?: 'error' | 'warning';
243
- /** Restrict to items owned by this package id. */
244
- packageId?: string;
245
- }
246
-
247
- /** One row in the `/meta/diagnostics` response. */
248
- export interface MetadataDiagnosticsEntry {
249
- type: string;
250
- name: string;
251
- diagnostics: MetadataDiagnostics;
252
- }
253
-
254
- /** Top-level envelope returned by `/meta/diagnostics`. */
255
- export interface MetadataDiagnosticsSummary {
256
- entries: MetadataDiagnosticsEntry[];
257
- /** Number of `entries` returned (post-filter). */
258
- total: number;
259
- /** How many metadata types the sweep visited. */
260
- scannedTypes: number;
261
- /** How many individual items were validated. */
262
- scannedItems: number;
263
- /**
264
- * Per-type aggregate stats — count of items and the list of
265
- * packages contributing to each type. Computed in the same sweep
266
- * so a single call serves both the diagnostics governance page and
267
- * the directory tile counts / package filter.
268
- *
269
- * Optional for backward compatibility with older framework
270
- * versions that do not yet emit it; clients should fall back to
271
- * an empty record.
272
- */
273
- stats?: Record<string, { count: number; locked?: number; packages: string[] }>;
274
- }
275
-
276
- /** Reference back-pointer — Phase 3a `/references`. */
277
- export interface MetadataReference {
278
- /** Referencing item's metadata type. */
279
- fromType: string;
280
- /** Referencing item's name. */
281
- fromName: string;
282
- /** JSON path within the referencing item that holds the reference. */
283
- path: string;
284
- /** The actual value seen at `path` (the referenced name). */
285
- value: string;
286
- }
287
-
288
- export interface MetadataHistoryOptions {
289
- /** Only return events after this sequence number. */
290
- sinceSeq?: number;
291
- /** Limit the number of events returned. */
292
- limit?: number;
293
- }
294
-
295
- /** A single field-anchored spec-validation issue (server `error.details.issues`). */
296
- export interface MetadataValidationIssue {
297
- /** Dot-path to the offending field, e.g. `fields.amount.type` (`''` = root). */
298
- path: string;
299
- message: string;
300
- code?: string;
301
- }
302
-
303
- export interface MetadataError extends Error {
304
- status: number;
305
- code?: string;
306
- body?: unknown;
307
- /** Structured spec-validation issues, when the failure was a validation error. */
308
- issues?: MetadataValidationIssue[];
309
- }
310
-
311
- const META_PREFIX = '/meta';
312
- const API_PREFIX = '/api/v1';
313
-
314
- function buildBase(config: MetadataClientConfig): string {
315
- const trimmed = config.baseUrl.replace(/\/+$/, '');
316
- const scoped = config.environmentId
317
- ? `${API_PREFIX}/environments/${encodeURIComponent(config.environmentId)}${META_PREFIX}`
318
- : `${API_PREFIX}${META_PREFIX}`;
319
- // Allow baseUrl to already include `/api/v1`; collapse the duplicate.
320
- if (/\/api\/v\d+$/i.test(trimmed)) {
321
- const stripped = trimmed.replace(/\/api\/v\d+$/i, '');
322
- const scopedNoApi = config.environmentId
323
- ? `${API_PREFIX}/environments/${encodeURIComponent(config.environmentId)}${META_PREFIX}`
324
- : `${API_PREFIX}${META_PREFIX}`;
325
- return `${stripped}${scopedNoApi}`;
326
- }
327
- return `${trimmed}${scoped}`;
328
- }
329
-
330
- async function parseError(res: Response): Promise<MetadataError> {
331
- let body: unknown;
332
- try {
333
- body = await res.json();
334
- } catch {
335
- body = await res.text().catch(() => undefined);
336
- }
337
- const bodyObj = body && typeof body === 'object' ? (body as Record<string, any>) : undefined;
338
- // The dispatcher error shape is `{ success:false, error:{ message, code,
339
- // details:{ code, issues } } }` — `error` is an OBJECT. Older/other surfaces
340
- // send `error` as a plain string or a top-level `message`. Accept all three
341
- // (reading `.message` off the object case, not `String(object)` which yields
342
- // "[object Object]").
343
- const errNode = bodyObj?.error;
344
- const message =
345
- (errNode && typeof errNode === 'object' ? errNode.message : errNode) ??
346
- bodyObj?.message ??
347
- `Metadata request failed: ${res.status} ${res.statusText}`;
348
- const err = new Error(String(message)) as MetadataError;
349
- err.status = res.status;
350
- err.body = body;
351
- // Field-anchored spec-validation issues. Two live server shapes carry them:
352
- // the REST server puts them at top-level `body.issues` (with `error` a string),
353
- // the HTTP dispatcher nests them under `error.details.issues` (with `error` an
354
- // object). Accept both (plus a defensive `error.issues`) so the caller can
355
- // point at the offending field regardless of which transport served the error.
356
- const details = errNode && typeof errNode === 'object' ? errNode.details : undefined;
357
- const issues =
358
- details?.issues ??
359
- (errNode && typeof errNode === 'object' ? errNode.issues : undefined) ??
360
- bodyObj?.issues;
361
- if (Array.isArray(issues)) err.issues = issues as MetadataValidationIssue[];
362
- const code =
363
- details?.code ??
364
- (errNode && typeof errNode === 'object' ? errNode.code : undefined) ??
365
- bodyObj?.code;
366
- if (code != null) err.code = String(code);
367
- return err;
368
- }
369
-
370
- /**
371
- * MetadataClient — read/write protocol metadata via the framework REST API.
372
- *
373
- * @example
374
- * ```ts
375
- * const client = new MetadataClient({ baseUrl: 'http://localhost:3000' });
376
- * const objects = await client.list<{ name: string; label?: string }>('object');
377
- * const account = await client.get<{ fields: Record<string, unknown> }>('object', 'account');
378
- * await client.save('object', 'account', { ...account, label: 'Customer' });
379
- * ```
380
- */
381
- export class MetadataClient {
382
- private readonly base: string;
383
- private readonly fetchImpl: typeof fetch;
384
- private readonly headers: Record<string, string>;
385
- /** ADR-0037: when true, reads render the draft-overlaid world. */
386
- readonly previewDrafts: boolean;
387
-
388
- constructor(config: MetadataClientConfig) {
389
- this.base = buildBase(config);
390
- this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
391
- this.headers = { Accept: 'application/json', ...(config.headers ?? {}) };
392
- this.previewDrafts = config.previewDrafts === true;
393
- }
394
-
395
- /** Update the client's environment scope at runtime. */
396
- withEnvironment(environmentId: string | undefined): MetadataClient {
397
- return new MetadataClient({
398
- baseUrl: this.base
399
- .replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/, '')
400
- .replace(/\/+$/, ''),
401
- environmentId,
402
- fetch: this.fetchImpl,
403
- headers: this.headers,
404
- previewDrafts: this.previewDrafts,
405
- });
406
- }
407
-
408
- /**
409
- * Derive a client whose reads render the draft-overlaid world (or not).
410
- * Same base/fetch/headers; used by the app-shell to switch the whole
411
- * renderer tree into ADR-0037 preview mode off one URL flag.
412
- */
413
- withPreviewDrafts(previewDrafts: boolean): MetadataClient {
414
- if (previewDrafts === this.previewDrafts) return this;
415
- // Preserve the environment scope baked into the base path (unlike
416
- // `withEnvironment`, which exists to REPLACE it).
417
- const envMatch = this.base.match(/\/api\/v\d+\/environments\/([^/]+)\/meta$/);
418
- return new MetadataClient({
419
- baseUrl: this.base
420
- .replace(/\/api\/v\d+(?:\/environments\/[^/]+)?\/meta$/, '')
421
- .replace(/\/+$/, ''),
422
- ...(envMatch ? { environmentId: decodeURIComponent(envMatch[1]) } : {}),
423
- fetch: this.fetchImpl,
424
- headers: this.headers,
425
- previewDrafts,
426
- });
427
- }
428
-
429
- /** List all registered metadata types (returns the registry rows). */
430
- async listTypes(): Promise<unknown[]> {
431
- const res = await this.fetchImpl(this.base, { method: 'GET', headers: this.headers, cache: 'no-store' });
432
- if (!res.ok) throw await parseError(res);
433
- const data = await res.json();
434
- if (Array.isArray(data)) return data;
435
- // Framework REST returns `{ types: string[], entries: TypeEntry[] }`
436
- // where `entries` is the rich per-type registry row. Older / scoped
437
- // shapes may use `items`. Prefer `entries` (rich), fall back to
438
- // `items` (legacy), then synthesize stub entries from `types[]`
439
- // if neither is present.
440
- if (data && Array.isArray((data as any).entries)) return (data as any).entries;
441
- if (data && Array.isArray((data as any).items)) return (data as any).items;
442
- if (data && Array.isArray((data as any).types)) {
443
- return (data as any).types.map((t: string) => ({ type: t }));
444
- }
445
- return [];
446
- }
447
-
448
- /** List items of a metadata type (e.g. `object`, `field`, `view`). */
449
- async list<T = unknown>(type: string, options: MetadataListOptions = {}): Promise<T[]> {
450
- const params: string[] = [];
451
- if (options.packageId) params.push(`package=${encodeURIComponent(options.packageId)}`);
452
- if (this.previewDrafts) params.push('preview=draft');
453
- const qs = params.length ? `?${params.join('&')}` : '';
454
- const url = `${this.base}/${encodeURIComponent(type)}${qs}`;
455
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
456
- if (!res.ok) throw await parseError(res);
457
- const data = await res.json();
458
- if (Array.isArray(data)) return data as T[];
459
- if (data && Array.isArray((data as { items?: unknown[] }).items)) {
460
- return (data as { items: T[] }).items;
461
- }
462
- return [];
463
- }
464
-
465
- /**
466
- * List pending DRAFT items (ADR-0033) — what an AI authored but nobody
467
- * published yet. `list()` only sees published/active metadata, so a
468
- * just-built app package looks empty there; this surfaces the drafts so the
469
- * console can show a "pending changes" view and draft-aware package contents.
470
- * Optionally narrow by `packageId` and/or `type`. Returns light headers
471
- * (no body) carrying `packageId` for grouping.
472
- */
473
- async listDrafts(
474
- options: { packageId?: string; type?: string } = {},
475
- ): Promise<MetadataDraftHeader[]> {
476
- const params: string[] = [];
477
- if (options.packageId) params.push(`packageId=${encodeURIComponent(options.packageId)}`);
478
- if (options.type) params.push(`type=${encodeURIComponent(options.type)}`);
479
- const qs = params.length ? `?${params.join('&')}` : '';
480
- const url = `${this.base}/_drafts${qs}`;
481
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
482
- if (!res.ok) throw await parseError(res);
483
- const data = (await res.json()) as
484
- | MetadataDraftHeader[]
485
- | { drafts?: MetadataDraftHeader[]; data?: { drafts?: MetadataDraftHeader[] } };
486
- if (Array.isArray(data)) return data;
487
- return data?.drafts ?? data?.data?.drafts ?? [];
488
- }
489
-
490
- /**
491
- * Get a single metadata item. Returns the unwrapped item content
492
- * (matching the framework REST handler which calls `res.json(item)`).
493
- * Returns `null` on 404 to keep the call-site ergonomic.
494
- */
495
- async get<T = unknown>(
496
- type: string,
497
- name: string,
498
- options: MetadataGetOptions = {},
499
- ): Promise<T | null> {
500
- const params: string[] = [];
501
- if (options.state === 'draft') params.push('state=draft');
502
- // `state=draft` reads the raw draft row explicitly; the overlay flag is
503
- // redundant (and the dispatcher resolves `state` first), so skip it.
504
- else if (this.previewDrafts) params.push('preview=draft');
505
- if (options.packageId) params.push(`package=${encodeURIComponent(options.packageId)}`);
506
- const qs = params.length ? `?${params.join('&')}` : '';
507
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}${qs}`;
508
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
509
- if (res.status === 404) return null;
510
- if (!res.ok) throw await parseError(res);
511
- return (await res.json()) as T;
512
- }
513
-
514
- /**
515
- * Read the pending draft body for an item (`?state=draft`). Returns
516
- * `null` when there is no draft pending. Draft reads do NOT fall
517
- * back to the published overlay or the artifact registry — a `null`
518
- * unambiguously means "nothing to publish".
519
- *
520
- * Note: the framework wraps draft responses in an envelope
521
- * `{ type, name, item }` (matching `getMetaItem`); callers should
522
- * read `.item` to get the body. The legacy `get()` returns the
523
- * unwrapped body, so this method preserves that asymmetry by
524
- * returning whatever the server sent.
525
- */
526
- async getDraft<T = unknown>(
527
- type: string,
528
- name: string,
529
- options: { packageId?: string } = {},
530
- ): Promise<T | null> {
531
- return this.get<T>(type, name, { state: 'draft', ...(options.packageId ? { packageId: options.packageId } : {}) });
532
- }
533
-
534
- /**
535
- * Save (PUT) a metadata item. The framework accepts both the bare
536
- * item payload and the `{ item: ... }` / `{ metadata: ... }`
537
- * envelopes; we send bare for consistency. Pass `mode: 'draft'` to
538
- * stage the change without publishing (Studio's "Save" button).
539
- */
540
- async save<T = unknown>(
541
- type: string,
542
- name: string,
543
- item: unknown,
544
- options: MetadataClientSaveOptions = {},
545
- ): Promise<T> {
546
- if (!name || !String(name).trim()) {
547
- // The `PUT /meta/:type/:name` route rejects a missing `:name` segment
548
- // with 405. Fail with a clear contextual error at the call boundary
549
- // instead of firing a malformed request at the server (#2767).
550
- throw new Error(
551
- `MetadataClient.save: name must be non-empty (type="${type}").` +
552
- ' The PUT /meta/:type/:name route requires a name segment.',
553
- );
554
- }
555
- const params: string[] = [];
556
- if (options.force) params.push('force=true');
557
- if (options.mode === 'draft') params.push('mode=draft');
558
- if (options.packageId) params.push(`package=${encodeURIComponent(options.packageId)}`);
559
- const qs = params.length ? `?${params.join('&')}` : '';
560
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}${qs}`;
561
- const headers: Record<string, string> = {
562
- ...this.headers,
563
- 'Content-Type': 'application/json',
564
- };
565
- if (options.ifMatch) headers['If-Match'] = options.ifMatch;
566
- if (options.actor) headers['X-Actor'] = options.actor;
567
- const res = await this.fetchImpl(url, {
568
- method: 'PUT',
569
- headers,
570
- body: JSON.stringify(item),
571
- });
572
- if (!res.ok) throw await parseError(res);
573
- return (await res.json()) as T;
574
- }
575
-
576
- /**
577
- * Publish a single pending draft BY REFERENCE — promotes the draft row for
578
- * `(type, name)` into the active overlay and drops the draft. Works for ANY
579
- * draft, including ones with no `packageId` binding (which the package-scoped
580
- * `/packages/:id/publish-drafts` flow cannot reach). Use this to publish the
581
- * exact set returned by {@link listDrafts} without needing a package.
582
- *
583
- * Returns the server result. For `seed` drafts the protocol also materializes
584
- * the rows and reports under `seedApplied` — a data problem never fails the
585
- * publish, so callers should check `seedApplied?.success` and warn the user
586
- * rather than assume the data went live.
587
- */
588
- async publishDraft(
589
- type: string,
590
- name: string,
591
- ): Promise<{
592
- success?: boolean;
593
- seedApplied?: { success: boolean; inserted?: number; updated?: number; error?: string; errors?: unknown[] };
594
- } & Record<string, unknown>> {
595
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/publish`;
596
- const res = await this.fetchImpl(url, {
597
- method: 'POST',
598
- headers: { ...this.headers, 'Content-Type': 'application/json', Accept: 'application/json' },
599
- body: '{}',
600
- });
601
- if (!res.ok) throw await parseError(res);
602
- const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
603
- // Tolerate the dispatcher's `{ success, data: {...} }` envelope.
604
- const inner = (body as any)?.data && typeof (body as any).data === 'object' ? (body as any).data : body;
605
- return inner as any;
606
- }
607
-
608
- /**
609
- * Get the 3-state layered view of a metadata item (Phase 3a). Returns
610
- * `code` (the artifact / fallback default), `overlay` (the saved
611
- * customisation, if any), and `effective` (what the runtime sees).
612
- */
613
- async layered<T = unknown>(
614
- type: string,
615
- name: string,
616
- options: { packageId?: string } = {},
617
- ): Promise<MetadataLayered<T>> {
618
- const pkg = options.packageId ? `&package=${encodeURIComponent(options.packageId)}` : '';
619
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}?layers=true${pkg}`;
620
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
621
- if (res.status === 404) {
622
- return { code: null, overlay: null, overlayScope: null, effective: null };
623
- }
624
- if (!res.ok) throw await parseError(res);
625
- const body = (await res.json()) as MetadataLayered<T> & Record<string, unknown>;
626
- const hasEnvelope =
627
- body && (('code' in body) || ('overlay' in body) || ('effective' in body));
628
- if (!hasEnvelope) {
629
- return {
630
- code: null,
631
- overlay: null,
632
- overlayScope: null,
633
- effective: body as unknown as T,
634
- };
635
- }
636
- return {
637
- code: body.code ?? null,
638
- overlay: body.overlay ?? null,
639
- overlayScope: body.overlayScope ?? null,
640
- effective: body.effective ?? null,
641
- ...(body._diagnostics ? { _diagnostics: body._diagnostics as MetadataDiagnostics } : {}),
642
- // ADR-0010 Phase 4 — pass through the metadata-protection envelope so
643
- // the editor can render lock affordances without a second round trip.
644
- ...(body.lock !== undefined ? { lock: body.lock as MetadataLayered['lock'] } : {}),
645
- ...(body.lockReason !== undefined ? { lockReason: body.lockReason as string } : {}),
646
- ...(body.lockSource !== undefined ? { lockSource: body.lockSource as MetadataLayered['lockSource'] } : {}),
647
- ...(body.lockDocsUrl !== undefined ? { lockDocsUrl: body.lockDocsUrl as string } : {}),
648
- ...(body.provenance !== undefined ? { provenance: body.provenance as MetadataLayered['provenance'] } : {}),
649
- ...(body.packageId !== undefined ? { packageId: body.packageId as string } : {}),
650
- ...(body.packageVersion !== undefined ? { packageVersion: body.packageVersion as string } : {}),
651
- ...(body.editable !== undefined ? { editable: body.editable as boolean } : {}),
652
- ...(body.deletable !== undefined ? { deletable: body.deletable as boolean } : {}),
653
- ...(body.resettable !== undefined ? { resettable: body.resettable as boolean } : {}),
654
- };
655
- }
656
-
657
- /**
658
- * Cross-type sweep of load-time validation results — calls
659
- * `GET /meta/diagnostics`. Returns every entry the framework
660
- * considers invalid (or, when `severity: 'warning'`, also entries
661
- * with only warnings).
662
- *
663
- * Used by the Studio's governance overview page and by the
664
- * directory page to show "N invalid" badges per metadata type.
665
- */
666
- async diagnostics(
667
- options: MetadataDiagnosticsOptions = {},
668
- ): Promise<MetadataDiagnosticsSummary> {
669
- const params: string[] = [];
670
- if (options.type) params.push(`type=${encodeURIComponent(options.type)}`);
671
- if (options.severity) params.push(`severity=${encodeURIComponent(options.severity)}`);
672
- if (options.packageId) params.push(`package=${encodeURIComponent(options.packageId)}`);
673
- const qs = params.length ? `?${params.join('&')}` : '';
674
- const url = `${this.base}/diagnostics${qs}`;
675
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
676
- if (res.status === 404) {
677
- // Older server without the sweep endpoint — caller should treat
678
- // as "no diagnostics available", not as an error.
679
- return { entries: [], total: 0, scannedTypes: 0, scannedItems: 0, stats: {} };
680
- }
681
- if (!res.ok) throw await parseError(res);
682
- const data = (await res.json()) as Partial<MetadataDiagnosticsSummary>;
683
- return {
684
- entries: Array.isArray(data.entries) ? data.entries : [],
685
- total: typeof data.total === 'number' ? data.total : 0,
686
- scannedTypes: typeof data.scannedTypes === 'number' ? data.scannedTypes : 0,
687
- scannedItems: typeof data.scannedItems === 'number' ? data.scannedItems : 0,
688
- stats: data.stats && typeof data.stats === 'object' ? data.stats : {},
689
- };
690
- }
691
-
692
- /**
693
- * Find every metadata item that references this one (Phase 3a). Useful
694
- * for pre-delete impact analysis: "Are any views pointing at this
695
- * object before I drop it?".
696
- */
697
- async references(type: string, name: string): Promise<MetadataReference[]> {
698
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/references`;
699
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
700
- if (res.status === 404) return [];
701
- if (!res.ok) throw await parseError(res);
702
- const data = await res.json();
703
- return Array.isArray(data) ? (data as MetadataReference[]) : (data?.items ?? []);
704
- }
705
-
706
- /**
707
- * Reset a metadata customization overlay back to the artifact default.
708
- * Idempotent: returns the result even when no overlay row existed.
709
- * Pass `state: 'draft'` to discard the pending draft only (keeps the
710
- * published overlay intact) — useful for a Studio "Discard draft" button.
711
- */
712
- async reset<T = unknown>(
713
- type: string,
714
- name: string,
715
- options: MetadataDeleteOptions = {},
716
- ): Promise<T> {
717
- const qs = options.state === 'draft' ? '?state=draft' : '';
718
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}${qs}`;
719
- const headers: Record<string, string> = { ...this.headers };
720
- if (options.ifMatch) headers['If-Match'] = options.ifMatch;
721
- if (options.actor) headers['X-Actor'] = options.actor;
722
- const res = await this.fetchImpl(url, { method: 'DELETE', headers });
723
- if (!res.ok) throw await parseError(res);
724
- return (await res.json()) as T;
725
- }
726
-
727
- /**
728
- * Promote the pending draft of an item to the active overlay
729
- * (POST `/meta/:type/:name/publish`). Returns
730
- * `{ success, version, seq, message }`. Throws a `404 no_draft` if
731
- * nothing is pending and `409 metadata_conflict` if the published
732
- * overlay moved while the draft was sitting.
733
- */
734
- async publish<T = unknown>(
735
- type: string,
736
- name: string,
737
- options: { actor?: string; message?: string } = {},
738
- ): Promise<T> {
739
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/publish`;
740
- const headers: Record<string, string> = {
741
- ...this.headers,
742
- 'Content-Type': 'application/json',
743
- };
744
- if (options.actor) headers['X-Actor'] = options.actor;
745
- const res = await this.fetchImpl(url, {
746
- method: 'POST',
747
- headers,
748
- body: JSON.stringify(options.message ? { message: options.message } : {}),
749
- });
750
- if (!res.ok) throw await parseError(res);
751
- return (await res.json()) as T;
752
- }
753
-
754
- /**
755
- * Restore an item to a previous version (POST `/meta/:type/:name/rollback`).
756
- * The server reads the history row at `toVersion`, writes its body back
757
- * as the active overlay with `operation_type='revert'`. Returns
758
- * `{ success, version, seq, restoredFromVersion, message }`. Throws
759
- * `404 version_not_found` for unknown versions and `409 version_not_restorable`
760
- * when the target version is a delete tombstone.
761
- */
762
- async rollback<T = unknown>(
763
- type: string,
764
- name: string,
765
- toVersion: number,
766
- options: { actor?: string; message?: string } = {},
767
- ): Promise<T> {
768
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/rollback`;
769
- const headers: Record<string, string> = {
770
- ...this.headers,
771
- 'Content-Type': 'application/json',
772
- };
773
- if (options.actor) headers['X-Actor'] = options.actor;
774
- const res = await this.fetchImpl(url, {
775
- method: 'POST',
776
- headers,
777
- body: JSON.stringify({
778
- toVersion,
779
- ...(options.message ? { message: options.message } : {}),
780
- }),
781
- });
782
- if (!res.ok) throw await parseError(res);
783
- return (await res.json()) as T;
784
- }
785
-
786
- /**
787
- * Compute a structured top-level key diff between two history versions
788
- * (GET `/meta/:type/:name/diff?from=&to=`). Returns
789
- * `{ added, removed, changed }` where each entry carries a `path` and
790
- * the relevant value(s). Useful for "what changed in this draft?" and
791
- * pre-rollback previews.
792
- */
793
- async diff<T = unknown>(
794
- type: string,
795
- name: string,
796
- fromVersion?: number,
797
- toVersion?: number,
798
- ): Promise<T> {
799
- const params = new URLSearchParams();
800
- if (fromVersion !== undefined) params.set('from', String(fromVersion));
801
- if (toVersion !== undefined) params.set('to', String(toVersion));
802
- const qs = params.toString();
803
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/diff${qs ? `?${qs}` : ''}`;
804
- const res = await this.fetchImpl(url, {
805
- method: 'GET',
806
- headers: this.headers,
807
- cache: 'no-store',
808
- });
809
- if (!res.ok) throw await parseError(res);
810
- return (await res.json()) as T;
811
- }
812
-
813
- /** Fetch the durable history (change log) for one metadata item. */
814
- async history<T = unknown>(
815
- type: string,
816
- name: string,
817
- options: MetadataHistoryOptions = {},
818
- ): Promise<T> {
819
- const params = new URLSearchParams();
820
- if (options.sinceSeq !== undefined) params.set('sinceSeq', String(options.sinceSeq));
821
- if (options.limit !== undefined) params.set('limit', String(options.limit));
822
- const qs = params.toString();
823
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/history${qs ? `?${qs}` : ''}`;
824
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
825
- if (!res.ok) throw await parseError(res);
826
- return (await res.json()) as T;
827
- }
828
-
829
- /**
830
- * Fetch the protection-audit trail for one metadata item
831
- * (ADR-0010 §3.6 / Phase 4.1). Shows every save/publish/rollback/
832
- * delete/reset attempt — allowed, denied, or forced — so the
833
- * Studio "审计日志 / Audit log" tab can render who tried what
834
- * and whether a lock blocked it.
835
- */
836
- async audit(
837
- type: string,
838
- name: string,
839
- options: { limit?: number } = {},
840
- ): Promise<MetadataAuditResponse> {
841
- const params = new URLSearchParams();
842
- if (options.limit !== undefined) params.set('limit', String(options.limit));
843
- const qs = params.toString();
844
- const url = `${this.base}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/audit${qs ? `?${qs}` : ''}`;
845
- const res = await this.fetchImpl(url, { method: 'GET', headers: this.headers, cache: 'no-store' });
846
- if (!res.ok) throw await parseError(res);
847
- return (await res.json()) as MetadataAuditResponse;
848
- }
849
- }