|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, expect, it } from 'vitest'; |
| 4 | +import { ObjectStackProtocolImplementation } from './protocol.js'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Regression for #3115 — `publish-drafts` fails with `no_draft` after saving a |
| 8 | + * draft via Studio UI. |
| 9 | + * |
| 10 | + * Root cause (a cross-layer org-scope asymmetry): |
| 11 | + * |
| 12 | + * • Studio's "Save Draft" goes through REST `PUT /meta/:type/:name?mode=draft`, |
| 13 | + * which does NOT thread the session's `activeOrganizationId` into |
| 14 | + * `saveMetaItem` — so the draft row is written env-wide |
| 15 | + * (`organization_id = NULL`). |
| 16 | + * • "Publish" goes through `POST /packages/:id/publish-drafts`, which DOES |
| 17 | + * resolve `activeOrganizationId` (non-null when the session carries a |
| 18 | + * default org) and passes it to `publishPackageDrafts`. |
| 19 | + * • `listDrafts` was taught (PR #1852) to surface env-wide drafts to a |
| 20 | + * non-null-org caller via `$or [{org}, {org IS NULL}]`, so the Publish CTA |
| 21 | + * appears — but `promoteDraft` still looked the draft up with a STRICT |
| 22 | + * `organization_id = <org>` equality and 404'd (`no_draft`) on the |
| 23 | + * env-wide row it could never match. |
| 24 | + * |
| 25 | + * The fix promotes each listed draft in the org scope it actually lives in |
| 26 | + * (the scope `listDrafts` surfaced it from), so the pending-changes list and |
| 27 | + * the publish path agree. |
| 28 | + * |
| 29 | + * These tests exercise the REAL `listDrafts` + `promoteDraft` interaction |
| 30 | + * against a faithful multi-table stub engine (honours `$or` and |
| 31 | + * `organization_id IS NULL`), reproducing the exact save-env-wide / |
| 32 | + * publish-under-org mismatch. |
| 33 | + */ |
| 34 | + |
| 35 | +interface Row { |
| 36 | + id: string; |
| 37 | + type: string; |
| 38 | + name: string; |
| 39 | + organization_id: string | null; |
| 40 | + package_id: string | null; |
| 41 | + state: string; |
| 42 | + metadata: string; |
| 43 | + checksum?: string; |
| 44 | + version?: number; |
| 45 | + updated_at?: string; |
| 46 | + created_at?: string; |
| 47 | +} |
| 48 | + |
| 49 | +interface HistoryRow { |
| 50 | + id: string; |
| 51 | + event_seq: number; |
| 52 | + name: string; |
| 53 | + type: string; |
| 54 | + version: number; |
| 55 | + operation_type: string; |
| 56 | + metadata: string | null; |
| 57 | + checksum: string | null; |
| 58 | + previous_checksum: string | null; |
| 59 | + change_note?: string | null; |
| 60 | + source?: string | null; |
| 61 | + organization_id: string | null; |
| 62 | + recorded_by?: string | null; |
| 63 | + recorded_at: string; |
| 64 | +} |
| 65 | + |
| 66 | +// Overlay rows are keyed by (type, name, org, state, package_id) — the ADR-0048 |
| 67 | +// key — so an env-wide draft and an org-scoped active row for the same identity |
| 68 | +// can coexist without colliding. |
| 69 | +function keyOf(w: Record<string, unknown>) { |
| 70 | + return `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; |
| 71 | +} |
| 72 | + |
| 73 | +/** Does row `r` satisfy `where` (top-level eq + `$or` + `organization_id IS NULL`)? */ |
| 74 | +function matchesMetadataWhere(r: Row, where: Record<string, unknown>): boolean { |
| 75 | + for (const [k, v] of Object.entries(where)) { |
| 76 | + if (k === '$or') { |
| 77 | + const clauses = v as Array<Record<string, unknown>>; |
| 78 | + if (!clauses.some((c) => matchesMetadataWhere(r, c))) return false; |
| 79 | + continue; |
| 80 | + } |
| 81 | + // `undefined` = "dimension not constrained"; `null` = "must be NULL". |
| 82 | + if (v === undefined) continue; |
| 83 | + if ((r as any)[k] !== v) return false; |
| 84 | + } |
| 85 | + return true; |
| 86 | +} |
| 87 | + |
| 88 | +function makeStubEngine() { |
| 89 | + const rows = new Map<string, Row>(); |
| 90 | + const historyRows: HistoryRow[] = []; |
| 91 | + let nextId = 0; |
| 92 | + |
| 93 | + const findRow = (w: Record<string, unknown>): { key: string; row: Row } | null => { |
| 94 | + if (w.id !== undefined) { |
| 95 | + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; |
| 96 | + return null; |
| 97 | + } |
| 98 | + // Exact-key lookups (findOne on a fully-qualified ref). When package_id |
| 99 | + // is not part of the where (promote's whereFor omits it → "match any |
| 100 | + // package"), fall back to a scan. |
| 101 | + if (w.package_id !== undefined) { |
| 102 | + const k = keyOf(w); |
| 103 | + const r = rows.get(k); |
| 104 | + return r ? { key: k, row: r } : null; |
| 105 | + } |
| 106 | + for (const [k, r] of rows) if (matchesMetadataWhere(r, w)) return { key: k, row: r }; |
| 107 | + return null; |
| 108 | + }; |
| 109 | + |
| 110 | + const matchesHistory = (h: HistoryRow, w: Record<string, unknown>): boolean => { |
| 111 | + if (w.organization_id !== undefined && h.organization_id !== w.organization_id) return false; |
| 112 | + if (w.type !== undefined && h.type !== w.type) return false; |
| 113 | + if (w.name !== undefined && h.name !== w.name) return false; |
| 114 | + if (w.version !== undefined && h.version !== w.version) return false; |
| 115 | + if (w.operation_type !== undefined && h.operation_type !== w.operation_type) return false; |
| 116 | + return true; |
| 117 | + }; |
| 118 | + |
| 119 | + const engine: any = { |
| 120 | + async findOne(table: string, opts: { where: Record<string, unknown> }) { |
| 121 | + if (table === 'sys_metadata_history') { |
| 122 | + return historyRows.find((h) => matchesHistory(h, opts.where)) ?? null; |
| 123 | + } |
| 124 | + return findRow(opts.where)?.row ?? null; |
| 125 | + }, |
| 126 | + async find(table: string, opts: { where: Record<string, unknown> }) { |
| 127 | + if (table === 'sys_metadata_history') { |
| 128 | + return historyRows.filter((h) => matchesHistory(h, opts.where)); |
| 129 | + } |
| 130 | + return Array.from(rows.values()).filter((r) => matchesMetadataWhere(r, opts.where)); |
| 131 | + }, |
| 132 | + async insert(table: string, data: Record<string, unknown>) { |
| 133 | + if (table === 'sys_metadata_audit') return { id: 'audit_skip' }; |
| 134 | + if (table === 'sys_metadata_history') { |
| 135 | + nextId += 1; |
| 136 | + const h: HistoryRow = { id: `h_${nextId}`, ...(data as any) }; |
| 137 | + historyRows.push(h); |
| 138 | + return { id: h.id }; |
| 139 | + } |
| 140 | + nextId += 1; |
| 141 | + const row = { id: `r_${nextId}`, ...(data as any) } as Row; |
| 142 | + rows.set(keyOf(data), row); |
| 143 | + return { id: row.id }; |
| 144 | + }, |
| 145 | + async update(_t: string, data: Record<string, unknown>, opts: { where: Record<string, unknown> }) { |
| 146 | + const found = findRow(opts.where); |
| 147 | + if (!found) return { id: null }; |
| 148 | + const merged = { ...found.row, ...(data as any) }; |
| 149 | + rows.delete(found.key); |
| 150 | + rows.set(keyOf(merged), merged); |
| 151 | + return { id: found.row.id }; |
| 152 | + }, |
| 153 | + async delete(_t: string, opts: { where: Record<string, unknown> }) { |
| 154 | + const found = findRow(opts.where); |
| 155 | + if (!found) return { deleted: 0 }; |
| 156 | + rows.delete(found.key); |
| 157 | + return { deleted: 1 }; |
| 158 | + }, |
| 159 | + async transaction<T>(cb: (ctx: any) => Promise<T>): Promise<T> { |
| 160 | + return cb(undefined); |
| 161 | + }, |
| 162 | + registry: { |
| 163 | + registerItem: () => {}, |
| 164 | + registerObject: () => {}, |
| 165 | + // No declared package namespace → publishPackageDrafts skips the |
| 166 | + // ADR-0028 prefix check (legacy-grandfathered path). |
| 167 | + getPackage: () => undefined, |
| 168 | + }, |
| 169 | + }; |
| 170 | + return { engine, rows, historyRows }; |
| 171 | +} |
| 172 | + |
| 173 | +const objectBody = (name: string) => ({ |
| 174 | + name, |
| 175 | + label: 'Project Task', |
| 176 | + fields: { |
| 177 | + title: { type: 'text', label: 'Title' }, |
| 178 | + done: { type: 'boolean', label: 'Done' }, |
| 179 | + }, |
| 180 | +}); |
| 181 | + |
| 182 | +describe('publishPackageDrafts — env-wide draft under a non-null active org (#3115)', () => { |
| 183 | + it('saves the object draft env-wide (organization_id = NULL) when no org is threaded', async () => { |
| 184 | + const { engine, rows } = makeStubEngine(); |
| 185 | + const protocol = new ObjectStackProtocolImplementation(engine); |
| 186 | + |
| 187 | + // Mirrors REST `PUT /meta/object/proj_task?mode=draft&package=app.projects` |
| 188 | + // — package bound, but no organizationId threaded. |
| 189 | + await protocol.saveMetaItem({ |
| 190 | + type: 'object', |
| 191 | + name: 'proj_task', |
| 192 | + item: objectBody('proj_task'), |
| 193 | + packageId: 'app.projects', |
| 194 | + mode: 'draft', |
| 195 | + }); |
| 196 | + |
| 197 | + const draftRows = Array.from(rows.values()).filter((r) => r.state === 'draft'); |
| 198 | + expect(draftRows).toHaveLength(1); |
| 199 | + expect(draftRows[0].organization_id).toBeNull(); |
| 200 | + expect(draftRows[0].package_id).toBe('app.projects'); |
| 201 | + }); |
| 202 | + |
| 203 | + it('publishes the env-wide draft even though the session carries a non-null active org', async () => { |
| 204 | + const { engine, rows } = makeStubEngine(); |
| 205 | + const protocol = new ObjectStackProtocolImplementation(engine); |
| 206 | + |
| 207 | + // 1. Studio "Save Draft" — env-wide (no active org threaded). |
| 208 | + await protocol.saveMetaItem({ |
| 209 | + type: 'object', |
| 210 | + name: 'proj_task', |
| 211 | + item: objectBody('proj_task'), |
| 212 | + packageId: 'app.projects', |
| 213 | + mode: 'draft', |
| 214 | + }); |
| 215 | + |
| 216 | + // 2. Studio "Publish" — the dispatcher resolved a non-null active org. |
| 217 | + const res = await protocol.publishPackageDrafts({ |
| 218 | + packageId: 'app.projects', |
| 219 | + organizationId: 'org_alpha', |
| 220 | + }); |
| 221 | + |
| 222 | + // Before the fix this returned { success:false, failedCount:1, |
| 223 | + // failed:[{ code:'no_draft' }] }. |
| 224 | + expect(res.failed).toEqual([]); |
| 225 | + expect(res).toMatchObject({ success: true, publishedCount: 1, failedCount: 0 }); |
| 226 | + expect(res.published.map((p) => p.name)).toEqual(['proj_task']); |
| 227 | + |
| 228 | + // The draft was consumed and the active row landed env-wide |
| 229 | + // (package-owned metadata is env-level, not per-org). |
| 230 | + const remaining = Array.from(rows.values()); |
| 231 | + expect(remaining.filter((r) => r.state === 'draft')).toHaveLength(0); |
| 232 | + const active = remaining.filter((r) => r.state === 'active'); |
| 233 | + expect(active).toHaveLength(1); |
| 234 | + expect(active[0].organization_id).toBeNull(); |
| 235 | + }); |
| 236 | + |
| 237 | + it('still publishes an org-scoped draft under that same org (no regression)', async () => { |
| 238 | + const { engine, rows } = makeStubEngine(); |
| 239 | + const protocol = new ObjectStackProtocolImplementation(engine); |
| 240 | + |
| 241 | + // A per-org overlay draft (organization_id = org_alpha). |
| 242 | + await protocol.saveMetaItem({ |
| 243 | + type: 'object', |
| 244 | + name: 'proj_task', |
| 245 | + item: objectBody('proj_task'), |
| 246 | + organizationId: 'org_alpha', |
| 247 | + packageId: 'app.projects', |
| 248 | + mode: 'draft', |
| 249 | + }); |
| 250 | + |
| 251 | + const res = await protocol.publishPackageDrafts({ |
| 252 | + packageId: 'app.projects', |
| 253 | + organizationId: 'org_alpha', |
| 254 | + }); |
| 255 | + |
| 256 | + expect(res).toMatchObject({ success: true, publishedCount: 1, failedCount: 0 }); |
| 257 | + const active = Array.from(rows.values()).filter((r) => r.state === 'active'); |
| 258 | + expect(active).toHaveLength(1); |
| 259 | + expect(active[0].organization_id).toBe('org_alpha'); |
| 260 | + }); |
| 261 | +}); |
0 commit comments