@apifuse/provider-sdk 2.1.0-beta.2 → 2.1.0-beta.20

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.
Files changed (215) hide show
  1. package/AUTHORING.md +330 -8
  2. package/CHANGELOG.md +85 -1
  3. package/README.md +64 -17
  4. package/SUBMISSION.md +86 -0
  5. package/bin/apifuse-check.ts +60 -6
  6. package/bin/apifuse-dev.ts +58 -8
  7. package/bin/apifuse-pack-check.ts +32 -2
  8. package/bin/apifuse-pack-smoke.ts +133 -6
  9. package/bin/apifuse-perf.ts +142 -49
  10. package/bin/apifuse-record.ts +182 -104
  11. package/bin/apifuse-submit-check.ts +2849 -0
  12. package/bin/apifuse.ts +1 -1
  13. package/dist/auth.d.ts +76 -0
  14. package/dist/auth.js +436 -0
  15. package/dist/ceremonies/index.d.ts +41 -0
  16. package/dist/ceremonies/index.js +490 -0
  17. package/dist/choice-token.d.ts +24 -0
  18. package/dist/choice-token.js +74 -0
  19. package/dist/cli/commands.d.ts +10 -0
  20. package/dist/cli/commands.js +80 -0
  21. package/dist/cli/create.d.ts +47 -0
  22. package/dist/cli/create.js +745 -0
  23. package/dist/cli/templates/provider/.dockerignore.tpl +22 -0
  24. package/dist/cli/templates/provider/.gitignore.tpl +22 -0
  25. package/dist/cli/templates/provider/Dockerfile.tpl +7 -0
  26. package/dist/cli/templates/provider/README.md.tpl +163 -0
  27. package/dist/cli/templates/provider/dev.ts.tpl +5 -0
  28. package/dist/cli/templates/provider/domain/README.md.tpl +3 -0
  29. package/dist/cli/templates/provider/index.test.ts.tpl +13 -0
  30. package/dist/cli/templates/provider/index.ts.tpl +15 -0
  31. package/dist/cli/templates/provider/mappers/README.md.tpl +3 -0
  32. package/dist/cli/templates/provider/meta.ts.tpl +7 -0
  33. package/dist/cli/templates/provider/operations/index.ts.tpl +5 -0
  34. package/dist/cli/templates/provider/operations/ping.ts.tpl +24 -0
  35. package/dist/cli/templates/provider/schemas/ping.ts.tpl +24 -0
  36. package/dist/cli/templates/provider/start.ts.tpl +5 -0
  37. package/dist/cli/templates/provider/upstream/README.md.tpl +3 -0
  38. package/dist/config/loader.d.ts +107 -0
  39. package/dist/config/loader.js +935 -0
  40. package/dist/contract-json.d.ts +9 -0
  41. package/dist/contract-json.js +51 -0
  42. package/dist/contract-serialization.d.ts +4 -0
  43. package/dist/contract-serialization.js +78 -0
  44. package/dist/contract-types.d.ts +49 -0
  45. package/dist/contract-types.js +1 -0
  46. package/dist/contract.d.ts +6 -0
  47. package/dist/contract.js +156 -0
  48. package/dist/define.d.ts +100 -0
  49. package/dist/define.js +1383 -0
  50. package/dist/dev.d.ts +9 -0
  51. package/dist/dev.js +15 -0
  52. package/dist/errors.d.ts +59 -0
  53. package/dist/errors.js +97 -0
  54. package/dist/i18n/catalog.d.ts +29 -0
  55. package/dist/i18n/catalog.js +159 -0
  56. package/dist/i18n/index.d.ts +2 -0
  57. package/dist/i18n/index.js +2 -0
  58. package/dist/i18n/keys.d.ts +10 -0
  59. package/dist/i18n/keys.js +34 -0
  60. package/dist/index.d.ts +42 -0
  61. package/dist/index.js +38 -0
  62. package/dist/lint.d.ts +74 -0
  63. package/dist/lint.js +729 -0
  64. package/dist/observability.d.ts +5 -0
  65. package/dist/observability.js +39 -0
  66. package/dist/provider.d.ts +11 -0
  67. package/dist/provider.js +9 -0
  68. package/dist/public-schema-field-lint.d.ts +2 -0
  69. package/dist/public-schema-field-lint.js +158 -0
  70. package/dist/recipes/gov-api.d.ts +19 -0
  71. package/dist/recipes/gov-api.js +72 -0
  72. package/dist/recipes/rest-api.d.ts +21 -0
  73. package/dist/recipes/rest-api.js +115 -0
  74. package/dist/runtime/auth-flow.d.ts +14 -0
  75. package/dist/runtime/auth-flow.js +46 -0
  76. package/dist/runtime/browser.d.ts +25 -0
  77. package/dist/runtime/browser.js +1237 -0
  78. package/dist/runtime/cache.d.ts +10 -0
  79. package/dist/runtime/cache.js +372 -0
  80. package/dist/runtime/choice.d.ts +15 -0
  81. package/dist/runtime/choice.js +435 -0
  82. package/dist/runtime/credential.d.ts +8 -0
  83. package/dist/runtime/credential.js +61 -0
  84. package/dist/runtime/env.d.ts +2 -0
  85. package/dist/runtime/env.js +10 -0
  86. package/dist/runtime/executor.d.ts +16 -0
  87. package/dist/runtime/executor.js +51 -0
  88. package/dist/runtime/http.d.ts +8 -0
  89. package/dist/runtime/http.js +726 -0
  90. package/dist/runtime/insights.d.ts +9 -0
  91. package/dist/runtime/insights.js +324 -0
  92. package/dist/runtime/instrumentation.d.ts +8 -0
  93. package/dist/runtime/instrumentation.js +269 -0
  94. package/dist/runtime/key-derivation.d.ts +24 -0
  95. package/dist/runtime/key-derivation.js +73 -0
  96. package/dist/runtime/keyring.d.ts +25 -0
  97. package/dist/runtime/keyring.js +93 -0
  98. package/dist/runtime/namespace.d.ts +9 -0
  99. package/dist/runtime/namespace.js +19 -0
  100. package/dist/runtime/otlp.d.ts +39 -0
  101. package/dist/runtime/otlp.js +103 -0
  102. package/dist/runtime/perf.d.ts +12 -0
  103. package/dist/runtime/perf.js +52 -0
  104. package/dist/runtime/prevalidate.d.ts +12 -0
  105. package/dist/runtime/prevalidate.js +173 -0
  106. package/dist/runtime/provider.d.ts +2 -0
  107. package/dist/runtime/provider.js +11 -0
  108. package/dist/runtime/proxy-errors.d.ts +21 -0
  109. package/dist/runtime/proxy-errors.js +83 -0
  110. package/dist/runtime/proxy-telemetry.d.ts +8 -0
  111. package/dist/runtime/proxy-telemetry.js +174 -0
  112. package/dist/runtime/redis.d.ts +17 -0
  113. package/dist/runtime/redis.js +82 -0
  114. package/dist/runtime/request-options.d.ts +3 -0
  115. package/dist/runtime/request-options.js +42 -0
  116. package/dist/runtime/state.d.ts +17 -0
  117. package/dist/runtime/state.js +344 -0
  118. package/dist/runtime/stealth.d.ts +21 -0
  119. package/dist/runtime/stealth.js +980 -0
  120. package/dist/runtime/stt.d.ts +22 -0
  121. package/dist/runtime/stt.js +480 -0
  122. package/dist/runtime/trace.d.ts +26 -0
  123. package/dist/runtime/trace.js +142 -0
  124. package/dist/runtime/waterfall.d.ts +12 -0
  125. package/dist/runtime/waterfall.js +147 -0
  126. package/dist/schema.d.ts +74 -0
  127. package/dist/schema.js +243 -0
  128. package/dist/serve.d.ts +1 -0
  129. package/dist/serve.js +1 -0
  130. package/dist/server/index.d.ts +3 -0
  131. package/dist/server/index.js +2 -0
  132. package/dist/server/serve.d.ts +64 -0
  133. package/dist/server/serve.js +1118 -0
  134. package/dist/server/types.d.ts +136 -0
  135. package/dist/server/types.js +86 -0
  136. package/dist/stealth/profiles.d.ts +4 -0
  137. package/dist/stealth/profiles.js +259 -0
  138. package/dist/stream.d.ts +44 -0
  139. package/dist/stream.js +151 -0
  140. package/dist/testing/helpers.d.ts +23 -0
  141. package/dist/testing/helpers.js +95 -0
  142. package/dist/testing/index.d.ts +2 -0
  143. package/dist/testing/index.js +2 -0
  144. package/dist/testing/run.d.ts +34 -0
  145. package/dist/testing/run.js +307 -0
  146. package/dist/types.d.ts +1467 -0
  147. package/dist/types.js +61 -0
  148. package/dist/utils/date.d.ts +6 -0
  149. package/dist/utils/date.js +101 -0
  150. package/dist/utils/parse.d.ts +16 -0
  151. package/dist/utils/parse.js +51 -0
  152. package/dist/utils/text.d.ts +4 -0
  153. package/dist/utils/text.js +14 -0
  154. package/dist/utils/transform.d.ts +8 -0
  155. package/dist/utils/transform.js +48 -0
  156. package/package.json +56 -29
  157. package/src/auth.ts +786 -0
  158. package/src/ceremonies/index.ts +8 -2
  159. package/src/choice-token.ts +165 -0
  160. package/src/cli/commands.ts +34 -11
  161. package/src/cli/create.ts +222 -128
  162. package/src/cli/templates/provider/.dockerignore.tpl +22 -0
  163. package/src/cli/templates/provider/.gitignore.tpl +22 -0
  164. package/src/cli/templates/provider/README.md.tpl +87 -7
  165. package/src/cli/templates/provider/dev.ts.tpl +1 -1
  166. package/src/cli/templates/provider/domain/README.md.tpl +3 -0
  167. package/src/cli/templates/provider/index.ts.tpl +5 -47
  168. package/src/cli/templates/provider/mappers/README.md.tpl +3 -0
  169. package/src/cli/templates/provider/meta.ts.tpl +7 -0
  170. package/src/cli/templates/provider/operations/index.ts.tpl +5 -0
  171. package/src/cli/templates/provider/operations/ping.ts.tpl +24 -0
  172. package/src/cli/templates/provider/schemas/ping.ts.tpl +24 -0
  173. package/src/cli/templates/provider/start.ts.tpl +1 -1
  174. package/src/cli/templates/provider/upstream/README.md.tpl +3 -0
  175. package/src/config/loader.ts +1224 -9
  176. package/src/contract-json.ts +75 -0
  177. package/src/contract-serialization.ts +89 -0
  178. package/src/contract-types.ts +52 -0
  179. package/src/contract.ts +216 -0
  180. package/src/define.ts +1820 -70
  181. package/src/errors.ts +27 -0
  182. package/src/i18n/catalog.ts +277 -0
  183. package/src/i18n/index.ts +2 -0
  184. package/src/i18n/keys.ts +64 -0
  185. package/src/index.ts +189 -9
  186. package/src/lint.ts +580 -73
  187. package/src/observability.ts +41 -0
  188. package/src/provider.ts +131 -4
  189. package/src/public-schema-field-lint.ts +237 -0
  190. package/src/runtime/auth-flow.ts +9 -0
  191. package/src/runtime/browser.ts +1054 -51
  192. package/src/runtime/cache.ts +528 -0
  193. package/src/runtime/choice.ts +760 -0
  194. package/src/runtime/executor.ts +32 -3
  195. package/src/runtime/http.ts +980 -195
  196. package/src/runtime/insights.ts +11 -11
  197. package/src/runtime/instrumentation.ts +12 -4
  198. package/src/runtime/key-derivation.ts +1 -1
  199. package/src/runtime/keyring.ts +4 -3
  200. package/src/runtime/proxy-errors.ts +132 -0
  201. package/src/runtime/proxy-telemetry.ts +253 -0
  202. package/src/runtime/redis.ts +116 -0
  203. package/src/runtime/request-options.ts +66 -0
  204. package/src/runtime/state.ts +563 -0
  205. package/src/runtime/stealth.ts +1336 -0
  206. package/src/runtime/stt.ts +629 -0
  207. package/src/runtime/trace.ts +1 -1
  208. package/src/schema.ts +363 -1
  209. package/src/server/serve.ts +1192 -75
  210. package/src/server/types.ts +37 -0
  211. package/src/stream.ts +210 -0
  212. package/src/testing/run.ts +40 -6
  213. package/src/types.ts +1283 -59
  214. package/src/runtime/tls.ts +0 -434
  215. package/src/types/playwright-stealth.d.ts +0 -9
@@ -0,0 +1,2849 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { type ChildProcess, spawn } from "node:child_process";
4
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
5
+ import { writeFile } from "node:fs/promises";
6
+ import { createServer } from "node:net";
7
+ import { basename, dirname, join, relative, resolve } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+
10
+ import { z } from "zod";
11
+
12
+ import packageJson from "../package.json";
13
+ import type { ProviderDefinition } from "../src";
14
+ import {
15
+ loadProviderLocaleCatalogs,
16
+ type ProviderLocale,
17
+ validateProviderLocaleCatalogs,
18
+ } from "../src/i18n";
19
+ import { APIFUSE_DESCRIPTION_KEY_META_KEY } from "../src/schema";
20
+ import { safeParseSchemaSync } from "../src/schema";
21
+ import { type CheckResult, runChecks } from "./apifuse-check";
22
+
23
+ const TIERS = ["bronze", "silver", "gold", "diamond"] as const;
24
+ const TIER_VALUES: ReadonlySet<string> = new Set(TIERS);
25
+ type BountyTier = (typeof TIERS)[number];
26
+
27
+ type CheckLevel = "blocker" | "warn" | "info";
28
+ type CheckStatus = "pass" | "fail" | "warn" | "not_applicable";
29
+ type Verdict = "ready" | "reviewable_with_warnings" | "blocked";
30
+
31
+ export type SubmitCheck = {
32
+ id: string;
33
+ category: string;
34
+ level: CheckLevel;
35
+ status: CheckStatus;
36
+ points: number;
37
+ maxPoints: number;
38
+ message: string;
39
+ remediation?: string;
40
+ evidence?: string[];
41
+ details?: unknown;
42
+ };
43
+
44
+ export type SubmitCheckReport = {
45
+ schemaVersion: 1;
46
+ generatedAt: string;
47
+ provider: {
48
+ id: string;
49
+ version: string;
50
+ runtime: string;
51
+ authMode: string;
52
+ sdkVersion: string;
53
+ tier?: BountyTier;
54
+ };
55
+ score: {
56
+ total: number;
57
+ max: 100;
58
+ verdict: Verdict;
59
+ };
60
+ summary: {
61
+ blockers: number;
62
+ warnings: number;
63
+ passed: number;
64
+ };
65
+ checks: SubmitCheck[];
66
+ };
67
+
68
+ export function isAutoPromotionEligible(report: SubmitCheckReport): boolean {
69
+ return report.score.total >= 95 && report.summary.blockers === 0;
70
+ }
71
+
72
+ type CliArgs = {
73
+ isJson: boolean;
74
+ markdownPath?: string;
75
+ providerPath?: string;
76
+ smoke: boolean;
77
+ smokeNote?: string;
78
+ tier?: BountyTier;
79
+ };
80
+
81
+ type SecretFinding = {
82
+ label: string;
83
+ file: string;
84
+ line?: number;
85
+ level?: CheckLevel;
86
+ remediation?: string;
87
+ evidence?: string;
88
+ };
89
+
90
+ export type SmokeOperationOutcome = {
91
+ operationId: string;
92
+ status: "success" | "structured_error" | "incoherent";
93
+ httpStatus?: number;
94
+ message: string;
95
+ };
96
+
97
+ export type SmokeResult = {
98
+ measured: true;
99
+ healthOk: boolean;
100
+ bootError?: string;
101
+ operations: SmokeOperationOutcome[];
102
+ };
103
+
104
+ type SourceFinding = {
105
+ file: string;
106
+ line: number;
107
+ };
108
+
109
+ const SDK_NATIVE_CATEGORY = "sdk-native";
110
+ const VENDOR_SHIM_PROVIDER_ID_PREFIX = "apifuse-provider-";
111
+ const MAX_SOURCE_FINDING_EVIDENCE = 5;
112
+
113
+ const CATEGORY_MAX_POINTS = {
114
+ definition: 15,
115
+ operations: 15,
116
+ fixtures: 15,
117
+ health: 15,
118
+ smoke: 10,
119
+ auth: 10,
120
+ security: 10,
121
+ docs: 10,
122
+ } as const;
123
+
124
+ const REQUIRED_PUBLIC_PROVIDER_LOCALES = ["en", "ko"] as const satisfies readonly ProviderLocale[];
125
+
126
+ const HELP_TEXT = `Usage: apifuse submit-check [path] [--tier bronze|silver|gold|diamond] [--json] [--markdown <path>] [--smoke]
127
+ Alias: apifuse bounty-check [path]
128
+ Default: apifuse submit-check .
129
+
130
+ Smoke: --smoke boots the provider dev server, checks /health, and POSTs every operation fixture. APIFUSE__PROVIDER__* env vars enable live upstream calls; without them, structured provider errors can still verify runtime routing. --smoke-note is deprecated and ignored for scoring.`;
131
+
132
+ export async function main() {
133
+ try {
134
+ const args = parseArgs(normalizeArgs(process.argv.slice(2)));
135
+
136
+ if (args.isJson && process.argv.includes("--help")) {
137
+ console.log(JSON.stringify({ help: HELP_TEXT }));
138
+ return;
139
+ }
140
+
141
+ const providerRoot = resolveProviderRoot(args.providerPath ?? ".");
142
+ const report = await buildSubmitCheckReport(providerRoot, args);
143
+
144
+ if (args.markdownPath) {
145
+ await writeFile(resolve(process.cwd(), args.markdownPath), renderMarkdown(report));
146
+ }
147
+
148
+ if (args.isJson) {
149
+ console.log(JSON.stringify(report, null, 2));
150
+ } else {
151
+ console.log(renderText(report));
152
+ if (args.markdownPath) {
153
+ console.log(`\nMarkdown report: ${args.markdownPath}`);
154
+ }
155
+ }
156
+
157
+ if (report.score.verdict === "blocked") {
158
+ process.exit(1);
159
+ }
160
+ } catch (error) {
161
+ console.error(error instanceof Error ? error.message : String(error));
162
+ process.exit(1);
163
+ }
164
+ }
165
+
166
+ function normalizeArgs(argv: string[]): string[] {
167
+ const [command, ...rest] = argv;
168
+ return command === "submit-check" || command === "bounty-check" ? rest : argv;
169
+ }
170
+
171
+ function parseArgs(argv: string[]): CliArgs {
172
+ const args: CliArgs = { isJson: false, smoke: false };
173
+
174
+ for (let index = 0; index < argv.length; index += 1) {
175
+ const arg = argv[index];
176
+ if (!arg) continue;
177
+
178
+ if (arg === "--help" || arg === "-h") {
179
+ console.log(HELP_TEXT);
180
+ process.exit(0);
181
+ }
182
+
183
+ if (arg === "--json") {
184
+ args.isJson = true;
185
+ continue;
186
+ }
187
+
188
+ if (arg === "--markdown") {
189
+ args.markdownPath = requireValue(argv, index, arg);
190
+ index += 1;
191
+ continue;
192
+ }
193
+
194
+ if (arg.startsWith("--markdown=")) {
195
+ args.markdownPath = arg.slice("--markdown=".length);
196
+ continue;
197
+ }
198
+
199
+ if (arg === "--smoke") {
200
+ args.smoke = true;
201
+ continue;
202
+ }
203
+
204
+ if (arg === "--smoke-note") {
205
+ args.smokeNote = requireValue(argv, index, arg);
206
+ index += 1;
207
+ continue;
208
+ }
209
+
210
+ if (arg.startsWith("--smoke-note=")) {
211
+ args.smokeNote = arg.slice("--smoke-note=".length);
212
+ continue;
213
+ }
214
+
215
+ if (arg === "--tier") {
216
+ args.tier = parseTier(requireValue(argv, index, arg));
217
+ index += 1;
218
+ continue;
219
+ }
220
+
221
+ if (arg.startsWith("--tier=")) {
222
+ args.tier = parseTier(arg.slice("--tier=".length));
223
+ continue;
224
+ }
225
+
226
+ if (arg.startsWith("-")) {
227
+ throw new Error(`Unknown option: ${arg}`);
228
+ }
229
+
230
+ if (!args.providerPath) {
231
+ args.providerPath = arg;
232
+ continue;
233
+ }
234
+
235
+ throw new Error(`Unexpected argument: ${arg}`);
236
+ }
237
+
238
+ return args;
239
+ }
240
+
241
+ function requireValue(argv: string[], index: number, label: string): string {
242
+ const value = argv[index + 1];
243
+ if (!value) {
244
+ throw new Error(`Missing value for ${label}.`);
245
+ }
246
+ return value;
247
+ }
248
+
249
+ function parseTier(value: string): BountyTier {
250
+ if (isBountyTier(value)) {
251
+ return value;
252
+ }
253
+ throw new Error(`Invalid --tier "${value}". Expected one of: ${TIERS.join(", ")}`);
254
+ }
255
+
256
+ function isBountyTier(value: string): value is BountyTier {
257
+ return TIER_VALUES.has(value);
258
+ }
259
+
260
+ export async function buildSubmitCheckReport(
261
+ providerRoot: string,
262
+ args: { smoke?: boolean; smokeNote?: string; tier?: BountyTier } = {},
263
+ ): Promise<SubmitCheckReport> {
264
+ const checks: SubmitCheck[] = [];
265
+ const baseChecks = await safeRunChecks(providerRoot);
266
+ const provider = await safeLoadProvider(providerRoot);
267
+
268
+ checks.push(...scoreBaseChecks(baseChecks));
269
+ checks.push(scoreProviderIdSlug(providerRoot, provider));
270
+ checks.push(scoreNoVendorShim(providerRoot));
271
+ checks.push(scoreNoVendorImport(providerRoot));
272
+ checks.push(scoreDescribeKey(providerRoot));
273
+ checks.push(scoreNoRawFetch(providerRoot));
274
+ checks.push(scoreNoRedundantRuntimeGuards(providerRoot));
275
+ checks.push(scoreManagedBrowserRuntime(providerRoot));
276
+ checks.push(scoreAsAssertionCount(providerRoot));
277
+ checks.push(scoreUnsafeInputPassthrough(providerRoot));
278
+ checks.push(scoreUnjustifiedLooseSchema(providerRoot));
279
+ checks.push(scoreFlatOperationComposition(providerRoot));
280
+
281
+ if (provider) {
282
+ const smokeResult = args.smoke ? await runSubmitCheckSmoke(providerRoot, provider) : undefined;
283
+ checks.push(scoreCredentialUsage(providerRoot, provider));
284
+ checks.push(scoreLocaleCatalog(providerRoot, provider));
285
+ checks.push(scoreOperationMetadata(provider));
286
+ checks.push(scoreFixtureCoverage(provider));
287
+ checks.push(scoreHealthCoverage(provider));
288
+ checks.push(scoreAuthSafety(provider));
289
+ checks.push(scoreSmoke(smokeResult, args.smokeNote));
290
+ checks.push(...scoreProviderDocs(providerRoot));
291
+ checks.push(scoreRepositoryDx(providerRoot));
292
+ checks.push(scoreSecrets(providerRoot, provider));
293
+ } else {
294
+ checks.push(
295
+ blocker(
296
+ "provider-load",
297
+ "definition",
298
+ "Provider could not be loaded.",
299
+ "Fix index.ts so it default-exports defineProvider(...).",
300
+ CATEGORY_MAX_POINTS.definition,
301
+ ),
302
+ );
303
+ }
304
+
305
+ const total = clamp(Math.round(checks.reduce((sum, check) => sum + check.points, 0)), 0, 100);
306
+ const blockers = checks.filter(
307
+ (check) => check.level === "blocker" && check.status === "fail",
308
+ ).length;
309
+ const warnings = checks.filter((check) => check.status === "warn").length;
310
+ const passed = checks.filter((check) => check.status === "pass").length;
311
+ const verdict: Verdict =
312
+ blockers > 0 ? "blocked" : total >= 90 && warnings === 0 ? "ready" : "reviewable_with_warnings";
313
+
314
+ return {
315
+ schemaVersion: 1,
316
+ generatedAt: new Date().toISOString(),
317
+ provider: {
318
+ id: provider?.id ?? basename(providerRoot),
319
+ version: provider?.version ?? "unknown",
320
+ runtime: provider?.runtime ?? "unknown",
321
+ authMode: provider?.auth?.mode ?? "none",
322
+ sdkVersion: packageJson.version,
323
+ ...(args.tier ? { tier: args.tier } : {}),
324
+ },
325
+ score: { total, max: 100, verdict },
326
+ summary: { blockers, warnings, passed },
327
+ checks,
328
+ };
329
+ }
330
+
331
+ function scoreProviderIdSlug(
332
+ providerRoot: string,
333
+ provider: ProviderDefinition | undefined,
334
+ ): SubmitCheck {
335
+ const remediation =
336
+ 'Rename defineProvider({ id }) to the short slug (e.g. "tabelog", not "apifuse-provider-tabelog"). Also update manifest/PROVIDER_ID consts and tests. Grep: git grep "apifuse-provider-<name>".';
337
+
338
+ // Prefer the loaded provider id; fall back to scanning source so the rule
339
+ // still fires when the provider fails to load (e.g. a vendor shim or other
340
+ // structural problem prevents defineProvider from resolving).
341
+ if (provider) {
342
+ if (provider.id.startsWith(VENDOR_SHIM_PROVIDER_ID_PREFIX)) {
343
+ return blocker(
344
+ "id-slug",
345
+ SDK_NATIVE_CATEGORY,
346
+ "Provider id uses the apifuse-provider- prefix.",
347
+ remediation,
348
+ 0,
349
+ [provider.id],
350
+ );
351
+ }
352
+
353
+ return pass("id-slug", SDK_NATIVE_CATEGORY, "Provider id uses the short slug.", 0);
354
+ }
355
+
356
+ const findings = findSourceLineMatches(providerRoot, /["'`]apifuse-provider-[a-z0-9-]/i);
357
+ if (findings.length > 0) {
358
+ return blocker(
359
+ "id-slug",
360
+ SDK_NATIVE_CATEGORY,
361
+ "Provider id uses the apifuse-provider- prefix.",
362
+ remediation,
363
+ 0,
364
+ formatSourceFindings(findings),
365
+ );
366
+ }
367
+
368
+ return pass("id-slug", SDK_NATIVE_CATEGORY, "Provider id uses the short slug.", 0);
369
+ }
370
+
371
+ function scoreNoVendorShim(providerRoot: string): SubmitCheck {
372
+ const vendorPath = resolve(providerRoot, "vendor");
373
+ if (existsSync(vendorPath)) {
374
+ return blocker(
375
+ "no-vendor-shim",
376
+ SDK_NATIVE_CATEGORY,
377
+ "Provider contains a vendor/ SDK shim directory.",
378
+ "Delete vendor/ and import directly from @apifuse/provider-sdk (/provider, root, /testing). SDK-absent symbols (e.g. createStateContext) must use real SDK equivalents (createUnsupportedProviderRuntimeState for unused ctx.state).",
379
+ 0,
380
+ [vendorPath],
381
+ );
382
+ }
383
+
384
+ return pass(
385
+ "no-vendor-shim",
386
+ SDK_NATIVE_CATEGORY,
387
+ "Provider does not contain a vendor/ SDK shim directory.",
388
+ 0,
389
+ );
390
+ }
391
+
392
+ function scoreNoVendorImport(providerRoot: string): SubmitCheck {
393
+ const findings = findSourceLineMatches(providerRoot, /from\s+["'][^"']*vendor\//);
394
+ if (findings.length > 0) {
395
+ return blocker(
396
+ "no-vendor-import",
397
+ SDK_NATIVE_CATEGORY,
398
+ "Provider source imports from vendor/ shim.",
399
+ "Re-point every import from ../vendor/provider-sdk to @apifuse/provider-sdk/provider, @apifuse/provider-sdk, or @apifuse/provider-sdk/testing.",
400
+ 0,
401
+ formatSourceFindings(findings),
402
+ );
403
+ }
404
+
405
+ return pass(
406
+ "no-vendor-import",
407
+ SDK_NATIVE_CATEGORY,
408
+ "Provider source imports directly from the SDK.",
409
+ 0,
410
+ );
411
+ }
412
+
413
+ function scoreDescribeKey(providerRoot: string): SubmitCheck {
414
+ const findings = findSourceLineMatches(providerRoot, /\.describe\(["']/);
415
+ if (findings.length > 0) {
416
+ return blocker(
417
+ "describe-key",
418
+ SDK_NATIVE_CATEGORY,
419
+ "Schema descriptions use raw .describe() prose instead of describeKey.",
420
+ 'Replace .describe("prose") with describeKey(schema, key, { description }) backed by locale keys in locales/en.json + ko.json.',
421
+ 0,
422
+ formatSourceFindings(findings),
423
+ );
424
+ }
425
+
426
+ return pass("describe-key", SDK_NATIVE_CATEGORY, "Schema descriptions use describeKey.", 0);
427
+ }
428
+
429
+ function scoreNoRawFetch(providerRoot: string): SubmitCheck {
430
+ const findings = findSourceLineMatches(providerRoot, /(?<![.\w])fetch\s*\(/);
431
+ if (findings.length > 0) {
432
+ const evidence = formatSourceFindings(findings);
433
+ return blocker(
434
+ "no-raw-fetch",
435
+ SDK_NATIVE_CATEGORY,
436
+ "Provider source calls raw fetch().",
437
+ `Replace raw fetch() in ${evidence.join(", ")} with ctx.stealth.fetch() for stealth/cloud-IP-sensitive calls or ctx.http.get/post/request for ordinary HTTP calls.`,
438
+ 0,
439
+ evidence,
440
+ );
441
+ }
442
+
443
+ return pass("no-raw-fetch", SDK_NATIVE_CATEGORY, "Provider source avoids raw fetch().", 0);
444
+ }
445
+
446
+ const REDUNDANT_RUNTIME_GUARD_PATTERNS: readonly RegExp[] = [
447
+ /\bctx\.(?:stealth|http|cache|state|browser|trace|auth|stt|choice)\?\./,
448
+ ];
449
+
450
+ const SDK_CONTEXT_METHOD_ALIAS_PATTERN =
451
+ /\bconst\s+(\w+)\s*=\s*ctx\.(?:stealth|http|cache|state|browser|trace|auth|stt|choice)\.(?:\w+)/;
452
+
453
+ function hasRedundantRuntimeGuard(line: string, remainingLines: readonly string[]): boolean {
454
+ if (REDUNDANT_RUNTIME_GUARD_PATTERNS.some((pattern) => pattern.test(line))) {
455
+ return true;
456
+ }
457
+
458
+ const aliasMatch = SDK_CONTEXT_METHOD_ALIAS_PATTERN.exec(line);
459
+ const alias = aliasMatch?.[1];
460
+ if (!alias) {
461
+ return false;
462
+ }
463
+
464
+ const guardPattern = new RegExp(`(?:typeof\\s+${alias}\\s*!==\\s*["']function["']|!${alias}\\b)`);
465
+ return remainingLines.slice(0, 8).some((candidate) => guardPattern.test(candidate));
466
+ }
467
+
468
+ function scoreNoRedundantRuntimeGuards(providerRoot: string): SubmitCheck {
469
+ const findings = findSourceFindings(providerRoot, hasRedundantRuntimeGuard);
470
+ if (findings.length > 0) {
471
+ return blocker(
472
+ "no-redundant-runtime-guards",
473
+ SDK_NATIVE_CATEGORY,
474
+ "Provider source has redundant runtime guard code for SDK-owned context APIs.",
475
+ "Trust the provider SDK context contract: call ctx.stealth.fetch(), ctx.http, and other SDK-owned context APIs directly. Remove optional chaining and typeof function guards around non-null runtime clients.",
476
+ 0,
477
+ formatSourceFindings(findings),
478
+ );
479
+ }
480
+
481
+ return pass(
482
+ "no-redundant-runtime-guards",
483
+ SDK_NATIVE_CATEGORY,
484
+ "Provider source avoids redundant runtime guard code around SDK-owned context APIs.",
485
+ 0,
486
+ );
487
+ }
488
+
489
+ const AS_ASSERTION_PATTERN =
490
+ /\bas\s+(any|unknown|never|string|number|boolean)\b|\bas\s+[A-Z]|\bas\s+\{|\bas\s+Record\b|\bas\s+typeof\b/;
491
+
492
+ function countAsAssertions(providerRoot: string): {
493
+ count: number;
494
+ findings: SourceFinding[];
495
+ } {
496
+ let count = 0;
497
+ const findings: SourceFinding[] = [];
498
+
499
+ for (const filePath of listNonTestTypeScriptFiles(providerRoot)) {
500
+ const content = readFileSync(filePath, "utf8");
501
+ const lines = content.split(/\r?\n/);
502
+ for (let index = 0; index < lines.length; index += 1) {
503
+ const line = lines[index];
504
+ if (
505
+ line === undefined ||
506
+ line.includes("import") ||
507
+ /\bas\s*const\b/.test(line) ||
508
+ !AS_ASSERTION_PATTERN.test(line)
509
+ ) {
510
+ continue;
511
+ }
512
+
513
+ count += 1;
514
+ if (findings.length < MAX_SOURCE_FINDING_EVIDENCE) {
515
+ findings.push({
516
+ file: toRelativeProviderPath(providerRoot, filePath),
517
+ line: index + 1,
518
+ });
519
+ }
520
+ }
521
+ }
522
+
523
+ return { count, findings };
524
+ }
525
+
526
+ function scoreAsAssertionCount(providerRoot: string): SubmitCheck {
527
+ const { count, findings } = countAsAssertions(providerRoot);
528
+ const assertionLabel = "as " + "Type";
529
+ const remediation = `Replace \`${assertionLabel}\` with zod \`schema.safeParse()\` or \`if ('key' in obj)\` type guards. \`as const\` is allowed.`;
530
+
531
+ if (count > 20) {
532
+ return blocker(
533
+ "as-assertion-count",
534
+ SDK_NATIVE_CATEGORY,
535
+ `Provider uses ${count} type assertions (${assertionLabel}). Replace with zod safeParse or type guards.`,
536
+ remediation,
537
+ 0,
538
+ formatSourceFindings(findings),
539
+ );
540
+ }
541
+
542
+ if (count >= 6) {
543
+ return {
544
+ id: "as-assertion-count",
545
+ category: SDK_NATIVE_CATEGORY,
546
+ level: "warn",
547
+ status: "warn",
548
+ points: 0,
549
+ maxPoints: 0,
550
+ message: `Provider uses ${count} type assertions (${assertionLabel}). Replace with zod safeParse or type guards.`,
551
+ remediation,
552
+ evidence: formatSourceFindings(findings),
553
+ };
554
+ }
555
+
556
+ return pass(
557
+ "as-assertion-count",
558
+ SDK_NATIVE_CATEGORY,
559
+ "Type assertions are within the recommended limit.",
560
+ 0,
561
+ );
562
+ }
563
+
564
+ // Returns true when `findingLine` (1-based) or the line directly above it
565
+ // carries an `// @apifuse-allow <ruleId>:` acknowledgement comment.
566
+ function hasAllowOverride(lines: readonly string[], findingLine: number, ruleId: string): boolean {
567
+ const pattern = new RegExp(`@apifuse-allow\\s+${ruleId}\\b`);
568
+ const current = lines[findingLine - 1];
569
+ const previous = lines[findingLine - 2];
570
+ return (
571
+ (current !== undefined && pattern.test(current)) ||
572
+ (previous !== undefined && pattern.test(previous))
573
+ );
574
+ }
575
+
576
+ // Splits source findings into non-overridden (still violations) and
577
+ // acknowledged (escape-hatched) sets by re-reading each file's lines.
578
+ function partitionAllowOverrides(
579
+ providerRoot: string,
580
+ findings: readonly SourceFinding[],
581
+ ruleId: string,
582
+ ): { violations: SourceFinding[]; overridden: SourceFinding[] } {
583
+ const fileLineCache = new Map<string, string[]>();
584
+ const violations: SourceFinding[] = [];
585
+ const overridden: SourceFinding[] = [];
586
+
587
+ for (const finding of findings) {
588
+ const absolute = resolve(providerRoot, finding.file);
589
+ let lines = fileLineCache.get(absolute);
590
+ if (lines === undefined) {
591
+ lines = readFileSync(absolute, "utf8").split(/\r?\n/);
592
+ fileLineCache.set(absolute, lines);
593
+ }
594
+ if (hasAllowOverride(lines, finding.line, ruleId)) {
595
+ overridden.push(finding);
596
+ } else {
597
+ violations.push(finding);
598
+ }
599
+ }
600
+
601
+ return { violations, overridden };
602
+ }
603
+
604
+ // Builds a blocker/warn/pass result for an escape-hatch-aware rule:
605
+ // any non-overridden finding => blocker; only acknowledged overrides => warn;
606
+ // nothing => pass.
607
+ function escapeHatchResult(
608
+ providerRoot: string,
609
+ ruleId: string,
610
+ findings: readonly SourceFinding[],
611
+ copy: { blockerMessage: string; remediation: string; passMessage: string },
612
+ ): SubmitCheck {
613
+ if (findings.length === 0) {
614
+ return pass(ruleId, SDK_NATIVE_CATEGORY, copy.passMessage, 0);
615
+ }
616
+
617
+ const { violations, overridden } = partitionAllowOverrides(providerRoot, findings, ruleId);
618
+
619
+ if (violations.length > 0) {
620
+ return blocker(
621
+ ruleId,
622
+ SDK_NATIVE_CATEGORY,
623
+ copy.blockerMessage,
624
+ copy.remediation,
625
+ 0,
626
+ formatSourceFindings(violations),
627
+ );
628
+ }
629
+
630
+ return {
631
+ id: ruleId,
632
+ category: SDK_NATIVE_CATEGORY,
633
+ level: "warn",
634
+ status: "warn",
635
+ points: 0,
636
+ maxPoints: 0,
637
+ message: `${copy.blockerMessage} ${overridden.length} acknowledged @apifuse-allow override(s).`,
638
+ remediation: copy.remediation,
639
+ evidence: formatSourceFindings(overridden),
640
+ };
641
+ }
642
+
643
+ // 1-based line number of a character offset in `source`.
644
+ function offsetToLine(source: string, offset: number): number {
645
+ let line = 1;
646
+ for (let index = 0; index < offset && index < source.length; index += 1) {
647
+ if (source[index] === "\n") {
648
+ line += 1;
649
+ }
650
+ }
651
+ return line;
652
+ }
653
+
654
+ // ---------------------------------------------------------------------------
655
+ // SDK-native structural rules (input-passthrough, loose-schema, flat-operation)
656
+ //
657
+ // SCOPE & LIMITATION: these checks are source-grep heuristics, not a full AST
658
+ // analysis. They are deliberately tuned against the new-structure golden corpus
659
+ // (demaecan / kakaomap / triple) to catch the common non-standard SDK
660
+ // integration shapes seen in bounty submissions: inline/aliased/multi-line
661
+ // input .passthrough(), unjustified loose schemas, and factory-composed
662
+ // operations (inline, aliased, destructured, sibling-module, or unresolved
663
+ // import). They balance brackets and resolve one alias hop across the whole
664
+ // provider submission so trivial formatting/aliasing/module-split bypasses do
665
+ // not slip through.
666
+ //
667
+ // The flat-operation rule guards the "unsafe form" (an op map built by an
668
+ // OPAQUE builder whose operation set is hidden at the call site), not the mere
669
+ // presence of a function call. The stdlib enumerate-and-reshape idiom
670
+ // `Object.fromEntries(Object.entries(<source-visible obj>) ...)` is exempted:
671
+ // its op set still originates from a source-enumerable object and is only
672
+ // filtered/reshaped by pure built-ins. This is the verified golden pattern
673
+ // (triple narrows a statically-defined op object by a whitelist Set). Any other
674
+ // call — `makeOperations()`, a destructured factory, or
675
+ // `Object.fromEntries(buildEntries())` with no source-visible `Object.entries`
676
+ // — stays classified as factory composition and is blocked.
677
+ //
678
+ // They do NOT achieve AST-completeness. Known residual bypasses (schemas or
679
+ // operation maps imported from an external npm package, computed/dynamic
680
+ // property construction, or deliberate obfuscation) are out of reach for a
681
+ // text scan. submit-check is a bounty-workspace gate that runs ALONGSIDE human
682
+ // review; manual review remains the final backstop for adversarial submissions.
683
+ // Promoting these rules to a real TypeScript AST pass (ts.createSourceFile)
684
+ // is tracked as deferred follow-up work (Phase 8.7) and would require adding
685
+ // TypeScript as a provider-sdk dependency.
686
+ // ---------------------------------------------------------------------------
687
+
688
+ // Matches a `.passthrough()` call tolerant of whitespace before the parens or
689
+ // between them, so `.passthrough ()` / `.passthrough\n()` are still detected.
690
+ const PASSTHROUGH_CALL = /\.passthrough\s*\(\s*\)/;
691
+
692
+ // Strips redundant wrapping parentheses from an expression so that a value like
693
+ // `(makeOperations())` or `((x))` classifies the same as `makeOperations()`.
694
+ // Only unwraps when the leading `(` matches the trailing `)` at depth 0 (i.e.
695
+ // the whole expression is parenthesized), preserving call expressions such as
696
+ // `makeOperations()` whose first `(` is not a wrapper.
697
+ function unwrapParens(expr: string): string {
698
+ let value = expr.trim();
699
+ while (value.startsWith("(")) {
700
+ let depth = 0;
701
+ let matchIndex = -1;
702
+ for (let i = 0; i < value.length; i += 1) {
703
+ const ch = value[i];
704
+ if (ch === "(") {
705
+ depth += 1;
706
+ } else if (ch === ")") {
707
+ depth -= 1;
708
+ if (depth === 0) {
709
+ matchIndex = i;
710
+ break;
711
+ }
712
+ }
713
+ }
714
+ // Only a true wrapper spans the entire expression (closing paren is the
715
+ // last char). Otherwise the leading `(` belongs to a sub-expression.
716
+ if (matchIndex === value.length - 1) {
717
+ value = value.slice(1, -1).trim();
718
+ } else {
719
+ break;
720
+ }
721
+ }
722
+ return value;
723
+ }
724
+
725
+ // Returns the value-expression substring starting at `valueStart`, balanced
726
+ // across (){}[] and stopping at the first top-level `,`/`;` or unmatched
727
+ // closing bracket. This lets a property value be read across newlines, so a
728
+ // multi-line `input: z.object({...})\n.passthrough()` is captured whole.
729
+ function balancedValueExpression(source: string, valueStart: number): string {
730
+ let depth = 0;
731
+ let index = valueStart;
732
+ for (; index < source.length; index += 1) {
733
+ const ch = source[index];
734
+ if (ch === "(" || ch === "{" || ch === "[") {
735
+ depth += 1;
736
+ } else if (ch === ")" || ch === "}" || ch === "]") {
737
+ if (depth === 0) {
738
+ break;
739
+ }
740
+ depth -= 1;
741
+ } else if ((ch === "," || ch === ";") && depth === 0) {
742
+ break;
743
+ }
744
+ }
745
+ return source.slice(valueStart, index);
746
+ }
747
+
748
+ // True when an object-literal expression spreads a CALL expression at its top
749
+ // level, e.g. `{ ...makeOperations() }` or `{ ...a, ...build(x) }`. Spreads
750
+ // nested deeper than the outer object (inside handler bodies, nested objects,
751
+ // or arrays) are ignored, so only a factory composition of the object itself
752
+ // is detected. Input is expected to start at the outer `{`.
753
+ function hasTopLevelFactorySpread(expr: string): boolean {
754
+ const open = expr.indexOf("{");
755
+ if (open === -1) {
756
+ return false;
757
+ }
758
+ let depth = 0;
759
+ for (let i = open; i < expr.length; i += 1) {
760
+ const ch = expr[i];
761
+ if (ch === "{" || ch === "(" || ch === "[") {
762
+ depth += 1;
763
+ } else if (ch === "}" || ch === ")" || ch === "]") {
764
+ depth -= 1;
765
+ if (depth === 0) {
766
+ break;
767
+ }
768
+ } else if (ch === "." && depth === 1 && expr.startsWith("...", i)) {
769
+ // A spread at the object's own level. Check whether the spread
770
+ // argument is a call expression (factory) rather than a plain
771
+ // identifier/member spread of an already-built object.
772
+ const rest = expr.slice(i + 3);
773
+ if (/^\s*[A-Za-z_$][\w$.]*\s*\(/.test(rest)) {
774
+ return true;
775
+ }
776
+ }
777
+ }
778
+ return false;
779
+ }
780
+
781
+ // Collects the depth-1 spread IDENTIFIERS of an object-literal expression that
782
+ // are bare identifiers (not call expressions), e.g. `{ ...hidden, ...base }` ->
783
+ // ["hidden", "base"]. A `...makeOps()` call spread is already caught by
784
+ // hasTopLevelFactorySpread, so it is excluded here. These identifiers must be
785
+ // resolved to their declarations: `const hidden = makeOperations()` spread as
786
+ // `{ ...hidden }` is still a factory-composed map and must block.
787
+ function topLevelSpreadIdentifiers(expr: string): string[] {
788
+ const open = expr.indexOf("{");
789
+ if (open === -1) {
790
+ return [];
791
+ }
792
+ const names: string[] = [];
793
+ let depth = 0;
794
+ for (let i = open; i < expr.length; i += 1) {
795
+ const ch = expr[i];
796
+ if (ch === "{" || ch === "(" || ch === "[") {
797
+ depth += 1;
798
+ } else if (ch === "}" || ch === ")" || ch === "]") {
799
+ depth -= 1;
800
+ if (depth === 0) {
801
+ break;
802
+ }
803
+ } else if (ch === "." && depth === 1 && expr.startsWith("...", i)) {
804
+ const rest = expr.slice(i + 3);
805
+ // Bare identifier spread (no call parens) -> needs declaration
806
+ // resolution. `...obj.prop` member spreads are treated as already
807
+ // built and ignored (the leading identifier is captured).
808
+ const m = rest.match(/^\s*([A-Za-z_$][\w$]*)\s*(?![\w$(])/);
809
+ if (m?.[1]) {
810
+ names.push(m[1]);
811
+ }
812
+ }
813
+ }
814
+ return names;
815
+ }
816
+
817
+ // A call expression is an OPAQUE builder (block) when it invokes a
818
+ // provider-authored function whose body — and therefore the operation set — is
819
+ // not visible at the call site, e.g. `makeOperations()` or a destructured
820
+ // `const { operations } = createProviderComposition(...)`. It is NOT opaque
821
+ // when it is the stdlib `Object.fromEntries(Object.entries(<obj>) ...)`
822
+ // enumerate-and-reshape idiom: the operation set still originates from a
823
+ // source-visible object (the `Object.entries(...)` argument) and is merely
824
+ // filtered/reshaped by pure built-ins, so the registry/reviewer can still
825
+ // enumerate the op map from source. This is the verified golden pattern (a
826
+ // statically-defined op object narrowed by a whitelist Set).
827
+ //
828
+ // The exemption requires `Object.entries(` to be the ROOT of fromEntries'
829
+ // FIRST argument — not merely present somewhere inside the expression. This
830
+ // rejects opaque maps that only mention `Object.entries` deeper in a predicate,
831
+ // e.g. `Object.fromEntries(buildEntries().filter(([id]) => Object.entries(ALLOWED).some(...)))`,
832
+ // whose entries still originate from the opaque `buildEntries()` call. Any other
833
+ // expression — `Object.fromEntries(buildEntries())`, a destructured factory,
834
+ // `makeOperations()` — stays classified as factory composition.
835
+ const TRANSPARENT_RESHAPE_HEAD = /^Object\s*\.\s*fromEntries\s*\(/;
836
+ const OBJECT_ENTRIES_HEAD = /^Object\s*\.\s*entries\s*\(/;
837
+ function isTransparentObjectReshape(expr: string): boolean {
838
+ const head = TRANSPARENT_RESHAPE_HEAD.exec(expr);
839
+ if (!head) {
840
+ return false;
841
+ }
842
+ // First argument starts immediately after `fromEntries(`. The reshape is
843
+ // transparent only when that argument's root callee is `Object.entries(`
844
+ // (optionally chained: `Object.entries(obj).filter(...)`), so the source
845
+ // object is enumerable from source rather than produced by an opaque call.
846
+ const firstArg = expr.slice(head[0].length).trimStart();
847
+ return OBJECT_ENTRIES_HEAD.test(firstArg);
848
+ }
849
+
850
+ // Decide whether an `input:` property at `propIndex` is an operation's public
851
+ // input schema (the thing the rule guards) or merely a field literally named
852
+ // "input" inside a zod schema body (e.g. modelling an upstream payload that
853
+ // happens to have an `input` field: `z.object({ input: z.object(...) })`).
854
+ // We walk backwards to the directly-enclosing `{` and inspect the token that
855
+ // opened it: if that brace is the argument of a zod builder call such as
856
+ // `z.object(`, `z.strictObject(`, `z.looseObject(`, `z.record(`, or a bare
857
+ // `.object(` / `.shape(`, the `input` key is a schema field, not an operation
858
+ // input. Operation inputs live in a plain object literal (the operation
859
+ // definition), so their enclosing `{` is NOT immediately preceded by `(` of a
860
+ // schema builder.
861
+ function inputKeyIsSchemaField(source: string, propIndex: number): boolean {
862
+ let depth = 0;
863
+ let i = propIndex - 1;
864
+ for (; i >= 0; i -= 1) {
865
+ const ch = source[i];
866
+ if (ch === "}" || ch === ")" || ch === "]") {
867
+ depth += 1;
868
+ } else if (ch === "(" || ch === "[") {
869
+ if (depth === 0) {
870
+ // Reached an opening paren/bracket that directly contains the
871
+ // property — an array/call arg position, not an object literal.
872
+ return false;
873
+ }
874
+ depth -= 1;
875
+ } else if (ch === "{") {
876
+ if (depth === 0) {
877
+ break;
878
+ }
879
+ depth -= 1;
880
+ }
881
+ }
882
+ if (i < 0) {
883
+ return false;
884
+ }
885
+ // `i` indexes the directly-enclosing `{`. Look at the non-whitespace text
886
+ // immediately before it. A zod object/record builder opens with `(` then
887
+ // optionally whitespace then `{`, so the char before `{` is `(` and the
888
+ // callee just before that `(` is a zod builder identifier.
889
+ let j = i - 1;
890
+ while (j >= 0 && /\s/.test(source[j] ?? "")) {
891
+ j -= 1;
892
+ }
893
+ if (source[j] !== "(") {
894
+ return false;
895
+ }
896
+ // Capture the callee identifier chain that ends at this `(` and test its
897
+ // final member against the set of zod builders that take an object body.
898
+ const before = source.slice(Math.max(0, j - 60), j);
899
+ const calleeMatch = before.match(/([A-Za-z_$][\w$]*)\s*$/);
900
+ const callee = calleeMatch?.[1];
901
+ if (callee === undefined) {
902
+ return false;
903
+ }
904
+ const SCHEMA_BODY_BUILDERS = new Set([
905
+ "object",
906
+ "strictObject",
907
+ "looseObject",
908
+ "record",
909
+ "shape",
910
+ "extend",
911
+ "merge",
912
+ "catchall",
913
+ "partial",
914
+ "required",
915
+ "pick",
916
+ "omit",
917
+ "augment",
918
+ ]);
919
+ return SCHEMA_BODY_BUILDERS.has(callee);
920
+ }
921
+
922
+ // True when `source` imports the binding `name` from another module, i.e. a
923
+ // top-level `import { ..., name, ... } from "..."` (named or aliased) or a
924
+ // default/namespace import of `name`. Used to confirm an `input: <alias>`
925
+ // reference actually binds to an imported declaration before resolving it
926
+ // against the provider-wide passthrough map (prevents same-name collisions
927
+ // across unrelated modules from producing false positives).
928
+ function fileImportsBinding(source: string, name: string): boolean {
929
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
930
+ return new RegExp(`\\bimport\\b[^;]*\\b${escaped}\\b[^;]*\\bfrom\\b`).test(source);
931
+ }
932
+
933
+ // Resolves the ORIGINAL exported name for a local binding `localName`. When the
934
+ // file imports it under an alias — `import { requestSchema as inputSchema }` —
935
+ // the provider-wide passthrough map is keyed by the exported declaration name
936
+ // (`requestSchema`), not the local alias (`inputSchema`), so the alias must be
937
+ // mapped back before lookup. Returns `localName` unchanged when there is no
938
+ // aliased import (plain `import { requestSchema }` or a local declaration).
939
+ function importedOriginalName(source: string, localName: string): string {
940
+ const escaped = localName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
941
+ // Match `<original> as <localName>` inside any import specifier list.
942
+ const aliasMatch = new RegExp(
943
+ `\\bimport\\b[^;]*\\{[^}]*\\b([A-Za-z_$][\\w$]*)\\s+as\\s+${escaped}\\b[^}]*\\}[^;]*\\bfrom\\b`,
944
+ ).exec(source);
945
+ return aliasMatch?.[1] ?? localName;
946
+ }
947
+
948
+ function scoreUnsafeInputPassthrough(providerRoot: string): SubmitCheck {
949
+ const findings: SourceFinding[] = [];
950
+ const files = listNonTestTypeScriptFiles(providerRoot);
951
+
952
+ // Pass 1: collect every passthrough schema const across the WHOLE provider
953
+ // submission (not per-file), keyed by name -> declaration site. This lets an
954
+ // `input:` in index.ts resolve a non-`input`-named passthrough schema that
955
+ // was declared in another module (e.g. schemas.ts) and imported.
956
+ type ConstSite = { file: string; line: number };
957
+ const passthroughConsts = new Map<string, ConstSite>();
958
+ // Per-file map of passthrough const declarations, so an `input: <alias>` can
959
+ // resolve its ACTUAL binding (a same-file local declaration) before falling
960
+ // back to an imported cross-module schema. This prevents a generic name like
961
+ // `requestSchema` declared in one module from being matched against an
962
+ // unrelated `input: requestSchema` in another module (a false positive on a
963
+ // strict schema that merely shares the identifier).
964
+ const passthroughByFile = new Map<string, Map<string, ConstSite>>();
965
+ const fileSources = new Map<string, string>();
966
+ for (const filePath of files) {
967
+ const source = readFileSync(filePath, "utf8");
968
+ const relPath = toRelativeProviderPath(providerRoot, filePath);
969
+ fileSources.set(filePath, source);
970
+ const localMap = new Map<string, ConstSite>();
971
+ passthroughByFile.set(filePath, localMap);
972
+ const constDecl =
973
+ /(?:^|\n)[ \t]*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?\s*=/g;
974
+ for (let match = constDecl.exec(source); match !== null; match = constDecl.exec(source)) {
975
+ const name = match[1];
976
+ if (name === undefined) {
977
+ continue;
978
+ }
979
+ const valueStart = match.index + match[0].length;
980
+ const value = balancedValueExpression(source, valueStart);
981
+ if (PASSTHROUGH_CALL.test(value)) {
982
+ const site: ConstSite = {
983
+ file: relPath,
984
+ line: offsetToLine(source, valueStart),
985
+ };
986
+ localMap.set(name, site);
987
+ // First declaration wins for line attribution; duplicate names
988
+ // across modules are rare and either site is a valid pointer.
989
+ if (!passthroughConsts.has(name)) {
990
+ passthroughConsts.set(name, site);
991
+ }
992
+ }
993
+ }
994
+ }
995
+
996
+ const seen = new Set<string>();
997
+ const push = (site: ConstSite) => {
998
+ const key = `${site.file}:${site.line}`;
999
+ if (!seen.has(key)) {
1000
+ seen.add(key);
1001
+ findings.push({ file: site.file, line: site.line });
1002
+ }
1003
+ };
1004
+
1005
+ // Pass 2: inspect every `input:` property value across all files. A value
1006
+ // that is itself a passthrough expression, or that references a passthrough
1007
+ // const by name (resolved against the provider-wide map), is a violation.
1008
+ for (const filePath of files) {
1009
+ const source = fileSources.get(filePath) ?? readFileSync(filePath, "utf8");
1010
+ const relPath = toRelativeProviderPath(providerRoot, filePath);
1011
+
1012
+ const inputProp = /\binput\s*:\s*/g;
1013
+ for (let match = inputProp.exec(source); match !== null; match = inputProp.exec(source)) {
1014
+ // Skip `input` keys that are fields inside a zod schema body (e.g. an
1015
+ // upstream payload modelled as `z.object({ input: ... })`). Only an
1016
+ // operation's public `input:` property is in scope for this rule.
1017
+ if (inputKeyIsSchemaField(source, match.index)) {
1018
+ continue;
1019
+ }
1020
+ const valueStart = match.index + match[0].length;
1021
+ const value = balancedValueExpression(source, valueStart);
1022
+ if (PASSTHROUGH_CALL.test(value)) {
1023
+ push({ file: relPath, line: offsetToLine(source, valueStart) });
1024
+ continue;
1025
+ }
1026
+ const ref = value.trim().match(/^([A-Za-z_$][\w$]*)/);
1027
+ const refName = ref?.[1];
1028
+ if (refName) {
1029
+ // Resolve the alias by BINDING, not by global name. Prefer a
1030
+ // passthrough const declared in THIS file; otherwise only fall
1031
+ // back to the provider-wide map when this file actually imports
1032
+ // `refName` (so a generic name shared across modules cannot link
1033
+ // an unrelated strict input to a foreign passthrough schema).
1034
+ const localSite = passthroughByFile.get(filePath)?.get(refName);
1035
+ if (localSite) {
1036
+ push(localSite);
1037
+ } else if (fileImportsBinding(source, refName)) {
1038
+ // Imported binding: map a possible `orig as refName` alias
1039
+ // back to the exported name the provider-wide map is keyed by.
1040
+ const originalName = importedOriginalName(source, refName);
1041
+ const site = passthroughConsts.get(refName) ?? passthroughConsts.get(originalName);
1042
+ if (site) {
1043
+ push(site);
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+
1049
+ // `input,` shorthand binds a local `input` const; flag it if that const
1050
+ // is a passthrough schema declared in THIS file (the binding the
1051
+ // shorthand actually closes over).
1052
+ if (/(?:^|\n)[ \t]*input\s*,/.test(source)) {
1053
+ const localInput = passthroughByFile.get(filePath)?.get("input");
1054
+ if (localInput) {
1055
+ push(localInput);
1056
+ } else if (fileImportsBinding(source, "input")) {
1057
+ const site = passthroughConsts.get("input");
1058
+ if (site) {
1059
+ push(site);
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ return escapeHatchResult(providerRoot, "unsafe-input-passthrough", findings, {
1066
+ blockerMessage:
1067
+ "Public input schema uses .passthrough(); unknown caller fields are silently accepted or dropped.",
1068
+ remediation:
1069
+ "Use strict input schemas (z.object({...}) without .passthrough()). If upstream form replay genuinely needs it, allowlist the forwarded fields and add `// @apifuse-allow unsafe-input-passthrough: <reason>`.",
1070
+ passMessage: "Input schemas do not use unscoped .passthrough().",
1071
+ });
1072
+ }
1073
+
1074
+ function scoreUnjustifiedLooseSchema(providerRoot: string): SubmitCheck {
1075
+ const findings: SourceFinding[] = [];
1076
+
1077
+ for (const filePath of listNonTestTypeScriptFiles(providerRoot)) {
1078
+ const lines = readFileSync(filePath, "utf8").split(/\r?\n/);
1079
+ for (let index = 0; index < lines.length; index += 1) {
1080
+ const line = lines[index];
1081
+ if (line === undefined || !/\bz\.(record|unknown|any)\s*\(/.test(line)) {
1082
+ continue;
1083
+ }
1084
+ // A `//` justification comment on the same line or the line above
1085
+ // (including the `@apifuse-allow loose-schema:` form) acknowledges it.
1086
+ const previous = lines[index - 1];
1087
+ const justified = line.includes("//") || previous?.trim().startsWith("//") === true;
1088
+ if (!justified) {
1089
+ findings.push({
1090
+ file: toRelativeProviderPath(providerRoot, filePath),
1091
+ line: index + 1,
1092
+ });
1093
+ }
1094
+ }
1095
+ }
1096
+
1097
+ return escapeHatchResult(providerRoot, "unjustified-loose-schema", findings, {
1098
+ blockerMessage: "Loose schema (z.record/z.unknown/z.any) used without justification.",
1099
+ remediation:
1100
+ "Model the real shape with a typed zod schema. If the upstream payload is genuinely arbitrary, add a `// <reason>` comment or `// @apifuse-allow loose-schema: <reason>` on the line above.",
1101
+ passMessage: "Loose schemas are justified or absent.",
1102
+ });
1103
+ }
1104
+
1105
+ // True when `name` resolves, anywhere in the provider submission, to a
1106
+ // declaration whose initializer is an OPAQUE factory — a call expression
1107
+ // (`const hidden = makeOperations()`) or itself a factory spread — or to an
1108
+ // imported binding with no local declaration (out-of-view construction). Used
1109
+ // to classify a top-level spread identifier (`{ ...hidden }`) so an opaque
1110
+ // factory map cannot be laundered through a variable before being spread. The
1111
+ // stdlib transparent reshape is NOT treated as a factory (parity with the
1112
+ // direct-alias classification).
1113
+ function spreadIdentifierResolvesToFactory(
1114
+ providerRoot: string,
1115
+ indexPath: string,
1116
+ indexSource: string,
1117
+ name: string,
1118
+ ): boolean {
1119
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1120
+ const declRe = new RegExp(
1121
+ `(?:^|\\n)[ \t]*(?:export\\s+)?(?:const|let|var)\\s+${escaped}\\s*(?::[^=\\n]+)?\\s*=`,
1122
+ "g",
1123
+ );
1124
+ let sawDeclaration = false;
1125
+ for (const filePath of [
1126
+ indexPath,
1127
+ ...listNonTestTypeScriptFiles(providerRoot).filter((p) => resolve(p) !== resolve(indexPath)),
1128
+ ]) {
1129
+ if (!existsSync(filePath)) {
1130
+ continue;
1131
+ }
1132
+ const fileSource = filePath === indexPath ? indexSource : readFileSync(filePath, "utf8");
1133
+ const re = new RegExp(declRe.source, "g");
1134
+ for (let m = re.exec(fileSource); m !== null; m = re.exec(fileSource)) {
1135
+ sawDeclaration = true;
1136
+ const expr = unwrapParens(balancedValueExpression(fileSource, m.index + m[0].length).trim());
1137
+ const isFactory =
1138
+ (/^[A-Za-z_$][\w$.]*\s*\(/.test(expr) || hasTopLevelFactorySpread(expr)) &&
1139
+ !isTransparentObjectReshape(expr);
1140
+ if (isFactory) {
1141
+ return true;
1142
+ }
1143
+ }
1144
+ }
1145
+ // No local declaration anywhere but imported into index.ts => constructed
1146
+ // out of view; treat as factory (conservative, false-negative-safe).
1147
+ if (!sawDeclaration && fileImportsBinding(indexSource, name)) {
1148
+ return true;
1149
+ }
1150
+ return false;
1151
+ }
1152
+
1153
+ function scoreFlatOperationComposition(providerRoot: string): SubmitCheck {
1154
+ const indexPath = resolve(providerRoot, "index.ts");
1155
+ const ruleId = "flat-operation-composition";
1156
+ if (!existsSync(indexPath)) {
1157
+ return pass(
1158
+ ruleId,
1159
+ SDK_NATIVE_CATEGORY,
1160
+ "Provider index.ts not found; flat-operation check skipped.",
1161
+ 0,
1162
+ );
1163
+ }
1164
+
1165
+ const source = readFileSync(indexPath, "utf8");
1166
+ // Use the same whitespace-tolerant detection as the resolver below, so a
1167
+ // `defineProvider (` / `defineProvider\n(` formatting cannot pass the early
1168
+ // exit before the real classification runs.
1169
+ if (!/\bdefineProvider\s*\(/.test(source)) {
1170
+ return pass(
1171
+ ruleId,
1172
+ SDK_NATIVE_CATEGORY,
1173
+ "No defineProvider call to evaluate for operation composition.",
1174
+ 0,
1175
+ );
1176
+ }
1177
+
1178
+ // Scope the scan to the argument of the EXPORTED `defineProvider(...)` call.
1179
+ // A provider can contain helper/non-exported defineProvider calls before the
1180
+ // real default export (e.g. test scaffolds), so resolve the default export
1181
+ // rather than blindly taking the first regex match. Resolution order:
1182
+ // 1. `export default defineProvider(` — inline default export
1183
+ // 2. `export default <ident>` then `const <ident> = defineProvider(`
1184
+ // 3. fallback: first `defineProvider(` in the file
1185
+ let defineParenIndex = -1;
1186
+ const inlineDefault = /\bexport\s+default\s+defineProvider\s*\(/.exec(source);
1187
+ if (inlineDefault) {
1188
+ defineParenIndex = inlineDefault.index + inlineDefault[0].length - 1; // points at `(`
1189
+ } else {
1190
+ const namedDefault = /\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;?/.exec(source);
1191
+ const exportedName = namedDefault?.[1];
1192
+ if (exportedName !== undefined) {
1193
+ const namedDecl = new RegExp(
1194
+ `(?:^|\\n)[ \t]*(?:export\\s+)?(?:const|let|var)\\s+${exportedName}\\s*(?::[^=\\n]+)?\\s*=\\s*defineProvider\\s*\\(`,
1195
+ ).exec(source);
1196
+ if (namedDecl) {
1197
+ defineParenIndex = namedDecl.index + namedDecl[0].length - 1;
1198
+ }
1199
+ }
1200
+ if (defineParenIndex === -1) {
1201
+ const firstCall = /\bdefineProvider\s*\(/.exec(source);
1202
+ if (firstCall) {
1203
+ defineParenIndex = firstCall.index + firstCall[0].length - 1;
1204
+ }
1205
+ }
1206
+ }
1207
+ if (defineParenIndex === -1) {
1208
+ return pass(
1209
+ ruleId,
1210
+ SDK_NATIVE_CATEGORY,
1211
+ "No defineProvider call to evaluate for operation composition.",
1212
+ 0,
1213
+ );
1214
+ }
1215
+ const argStart = defineParenIndex + 1;
1216
+ const argText = balancedValueExpression(source, argStart);
1217
+
1218
+ // Resolve the value passed as `operations:` inside the defineProvider call,
1219
+ // following one alias hop. The value is classified as a static object
1220
+ // literal (pass) or a factory/call expression (block). The regex index is
1221
+ // offset back into the full source so line numbers stay accurate.
1222
+ const opsProp = /\boperations\s*:\s*/.exec(argText);
1223
+ let opsValue: string | undefined;
1224
+ let opsLine = 1;
1225
+ if (opsProp) {
1226
+ const valueStart = argStart + opsProp.index + opsProp[0].length;
1227
+ opsValue = unwrapParens(balancedValueExpression(source, valueStart).trim());
1228
+ opsLine = offsetToLine(source, valueStart);
1229
+ }
1230
+
1231
+ // Property shorthand: `defineProvider({ ..., operations })` — resolve the
1232
+ // local `operations` const initializer.
1233
+ let aliasName: string | undefined;
1234
+ if (opsValue === undefined) {
1235
+ if (/\boperations\s*[,}]/.test(argText)) {
1236
+ aliasName = "operations";
1237
+ }
1238
+ } else if (/^[A-Za-z_$][\w$]*$/.test(opsValue)) {
1239
+ // `operations: ops` — a bare identifier alias to resolve.
1240
+ aliasName = opsValue;
1241
+ }
1242
+
1243
+ // Determine the effective initializer expression to classify. The alias may
1244
+ // be declared in index.ts OR re-exported from a sibling module (the common
1245
+ // generated scaffold: `import { operations } from "./operations"` where
1246
+ // ./operations.ts builds the map with makeOperations()/Object.fromEntries).
1247
+ // Resolve across every provider source file so cross-module factory
1248
+ // composition cannot evade the blocker.
1249
+ let effective = opsValue;
1250
+ let effectiveLine = opsLine;
1251
+ let effectiveFile = "index.ts";
1252
+ if (aliasName !== undefined) {
1253
+ const aliasDecl = new RegExp(
1254
+ `(?:^|\\n)[ \t]*(?:export\\s+)?(?:const|let|var)\\s+${aliasName}\\s*(?::[^=\\n]+)?\\s*=`,
1255
+ );
1256
+ // Destructured factory form: `const { operations } = makeOps()`.
1257
+ const destructured = new RegExp(
1258
+ `(?:^|\\n)[ \t]*(?:export\\s+)?(?:const|let|var)\\s*\\{[^}]*\\b${aliasName}\\b[^}]*\\}\\s*=\\s*([A-Za-z_$][\\w$.]*)\\s*\\(`,
1259
+ );
1260
+
1261
+ // Search index.ts first (its line attribution wins), then siblings.
1262
+ const searchOrder = [
1263
+ indexPath,
1264
+ ...listNonTestTypeScriptFiles(providerRoot).filter((p) => resolve(p) !== resolve(indexPath)),
1265
+ ];
1266
+
1267
+ // Collect EVERY same-named declaration across the submission and classify
1268
+ // each as factory vs static. A factory declaration anywhere wins, so a
1269
+ // decoy static `const operations = {}` in an earlier-scanned file cannot
1270
+ // mask a factory-composed declaration in another module. (We deliberately
1271
+ // do not resolve the exact import target path; "any same-named factory
1272
+ // blocks" is the conservative, false-negative-avoiding choice for a gate.)
1273
+ type Candidate = {
1274
+ expr: string;
1275
+ line: number;
1276
+ file: string;
1277
+ isFactory: boolean;
1278
+ };
1279
+ const candidates: Candidate[] = [];
1280
+ for (const filePath of searchOrder) {
1281
+ if (!existsSync(filePath)) {
1282
+ continue;
1283
+ }
1284
+ const fileSource = filePath === indexPath ? source : readFileSync(filePath, "utf8");
1285
+ const relPath = toRelativeProviderPath(providerRoot, filePath);
1286
+
1287
+ const declRe = new RegExp(aliasDecl.source, "g");
1288
+ for (let m = declRe.exec(fileSource); m !== null; m = declRe.exec(fileSource)) {
1289
+ const valueStart = m.index + m[0].length;
1290
+ const expr = unwrapParens(balancedValueExpression(fileSource, valueStart).trim());
1291
+ const isFactory =
1292
+ (/^[A-Za-z_$][\w$.]*\s*\(/.test(expr) || hasTopLevelFactorySpread(expr)) &&
1293
+ !isTransparentObjectReshape(expr);
1294
+ candidates.push({
1295
+ expr,
1296
+ line: offsetToLine(fileSource, valueStart),
1297
+ file: relPath,
1298
+ isFactory,
1299
+ });
1300
+ }
1301
+ const destructRe = new RegExp(destructured.source, "g");
1302
+ for (let m = destructRe.exec(fileSource); m !== null; m = destructRe.exec(fileSource)) {
1303
+ candidates.push({
1304
+ expr: `${m[1]}(`,
1305
+ line: offsetToLine(fileSource, m.index),
1306
+ file: relPath,
1307
+ isFactory: true,
1308
+ });
1309
+ }
1310
+ }
1311
+
1312
+ const resolved = candidates.length > 0;
1313
+ if (resolved) {
1314
+ // Prefer a factory declaration (it blocks); otherwise keep the first
1315
+ // static declaration for line attribution.
1316
+ const factory = candidates.find((c) => c.isFactory);
1317
+ const chosen = factory ?? candidates[0];
1318
+ if (chosen !== undefined) {
1319
+ effective = chosen.expr;
1320
+ effectiveLine = chosen.line;
1321
+ effectiveFile = chosen.file;
1322
+ }
1323
+ }
1324
+
1325
+ // An imported alias that resolves to no local declaration anywhere in the
1326
+ // submission means the operations map is constructed out of view. Treat
1327
+ // the unresolved import as a factory-composed (non-static) shape rather
1328
+ // than silently passing.
1329
+ if (!resolved) {
1330
+ const importMatch = new RegExp(`\\bimport\\b[^;]*\\b${aliasName}\\b[^;]*\\bfrom\\b`).exec(
1331
+ source,
1332
+ );
1333
+ if (importMatch) {
1334
+ effective = `${aliasName}(`;
1335
+ effectiveLine = offsetToLine(source, importMatch.index);
1336
+ effectiveFile = "index.ts";
1337
+ }
1338
+ }
1339
+ }
1340
+
1341
+ // A value starting with `{` is an object literal, but it is only STATIC if
1342
+ // its TOP-LEVEL entries are all explicit properties. A factory spread such
1343
+ // as `{ ...makeOperations() }` still composes the map dynamically. We only
1344
+ // inspect depth-1 entries so that ordinary spreads deep inside operation
1345
+ // handler bodies (e.g. `{ ...headers }`, `...arr.map(...)`) are NOT mistaken
1346
+ // for a top-level factory composition of the operations map itself.
1347
+ const hasFactorySpread = effective !== undefined && hasTopLevelFactorySpread(effective);
1348
+ // A spread of a bare identifier (`{ ...hidden }`) is static ONLY when that
1349
+ // identifier resolves to a non-factory declaration. Resolve each top-level
1350
+ // spread identifier so an opaque factory map laundered through a variable
1351
+ // (`const hidden = makeOperations(); operations: { ...hidden }`) still blocks.
1352
+ const hasFactorySpreadIdentifier =
1353
+ effective !== undefined &&
1354
+ topLevelSpreadIdentifiers(effective).some((name) =>
1355
+ spreadIdentifierResolvesToFactory(providerRoot, indexPath, source, name),
1356
+ );
1357
+ const isStaticLiteral =
1358
+ effective?.startsWith("{") === true && !hasFactorySpread && !hasFactorySpreadIdentifier;
1359
+ // A call expression `ident(...)` (factory) or a factory-spread literal is
1360
+ // the rejected, non-static shape — UNLESS it is the stdlib
1361
+ // `Object.fromEntries(Object.entries(<source-visible obj>)...)` reshape,
1362
+ // whose op set is still enumerable from source (verified golden pattern).
1363
+ const isFactoryCall =
1364
+ effective !== undefined &&
1365
+ (/^[A-Za-z_$][\w$.]*\s*\(/.test(effective) || hasFactorySpread || hasFactorySpreadIdentifier) &&
1366
+ !isTransparentObjectReshape(effective);
1367
+
1368
+ if (isFactoryCall && !isStaticLiteral) {
1369
+ // Route through the shared escape-hatch partitioner so an
1370
+ // `// @apifuse-allow flat-operation-composition: <reason>` comment on
1371
+ // the reported line (or the line above) downgrades this blocker to a
1372
+ // counted warning, consistent with the other structural rules.
1373
+ return escapeHatchResult(providerRoot, ruleId, [{ file: effectiveFile, line: effectiveLine }], {
1374
+ blockerMessage:
1375
+ "defineProvider operations are composed by a factory call instead of a static object literal.",
1376
+ remediation:
1377
+ "Declare operations as a static literal: defineProvider({ operations: { 'op-id': defineOperation({...}) } }). The provider-registry AST gate requires static runtime/operations; factory composition fails the registry build. If composition is unavoidable, add `// @apifuse-allow flat-operation-composition: <reason>`.",
1378
+ passMessage: "defineProvider declares operations as a static object literal.",
1379
+ });
1380
+ }
1381
+
1382
+ return pass(
1383
+ ruleId,
1384
+ SDK_NATIVE_CATEGORY,
1385
+ "defineProvider declares operations as a static object literal.",
1386
+ 0,
1387
+ );
1388
+ }
1389
+
1390
+ function scoreCredentialUsage(providerRoot: string, provider: ProviderDefinition): SubmitCheck {
1391
+ const credentialReferences = findSourceLineMatches(providerRoot, /ctx\.credential/);
1392
+ const authMode = provider.auth?.mode ?? "none";
1393
+ const credentialKeys = provider.credential?.keys ?? [];
1394
+ const storesProviderCredential = authMode !== "none" || credentialKeys.length > 0;
1395
+
1396
+ if (storesProviderCredential && credentialReferences.length === 0) {
1397
+ return {
1398
+ id: "credential-usage",
1399
+ category: SDK_NATIVE_CATEGORY,
1400
+ level: "warn",
1401
+ status: "warn",
1402
+ points: 0,
1403
+ maxPoints: 0,
1404
+ message: "Credential-backed provider does not reference credential persistence in source.",
1405
+ remediation:
1406
+ "Persist provider session state through the SDK credential context instead of process-local state. See providers/catchtable for the reference pattern.",
1407
+ };
1408
+ }
1409
+
1410
+ return pass(
1411
+ "credential-usage",
1412
+ SDK_NATIVE_CATEGORY,
1413
+ authMode === "none" && credentialKeys.length === 0
1414
+ ? "Provider does not declare reusable credentials."
1415
+ : "Credential-backed provider references ctx.credential.",
1416
+ 0,
1417
+ credentialReferences.length > 0 ? formatSourceFindings(credentialReferences) : undefined,
1418
+ );
1419
+ }
1420
+
1421
+ function findSourceLineMatches(
1422
+ providerRoot: string,
1423
+ pattern: RegExp | ((line: string) => boolean),
1424
+ ): SourceFinding[] {
1425
+ return findSourceFindings(providerRoot, (line) => matchesLinePattern(line, pattern));
1426
+ }
1427
+
1428
+ function findSourceFindings(
1429
+ providerRoot: string,
1430
+ matchesLine: (line: string, remainingLines: readonly string[]) => boolean,
1431
+ ): SourceFinding[] {
1432
+ const findings: SourceFinding[] = [];
1433
+ for (const filePath of listNonTestTypeScriptFiles(providerRoot)) {
1434
+ const content = readFileSync(filePath, "utf8");
1435
+ const lines = content.split(/\r?\n/);
1436
+ for (let index = 0; index < lines.length; index += 1) {
1437
+ const line = lines[index];
1438
+ if (line !== undefined && matchesLine(line, lines.slice(index + 1))) {
1439
+ findings.push({
1440
+ file: toRelativeProviderPath(providerRoot, filePath),
1441
+ line: index + 1,
1442
+ });
1443
+ if (findings.length >= MAX_SOURCE_FINDING_EVIDENCE) {
1444
+ return findings;
1445
+ }
1446
+ }
1447
+ }
1448
+ }
1449
+ return findings;
1450
+ }
1451
+
1452
+ function matchesLinePattern(line: string, pattern: RegExp | ((line: string) => boolean)): boolean {
1453
+ return typeof pattern === "function" ? pattern(line) : pattern.test(line);
1454
+ }
1455
+
1456
+ function listNonTestTypeScriptFiles(providerRoot: string): string[] {
1457
+ const files: string[] = [];
1458
+ collectNonTestTypeScriptFiles(providerRoot, providerRoot, files);
1459
+ return files;
1460
+ }
1461
+
1462
+ function listNonTestProviderSourceFiles(providerRoot: string): string[] {
1463
+ const files: string[] = [];
1464
+ collectNonTestProviderSourceFiles(providerRoot, providerRoot, files);
1465
+ return files;
1466
+ }
1467
+
1468
+ function collectNonTestProviderSourceFiles(
1469
+ providerRoot: string,
1470
+ currentPath: string,
1471
+ files: string[],
1472
+ ): void {
1473
+ for (const entry of readdirSync(currentPath, { withFileTypes: true })) {
1474
+ const entryPath = join(currentPath, entry.name);
1475
+ const relativePath = toRelativeProviderPath(providerRoot, entryPath);
1476
+ if (entry.isDirectory()) {
1477
+ if (shouldScanSourceDirectory(relativePath)) {
1478
+ collectNonTestProviderSourceFiles(providerRoot, entryPath, files);
1479
+ }
1480
+ continue;
1481
+ }
1482
+ if (
1483
+ entry.isFile() &&
1484
+ isScannableProviderSourceFile(relativePath) &&
1485
+ !isExcludedTestSource(relativePath)
1486
+ ) {
1487
+ files.push(entryPath);
1488
+ }
1489
+ }
1490
+ }
1491
+
1492
+ function collectNonTestTypeScriptFiles(
1493
+ providerRoot: string,
1494
+ currentPath: string,
1495
+ files: string[],
1496
+ ): void {
1497
+ for (const entry of readdirSync(currentPath, { withFileTypes: true })) {
1498
+ const entryPath = join(currentPath, entry.name);
1499
+ const relativePath = toRelativeProviderPath(providerRoot, entryPath);
1500
+ if (entry.isDirectory()) {
1501
+ if (shouldScanSourceDirectory(relativePath)) {
1502
+ collectNonTestTypeScriptFiles(providerRoot, entryPath, files);
1503
+ }
1504
+ continue;
1505
+ }
1506
+ if (entry.isFile() && relativePath.endsWith(".ts") && !isExcludedTestSource(relativePath)) {
1507
+ files.push(entryPath);
1508
+ }
1509
+ }
1510
+ }
1511
+
1512
+ function isScannableProviderSourceFile(relativePath: string): boolean {
1513
+ return (
1514
+ /\.(?:ts|tsx|js|jsx|mjs|cjs|sh|bash)$/.test(relativePath) ||
1515
+ /(?:^|\/)Dockerfile(?:\.|$)/.test(relativePath) ||
1516
+ /(?:^|\/)entrypoint(?:\.|$)/.test(relativePath)
1517
+ );
1518
+ }
1519
+
1520
+ function shouldScanSourceDirectory(relativePath: string): boolean {
1521
+ return ![".git", "node_modules", "dist", "build", "coverage"].includes(relativePath);
1522
+ }
1523
+
1524
+ function isExcludedTestSource(relativePath: string): boolean {
1525
+ return (
1526
+ relativePath.endsWith(".test.ts") ||
1527
+ relativePath.startsWith("__tests__/") ||
1528
+ relativePath.includes("/__tests__/") ||
1529
+ relativePath.startsWith("tests/") ||
1530
+ relativePath.includes("/tests/")
1531
+ );
1532
+ }
1533
+
1534
+ function toRelativeProviderPath(providerRoot: string, filePath: string): string {
1535
+ return relative(providerRoot, filePath).replaceAll("\\", "/");
1536
+ }
1537
+
1538
+ function formatSourceFindings(findings: readonly SourceFinding[]): string[] {
1539
+ return findings.map((finding) => `${finding.file}:${finding.line}`);
1540
+ }
1541
+
1542
+ function scoreRepositoryDx(providerRoot: string): SubmitCheck {
1543
+ const missing: string[] = [];
1544
+ if (!existsSync(resolve(providerRoot, ".gitignore"))) {
1545
+ missing.push(".gitignore");
1546
+ }
1547
+
1548
+ const packageJsonPath = resolve(providerRoot, "package.json");
1549
+ const packageScripts = readPackageScripts(packageJsonPath);
1550
+ if (typeof packageScripts?.["type-check"] !== "string") {
1551
+ missing.push("package.json scripts.type-check");
1552
+ }
1553
+ if (!checkScriptRunsTypeCheck(packageScripts?.check)) {
1554
+ missing.push("package.json scripts.check includes type-check");
1555
+ }
1556
+
1557
+ if (missing.length === 0) {
1558
+ return pass(
1559
+ "repository-dx",
1560
+ "docs",
1561
+ "Repository includes generated-provider DX guardrails.",
1562
+ 0,
1563
+ );
1564
+ }
1565
+
1566
+ return {
1567
+ id: "repository-dx",
1568
+ category: "docs",
1569
+ level: "warn",
1570
+ status: "warn",
1571
+ points: 0,
1572
+ maxPoints: 0,
1573
+ message: `Generated repository DX guardrails are missing: ${missing.join(", ")}.`,
1574
+ remediation:
1575
+ "Regenerate with the current `apifuse create` template or add .gitignore plus `type-check: tsc --noEmit` and include it from `check`.",
1576
+ evidence: missing,
1577
+ };
1578
+ }
1579
+
1580
+ function readPackageScripts(packageJsonPath: string): Record<string, unknown> | undefined {
1581
+ if (!existsSync(packageJsonPath)) {
1582
+ return undefined;
1583
+ }
1584
+
1585
+ try {
1586
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
1587
+ if (!isRecord(packageJson) || !isRecord(packageJson.scripts)) {
1588
+ return undefined;
1589
+ }
1590
+ return packageJson.scripts;
1591
+ } catch {
1592
+ return undefined;
1593
+ }
1594
+ }
1595
+
1596
+ function checkScriptRunsTypeCheck(checkScript: unknown): boolean {
1597
+ return (
1598
+ typeof checkScript === "string" &&
1599
+ /(?:^|&&|;)\s*bun\s+run\s+type-check(?:\s|$)/.test(checkScript)
1600
+ );
1601
+ }
1602
+
1603
+ async function safeRunChecks(providerRoot: string): Promise<CheckResult[]> {
1604
+ try {
1605
+ return await runChecks(providerRoot, { lintMode: "standalone" });
1606
+ } catch (error) {
1607
+ return [
1608
+ {
1609
+ message: "Base provider checks can run",
1610
+ passed: false,
1611
+ details: [error instanceof Error ? error.message : String(error)],
1612
+ },
1613
+ ];
1614
+ }
1615
+ }
1616
+
1617
+ const SUBMIT_CHECK_BROWSER_PATTERNS: ReadonlyArray<{
1618
+ rule: string;
1619
+ pattern: RegExp;
1620
+ }> = [
1621
+ {
1622
+ rule: "browser-self-hosted-launch",
1623
+ pattern: /\b(?:playwright|chromium|firefox|webkit|puppeteer)\.launch\s*\(/,
1624
+ },
1625
+ {
1626
+ rule: "browser-self-hosted-child-process",
1627
+ pattern:
1628
+ /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|Bun\.spawn|Bun\.spawnSync)\s*\([^;]*\b(?:google-chrome|chrome|chromium|chromium-browser)\b|\$`[^`]*\b(?:google-chrome|chrome|chromium|chromium-browser)\b/,
1629
+ },
1630
+ {
1631
+ rule: "browser-self-hosted-remote-debugging-port",
1632
+ pattern:
1633
+ /(?:\b(?:google-chrome|chrome|chromium|chromium-browser)\b[\s\S]{0,240}--remote-debugging-port\b|--remote-debugging-port(?:=|\s+))/,
1634
+ },
1635
+ {
1636
+ rule: "browser-direct-cdp-version-poll",
1637
+ pattern: /\/json\/version\b/,
1638
+ },
1639
+ {
1640
+ rule: "browser-provider-local-cdp-env",
1641
+ pattern:
1642
+ /\b(?!APIFUSE__CDP_POOL__URL\b)[A-Z][A-Z0-9_]*_CDP_URL\b|process\.env(?:\.(?!APIFUSE__CDP_POOL__URL\b)[A-Z0-9_]*_CDP_URL\b|\[\s*["'`](?!APIFUSE__CDP_POOL__URL\b)[A-Z0-9_]*_CDP_URL["'`]\s*\])/,
1643
+ },
1644
+ ];
1645
+
1646
+ function scoreManagedBrowserRuntime(providerRoot: string): SubmitCheck {
1647
+ const maxManagedBrowserEvidence = MAX_SOURCE_FINDING_EVIDENCE * 2;
1648
+ const browserFindings: string[] = [];
1649
+ for (const filePath of listNonTestProviderSourceFiles(providerRoot)) {
1650
+ const content = readFileSync(filePath, "utf8");
1651
+ const lines = content.split(/\r?\n/);
1652
+ for (let index = 0; index < lines.length; index += 1) {
1653
+ const line = lines[index];
1654
+ if (line === undefined) continue;
1655
+ for (const { rule, pattern } of SUBMIT_CHECK_BROWSER_PATTERNS) {
1656
+ pattern.lastIndex = 0;
1657
+ if (!pattern.test(line)) continue;
1658
+ browserFindings.push(
1659
+ `${rule} ${toRelativeProviderPath(providerRoot, filePath)}:${index + 1}`,
1660
+ );
1661
+ if (browserFindings.length >= maxManagedBrowserEvidence) break;
1662
+ }
1663
+ if (browserFindings.length >= maxManagedBrowserEvidence) break;
1664
+ }
1665
+ if (browserFindings.length >= maxManagedBrowserEvidence) break;
1666
+ }
1667
+
1668
+ if (browserFindings.length > 0) {
1669
+ return {
1670
+ id: "managed-browser-runtime",
1671
+ category: SDK_NATIVE_CATEGORY,
1672
+ level: "warn",
1673
+ status: "warn",
1674
+ points: 0,
1675
+ maxPoints: 0,
1676
+ message:
1677
+ "Provider source contains self-hosted browser/CDP patterns that APIFuse maintainers must review before promotion.",
1678
+ remediation:
1679
+ "Use ctx.browser backed by the managed CDP Pool. Do not launch Playwright/Puppeteer/Chrome, poll /json/version, or read provider-local *_CDP_URL env vars in provider runtime code.",
1680
+ evidence: browserFindings.map(redact),
1681
+ };
1682
+ }
1683
+
1684
+ return pass(
1685
+ "managed-browser-runtime",
1686
+ SDK_NATIVE_CATEGORY,
1687
+ "Provider source avoids self-hosted browser/CDP runtime patterns.",
1688
+ 0,
1689
+ );
1690
+ }
1691
+
1692
+ function scoreBaseChecks(results: CheckResult[]): SubmitCheck[] {
1693
+ const failed = results.filter((result) => !result.passed);
1694
+ if (failed.length > 0) {
1695
+ const remediation = [
1696
+ "Run `bunx apifuse check .` from the provider root.",
1697
+ ...Array.from(new Set(failed.map(baseCheckRemediation))),
1698
+ ].join(" ");
1699
+ return [
1700
+ {
1701
+ id: "base-checks",
1702
+ category: "definition",
1703
+ level: "blocker",
1704
+ status: "fail",
1705
+ points: 0,
1706
+ maxPoints: CATEGORY_MAX_POINTS.definition,
1707
+ message: "Base provider checks failed.",
1708
+ remediation,
1709
+ evidence: failed.map((result) =>
1710
+ redact(`${result.message}: ${(result.details ?? []).join("; ")}`),
1711
+ ),
1712
+ },
1713
+ ];
1714
+ }
1715
+
1716
+ return [
1717
+ {
1718
+ id: "base-checks",
1719
+ category: "definition",
1720
+ level: "info",
1721
+ status: "pass",
1722
+ points: CATEGORY_MAX_POINTS.definition,
1723
+ maxPoints: CATEGORY_MAX_POINTS.definition,
1724
+ message: "Base provider checks passed.",
1725
+ evidence: results.map((result) => result.message),
1726
+ },
1727
+ ];
1728
+ }
1729
+
1730
+ function baseCheckRemediation(result: CheckResult): string {
1731
+ switch (result.message) {
1732
+ case "index.ts exists and exports default defineProvider":
1733
+ return "Fix `index.ts` so it default-exports `defineProvider({...})`.";
1734
+ case "All operations have handler, input, output":
1735
+ return "For each operation named in evidence, add `handler`, `input`, and `output` fields to `defineProvider({ operations })`.";
1736
+ case "All operations have fixtures":
1737
+ return "For each operation named in evidence, add `fixtures.request` and `fixtures.response` values that exercise the operation schemas.";
1738
+ case "Zod schemas parse fixtures without error":
1739
+ return "Update the failing fixture values or their zod schemas until `fixtures.request` and `fixtures.response` parse cleanly.";
1740
+ case "Provider authoring lint has no error-level diagnostics":
1741
+ return "Fix each lint diagnostic shown in evidence, then rerun `bunx apifuse check .`.";
1742
+ case "Provider metadata is declared in defineProvider":
1743
+ return "Fill the missing `defineProvider` metadata fields: `id`, `meta.displayName`, `meta.category`, `runtime`, and `auth.mode`.";
1744
+ case "Dockerfile exists":
1745
+ return "Add a provider-root `Dockerfile` based on the current `apifuse create` template.";
1746
+ case "package.json exists with @apifuse/provider-sdk dependency":
1747
+ return "Add `@apifuse/provider-sdk` to `package.json` dependencies.";
1748
+ case "Base provider checks can run":
1749
+ return "Fix the import/runtime error shown in evidence so `apifuse check` can load the provider.";
1750
+ default:
1751
+ return `Fix the failing base check "${result.message}" shown in evidence.`;
1752
+ }
1753
+ }
1754
+
1755
+ function scoreLocaleCatalog(providerRoot: string, provider: ProviderDefinition): SubmitCheck {
1756
+ const requiredKeys = collectProviderRequiredLocaleKeys(provider);
1757
+ if (requiredKeys.length === 0) {
1758
+ return pass(
1759
+ "locale-catalog",
1760
+ "operations",
1761
+ "No key-owned provider metadata or operation metadata requires locale catalog validation.",
1762
+ 0,
1763
+ );
1764
+ }
1765
+
1766
+ try {
1767
+ const availableLocales = REQUIRED_PUBLIC_PROVIDER_LOCALES.filter((locale) =>
1768
+ existsSync(join(providerRoot, "locales", `${locale}.json`)),
1769
+ );
1770
+ const catalogs = loadProviderLocaleCatalogs({
1771
+ providerDir: providerRoot,
1772
+ locales: availableLocales,
1773
+ });
1774
+ const validation = validateProviderLocaleCatalogs({
1775
+ catalogs,
1776
+ requiredLocales: REQUIRED_PUBLIC_PROVIDER_LOCALES,
1777
+ requiredKeys,
1778
+ });
1779
+ if (!validation.ok) {
1780
+ return blocker(
1781
+ "locale-catalog",
1782
+ "operations",
1783
+ "Provider locale catalog is missing required public-provider copy.",
1784
+ "Add provider-local locales/en.json and locales/ko.json values for every provider metadata key, operation descriptionKey, and .describeKey() or describeKey() schema field.",
1785
+ 0,
1786
+ validation.issues.map((issue) => `${issue.locale}:${issue.key}: ${issue.message}`),
1787
+ );
1788
+ }
1789
+ } catch (error) {
1790
+ const message = error instanceof Error ? error.message : String(error);
1791
+ return blocker(
1792
+ "locale-catalog",
1793
+ "operations",
1794
+ "Provider locale catalog is missing required public-provider copy.",
1795
+ "Add provider-local locales/en.json and locales/ko.json values for every provider metadata key, operation descriptionKey, and .describeKey() or describeKey() schema field.",
1796
+ 0,
1797
+ [`*:*: ${message}`],
1798
+ );
1799
+ }
1800
+
1801
+ return pass(
1802
+ "locale-catalog",
1803
+ "operations",
1804
+ "Required provider and operation locale keys resolve in locales/en.json and locales/ko.json.",
1805
+ 0,
1806
+ );
1807
+ }
1808
+
1809
+ function collectProviderRequiredLocaleKeys(provider: ProviderDefinition): string[] {
1810
+ const keys = new Set<string>();
1811
+
1812
+ addLocaleKeys(keys, [
1813
+ provider.meta.descriptionKey,
1814
+ provider.meta.docTitleKey,
1815
+ provider.meta.docDescriptionKey,
1816
+ provider.meta.docSummaryKey,
1817
+ provider.meta.docMarkdownKey,
1818
+ ]);
1819
+
1820
+ const publicProfile = provider.meta.publicProfile;
1821
+ if (publicProfile) {
1822
+ addLocaleKeys(keys, [
1823
+ publicProfile.displayNameKey,
1824
+ publicProfile.shortDescriptionKey,
1825
+ publicProfile.longDescriptionKey,
1826
+ publicProfile.setupSummaryKey,
1827
+ ...(publicProfile.capabilityKeys ?? []),
1828
+ ...(publicProfile.examplePromptKeys ?? []),
1829
+ ...(publicProfile.requirementKeys ?? []),
1830
+ ...(publicProfile.limitationKeys ?? []),
1831
+ ]);
1832
+ }
1833
+
1834
+ for (const operation of Object.values(provider.operations)) {
1835
+ addLocaleKeys(keys, [
1836
+ operation.descriptionKey,
1837
+ operation.docs?.titleKey,
1838
+ operation.docs?.descriptionKey,
1839
+ operation.docs?.summaryKey,
1840
+ operation.docs?.markdownKey,
1841
+ ...(operation.whenToUseKeys ?? []),
1842
+ ...(operation.whenNotToUseKeys ?? []),
1843
+ ...collectSchemaDescriptionKeys(operation.input),
1844
+ ...collectSchemaDescriptionKeys(operation.output),
1845
+ ]);
1846
+ }
1847
+
1848
+ return Array.from(keys);
1849
+ }
1850
+
1851
+ function addLocaleKeys(keys: Set<string>, values: readonly unknown[]): void {
1852
+ for (const key of values) {
1853
+ if (typeof key === "string" && key.length > 0) {
1854
+ keys.add(key);
1855
+ }
1856
+ }
1857
+ }
1858
+
1859
+ function collectSchemaDescriptionKeys(schema: unknown): string[] {
1860
+ if (!(schema instanceof z.ZodType)) {
1861
+ return [];
1862
+ }
1863
+ const jsonSchema = z.toJSONSchema(schema);
1864
+ if (!isRecord(jsonSchema)) {
1865
+ return [];
1866
+ }
1867
+ const keys: string[] = [];
1868
+ collectJsonSchemaDescriptionKeys(jsonSchema, keys);
1869
+ return keys;
1870
+ }
1871
+
1872
+ function collectJsonSchemaDescriptionKeys(schema: Record<string, unknown>, keys: string[]): void {
1873
+ const descriptionKey = schema[APIFUSE_DESCRIPTION_KEY_META_KEY];
1874
+ if (typeof descriptionKey === "string" && descriptionKey.length > 0) {
1875
+ keys.push(descriptionKey);
1876
+ }
1877
+
1878
+ for (const value of Object.values(schema)) {
1879
+ if (isRecord(value)) {
1880
+ collectJsonSchemaDescriptionKeys(value, keys);
1881
+ } else if (Array.isArray(value)) {
1882
+ for (const item of value) {
1883
+ if (isRecord(item)) {
1884
+ collectJsonSchemaDescriptionKeys(item, keys);
1885
+ }
1886
+ }
1887
+ }
1888
+ }
1889
+ }
1890
+
1891
+ function isRecord(value: unknown): value is Record<string, unknown> {
1892
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1893
+ }
1894
+
1895
+ function scoreOperationMetadata(provider: ProviderDefinition): SubmitCheck {
1896
+ const operations = Object.entries(provider.operations);
1897
+ const weakDescriptions = operations
1898
+ .filter(([, operation]) => {
1899
+ // Hard-cut providers move operation copy into locale catalogs via
1900
+ // descriptionKey instead of raw inline prose; the resolved text length
1901
+ // is enforced at registry catalog-build time, matching how lintOperation
1902
+ // skips the raw-description min-length rule when a descriptionKey is set.
1903
+ const hasDescriptionKey =
1904
+ typeof operation.descriptionKey === "string" && operation.descriptionKey.length > 0;
1905
+ if (hasDescriptionKey) return false;
1906
+ return true;
1907
+ })
1908
+ .map(([operationId]) => operationId);
1909
+ const missingAnnotations = operations
1910
+ .filter(([, operation]) => !operation.annotations)
1911
+ .map(([operationId]) => operationId);
1912
+
1913
+ if (weakDescriptions.length > 0) {
1914
+ return {
1915
+ id: "operation-metadata",
1916
+ category: "operations",
1917
+ level: "blocker",
1918
+ status: "fail",
1919
+ points: 0,
1920
+ maxPoints: CATEGORY_MAX_POINTS.operations,
1921
+ message: "One or more operations have weak descriptions.",
1922
+ remediation: `For ${weakDescriptions.join(", ")}, add an operation \`descriptionKey\` backed by \`locales/en.json\` and \`locales/ko.json\`, or add a 150+ character \`description\` explaining when to use it, when not to use it, outputs, and caveats.`,
1923
+ evidence: weakDescriptions,
1924
+ };
1925
+ }
1926
+
1927
+ const points = missingAnnotations.length > 0 ? 11 : CATEGORY_MAX_POINTS.operations;
1928
+ return {
1929
+ id: "operation-metadata",
1930
+ category: "operations",
1931
+ level: missingAnnotations.length > 0 ? "warn" : "info",
1932
+ status: missingAnnotations.length > 0 ? "warn" : "pass",
1933
+ points,
1934
+ maxPoints: CATEGORY_MAX_POINTS.operations,
1935
+ message:
1936
+ missingAnnotations.length > 0
1937
+ ? "Operations are described, but some are missing safety annotations."
1938
+ : "Operation descriptions and metadata are review-ready.",
1939
+ remediation:
1940
+ missingAnnotations.length > 0
1941
+ ? `For ${missingAnnotations.join(", ")}, add \`annotations\` with the applicable safety fields, such as \`readOnly\`, \`destructive\`, \`idempotent\`, \`openWorld\`, \`rateLimit\`, or \`timeoutMs\`.`
1942
+ : undefined,
1943
+ evidence:
1944
+ missingAnnotations.length > 0
1945
+ ? missingAnnotations.map((operationId) => `${operationId}: missing annotations`)
1946
+ : operations.map(([operationId]) => operationId),
1947
+ };
1948
+ }
1949
+
1950
+ function scoreFixtureCoverage(provider: ProviderDefinition): SubmitCheck {
1951
+ const missing = Object.entries(provider.operations)
1952
+ .filter(([, operation]) => !operation.fixtures?.request || !operation.fixtures?.response)
1953
+ .map(([operationId]) => operationId);
1954
+ if (missing.length > 0) {
1955
+ return blocker(
1956
+ "fixtures",
1957
+ "fixtures",
1958
+ "One or more operations are missing bidirectional fixtures.",
1959
+ `For ${missing.join(", ")}, add \`fixtures.request\` and \`fixtures.response\` values that parse against the operation input and output schemas.`,
1960
+ CATEGORY_MAX_POINTS.fixtures,
1961
+ missing,
1962
+ );
1963
+ }
1964
+ return pass(
1965
+ "fixtures",
1966
+ "fixtures",
1967
+ "All operations include bidirectional fixtures.",
1968
+ CATEGORY_MAX_POINTS.fixtures,
1969
+ );
1970
+ }
1971
+
1972
+ function scoreHealthCoverage(provider: ProviderDefinition): SubmitCheck {
1973
+ const operations = Object.entries(provider.operations);
1974
+ const missing: string[] = [];
1975
+ const placeholder: string[] = [];
1976
+ const unsupported: string[] = [];
1977
+ const generatedStarter: string[] = [];
1978
+
1979
+ for (const [operationId, operation] of operations) {
1980
+ const hasCheck = operation.healthCheck !== undefined;
1981
+ const hasUnsupported = operation.healthCheckUnsupported !== undefined;
1982
+ if (!hasCheck && !hasUnsupported) {
1983
+ missing.push(operationId);
1984
+ continue;
1985
+ }
1986
+ if (hasUnsupported) {
1987
+ const reason = operation.healthCheckUnsupported?.reason ?? "";
1988
+ unsupported.push(operationId);
1989
+ if (/generated local-only scaffold/i.test(reason)) {
1990
+ generatedStarter.push(operationId);
1991
+ }
1992
+ if (
1993
+ /(todo|later|tbd|test fixture|unit test|placeholder|not sure|skip for test)/i.test(reason)
1994
+ ) {
1995
+ placeholder.push(operationId);
1996
+ }
1997
+ }
1998
+ }
1999
+
2000
+ if (missing.length > 0) {
2001
+ return blocker(
2002
+ "health-coverage",
2003
+ "health",
2004
+ "One or more operations lack healthCheck or healthCheckUnsupported.",
2005
+ `For ${missing.join(", ")}, add \`healthCheck: { interval, cases }\` for safe read-only upstream probes, or add \`healthCheckUnsupported: { reason: "<specific reason>" }\`.`,
2006
+ CATEGORY_MAX_POINTS.health,
2007
+ missing,
2008
+ );
2009
+ }
2010
+
2011
+ if (placeholder.length > 0) {
2012
+ return {
2013
+ id: "health-coverage",
2014
+ category: "health",
2015
+ level: "warn",
2016
+ status: "warn",
2017
+ points: 8,
2018
+ maxPoints: CATEGORY_MAX_POINTS.health,
2019
+ message: "Some healthCheckUnsupported reasons look placeholder-like.",
2020
+ remediation: `For ${placeholder.join(", ")}, replace the placeholder \`healthCheckUnsupported.reason\` with a specific reason such as destructive mutation, paid call, credential sensitivity, or upstream flakiness.`,
2021
+ evidence: placeholder,
2022
+ };
2023
+ }
2024
+
2025
+ if (generatedStarter.length > 0) {
2026
+ return {
2027
+ id: "health-coverage",
2028
+ category: "health",
2029
+ level: "warn",
2030
+ status: "warn",
2031
+ points: 10,
2032
+ maxPoints: CATEGORY_MAX_POINTS.health,
2033
+ message:
2034
+ "Generated starter operation health rationale is present; replace starter logic before bounty submission.",
2035
+ remediation: `Replace generated starter operation(s) ${generatedStarter.join(", ")} with real upstream-backed operations and add \`healthCheck\` for safe read-only probes.`,
2036
+ evidence: generatedStarter,
2037
+ };
2038
+ }
2039
+
2040
+ if (unsupported.length > 0) {
2041
+ return {
2042
+ id: "health-coverage",
2043
+ category: "health",
2044
+ level: "warn",
2045
+ status: "warn",
2046
+ points: 12,
2047
+ maxPoints: CATEGORY_MAX_POINTS.health,
2048
+ message: "Health coverage is declared, with one or more unsupported probes.",
2049
+ remediation: `For ${unsupported.join(", ")}, replace \`healthCheckUnsupported\` with \`healthCheck: { interval, cases }\` when the upstream operation is safe and read-only; keep unsupported only for destructive, paid, credential-sensitive, or flaky probes with a specific reason.`,
2050
+ evidence: unsupported.map((operationId) => `${operationId}: healthCheckUnsupported`),
2051
+ };
2052
+ }
2053
+
2054
+ return pass(
2055
+ "health-coverage",
2056
+ "health",
2057
+ "All operations declare real health checks.",
2058
+ CATEGORY_MAX_POINTS.health,
2059
+ );
2060
+ }
2061
+
2062
+ function scoreSmoke(
2063
+ smokeResult: SmokeResult | undefined,
2064
+ smokeNote: string | undefined,
2065
+ ): SubmitCheck {
2066
+ const deprecatedEvidence = smokeNote?.trim()
2067
+ ? ["Deprecated --smoke-note was provided and ignored for scoring."]
2068
+ : [];
2069
+ if (!smokeResult) {
2070
+ return {
2071
+ id: "local-smoke",
2072
+ category: "smoke",
2073
+ level: "warn",
2074
+ status: "warn",
2075
+ points: 0,
2076
+ maxPoints: CATEGORY_MAX_POINTS.smoke,
2077
+ message: "Measured local smoke was not run.",
2078
+ remediation:
2079
+ "Rerun submit-check with `--smoke` so it boots the provider, verifies `/health`, and POSTs every operation fixture. Set APIFUSE__PROVIDER__* env vars when live upstream credentials are available.",
2080
+ evidence: deprecatedEvidence,
2081
+ };
2082
+ }
2083
+
2084
+ const evidence = [
2085
+ `/health: ${smokeResult.healthOk ? "ok" : "failed"}`,
2086
+ ...smokeResult.operations.map(
2087
+ (outcome) =>
2088
+ `${outcome.operationId}: ${outcome.status}${outcome.httpStatus ? ` HTTP ${outcome.httpStatus}` : ""} - ${outcome.message}`,
2089
+ ),
2090
+ ...deprecatedEvidence,
2091
+ ];
2092
+ const incoherent = smokeResult.operations.filter((outcome) => outcome.status === "incoherent");
2093
+ if (!smokeResult.healthOk || smokeResult.bootError || incoherent.length > 0) {
2094
+ return {
2095
+ id: "local-smoke",
2096
+ category: "smoke",
2097
+ level: "blocker",
2098
+ status: "fail",
2099
+ points: 0,
2100
+ maxPoints: CATEGORY_MAX_POINTS.smoke,
2101
+ message: "Measured smoke failed to verify a coherent provider runtime.",
2102
+ remediation:
2103
+ "Fix the dev server boot, `/health`, or incoherent operation responses, then rerun `bun run submit-check -- --smoke`.",
2104
+ evidence: smokeResult.bootError ? [`boot: ${smokeResult.bootError}`, ...evidence] : evidence,
2105
+ details: smokeResult,
2106
+ };
2107
+ }
2108
+
2109
+ const successes = smokeResult.operations.filter((outcome) => outcome.status === "success");
2110
+ if (successes.length > 0) {
2111
+ return {
2112
+ id: "local-smoke",
2113
+ category: "smoke",
2114
+ level: "info",
2115
+ status: "pass",
2116
+ points: CATEGORY_MAX_POINTS.smoke,
2117
+ maxPoints: CATEGORY_MAX_POINTS.smoke,
2118
+ message: "Measured smoke passed with at least one schema-valid operation success.",
2119
+ evidence,
2120
+ details: smokeResult,
2121
+ };
2122
+ }
2123
+
2124
+ return {
2125
+ id: "local-smoke",
2126
+ category: "smoke",
2127
+ level: "warn",
2128
+ status: "warn",
2129
+ points: 7,
2130
+ maxPoints: CATEGORY_MAX_POINTS.smoke,
2131
+ message: "Runtime path was verified, but no live upstream schema-valid success was observed.",
2132
+ remediation:
2133
+ "Provide APIFUSE__PROVIDER__* env vars or fixture-safe upstream access, then rerun `bun run submit-check -- --smoke` to capture at least one schema-valid success.",
2134
+ evidence,
2135
+ details: smokeResult,
2136
+ };
2137
+ }
2138
+
2139
+ export async function runSubmitCheckSmoke(
2140
+ providerRoot: string,
2141
+ provider?: ProviderDefinition,
2142
+ ): Promise<SmokeResult> {
2143
+ const loadedProvider = provider ?? (await loadProvider(providerRoot));
2144
+ if (!loadedProvider) {
2145
+ return {
2146
+ measured: true,
2147
+ healthOk: false,
2148
+ bootError: "Provider could not be loaded.",
2149
+ operations: [],
2150
+ };
2151
+ }
2152
+
2153
+ const port = await getAvailablePort();
2154
+ const server = spawn("bun", ["run", "dev"], {
2155
+ cwd: providerRoot,
2156
+ env: { ...process.env, APIFUSE__RUNTIME__PORT: String(port) },
2157
+ detached: process.platform !== "win32",
2158
+ stdio: ["ignore", "pipe", "pipe"],
2159
+ });
2160
+ let output = "";
2161
+ server.stdout?.on("data", (chunk) => {
2162
+ output += chunk.toString();
2163
+ });
2164
+ server.stderr?.on("data", (chunk) => {
2165
+ output += chunk.toString();
2166
+ });
2167
+
2168
+ try {
2169
+ const baseUrl = `http://127.0.0.1:${port}`;
2170
+ const health = await waitForSmokeHealth(`${baseUrl}/health`, server, () => output);
2171
+ if (!health.ok) {
2172
+ return {
2173
+ measured: true,
2174
+ healthOk: false,
2175
+ bootError: health.error,
2176
+ operations: [],
2177
+ };
2178
+ }
2179
+ const operations: SmokeOperationOutcome[] = [];
2180
+ for (const [operationId, operation] of Object.entries(loadedProvider.operations)) {
2181
+ operations.push(
2182
+ await smokeOperation(baseUrl, operationId, operation.output, {
2183
+ requestId: `req_submit_check_smoke_${operationId}`,
2184
+ input: operation.fixtures?.request ?? {},
2185
+ headers: {},
2186
+ }),
2187
+ );
2188
+ }
2189
+ return { measured: true, healthOk: true, operations };
2190
+ } finally {
2191
+ await stopSmokeServer(server);
2192
+ }
2193
+ }
2194
+
2195
+ async function smokeOperation(
2196
+ baseUrl: string,
2197
+ operationId: string,
2198
+ outputSchema: ProviderDefinition["operations"][string]["output"],
2199
+ body: unknown,
2200
+ ): Promise<SmokeOperationOutcome> {
2201
+ try {
2202
+ const response = await fetch(`${baseUrl}/v1/${operationId}`, {
2203
+ method: "POST",
2204
+ headers: { "content-type": "application/json" },
2205
+ body: JSON.stringify(body),
2206
+ signal: AbortSignal.timeout(20_000),
2207
+ });
2208
+ const payload = await response.json().catch(() => undefined);
2209
+ if (response.ok && isRecord(payload) && "data" in payload) {
2210
+ const parsed = safeParseSchemaSync(
2211
+ outputSchema,
2212
+ payload.data,
2213
+ `operations.${operationId}.output`,
2214
+ );
2215
+ if (parsed.success) {
2216
+ return {
2217
+ operationId,
2218
+ status: "success",
2219
+ httpStatus: response.status,
2220
+ message: "schema-valid success",
2221
+ };
2222
+ }
2223
+ return {
2224
+ operationId,
2225
+ status: "incoherent",
2226
+ httpStatus: response.status,
2227
+ message: "success payload failed output schema validation",
2228
+ };
2229
+ }
2230
+ if (isStructuredProviderError(payload) && response.status < 500) {
2231
+ return {
2232
+ operationId,
2233
+ status: "structured_error",
2234
+ httpStatus: response.status,
2235
+ message: `${payload.error.code}: ${payload.error.message}`,
2236
+ };
2237
+ }
2238
+ return {
2239
+ operationId,
2240
+ status: "incoherent",
2241
+ httpStatus: response.status,
2242
+ message: isStructuredProviderError(payload)
2243
+ ? `${payload.error.code}: ${payload.error.message}`
2244
+ : "response was not a schema-valid success or structured provider error",
2245
+ };
2246
+ } catch (error) {
2247
+ return {
2248
+ operationId,
2249
+ status: "incoherent",
2250
+ message: error instanceof Error ? error.message : String(error),
2251
+ };
2252
+ }
2253
+ }
2254
+
2255
+ function isStructuredProviderError(
2256
+ value: unknown,
2257
+ ): value is { error: { code: string; message: string } } {
2258
+ return (
2259
+ isRecord(value) &&
2260
+ isRecord(value.error) &&
2261
+ typeof value.error.code === "string" &&
2262
+ typeof value.error.message === "string"
2263
+ );
2264
+ }
2265
+
2266
+ async function getAvailablePort(): Promise<number> {
2267
+ return await new Promise((resolvePromise, rejectPromise) => {
2268
+ const server = createServer();
2269
+ server.once("error", rejectPromise);
2270
+ server.listen(0, "127.0.0.1", () => {
2271
+ const address = server.address();
2272
+ server.close((error) => {
2273
+ if (error) {
2274
+ rejectPromise(error);
2275
+ return;
2276
+ }
2277
+ if (!address || typeof address === "string") {
2278
+ rejectPromise(new Error("Could not allocate a local TCP port."));
2279
+ return;
2280
+ }
2281
+ resolvePromise(address.port);
2282
+ });
2283
+ });
2284
+ });
2285
+ }
2286
+
2287
+ async function waitForSmokeHealth(
2288
+ url: string,
2289
+ server: ChildProcess,
2290
+ getOutput: () => string,
2291
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
2292
+ const deadline = Date.now() + 20_000;
2293
+ let lastError: unknown;
2294
+
2295
+ while (Date.now() < deadline) {
2296
+ if (server.exitCode !== null) {
2297
+ return {
2298
+ ok: false,
2299
+ error: `Dev server exited early with code ${server.exitCode}. ${getOutput()}`,
2300
+ };
2301
+ }
2302
+
2303
+ try {
2304
+ const response = await fetch(url, { signal: AbortSignal.timeout(1_000) });
2305
+ if (response.ok) return { ok: true };
2306
+ lastError = new Error(`${url} returned ${response.status}`);
2307
+ } catch (error) {
2308
+ lastError = error;
2309
+ }
2310
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, 200));
2311
+ }
2312
+
2313
+ return {
2314
+ ok: false,
2315
+ error: `Timed out waiting for ${url}: ${lastError instanceof Error ? lastError.message : String(lastError)}. ${getOutput()}`,
2316
+ };
2317
+ }
2318
+
2319
+ async function stopSmokeServer(server: ChildProcess): Promise<void> {
2320
+ if (server.exitCode !== null) return;
2321
+ killSmokeProcessTree(server, "SIGTERM");
2322
+ await new Promise<void>((resolvePromise) => {
2323
+ const timeout = setTimeout(() => {
2324
+ if (server.exitCode === null) {
2325
+ killSmokeProcessTree(server, "SIGKILL");
2326
+ }
2327
+ resolvePromise();
2328
+ }, 2_000);
2329
+ server.once("exit", () => {
2330
+ clearTimeout(timeout);
2331
+ resolvePromise();
2332
+ });
2333
+ });
2334
+ }
2335
+
2336
+ function killSmokeProcessTree(server: ChildProcess, signal: NodeJS.Signals): void {
2337
+ if (server.pid === undefined) return;
2338
+ try {
2339
+ if (process.platform === "win32") {
2340
+ server.kill(signal);
2341
+ return;
2342
+ }
2343
+ process.kill(-server.pid, signal);
2344
+ } catch {
2345
+ server.kill(signal);
2346
+ }
2347
+ }
2348
+
2349
+ function scoreAuthSafety(provider: ProviderDefinition): SubmitCheck {
2350
+ const authMode = provider.auth?.mode ?? "none";
2351
+ const credentialKeys = provider.credential?.keys ?? [];
2352
+ if (authMode === "credentials" && credentialKeys.length === 0) {
2353
+ return blocker(
2354
+ "auth-safety",
2355
+ "auth",
2356
+ "Credential-backed auth mode is missing credential.keys.",
2357
+ "Declare credential.keys and document local-only connection.secrets debugging.",
2358
+ CATEGORY_MAX_POINTS.auth,
2359
+ );
2360
+ }
2361
+
2362
+ if (authMode === "oauth2" && credentialKeys.length === 0) {
2363
+ return {
2364
+ id: "auth-safety",
2365
+ category: "auth",
2366
+ level: "warn",
2367
+ status: "warn",
2368
+ points: 7,
2369
+ maxPoints: CATEGORY_MAX_POINTS.auth,
2370
+ message: "OAuth auth mode does not declare persisted credential.keys.",
2371
+ remediation:
2372
+ "Add `credential: { keys: [...] }` to `defineProvider` with the persisted OAuth token fields returned by the real token exchange.",
2373
+ };
2374
+ }
2375
+
2376
+ if (authMode === "none") {
2377
+ const securedOperations = Object.entries(provider.operations).filter(
2378
+ ([, operation]) => operation.annotations?.openWorld === false,
2379
+ );
2380
+ if (securedOperations.length > 0) {
2381
+ return {
2382
+ id: "auth-safety",
2383
+ category: "auth",
2384
+ level: "warn",
2385
+ status: "warn",
2386
+ points: 7,
2387
+ maxPoints: CATEGORY_MAX_POINTS.auth,
2388
+ message: "Provider is no-auth but at least one operation is not marked openWorld.",
2389
+ remediation: `Either set \`auth.mode\` to the upstream auth model, or mark these public no-auth operations with \`annotations.openWorld: true\`: ${securedOperations.map(([operationId]) => operationId).join(", ")}.`,
2390
+ evidence: securedOperations.map(([operationId]) => operationId),
2391
+ };
2392
+ }
2393
+ }
2394
+
2395
+ return pass(
2396
+ "auth-safety",
2397
+ "auth",
2398
+ "Auth and credential declarations are internally consistent.",
2399
+ CATEGORY_MAX_POINTS.auth,
2400
+ );
2401
+ }
2402
+
2403
+ function scoreProviderDocs(providerRoot: string): SubmitCheck[] {
2404
+ const readmePath = resolve(providerRoot, "README.md");
2405
+ if (!existsSync(readmePath)) {
2406
+ return [
2407
+ {
2408
+ id: "submission-docs",
2409
+ category: "docs",
2410
+ level: "warn",
2411
+ status: "warn",
2412
+ points: 4,
2413
+ maxPoints: CATEGORY_MAX_POINTS.docs,
2414
+ message: "Provider README.md is missing.",
2415
+ remediation:
2416
+ "Add README sections for parameters, response shape, examples, auth/env setup, health coverage, and known upstream constraints.",
2417
+ },
2418
+ ];
2419
+ }
2420
+
2421
+ const readme = readFileSync(readmePath, "utf8").toLowerCase();
2422
+ const missing = [
2423
+ ["parameters", "Parameters"],
2424
+ ["response", "Response"],
2425
+ ["example", "Example"],
2426
+ ].filter(([needle]) => !readme.includes(needle));
2427
+ const mentionsSubmitCheck = readme.includes("submit-check");
2428
+
2429
+ const points = Math.max(
2430
+ 0,
2431
+ CATEGORY_MAX_POINTS.docs - missing.length * 2 - (mentionsSubmitCheck ? 0 : 1),
2432
+ );
2433
+
2434
+ return [
2435
+ {
2436
+ id: "submission-docs",
2437
+ category: "docs",
2438
+ level: missing.length > 0 || !mentionsSubmitCheck ? "warn" : "info",
2439
+ status: missing.length > 0 || !mentionsSubmitCheck ? "warn" : "pass",
2440
+ points,
2441
+ maxPoints: CATEGORY_MAX_POINTS.docs,
2442
+ message:
2443
+ missing.length > 0 || !mentionsSubmitCheck
2444
+ ? "Provider README is present but missing some submission evidence guidance."
2445
+ : "Provider README includes expected submission guidance.",
2446
+ remediation:
2447
+ missing.length > 0 || !mentionsSubmitCheck
2448
+ ? "Update `README.md` to include `Parameters`, `Response`, `Example`, and submit-check evidence guidance sections."
2449
+ : undefined,
2450
+ evidence: [
2451
+ ...missing.map(([, label]) => `missing ${label}`),
2452
+ ...(mentionsSubmitCheck ? [] : ["missing submit-check mention"]),
2453
+ ],
2454
+ },
2455
+ ];
2456
+ }
2457
+
2458
+ function scoreSecrets(providerRoot: string, provider?: ProviderDefinition): SubmitCheck {
2459
+ const findings = findSecretFindings(providerRoot, provider?.id);
2460
+ const blockerFindings = findings.filter((finding) => finding.level !== "warn");
2461
+ if (blockerFindings.length > 0) {
2462
+ return {
2463
+ id: "secret-scan",
2464
+ category: "security",
2465
+ level: "blocker",
2466
+ status: "fail",
2467
+ points: 0,
2468
+ maxPoints: CATEGORY_MAX_POINTS.security,
2469
+ message: "Potential real credential material was found in shareable files.",
2470
+ remediation:
2471
+ blockerFindings[0]?.remediation ??
2472
+ 'Move hardcoded credentials to env vars read via `ctx.env.get("APIFUSE__PROVIDER__<ID>__<NAME>")` and rotate the leaked credential.',
2473
+ evidence: blockerFindings.map(
2474
+ (finding) =>
2475
+ finding.evidence ??
2476
+ `${finding.file}${finding.line ? `:${finding.line}` : ""}: ${finding.label}`,
2477
+ ),
2478
+ };
2479
+ }
2480
+ if (findings.length > 0) {
2481
+ return {
2482
+ id: "secret-scan",
2483
+ category: "security",
2484
+ level: "warn",
2485
+ status: "warn",
2486
+ points: 8,
2487
+ maxPoints: CATEGORY_MAX_POINTS.security,
2488
+ message:
2489
+ "High-entropy source strings were found without secret-like identifier context; they may be false positives.",
2490
+ remediation:
2491
+ 'Review the listed strings. If any are credentials, move them to env vars read via `ctx.env.get("APIFUSE__PROVIDER__<ID>__<NAME>")` and rotate the leaked credential; otherwise keep generated blobs in fixtures/tests or document why they are public.',
2492
+ evidence: findings.map(
2493
+ (finding) =>
2494
+ finding.evidence ??
2495
+ `${finding.file}${finding.line ? `:${finding.line}` : ""}: ${finding.label}`,
2496
+ ),
2497
+ };
2498
+ }
2499
+
2500
+ return pass(
2501
+ "secret-scan",
2502
+ "security",
2503
+ "No high-confidence secrets were found in README, source, package, or fixtures.",
2504
+ CATEGORY_MAX_POINTS.security,
2505
+ );
2506
+ }
2507
+
2508
+ function findSecretFindings(providerRoot: string, providerId = "<ID>"): SecretFinding[] {
2509
+ const candidateFiles = [
2510
+ "README.md",
2511
+ "index.ts",
2512
+ "package.json",
2513
+ "__fixtures__/raw.json",
2514
+ "__fixtures__/transform.snap.json",
2515
+ ];
2516
+ const findings: SecretFinding[] = [];
2517
+
2518
+ for (const relativePath of candidateFiles) {
2519
+ const filePath = resolve(providerRoot, relativePath);
2520
+ if (!existsSync(filePath)) continue;
2521
+ const content = readFileSync(filePath, "utf8");
2522
+ for (const [label, pattern] of SECRET_PATTERNS) {
2523
+ if (pattern.test(content)) {
2524
+ findings.push({ label, file: relativePath });
2525
+ }
2526
+ }
2527
+ }
2528
+
2529
+ findings.push(...findEntropySecretFindings(providerRoot, providerId));
2530
+ return findings;
2531
+ }
2532
+
2533
+ function findEntropySecretFindings(providerRoot: string, providerId: string): SecretFinding[] {
2534
+ const findings: SecretFinding[] = [];
2535
+ for (const filePath of listNonTestProviderSourceFiles(providerRoot)) {
2536
+ const relativePath = toRelativeProviderPath(providerRoot, filePath);
2537
+ if (isEntropySecretExcludedPath(relativePath)) continue;
2538
+ const content = readFileSync(filePath, "utf8");
2539
+ const lines = content.split(/\r?\n/);
2540
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
2541
+ const line = lines[lineIndex] ?? "";
2542
+ for (const candidate of extractStringLiteralCandidates(line)) {
2543
+ const finding = classifyEntropyCandidate({
2544
+ value: candidate,
2545
+ line,
2546
+ file: relativePath,
2547
+ lineNumber: lineIndex + 1,
2548
+ providerId,
2549
+ });
2550
+ if (finding) findings.push(finding);
2551
+ }
2552
+ }
2553
+ }
2554
+ return findings;
2555
+ }
2556
+
2557
+ function isEntropySecretExcludedPath(relativePath: string): boolean {
2558
+ return (
2559
+ relativePath.endsWith(".test.ts") ||
2560
+ relativePath.startsWith("__tests__/") ||
2561
+ relativePath.includes("/__tests__/") ||
2562
+ relativePath.startsWith("__fixtures__/") ||
2563
+ relativePath.includes("/__fixtures__/")
2564
+ );
2565
+ }
2566
+
2567
+ export function extractStringLiteralCandidates(line: string): string[] {
2568
+ const candidates: string[] = [];
2569
+ for (let index = 0; index < line.length; index += 1) {
2570
+ const quote = line[index];
2571
+ if (quote !== '"' && quote !== "'" && quote !== "`") continue;
2572
+
2573
+ const contentStart = index + 1;
2574
+ let cursor = contentStart;
2575
+ while (cursor < line.length) {
2576
+ const char = line[cursor];
2577
+ if (char === "\\") {
2578
+ cursor += 2;
2579
+ continue;
2580
+ }
2581
+ if (char === quote) {
2582
+ if (cursor - contentStart >= 20) {
2583
+ candidates.push(line.slice(contentStart, cursor));
2584
+ }
2585
+ index = cursor;
2586
+ break;
2587
+ }
2588
+ cursor += 1;
2589
+ }
2590
+ }
2591
+ return candidates;
2592
+ }
2593
+
2594
+ function classifyEntropyCandidate(input: {
2595
+ value: string;
2596
+ line: string;
2597
+ file: string;
2598
+ lineNumber: number;
2599
+ providerId: string;
2600
+ }): SecretFinding | undefined {
2601
+ const value = input.value;
2602
+ if (!shouldConsiderEntropyValue(value)) return undefined;
2603
+ const charset = classifyEntropyCharset(value);
2604
+ if (!charset) return undefined;
2605
+ const entropy = shannonEntropy(value);
2606
+ const secretishContext = SECRETISH_IDENTIFIER_PATTERN.test(input.line);
2607
+ const threshold = charset === "hex" ? 3.0 : secretishContext ? 4.0 : 4.5;
2608
+ if (entropy < threshold) return undefined;
2609
+
2610
+ const preview = `${value.slice(0, 4)}...[REDACTED length=${value.length}]`;
2611
+ const envName = `APIFUSE__PROVIDER__${input.providerId.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}__${guessSecretName(input.line)}`;
2612
+ const location = `${input.file}:${input.lineNumber}`;
2613
+ const label =
2614
+ charset === "hex"
2615
+ ? `high-entropy hex string (${entropy.toFixed(2)} bits/char)`
2616
+ : `high-entropy base64-like string (${entropy.toFixed(2)} bits/char)`;
2617
+ return {
2618
+ label,
2619
+ file: input.file,
2620
+ line: input.lineNumber,
2621
+ level: secretishContext ? "blocker" : "warn",
2622
+ remediation: `Move ${location} to an env var read via \`ctx.env.get("${envName}")\` and rotate the leaked credential.`,
2623
+ evidence: `${location}: ${label}; preview ${preview}${secretishContext ? "" : "; may be a false positive"}`,
2624
+ };
2625
+ }
2626
+
2627
+ function shouldConsiderEntropyValue(value: string): boolean {
2628
+ const lower = value.toLowerCase();
2629
+ if (/^(?:dev-only|local|example|sample|your-|replace|<)/i.test(value)) {
2630
+ return false;
2631
+ }
2632
+ if (/^sha(?:256|512)-/i.test(value)) return false;
2633
+ if (/\s/.test(value)) return false;
2634
+ if (value.includes("${")) return false;
2635
+ if (value.includes("/")) return false;
2636
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return false;
2637
+ if (/^(?:\.{0,2}\/|~\/|[A-Za-z]:\\)/.test(value)) return false;
2638
+ if (value.includes(".") && /^[A-Za-z0-9_.-]+$/.test(value)) return false;
2639
+ if (lower.includes("/") && /\.[a-z0-9]{1,8}(?:$|[/?#])/i.test(value)) {
2640
+ return false;
2641
+ }
2642
+ return value.length >= 20;
2643
+ }
2644
+
2645
+ function classifyEntropyCharset(value: string): "base64" | "hex" | undefined {
2646
+ if (/^[a-f0-9]+$/i.test(value) && value.length >= 32) return "hex";
2647
+ const base64ishChars = value.match(/[A-Za-z0-9+/=_-]/g)?.length ?? 0;
2648
+ if (base64ishChars / value.length >= 0.9) return "base64";
2649
+ return undefined;
2650
+ }
2651
+
2652
+ function shannonEntropy(value: string): number {
2653
+ const counts = new Map<string, number>();
2654
+ for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
2655
+ let entropy = 0;
2656
+ for (const count of counts.values()) {
2657
+ const probability = count / value.length;
2658
+ entropy -= probability * Math.log2(probability);
2659
+ }
2660
+ return entropy;
2661
+ }
2662
+
2663
+ function guessSecretName(line: string): string {
2664
+ const match =
2665
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/.exec(line) ??
2666
+ /["']?([A-Za-z_$][\w$-]*)["']?\s*:/.exec(line);
2667
+ const raw = match?.[1] ?? "SECRET";
2668
+ return raw
2669
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
2670
+ .toUpperCase()
2671
+ .replace(/[^A-Z0-9]+/g, "_");
2672
+ }
2673
+
2674
+ const SECRETISH_IDENTIFIER_PATTERN = /key|token|secret|password|credential|auth/i;
2675
+
2676
+ const SECRET_PATTERNS: Array<[string, RegExp]> = [
2677
+ ["JWT-like token", /eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}/],
2678
+ ["GitHub token", /gh[pousr]_[A-Za-z0-9_]{30,}/],
2679
+ ["Stripe live key", /(?:sk|rk)_live_[A-Za-z0-9]{20,}/],
2680
+ ["Bearer token", /Bearer\s+[A-Za-z0-9._~+/=-]{32,}/i],
2681
+ [
2682
+ "credential field",
2683
+ /"(?:apiKey|api_key|accessToken|access_token|refreshToken|refresh_token|password|secret|sessionCookie|cookie)"\s*:\s*"(?!dev-only|local|example|sample|your-|replace|<)[^"]{16,}"/i,
2684
+ ],
2685
+ ];
2686
+
2687
+ async function safeLoadProvider(providerRoot: string): Promise<ProviderDefinition | undefined> {
2688
+ try {
2689
+ return await loadProvider(providerRoot);
2690
+ } catch {
2691
+ return undefined;
2692
+ }
2693
+ }
2694
+
2695
+ async function loadProvider(providerRoot: string): Promise<ProviderDefinition | undefined> {
2696
+ const entryPath = resolve(providerRoot, "index.ts");
2697
+ if (!existsSync(entryPath)) {
2698
+ return undefined;
2699
+ }
2700
+ const module = (await import(pathToFileURL(entryPath).href)) as {
2701
+ default?: ProviderDefinition;
2702
+ };
2703
+ return module.default;
2704
+ }
2705
+
2706
+ function resolveProviderRoot(inputPath: string): string {
2707
+ let current = resolve(process.cwd(), inputPath);
2708
+ if (!existsSync(current)) {
2709
+ throw new Error(`Provider path not found: ${inputPath}`);
2710
+ }
2711
+ if (!existsSync(resolve(current, "index.ts"))) {
2712
+ current = dirname(current);
2713
+ }
2714
+ while (!existsSync(resolve(current, "index.ts"))) {
2715
+ const parent = dirname(current);
2716
+ if (parent === current) {
2717
+ throw new Error(`Could not find provider root for: ${inputPath}`);
2718
+ }
2719
+ current = parent;
2720
+ }
2721
+ return current;
2722
+ }
2723
+
2724
+ function pass(
2725
+ id: string,
2726
+ category: string,
2727
+ message: string,
2728
+ points: number,
2729
+ evidence?: string[],
2730
+ ): SubmitCheck {
2731
+ return {
2732
+ id,
2733
+ category,
2734
+ level: "info",
2735
+ status: "pass",
2736
+ points,
2737
+ maxPoints: points,
2738
+ message,
2739
+ ...(evidence ? { evidence } : {}),
2740
+ };
2741
+ }
2742
+
2743
+ function blocker(
2744
+ id: string,
2745
+ category: string,
2746
+ message: string,
2747
+ remediation: string,
2748
+ maxPoints: number,
2749
+ evidence?: string[],
2750
+ ): SubmitCheck {
2751
+ return {
2752
+ id,
2753
+ category,
2754
+ level: "blocker",
2755
+ status: "fail",
2756
+ points: 0,
2757
+ maxPoints,
2758
+ message,
2759
+ remediation,
2760
+ ...(evidence ? { evidence: evidence.map(redact) } : {}),
2761
+ };
2762
+ }
2763
+
2764
+ export function renderText(report: SubmitCheckReport): string {
2765
+ const lines = [
2766
+ `APIFuse Provider Submission Score: ${report.score.total} / ${report.score.max}`,
2767
+ `Verdict: ${report.score.verdict.toUpperCase()}`,
2768
+ `Provider: ${report.provider.id}@${report.provider.version} (${report.provider.runtime}, auth: ${report.provider.authMode})`,
2769
+ `Blockers: ${report.summary.blockers} Warnings: ${report.summary.warnings} Passed: ${report.summary.passed}`,
2770
+ "",
2771
+ "Checklist:",
2772
+ ];
2773
+
2774
+ for (const check of report.checks) {
2775
+ const marker = check.status === "pass" ? "✓" : check.status === "warn" ? "⚠" : "✗";
2776
+ lines.push(
2777
+ `${marker} [${check.category}] ${check.message} (${check.points}/${check.maxPoints})`,
2778
+ );
2779
+ if (check.remediation) {
2780
+ lines.push(` Fix: ${check.remediation}`);
2781
+ }
2782
+ for (const evidence of check.evidence ?? []) {
2783
+ lines.push(` - ${redact(evidence)}`);
2784
+ }
2785
+ }
2786
+
2787
+ return lines.join("\n");
2788
+ }
2789
+
2790
+ export function renderMarkdown(report: SubmitCheckReport): string {
2791
+ const lines = [
2792
+ "# APIFuse Provider Submission Report",
2793
+ "",
2794
+ `- **Provider**: ${report.provider.id}@${report.provider.version}`,
2795
+ `- **SDK**: ${report.provider.sdkVersion}`,
2796
+ `- **Runtime/Auth**: ${report.provider.runtime} / ${report.provider.authMode}`,
2797
+ ...(report.provider.tier ? [`- **Bounty tier**: ${report.provider.tier}`] : []),
2798
+ `- **Score**: ${report.score.total}/${report.score.max}`,
2799
+ `- **Verdict**: ${report.score.verdict}`,
2800
+ `- **Blockers**: ${report.summary.blockers}`,
2801
+ `- **Warnings**: ${report.summary.warnings}`,
2802
+ "",
2803
+ "## Checklist",
2804
+ "",
2805
+ "| Status | Category | Check | Points | Remediation |",
2806
+ "|---|---|---|---:|---|",
2807
+ ];
2808
+
2809
+ for (const check of report.checks) {
2810
+ const status = check.status === "pass" ? "PASS" : check.status === "warn" ? "WARN" : "FAIL";
2811
+ lines.push(
2812
+ `| ${status} | ${escapeMarkdown(check.category)} | ${escapeMarkdown(check.message)} | ${check.points}/${check.maxPoints} | ${escapeMarkdown(check.remediation ?? "")} |`,
2813
+ );
2814
+ }
2815
+
2816
+ const evidence = report.checks.flatMap((check) =>
2817
+ (check.evidence ?? []).map((item) => `- **${check.id}**: ${redact(item)}`),
2818
+ );
2819
+ if (evidence.length > 0) {
2820
+ lines.push("", "## Evidence", "", ...evidence);
2821
+ }
2822
+
2823
+ lines.push("");
2824
+ return `${lines.join("\n")}\n`;
2825
+ }
2826
+
2827
+ function escapeMarkdown(value: string): string {
2828
+ return redact(value).replaceAll("|", "\\|").replaceAll("\n", " ");
2829
+ }
2830
+
2831
+ function redact(value: string): string {
2832
+ let output = value;
2833
+ for (const [, pattern] of SECRET_PATTERNS) {
2834
+ output = output.replace(toGlobalRegex(pattern), "[REDACTED]");
2835
+ }
2836
+ return output;
2837
+ }
2838
+
2839
+ function toGlobalRegex(pattern: RegExp): RegExp {
2840
+ return pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
2841
+ }
2842
+
2843
+ function clamp(value: number, min: number, max: number): number {
2844
+ return Math.min(max, Math.max(min, value));
2845
+ }
2846
+
2847
+ if (import.meta.main) {
2848
+ await main();
2849
+ }