Skip to content

Commit bf06a50

Browse files
fix(lint, service-automation): warn when a mapping's connectorSource.connector names no rest or openapi connector, and log a failed pull (#31833)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9TfjTSudogGJweENGQ63yHe)_ Fixes #31813 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`os validate` / `os lint` / `os build` 现在会对 mapping 的 `connectorSource.connector` 给出警告(`mapping-connector-source-unknown`),当它不是 provider 为 rest 或 openapi 的 `connectors[]` 项时;名字是数据源时直接说「这是数据源」。同步拉取失败时,每次在 warn 级别记一行日志,写明 mapping 名和原因。 - 为什么改:之前把同步指向错名字(比如数据源 `legacy_db`)时,校验和启动都说一切正常,之后每个定时周期都静默失败,只有去翻 `sys_job_run` 才能发现。 - 风险与回滚:只新增一条警告和一行日志,不改任何接受面,校验退出码不变;`sys_job_run` 的写法不变。回滚即还原本 PR。 - 先看:`packages/lint/src/validate-mapping-connector-source.ts`(判定与严重级别依据)、`packages/services/service-automation/src/connector-pull.ts`(包一层 try/catch 打 warn 后原样抛出)、`packages/lint/src/reference-integrity-suite.ts`(一行接线)。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project integration test/validate-mapping-connector-source-unknown.test.ts`,预期 1 passed:指向数据源的 mapping 得到一条警告,指向已声明 rest 连接器的 mapping 没有。 - 需要你做的:无,席位落地。 ## What changes 1. **`os validate` names the bad connector reference.** New `@objectstack/lint` rule `mapping-connector-source-unknown` (`validate-mapping-connector-source.ts`), wired as one member of the reference-integrity suite right after its mapping sibling `validateMappingTargetFields`, so `os validate`, `os lint` and `os build` all run it on the whole stack. A mapping's `connectorSource.connector` resolves when this stack, or a sibling package of the same artifact, declares a `connectors[]` entry of that name with provider `rest` or `openapi`. Otherwise one finding at `mappings[N].connectorSource.connector`, saying what the name is: a datasource, a connector of another provider, a provider-less catalog descriptor, or nothing (with the nearest declared rest/openapi name). 2. **Severity `warning`, following the nearest rule of the same class.** The same question (does a name resolve into a collection whose members can also come from outside this stack?) is asked by `capability-reference-unknown` and `ai-skill-tool-unresolved`, and both advise. The connector universe has that shape: the automation plugin materializes `connectors[]` from every loaded package and from connector rows a Studio publish stores after boot, and one package's lint sees neither. `mapping-target-field-unknown` gates, but its universe (the target object's fields) is closed inside the stack and it skips any object the stack does not define. A warning keeps the stack's exit code, so the accept set does not move and `Clause-②: no` / `Metadata-protocol: none` stand as claimed. 3. **A failed pull logs one `warn` line.** `pullConnectorSource` now wraps its body: on any failure it logs `[Automation] connector pull of mapping "NAME" failed (REASON): MESSAGE` with `{ mapping, reason }` meta (`reason` is the `ConnectorPullError` discriminator, or `failed` for any other throw), then rethrows the same error. The job run's `error` is written exactly as before. `warn`, not `error`: nothing was written, so no durability claim is broken (AGENTS.md degradation log levels), and the caller still receives the failure. 4. New exports from `@objectstack/lint`: `validateMappingConnectorSources`, `MAPPING_CONNECTOR_SOURCE_UNKNOWN`, `CONNECTOR_SOURCE_PROVIDERS`, `MappingConnectorSourceFinding`; an `os explain mapping-connector-source-unknown` entry. ## Tests - `packages/lint/src/validate-mapping-connector-source.test.ts` (new, 9 cases): datasource named as a datasource (warning, located); CONTROL rest and openapi connectors clean; another provider and a provider-less descriptor; an unknown name with "Did you mean"; a sibling package's connector resolves; no `connectorSource` / non-string connector judged nothing; the finding comes out of `validateReferenceIntegrity`; the provider pair; the explain entry. - `packages/cli/test/validate-mapping-connector-source-unknown.test.ts` (new, integration tier, one spawn): `os validate --json` on a stack with a mapping naming the datasource `legacy_db` and a second naming the declared rest connector `crm_api`. Exactly one finding, at `mappings[0]`, saying it is a datasource; exit 0. A second case pins the lint rule's provider pair to the connector pull's (`CONNECTOR_SOURCE_PROVIDERS` == `CONNECTOR_PULL_PROVIDERS`, both from the package roots). - `packages/services/service-automation/src/connector-pull.test.ts` (3 cases appended): a mapping naming `legacy_db` logs one warn line with `{ mapping, reason: 'connector_not_registered' }` and the typed refusal still reaches the caller; an untyped throw is logged as `failed` and rethrown as it was; CONTROL a successful pull logs no warn line. - Forced test change: `packages/lint/src/reference-integrity-suite.test.ts` pins the suite roster in report order, so the new member's name is added after `validateMappingTargetFields`. No other existing test was changed. <details><summary>Ablations (each red, then restored: blob == HEAD, git diff HEAD empty)</summary> A1, the suite wiring, via `scripts/ablation-replace.mjs` on `packages/lint/src/reference-integrity-suite.ts` (member made to return no findings behind a string marker), lint rebuilt, `ablation-dist-preflight` found the marker in 4 built files: - lint: `× runs inside the reference-integrity suite, which os validate dispatches` (expected length 1, got 0). - cli: `× names the datasource, and passes the mapping naming a declared rest connector`. The ablated `os validate --json` answered `"valid":true` with no finding and exit 0, which is main's behaviour: the card's red reading. - Restored, lint rebuilt, preflight `--absent`: marker absent from all 20 built files, tree clean. A2, the warn line, on `packages/services/service-automation/src/connector-pull.ts` (the `deps.logger.warn(` call put behind an unset global): - `× a mapping naming a datasource, not a connector: one warn line…` and `× a throw that is not a typed refusal is logged too…`; 2 failed, 24 passed. - Restored: blob == HEAD, `git diff HEAD` empty. </details> ## Acceptance notes - `CONNECTOR_SOURCE_PROVIDERS` in lint mirrors `CONNECTOR_PULL_PROVIDERS` in `@objectstack/service-automation`, which `@objectstack/lint` cannot import; `packages/cli`, which depends on both, holds them equal. - The rule does not judge `connectorSource.action` against the connector's actions: a rest connector's action list is materialized at run time from `providerConfig`, which static lint cannot see. - The `#21127` validate/lint test (`validate-lint-mapping-connector-source.test.ts`) declares no `crm_api` connector, so `os lint` on its fixture now also carries this warning. Its assertions filter on messages containing `connectorSource`, which this rule's message does not spell, and they stay green unchanged. ## Verification - Tree: head `0031be1a`, a merge of `origin/main` (with #31810's fix, b287761) into this branch, no rebase. The one conflict was `connector-pull.test.ts`, where both sides appended a describe at the end: main's blank-match-key block is kept byte-identical, followed by this branch's warn-line block. `connector-pull.ts` merged cleanly, and main's change sits inside `pullOnce`; this branch's diff against main in that file is only the wrapper. - Gates on `0031be1a`: `dispatch-gates --commands` derived 70, all 70 run with exit 0; `--ran` with exit codes reconciles 70 run, 0 NOT MEASURED, 0 UNRUN. - Package suites on `0031be1a` (rebuilt after the merge): `@objectstack/service-automation` test 267/267 files, 3500/3500 tests, typecheck 0; `@objectstack/lint` test 198/198 files, 8374/8374 tests, typecheck 0; `@objectstack/cli` unit project 406/406 files, 5791/5791 tests, typecheck 0; the two CLI integration files 2/2 files, 5/5 tests. - Provider parity (seat review): the CLI file asserts `CONNECTOR_SOURCE_PROVIDERS` (lint) equals `CONNECTOR_PULL_PROVIDERS` (service-automation). Ablated by changing the pull's pair to `rest` plus a marker (rebuilt, marker in 2 built files): 1 failed, 1 passed. Restored: blob == HEAD, `git diff HEAD` empty, marker absent from 6/6 built files. - Lint: none of the three packages has a `lint` script; the root eslint (`--no-inline-config`) over the changed `.ts` files exits 0. - Dogfood: not run locally (no `!` in the title, no narrowing arm, no example stack authors `connectorSource`); the queue's Dogfood Regression Gate runs it. --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmQLmfxbhuRvNyUKiJ9)_ <!-- signed: domain:server#4 · os-steve · session_01ADHkmP8JJo4zF2sjTBRwnX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b6fa08e commit bf06a50

10 files changed

Lines changed: 510 additions & 0 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/lint': patch
3+
'@objectstack/service-automation': patch
4+
---
5+
6+
fix(lint, service-automation): `os validate` warns when a mapping's `connectorSource.connector` is not a declared rest or openapi connector, and a failed connector pull logs one `warn` line
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
A mapping whose `connectorSource.connector` named a datasource, a connector of another provider, or nothing at all validated with no finding, and every scheduled pull then failed into the job run's `error` with nothing in the process log. `os validate`, `os lint` and `os build` now report `mapping-connector-source-unknown` (a warning; it says when the name is a datasource), and `@objectstack/lint` exports `validateMappingConnectorSources`, `MAPPING_CONNECTOR_SOURCE_UNKNOWN`, `CONNECTOR_SOURCE_PROVIDERS` and the `MappingConnectorSourceFinding` type. The connector pull (`pullConnectorSource`) logs `[Automation] connector pull of mapping "NAME" failed (REASON): …` at `warn` on every failed pull and rethrows the failure unchanged; the job run's `error` is written as before.
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `os validate` names a mapping whose `connectorSource.connector` is not a
5+
* declared rest or openapi connector, and says when the name is a datasource.
6+
*
7+
* ## The defect, measured before the rule
8+
*
9+
* A mapping pointing its pull at the datasource `legacy_db` validated at exit
10+
* 0 with no finding of any kind. The boot then scheduled the `job` that pulls
11+
* it, and every tick wrote a failed job run (`connector_not_registered`) that
12+
* nothing else reported. The rule (`mapping-connector-source-unknown`) is a
13+
* reference-integrity member, so `os validate` runs it on the whole stack.
14+
*
15+
* ## The control
16+
*
17+
* The same stack's second mapping names the declared `rest` connector
18+
* `crm_api`: no finding at its path. One spawn carries both legs.
19+
*
20+
* ## The provider pair
21+
*
22+
* `@objectstack/lint` cannot import `@objectstack/service-automation`, so the
23+
* rule keeps its own copy of the providers a pull reads through. This package
24+
* depends on both, so the parity case below goes red the day the pull's pair
25+
* changes and the lint copy does not.
26+
*
27+
* The CLI runs through `bin/run-dev.js` (the source entry), and
28+
* `@objectstack/lint` resolves through `exports` to `dist/`, so the lint
29+
* package must be built for this file to see the rule.
30+
*/
31+
32+
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
33+
import { execFile } from 'node:child_process';
34+
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
35+
import { tmpdir } from 'node:os';
36+
import { join, resolve } from 'node:path';
37+
import { fileURLToPath } from 'node:url';
38+
import { childEnv } from './helpers/serve-process.js';
39+
import { defineStackSource, linkSpec } from './helpers/define-stack-fixture.js';
40+
import { CONNECTOR_SOURCE_PROVIDERS } from '@objectstack/lint';
41+
import { CONNECTOR_PULL_PROVIDERS } from '@objectstack/service-automation';
42+
43+
const HERE = resolve(fileURLToPath(import.meta.url), '..');
44+
const CLI = resolve(HERE, '../bin/run-dev.js');
45+
/** A cold spawn of the CLI source entry runs well past vitest's 5 s default. */
46+
const SPAWN_TIMEOUT_MS = 120_000;
47+
const RULE = 'mapping-connector-source-unknown';
48+
49+
interface Run {
50+
code: number;
51+
stdout: string;
52+
stderr: string;
53+
}
54+
55+
function runCli(args: string[], cwd: string): Promise<Run> {
56+
return new Promise((resolvePromise) => {
57+
execFile(
58+
process.execPath,
59+
[CLI, ...args],
60+
{ cwd, maxBuffer: 16 * 1024 * 1024, env: childEnv({ NO_COLOR: '1' }) },
61+
(err, stdout, stderr) => {
62+
resolvePromise({
63+
code: err ? (typeof (err as { code?: unknown }).code === 'number' ? (err as unknown as { code: number }).code : 1) : 0,
64+
stdout: String(stdout),
65+
stderr: String(stderr),
66+
});
67+
},
68+
);
69+
});
70+
}
71+
72+
const pull = (name: string, connector: string) => ({
73+
name,
74+
label: name,
75+
sourceFormat: 'json',
76+
targetObject: 'fx_contact',
77+
mode: 'upsert',
78+
upsertKey: ['external_id'],
79+
fieldMapping: [
80+
{ source: 'id', target: 'external_id', transform: 'none' },
81+
{ source: 'name', target: 'name', transform: 'none' },
82+
],
83+
connectorSource: { connector, action: 'request' },
84+
});
85+
86+
const STACK = {
87+
manifest: { id: 'com.example.fx-connector-ref', name: 'fx', version: '0.1.0', type: 'app', namespace: 'fx' },
88+
objects: [
89+
{
90+
name: 'fx_contact',
91+
label: 'Contact',
92+
sharingModel: 'private',
93+
fields: { name: { type: 'text', label: 'Name' }, external_id: { type: 'text', label: 'External ID' } },
94+
},
95+
],
96+
datasources: [{ name: 'legacy_db', driver: 'sqlite', config: { filename: 'legacy.db' } }],
97+
connectors: [{ name: 'crm_api', label: 'CRM', type: 'api', provider: 'rest' }],
98+
mappings: [pull('fx_contacts_legacy', 'legacy_db'), pull('fx_contacts_crm', 'crm_api')],
99+
};
100+
101+
let root = '';
102+
103+
beforeAll(() => {
104+
root = mkdtempSync(join(tmpdir(), 'os-validate-connector-source-ref-'));
105+
mkdirSync(join(root, 'app'), { recursive: true });
106+
writeFileSync(join(root, 'app', 'objectstack.config.ts'), defineStackSource(STACK));
107+
linkSpec(join(root, 'app'));
108+
});
109+
110+
afterAll(() => {
111+
if (root) rmSync(root, { recursive: true, force: true });
112+
});
113+
114+
describe('`os validate` resolves a mapping\'s connectorSource.connector', () => {
115+
it('names the datasource, and passes the mapping naming a declared rest connector', async () => {
116+
const run = await runCli(['validate', '--json'], join(root, 'app'));
117+
let payload: Record<string, any>;
118+
try {
119+
payload = JSON.parse(run.stdout) as Record<string, any>;
120+
} catch {
121+
throw new Error(`stdout was not one JSON document (exit ${run.code})\n${run.stdout}\n${run.stderr}`);
122+
}
123+
const all = JSON.stringify(payload);
124+
const findings = [...(payload.errors ?? []), ...(payload.warnings ?? []), ...(payload.issues ?? [])] as Array<
125+
{ rule?: string; path?: string; message?: string; severity?: string }
126+
>;
127+
const hits = findings.filter((f) => f.rule === RULE);
128+
expect(hits.map((f) => f.path), all).toEqual(['mappings[0].connectorSource.connector']);
129+
expect(hits[0].message).toContain('"legacy_db" is a datasource');
130+
// An advisory: the stack still validates (the connector universe reaches past this stack).
131+
expect(run.code, `${run.stdout}\n${run.stderr}`).toBe(0);
132+
}, SPAWN_TIMEOUT_MS);
133+
});
134+
135+
describe('the lint rule\'s provider pair is the connector pull\'s', () => {
136+
it('CONNECTOR_SOURCE_PROVIDERS (lint) equals CONNECTOR_PULL_PROVIDERS (service-automation)', () => {
137+
expect([...CONNECTOR_SOURCE_PROVIDERS]).toEqual([...CONNECTOR_PULL_PROVIDERS]);
138+
});
139+
});

‎packages/lint/src/index.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -791,6 +791,15 @@ export {
791791
} from './validate-mapping-target-fields.js';
792792
export type { MappingTargetFieldFinding } from './validate-mapping-target-fields.js';
793793

794+
// A mapping's `connectorSource.connector` must name a declared `connectors[]`
795+
// entry whose provider a pull reads through (rest or openapi).
796+
export {
797+
validateMappingConnectorSources,
798+
MAPPING_CONNECTOR_SOURCE_UNKNOWN,
799+
CONNECTOR_SOURCE_PROVIDERS,
800+
} from './validate-mapping-connector-source.js';
801+
export type { MappingConnectorSourceFinding } from './validate-mapping-connector-source.js';
802+
794803
// The two reusable seams the rule above is written on, exported because the
795804
// queued siblings (#14148 widget filter keys + sortBy, #14107 list-view field
796805
// positions) must reuse ONE mechanism rather than growing a second hop-walker

‎packages/lint/src/reference-integrity-suite.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ describe('reference-integrity suite — membership', () => {
6565
// after the dataset member: both resolve field names written on a
6666
// collection other than the object itself.
6767
'validateMappingTargetFields',
68+
'validateMappingConnectorSources',
6869
'validateNavAccess',
6970
'validateNavTargetRefs',
7071
// [#17063] `validateViewPageRefs` sat HERE, beside the nav twin that asks

‎packages/lint/src/reference-integrity-suite.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ import { validateReportDateRange } from './validate-report-date-range.js';
114114
import { validateReportRuntimeFilters } from './validate-report-runtime-filter.js';
115115
import { validateDatasetReferences } from './validate-dataset-references.js';
116116
import { validateMappingTargetFields } from './validate-mapping-target-fields.js';
117+
import { validateMappingConnectorSources } from './validate-mapping-connector-source.js';
117118
import { validateNavAccess } from './validate-nav-access.js';
118119
import { validateNavTargetRefs } from './validate-nav-target-refs.js';
119120
import { validateNavObjectServability } from './validate-nav-object-servability.js';
@@ -613,6 +614,14 @@ export const REFERENCE_INTEGRITY_RULES: readonly ReferenceIntegrityRule[] = [
613614
// write at the runtime publish gate would be its own crossing, with its own
614615
// measurement; at runtime the import door already refuses the mapping.
615616
{ name: 'validateMappingTargetFields', run: validateMappingTargetFields },
617+
// The mapping's other name: `connectorSource.connector`, resolved against the
618+
// `connectors[]` entries (this stack's and its sibling packages') whose
619+
// provider a pull reads through, rest or openapi. It advises: the connector
620+
// universe also holds other installed packages' and Studio-published
621+
// connectors, which no single package's lint sees (the reason
622+
// `validateAiToolReferences` below advises). NO `runtimeTypes`, for the reason
623+
// its sibling above gives: no per-write snapshot carries `stack.mappings`.
624+
{ name: 'validateMappingConnectorSources', run: validateMappingConnectorSources },
616625
{ name: 'validateNavAccess', run: validateNavAccess },
617626
// Nav targets that are NOT object names — page/report/dashboard. Restores the
618627
// coverage `defineStack`'s own cross-reference block switches off whenever the

‎packages/lint/src/rule-explanations.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4971,6 +4971,28 @@ const MAPPING_TARGET_FIELD_UNKNOWN_EXPLANATION: RuleExplanation = {
49714971
],
49724972
};
49734973

4974+
// ── Mapping connector source (`validate-mapping-connector-source.ts`) ─────
4975+
4976+
const MAPPING_CONNECTOR_SOURCE_UNKNOWN_EXPLANATION: RuleExplanation = {
4977+
rule: 'mapping-connector-source-unknown',
4978+
covers: 'what a mapping\'s connector source may name',
4979+
paragraphs: [
4980+
'A mapping\'s `connectorSource.connector` names the connector a sync pulls its records from. ' +
4981+
'The pull reads only a declared instance, a `connectors[]` entry, never a connector a plugin ' +
4982+
'registers in code, and only one whose `provider` is `rest` or `openapi`. Any other name is ' +
4983+
'refused on every pull: a `job` whose `pull` names the mapping is still scheduled, and every run ' +
4984+
'records a failed job run that writes nothing. This rule reports the name at `os validate`.',
4985+
'It names what the stack can tell the name is: a datasource (a `datasources[]` entry is a ' +
4986+
'database connection, not a connector), a connector of another provider or a provider-less ' +
4987+
'catalog descriptor, or nothing at all, with the nearest declared rest or openapi connector ' +
4988+
'when one is close.',
4989+
'A warning, not an error: the automation plugin also materializes connectors other installed ' +
4990+
'packages declare and connector rows a Studio publish stores, and one package\'s lint sees ' +
4991+
'neither, so a name it cannot resolve may still resolve at run time. This stack\'s own ' +
4992+
'connectors and those of sibling packages in the same artifact are judged.',
4993+
],
4994+
};
4995+
49744996
// ── View container shape (`validate-view-containers.ts`) ───────────────────
49754997

49764998
const VIEW_CONTAINER_SHAPE_EXPLANATION: RuleExplanation = {
@@ -5968,6 +5990,7 @@ export const RULE_EXPLANATIONS: Readonly<Record<string, RuleExplanation>> = Obje
59685990
[FLOW_BRANCH_LABEL_UNMATCHED_EXPLANATION.rule]: FLOW_BRANCH_LABEL_UNMATCHED_EXPLANATION,
59695991
[ACTION_NAME_UNDEFINED_EXPLANATION.rule]: ACTION_NAME_UNDEFINED_EXPLANATION,
59705992
[MAPPING_TARGET_FIELD_UNKNOWN_EXPLANATION.rule]: MAPPING_TARGET_FIELD_UNKNOWN_EXPLANATION,
5993+
[MAPPING_CONNECTOR_SOURCE_UNKNOWN_EXPLANATION.rule]: MAPPING_CONNECTOR_SOURCE_UNKNOWN_EXPLANATION,
59715994
[VIEW_CONTAINER_SHAPE_EXPLANATION.rule]: VIEW_CONTAINER_SHAPE_EXPLANATION,
59725995
[PAGE_SOURCE_CLASSNAME_TAILWIND_EXPLANATION.rule]: PAGE_SOURCE_CLASSNAME_TAILWIND_EXPLANATION,
59735996
[PAGE_VISUALIZATION_WITHOUT_BINDING_EXPLANATION.rule]: PAGE_VISUALIZATION_WITHOUT_BINDING_EXPLANATION,
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
5+
import {
6+
CONNECTOR_SOURCE_PROVIDERS,
7+
MAPPING_CONNECTOR_SOURCE_UNKNOWN,
8+
validateMappingConnectorSources,
9+
} from './validate-mapping-connector-source.js';
10+
import { explainRule } from './rule-explanations.js';
11+
import { validateReferenceIntegrity } from './reference-integrity-suite.js';
12+
13+
// A mapping's `connectorSource.connector` names the connector a pull reads
14+
// from. The executor refuses every name that is not a declared rest or openapi
15+
// `connectors[]` entry, on every pull; this rule says so at `os validate`.
16+
17+
const pull = (connector: unknown, extra: Record<string, unknown> = {}) => ({
18+
name: 'crm_contacts',
19+
targetObject: 'contact',
20+
fieldMapping: [{ source: 'id', target: 'external_id' }],
21+
connectorSource: { connector, action: 'request' },
22+
...extra,
23+
});
24+
25+
const restConnector = { name: 'crm_api', label: 'CRM', type: 'api', provider: 'rest', providerConfig: { baseUrl: 'https://crm.example.com' } };
26+
const legacyDb = { name: 'legacy_db', driver: 'postgres', config: {} };
27+
28+
describe('validateMappingConnectorSources', () => {
29+
it('names a datasource as a datasource, at the connector key, as a warning', () => {
30+
const findings = validateMappingConnectorSources({
31+
connectors: [restConnector],
32+
datasources: [legacyDb],
33+
mappings: [pull('legacy_db')],
34+
});
35+
expect(findings).toHaveLength(1);
36+
expect(findings[0]).toMatchObject({
37+
severity: 'warning',
38+
rule: MAPPING_CONNECTOR_SOURCE_UNKNOWN,
39+
where: 'mapping "crm_contacts" · connector "legacy_db"',
40+
path: 'mappings[0].connectorSource.connector',
41+
});
42+
expect(findings[0].message).toContain('is a datasource');
43+
});
44+
45+
it('CONTROL: a mapping naming a declared rest connector is clean, and so is an openapi one', () => {
46+
expect(validateMappingConnectorSources({ connectors: [restConnector], mappings: [pull('crm_api')] })).toEqual([]);
47+
expect(validateMappingConnectorSources({
48+
connectors: [{ ...restConnector, name: 'erp_api', provider: 'openapi' }],
49+
mappings: [pull('erp_api')],
50+
})).toEqual([]);
51+
});
52+
53+
it('names a connector of another provider, and a provider-less catalog descriptor', () => {
54+
const findings = validateMappingConnectorSources({
55+
connectors: [
56+
{ ...restConnector, name: 'crm_mcp', provider: 'mcp' },
57+
{ name: 'crm_catalog', label: 'CRM catalog', type: 'api' },
58+
],
59+
mappings: [pull('crm_mcp'), pull('crm_catalog', { name: 'crm_catalog_pull' })],
60+
});
61+
expect(findings.map((f) => f.path)).toEqual([
62+
'mappings[0].connectorSource.connector',
63+
'mappings[1].connectorSource.connector',
64+
]);
65+
expect(findings[0].message).toContain('"mcp" connector');
66+
expect(findings[1].message).toContain('no provider');
67+
});
68+
69+
it('names a name that is nothing, with the nearest rest connector', () => {
70+
const findings = validateMappingConnectorSources({ connectors: [restConnector], mappings: [pull('crm_apii')] });
71+
expect(findings).toHaveLength(1);
72+
expect(findings[0].message).toContain('names no connectors[] entry');
73+
expect(findings[0].message).toContain('Did you mean "crm_api"?');
74+
});
75+
76+
it('resolves a connector a sibling package of the same artifact declares', () => {
77+
const stack = {
78+
mappings: [pull('crm_api')],
79+
packages: [{ manifest: { id: 'com.example.connectors', name: 'connectors', version: '1.0.0', connectors: [restConnector] } }],
80+
};
81+
expect(validateMappingConnectorSources(stack)).toEqual([]);
82+
});
83+
84+
it('judges nothing without a connectorSource, or with a connector that is not a name', () => {
85+
expect(validateMappingConnectorSources({
86+
mappings: [
87+
{ name: 'csv_import', targetObject: 'contact', fieldMapping: [] },
88+
pull(42),
89+
pull(''),
90+
],
91+
})).toEqual([]);
92+
});
93+
94+
it('runs inside the reference-integrity suite, which `os validate` dispatches', () => {
95+
const findings = validateReferenceIntegrity({ datasources: [legacyDb], mappings: [pull('legacy_db')] });
96+
expect(findings.filter((f) => f.rule === MAPPING_CONNECTOR_SOURCE_UNKNOWN)).toHaveLength(1);
97+
});
98+
99+
it('mirrors the providers the connector pull reads through', () => {
100+
expect([...CONNECTOR_SOURCE_PROVIDERS]).toEqual(['rest', 'openapi']);
101+
});
102+
103+
it('has an `os explain` entry', () => {
104+
expect(explainRule(MAPPING_CONNECTOR_SOURCE_UNKNOWN)?.rule).toBe(MAPPING_CONNECTOR_SOURCE_UNKNOWN);
105+
});
106+
});

0 commit comments

Comments
 (0)