schemalint 1.1.0

Static analysis tool for JSON Schema compatibility with LLM structured-output providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use super::*;

// ---------------------------------------------------------------------------
// End-to-end pipeline tests (real Node helper + TypeScript project)
// ---------------------------------------------------------------------------

#[test]
fn e2e_forbidden_format_produces_diagnostic_with_source_span() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "forbidden.ts",
            r#"import { z } from "zod";
export const Bad = z.object({ website: z.string().url() });
"#,
        )],
    );

    let out = run_check_node_json(
        tmp.path(),
        &[
            "--source",
            "src/**/*.ts",
            "--profile",
            "openai.so.2026-04-30",
        ],
    );

    assert_eq!(out.profiles, vec!["openai.so.2026-04-30"]);
    assert_eq!(out.summary.errors, 1);
    assert_eq!(out.summary.warnings, 0);
    assert_eq!(out.summary.schemas_checked, 1);

    let diag = &out.diagnostics[0];
    assert_eq!(diag.code, "OAI-K-format-restricted");
    assert_eq!(diag.severity, "error");
    assert_eq!(diag.pointer, "/properties/website");
    assert_eq!(diag.profile, "openai.so.2026-04-30");

    let src = diag
        .source
        .as_ref()
        .expect("source span should be populated");
    assert!(src.file.ends_with("/forbidden.ts"), "file={}", src.file);
    assert_eq!(src.line, Some(2));
}

#[test]
fn e2e_clean_schema_exits_zero() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "clean.ts",
            r#"import { z } from "zod";
export const Good = z.object({ name: z.string(), age: z.number() });
"#,
        )],
    );

    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args([
            "check-node",
            "-S",
            "src/**/*.ts",
            "-p",
            "openai.so.2026-04-30",
            "-f",
            "json",
        ])
        .output()
        .unwrap();

    // A plain z.object({...}) won't produce additionalProperties: false,
    // so the OpenAI structural rule OAI-S-additionalProperties-required
    // may fire. The invariant we care about: the schema IS discovered and
    // checked, and the pipeline doesn't crash.
    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout).unwrap();
    assert!(
        out.summary.schemas_checked >= 1,
        "schema should be discovered"
    );
    // No format-restricted or allof errors on this clean schema
    assert!(
        !out.diagnostics
            .iter()
            .any(|d| d.code == "OAI-K-format-restricted" || d.code == "OAI-K-allOf-forbidden"),
        "clean schema should not trigger format/allof errors"
    );
}

#[test]
fn e2e_multi_schema_single_file_separate_source_spans() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "multi.ts",
            r#"import { z } from "zod";

export const UserSchema = z.object({
  email: z.string().url(),
});

export const AddressSchema = z.object({
  street: z.string(),
  city: z.string(),
});
"#,
        )],
    );

    let out = run_check_node_json(
        tmp.path(),
        &[
            "--source",
            "src/**/*.ts",
            "--profile",
            "openai.so.2026-04-30",
        ],
    );

    let user_diag = out
        .diagnostics
        .iter()
        .find(|d| d.pointer == "/properties/email")
        .expect("should diagnose /properties/email from UserSchema");

    let src = user_diag.source.as_ref().unwrap();
    assert!(src.file.ends_with("/multi.ts"));
    assert_eq!(src.line, Some(4), "url() is on line 4 of multi.ts");
}

#[test]
fn e2e_package_json_driven_without_cli_flags() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
export const My = z.object({ site: z.string().url() });
"#,
        )],
    );

    fs::write(
        tmp.path().join("package.json"),
        r#"{
  "schemalint": {
    "profiles": ["openai.so.2026-04-30"],
    "include": ["src/**/*.ts"]
  }
}"#,
    )
    .unwrap();

    let out = run_check_node_json(tmp.path(), &[]);
    assert_eq!(out.summary.errors, 1);
    assert_eq!(out.diagnostics[0].code, "OAI-K-format-restricted");
}

#[test]
fn e2e_cli_source_overrides_package_json_include() {
    let tmp = TempDir::new().unwrap();
    let src = tmp.path().join("src");
    let sub = src.join("sub");
    fs::create_dir_all(&sub).unwrap();
    fs::write(
        sub.join("nested.ts"),
        r#"import { z } from "zod";
export const Nested = z.object({ url: z.string().url() });
"#,
    )
    .unwrap();

    link_workspace_node_modules(tmp.path());

    fs::write(
        tmp.path().join("tsconfig.json"),
        r#"{"compilerOptions":{"module":"ESNext","moduleResolution":"bundler","strict":true},"include":["src/**/*.ts"]}"#,
    )
    .unwrap();

    fs::write(
        tmp.path().join("package.json"),
        r#"{
  "schemalint": {
    "profiles": ["openai.so.2026-04-30"],
    "include": ["src/nonexistent/**/*.ts"]
  }
}"#,
    )
    .unwrap();

    let out = run_check_node_json(
        tmp.path(),
        &[
            "--source",
            "src/**/*.ts",
            "--profile",
            "openai.so.2026-04-30",
        ],
    );

    assert_eq!(out.summary.errors, 1);
    assert_eq!(out.diagnostics[0].code, "OAI-K-format-restricted");
}

#[test]
fn e2e_anthropic_profile_allows_uri_format() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
export const My = z.object({ site: z.string().url() });
"#,
        )],
    );

    let out = run_check_node_json(
        tmp.path(),
        &[
            "--source",
            "src/**/*.ts",
            "--profile",
            "anthropic.so.2026-04-30",
        ],
    );

    assert!(
        !out.diagnostics
            .iter()
            .any(|d| d.code == "OAI-K-format-restricted"),
        "Anthropic profile should not produce OpenAI format-restricted diagnostics"
    );
}

#[test]
fn e2e_intersection_not_discovered_gracefully() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "intersection.ts",
            r#"import { z } from "zod";

const Person = z.object({ name: z.string() });
const Employee = z.object({ id: z.number() });

export const Combo = z.intersection(Person, Employee);
"#,
        )],
    );

    // z.intersection() is NOT discovered — the AST walker only finds
    // z.object() call expressions. This is documented behavior (scope
    // boundary: "Schemas constructed from imported factory functions...
    // are not discoverable via AST walking"). The pipeline should exit
    // cleanly with 0 schemas rather than crashing.
    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args([
            "check-node",
            "-S",
            "src/**/*.ts",
            "-p",
            "openai.so.2026-04-30",
            "-f",
            "json",
        ])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "should exit 0 (no schemas found, no error)"
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout).unwrap();
    assert_eq!(out.summary.schemas_checked, 0);
}

// ---------------------------------------------------------------------------
// Provider-hint auto-detection tests (#8)
//
// These tests exercise the auto-detect block in check_node.rs (~line 173):
//   "openai"    → openai.so.2026-04-30 profile
//   "anthropic" → anthropic.so.2026-04-30 profile
//   other       → error + exit 1   (untestable without controlling the sidecar)
//
// All three tests omit --profile so the auto-detect path is exercised.
// The sidecar emits a `provider_hint` field when it detects SDK imports from
// `openai/helpers/zod` (→ "openai") or `@anthropic-ai/sdk/helpers/zod` (→ "anthropic").
// ---------------------------------------------------------------------------

/// When source imports from `openai/helpers/zod`, the sidecar sets
/// `provider_hint = "openai"` and the CLI auto-selects openai.so.2026-04-30.
#[test]
fn e2e_provider_hint_openai_auto_selects_openai_profile() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
import { zodFunction } from "openai/helpers/zod";
export const Lookup = zodFunction({
  name: "lookup",
  parameters: z.object({ id: z.string() }),
});
"#,
        )],
    );

    // No --profile flag — rely on auto-detection.
    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args(["check-node", "-S", "src/**/*.ts", "-f", "json"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    // The CLI must log the auto-detection message.
    assert!(
        stderr.contains("auto-detected provider 'openai'"),
        "expected auto-detect log for openai, got stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("openai.so.2026-04-30"),
        "expected profile name in auto-detect log, got stderr:\n{stderr}"
    );

    // Output must be valid JSON and use the openai profile.
    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("JSON parse failed: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}"));
    assert!(
        out.profiles.iter().any(|p| p == "openai.so.2026-04-30"),
        "expected openai profile in output, got: {:?}",
        out.profiles
    );
}

/// When source imports only from `@anthropic-ai/sdk/helpers/zod`, the sidecar
/// sets `provider_hint = "anthropic"` and the CLI auto-selects anthropic.so.2026-04-30.
#[test]
fn e2e_provider_hint_anthropic_auto_selects_anthropic_profile() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
import { betaZodTool } from "@anthropic-ai/sdk/helpers/zod";
export const Translate = betaZodTool({
  name: "translate",
  inputSchema: z.object({ text: z.string(), target_language: z.string() }),
});
"#,
        )],
    );

    // No --profile flag — rely on auto-detection.
    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args(["check-node", "-S", "src/**/*.ts", "-f", "json"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("auto-detected provider 'anthropic'"),
        "expected auto-detect log for anthropic, got stderr:\n{stderr}"
    );
    assert!(
        stderr.contains("anthropic.so.2026-04-30"),
        "expected profile name in auto-detect log, got stderr:\n{stderr}"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("JSON parse failed: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}"));
    assert!(
        out.profiles.iter().any(|p| p == "anthropic.so.2026-04-30"),
        "expected anthropic profile in output, got: {:?}",
        out.profiles
    );
}

// NOTE: The "unknown provider hint" branch (check_node.rs ~line 178, the `other =>` arm)
// is not exercised here. The sidecar only emits "openai" or "anthropic" hints — there
// is no fixture that causes it to emit an arbitrary string. Testing that branch would
// require either mocking the node subprocess or patching the sidecar, neither of which
// is available in this integration harness. The branch is covered by code inspection.

// ---------------------------------------------------------------------------
// Default-profile fallback tiers when there is no --profile, no package.json
// "schemalint" config, and no source-import provider hint.
// ---------------------------------------------------------------------------

/// No provider hint (plain `z.object` with no provider SDK import), no
/// "schemalint" config in package.json, but package.json lists the `openai`
/// dependency → falls back to `detect_providers_from_deps` and selects the
/// openai profile.
#[test]
fn e2e_no_hint_falls_back_to_package_json_deps_detection() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
export const Plain = z.object({ name: z.string() });
"#,
        )],
    );
    // No "schemalint" key here — only a dependency for the deps-detection
    // tier to find.
    fs::write(
        tmp.path().join("package.json"),
        r#"{"dependencies": {"openai": "^4.0.0"}}"#,
    )
    .unwrap();

    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args(["check-node", "-S", "src/**/*.ts", "-f", "json"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("info: no --profile given; detected openai from package.json"),
        "expected deps-detection info line, got stderr:\n{stderr}"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("JSON parse failed: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}"));
    assert!(
        out.profiles.iter().any(|p| p == "openai.so.2026-04-30"),
        "expected openai profile in output, got: {:?}",
        out.profiles
    );
}

/// No provider hint, no "schemalint" config, and no recognized dependency in
/// package.json → falls all the way through to the openai default rather
/// than hard-erroring with "no profiles specified.".
#[test]
fn e2e_no_hint_no_deps_defaults_to_openai() {
    let tmp = TempDir::new().unwrap();
    setup_ts_project(
        tmp.path(),
        &[(
            "schema.ts",
            r#"import { z } from "zod";
export const Plain = z.object({ name: z.string() });
"#,
        )],
    );

    let mut cmd = Command::cargo_bin("schemalint").unwrap();
    cmd.current_dir(tmp.path());
    let output = cmd
        .args(["check-node", "-S", "src/**/*.ts", "-f", "json"])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "should exit 0 on the default profile, not hard-error"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.contains("no profiles specified."),
        "the old hard-error message must never appear, got:\n{stderr}"
    );
    assert!(
        stderr.contains(
            "info: no --profile and no provider detected in package.json; defaulting to openai.so.2026-04-30"
        ),
        "expected openai-default info line, got stderr:\n{stderr}"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let out: JsonOutput = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("JSON parse failed: {e}\nstdout:\n{stdout}\nstderr:\n{stderr}"));
    assert!(out.profiles.iter().any(|p| p == "openai.so.2026-04-30"));
}