Skip to content

Commit 48ab8da

Browse files
committed
feat(plugin-email): resolve email template names through the package-scoped resolver
An email template's name is answered by resolvePackageScopedName as a caller with no package before the layered per-locale pick; a name two packages hold fails the send with a 409 naming every candidate. Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude <noreply@anthropic.com>
1 parent 630a0ba commit 48ab8da

6 files changed

Lines changed: 146 additions & 12 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-email': patch
3+
---
4+
5+
feat: an email template's name resolves by (package, name) through the shared package-scoped resolver (ADR-0150 D3/D4)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Which email template a send or a render uses is now decided by `resolvePackageScopedName` from `@objectstack/objectql`, never by list order. A send names no package (`SendTemplateInput` carries none), so the loader asks as a caller with no package: the environment's own template, else the unique package holder (the email service's built-in templates rank below an app's, and a dependent package's added locale is no second holder of its base's name), else a refusal that names every candidate. Within the answer, the per-locale pick is unchanged.
11+
12+
Who is affected: a deployment that held one email template name in two packages from before phase 1's one-holder refusal (the cold boot warns about it as a "Bare-name conflict at boot"). Its sends were rendered from whichever package's bundle listed first; they now fail with a `409 RESOURCE_CONFLICT` naming both packages. Rename one of the two (the boot warning names the rename). First-party count of such clashes: 0. Every other name renders exactly as before, since phase 1 still refuses a new clash at install.
13+
14+
`@objectstack/plugin-email` now depends on `@objectstack/objectql` at runtime (it was a dev dependency).

‎packages/plugins/plugin-email/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,12 @@
2828
"dependencies": {
2929
"@objectstack/core": "workspace:*",
3030
"@objectstack/formula": "workspace:*",
31+
"@objectstack/objectql": "workspace:*",
3132
"@objectstack/platform-objects": "workspace:*",
3233
"@objectstack/spec": "workspace:*",
3334
"nodemailer": "^10.1.4"
3435
},
3536
"devDependencies": {
36-
"@objectstack/objectql": "workspace:*",
3737
"@objectstack/service-queue": "workspace:*",
3838
"@objectstack/service-settings": "workspace:*",
3939
"@types/node": "^26.6.5",

‎packages/plugins/plugin-email/src/template-loader.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@
3131
*/
3232

3333
import { describe, expect, it } from 'vitest';
34+
import { SchemaRegistry } from '@objectstack/objectql';
3435
import {
3536
BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID,
37+
EmailTemplateAmbiguousError,
3638
createRegistryEmailTemplateLoader,
3739
} from './template-loader.js';
3840

@@ -284,3 +286,45 @@ describe('createRegistryEmailTemplateLoader — a malformed item is refused, nev
284286
await expect(loader.load('ops.digest', 'en-US')).rejects.toThrow(/ops\.digest/);
285287
});
286288
});
289+
290+
describe('createRegistryEmailTemplateLoader — the name resolves by (package, name) (ADR-0150 D3)', () => {
291+
const OTHER_PACKAGE = 'com.example.other';
292+
293+
/** A real registry: each id installed as a code package, shipping `items` in its composite slot. */
294+
function registryShipping(shipped: Array<[string, AnyRecord]>): SchemaRegistry {
295+
const reg = new SchemaRegistry();
296+
reg.logLevel = 'silent';
297+
for (const [id, item] of shipped) {
298+
if (!reg.getPackage(id)) {
299+
reg.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code');
300+
}
301+
const { _packageId: _drop, ...body } = item;
302+
reg.registerItem('email_template', body, 'name' as never, id);
303+
}
304+
return reg;
305+
}
306+
307+
it('one package holder beside the built-in: resolves, and the layered list answers as before', async () => {
308+
const reg = registryShipping([[BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID, builtin()], [APP_PACKAGE, declared()]]);
309+
const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([builtin(), declared()]), registry: reg });
310+
expect((await loader.load('auth.password_reset', 'en-US'))?.subject).toBe(AUTHORED);
311+
});
312+
313+
it('two package holders: the send is refused with the 409 conflict naming both — never the first listed', async () => {
314+
const other = declared({ subject: 'Other wording', _packageId: OTHER_PACKAGE });
315+
const reg = registryShipping([[APP_PACKAGE, declared()], [OTHER_PACKAGE, other]]);
316+
const loader = createRegistryEmailTemplateLoader({ protocol: layeredProtocol([declared(), other]), registry: reg });
317+
318+
const err = await loader.load('auth.password_reset', 'en-US').then(() => undefined, (e: unknown) => e);
319+
expect(err).toBeInstanceOf(EmailTemplateAmbiguousError);
320+
expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, template: 'auth.password_reset' });
321+
expect((err as EmailTemplateAmbiguousError).candidates).toEqual([
322+
{ kind: 'package', packageId: APP_PACKAGE },
323+
{ kind: 'package', packageId: OTHER_PACKAGE },
324+
]);
325+
expect((err as Error).message).toContain(`"${APP_PACKAGE}"`);
326+
expect((err as Error).message).toContain(`"${OTHER_PACKAGE}"`);
327+
// No locale escapes it: the name is refused before any bundle is read.
328+
await expect(loader.load('auth.password_reset', undefined)).rejects.toBeInstanceOf(EmailTemplateAmbiguousError);
329+
});
330+
});

‎packages/plugins/plugin-email/src/template-loader.ts‎

Lines changed: 69 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,28 @@
2828
* Language-only prefix matching (`zh` → `zh-CN`) is deliberately NOT here: no
2929
* contract declares it, and inventing it would put a resolution rule in the
3030
* code that no spec, doc or form describes.
31+
*
32+
* ## The name rule: `(package, name)` (ADR-0150 D3/D4)
33+
*
34+
* An email template is addressed by `(package, name)`. Before a bundle is
35+
* read, the name is resolved by the ONE package-scoped resolver
36+
* (`resolvePackageScopedName`, `@objectstack/objectql`) over the ObjectQL
37+
* registry, as a caller with no package: `SendTemplateInput` names no
38+
* package, so every send is context-free — the environment's own item, else
39+
* the unique package holder (the built-ins rank below it, ADR-0150 D3 (b)),
40+
* else a refusal naming every candidate, which fails the send
41+
* ({@link EmailTemplateAmbiguousError}). ⛔ Never a first-listed pick. While
42+
* phase 1's one-holder refusal stands (`email_template` is one of its types)
43+
* no two packages hold a name, so every name resolves as before, and the
44+
* layered list below answers the bundle exactly as it did.
3145
*/
3246

47+
import {
48+
resolvePackageScopedName,
49+
type PackageScopedHolder,
50+
type PackageScopedRefusal,
51+
type PackageScopedRegistry,
52+
} from '@objectstack/objectql';
3353
import { stripReadDecorations } from '@objectstack/spec/kernel';
3454
import { EmailTemplateDefinitionSchema, type EmailTemplateDefinitionParsed } from '@objectstack/spec/system';
3555
import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow, type TemplateLoader, type TemplateBundleLocales } from './email-service.js';
@@ -42,7 +62,7 @@ import { DEFAULT_TEMPLATE_LOCALE, TEMPLATE_BUNDLE_LOCALES, type EmailTemplateRow
4262
export const BUILTIN_EMAIL_TEMPLATES_PACKAGE_ID = 'com.objectstack.service.email';
4363

4464
/** The metadata type the loader reads. */
45-
const EMAIL_TEMPLATE_TYPE = 'email_template';
65+
const EMAIL_TEMPLATE_TYPE = 'email_template' as const;
4666

4767
/**
4868
* The reads {@link createRegistryEmailTemplateLoader} resolves through, looked
@@ -58,12 +78,47 @@ export interface EmailTemplateRegistrySources {
5878
*/
5979
protocol?: { getMetaItemsForExecution(request: { type: string }): Promise<{ items?: unknown[] }> };
6080
/**
61-
* The ObjectQL `SchemaRegistry`. Read ONLY when no `protocol` is
62-
* registered: such a host has no metadata door, so no environment item can
63-
* exist and the code declarations the registry holds are already the
64-
* effective set.
81+
* The ObjectQL `SchemaRegistry`. Its items are read ONLY when no `protocol`
82+
* is registered: such a host has no metadata door, so no environment item
83+
* can exist and the code declarations the registry holds are already the
84+
* effective set. When it carries the package-scoped slice
85+
* ({@link PackageScopedRegistry}), every name is resolved over it first
86+
* (module doc, "The name rule").
6587
*/
66-
registry?: { listItems(type: string): unknown[] };
88+
registry?: { listItems(type: string): unknown[] } & Partial<PackageScopedRegistry>;
89+
}
90+
91+
/**
92+
* [ADR-0150 D3, epic #31527 red line 2] A template name that resolves to no
93+
* single template: two packages ship it, and nothing picks one. `code` +
94+
* `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the status
95+
* ADR-0150 D5 gives an ambiguous bare name); `candidates` names every holder,
96+
* and so does the message.
97+
*/
98+
export class EmailTemplateAmbiguousError extends Error {
99+
readonly code = 'RESOURCE_CONFLICT';
100+
readonly status = 409;
101+
/** The template name. */
102+
readonly template: string;
103+
/** Every holder of the name, in the resolver's order. */
104+
readonly candidates: readonly PackageScopedHolder[];
105+
constructor(refusal: PackageScopedRefusal) {
106+
super(`email template '${refusal.name}' cannot be sent: ${refusal.message}`);
107+
this.name = 'EmailTemplateAmbiguousError';
108+
this.template = refusal.name;
109+
this.candidates = refusal.candidates;
110+
}
111+
}
112+
113+
/** The registry, when it carries the slice the package-scoped resolver reads. */
114+
function packageScopedRegistryOf(registry: EmailTemplateRegistrySources['registry']): PackageScopedRegistry | undefined {
115+
return typeof registry?.packageScopedHoldersOf === 'function'
116+
&& typeof registry.getPackageScopedItem === 'function'
117+
&& typeof registry.getEnvironmentScopedItem === 'function'
118+
&& typeof registry.getPackage === 'function'
119+
&& typeof registry.getAllPackages === 'function'
120+
? (registry as PackageScopedRegistry)
121+
: undefined;
67122
}
68123

69124
/** An item's locale as the bundle key reads it: the schema default when it declares none. */
@@ -138,6 +193,14 @@ export function createRegistryEmailTemplateLoader(
138193

139194
const readBundle = async (name: string): Promise<Record<string, unknown>[]> => {
140195
const { protocol, registry } = resolveSources() ?? {};
196+
// [ADR-0150 D3] The name first: a send names no package, so it resolves
197+
// as a caller with no package. A refusal fails the send, naming every
198+
// candidate; any other answer leaves the bundle to the read below.
199+
const scoped = packageScopedRegistryOf(registry);
200+
if (scoped) {
201+
const resolved = resolvePackageScopedName(scoped, { type: EMAIL_TEMPLATE_TYPE, name });
202+
if (resolved.status === 'refused') throw new EmailTemplateAmbiguousError(resolved);
203+
}
141204
let items: unknown[];
142205
if (typeof protocol?.getMetaItemsForExecution === 'function') {
143206
const listed = await protocol.getMetaItemsForExecution({ type: EMAIL_TEMPLATE_TYPE });
Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,17 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

3-
// This package needs nothing beyond the shared preset; see its header.
4-
export { default } from '../../../vitest.preset.mts';
3+
// The shared preset (see its header), merged with this package's one setting.
4+
import { mergeConfig } from 'vitest/config';
5+
import preset from '../../../vitest.preset.mts';
6+
7+
export default mergeConfig(preset, {
8+
test: {
9+
// #13517: quiet the registry's per-item registration chatter — the
10+
// engine's own `OS_REGISTRY_LOG` seam, not a change to its shipped
11+
// default. Enforced by scripts/check-registry-log-declared.mjs, which
12+
// reads this suite as engine-booting since `template-loader.test.ts`
13+
// resolves email template names through a real `SchemaRegistry`
14+
// (ADR-0150 D3).
15+
env: { OS_REGISTRY_LOG: 'warn' },
16+
},
17+
});

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)