|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * #22994: `AppPlugin` registers the ADR-0087 forward-converted copy of EVERY |
| 5 | + * collection, not only the security ones (#12844), and it converts once. |
| 6 | + * |
| 7 | + * The seam is `AppPlugin.init()`'s `manifest.register(...)`. It decomposes the |
| 8 | + * bundle into the ObjectQL registry over `METADATA_ARRAY_KEYS`, and that |
| 9 | + * registry is the code layer of the flattened list, the list |
| 10 | + * `GET /meta/<type>` serves and that `getMetaItemsForExecution` hands to the |
| 11 | + * email loader. It used to be handed the RAW bundle. On the artifact boot |
| 12 | + * (`createStandaloneStack`, the composition `os dev -a` runs) the door, |
| 13 | + * `MetadataPlugin`, registers the converted copy into the metadata service, so |
| 14 | + * `GET /meta/<type>/NAME` served that copy while the list served the raw one. |
| 15 | + * Measured before this change, on `origin/main`, for the artifact below: |
| 16 | + * |
| 17 | + * list dashboard/ops_board refreshInterval: 300 _diagnostics.valid: false |
| 18 | + * item dashboard/ops_board refreshIntervalSeconds: 300 _diagnostics.valid: true |
| 19 | + * execution face refreshInterval: 300 |
| 20 | + * |
| 21 | + * The second type is `dashboard`, converted by the major-18 retired entry |
| 22 | + * `dashboard-refresh-interval-to-refresh-interval-seconds` (retiredAfter |
| 23 | + * 17.3.0). It sits beside `emailTemplates`, the card's own type. That type has |
| 24 | + * no conversion on this tree: its `category` / `isSystem` retirement is a |
| 25 | + * separate change. So its legs below assert the contract (the registry |
| 26 | + * holds the conversion's OUTPUT, and that output passes the email loader's own |
| 27 | + * parse). That contract has no retired key to bite on here, and it does the |
| 28 | + * day a retirement of that type lands. |
| 29 | + * |
| 30 | + * Out of scope, on purpose: the PARSE axis. The door strict-parses (schema |
| 31 | + * defaults, ADR-0122 transforms), and the registry copy does not. So the item |
| 32 | + * read can carry keys the listed copy lacks (an email template's |
| 33 | + * `variables: []` / `active: true`). The list pins below therefore assert |
| 34 | + * "every key the list serves is the key the item read serves", never "the two |
| 35 | + * are one document". Unifying them is a route-ownership question (#12892), |
| 36 | + * not this conversion. |
| 37 | + */ |
| 38 | + |
| 39 | +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; |
| 40 | +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; |
| 41 | +import { tmpdir } from 'node:os'; |
| 42 | +import { join } from 'node:path'; |
| 43 | +import { applyArtifactForwardConversions } from '@objectstack/metadata-core'; |
| 44 | +import { stripReadDecorations } from '@objectstack/spec/kernel'; |
| 45 | +import { EmailTemplateDefinitionSchema } from '@objectstack/spec/system'; |
| 46 | +import { Runtime } from './runtime.js'; |
| 47 | +import { AppPlugin } from './app-plugin.js'; |
| 48 | +import { createStandaloneStack } from './standalone-stack.js'; |
| 49 | + |
| 50 | +// [#10126] Pay the first transform of these dist-resolved workspace deps at |
| 51 | +// MODULE LOAD: the factory and the kernel boot below import them lazily, inside |
| 52 | +// a clocked hook (`scripts/check-test-source-alias.mjs`, the clocked-window rule). |
| 53 | +import '@objectstack/metadata'; |
| 54 | +import '@objectstack/objectql'; |
| 55 | +import '@objectstack/service-datasource'; |
| 56 | + |
| 57 | +const APP_ID = 'com.test.issue-22994'; |
| 58 | +const STAMPS = { _packageId: APP_ID, _packageVersion: '1.0.0', _provenance: 'package' } as const; |
| 59 | + |
| 60 | +/** A dashboard carrying the retired `refreshInterval` spelling. */ |
| 61 | +const RETIRED_DASHBOARD = { name: 'ops_board', label: 'Ops Board', widgets: [], refreshInterval: 300 }; |
| 62 | +/** What a 17.x parse emitted for an email template: both defaulted keys present. */ |
| 63 | +const EMAIL_TEMPLATE = { |
| 64 | + name: 'probe.welcome', |
| 65 | + label: 'Welcome', |
| 66 | + locale: 'en-US', |
| 67 | + subject: 'Welcome', |
| 68 | + bodyHtml: '<p>Hi</p>', |
| 69 | + category: 'custom', |
| 70 | + isSystem: false, |
| 71 | +}; |
| 72 | + |
| 73 | +/** |
| 74 | + * The card's reproduction shape: an UNDECLARED-engines artifact, so the |
| 75 | + * window opens (`converted-undeclared`) at the door and here alike. |
| 76 | + */ |
| 77 | +const RETIRED_ARTIFACT = { |
| 78 | + manifest: { id: APP_ID, name: 'Converted Collections Probe', type: 'app', version: '1.0.0' }, |
| 79 | + dashboards: [RETIRED_DASHBOARD], |
| 80 | + emailTemplates: [EMAIL_TEMPLATE], |
| 81 | +}; |
| 82 | + |
| 83 | +/** The CONTROL: the same app authored in the current spellings. Nothing to convert. */ |
| 84 | +const CURRENT_DASHBOARD = { name: 'ops_board', label: 'Ops Board', widgets: [], refreshIntervalSeconds: 300 }; |
| 85 | +const CURRENT_EMAIL_TEMPLATE = { name: 'probe.welcome', label: 'Welcome', locale: 'en-US', subject: 'Welcome', bodyHtml: '<p>Hi</p>' }; |
| 86 | +const CURRENT_ARTIFACT = { |
| 87 | + manifest: { id: APP_ID, name: 'Converted Collections Probe', type: 'app', version: '1.0.0' }, |
| 88 | + dashboards: [CURRENT_DASHBOARD], |
| 89 | + emailTemplates: [CURRENT_EMAIL_TEMPLATE], |
| 90 | +}; |
| 91 | + |
| 92 | +const BOOT_TIMEOUT = 120_000; |
| 93 | + |
| 94 | +/** Fresh bytes per reader: readers stamp and normalize what they are handed. */ |
| 95 | +const copy = <T>(value: T): T => JSON.parse(JSON.stringify(value)); |
| 96 | + |
| 97 | +/** `item` minus the read-side `_diagnostics` badge, which only the served reads add. */ |
| 98 | +function undiagnosed(item: Record<string, unknown>): Record<string, unknown> { |
| 99 | + const { _diagnostics: _ignored, ...rest } = item; |
| 100 | + return rest; |
| 101 | +} |
| 102 | + |
| 103 | +/** The authored item as the conversion rewrites it: the policy function's own answer. */ |
| 104 | +function convertedAuthored(collection: 'dashboards' | 'emailTemplates', name: string): Record<string, unknown> { |
| 105 | + const result = applyArtifactForwardConversions(copy(RETIRED_ARTIFACT) as Record<string, unknown>); |
| 106 | + const items = (result.definition as Record<string, Array<Record<string, unknown>>>)[collection]; |
| 107 | + const item = items.find((i) => i.name === name); |
| 108 | + if (!item) throw new Error(`the conversion lost ${collection}/${name}`); |
| 109 | + return item; |
| 110 | +} |
| 111 | + |
| 112 | +interface BootedArtifact { |
| 113 | + kernel: any; |
| 114 | + dir: string; |
| 115 | +} |
| 116 | + |
| 117 | +/** Boot the card's composition over `artifact`, the way `os dev -a` composes it. */ |
| 118 | +async function bootArtifact(tag: string, artifact: unknown): Promise<BootedArtifact> { |
| 119 | + const dir = mkdtempSync(join(tmpdir(), `os-22994-${tag}-`)); |
| 120 | + const artifactPath = join(dir, 'objectstack.json'); |
| 121 | + writeFileSync(artifactPath, JSON.stringify(artifact), 'utf-8'); |
| 122 | + const stack = await createStandaloneStack({ |
| 123 | + artifactPath, |
| 124 | + projectRoot: dir, |
| 125 | + databaseUrl: ':memory:', |
| 126 | + skipSeedData: true, |
| 127 | + runPlatformMigrations: false, |
| 128 | + }); |
| 129 | + const runtime = new Runtime({ cluster: false }); |
| 130 | + const kernel = runtime.getKernel(); |
| 131 | + for (const p of stack.plugins) await kernel.use(p as any); |
| 132 | + await kernel.bootstrap(); |
| 133 | + return { kernel, dir }; |
| 134 | +} |
| 135 | + |
| 136 | +async function teardown(booted: BootedArtifact | undefined): Promise<void> { |
| 137 | + if (!booted) return; |
| 138 | + try { await booted.kernel.shutdown(); } catch { /* noop */ } |
| 139 | + rmSync(booted.dir, { recursive: true, force: true }); |
| 140 | +} |
| 141 | + |
| 142 | +/** The one item named `name` in the list `getMetaItems({ type })` serves, the `GET /meta/<type>` read. */ |
| 143 | +async function listed(kernel: any, type: string, name: string): Promise<Record<string, unknown>> { |
| 144 | + const answer = await kernel.getService('protocol').getMetaItems({ type }); |
| 145 | + const hits = (answer?.items as Array<Record<string, unknown>> | undefined)?.filter((i) => i?.name === name) ?? []; |
| 146 | + expect(hits, `GET /meta/${type} must list exactly one ${name}`).toHaveLength(1); |
| 147 | + return hits[0]!; |
| 148 | +} |
| 149 | + |
| 150 | +/** The item `getMetaItem({ type, name })` serves, the `GET /meta/<type>/NAME` read. */ |
| 151 | +async function served(kernel: any, type: string, name: string): Promise<Record<string, unknown>> { |
| 152 | + const answer = await kernel.getService('protocol').getMetaItem({ type, name }); |
| 153 | + expect(answer?.item, `GET /meta/${type}/${name} must serve an item`).toBeDefined(); |
| 154 | + return answer.item as Record<string, unknown>; |
| 155 | +} |
| 156 | + |
| 157 | +/** The one item named `name` on the execution face, the list the email loader reads. */ |
| 158 | +async function executed(kernel: any, type: string, name: string): Promise<Record<string, unknown>> { |
| 159 | + const answer = await kernel.getService('protocol').getMetaItemsForExecution({ type }); |
| 160 | + const hits = (answer?.items as Array<Record<string, unknown>> | undefined)?.filter((i) => i?.name === name) ?? []; |
| 161 | + expect(hits, `the execution face must carry exactly one ${type}/${name}`).toHaveLength(1); |
| 162 | + return hits[0]!; |
| 163 | +} |
| 164 | + |
| 165 | +describe('#22994: the artifact boot lists the converted copy the item read serves', () => { |
| 166 | + let booted: BootedArtifact | undefined; |
| 167 | + |
| 168 | + beforeAll(async () => { |
| 169 | + booted = await bootArtifact('retired', RETIRED_ARTIFACT); |
| 170 | + }, BOOT_TIMEOUT); |
| 171 | + |
| 172 | + afterAll(async () => { |
| 173 | + await teardown(booted); |
| 174 | + }); |
| 175 | + |
| 176 | + it('dashboard: GET /meta/dashboard lists the converted copy, valid, the very document GET /meta/dashboard/NAME serves', async () => { |
| 177 | + const list = await listed(booted!.kernel, 'dashboard', 'ops_board'); |
| 178 | + const item = await served(booted!.kernel, 'dashboard', 'ops_board'); |
| 179 | + |
| 180 | + expect(list.refreshIntervalSeconds).toBe(300); |
| 181 | + expect(list).not.toHaveProperty('refreshInterval'); |
| 182 | + expect(list._diagnostics).toEqual({ valid: true }); |
| 183 | + // The dashboard schema adds no default here, so the two reads are one |
| 184 | + // document. That is the card's whole defect, stated directly. |
| 185 | + expect(undiagnosed(list)).toEqual(undiagnosed(item)); |
| 186 | + }); |
| 187 | + |
| 188 | + it('dashboard: the execution face carries the converted copy, the conversion\'s own output', async () => { |
| 189 | + const exec = await executed(booted!.kernel, 'dashboard', 'ops_board'); |
| 190 | + expect(exec).toEqual({ ...convertedAuthored('dashboards', 'ops_board'), ...STAMPS }); |
| 191 | + }); |
| 192 | + |
| 193 | + it('email_template: every key the list serves is the key the item read serves, and the list is valid', async () => { |
| 194 | + const list = await listed(booted!.kernel, 'email_template', 'probe.welcome'); |
| 195 | + const item = await served(booted!.kernel, 'email_template', 'probe.welcome'); |
| 196 | + |
| 197 | + expect(list._diagnostics).toEqual({ valid: true }); |
| 198 | + // Subset, not equality: the item read is the door's strict-parsed copy |
| 199 | + // and carries schema defaults the registry copy never had (the parse |
| 200 | + // axis, #12892). A retired key the conversion strips is in neither, |
| 201 | + // and one the registry kept would fail here. |
| 202 | + for (const [key, value] of Object.entries(undiagnosed(list))) { |
| 203 | + expect(item[key], `GET /meta/email_template/probe.welcome serves ${key}`).toEqual(value); |
| 204 | + } |
| 205 | + }); |
| 206 | + |
| 207 | + it('email_template: the email loader is handed the conversion\'s output, and it parses as the loader parses it', async () => { |
| 208 | + const exec = await executed(booted!.kernel, 'email_template', 'probe.welcome'); |
| 209 | + expect(exec).toEqual({ ...convertedAuthored('emailTemplates', 'probe.welcome'), ...STAMPS }); |
| 210 | + // `createRegistryEmailTemplateLoader`'s own refusal test, verbatim: |
| 211 | + // `EmailTemplateDefinitionSchema.safeParse(stripReadDecorations(item))`, |
| 212 | + // which refuses with "is not a valid email template, so it cannot be sent". |
| 213 | + const parsed = EmailTemplateDefinitionSchema.safeParse(stripReadDecorations(exec)); |
| 214 | + expect(parsed.success, parsed.success ? '' : JSON.stringify(parsed.error.issues)).toBe(true); |
| 215 | + }); |
| 216 | +}); |
| 217 | + |
| 218 | +describe('#22994 control: an artifact authored in the current spellings registers exactly what it authored', () => { |
| 219 | + let booted: BootedArtifact | undefined; |
| 220 | + |
| 221 | + beforeAll(async () => { |
| 222 | + booted = await bootArtifact('current', CURRENT_ARTIFACT); |
| 223 | + }, BOOT_TIMEOUT); |
| 224 | + |
| 225 | + afterAll(async () => { |
| 226 | + await teardown(booted); |
| 227 | + }); |
| 228 | + |
| 229 | + it('the registry holds the authored items, stamped, and nothing rewritten', () => { |
| 230 | + const registry = booted!.kernel.getService('objectql').registry; |
| 231 | + const pick = (type: string, name: string) => registry.listItems(type).filter((i: any) => i?.name === name); |
| 232 | + expect(pick('dashboard', 'ops_board')).toEqual([{ ...CURRENT_DASHBOARD, ...STAMPS }]); |
| 233 | + expect(pick('email_template', 'probe.welcome')).toEqual([{ ...CURRENT_EMAIL_TEMPLATE, ...STAMPS }]); |
| 234 | + }); |
| 235 | +}); |
| 236 | + |
| 237 | +/** A context whose `manifest` service captures the payload and whose metadata service captures writes. */ |
| 238 | +function capturingCtx() { |
| 239 | + const payloads: any[] = []; |
| 240 | + const registrations: Array<{ type: string; name: string; item: any }> = []; |
| 241 | + const services: Record<string, unknown> = { |
| 242 | + manifest: { register: (payload: unknown) => { payloads.push(payload); } }, |
| 243 | + metadata: { |
| 244 | + registerInMemory: (type: string, name: string, item: unknown) => { |
| 245 | + registrations.push({ type, name, item }); |
| 246 | + }, |
| 247 | + }, |
| 248 | + objectql: {}, |
| 249 | + }; |
| 250 | + const ctx = { |
| 251 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 252 | + registerService: vi.fn(), |
| 253 | + // Unknown services answer `undefined`, as in the two-reader harness |
| 254 | + // (app-plugin-artifact-forward-conversion.test.ts): every other read |
| 255 | + // `start()` makes is an optional one it degrades past. |
| 256 | + getService: vi.fn((name: string) => services[name]), |
| 257 | + getServices: vi.fn(() => new Map()), |
| 258 | + hook: vi.fn(), |
| 259 | + trigger: vi.fn(), |
| 260 | + } as any; |
| 261 | + return { ctx, payloads, registrations }; |
| 262 | +} |
| 263 | + |
| 264 | +describe('#22994: one conversion per boot, and every registrar takes its result', () => { |
| 265 | + it('the config boot hands the manifest service the converted copy, and the security registrar registers the SAME converted objects', async () => { |
| 266 | + const bundle = { |
| 267 | + manifest: { id: APP_ID, name: 'Converted Collections Probe', type: 'app', version: '1.0.0' }, |
| 268 | + dashboards: [RETIRED_DASHBOARD], |
| 269 | + // `allowRestore` is retired (`permission-allow-restore-purge-removed`), |
| 270 | + // so the security registrar's copy is a converted one too. |
| 271 | + permissions: [{ name: 'support_agent', label: 'Support Agent', objects: { crm_ticket: { allowRead: true, allowRestore: true } } }], |
| 272 | + }; |
| 273 | + const { ctx, payloads, registrations } = capturingCtx(); |
| 274 | + const plugin = new AppPlugin(copy(bundle)); |
| 275 | + await plugin.init!(ctx); |
| 276 | + await plugin.start!(ctx); |
| 277 | + |
| 278 | + expect(payloads).toHaveLength(1); |
| 279 | + const payload = payloads[0]; |
| 280 | + expect(payload.dashboards[0]).toEqual({ name: 'ops_board', label: 'Ops Board', widgets: [], refreshIntervalSeconds: 300 }); |
| 281 | + expect(payload.permissions[0].objects.crm_ticket).toEqual({ allowRead: true }); |
| 282 | + |
| 283 | + // ONE conversion: a second pass would hand the registrar a second, |
| 284 | + // equal-looking copy. Identity is what tells the two apart. |
| 285 | + const permission = registrations.find((r) => r.type === 'permission' && r.name === 'support_agent'); |
| 286 | + expect(permission?.item).toBe(payload.permissions[0]); |
| 287 | + }); |
| 288 | + |
| 289 | + it('a current bundle is handed over unchanged: the authored collections, the same references', async () => { |
| 290 | + const bundle = copy(CURRENT_ARTIFACT); |
| 291 | + const { ctx, payloads } = capturingCtx(); |
| 292 | + await new AppPlugin(bundle).init!(ctx); |
| 293 | + |
| 294 | + expect(payloads).toHaveLength(1); |
| 295 | + expect(payloads[0]).toStrictEqual({ ...bundle.manifest, ...bundle }); |
| 296 | + // Copy-on-write: a conversion that changed nothing returns what it was |
| 297 | + // given, so nothing the boot registers is a rewritten copy. |
| 298 | + expect(payloads[0].dashboards).toBe(bundle.dashboards); |
| 299 | + expect(payloads[0].emailTemplates).toBe(bundle.emailTemplates); |
| 300 | + }); |
| 301 | + |
| 302 | + it('a bundle carrying packages[] is handed over as authored: init() never resolves the package list', async () => { |
| 303 | + const bundle = { |
| 304 | + manifest: { id: APP_ID, name: 'Converted Collections Probe', type: 'app', version: '1.0.0' }, |
| 305 | + packages: [{ manifest: { id: `${APP_ID}.core`, name: 'core', version: '1.0.0', type: 'app', dashboards: [RETIRED_DASHBOARD] } }], |
| 306 | + }; |
| 307 | + const { ctx, payloads } = capturingCtx(); |
| 308 | + await new AppPlugin(bundle).init!(ctx); |
| 309 | + |
| 310 | + expect(payloads).toHaveLength(1); |
| 311 | + expect(payloads[0]).toStrictEqual({ ...bundle.manifest, ...bundle }); |
| 312 | + expect(payloads[0].packages).toBe(bundle.packages); |
| 313 | + }); |
| 314 | +}); |
0 commit comments