Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/codec-standard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@systemfsoftware/api-extractor": minor
---

Every JSON encoding is now its format's Effect Schema through `Schema.fromJsonString`.

- `ApiModel.ApiModelFromJsonText` replaces `ApiModel.decode` and `ApiModel.encode`, which are removed. `ApiModel.serialise` returns an `Effect` that can fail with a `SchemaError`, instead of a `string`.
- `Verdict.RuleCorpusFromJsonText` replaces `Verdict.decodeRuleCorpus`, which is removed. `Verdict.VerdictFromJsonText` is new.
- `FrontEnd.PackageManifestFromJsonText`, `FrontEnd.ExportTargetFromPackageExports` and the `FrontEnd.ExportTarget` and `FrontEnd.PackageManifest` types are new.
- `FrontEnd.formatDocModel` and `FrontEnd.formatTsdocMetadata` return a `Result`, and `Verdict.cell` reports a `SchemaError` on its write channel, instead of throwing. `FrontEnd.ExtractPackageError` gains `SchemaError`.
- The JSON this package writes lists object keys in the order its schema declares them, not sorted, and has no trailing newline. Decoding accepts any key order, and `API_MODEL_SCHEMA_VERSION` is unchanged.
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ verdict. Requirements and decisions: `docs/plans/2026-10-10-1146-feat-effect-api
## Rules

- Read `docs/solutions/` before planning or changing code here.
- Every output goes through `canonicalJson` (`packages/api-extractor/src/canonical-json.schema.ts`).
Order strings by UTF-16 code unit with effect's `Order.String`; never `localeCompare`,
- Every JSON output is its format's Effect Schema encoded with `Schema.fromJsonString`; never a
hand-written writer, reader or key sorter. Order strings by UTF-16 code unit with effect's `Order.String`; never `localeCompare`,
`toLocale*` or `Intl` in `src`.
- Code the verdict decision reaches lives in the workflow file or in `*.schema.ts` files
beside the type it operates on (gate: `pnpm lint`, rule `dmmf-workflow(make-body-purity)`).
Expand Down
4 changes: 2 additions & 2 deletions apps/api-extractor-e2e/tests/__fixtures__/json-text.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Result, Schema } from 'effect'

const codec = Schema.fromJsonString(Schema.Unknown)
const codec = Schema.fromJsonString(Schema.Json)

export const jsonText = (value: object): string => Result.getOrThrow(Schema.encodeResult(codec)(value))
export const jsonText = (value: Schema.Json): string => Result.getOrThrow(Schema.encodeResult(codec)(value))
15 changes: 10 additions & 5 deletions apps/api-extractor-e2e/tests/front-ends.integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NodeServices } from '@effect/platform-node'
import { ApiModel, FrontEnd } from '@systemfsoftware/api-extractor'
import { Gherkin, Given, it, makeFeature, Then, When } from '@systemfsoftware/effect-gherkin-spec'
import { Effect, FileSystem, Layer, Match, Option, Path } from 'effect'
import { Effect, FileSystem, Layer, Match, Option, Path, Schema } from 'effect'
import { jsonText } from './__fixtures__/json-text.js'

const Feature = makeFeature({ it })
Expand All @@ -18,6 +18,11 @@ const STANDALONE_TSCONFIG = {

const SOURCE_CONDITION = FrontEnd.FAMILY_SOURCE_CONDITION

const roundTripped = (model: ApiModel.ApiModel): ApiModel.ApiModel =>
Effect.runSync(
Effect.flatMap(Schema.encodeEffect(ApiModel.ApiModelFromJsonText)(model), (text) => Schema.decodeEffect(ApiModel.ApiModelFromJsonText)(text)),
)

const manifestWith = (name: string, exports: Readonly<Record<string, string>>): string =>
jsonText({
name,
Expand All @@ -26,7 +31,7 @@ const manifestWith = (name: string, exports: Readonly<Record<string, string>>):
exports: Object.fromEntries(Object.entries(exports).map(([exportPath, source]) => [exportPath, { [SOURCE_CONDITION]: source }])),
})

const fallingBackPackage = (name: string, exports: Readonly<Record<string, string>>, files: Readonly<Record<string, string>>, tsconfig?: object) =>
const fallingBackPackage = (name: string, exports: Readonly<Record<string, string>>, files: Readonly<Record<string, string>>, tsconfig?: Schema.Json) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem
const path = yield* Path.Path
Expand All @@ -42,7 +47,7 @@ const fallingBackPackage = (name: string, exports: Readonly<Record<string, strin
return yield* FrontEnd.readPackage({ packageRoot: root })
})

const packageWith = (name: string, source: string, compilerOptions: object = {}) =>
const packageWith = (name: string, source: string, compilerOptions: Readonly<Record<string, Schema.Json>> = {}) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem
const path = yield* Path.Path
Expand Down Expand Up @@ -244,7 +249,7 @@ const analysedThrough = <E, Id>(emitter: Effect.Effect<FrontEnd.DeclarationEmitt
const declarations = yield* (yield* emitter).emit(source)
const model = yield* FrontEnd.buildModel({ ...declarations, producer: 'one producer' })
return {
bytes: ApiModel.serialise(model),
bytes: yield* ApiModel.serialise(model),
exports: model.entryPoints.flatMap((entry) => entry.items.map((item) => item.name)),
messages: yield* FrontEnd.resolveMessages(declarations),
files: declarations.files.map((file) => file.path),
Expand Down Expand Up @@ -587,7 +592,7 @@ Feature('Analysing a package into one model')
producer: scope.analysis.model.producer.declarations,
entryPoints: scope.analysis.model.entryPoints.map((entry) => entry.path),
exports: scope.analysis.model.entryPoints.flatMap((entry) => entry.items.map((item) => `${item.kind}:${item.name}`)),
decoded: ApiModel.decode(ApiModel.encode(scope.analysis.model)),
decoded: roundTripped(scope.analysis.model),
}).toEqual({
route: 'Fallback',
producer: FrontEnd.TYPESCRIPT_PRODUCER,
Expand Down
99 changes: 52 additions & 47 deletions apps/api-extractor-profile/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { parseSync } from 'oxc-parser'
import { isolatedDeclarationSync } from 'oxc-transform'
import ts59 from 'typescript-5.9'

const JsonText: Schema.Codec<Schema.Json, string> = Schema.fromJsonString(Schema.Json, { space: 2 })

const jsonText = (value: Schema.Json): Result.Result<string, Schema.SchemaError> => Schema.encodeResult(JsonText)(value)

const WARM_RUNS = 5
const require = createRequire(import.meta.url)

Expand Down Expand Up @@ -44,7 +48,7 @@ interface Subject {
readonly workspaceRoot: string
}

interface Timing {
type Timing = {
readonly coldMs: number
readonly warmMedianMs: number
}
Expand Down Expand Up @@ -81,7 +85,8 @@ const readManifest = (root: string) =>
const fileSystem = yield* FileSystem.FileSystem
const path = yield* Path.Path
const text = yield* fileSystem.readFileString(path.join(root, 'package.json'))
return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Manifest))(text)
const json = yield* Schema.decodeUnknownEffect(JsonText)(text)
return yield* Schema.decodeUnknownEffect(Manifest)(json)
})

const RELATIVE = /^\.\.?\//
Expand Down Expand Up @@ -160,28 +165,26 @@ const writeDerivedConfig = (tsconfig: string, workspaceRoot: string, outDir: str
const readConfigFile = (fileName: string): string | undefined => ts59.sys.readFile(fileName)
const parsed = ts59.parseJsonConfigFileContent(ts59.readConfigFile(tsconfig, readConfigFile).config, ts59.sys, path.dirname(tsconfig), undefined, tsconfig)
const derived = path.join(outDir, 'tsconfig.json')
yield* fileSystem.writeFileString(
derived,
JSON.stringify({
extends: tsconfig,
compilerOptions: {
noEmit: false,
declaration: true,
emitDeclarationOnly: true,
declarationMap: false,
sourceMap: false,
stripInternal: false,
isolatedDeclarations: false,
removeComments: false,
incremental: false,
composite: false,
rootDir: workspaceRoot,
outDir,
declarationDir: outDir,
},
files: parsed.fileNames,
}),
)
const text = yield* Effect.fromResult(jsonText({
extends: tsconfig,
compilerOptions: {
noEmit: false,
declaration: true,
emitDeclarationOnly: true,
declarationMap: false,
sourceMap: false,
stripInternal: false,
isolatedDeclarations: false,
removeComments: false,
incremental: false,
composite: false,
rootDir: workspaceRoot,
outDir,
declarationDir: outDir,
},
files: parsed.fileNames,
}))
yield* fileSystem.writeFileString(derived, text)
return derived
})

Expand Down Expand Up @@ -254,12 +257,12 @@ const PHASES = [
] as const
type Phase = (typeof PHASES)[number]

interface Cleanliness {
type Cleanliness = {
readonly diagnostics: number
readonly clean: boolean
}

interface PackageProfile {
type PackageProfile = {
readonly name: string
readonly version: string
readonly origin: Subject['origin']
Expand All @@ -275,7 +278,7 @@ interface PackageProfile {
readonly phases: Readonly<Record<Phase, Timing>>
}

interface FrontEndOutcome {
type FrontEndOutcome = {
readonly route: 'FastPath' | 'Fallback' | 'refused'
readonly outcome: string
readonly items: number
Expand Down Expand Up @@ -408,7 +411,7 @@ const versionOf = (specifier: string) =>
return manifest.version
})

interface Report {
type Report = {
readonly corpus: { readonly repository: string; readonly commit: string }
readonly ownPackage: { readonly repository: string; readonly commit: string }
readonly host: { readonly cpu: string; readonly cores: number; readonly platform: string; readonly node: string }
Expand All @@ -421,29 +424,31 @@ interface Report {
const total = (packages: ReadonlyArray<PackageProfile>, phase: Phase, key: keyof Timing): number =>
round(packages.reduce((sum, item) => sum + item.phases[phase][key], 0))

const markdownOf = (report: Report): string => {
const markdownOf = (report: Report): Result.Result<string, Schema.SchemaError> => {
const header = `| Package | Origin | Sources | oxc clean | tD clean | tsc ID clean | ${PHASES.join(' | ')} | TS7≠5.9.3 | no 5.9.3 emit | route | model |`
const rule = `|${'---|'.repeat(PHASES.length + 10)}`
const rows = report.packages.map((item) =>
`| ${item.name} | ${item.origin} | ${item.sourceFiles} | ${item.clean['oxc-transform'].diagnostics} | ${item.clean.transpileDeclaration.diagnostics} | ${item.clean['tsc --isolatedDeclarations'].diagnostics} | ${PHASES.map((phase) => item.phases[phase].warmMedianMs).join(' | ')} | ${item.divergence.differing}/${item.divergence.compared} | ${item.divergence.missing} | ${item.frontEnd.route} | ${item.frontEnd.outcome} |`
)
const totals = `| **total** | | ${report.packages.reduce((sum, item) => sum + item.sourceFiles, 0)} | | | | ${PHASES.map((phase) => report.totals[phase]).join(' | ')} | ${report.packages.reduce((sum, item) => sum + item.divergence.differing, 0)}/${report.packages.reduce((sum, item) => sum + item.divergence.compared, 0)} | ${report.packages.reduce((sum, item) => sum + item.divergence.missing, 0)} | | |`
return [
'# Front-end phase profile',
'',
'Generated by `apps/api-extractor-profile/profile.ts`; the JSON beside this file is the record. Times are warm medians in milliseconds;',
'the clean columns count isolated-declaration diagnostics over the files the entry sources reach.',
'',
'```json',
JSON.stringify(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages')), null, 2),
'```',
'',
header,
rule,
...rows,
totals,
'',
].join('\n')
return Result.map(jsonText(Object.fromEntries(Object.entries(report).filter(([key]) => key !== 'packages'))), (summary) =>
[
'# Front-end phase profile',
'',
'Generated by `apps/api-extractor-profile/profile.ts`; the JSON beside this file is the record. Times are warm medians in milliseconds;',
'the clean columns count isolated-declaration diagnostics over the files the entry sources reach.',
'',
'```json',
summary,
'```',
'',
header,
rule,
...rows,
totals,
'',
].join('\n'),
)
}

const program = Effect.gen(function* () {
Expand All @@ -468,8 +473,8 @@ const program = Effect.gen(function* () {
totals: Object.fromEntries(PHASES.map((phase) => [phase, total(packages, phase, 'warmMedianMs')])),
packages,
}
yield* fileSystem.writeFileString(`${outputArgument}.json`, `${JSON.stringify(report, null, 2)}\n`)
yield* fileSystem.writeFileString(`${outputArgument}.md`, markdownOf(report))
yield* fileSystem.writeFileString(`${outputArgument}.json`, yield* Effect.fromResult(jsonText(report)))
yield* fileSystem.writeFileString(`${outputArgument}.md`, yield* Effect.fromResult(markdownOf(report)))
})

const emitters = Layer.mergeAll(FrontEnd.isolatedEmitterLayer, FrontEnd.compilerEmitterLayer).pipe(
Expand Down
2 changes: 1 addition & 1 deletion packages/api-extractor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ The config left `projectFolder` as `<lookup>`, and neither the package nor a par

**`a surface or the corpus does not decode`**

`Verdict.cell.run` was given a value that is not an API model, or a corpus that is not the rule corpus. Produce models with `FrontEnd.analyse`, or decode them with `ApiModel.decode`.
`Verdict.cell.run` was given a value that is not an API model, or a corpus that is not the rule corpus. Produce models with `FrontEnd.analyse`, or decode them with `ApiModel.ApiModelFromJsonText`.

**`api-extractor: the API report changed; run with --local to update it`**

Expand Down
3 changes: 1 addition & 2 deletions packages/api-extractor/src/ApiModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ export {
API_MODEL_SCHEMA_VERSION as SCHEMA_VERSION,
ApiItem,
ApiModel,
ApiModelFromJsonText,
type ClassItem,
decodeApiModel as decode,
encodeApiModel as encode,
type EntryPoint,
type EnumItem,
type EnumMember,
Expand Down
3 changes: 3 additions & 0 deletions packages/api-extractor/src/FrontEnd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export {
} from './front-end/declaration-emitter.service.js'
export { DeclarationParser, type DeclarationParserId, type ParsedDeclarations, type VisitorHandlers } from './front-end/declaration-parser.service.js'
export { type DeclarationFile, Declarations, Diagnostic, Note, type PackageSource, Reported, type SourceEntryPoint } from './front-end/declarations.schema.js'
export { type ExportTarget } from './front-end/export-target.schema.js'
export { type PackageManifest, PackageManifestFromJsonText } from './front-end/package-source.schema.js'
export { ExportTargetFromPackageExports } from './front-end/package-source.schema.js'
export { CompilerRejected, CompilerUnavailable, ManifestRejected, NoSourceEntry, NotIsolated, UnsupportedDeclaration } from './front-end/front-end-error.schema.js'
export { layer as isolatedEmitterLayer, OXC_TRANSFORM_PRODUCER } from './front-end/oxc-isolated-emitter.js'
export { layer as declarationParserLayer } from './front-end/oxc-declaration-parser.js'
Expand Down
3 changes: 2 additions & 1 deletion packages/api-extractor/src/Verdict.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export { type Change, ChangeKind, type Changes, diffModels as diff } from './dif
export { Direction } from './diff/direction.schema.js'
export { ChannelType, Position, Variance } from './diff/position.schema.js'
export { judgeSurfaces as judge } from './judge-surfaces.workflow.js'
export { Bump, classify, decodeRuleCorpus, maxBump, type Rule, RuleCorpus, type RuleMatch, UNCLASSIFIED } from './rules/corpus.schema.js'
export { Bump, classify, maxBump, type Rule, RuleCorpus, RuleCorpusFromJsonText, type RuleMatch, UNCLASSIFIED } from './rules/corpus.schema.js'
export { defaultCorpus } from './rules/default-corpus.js'
export { bumpOf, Finding, Findings } from './rules/finding.schema.js'
export { type VerdictInput as Input, verdictCell as cell } from './verdict.cell.js'
Expand All @@ -16,6 +16,7 @@ export {
RuleCorpusRejected,
SurfaceRejected,
Verdict,
VerdictFromJsonText,
VERDICT_SCHEMA_VERSION as SCHEMA_VERSION,
VerdictTypeId,
} from './verdict.schema.js'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { describe } from '@systemfsoftware/vitest'
import { Result } from 'effect'
import { canonicalJson, type Json } from '../canonical-json.schema.js'
import { Result, Schema } from 'effect'
import { judgeSurfaces } from '../judge-surfaces.workflow.js'
import type { ApiItem, ApiModel } from '../model/api-model.schema.js'
import type { TypeExpr } from '../model/type-expr.schema.js'
Expand Down Expand Up @@ -37,7 +36,7 @@ const located = (result: Judged) =>
? { bump: result.success.bump, findings: result.success.findings.map((finding) => [finding.reason_code, finding.locations]) }
: { refused: result.failure.ambiguities }

const same = (left: Json, right: Json): boolean => canonicalJson(left) === canonicalJson(right)
const same = (left: Schema.Json, right: Schema.Json): boolean => Schema.toEquivalence(Schema.Json)(left, right)
const verdict = (bump: Bump, ...findings: ReadonlyArray<readonly [string, ReadonlyArray<string>]>) => ({ bump, findings })

const surface = (item: ApiItem): ApiModel => rootedWith(empty, [item])
Expand Down
Loading