|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #5745 — conformance gate: the body `saveMetaItem` really returns must parse |
| 5 | + * through `SaveMetaItemResponseSchema` with NOTHING stripped. |
| 6 | + * |
| 7 | + * This is the producer side of the declaration. The spec-side suite |
| 8 | + * (`packages/spec/src/api/protocol.test.ts`) pins what the schema says; this |
| 9 | + * one pins that the schema still matches what the code emits, driving the REAL |
| 10 | + * protocol against a REAL ObjectQL engine. The two together are what makes |
| 11 | + * "declared = returned" checkable — a future field added to the response, or an |
| 12 | + * existing one dropped, turns this red instead of silently vanishing at parse. |
| 13 | + * |
| 14 | + * Why the REST layer needs no separate case: the route hands this exact object |
| 15 | + * to `res.json()` verbatim (`rest-server.ts`, `PUT /meta/:type/:name`), so the |
| 16 | + * protocol return IS the wire body. |
| 17 | + * |
| 18 | + * Before the #5745 declaration this file's first assertion was red in a |
| 19 | + * specific, quiet way: `safeParse` SUCCEEDED and `version` / `seq` / `state` |
| 20 | + * were dropped from the parsed result, so the "stripped keys" set was |
| 21 | + * non-empty. That is the direction it must never drift back to. |
| 22 | + */ |
| 23 | +import { describe, it, expect } from 'vitest'; |
| 24 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 25 | +import { SaveMetaItemResponseSchema } from '@objectstack/spec/api'; |
| 26 | +import { ObjectQL } from './engine.js'; |
| 27 | + |
| 28 | +const sysMetadataObject = { |
| 29 | + name: 'sys_metadata', |
| 30 | + label: 'System Metadata', |
| 31 | + fields: { |
| 32 | + id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true }, |
| 33 | + type: { name: 'type', label: 'Type', type: 'text' as const, required: true }, |
| 34 | + name: { name: 'name', label: 'Name', type: 'text' as const, required: true }, |
| 35 | + organization_id: { name: 'organization_id', label: 'Org', type: 'text' as const }, |
| 36 | + metadata: { name: 'metadata', label: 'Body', type: 'longtext' as const }, |
| 37 | + checksum: { name: 'checksum', label: 'Checksum', type: 'text' as const, maxLength: 71 }, |
| 38 | + state: { name: 'state', label: 'State', type: 'text' as const }, |
| 39 | + version: { name: 'version', label: 'Version', type: 'number' as const }, |
| 40 | + created_at: { name: 'created_at', label: 'Created', type: 'datetime' as const }, |
| 41 | + updated_at: { name: 'updated_at', label: 'Updated', type: 'datetime' as const }, |
| 42 | + }, |
| 43 | +}; |
| 44 | + |
| 45 | +function makeMemoryDriver() { |
| 46 | + const stores = new Map<string, Map<string, Record<string, unknown>>>(); |
| 47 | + const storeFor = (obj: string) => { |
| 48 | + let s = stores.get(obj); |
| 49 | + if (!s) { s = new Map(); stores.set(obj, s); } |
| 50 | + return s; |
| 51 | + }; |
| 52 | + let nextId = 0; |
| 53 | + const matchesWhere = (row: Record<string, unknown>, where: any): boolean => { |
| 54 | + if (!where || typeof where !== 'object') return true; |
| 55 | + if (Array.isArray(where.$and)) return where.$and.every((w: any) => matchesWhere(row, w)); |
| 56 | + if (Array.isArray(where.$or)) return where.$or.some((w: any) => matchesWhere(row, w)); |
| 57 | + for (const [k, v] of Object.entries(where)) { |
| 58 | + if (k.startsWith('$')) continue; |
| 59 | + const rowVal = row[k]; |
| 60 | + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; |
| 61 | + const a = rowVal === undefined ? null : rowVal; |
| 62 | + const b = expected === undefined ? null : expected; |
| 63 | + if (a !== b) return false; |
| 64 | + } |
| 65 | + return true; |
| 66 | + }; |
| 67 | + const driver: any = { |
| 68 | + name: 'memory', version: '0.0.0', supports: {} as any, |
| 69 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, |
| 70 | + async execute() { return null; }, |
| 71 | + async find(object: string, ast: any) { |
| 72 | + return Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); |
| 73 | + }, |
| 74 | + async findOne(object: string, ast: any) { |
| 75 | + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; |
| 76 | + return null; |
| 77 | + }, |
| 78 | + async create(object: string, data: Record<string, unknown>) { |
| 79 | + nextId += 1; |
| 80 | + const id = (data.id as string) ?? `r_${nextId}`; |
| 81 | + const row = { ...data, id }; |
| 82 | + storeFor(object).set(id, row); |
| 83 | + return row; |
| 84 | + }, |
| 85 | + async update(object: string, id: string, data: Record<string, unknown>) { |
| 86 | + const s = storeFor(object); |
| 87 | + const cur = s.get(id); |
| 88 | + if (!cur) throw new Error(`not found: ${object}/${id}`); |
| 89 | + const updated = { ...cur, ...data, id }; |
| 90 | + s.set(id, updated); |
| 91 | + return updated; |
| 92 | + }, |
| 93 | + async upsert(object: string, data: Record<string, unknown>) { |
| 94 | + const id = data.id as string | undefined; |
| 95 | + if (id && storeFor(object).has(id)) return this.update(object, id, data); |
| 96 | + return this.create(object, data); |
| 97 | + }, |
| 98 | + async delete(object: string, id: string) { return storeFor(object).delete(id); }, |
| 99 | + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, |
| 100 | + async bulkCreate(object: string, rows: Record<string, unknown>[]) { |
| 101 | + return Promise.all(rows.map((r) => this.create(object, r))); |
| 102 | + }, |
| 103 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 104 | + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, |
| 105 | + async commit() {}, async rollback() {}, |
| 106 | + }; |
| 107 | + return { driver, stores }; |
| 108 | +} |
| 109 | + |
| 110 | +async function makeProtocol() { |
| 111 | + const engine = new ObjectQL(); |
| 112 | + const { driver } = makeMemoryDriver(); |
| 113 | + engine.registerDriver(driver, true); |
| 114 | + await engine.init(); |
| 115 | + engine.registry.registerObject(sysMetadataObject as any); |
| 116 | + return new ObjectStackProtocolImplementation(engine); |
| 117 | +} |
| 118 | + |
| 119 | +const LOG = (...a: any[]) => appendFileSync(OUT, a.join(' ') + '\n'); |
| 120 | + |
| 121 | +const viewBody = (label: string) => ({ name: 'cases', type: 'grid', label, columns: ['id'] }); |
| 122 | + |
| 123 | +/** Keys the producer emitted that the schema refused to carry through. */ |
| 124 | +function strippedKeys(raw: Record<string, unknown>): string[] { |
| 125 | + const parsed = SaveMetaItemResponseSchema.parse(raw) as Record<string, unknown>; |
| 126 | + return Object.keys(raw).filter((k) => !(k in parsed)); |
| 127 | +} |
| 128 | + |
| 129 | +describe('saveMetaItem response conforms to SaveMetaItemResponseSchema (#5745)', () => { |
| 130 | + it('publish-mode save: parses green and strips nothing', async () => { |
| 131 | + const p = await makeProtocol(); |
| 132 | + const raw: any = await p.saveMetaItem({ |
| 133 | + type: 'view', name: 'cases', organizationId: 'org_x', item: viewBody('A'), |
| 134 | + }); |
| 135 | + |
| 136 | + expect(strippedKeys(raw)).toEqual([]); |
| 137 | + const parsed = SaveMetaItemResponseSchema.parse(raw); |
| 138 | + expect(parsed.success).toBe(true); |
| 139 | + expect(parsed.state).toBe('active'); |
| 140 | + expect(parsed.seq).toBe(1); |
| 141 | + // The ADR-0008 OCC token survives parse — this is the value a caller |
| 142 | + // echoes back as `If-Match` on the next write to this item. |
| 143 | + expect(parsed.version).toBe(raw.version); |
| 144 | + expect(typeof parsed.version).toBe('string'); |
| 145 | + }); |
| 146 | + |
| 147 | + it('draft-mode save: state is "draft" and still strips nothing', async () => { |
| 148 | + const p = await makeProtocol(); |
| 149 | + const raw: any = await p.saveMetaItem({ |
| 150 | + type: 'view', name: 'cases', organizationId: 'org_x', item: viewBody('D'), mode: 'draft', |
| 151 | + }); |
| 152 | + |
| 153 | + expect(strippedKeys(raw)).toEqual([]); |
| 154 | + expect(SaveMetaItemResponseSchema.parse(raw).state).toBe('draft'); |
| 155 | + }); |
| 156 | + |
| 157 | + it('with an ADR-0094 projector registered: projectionApplied is carried through', async () => { |
| 158 | + const p = await makeProtocol(); |
| 159 | + p.registerMutationProjector('view', async () => { throw new Error('boom-from-projector'); }); |
| 160 | + |
| 161 | + const raw: any = await p.saveMetaItem({ |
| 162 | + type: 'view', name: 'cases', organizationId: 'org_x', item: viewBody('P'), |
| 163 | + }); |
| 164 | + |
| 165 | + expect(Object.keys(raw)).toContain('projectionApplied'); |
| 166 | + expect(strippedKeys(raw)).toEqual([]); |
| 167 | + const parsed = SaveMetaItemResponseSchema.parse(raw); |
| 168 | + // Best-effort by contract: the projector threw, the write still succeeded, |
| 169 | + // and the failure is reported here rather than as a non-200. |
| 170 | + expect(parsed.success).toBe(true); |
| 171 | + expect(parsed.projectionApplied).toEqual({ success: false, error: 'boom-from-projector' }); |
| 172 | + }); |
| 173 | + |
| 174 | + it('no projector registered → projectionApplied is absent, which is why it alone is optional', async () => { |
| 175 | + const p = await makeProtocol(); |
| 176 | + const raw: any = await p.saveMetaItem({ |
| 177 | + type: 'view', name: 'cases', organizationId: 'org_x', item: viewBody('N'), |
| 178 | + }); |
| 179 | + |
| 180 | + expect(raw.projectionApplied).toBeUndefined(); |
| 181 | + expect(SaveMetaItemResponseSchema.safeParse(raw).success).toBe(true); |
| 182 | + }); |
| 183 | + |
| 184 | + it('version / seq / state are required because no reachable success return omits them', async () => { |
| 185 | + // `saveMetaItem` now has exactly ONE success return — the repository |
| 186 | + // write path — and it always sets all three. The shape that carried |
| 187 | + // none of them was the legacy raw-engine return, deleted in #5264 / |
| 188 | + // PR #5782 after being proved unreachable; the gate that made it |
| 189 | + // unreachable is the one exercised here, and it is still what keeps a |
| 190 | + // second, receipt-less write path from appearing. A type declaring |
| 191 | + // neither `allowOrgOverride` nor `allowRuntimeCreate` (`agent`, `job`) |
| 192 | + // is refused outright rather than persisted without a receipt. |
| 193 | + // |
| 194 | + // This is the tripwire for the `required` decision: if that gate is |
| 195 | + // ever relaxed so such a type is written some other way, whatever |
| 196 | + // receipt that path returns has to be re-measured before these three |
| 197 | + // fields can stay required. |
| 198 | + const p = await makeProtocol(); |
| 199 | + await expect( |
| 200 | + p.saveMetaItem({ type: 'agent', name: 'helper', organizationId: 'org_x', item: { name: 'helper' } }), |
| 201 | + ).rejects.toMatchObject({ code: 'NOT_CREATABLE', status: 403 }); |
| 202 | + }); |
| 203 | +}); |
0 commit comments