Skip to content

Commit 1a66fcf

Browse files
refactor(core,objectql,plugin-sharing): one PackageScopedNameRefusedError class for every package-scoped by-name refusal (#31876)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Pd2vxfndbHVQLiX3wzkDSN)_ Fixes #31852 Clause-②: yes (widening) — `@objectstack/core` and the lean entry `@objectstack/objectql/core` gain `PackageScopedNameRefusedError` Metadata-protocol: none ## 维护者速读 - 改了什么:包作用域按名读取被拒时抛出的 `PackageScopedNameRefusedError` 原本在 objectql 和 plugin-sharing 各有一份,现在只在 `@objectstack/core` 声明一次,两个包原名转出同一个类;objectql 的精简入口 `@objectstack/objectql/core` 也导出它。导航翻译检查脚本遇到同名应用被拒时,改为报一条列出所有候选包的组合错误,不再抛出 409 中断。 - 为什么改:两份同名类互不 `instanceof`,以后谁要捕获"包作用域名字冲突"就得猜用哪一份,猜错一半;精简入口的使用者只能按 code 和 status 匹配。 - 风险与回滚:每个入口仍返回 409 `RESOURCE_CONFLICT`、同一句话,行为不变;plugin-sharing 抛出的错误多带一个值相同的 `httpStatus` 字段。回滚即还原本 PR。 - 先看:`packages/core/src/package-scoped-resolution.ts`(类本体)、`packages/plugins/plugin-sharing/src/package-scoped-declarations.ts`(改为转出)、`packages/cli/scripts/check-app-nav-i18n.mjs`(`readMergedApp`)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-sharing exec vitest run src/package-scoped-declarations.test.ts`,预期 26 个全过,其中 3 个是本 PR 新增的跨包 `instanceof` 断言。 - 需要你做的:无,席位落地。 ## What changes - **`@objectstack/core`** (`package-scoped-resolution.ts`): `PackageScopedNameRefusedError` is declared here once, beside `PackageScopedRefusal` and `packageScopedRefusalMessage`. It carries the union of the two old copies' fields: `code = 'RESOURCE_CONFLICT'`, `status = 409`, `httpStatus = 409` and `refusal`, and its message is the refusal's own sentence. Core's barrel already re-exports the module (`export *`), so no barrel edit. - **`@objectstack/objectql`** (`package-scoped-read.ts`): the local class is gone; the module re-exports core's binding under the same name, so the barrel, `metadata-facade.ts` and `registry.ts` keep their imports. - **`@objectstack/objectql/core`** (lean entry, `core.ts`): exports the class too, since the `SchemaRegistry` it exports throws it from `getApp`. Core is already in the entry's closure, so `core-boundary.ratchet.test.ts` stays green. - **`@objectstack/plugin-sharing`** (`package-scoped-declarations.ts`): the local class is gone; the module re-exports core's binding under the same name, so `sharing-rule-service.ts` and `ownership-queue-service.ts` keep their imports. Its refusals gain `httpStatus: 409`. - **`packages/cli/scripts/check-app-nav-i18n.mjs`** (N1): the app is read through a new pure `readMergedApp(name, getApp, isRefusal)`. A `PackageScopedNameRefusedError` from `registry.getApp(name)` becomes a composition finding naming the app and every candidate, reported beside the gate's other composition errors (so the coverage verdict is not attempted). It never reads as "not registered", whose remedy is the opposite. Any other error is rethrown untouched. I chose "catch and report" over "read by the shell's package": a read naming the shell package would silently pick the shell's app and hide a real name clash from the gate. Measured site census (delta ruling 1), `git grep -n "PackageScopedNameRefusedError\|RESOURCE_CONFLICT.*refusal"` on `origin/main` `074a014c`: two declarations (objectql `package-scoped-read.ts`, plugin-sharing `package-scoped-declarations.ts`); throws in `package-scoped-read.ts`, `sharing-rule-service.ts` (2) and `ownership-queue-service.ts` (2); `instanceof` in `metadata-facade.ts`, `sharing-rule-service.ts` and `ownership-queue-service.ts` (2). No third copy on main. Open PRs read at their heads: E3 #31815 adds no site. plugin-email #31825 adds a separate class, `EmailTemplateAmbiguousError` (same 409 `RESOURCE_CONFLICT` envelope, different name, extra `template` and `candidates` fields), in `plugin-email/src/template-loader.ts`. It is left to that PR's seat, as ruled. Changeset: `.changeset/31852-one-package-scoped-refusal-class.md`, patch for core, objectql and plugin-sharing. `@objectstack/cli` takes none: its `files` is `dist`, `README.md` and `CHANGELOG.md`, so `scripts/` does not publish. ## Tests - `packages/core/src/package-scoped-resolution.test.ts`: the class carries `code`, `status`, `httpStatus`, `refusal` and the refusal's sentence. - `packages/objectql/src/package-scoped-e8-readers.test.ts`: `toBe` identity of the class from `package-scoped-read.js`, the barrel and the lean `./core` entry against core's; a `getApp` refusal is `instanceof` the lean entry's class. - `packages/plugins/plugin-sharing/src/package-scoped-declarations.test.ts`: `toBe` identity of plugin-sharing's and objectql's export against core's; a refusal from objectql's by-name reader (`SchemaRegistry#getApp`) is `instanceof` plugin-sharing's class, and a refusal from plugin-sharing's door (`SharingRuleService#declaredRuleNamed`) is `instanceof` objectql's class. - `check-app-nav-i18n.mjs --self-test`: six new cases for `readMergedApp` (refusal becomes a finding, names every candidate, never reads as unregistered; served and unregistered reads unchanged; a non-refusal error is rethrown, as a negative control; the boot read passes the class test). - Wire envelope (delta ruling 5) already pinned by existing tests, unchanged: objectql `package-scoped-e8-readers.test.ts` ("the refusal crosses a wire door as 409 RESOURCE_CONFLICT") and plugin-sharing `package-scoped-declarations.test.ts` ("refuses the sharing rule by name with 409 RESOURCE_CONFLICT naming both packages"). No existing test was edited or deleted. ## Acceptance notes - plugin-email #31825 adds `EmailTemplateAmbiguousError`, a third class for the same refusal family. Not touched here (ruling 1); its seat decides whether it extends or reuses this class. ## Verification Head `3bb5c3e6` (`02e922a7` plus a merge of `origin/main`). <details><summary>Red first, on origin/main 074a014 (tests added, fix not yet applied)</summary> - core `package-scoped-resolution.test.ts`: `Tests 1 failed | 23 passed (24)`. - objectql `package-scoped-e8-readers.test.ts`: `Tests 2 failed | 71 passed (73)`. - plugin-sharing `package-scoped-declarations.test.ts` (core and objectql built from main): `Tests 3 failed | 23 passed (26)`. </details> <details><summary>Ablation (scripts/ablation-replace.mjs, both legs restored to HEAD by blob hash)</summary> - plugin-sharing: `export { PackageScopedNameRefusedError };` replaced by a local class. `mutation landed: anchor 1 -> 0`; `Tests 3 failed | 23 passed (26)`, all three new cross-package pins red; `restored: blob == HEAD (339e4de)`. - objectql: the same replacement in `package-scoped-read.ts`. `mutation landed: anchor 1 -> 0`; `Tests 1 failed | 72 passed (73)` (the identity pin); `restored: blob == HEAD (45f07d0)`. </details> <details><summary>Builds, tests, typecheck, lint</summary> - `turbo run build --filter='./packages/**' --concurrency=2` under the lock at `02e922a7`: `VERDICT command-exit 0`, `Tasks: 81 successful, 81 total`. - At `02e922a7`, one lock run: `typecheck` for core, objectql, plugin-sharing, then `pnpm --filter @objectstack/core test` (`Test Files 139 passed`, `Tests 3207 passed`), plugin-sharing (`Test Files 72 passed`, `Tests 1496 passed`), objectql (`Test Files 580 passed`, `Tests 11936 passed`): `VERDICT command-exit 0`. - At `3bb5c3e6` (after the merge; incoming main touched other files of core and objectql): rebuild of the three packages, their `typecheck`, and the three changed test files plus `core-boundary.ratchet.test.ts`: 24/24, 75/75, 26/26, `VERDICT command-exit 0`. - `pnpm check:app-nav-i18n` (self-test, then the live composition): exit 0, `OK (13 contributor(s), 11 locale(s), 2 app(s) — setup: 57 merged nav id(s), account: 13 merged nav id(s) …)`. - `eslint --no-inline-config` on `packages/core/src`, `packages/objectql/src`, `packages/plugins/plugin-sharing/src` and the script: exit 0. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 73 commands, each run with its exit code captured before any pipe, all exit 0 at `02e922a7`. Reconciliation: `73 derived famil(ies) accounted for — 73 run, 0 NOT-MEASURED (a DERIVED zero — all 73 recorded an exit code and none of them is 3)`. Re-run at `3bb5c3e6`: see the report comment on the card. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQHXhv9SKTU1qQ9CNC)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8079fa9 commit 1a66fcf

9 files changed

Lines changed: 235 additions & 44 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/core': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/plugin-sharing': patch
5+
---
6+
7+
refactor(core,objectql,plugin-sharing): one `PackageScopedNameRefusedError` class for the 409 a package-scoped by-name read refuses with
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
- **`@objectstack/core`: `PackageScopedNameRefusedError`** (new export), beside `PackageScopedRefusal` and `packageScopedRefusalMessage`. It carries `code: 'RESOURCE_CONFLICT'`, `status: 409`, `httpStatus: 409` and the resolver's `refusal`, and its message is the refusal's own sentence, which names every candidate.
13+
- **`@objectstack/objectql`** and **`@objectstack/plugin-sharing`** each declared a class of that name before, and an `instanceof` against one never matched the other. Both now re-export core's class under the same name, so every existing import keeps resolving and one `instanceof` matches a refusal from an objectql reader (`SchemaRegistry#getApp` and the other ADR-0150 by-name readers) and from a plugin-sharing door (a declared sharing rule, queue or assignment rule name) alike. objectql's copy already carried `httpStatus`; plugin-sharing's refusal now carries it too, with the same value.
14+
- **`@objectstack/objectql/core`** (the lean entry) now exports `PackageScopedNameRefusedError` too, since the `SchemaRegistry` it exports throws it.
15+
16+
No door changes its answer: each still refuses `409 RESOURCE_CONFLICT` with the same sentence.

‎packages/cli/scripts/check-app-nav-i18n.mjs‎

Lines changed: 94 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@
9696
// removed there under #6660, and `nav_sso_providers` — labelled in #6659
9797
// although no composition this gate boots ever merges it — is pinned as the
9898
// converse case. Neither verdict is one this gate could honestly reach.
99-
import { existsSync } from 'node:fs';
99+
import { existsSync, readFileSync } from 'node:fs';
100100
import { join, dirname } from 'node:path';
101101
import { fileURLToPath } from 'node:url';
102102
// The exit-code contract for a refusal, from the frame that owns it —
@@ -231,6 +231,43 @@ export function contributionsForApp(contributions, appName) {
231231
.map((c) => ({ source: c.source, ids: c.idsByApp?.[appName] ?? [] }));
232232
}
233233

234+
/**
235+
* Read one app back from the composition: its merged nav ids, `undefined` when
236+
* it was never registered, or — when the by-name read is REFUSED — a finding
237+
* that names every candidate.
238+
*
239+
* `registry.getApp(name)` with no package is a read by a caller with no package
240+
* (ADR-0150 D3), so a name two packages in this composition both ship is
241+
* refused `409 RESOURCE_CONFLICT` (`PackageScopedNameRefusedError`) rather than
242+
* answered. That is a composition finding — there is no ONE app to judge —
243+
* and it is reported as one, beside the other composition errors. ⛔ Never
244+
* swallowed (it would read as "not registered", whose remedy is the opposite),
245+
* and never thrown out of the gate as a bare stack. Any other error is not a
246+
* refusal and is rethrown untouched.
247+
*
248+
* `isRefusal` is the class test, handed in so `--self-test` can drive this
249+
* without a build.
250+
*/
251+
export function readMergedApp(appName, getApp, isRefusal) {
252+
let mergedApp;
253+
try {
254+
mergedApp = getApp(appName);
255+
} catch (err) {
256+
if (!isRefusal(err)) throw err;
257+
const candidates = (err.refusal?.candidates ?? []).map((c) =>
258+
c?.kind === 'package' ? `package "${c.packageId}"` : `the ${c?.kind ?? 'unknown holder'}`,
259+
);
260+
return {
261+
refused:
262+
`the \`${appName}\` app could not be read back: the composition holds more than one app by that name, ` +
263+
`so a read naming no package is refused (${err.code} ${err.status}) — ${err.message} ` +
264+
`Candidates: ${candidates.join(', ') || 'none named'}. This gate judges ONE merged app per name: ` +
265+
`rename or remove the app in the package that should not hold it.`,
266+
};
267+
}
268+
return { ids: mergedApp ? collectNavIds(mergedApp.navigation) : undefined };
269+
}
270+
234271
/**
235272
* The pass line, as a VALUE so `--self-test` can pin it.
236273
*
@@ -702,6 +739,51 @@ function selfTest() {
702739
expect('#14857 NEGATIVE CONTROL: the literal-advisory pin can still fail', spellsALiteralCode(controlLiteralAdvisory), 'the predicate no longer sees a spelled-out code');
703740
expect('#14857 NEGATIVE CONTROL: the stale-code pin can still fail', /Exit code 1\b/.test(controlLiteralAdvisory()), 'the stale-spelling predicate no longer sees `Exit code 1`');
704741

742+
// ── A REFUSED app read is a composition finding, never a throw or a miss (#31852) ──
743+
//
744+
// `getApp(name)` naming no package is refused when two packages ship the name
745+
// (ADR-0150 D3). Recorded shape: the refusal class carries `code`, `status`
746+
// and the resolver's `refusal` with every candidate. The local class stands
747+
// in for `PackageScopedNameRefusedError` so this runs without a build.
748+
class RefusedSample extends Error {
749+
code = 'RESOURCE_CONFLICT';
750+
status = 409;
751+
refusal = {
752+
candidates: [
753+
{ kind: 'package', packageId: 'com.acme.alpha' },
754+
{ kind: 'package', packageId: 'com.acme.beta' },
755+
],
756+
};
757+
}
758+
const isRefusedSample = (err) => err instanceof RefusedSample;
759+
const refusedRead = readMergedApp('setup', () => { throw new RefusedSample('The app "setup" is held by 2 packages.'); }, isRefusedSample);
760+
expect('#31852 a refused read is reported as a finding, not thrown', typeof refusedRead.refused === 'string', JSON.stringify(refusedRead));
761+
expect(
762+
'#31852 the finding names the app and every candidate',
763+
refusedRead.refused?.includes('`setup`') && refusedRead.refused.includes('com.acme.alpha') && refusedRead.refused.includes('com.acme.beta'),
764+
String(refusedRead.refused),
765+
);
766+
expect(
767+
'#31852 a refused read never reads as "not registered" (an undefined id list), whose remedy is the opposite',
768+
refusedRead.ids === undefined && !('ids' in refusedRead),
769+
JSON.stringify(refusedRead),
770+
);
771+
const mergedRead = readMergedApp('setup', () => ({ navigation: MERGED_NAV_SAMPLE }), isRefusedSample);
772+
expect('#31852 a served read answers its merged ids', mergedRead.ids?.includes('nav_webhooks') && !mergedRead.refused, JSON.stringify(mergedRead));
773+
expect('#31852 an unregistered app still answers undefined ids', readMergedApp('setup', () => undefined, isRefusedSample).ids === undefined, 'undefined');
774+
let rethrown;
775+
try {
776+
readMergedApp('setup', () => { throw new TypeError('boom'); }, isRefusedSample);
777+
} catch (err) {
778+
rethrown = err;
779+
}
780+
expect('#31852 NEGATIVE CONTROL: an error that is not the refusal is rethrown, never swallowed', rethrown instanceof TypeError, String(rethrown));
781+
expect(
782+
'#31852 the gate hands readMergedApp the refusal CLASS test, not a code match',
783+
/readMergedApp\(app\.name,[^\n]*instanceof PackageScopedNameRefusedError/.test(readFileSync(fileURLToPath(import.meta.url), 'utf8')),
784+
'the boot read no longer passes the class test',
785+
);
786+
705787
if (failures.length) {
706788
console.error(`\ncheck-app-nav-i18n --self-test: ${failures.length} failure(s)\n`);
707789
for (const f of failures) console.error(` ${f}`);
@@ -803,7 +885,7 @@ checkBuildPrerequisite();
803885
// Boot the composition and read the merged app back.
804886
// ---------------------------------------------------------------------------
805887

806-
const { ObjectQL } = await import('@objectstack/objectql');
888+
const { ObjectQL, PackageScopedNameRefusedError } = await import('@objectstack/objectql');
807889
const { SetupAppTranslations } = await import('@objectstack/platform-objects/apps');
808890

809891
const engine = new ObjectQL();
@@ -904,12 +986,13 @@ for (const contributor of CONTRIBUTORS) {
904986
* at all" have different remedies, and `collectNavIds(undefined)` answers `[]`
905987
* for both.
906988
*/
907-
const mergedIdsByApp = new Map(
908-
APPS.map((app) => {
909-
const mergedApp = engine.registry.getApp(app.name);
910-
return [app.name, mergedApp ? collectNavIds(mergedApp.navigation) : undefined];
911-
}),
989+
const mergedReads = new Map(
990+
APPS.map((app) => [
991+
app.name,
992+
readMergedApp(app.name, (name) => engine.registry.getApp(name), (err) => err instanceof PackageScopedNameRefusedError),
993+
]),
912994
);
995+
const mergedIdsByApp = new Map(APPS.map((app) => [app.name, mergedReads.get(app.name).ids]));
913996

914997
// The two verdicts are kept apart because their REMEDIES are opposites, and a
915998
// footer that prescribes one for the other is the #5862 defect (a confident
@@ -928,7 +1011,10 @@ for (const app of APPS) {
9281011
`ids to check.`,
9291012
);
9301013
}
931-
if (mergedIdsByApp.get(app.name) === undefined) {
1014+
const refused = mergedReads.get(app.name).refused;
1015+
if (refused) {
1016+
compositionErrors.push(refused);
1017+
} else if (mergedIdsByApp.get(app.name) === undefined) {
9321018
compositionErrors.push(
9331019
`the \`${app.name}\` app is not registered at all — the composition produced no app to judge. ` +
9341020
`Its shell ships in \`${app.shellPackage}\`, which must be a CONTRIBUTORS entry above.`,

‎packages/core/src/package-scoped-resolution.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { describe, expect, it } from 'vitest';
1616
import {
1717
ENGINE_FUNCTION_TYPE,
1818
OVERRIDABLE_BASELINE_PACKAGES,
19+
PackageScopedNameRefusedError,
1920
RUNTIME_COMPATIBILITY_PACKAGE_ID,
2021
packageScopedHolderSource,
2122
resolvePackageScopedHolders,
@@ -204,3 +205,19 @@ describe('the compatibility API\'s default package id is a caller with no packag
204205
expect(resolve([['__runtime__', 'r'], [A, 'a']], [])).toMatchObject({ status: 'refused', reason: 'ambiguous-in-environment' });
205206
});
206207
});
208+
209+
describe('the one refusal class every package-scoped by-name door throws (ADR-0150 D5)', () => {
210+
it('carries the 409 RESOURCE_CONFLICT envelope under both status spellings, and the resolver\'s refusal and sentence', () => {
211+
const refusal = resolve([[A, 'a'], [B, 'b']], []);
212+
expect(refusal.status).toBe('refused');
213+
if (refusal.status !== 'refused') return;
214+
const err = new PackageScopedNameRefusedError(refusal);
215+
expect(err).toBeInstanceOf(Error);
216+
expect(err.name).toBe('PackageScopedNameRefusedError');
217+
expect(err.code).toBe('RESOURCE_CONFLICT');
218+
expect(err.status).toBe(409);
219+
expect(err.httpStatus).toBe(409);
220+
expect(err.refusal).toBe(refusal);
221+
expect(err.message).toBe(refusal.message);
222+
});
223+
});

‎packages/core/src/package-scoped-resolution.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,37 @@ export function packageScopedRefusalMessage(refusal: Omit<PackageScopedRefusal,
472472
}
473473
}
474474

475+
/**
476+
* A by-name read the package-scoped rule refused (ADR-0150 D3): the name means
477+
* more than one item here, or only items the caller may not reach. The message
478+
* is the refusal's own sentence ({@link packageScopedRefusalMessage}), which
479+
* names every candidate.
480+
*
481+
* The ONE class every package-scoped by-name door throws — objectql's readers
482+
* and plugin-sharing's declared-name doors alike re-export this binding, so a
483+
* catcher matches every one of them with a single `instanceof`. It lives here,
484+
* beside the refusal it carries, because this is the lowest package all of
485+
* them read.
486+
*
487+
* The ADR-0112 envelope a wire door answers: `409 RESOURCE_CONFLICT`, the
488+
* standard catalog's member for a name in conflict, which ADR-0150 D5 gives a
489+
* by-name door's ambiguity. ⛔ Never the `500` fallback, and never `404`.
490+
*/
491+
export class PackageScopedNameRefusedError extends Error {
492+
readonly code = 'RESOURCE_CONFLICT';
493+
readonly status = 409;
494+
/** The same number under ADR-0112 D5's spelling — what a consumer holding the THROWN error reads. */
495+
readonly httpStatus = 409;
496+
/** The refusal: the reason, the caller's package and every candidate. */
497+
readonly refusal: PackageScopedRefusal;
498+
499+
constructor(refusal: PackageScopedRefusal) {
500+
super(refusal.message);
501+
this.name = 'PackageScopedNameRefusedError';
502+
this.refusal = refusal;
503+
}
504+
}
505+
475506
function refuse(
476507
query: PackageScopedHoldersQuery,
477508
callerPackageId: string | null,

‎packages/objectql/src/core.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ export {
2424
} from './registry.js';
2525
export type { ObjectContributor, SchemaRegistryOptions } from './registry.js';
2626

27+
// [#31852, ADR-0150 D5] The refusal `SchemaRegistry#getApp` (and every other
28+
// package-scoped by-name read) throws: `@objectstack/core`'s one class, so a
29+
// lean consumer can match it by class rather than by `code` and `status`.
30+
// Core is already this entry's dependency, so it costs the boundary nothing.
31+
export { PackageScopedNameRefusedError } from './package-scoped-read.js';
32+
2733
// [#14553] The navigation-contribution group diagnostic. Belongs on the LEAN
2834
// entry as well as the barrel: it is a pure derivation over authored metadata
2935
// with no imports of its own, so it costs this entry nothing and stays clear of

‎packages/objectql/src/package-scoped-e8-readers.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protoco
3333
import { SchemaRegistry } from './registry.js';
3434
import { MetadataFacade } from './metadata-facade.js';
3535
import { resolveThrownHttpError } from '@objectstack/types';
36+
import { PackageScopedNameRefusedError as CorePackageScopedNameRefusedError } from '@objectstack/core';
37+
import * as barrel from './index.js';
38+
import * as leanEntry from './core.js';
3639
import {
3740
PACKAGE_SCOPED_READ_TYPES,
3841
PackageScopedNameRefusedError,
@@ -135,6 +138,28 @@ describe('the refusal crosses a wire door as 409 RESOURCE_CONFLICT (ADR-0150 D5)
135138
});
136139
});
137140

141+
describe('the refusal class is @objectstack/core\'s, one binding on every objectql entry (#31852)', () => {
142+
it('package-scoped-read, the barrel and the lean `./core` entry all export core\'s class itself', () => {
143+
expect(PackageScopedNameRefusedError).toBe(CorePackageScopedNameRefusedError);
144+
expect(barrel.PackageScopedNameRefusedError).toBe(CorePackageScopedNameRefusedError);
145+
expect(leanEntry.PackageScopedNameRefusedError).toBe(CorePackageScopedNameRefusedError);
146+
});
147+
148+
it('a lean consumer matches SchemaRegistry#getApp\'s refusal by class, not only by code and status', () => {
149+
ship('app', 'home', A);
150+
ship('app', 'home', B);
151+
let thrown: unknown;
152+
try {
153+
registry.getApp('home');
154+
} catch (err) {
155+
thrown = err;
156+
}
157+
expect(registry).toBeInstanceOf(leanEntry.SchemaRegistry);
158+
expect(thrown).toBeInstanceOf(leanEntry.PackageScopedNameRefusedError);
159+
expect(thrown).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, httpStatus: 409 });
160+
});
161+
});
162+
138163
describe('narrowing (1) — an uncovered type two packages hold: the bare read refuses naming both', () => {
139164
for (const type of UNCOVERED) {
140165
it(`${type}: a caller with no package is refused at the protocol read (both faces), the registry and the facade`, async () => {

‎packages/objectql/src/package-scoped-read.ts‎

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
* `@objectstack/metadata-core`.
5151
*/
5252

53-
import type { PackageScopedRefusal } from '@objectstack/core';
53+
import { PackageScopedNameRefusedError } from '@objectstack/core';
5454
import {
5555
resolvePackageScopedName,
5656
type PackageScopedQuery,
@@ -83,28 +83,12 @@ export function isPackageScopedReadType(type: unknown): type is PackageScopedRea
8383
}
8484

8585
/**
86-
* A by-name read the package-scoped resolver refused (ADR-0150 D3): the name
87-
* means more than one item here, or only items the caller may not reach. The
88-
* message is the resolver's own sentence, which names every candidate.
89-
*
90-
* The ADR-0112 envelope a wire door answers: `409 RESOURCE_CONFLICT`, the
91-
* standard catalog's member for a name in conflict, which ADR-0150 D5 gives a
92-
* by-name door's ambiguity. ⛔ Never the `500` fallback, and never `404`.
86+
* The refusal a by-name read throws: `@objectstack/core`'s one class (ADR-0150
87+
* D5, `409 RESOURCE_CONFLICT`), re-exported under its own name so every
88+
* existing import keeps resolving — the same binding plugin-sharing's doors
89+
* throw, so one `instanceof` matches both.
9390
*/
94-
export class PackageScopedNameRefusedError extends Error {
95-
readonly code = 'RESOURCE_CONFLICT';
96-
readonly status = 409;
97-
/** The same number under ADR-0112 D5's spelling — what a consumer holding the THROWN error reads. */
98-
readonly httpStatus = 409;
99-
/** The resolver's refusal: the reason, the caller's package and every candidate. */
100-
readonly refusal: PackageScopedRefusal;
101-
102-
constructor(refusal: PackageScopedRefusal) {
103-
super(refusal.message);
104-
this.name = 'PackageScopedNameRefusedError';
105-
this.refusal = refusal;
106-
}
107-
}
91+
export { PackageScopedNameRefusedError };
10892

10993
/**
11094
* Read `(type, name)` for a caller through {@link resolvePackageScopedName}:

‎packages/plugins/plugin-sharing/src/package-scoped-declarations.test.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
*/
2626

2727
import { describe, it, expect, beforeEach } from 'vitest';
28-
import { SchemaRegistry } from '@objectstack/objectql';
28+
import { SchemaRegistry, PackageScopedNameRefusedError as ObjectQLPackageScopedNameRefusedError } from '@objectstack/objectql';
29+
import { PackageScopedNameRefusedError as CorePackageScopedNameRefusedError } from '@objectstack/core';
2930
import { createDeclaredSharingRuleSource } from './declared-sharing-rules.js';
3031
import { SharingRuleService, bindDeclaredRuleNameGuard } from './sharing-rule-service.js';
3132
import { OwnershipQueueService } from './ownership-queue-service.js';
@@ -538,3 +539,35 @@ describe('a queue read from a caller package resolves by D3 (ADR-0150, the queue
538539
expect(await queues.queuesNaming('position', new Set(['gamma_agent']), 'org_a')).toEqual(['support']);
539540
});
540541
});
542+
543+
describe('one refusal class: objectql\'s readers and this plugin\'s doors throw the same class (#31852)', () => {
544+
it('this plugin re-exports @objectstack/core\'s class, the same binding objectql exports', () => {
545+
expect(PackageScopedNameRefusedError).toBe(CorePackageScopedNameRefusedError);
546+
expect(ObjectQLPackageScopedNameRefusedError).toBe(CorePackageScopedNameRefusedError);
547+
});
548+
549+
it('a refusal thrown by objectql\'s by-name reader is instanceof the class this plugin exports', () => {
550+
registry.registerItem<Row>('app', { name: 'home', label: 'alpha home' }, 'name', ALPHA);
551+
registry.registerItem<Row>('app', { name: 'home', label: 'beta home' }, 'name', BETA);
552+
const refused = (() => {
553+
try {
554+
registry.getApp('home');
555+
} catch (err) {
556+
return err;
557+
}
558+
return undefined;
559+
})();
560+
expect(refused).toBeInstanceOf(PackageScopedNameRefusedError);
561+
expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
562+
});
563+
564+
it('a refusal thrown by this plugin\'s by-name door is instanceof the class objectql exports', async () => {
565+
declare('sharing_rule', ALPHA, sharingRule('emea_share', 'alpha_agent'));
566+
declare('sharing_rule', BETA, sharingRule('emea_share', 'beta_agent'));
567+
const source = createDeclaredSharingRuleSource({ engine: { registry } });
568+
const rules = new SharingRuleService({ engine: makeEngine() as any, sharing: {} as any, declaredRules: source, logger: { warn: () => {} } });
569+
const refused = await rules.declaredRuleNamed('emea_share').catch((e: unknown) => e);
570+
expect(refused).toBeInstanceOf(ObjectQLPackageScopedNameRefusedError);
571+
expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
572+
});
573+
});

0 commit comments

Comments
 (0)