@noego/trust 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -21
- package/dist/{chunk-APNT6ZSM.js → chunk-YJYGTNJD.js} +3 -3
- package/dist/chunk-YJYGTNJD.js.map +1 -0
- package/dist/cli/index.js +2 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/eslint/index.d.ts +3 -3
- package/dist/eslint/index.js +2 -2
- package/dist/eslint/index.js.map +1 -1
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -15
- package/dist/index.d.ts +42 -15
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-APNT6ZSM.js.map +0 -1
package/dist/cli/index.js
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
parseBaseline,
|
|
11
11
|
realpathOrSelf,
|
|
12
12
|
serializeBaseline
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-YJYGTNJD.js";
|
|
14
14
|
|
|
15
15
|
// src/cli/baseline-command.ts
|
|
16
16
|
import { existsSync, readFileSync, writeFileSync } from "fs";
|
|
@@ -54,7 +54,7 @@ async function runBaselineCommand(options) {
|
|
|
54
54
|
const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);
|
|
55
55
|
options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);
|
|
56
56
|
for (const delta of added) for (const line of describeDelta(delta)) options.log(` ${line}`);
|
|
57
|
-
options.log("Guard each call (try/catch returning Result.err, or
|
|
57
|
+
options.log("Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.");
|
|
58
58
|
options.log("`trust explain <file>:<line>` shows which origin a call resolves to.");
|
|
59
59
|
return 1;
|
|
60
60
|
}
|
package/dist/cli/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/baseline-command.ts","../../src/cli/explain.ts","../../src/cli/index.ts"],"sourcesContent":["// `trust baseline [paths…] [--update]` — runs the project's own ESLint config and compares the\n// trust-rule findings against trust-baseline.json (file + rule + origin → count).\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join, resolve } from 'node:path';\nimport type { ESLint as ESLintClass } from 'eslint';\nimport {\n compareToBaseline,\n countFindings,\n fatalMessages,\n findingsFromResults,\n parseBaseline,\n serializeBaseline,\n type BaselineDelta,\n} from '../eslint/baseline.js';\nimport { loadTrustConfig } from '../eslint/config.js';\n\nexport interface BaselineCommandOptions {\n readonly cwd: string;\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly baselineFile?: string;\n readonly update: boolean;\n readonly log: (line: string) => void;\n /** Extra ESLint constructor options (tests use overrideConfig to inject the plugin). */\n readonly eslintOptions?: ESLintClass.Options;\n}\n\nfunction loadESLint(cwd: string): typeof ESLintClass {\n const require = createRequire(join(cwd, '__noego_trust__.cjs'));\n return (require('eslint') as { ESLint: typeof ESLintClass }).ESLint;\n}\n\nfunction describeDelta(delta: BaselineDelta): string[] {\n const header = `${delta.file} ${delta.rule} ${delta.origin}: ${delta.found} found, ${delta.allowed} baselined`;\n return [header, ...delta.findings.map((finding) => ` ${delta.file}:${finding.line}:${finding.column} ${finding.message}`)];\n}\n\n/** Returns the process exit code: 0 ok, 1 new violations, 2 lint could not run cleanly. */\nexport async function runBaselineCommand(options: BaselineCommandOptions): Promise<number> {\n const config = loadTrustConfig(resolve(options.cwd, options.configFile));\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const ESLint = loadESLint(options.cwd);\n const eslint = new ESLint({ cwd: options.cwd, ...options.eslintOptions });\n const results = await eslint.lintFiles(options.paths.length > 0 ? [...options.paths] : ['.']);\n const fatal = fatalMessages(results);\n if (fatal.length > 0) {\n options.log(`ESLint reported ${fatal.length} fatal error(s); fix them before using the baseline:`);\n for (const line of fatal.slice(0, 50)) options.log(` ${line}`);\n return 2;\n }\n const findings = findingsFromResults(results, config.rootDir);\n if (options.update) {\n writeFileSync(baselineFile, serializeBaseline(countFindings(findings)));\n options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${results.length} linted file(s).`);\n return 0;\n }\n const baseline = existsSync(baselineFile) ? parseBaseline(readFileSync(baselineFile, 'utf8'), baselineFile) : {};\n const { added, stale } = compareToBaseline(findings, baseline);\n if (stale.length > 0) {\n options.log(`${stale.length} baseline entr${stale.length === 1 ? 'y has' : 'ies have'} fewer findings now; run with --update to shrink the baseline.`);\n }\n if (added.length === 0) {\n options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${results.length} file(s)).`);\n return 0;\n }\n const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);\n options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);\n for (const delta of added) for (const line of describeDelta(delta)) options.log(` ${line}`);\n options.log('Guard each call (try/catch returning Result.err, or Result.try), or trust its origin in trust.config.json.');\n options.log('`trust explain <file>:<line>` shows which origin a call resolves to.');\n return 1;\n}\n","// `trust explain <file>:<line>[:<column>]` — which origin does each call on that line resolve to,\n// and why is it (un)trusted? Tells the user exactly which trust entry to add or remove.\nimport { dirname, resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { TrustPolicy, type Verdict } from '../eslint/policy.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\nimport { realpathOrSelf } from '../eslint/zones.js';\n\nexport interface ExplainOptions {\n readonly cwd: string;\n readonly file: string;\n readonly line: number;\n readonly column?: number;\n readonly configFile: string;\n readonly tsconfig?: string;\n}\n\nexport interface ExplainedCall {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n readonly verdict: Verdict;\n readonly declaredAt: string | null;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly zone: string;\n readonly calls: readonly ExplainedCall[];\n}\n\nfunction compilerOptions(ts: typeof TS, tsconfig: string | undefined): TS.CompilerOptions {\n if (!tsconfig) return { allowJs: true, strict: true };\n const parsed = ts.getParsedCommandLineOfConfigFile(tsconfig, {}, {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: (diagnostic) => {\n throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'));\n },\n });\n return parsed?.options ?? {};\n}\n\nfunction declaredAt(ts: typeof TS, policy: TrustPolicy, node: TS.CallExpression | TS.NewExpression): string | null {\n const resolved = policy.calleeDeclaration(node);\n if (!resolved) return null;\n const source = resolved.declaration.getSourceFile();\n const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));\n return `${source.fileName}:${line + 1}`;\n}\n\nexport function explain(options: ExplainOptions): Explanation {\n const ts = loadTypeScript(options.cwd);\n const file = resolve(options.cwd, options.file);\n const tsconfig = options.tsconfig ? resolve(options.cwd, options.tsconfig) : ts.findConfigFile(dirname(file), ts.sys.fileExists);\n const program = ts.createProgram({ rootNames: [file], options: { ...compilerOptions(ts, tsconfig), noEmit: true } });\n const source = program.getSourceFile(file) ?? program.getSourceFile(realpathOrSelf(file));\n if (!source) throw new Error(`could not load ${file} into a TypeScript program`);\n const checker = program.getTypeChecker();\n const policy = new TrustPolicy(ts, checker, loadTrustConfig(resolve(options.cwd, options.configFile)));\n const calls: ExplainedCall[] = [];\n const visit = (node: TS.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n const position = ts.getLineAndCharacterOfPosition(source, node.getStart(source));\n const onLine = position.line + 1 === options.line;\n if (onLine && (options.column === undefined || position.character + 1 === options.column)) {\n const text = node.getText(source).replace(/\\s+/g, ' ');\n calls.push({\n line: position.line + 1,\n column: position.character + 1,\n text: text.length > 80 ? `${text.slice(0, 77)}...` : text,\n verdict: policy.classify(node),\n declaredAt: declaredAt(ts, policy, node),\n });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return { file, zone: policy.zones.zoneOf(file), calls };\n}\n\nfunction describe(verdict: Verdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return ['verdict: not checked (callee has no declaration, e.g. an `any` value)'];\n case 'first-party':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (first-party code in a checked file is checked itself)'];\n case 'returns-result':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (declared return type is Result from @noego/trust)'];\n case 'trusted':\n return [`origin: ${verdict.origin.origin}`, `verdict: trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'calls-ignored':\n return [\n `origin: ${verdict.origin.origin}`,\n 'verdict: reported (callsIgnored): the callee file is ignored; make it passthrough so calls into it must be handled',\n ];\n case 'untrusted':\n return [\n `origin: ${verdict.origin.origin}`,\n verdict.distrustedBy\n ? `verdict: UNTRUSTED (distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'verdict: UNTRUSTED (no trust entry matches)',\n `hint: guard it, or trust \"${verdict.origin.origin}\" (or a prefix of it) in trust.config.json`,\n ];\n }\n}\n\nexport function formatExplanation(explanation: Explanation): string {\n const lines = [`${explanation.file} (zone: ${explanation.zone})`];\n if (explanation.zone !== 'checked') lines.push('note: calls in this file are not checked (only checked-zone files are linted)');\n if (explanation.calls.length === 0) lines.push('no call or `new` expression starts at that location');\n for (const call of explanation.calls) {\n lines.push('', `${call.line}:${call.column} ${call.text}`);\n for (const detail of describe(call.verdict)) lines.push(` ${detail}`);\n if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);\n }\n return lines.join('\\n');\n}\n","#!/usr/bin/env node\n// trust — CLI for @noego/trust.\n//\n// trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig tsconfig.json]\n// trust baseline [paths…] [--config trust.config.json] [--baseline trust-baseline.json] [--update]\nimport { runBaselineCommand } from './baseline-command.js';\nimport { explain, formatExplanation } from './explain.js';\n\nconst USAGE = `Usage:\n trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>]\n Print the origin each call on that line resolves to, and why it is (un)trusted.\n trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update]\n Lint with the project's ESLint config and fail on trust violations not in the baseline.\n --update rewrites the baseline from the current findings.`;\n\ninterface ParsedArgs {\n readonly positional: string[];\n readonly flags: Map<string, string | true>;\n}\n\nfunction parseArgs(argv: readonly string[]): ParsedArgs {\n const positional: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (!arg.startsWith('--')) {\n positional.push(arg);\n continue;\n }\n const [name, inline] = arg.slice(2).split('=', 2);\n if (inline !== undefined) flags.set(name, inline);\n else if (name === 'update' || name === 'help') flags.set(name, true);\n else {\n const value = argv[index + 1];\n if (value === undefined) throw new Error(`--${name} needs a value`);\n flags.set(name, value);\n index += 1;\n }\n }\n return { positional, flags };\n}\n\nfunction stringFlag(flags: Map<string, string | true>, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseLocation(location: string): { file: string; line: number; column?: number } {\n const match = /^(.*?):(\\d+)(?::(\\d+))?$/.exec(location);\n if (!match) throw new Error(`expected <file>:<line>[:<column>], got \"${location}\"`);\n return { file: match[1], line: Number(match[2]), column: match[3] ? Number(match[3]) : undefined };\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const [command, ...rest] = argv;\n const { positional, flags } = parseArgs(rest);\n const cwd = process.cwd();\n const configFile = stringFlag(flags, 'config') ?? 'trust.config.json';\n if (!command || command === 'help' || flags.has('help')) {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n if (command === 'explain') {\n if (positional.length !== 1) throw new Error('explain takes exactly one <file>:<line>[:<column>]');\n const location = parseLocation(positional[0]);\n console.log(formatExplanation(explain({ cwd, configFile, tsconfig: stringFlag(flags, 'tsconfig'), ...location })));\n return 0;\n }\n if (command === 'baseline') {\n return runBaselineCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n update: flags.get('update') === true,\n log: (line) => console.log(line),\n });\n }\n throw new Error(`unknown command \"${command}\"\\n${USAGE}`);\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (error: unknown) => {\n console.error(`trust: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;AAEA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,qBAAqB;AAC9B,SAAS,MAAM,eAAe;AAwB9B,SAAS,WAAW,KAAiC;AACnD,QAAMA,WAAU,cAAc,KAAK,KAAK,qBAAqB,CAAC;AAC9D,SAAQA,SAAQ,QAAQ,EAAqC;AAC/D;AAEA,SAAS,cAAc,OAAgC;AACrD,QAAM,SAAS,GAAG,MAAM,IAAI,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,KAAK,MAAM,KAAK,WAAW,MAAM,OAAO;AACpG,SAAO,CAAC,QAAQ,GAAG,MAAM,SAAS,IAAI,CAAC,YAAY,OAAO,MAAM,IAAI,IAAI,QAAQ,IAAI,IAAI,QAAQ,MAAM,KAAK,QAAQ,OAAO,EAAE,CAAC;AAC/H;AAGA,eAAsB,mBAAmB,SAAkD;AACzF,QAAM,SAAS,gBAAgB,QAAQ,QAAQ,KAAK,QAAQ,UAAU,CAAC;AACvE,QAAM,eAAe,QAAQ,QAAQ,KAAK,QAAQ,gBAAgB,KAAK,OAAO,SAAS,qBAAqB,CAAC;AAC7G,QAAM,SAAS,WAAW,QAAQ,GAAG;AACrC,QAAM,SAAS,IAAI,OAAO,EAAE,KAAK,QAAQ,KAAK,GAAG,QAAQ,cAAc,CAAC;AACxE,QAAM,UAAU,MAAM,OAAO,UAAU,QAAQ,MAAM,SAAS,IAAI,CAAC,GAAG,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC;AAC5F,QAAM,QAAQ,cAAc,OAAO;AACnC,MAAI,MAAM,SAAS,GAAG;AACpB,YAAQ,IAAI,mBAAmB,MAAM,MAAM,sDAAsD;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;AAAA,IACjC,CAAC;AAAA,EACH;AACA,QAAM,IAAI,MAAM,oBAAoB,OAAO;AAAA,EAAM,KAAK,EAAE;AAC1D;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAC1B,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["require","resolve","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/baseline-command.ts","../../src/cli/explain.ts","../../src/cli/index.ts"],"sourcesContent":["// `trust baseline [paths…] [--update]` — runs the project's own ESLint config and compares the\n// trust-rule findings against trust-baseline.json (file + rule + origin → count).\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { join, resolve } from 'node:path';\nimport type { ESLint as ESLintClass } from 'eslint';\nimport {\n compareToBaseline,\n countFindings,\n fatalMessages,\n findingsFromResults,\n parseBaseline,\n serializeBaseline,\n type BaselineDelta,\n} from '../eslint/baseline.js';\nimport { loadTrustConfig } from '../eslint/config.js';\n\nexport interface BaselineCommandOptions {\n readonly cwd: string;\n readonly paths: readonly string[];\n readonly configFile: string;\n readonly baselineFile?: string;\n readonly update: boolean;\n readonly log: (line: string) => void;\n /** Extra ESLint constructor options (tests use overrideConfig to inject the plugin). */\n readonly eslintOptions?: ESLintClass.Options;\n}\n\nfunction loadESLint(cwd: string): typeof ESLintClass {\n const require = createRequire(join(cwd, '__noego_trust__.cjs'));\n return (require('eslint') as { ESLint: typeof ESLintClass }).ESLint;\n}\n\nfunction describeDelta(delta: BaselineDelta): string[] {\n const header = `${delta.file} ${delta.rule} ${delta.origin}: ${delta.found} found, ${delta.allowed} baselined`;\n return [header, ...delta.findings.map((finding) => ` ${delta.file}:${finding.line}:${finding.column} ${finding.message}`)];\n}\n\n/** Returns the process exit code: 0 ok, 1 new violations, 2 lint could not run cleanly. */\nexport async function runBaselineCommand(options: BaselineCommandOptions): Promise<number> {\n const config = loadTrustConfig(resolve(options.cwd, options.configFile));\n const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, 'trust-baseline.json'));\n const ESLint = loadESLint(options.cwd);\n const eslint = new ESLint({ cwd: options.cwd, ...options.eslintOptions });\n const results = await eslint.lintFiles(options.paths.length > 0 ? [...options.paths] : ['.']);\n const fatal = fatalMessages(results);\n if (fatal.length > 0) {\n options.log(`ESLint reported ${fatal.length} fatal error(s); fix them before using the baseline:`);\n for (const line of fatal.slice(0, 50)) options.log(` ${line}`);\n return 2;\n }\n const findings = findingsFromResults(results, config.rootDir);\n if (options.update) {\n writeFileSync(baselineFile, serializeBaseline(countFindings(findings)));\n options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${results.length} linted file(s).`);\n return 0;\n }\n const baseline = existsSync(baselineFile) ? parseBaseline(readFileSync(baselineFile, 'utf8'), baselineFile) : {};\n const { added, stale } = compareToBaseline(findings, baseline);\n if (stale.length > 0) {\n options.log(`${stale.length} baseline entr${stale.length === 1 ? 'y has' : 'ies have'} fewer findings now; run with --update to shrink the baseline.`);\n }\n if (added.length === 0) {\n options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${results.length} file(s)).`);\n return 0;\n }\n const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);\n options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);\n for (const delta of added) for (const line of describeDelta(delta)) options.log(` ${line}`);\n options.log('Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.');\n options.log('`trust explain <file>:<line>` shows which origin a call resolves to.');\n return 1;\n}\n","// `trust explain <file>:<line>[:<column>]` — which origin does each call on that line resolve to,\n// and why is it (un)trusted? Tells the user exactly which trust entry to add or remove.\nimport { dirname, resolve } from 'node:path';\nimport type * as TS from 'typescript';\nimport { loadTrustConfig } from '../eslint/config.js';\nimport { TrustPolicy, type Verdict } from '../eslint/policy.js';\nimport { loadTypeScript } from '../eslint/typescript.js';\nimport { realpathOrSelf } from '../eslint/zones.js';\n\nexport interface ExplainOptions {\n readonly cwd: string;\n readonly file: string;\n readonly line: number;\n readonly column?: number;\n readonly configFile: string;\n readonly tsconfig?: string;\n}\n\nexport interface ExplainedCall {\n readonly line: number;\n readonly column: number;\n readonly text: string;\n readonly verdict: Verdict;\n readonly declaredAt: string | null;\n}\n\nexport interface Explanation {\n readonly file: string;\n readonly zone: string;\n readonly calls: readonly ExplainedCall[];\n}\n\nfunction compilerOptions(ts: typeof TS, tsconfig: string | undefined): TS.CompilerOptions {\n if (!tsconfig) return { allowJs: true, strict: true };\n const parsed = ts.getParsedCommandLineOfConfigFile(tsconfig, {}, {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: (diagnostic) => {\n throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n'));\n },\n });\n return parsed?.options ?? {};\n}\n\nfunction declaredAt(ts: typeof TS, policy: TrustPolicy, node: TS.CallExpression | TS.NewExpression): string | null {\n const resolved = policy.calleeDeclaration(node);\n if (!resolved) return null;\n const source = resolved.declaration.getSourceFile();\n const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));\n return `${source.fileName}:${line + 1}`;\n}\n\nexport function explain(options: ExplainOptions): Explanation {\n const ts = loadTypeScript(options.cwd);\n const file = resolve(options.cwd, options.file);\n const tsconfig = options.tsconfig ? resolve(options.cwd, options.tsconfig) : ts.findConfigFile(dirname(file), ts.sys.fileExists);\n const program = ts.createProgram({ rootNames: [file], options: { ...compilerOptions(ts, tsconfig), noEmit: true } });\n const source = program.getSourceFile(file) ?? program.getSourceFile(realpathOrSelf(file));\n if (!source) throw new Error(`could not load ${file} into a TypeScript program`);\n const checker = program.getTypeChecker();\n const policy = new TrustPolicy(ts, checker, loadTrustConfig(resolve(options.cwd, options.configFile)));\n const calls: ExplainedCall[] = [];\n const visit = (node: TS.Node): void => {\n if (ts.isCallExpression(node) || ts.isNewExpression(node)) {\n const position = ts.getLineAndCharacterOfPosition(source, node.getStart(source));\n const onLine = position.line + 1 === options.line;\n if (onLine && (options.column === undefined || position.character + 1 === options.column)) {\n const text = node.getText(source).replace(/\\s+/g, ' ');\n calls.push({\n line: position.line + 1,\n column: position.character + 1,\n text: text.length > 80 ? `${text.slice(0, 77)}...` : text,\n verdict: policy.classify(node),\n declaredAt: declaredAt(ts, policy, node),\n });\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return { file, zone: policy.zones.zoneOf(file), calls };\n}\n\nfunction describe(verdict: Verdict): string[] {\n switch (verdict.kind) {\n case 'unresolved':\n return ['verdict: not checked (callee has no declaration, e.g. an `any` value)'];\n case 'first-party':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (first-party code in a checked file is checked itself)'];\n case 'returns-result':\n return [`origin: ${verdict.origin.origin}`, 'verdict: trusted (declared return type is Result from @noego/trust)'];\n case 'trusted':\n return [`origin: ${verdict.origin.origin}`, `verdict: trusted by \"${verdict.by.entry}\" in ${verdict.by.source}`];\n case 'calls-ignored':\n return [\n `origin: ${verdict.origin.origin}`,\n 'verdict: reported (callsIgnored): the callee file is ignored; make it passthrough so calls into it must be handled',\n ];\n case 'untrusted':\n return [\n `origin: ${verdict.origin.origin}`,\n verdict.distrustedBy\n ? `verdict: UNTRUSTED (distrusted by \"${verdict.distrustedBy.entry}\" in ${verdict.distrustedBy.source})`\n : 'verdict: UNTRUSTED (no trust entry matches)',\n `hint: guard it, or trust \"${verdict.origin.origin}\" (or a prefix of it) in trust.config.json`,\n ];\n }\n}\n\nexport function formatExplanation(explanation: Explanation): string {\n const lines = [`${explanation.file} (zone: ${explanation.zone})`];\n if (explanation.zone !== 'checked') lines.push('note: calls in this file are not checked (only checked-zone files are linted)');\n if (explanation.calls.length === 0) lines.push('no call or `new` expression starts at that location');\n for (const call of explanation.calls) {\n lines.push('', `${call.line}:${call.column} ${call.text}`);\n for (const detail of describe(call.verdict)) lines.push(` ${detail}`);\n if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);\n }\n return lines.join('\\n');\n}\n","#!/usr/bin/env node\n// trust — CLI for @noego/trust.\n//\n// trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig tsconfig.json]\n// trust baseline [paths…] [--config trust.config.json] [--baseline trust-baseline.json] [--update]\nimport { runBaselineCommand } from './baseline-command.js';\nimport { explain, formatExplanation } from './explain.js';\n\nconst USAGE = `Usage:\n trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>]\n Print the origin each call on that line resolves to, and why it is (un)trusted.\n trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update]\n Lint with the project's ESLint config and fail on trust violations not in the baseline.\n --update rewrites the baseline from the current findings.`;\n\ninterface ParsedArgs {\n readonly positional: string[];\n readonly flags: Map<string, string | true>;\n}\n\nfunction parseArgs(argv: readonly string[]): ParsedArgs {\n const positional: string[] = [];\n const flags = new Map<string, string | true>();\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index];\n if (!arg.startsWith('--')) {\n positional.push(arg);\n continue;\n }\n const [name, inline] = arg.slice(2).split('=', 2);\n if (inline !== undefined) flags.set(name, inline);\n else if (name === 'update' || name === 'help') flags.set(name, true);\n else {\n const value = argv[index + 1];\n if (value === undefined) throw new Error(`--${name} needs a value`);\n flags.set(name, value);\n index += 1;\n }\n }\n return { positional, flags };\n}\n\nfunction stringFlag(flags: Map<string, string | true>, name: string): string | undefined {\n const value = flags.get(name);\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction parseLocation(location: string): { file: string; line: number; column?: number } {\n const match = /^(.*?):(\\d+)(?::(\\d+))?$/.exec(location);\n if (!match) throw new Error(`expected <file>:<line>[:<column>], got \"${location}\"`);\n return { file: match[1], line: Number(match[2]), column: match[3] ? Number(match[3]) : undefined };\n}\n\nasync function main(argv: readonly string[]): Promise<number> {\n const [command, ...rest] = argv;\n const { positional, flags } = parseArgs(rest);\n const cwd = process.cwd();\n const configFile = stringFlag(flags, 'config') ?? 'trust.config.json';\n if (!command || command === 'help' || flags.has('help')) {\n console.log(USAGE);\n return command ? 0 : 1;\n }\n if (command === 'explain') {\n if (positional.length !== 1) throw new Error('explain takes exactly one <file>:<line>[:<column>]');\n const location = parseLocation(positional[0]);\n console.log(formatExplanation(explain({ cwd, configFile, tsconfig: stringFlag(flags, 'tsconfig'), ...location })));\n return 0;\n }\n if (command === 'baseline') {\n return runBaselineCommand({\n cwd,\n paths: positional,\n configFile,\n baselineFile: stringFlag(flags, 'baseline'),\n update: flags.get('update') === true,\n log: (line) => console.log(line),\n });\n }\n throw new Error(`unknown command \"${command}\"\\n${USAGE}`);\n}\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code;\n },\n (error: unknown) => {\n console.error(`trust: ${error instanceof Error ? error.message : String(error)}`);\n process.exitCode = 2;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;AAEA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,qBAAqB;AAC9B,SAAS,MAAM,eAAe;AAwB9B,SAAS,WAAW,KAAiC;AACnD,QAAMA,WAAU,cAAc,KAAK,KAAK,qBAAqB,CAAC;AAC9D,SAAQA,SAAQ,QAAQ,EAAqC;AAC/D;AAEA,SAAS,cAAc,OAAgC;AACrD,QAAM,SAAS,GAAG,MAAM,IAAI,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,KAAK,MAAM,KAAK,WAAW,MAAM,OAAO;AACpG,SAAO,CAAC,QAAQ,GAAG,MAAM,SAAS,IAAI,CAAC,YAAY,OAAO,MAAM,IAAI,IAAI,QAAQ,IAAI,IAAI,QAAQ,MAAM,KAAK,QAAQ,OAAO,EAAE,CAAC;AAC/H;AAGA,eAAsB,mBAAmB,SAAkD;AACzF,QAAM,SAAS,gBAAgB,QAAQ,QAAQ,KAAK,QAAQ,UAAU,CAAC;AACvE,QAAM,eAAe,QAAQ,QAAQ,K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;AACjG,UAAM,WAAW,cAAc,WAAW,CAAC,CAAC;AAC5C,YAAQ,IAAI,kBAAkB,QAAQ,EAAE,KAAK,YAAY,UAAU,WAAW,OAAO,UAAU,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC;AACjH,WAAO;AAAA,EACT;AACA,MAAI,YAAY,YAAY;AAC1B,WAAO,mBAAmB;AAAA,MACxB;AAAA,MACA,OAAO;AAAA,MACP;AAAA,MACA,cAAc,WAAW,OAAO,UAAU;AAAA,MAC1C,QAAQ,MAAM,IAAI,QAAQ,MAAM;AAAA,MAChC,KAAK,CAAC,SAAS,QAAQ,IAAI,IAAI;AAAA,IACjC,CAAC;AAAA,EACH;AACA,QAAM,IAAI,MAAM,oBAAoB,OAAO;AAAA,EAAM,KAAK,EAAE;AAC1D;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAC1B,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAChF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["require","resolve","resolve"]}
|
package/dist/eslint/index.d.ts
CHANGED
|
@@ -184,7 +184,7 @@ interface GuardContext {
|
|
|
184
184
|
isResultErr(expression: AstNode): boolean;
|
|
185
185
|
/** The call is `Result.err(...)` / `err(...)` itself (for the raw-caught-value check). */
|
|
186
186
|
isErrCall(expression: AstNode): boolean;
|
|
187
|
-
/** 'sync' for
|
|
187
|
+
/** 'sync' for Trust.try, 'async' for Trust.tryAsync, else null. */
|
|
188
188
|
trustTryKind(call: AstNode): 'sync' | 'async' | null;
|
|
189
189
|
}
|
|
190
190
|
/** Every path through `statement` ends in return (or throw). */
|
|
@@ -227,7 +227,7 @@ declare function serializeBaseline(counts: BaselineCounts): string;
|
|
|
227
227
|
declare function parseBaseline(text: string, source: string): BaselineCounts;
|
|
228
228
|
|
|
229
229
|
declare const THROW_MESSAGES: {
|
|
230
|
-
readonly escapes: "`throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside
|
|
230
|
+
readonly escapes: "`throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync.";
|
|
231
231
|
readonly rethrow: string;
|
|
232
232
|
readonly notResultErr: string;
|
|
233
233
|
readonly rawCatchValue: string;
|
|
@@ -235,7 +235,7 @@ declare const THROW_MESSAGES: {
|
|
|
235
235
|
};
|
|
236
236
|
|
|
237
237
|
declare const UNTRUSTED_CALL_MESSAGES: {
|
|
238
|
-
readonly unguarded: "Call into untrusted \"{{origin}}\" must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside
|
|
238
|
+
readonly unguarded: "Call into untrusted \"{{origin}}\" must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync. If \"{{origin}}\" cannot fail, trust it in trust.config.json.";
|
|
239
239
|
readonly notAwaited: "Async call into untrusted \"{{origin}}\" must be awaited inside the guard, or its rejection escapes the catch.";
|
|
240
240
|
readonly callsIgnored: "Call into \"{{origin}}\" is trusted only because its file is ignored. List that file under \"passthrough\" instead of \"ignore\" so calls into it must be handled.";
|
|
241
241
|
readonly rethrow: string;
|
package/dist/eslint/index.js
CHANGED
|
@@ -24,14 +24,14 @@ import {
|
|
|
24
24
|
serializeBaseline,
|
|
25
25
|
setupRule,
|
|
26
26
|
untrusted_call_must_return_result_default
|
|
27
|
-
} from "../chunk-
|
|
27
|
+
} from "../chunk-YJYGTNJD.js";
|
|
28
28
|
|
|
29
29
|
// src/eslint/rules/throw-must-return-result.ts
|
|
30
30
|
function forThrow(template) {
|
|
31
31
|
return template.replace("{{target}}", "this `throw`");
|
|
32
32
|
}
|
|
33
33
|
var THROW_MESSAGES = {
|
|
34
|
-
escapes: "`throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside
|
|
34
|
+
escapes: "`throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync.",
|
|
35
35
|
rethrow: forThrow(CATCH_MESSAGES.rethrow),
|
|
36
36
|
notResultErr: forThrow(CATCH_MESSAGES.notResultErr),
|
|
37
37
|
rawCatchValue: forThrow(CATCH_MESSAGES.rawCatchValue),
|
package/dist/eslint/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/eslint/rules/throw-must-return-result.ts","../../src/eslint/index.ts"],"sourcesContent":["// Every `throw` in checked code must be guarded: inside a `try` (same function) whose `catch`\n// returns Result.err(...) on every path, or inside a
|
|
1
|
+
{"version":3,"sources":["../../src/eslint/rules/throw-must-return-result.ts","../../src/eslint/index.ts"],"sourcesContent":["// Every `throw` in checked code must be guarded: inside a `try` (same function) whose `catch`\n// returns Result.err(...) on every path, or inside a Trust.try / Trust.tryAsync callback.\n// Works with or without type information; with it, Result.err is recognised by declaration.\nimport type { Rule } from 'eslint';\nimport { CATCH_MESSAGES, guardOf, type AstNode, type CatchProblem } from '../guard.js';\nimport { OPTIONS_SCHEMA, setupRule } from '../rule-setup.js';\n\nfunction forThrow(template: string): string {\n return template.replace('{{target}}', 'this `throw`');\n}\n\nexport const THROW_MESSAGES = {\n escapes: '`throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync.',\n rethrow: forThrow(CATCH_MESSAGES.rethrow),\n notResultErr: forThrow(CATCH_MESSAGES.notResultErr),\n rawCatchValue: forThrow(CATCH_MESSAGES.rawCatchValue),\n notAllPaths: forThrow(CATCH_MESSAGES.notAllPaths),\n} as const satisfies Record<string, string> & Record<CatchProblem, string>;\n\nconst rule: Rule.RuleModule = {\n meta: {\n type: 'problem',\n docs: { description: 'Require every throw to be caught locally and returned as Result.err.' },\n schema: OPTIONS_SCHEMA as unknown as Rule.RuleMetaData['schema'],\n messages: THROW_MESSAGES,\n },\n create(context) {\n const setup = setupRule(context);\n if (setup.zone !== 'checked') return {};\n return {\n ThrowStatement(node) {\n const guard = guardOf(node as unknown as AstNode, setup.guardContext);\n if (guard.status === 'unguarded') context.report({ node, messageId: 'escapes' });\n else if (guard.status === 'badCatch') context.report({ node, messageId: guard.problem });\n },\n };\n },\n};\n\nexport default rule;\n","// @noego/trust/eslint — ESLint plugin, trust config loader, and policy.\n//\n// import { typedConfig } from '@noego/trust/eslint';\n// export default [\n// ...typedConfig({ files: ['server/**/*.ts'], configFile: 'trust.config.json' }),\n// ];\nimport type { ESLint, Linter } from 'eslint';\nimport throwMustReturnResult from './rules/throw-must-return-result.js';\nimport untrustedCallMustReturnResult from './rules/untrusted-call-must-return-result.js';\n\nexport const rules = {\n 'untrusted-call-must-return-result': untrustedCallMustReturnResult,\n 'throw-must-return-result': throwMustReturnResult,\n};\n\nexport interface TypedConfigOptions {\n /** Files to check (flat-config globs). They must be in a tsconfig the project service can find. */\n readonly files: readonly string[];\n readonly ignores?: readonly string[];\n /** trust.config.json path relative to the ESLint cwd (default \"trust.config.json\"). */\n readonly configFile?: string;\n readonly severity?: Linter.RuleSeverity;\n}\n\nconst plugin: ESLint.Plugin = {\n meta: { name: '@noego/trust' },\n rules,\n};\n\nexport default plugin;\n\n/** Flat config that registers the plugin as `trust` and enables both rules for `files`. Needs typed linting. */\nexport function typedConfig(options: TypedConfigOptions): Linter.Config[] {\n const severity = options.severity ?? 'warn';\n const ruleOptions = { configFile: options.configFile ?? 'trust.config.json' };\n return [\n {\n name: '@noego/trust/typed',\n files: [...options.files],\n ignores: [...(options.ignores ?? [])],\n plugins: { trust: plugin },\n rules: {\n 'trust/untrusted-call-must-return-result': [severity, ruleOptions],\n 'trust/throw-must-return-result': [severity, ruleOptions],\n },\n },\n ];\n}\n\nexport {\n effectiveTrustList,\n loadTrustConfig,\n normalizeOrigin,\n TrustConfigError,\n type LoadTrustConfigOptions,\n type TrustConfig,\n type TrustEntry,\n type TrustLevel,\n} from './config.js';\nexport { PRESETS, type PresetDefinition } from './presets.js';\nexport { entryMatches, TrustPolicy, type MatchedEntry, type Verdict } from './policy.js';\nexport { OriginResolver, type OriginInfo } from './origin.js';\nexport { Zones, type Zone, type ZoneGroup } from './zones.js';\nexport { alwaysExits, catchProblem, guardOf, type CatchProblem, type Guard, type GuardContext } from './guard.js';\nexport {\n compareToBaseline,\n countFindings,\n findingsFromResults,\n originFromMessage,\n parseBaseline,\n serializeBaseline,\n THROW_RULE,\n UNTRUSTED_CALL_RULE,\n type BaselineCounts,\n type BaselineDelta,\n type Finding,\n} from './baseline.js';\nexport { THROW_MESSAGES } from './rules/throw-must-return-result.js';\nexport { UNTRUSTED_CALL_MESSAGES } from './rules/untrusted-call-must-return-result.js';\nexport type { TrustRuleOptions } from './rule-setup.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,SAAS,UAA0B;AAC1C,SAAO,SAAS,QAAQ,cAAc,cAAc;AACtD;AAEO,IAAM,iBAAiB;AAAA,EAC5B,SAAS;AAAA,EACT,SAAS,SAAS,eAAe,OAAO;AAAA,EACxC,cAAc,SAAS,eAAe,YAAY;AAAA,EAClD,eAAe,SAAS,eAAe,aAAa;AAAA,EACpD,aAAa,SAAS,eAAe,WAAW;AAClD;AAEA,IAAM,OAAwB;AAAA,EAC5B,MAAM;AAAA,IACJ,MAAM;AAAA,IACN,MAAM,EAAE,aAAa,uEAAuE;AAAA,IAC5F,QAAQ;AAAA,IACR,UAAU;AAAA,EACZ;AAAA,EACA,OAAO,SAAS;AACd,UAAM,QAAQ,UAAU,OAAO;AAC/B,QAAI,MAAM,SAAS,UAAW,QAAO,CAAC;AACtC,WAAO;AAAA,MACL,eAAe,MAAM;AACnB,cAAM,QAAQ,QAAQ,MAA4B,MAAM,YAAY;AACpE,YAAI,MAAM,WAAW,YAAa,SAAQ,OAAO,EAAE,MAAM,WAAW,UAAU,CAAC;AAAA,iBACtE,MAAM,WAAW,WAAY,SAAQ,OAAO,EAAE,MAAM,WAAW,MAAM,QAAQ,CAAC;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,mCAAQ;;;AC7BR,IAAM,QAAQ;AAAA,EACnB,qCAAqC;AAAA,EACrC,4BAA4B;AAC9B;AAWA,IAAM,SAAwB;AAAA,EAC5B,MAAM,EAAE,MAAM,eAAe;AAAA,EAC7B;AACF;AAEA,IAAO,iBAAQ;AAGR,SAAS,YAAY,SAA8C;AACxE,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,cAAc,EAAE,YAAY,QAAQ,cAAc,oBAAoB;AAC5E,SAAO;AAAA,IACL;AAAA,MACE,MAAM;AAAA,MACN,OAAO,CAAC,GAAG,QAAQ,KAAK;AAAA,MACxB,SAAS,CAAC,GAAI,QAAQ,WAAW,CAAC,CAAE;AAAA,MACpC,SAAS,EAAE,OAAO,OAAO;AAAA,MACzB,OAAO;AAAA,QACL,2CAA2C,CAAC,UAAU,WAAW;AAAA,QACjE,kCAAkC,CAAC,UAAU,WAAW;AAAA,MAC1D;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
23
|
Result: () => Result,
|
|
24
|
+
Trust: () => Trust,
|
|
24
25
|
decide: () => decide,
|
|
25
26
|
err: () => err,
|
|
26
27
|
ok: () => ok,
|
|
@@ -63,10 +64,12 @@ function translate(result, mappers) {
|
|
|
63
64
|
const mapper = pick(mappers, result.error?.kind);
|
|
64
65
|
return mapper === void 0 ? result : err(mapper(result.error));
|
|
65
66
|
}
|
|
66
|
-
var Result = { ok, err
|
|
67
|
+
var Result = { ok, err };
|
|
68
|
+
var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate };
|
|
67
69
|
// Annotate the CommonJS export names for ESM import in node:
|
|
68
70
|
0 && (module.exports = {
|
|
69
71
|
Result,
|
|
72
|
+
Trust,
|
|
70
73
|
decide,
|
|
71
74
|
err,
|
|
72
75
|
ok,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n *
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * Public surface is two namespaces:\n *\n * Result.ok / Result.err — make a result\n * Trust.try / Trust.tryAsync — the only boundary that may catch a throw\n * Trust.decide / Trust.translate — the only places a failure may stop or change\n *\n * The underlying functions are exported as well because the `@noego/trust/eslint`\n * rules recognise calls by their declaration (not by name): `Trust.try(...)` resolves\n * to `tryResult`, `Result.err(...)` to `err`. Write the namespace form in application code.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** A failure is an object with a literal `kind` plus any fields. */\nexport type Failure<K extends string = string, Fields extends object = {}> = { readonly kind: K } & Readonly<Fields>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/**\n * Wraps a failure value. Pass a typed error, not a raw caught value.\n *\n * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`\n * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection, so no `as const`\n * is needed. `E` itself is still a plain type parameter, so a declared `Result` return\n * type sets it and other literal fields keep their declared union types. The second\n * overload covers arguments that cannot meet the intersection (generic, unknown, null).\n */\nexport function err<E, K extends string = string>(error: E & { readonly kind?: K }): Err<E>;\nexport function err<E>(error: E): Err<E>;\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E, K extends string = string>(\n fn: () => T,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResultAsync<T, E, K extends string = string>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Promise<Result<T, E>>;\nexport function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>>;\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;\n/**\n * One failure per kind. A single declared failure whose `kind` is a union\n * (`{ kind: 'a' | 'b'; op: string }`) is split into `{...; kind: 'a'} | {...; kind: 'b'}`\n * so that handlers narrow to one kind each; failures that already have one\n * literal kind are left as they are.\n */\ntype SplitByKind<E> = E extends { readonly kind: infer K extends string }\n ? IsUnion<K> extends true\n ? K extends unknown\n ? E & { readonly kind: K }\n : never\n : E\n : never;\n\ntype KindsOf<E> = E extends { readonly kind: infer K extends string } ? K : never;\ntype ErrorOf<R> = R extends Err<infer E> ? SplitByKind<E> : never;\ntype OkOf<R> = R extends Ok<infer T> ? T : never;\ntype CannotFail = { readonly __trust: 'decide needs a result that can fail (it has no Err member)' };\ntype BadFailure = { readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)' };\ntype NeedsLiteralKind = { readonly __trust: 'a translate mapper must return an object with a literal string kind' };\n\ntype RawErrorOf<R> = R extends Err<infer E> ? E : never;\ntype FailureGuard<R> = [RawErrorOf<R>] extends [never]\n ? CannotFail\n : [RawErrorOf<R>] extends [{ readonly kind: string }]\n ? unknown\n : BadFailure;\n\ntype HandlerBase<E, H> = { [K in keyof H]: K extends KindsOf<E> ? {} | null : never };\ntype HandlerFns<E, H> = {\n [K in keyof H]-?: (failure: Extract<E, { readonly kind: K }>) => H[K];\n};\ntype LiteralKind = '' | (string & {});\ntype MapperBase<E, M> = { [K in keyof M]: K extends KindsOf<E> ? { readonly kind: LiteralKind } : never };\ntype MapperFns<E, M> = {\n [K in keyof M]-?: (failure: Extract<E, { readonly kind: K }>) => M[K];\n};\ntype KindCheck<M> = [\n { [K in keyof M]-?: M[K] extends { readonly kind: infer Kd } ? (string extends Kd ? 1 : never) : 1 }[keyof M],\n] extends [never]\n ? []\n : [problem: NeedsLiteralKind];\n\ntype Remaining<E, H> = Exclude<E, { readonly kind: keyof H & string }>;\ntype Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never]\n ? Ok<OkOf<R> | H[keyof H]>\n : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;\ntype Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;\n\nfunction pick(table: object, kind: unknown): ((failure: unknown) => unknown) | undefined {\n if (typeof kind !== 'string' || !Object.prototype.hasOwnProperty.call(table, kind)) return undefined;\n return (table as Record<string, (failure: unknown) => unknown>)[kind];\n}\n\n/**\n * The only place a failure may stop: a failure whose kind has a handler becomes\n * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous\n * and must return a value (never `undefined`/`void`).\n */\nexport function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(\n result: R & FailureGuard<R>,\n handlers: HandlerFns<ErrorOf<R>, H>,\n): Decided<R, H>;\nexport function decide(result: Result<unknown, unknown>, handlers: object): unknown {\n if (result.ok) return result;\n const handler = pick(handlers, (result.error as { kind?: unknown } | null)?.kind);\n return handler === undefined ? result : ok(handler(result.error));\n}\n\n/** Turns failures into different failures; unmapped failures and successes pass through untouched. */\nexport function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(\n result: R & FailureGuard<R>,\n mappers: MapperFns<ErrorOf<R>, M>,\n ...check: KindCheck<M>\n): Translated<R, M>;\nexport function translate(result: Result<unknown, unknown>, mappers: object): unknown {\n if (result.ok) return result;\n const mapper = pick(mappers, (result.error as { kind?: unknown } | null)?.kind);\n return mapper === undefined ? result : err(mapper(result.error));\n}\n\n/** Make a result: `Result.ok(value)`, `Result.err({ kind: 'x', ... })`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n} = { ok, err };\n\n/**\n * Apply the discipline:\n * `Trust.try` / `Trust.tryAsync` are the only boundary that may catch a throw;\n * `Trust.decide` is the only place a failure may stop; `Trust.translate` the only place it may change kind.\n */\nexport const Trust: {\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n readonly decide: typeof decide;\n readonly translate: typeof translate;\n} = { try: tryResult, tryAsync: tryResultAsync, decide, translate };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAaO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAWO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAcA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAoDA,SAAS,KAAK,OAAe,MAA4D;AACvF,MAAI,OAAO,SAAS,YAAY,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,IAAI,EAAG,QAAO;AAC3F,SAAQ,MAAwD,IAAI;AACtE;AAWO,SAAS,OAAO,QAAkC,UAA2B;AAClF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,UAAU,KAAK,UAAW,OAAO,OAAqC,IAAI;AAChF,SAAO,YAAY,SAAY,SAAS,GAAG,QAAQ,OAAO,KAAK,CAAC;AAClE;AAQO,SAAS,UAAU,QAAkC,SAA0B;AACpF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,SAAS,KAAK,SAAU,OAAO,OAAqC,IAAI;AAC9E,SAAO,WAAW,SAAY,SAAS,IAAI,OAAO,OAAO,KAAK,CAAC;AACjE;AAGO,IAAM,SAGT,EAAE,IAAI,IAAI;AAOP,IAAM,QAKT,EAAE,KAAK,WAAW,UAAU,gBAAgB,QAAQ,UAAU;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -4,9 +4,15 @@
|
|
|
4
4
|
* `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no
|
|
5
5
|
* imports so it is safe in any bundle (Node, Electron main, renderer, browser).
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* Public surface is two namespaces:
|
|
8
|
+
*
|
|
9
|
+
* Result.ok / Result.err — make a result
|
|
10
|
+
* Trust.try / Trust.tryAsync — the only boundary that may catch a throw
|
|
11
|
+
* Trust.decide / Trust.translate — the only places a failure may stop or change
|
|
12
|
+
*
|
|
13
|
+
* The underlying functions are exported as well because the `@noego/trust/eslint`
|
|
14
|
+
* rules recognise calls by their declaration (not by name): `Trust.try(...)` resolves
|
|
15
|
+
* to `tryResult`, `Result.err(...)` to `err`. Write the namespace form in application code.
|
|
10
16
|
*/
|
|
11
17
|
type Ok<T> = {
|
|
12
18
|
readonly ok: true;
|
|
@@ -16,16 +22,20 @@ type Err<E> = {
|
|
|
16
22
|
readonly ok: false;
|
|
17
23
|
readonly error: E;
|
|
18
24
|
};
|
|
25
|
+
/** A failure is an object with a literal `kind` plus any fields. */
|
|
26
|
+
type Failure<K extends string = string, Fields extends object = {}> = {
|
|
27
|
+
readonly kind: K;
|
|
28
|
+
} & Readonly<Fields>;
|
|
19
29
|
/** Wraps a success value. */
|
|
20
30
|
declare function ok<T>(value: T): Ok<T>;
|
|
21
31
|
/**
|
|
22
32
|
* Wraps a failure value. Pass a typed error, not a raw caught value.
|
|
23
33
|
*
|
|
24
34
|
* The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`
|
|
25
|
-
* gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection
|
|
26
|
-
* still a plain type parameter, so a declared `Result` return
|
|
27
|
-
* literal fields keep their declared union types. The second
|
|
28
|
-
* arguments that cannot meet the intersection (generic, unknown, null
|
|
35
|
+
* gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection, so no `as const`
|
|
36
|
+
* is needed. `E` itself is still a plain type parameter, so a declared `Result` return
|
|
37
|
+
* type sets it and other literal fields keep their declared union types. The second
|
|
38
|
+
* overload covers arguments that cannot meet the intersection (generic, unknown, null).
|
|
29
39
|
*/
|
|
30
40
|
declare function err<E, K extends string = string>(error: E & {
|
|
31
41
|
readonly kind?: K;
|
|
@@ -47,14 +57,22 @@ declare function tryResultAsync<T, E, K extends string = string>(fn: () => T | P
|
|
|
47
57
|
readonly kind?: K;
|
|
48
58
|
}): Promise<Result<T, E>>;
|
|
49
59
|
declare function tryResultAsync<T, E>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E): Promise<Result<T, E>>;
|
|
50
|
-
|
|
51
|
-
|
|
60
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
61
|
+
/**
|
|
62
|
+
* One failure per kind. A single declared failure whose `kind` is a union
|
|
63
|
+
* (`{ kind: 'a' | 'b'; op: string }`) is split into `{...; kind: 'a'} | {...; kind: 'b'}`
|
|
64
|
+
* so that handlers narrow to one kind each; failures that already have one
|
|
65
|
+
* literal kind are left as they are.
|
|
66
|
+
*/
|
|
67
|
+
type SplitByKind<E> = E extends {
|
|
68
|
+
readonly kind: infer K extends string;
|
|
69
|
+
} ? IsUnion<K> extends true ? K extends unknown ? E & {
|
|
52
70
|
readonly kind: K;
|
|
53
|
-
}
|
|
71
|
+
} : never : E : never;
|
|
54
72
|
type KindsOf<E> = E extends {
|
|
55
73
|
readonly kind: infer K extends string;
|
|
56
74
|
} ? K : never;
|
|
57
|
-
type ErrorOf<R> = R extends Err<infer E> ? E : never;
|
|
75
|
+
type ErrorOf<R> = R extends Err<infer E> ? SplitByKind<E> : never;
|
|
58
76
|
type OkOf<R> = R extends Ok<infer T> ? T : never;
|
|
59
77
|
type CannotFail = {
|
|
60
78
|
readonly __trust: 'decide needs a result that can fail (it has no Err member)';
|
|
@@ -65,7 +83,8 @@ type BadFailure = {
|
|
|
65
83
|
type NeedsLiteralKind = {
|
|
66
84
|
readonly __trust: 'a translate mapper must return an object with a literal string kind';
|
|
67
85
|
};
|
|
68
|
-
type
|
|
86
|
+
type RawErrorOf<R> = R extends Err<infer E> ? E : never;
|
|
87
|
+
type FailureGuard<R> = [RawErrorOf<R>] extends [never] ? CannotFail : [RawErrorOf<R>] extends [{
|
|
69
88
|
readonly kind: string;
|
|
70
89
|
}] ? unknown : BadFailure;
|
|
71
90
|
type HandlerBase<E, H> = {
|
|
@@ -101,20 +120,28 @@ type Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never] ? Ok<OkOf<R> | H
|
|
|
101
120
|
type Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;
|
|
102
121
|
/**
|
|
103
122
|
* The only place a failure may stop: a failure whose kind has a handler becomes
|
|
104
|
-
* `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous
|
|
123
|
+
* `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous
|
|
124
|
+
* and must return a value (never `undefined`/`void`).
|
|
105
125
|
*/
|
|
106
126
|
declare function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(result: R & FailureGuard<R>, handlers: HandlerFns<ErrorOf<R>, H>): Decided<R, H>;
|
|
107
127
|
/** Turns failures into different failures; unmapped failures and successes pass through untouched. */
|
|
108
128
|
declare function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(result: R & FailureGuard<R>, mappers: MapperFns<ErrorOf<R>, M>, ...check: KindCheck<M>): Translated<R, M>;
|
|
109
129
|
type Result<T, E> = Ok<T> | Err<E>;
|
|
110
|
-
/**
|
|
130
|
+
/** Make a result: `Result.ok(value)`, `Result.err({ kind: 'x', ... })`. */
|
|
111
131
|
declare const Result: {
|
|
112
132
|
readonly ok: typeof ok;
|
|
113
133
|
readonly err: typeof err;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Apply the discipline:
|
|
137
|
+
* `Trust.try` / `Trust.tryAsync` are the only boundary that may catch a throw;
|
|
138
|
+
* `Trust.decide` is the only place a failure may stop; `Trust.translate` the only place it may change kind.
|
|
139
|
+
*/
|
|
140
|
+
declare const Trust: {
|
|
114
141
|
readonly try: typeof tryResult;
|
|
115
142
|
readonly tryAsync: typeof tryResultAsync;
|
|
116
143
|
readonly decide: typeof decide;
|
|
117
144
|
readonly translate: typeof translate;
|
|
118
145
|
};
|
|
119
146
|
|
|
120
|
-
export { type Err, type Failure, type Ok, Result, decide, err, ok, translate, tryResult, tryResultAsync };
|
|
147
|
+
export { type Err, type Failure, type Ok, Result, Trust, decide, err, ok, translate, tryResult, tryResultAsync };
|
package/dist/index.d.ts
CHANGED
|
@@ -4,9 +4,15 @@
|
|
|
4
4
|
* `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no
|
|
5
5
|
* imports so it is safe in any bundle (Node, Electron main, renderer, browser).
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* Public surface is two namespaces:
|
|
8
|
+
*
|
|
9
|
+
* Result.ok / Result.err — make a result
|
|
10
|
+
* Trust.try / Trust.tryAsync — the only boundary that may catch a throw
|
|
11
|
+
* Trust.decide / Trust.translate — the only places a failure may stop or change
|
|
12
|
+
*
|
|
13
|
+
* The underlying functions are exported as well because the `@noego/trust/eslint`
|
|
14
|
+
* rules recognise calls by their declaration (not by name): `Trust.try(...)` resolves
|
|
15
|
+
* to `tryResult`, `Result.err(...)` to `err`. Write the namespace form in application code.
|
|
10
16
|
*/
|
|
11
17
|
type Ok<T> = {
|
|
12
18
|
readonly ok: true;
|
|
@@ -16,16 +22,20 @@ type Err<E> = {
|
|
|
16
22
|
readonly ok: false;
|
|
17
23
|
readonly error: E;
|
|
18
24
|
};
|
|
25
|
+
/** A failure is an object with a literal `kind` plus any fields. */
|
|
26
|
+
type Failure<K extends string = string, Fields extends object = {}> = {
|
|
27
|
+
readonly kind: K;
|
|
28
|
+
} & Readonly<Fields>;
|
|
19
29
|
/** Wraps a success value. */
|
|
20
30
|
declare function ok<T>(value: T): Ok<T>;
|
|
21
31
|
/**
|
|
22
32
|
* Wraps a failure value. Pass a typed error, not a raw caught value.
|
|
23
33
|
*
|
|
24
34
|
* The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`
|
|
25
|
-
* gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection
|
|
26
|
-
* still a plain type parameter, so a declared `Result` return
|
|
27
|
-
* literal fields keep their declared union types. The second
|
|
28
|
-
* arguments that cannot meet the intersection (generic, unknown, null
|
|
35
|
+
* gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection, so no `as const`
|
|
36
|
+
* is needed. `E` itself is still a plain type parameter, so a declared `Result` return
|
|
37
|
+
* type sets it and other literal fields keep their declared union types. The second
|
|
38
|
+
* overload covers arguments that cannot meet the intersection (generic, unknown, null).
|
|
29
39
|
*/
|
|
30
40
|
declare function err<E, K extends string = string>(error: E & {
|
|
31
41
|
readonly kind?: K;
|
|
@@ -47,14 +57,22 @@ declare function tryResultAsync<T, E, K extends string = string>(fn: () => T | P
|
|
|
47
57
|
readonly kind?: K;
|
|
48
58
|
}): Promise<Result<T, E>>;
|
|
49
59
|
declare function tryResultAsync<T, E>(fn: () => T | PromiseLike<T>, onError: (cause: unknown) => E): Promise<Result<T, E>>;
|
|
50
|
-
|
|
51
|
-
|
|
60
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
61
|
+
/**
|
|
62
|
+
* One failure per kind. A single declared failure whose `kind` is a union
|
|
63
|
+
* (`{ kind: 'a' | 'b'; op: string }`) is split into `{...; kind: 'a'} | {...; kind: 'b'}`
|
|
64
|
+
* so that handlers narrow to one kind each; failures that already have one
|
|
65
|
+
* literal kind are left as they are.
|
|
66
|
+
*/
|
|
67
|
+
type SplitByKind<E> = E extends {
|
|
68
|
+
readonly kind: infer K extends string;
|
|
69
|
+
} ? IsUnion<K> extends true ? K extends unknown ? E & {
|
|
52
70
|
readonly kind: K;
|
|
53
|
-
}
|
|
71
|
+
} : never : E : never;
|
|
54
72
|
type KindsOf<E> = E extends {
|
|
55
73
|
readonly kind: infer K extends string;
|
|
56
74
|
} ? K : never;
|
|
57
|
-
type ErrorOf<R> = R extends Err<infer E> ? E : never;
|
|
75
|
+
type ErrorOf<R> = R extends Err<infer E> ? SplitByKind<E> : never;
|
|
58
76
|
type OkOf<R> = R extends Ok<infer T> ? T : never;
|
|
59
77
|
type CannotFail = {
|
|
60
78
|
readonly __trust: 'decide needs a result that can fail (it has no Err member)';
|
|
@@ -65,7 +83,8 @@ type BadFailure = {
|
|
|
65
83
|
type NeedsLiteralKind = {
|
|
66
84
|
readonly __trust: 'a translate mapper must return an object with a literal string kind';
|
|
67
85
|
};
|
|
68
|
-
type
|
|
86
|
+
type RawErrorOf<R> = R extends Err<infer E> ? E : never;
|
|
87
|
+
type FailureGuard<R> = [RawErrorOf<R>] extends [never] ? CannotFail : [RawErrorOf<R>] extends [{
|
|
69
88
|
readonly kind: string;
|
|
70
89
|
}] ? unknown : BadFailure;
|
|
71
90
|
type HandlerBase<E, H> = {
|
|
@@ -101,20 +120,28 @@ type Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never] ? Ok<OkOf<R> | H
|
|
|
101
120
|
type Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;
|
|
102
121
|
/**
|
|
103
122
|
* The only place a failure may stop: a failure whose kind has a handler becomes
|
|
104
|
-
* `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous
|
|
123
|
+
* `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous
|
|
124
|
+
* and must return a value (never `undefined`/`void`).
|
|
105
125
|
*/
|
|
106
126
|
declare function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(result: R & FailureGuard<R>, handlers: HandlerFns<ErrorOf<R>, H>): Decided<R, H>;
|
|
107
127
|
/** Turns failures into different failures; unmapped failures and successes pass through untouched. */
|
|
108
128
|
declare function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(result: R & FailureGuard<R>, mappers: MapperFns<ErrorOf<R>, M>, ...check: KindCheck<M>): Translated<R, M>;
|
|
109
129
|
type Result<T, E> = Ok<T> | Err<E>;
|
|
110
|
-
/**
|
|
130
|
+
/** Make a result: `Result.ok(value)`, `Result.err({ kind: 'x', ... })`. */
|
|
111
131
|
declare const Result: {
|
|
112
132
|
readonly ok: typeof ok;
|
|
113
133
|
readonly err: typeof err;
|
|
134
|
+
};
|
|
135
|
+
/**
|
|
136
|
+
* Apply the discipline:
|
|
137
|
+
* `Trust.try` / `Trust.tryAsync` are the only boundary that may catch a throw;
|
|
138
|
+
* `Trust.decide` is the only place a failure may stop; `Trust.translate` the only place it may change kind.
|
|
139
|
+
*/
|
|
140
|
+
declare const Trust: {
|
|
114
141
|
readonly try: typeof tryResult;
|
|
115
142
|
readonly tryAsync: typeof tryResultAsync;
|
|
116
143
|
readonly decide: typeof decide;
|
|
117
144
|
readonly translate: typeof translate;
|
|
118
145
|
};
|
|
119
146
|
|
|
120
|
-
export { type Err, type Failure, type Ok, Result, decide, err, ok, translate, tryResult, tryResultAsync };
|
|
147
|
+
export { type Err, type Failure, type Ok, Result, Trust, decide, err, ok, translate, tryResult, tryResultAsync };
|
package/dist/index.js
CHANGED
|
@@ -33,9 +33,11 @@ function translate(result, mappers) {
|
|
|
33
33
|
const mapper = pick(mappers, result.error?.kind);
|
|
34
34
|
return mapper === void 0 ? result : err(mapper(result.error));
|
|
35
35
|
}
|
|
36
|
-
var Result = { ok, err
|
|
36
|
+
var Result = { ok, err };
|
|
37
|
+
var Trust = { try: tryResult, tryAsync: tryResultAsync, decide, translate };
|
|
37
38
|
export {
|
|
38
39
|
Result,
|
|
40
|
+
Trust,
|
|
39
41
|
decide,
|
|
40
42
|
err,
|
|
41
43
|
ok,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n *
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * Closed result primitive: expected failures are values, not exceptions.\n *\n * `Result<T, E>` is `Ok<T> | Err<E>`, discriminated by `ok`. This module has no\n * imports so it is safe in any bundle (Node, Electron main, renderer, browser).\n *\n * Public surface is two namespaces:\n *\n * Result.ok / Result.err — make a result\n * Trust.try / Trust.tryAsync — the only boundary that may catch a throw\n * Trust.decide / Trust.translate — the only places a failure may stop or change\n *\n * The underlying functions are exported as well because the `@noego/trust/eslint`\n * rules recognise calls by their declaration (not by name): `Trust.try(...)` resolves\n * to `tryResult`, `Result.err(...)` to `err`. Write the namespace form in application code.\n */\nexport type Ok<T> = { readonly ok: true; readonly value: T };\nexport type Err<E> = { readonly ok: false; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/** A failure is an object with a literal `kind` plus any fields. */\nexport type Failure<K extends string = string, Fields extends object = {}> = { readonly kind: K } & Readonly<Fields>;\n\n/** Wraps a success value. */\nexport function ok<T>(value: T): Ok<T> {\n return { ok: true, value };\n}\n\n/**\n * Wraps a failure value. Pass a typed error, not a raw caught value.\n *\n * The first overload keeps a literal `kind` for inline failures (`err({ kind: 'X' })`\n * gives `Err<{ kind: 'X' }>`) through the `K` hint in the intersection, so no `as const`\n * is needed. `E` itself is still a plain type parameter, so a declared `Result` return\n * type sets it and other literal fields keep their declared union types. The second\n * overload covers arguments that cannot meet the intersection (generic, unknown, null).\n */\nexport function err<E, K extends string = string>(error: E & { readonly kind?: K }): Err<E>;\nexport function err<E>(error: E): Err<E>;\nexport function err<E>(error: E): Err<E> {\n return { ok: false, error };\n}\n\n/**\n * Runs `fn` and converts anything it throws into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResult<T, E, K extends string = string>(\n fn: () => T,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E>;\nexport function tryResult<T, E>(fn: () => T, onError: (cause: unknown) => E): Result<T, E> {\n try {\n return ok(fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\n/**\n * Awaits `fn` and converts a throw or rejection into `Err` via `onError`.\n * Calls made directly inside `fn` count as guarded for the trust lint rules.\n */\nexport function tryResultAsync<T, E, K extends string = string>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E & { readonly kind?: K },\n): Promise<Result<T, E>>;\nexport function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>>;\nexport async function tryResultAsync<T, E>(\n fn: () => T | PromiseLike<T>,\n onError: (cause: unknown) => E,\n): Promise<Result<T, E>> {\n try {\n return ok(await fn());\n } catch (cause) {\n return err(onError(cause));\n }\n}\n\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;\n/**\n * One failure per kind. A single declared failure whose `kind` is a union\n * (`{ kind: 'a' | 'b'; op: string }`) is split into `{...; kind: 'a'} | {...; kind: 'b'}`\n * so that handlers narrow to one kind each; failures that already have one\n * literal kind are left as they are.\n */\ntype SplitByKind<E> = E extends { readonly kind: infer K extends string }\n ? IsUnion<K> extends true\n ? K extends unknown\n ? E & { readonly kind: K }\n : never\n : E\n : never;\n\ntype KindsOf<E> = E extends { readonly kind: infer K extends string } ? K : never;\ntype ErrorOf<R> = R extends Err<infer E> ? SplitByKind<E> : never;\ntype OkOf<R> = R extends Ok<infer T> ? T : never;\ntype CannotFail = { readonly __trust: 'decide needs a result that can fail (it has no Err member)' };\ntype BadFailure = { readonly __trust: 'every failure needs a string `kind` (string and Error are not failures)' };\ntype NeedsLiteralKind = { readonly __trust: 'a translate mapper must return an object with a literal string kind' };\n\ntype RawErrorOf<R> = R extends Err<infer E> ? E : never;\ntype FailureGuard<R> = [RawErrorOf<R>] extends [never]\n ? CannotFail\n : [RawErrorOf<R>] extends [{ readonly kind: string }]\n ? unknown\n : BadFailure;\n\ntype HandlerBase<E, H> = { [K in keyof H]: K extends KindsOf<E> ? {} | null : never };\ntype HandlerFns<E, H> = {\n [K in keyof H]-?: (failure: Extract<E, { readonly kind: K }>) => H[K];\n};\ntype LiteralKind = '' | (string & {});\ntype MapperBase<E, M> = { [K in keyof M]: K extends KindsOf<E> ? { readonly kind: LiteralKind } : never };\ntype MapperFns<E, M> = {\n [K in keyof M]-?: (failure: Extract<E, { readonly kind: K }>) => M[K];\n};\ntype KindCheck<M> = [\n { [K in keyof M]-?: M[K] extends { readonly kind: infer Kd } ? (string extends Kd ? 1 : never) : 1 }[keyof M],\n] extends [never]\n ? []\n : [problem: NeedsLiteralKind];\n\ntype Remaining<E, H> = Exclude<E, { readonly kind: keyof H & string }>;\ntype Decided<R, H> = [Remaining<ErrorOf<R>, H>] extends [never]\n ? Ok<OkOf<R> | H[keyof H]>\n : Ok<OkOf<R> | H[keyof H]> | Err<Remaining<ErrorOf<R>, H>>;\ntype Translated<R, M> = Ok<OkOf<R>> | Err<M[keyof M] | Remaining<ErrorOf<R>, M>>;\n\nfunction pick(table: object, kind: unknown): ((failure: unknown) => unknown) | undefined {\n if (typeof kind !== 'string' || !Object.prototype.hasOwnProperty.call(table, kind)) return undefined;\n return (table as Record<string, (failure: unknown) => unknown>)[kind];\n}\n\n/**\n * The only place a failure may stop: a failure whose kind has a handler becomes\n * `ok(handler(failure))`; anything else is returned untouched. Handlers are synchronous\n * and must return a value (never `undefined`/`void`).\n */\nexport function decide<R extends Result<unknown, unknown>, H extends HandlerBase<ErrorOf<R>, H>>(\n result: R & FailureGuard<R>,\n handlers: HandlerFns<ErrorOf<R>, H>,\n): Decided<R, H>;\nexport function decide(result: Result<unknown, unknown>, handlers: object): unknown {\n if (result.ok) return result;\n const handler = pick(handlers, (result.error as { kind?: unknown } | null)?.kind);\n return handler === undefined ? result : ok(handler(result.error));\n}\n\n/** Turns failures into different failures; unmapped failures and successes pass through untouched. */\nexport function translate<R extends Result<unknown, unknown>, M extends MapperBase<ErrorOf<R>, M>>(\n result: R & FailureGuard<R>,\n mappers: MapperFns<ErrorOf<R>, M>,\n ...check: KindCheck<M>\n): Translated<R, M>;\nexport function translate(result: Result<unknown, unknown>, mappers: object): unknown {\n if (result.ok) return result;\n const mapper = pick(mappers, (result.error as { kind?: unknown } | null)?.kind);\n return mapper === undefined ? result : err(mapper(result.error));\n}\n\n/** Make a result: `Result.ok(value)`, `Result.err({ kind: 'x', ... })`. */\nexport const Result: {\n readonly ok: typeof ok;\n readonly err: typeof err;\n} = { ok, err };\n\n/**\n * Apply the discipline:\n * `Trust.try` / `Trust.tryAsync` are the only boundary that may catch a throw;\n * `Trust.decide` is the only place a failure may stop; `Trust.translate` the only place it may change kind.\n */\nexport const Trust: {\n readonly try: typeof tryResult;\n readonly tryAsync: typeof tryResultAsync;\n readonly decide: typeof decide;\n readonly translate: typeof translate;\n} = { try: tryResult, tryAsync: tryResultAsync, decide, translate };\n"],"mappings":";AAwBO,SAAS,GAAM,OAAiB;AACrC,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAaO,SAAS,IAAO,OAAkB;AACvC,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAWO,SAAS,UAAgB,IAAa,SAA8C;AACzF,MAAI;AACF,WAAO,GAAG,GAAG,CAAC;AAAA,EAChB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAcA,eAAsB,eACpB,IACA,SACuB;AACvB,MAAI;AACF,WAAO,GAAG,MAAM,GAAG,CAAC;AAAA,EACtB,SAAS,OAAO;AACd,WAAO,IAAI,QAAQ,KAAK,CAAC;AAAA,EAC3B;AACF;AAoDA,SAAS,KAAK,OAAe,MAA4D;AACvF,MAAI,OAAO,SAAS,YAAY,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,IAAI,EAAG,QAAO;AAC3F,SAAQ,MAAwD,IAAI;AACtE;AAWO,SAAS,OAAO,QAAkC,UAA2B;AAClF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,UAAU,KAAK,UAAW,OAAO,OAAqC,IAAI;AAChF,SAAO,YAAY,SAAY,SAAS,GAAG,QAAQ,OAAO,KAAK,CAAC;AAClE;AAQO,SAAS,UAAU,QAAkC,SAA0B;AACpF,MAAI,OAAO,GAAI,QAAO;AACtB,QAAM,SAAS,KAAK,SAAU,OAAO,OAAqC,IAAI;AAC9E,SAAO,WAAW,SAAY,SAAS,IAAI,OAAO,OAAO,KAAK,CAAC;AACjE;AAGO,IAAM,SAGT,EAAE,IAAI,IAAI;AAOP,IAAM,QAKT,EAAE,KAAK,WAAW,UAAU,gBAAgB,QAAQ,UAAU;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noego/trust",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Result type plus type-aware ESLint rules that make failure handling explicit: untrusted calls and throws must be caught locally and returned as Result.err.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|