@apifuse/provider-sdk 2.1.0-beta.3 → 2.1.0-beta.4

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 (60) hide show
  1. package/AUTHORING.md +163 -8
  2. package/CHANGELOG.md +8 -1
  3. package/README.md +17 -16
  4. package/SUBMISSION.md +4 -4
  5. package/bin/apifuse-dev.ts +12 -5
  6. package/bin/apifuse-pack-check.ts +9 -2
  7. package/bin/apifuse-pack-smoke.ts +127 -6
  8. package/bin/apifuse-perf.ts +19 -15
  9. package/bin/apifuse-record.ts +41 -53
  10. package/bin/apifuse-submit-check.ts +179 -7
  11. package/bin/apifuse.ts +1 -1
  12. package/package.json +17 -8
  13. package/src/choice-token.ts +164 -0
  14. package/src/cli/commands.ts +1 -3
  15. package/src/cli/create.ts +159 -50
  16. package/src/cli/templates/provider/README.md.tpl +24 -7
  17. package/src/cli/templates/provider/dev.ts.tpl +1 -1
  18. package/src/cli/templates/provider/domain/README.md.tpl +3 -0
  19. package/src/cli/templates/provider/index.ts.tpl +5 -47
  20. package/src/cli/templates/provider/mappers/README.md.tpl +3 -0
  21. package/src/cli/templates/provider/meta.ts.tpl +7 -0
  22. package/src/cli/templates/provider/operations/index.ts.tpl +5 -0
  23. package/src/cli/templates/provider/operations/ping.ts.tpl +23 -0
  24. package/src/cli/templates/provider/schemas/ping.ts.tpl +16 -0
  25. package/src/cli/templates/provider/start.ts.tpl +1 -1
  26. package/src/cli/templates/provider/upstream/README.md.tpl +3 -0
  27. package/src/config/loader.ts +1206 -9
  28. package/src/define.ts +1618 -104
  29. package/src/errors.ts +12 -0
  30. package/src/i18n/catalog.ts +121 -0
  31. package/src/i18n/index.ts +2 -0
  32. package/src/i18n/keys.ts +64 -0
  33. package/src/index.ts +149 -8
  34. package/src/lint.ts +297 -42
  35. package/src/observability.ts +41 -0
  36. package/src/provider.ts +60 -3
  37. package/src/public-schema-field-lint.ts +237 -0
  38. package/src/runtime/auth-flow.ts +7 -0
  39. package/src/runtime/browser.ts +77 -21
  40. package/src/runtime/cache.ts +582 -0
  41. package/src/runtime/executor.ts +13 -1
  42. package/src/runtime/http.ts +939 -195
  43. package/src/runtime/insights.ts +11 -11
  44. package/src/runtime/instrumentation.ts +12 -4
  45. package/src/runtime/key-derivation.ts +1 -1
  46. package/src/runtime/keyring.ts +4 -3
  47. package/src/runtime/proxy-errors.ts +132 -0
  48. package/src/runtime/proxy-telemetry.ts +253 -0
  49. package/src/runtime/request-options.ts +66 -0
  50. package/src/runtime/state.ts +76 -0
  51. package/src/runtime/stealth.ts +1145 -0
  52. package/src/runtime/stt.ts +629 -0
  53. package/src/schema.ts +363 -1
  54. package/src/server/serve.ts +816 -58
  55. package/src/server/types.ts +35 -0
  56. package/src/stream.ts +210 -0
  57. package/src/testing/run.ts +17 -4
  58. package/src/types.ts +869 -50
  59. package/src/runtime/tls.ts +0 -434
  60. package/src/types/playwright-stealth.d.ts +0 -9
@@ -0,0 +1,164 @@
1
+ import {
2
+ createCipheriv,
3
+ createDecipheriv,
4
+ createHash,
5
+ createHmac,
6
+ randomBytes,
7
+ timingSafeEqual,
8
+ } from "node:crypto";
9
+
10
+ export type ProviderChoiceTokenPayload = Record<string, unknown>;
11
+
12
+ export type ProviderChoiceTokenErrorReason =
13
+ | "invalid_shape"
14
+ | "invalid_signature"
15
+ | "invalid_payload"
16
+ | "stale";
17
+
18
+ export class ProviderChoiceTokenError extends Error {
19
+ readonly reason: ProviderChoiceTokenErrorReason;
20
+
21
+ constructor(reason: ProviderChoiceTokenErrorReason, message: string) {
22
+ super(message);
23
+ this.name = "ProviderChoiceTokenError";
24
+ this.reason = reason;
25
+ }
26
+ }
27
+
28
+ export interface CreateProviderChoiceTokenOptions<
29
+ TPayload extends ProviderChoiceTokenPayload,
30
+ > {
31
+ prefix: string;
32
+ payload: TPayload;
33
+ secret: string;
34
+ }
35
+
36
+ export interface ParseProviderChoiceTokenOptions {
37
+ token: string;
38
+ prefix: string;
39
+ secret: string;
40
+ }
41
+
42
+ export interface FreshProviderChoiceIssuedAtOptions {
43
+ ttlMs: number;
44
+ nowMs?: number;
45
+ futureToleranceMs?: number;
46
+ }
47
+
48
+ export function createProviderChoiceToken<
49
+ TPayload extends ProviderChoiceTokenPayload,
50
+ >(options: CreateProviderChoiceTokenOptions<TPayload>): string {
51
+ const iv = randomBytes(12);
52
+ const cipher = createCipheriv(
53
+ "aes-256-gcm",
54
+ choiceEncryptionKey(options.secret),
55
+ iv,
56
+ );
57
+ const encryptedPayload = Buffer.concat([
58
+ cipher.update(JSON.stringify(options.payload), "utf8"),
59
+ cipher.final(),
60
+ ]).toString("base64url");
61
+ const authTag = cipher.getAuthTag().toString("base64url");
62
+ const encodedIv = iv.toString("base64url");
63
+ const signature = signProviderChoiceTokenBody(
64
+ `${options.prefix}.${encodedIv}.${encryptedPayload}.${authTag}`,
65
+ options.secret,
66
+ );
67
+ return `${options.prefix}.${encodedIv}.${encryptedPayload}.${authTag}.${signature}`;
68
+ }
69
+
70
+ export function parseProviderChoiceToken(
71
+ options: ParseProviderChoiceTokenOptions,
72
+ ): ProviderChoiceTokenPayload {
73
+ const [
74
+ actualPrefix,
75
+ encodedIv,
76
+ encryptedPayload,
77
+ authTag,
78
+ signature,
79
+ ...extra
80
+ ] = options.token.split(".");
81
+ if (
82
+ actualPrefix !== options.prefix ||
83
+ !encodedIv ||
84
+ !encryptedPayload ||
85
+ !authTag ||
86
+ !signature ||
87
+ extra.length > 0
88
+ ) {
89
+ throw new ProviderChoiceTokenError(
90
+ "invalid_shape",
91
+ "Provider choice token shape is invalid.",
92
+ );
93
+ }
94
+
95
+ const signedBody = `${options.prefix}.${encodedIv}.${encryptedPayload}.${authTag}`;
96
+ const expectedSignature = signProviderChoiceTokenBody(
97
+ signedBody,
98
+ options.secret,
99
+ );
100
+ const actualBuffer = Buffer.from(signature);
101
+ const expectedBuffer = Buffer.from(expectedSignature);
102
+ if (
103
+ actualBuffer.length !== expectedBuffer.length ||
104
+ !timingSafeEqual(actualBuffer, expectedBuffer)
105
+ ) {
106
+ throw new ProviderChoiceTokenError(
107
+ "invalid_signature",
108
+ "Provider choice token signature is invalid.",
109
+ );
110
+ }
111
+
112
+ try {
113
+ const decipher = createDecipheriv(
114
+ "aes-256-gcm",
115
+ choiceEncryptionKey(options.secret),
116
+ Buffer.from(encodedIv, "base64url"),
117
+ );
118
+ decipher.setAuthTag(Buffer.from(authTag, "base64url"));
119
+ const decrypted = Buffer.concat([
120
+ decipher.update(Buffer.from(encryptedPayload, "base64url")),
121
+ decipher.final(),
122
+ ]).toString("utf8");
123
+ const parsed = JSON.parse(decrypted);
124
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
125
+ throw new Error("payload is not an object");
126
+ }
127
+ return Object.fromEntries(Object.entries(parsed));
128
+ } catch {
129
+ throw new ProviderChoiceTokenError(
130
+ "invalid_payload",
131
+ "Provider choice token payload is invalid.",
132
+ );
133
+ }
134
+ }
135
+
136
+ export function assertFreshProviderChoiceIssuedAt(
137
+ issuedAtMs: unknown,
138
+ options: FreshProviderChoiceIssuedAtOptions,
139
+ ): number {
140
+ const parsed =
141
+ typeof issuedAtMs === "number" ? issuedAtMs : Number(issuedAtMs);
142
+ const nowMs = options.nowMs ?? Date.now();
143
+ const futureToleranceMs = options.futureToleranceMs ?? 30_000;
144
+ if (
145
+ !Number.isFinite(parsed) ||
146
+ parsed <= 0 ||
147
+ nowMs - parsed > options.ttlMs ||
148
+ parsed - nowMs > futureToleranceMs
149
+ ) {
150
+ throw new ProviderChoiceTokenError(
151
+ "stale",
152
+ "Provider choice token is stale.",
153
+ );
154
+ }
155
+ return parsed;
156
+ }
157
+
158
+ function choiceEncryptionKey(secret: string): Buffer {
159
+ return createHash("sha256").update(secret).digest();
160
+ }
161
+
162
+ function signProviderChoiceTokenBody(body: string, secret: string): string {
163
+ return createHmac("sha256", secret).update(body).digest("base64url");
164
+ }
@@ -24,11 +24,9 @@ export const COMMAND_MANIFEST: Record<
24
24
  name: "create",
25
25
  summary:
26
26
  "Scaffold a provider, install dependencies, run baseline validation, and print the next local-dev command.",
27
- usage:
28
- "apifuse create <provider-name> [--preset standalone|monorepo] [--json] [--dry-run]",
27
+ usage: "apifuse create <provider-name> [--json] [--dry-run]",
29
28
  examples: [
30
29
  "apifuse create weather-provider",
31
- "apifuse create weather-provider --preset monorepo",
32
30
  "apifuse create --config ./apifuse.create.json --json",
33
31
  ],
34
32
  modulePath: "./apifuse-create",
package/src/cli/create.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, relative, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -101,11 +101,9 @@ const TEMPLATE_DIR = fileURLToPath(
101
101
  const HELP_TEXT = `Usage: apifuse create <provider-name> [options]
102
102
  Examples:
103
103
  apifuse create my-provider
104
- apifuse create my-provider --preset monorepo
105
104
  apifuse create --config ./apifuse.create.json --json
106
105
 
107
106
  Options:
108
- --preset <standalone|monorepo>
109
107
  --config <path>
110
108
  --output-dir <path>
111
109
  --display-name <name>
@@ -115,7 +113,7 @@ Options:
115
113
  --yes
116
114
  --dry-run
117
115
  --json
118
- --sdk-specifier <specifier> # internal/testing override for standalone dependency resolution
116
+ --sdk-specifier <specifier> # internal/testing override for dependency resolution
119
117
  --help, -h`;
120
118
 
121
119
  export async function main() {
@@ -273,14 +271,11 @@ async function resolveCreateOptions(
273
271
  config: CreateConfigFile | undefined,
274
272
  cwd: string,
275
273
  ): Promise<CreateResolvedOptions> {
276
- const detectedWorkspaceRoot = findWorkspaceRoot(cwd);
277
- const detectedPreset: CreatePreset = detectedWorkspaceRoot
278
- ? "monorepo"
279
- : "standalone";
274
+ const internalWorkspaceRoot = findApifuseInternalWorkspaceRoot(cwd);
280
275
 
281
276
  const partial: Partial<CreateResolvedOptions> = {
282
277
  name: parsed.name ?? config?.name,
283
- preset: parsed.preset ?? config?.preset ?? detectedPreset,
278
+ preset: parsed.preset ?? config?.preset ?? "standalone",
284
279
  outputDir: parsed.outputDir ?? config?.outputDir,
285
280
  displayName: parsed.displayName ?? config?.displayName,
286
281
  category: parsed.category ?? config?.category,
@@ -289,15 +284,15 @@ async function resolveCreateOptions(
289
284
  sdkSpecifier:
290
285
  parsed.sdkSpecifier ??
291
286
  config?.sdkSpecifier ??
292
- process.env.APIFUSE_SDK_SPECIFIER,
287
+ process.env.APIFUSE__SDK__SPECIFIER,
293
288
  dryRun: parsed.dryRun,
294
289
  json: parsed.json,
295
290
  yes: parsed.yes,
296
291
  };
297
292
 
298
- if (partial.preset === "monorepo" && !detectedWorkspaceRoot) {
293
+ if (partial.preset === "monorepo" && !internalWorkspaceRoot) {
299
294
  throw new Error(
300
- "Monorepo preset requires a workspace root with a providers/ directory.",
295
+ "Monorepo preset is internal to the APIFuse repository. External bounty workspaces are one-provider repositories; use the standalone default create flow.",
301
296
  );
302
297
  }
303
298
 
@@ -314,7 +309,7 @@ async function resolveCreateOptions(
314
309
  category: partial.category ?? "other",
315
310
  authMode: partial.authMode ?? "none",
316
311
  runtime: partial.runtime ?? "standard",
317
- preset: partial.preset ?? detectedPreset,
312
+ preset: partial.preset ?? "standalone",
318
313
  outputDir: partial.outputDir,
319
314
  dryRun: partial.dryRun ?? false,
320
315
  json: partial.json ?? false,
@@ -324,10 +319,10 @@ async function resolveCreateOptions(
324
319
  }
325
320
 
326
321
  if (!partial.json) {
327
- intro("Create a new ApiFuse provider");
322
+ intro("Create a new APIFuse provider");
328
323
  note(
329
- `Preset precedence: explicit flags > config file > workspace detection > standalone default\nDetected workspace preset: ${detectedPreset}`,
330
- "Preset resolution",
324
+ "External bounty workspaces are one-provider repositories. The public create flow defaults to standalone.",
325
+ "Provider workspace",
331
326
  );
332
327
  }
333
328
 
@@ -392,22 +387,7 @@ async function resolveCreateOptions(
392
387
  initialValue: "standard",
393
388
  }),
394
389
  )),
395
- preset:
396
- partial.preset ??
397
- (await promptValue(
398
- select({
399
- message: "Generation preset",
400
- options: PRESET_OPTIONS.map((value) => ({
401
- label: value,
402
- value,
403
- hint:
404
- value === "standalone"
405
- ? "Create a clean-room npm-ready provider package."
406
- : "Create the provider inside the current ApiFuse monorepo.",
407
- })),
408
- initialValue: detectedPreset,
409
- }),
410
- )),
390
+ preset: partial.preset ?? "standalone",
411
391
  outputDir: partial.outputDir,
412
392
  dryRun: partial.dryRun ?? false,
413
393
  json: partial.json ?? false,
@@ -429,15 +409,15 @@ export async function buildProviderCreatePlan(
429
409
  options: CreateResolvedOptions,
430
410
  cwd: string,
431
411
  ): Promise<ProviderCreatePlan> {
432
- const workspaceRoot =
433
- options.preset === "monorepo" ? findWorkspaceRoot(cwd) : undefined;
434
- if (options.preset === "monorepo" && !workspaceRoot) {
412
+ const resolvedWorkspaceRoot =
413
+ options.preset === "monorepo"
414
+ ? findApifuseInternalWorkspaceRoot(cwd)
415
+ : undefined;
416
+ if (options.preset === "monorepo" && !resolvedWorkspaceRoot) {
435
417
  throw new Error(
436
- "Monorepo preset requires a workspace root with a providers/ directory.",
418
+ "Monorepo preset is internal to the APIFuse repository. External bounty workspaces are one-provider repositories; use the standalone default create flow.",
437
419
  );
438
420
  }
439
- const resolvedWorkspaceRoot =
440
- options.preset === "monorepo" ? workspaceRoot : undefined;
441
421
  let providerRoot: string;
442
422
  let installCwd: string;
443
423
 
@@ -459,33 +439,87 @@ export async function buildProviderCreatePlan(
459
439
  throw new Error(`Target directory already exists: ${providerRoot}`);
460
440
  }
461
441
 
442
+ if (
443
+ options.sdkSpecifier?.startsWith("workspace:") &&
444
+ !resolvedWorkspaceRoot
445
+ ) {
446
+ throw new Error(
447
+ "workspace:* is only valid inside the APIFuse monorepo because public Provider SDK scaffolds must install from npm or an explicit tarball/file specifier.",
448
+ );
449
+ }
450
+
462
451
  const sdkSpecifier =
463
452
  options.sdkSpecifier ??
464
- (options.preset === "monorepo" ? "workspace:*" : `^${packageJson.version}`);
453
+ (options.preset === "monorepo" && resolvedWorkspaceRoot
454
+ ? "workspace:*"
455
+ : `^${packageJson.version}`);
465
456
  const relativeProviderRoot = relative(cwd, providerRoot) || options.name;
466
457
  const nextDevCommand = `cd ${relativeProviderRoot} && bun run dev`;
467
458
  const packageName =
468
459
  options.preset === "monorepo"
469
460
  ? `@apifuse/provider-${options.name}`
470
461
  : `apifuse-provider-${options.name}`;
462
+ const templateValues = {
463
+ PROVIDER_ID: options.name,
464
+ DISPLAY_NAME: escapeTemplate(options.displayName),
465
+ CATEGORY: options.category,
466
+ RUNTIME: options.runtime,
467
+ BROWSER_BLOCK:
468
+ options.runtime === "browser"
469
+ ? ',\n browser: {\n engine: "playwright-stealth",\n }'
470
+ : "",
471
+ SECRETS_BLOCK: renderSecretsBlock(options.authMode),
472
+ CREDENTIAL_BLOCK: renderCredentialBlock(options.authMode),
473
+ AUTH_BLOCK: renderAuthBlock(options.authMode),
474
+ };
471
475
 
472
476
  const files: ProviderPlanFile[] = [
473
477
  {
474
478
  path: resolve(providerRoot, "index.ts"),
475
- content: await renderTemplate("index.ts.tpl", {
479
+ content: await renderTemplate("index.ts.tpl", templateValues),
480
+ },
481
+ {
482
+ path: resolve(providerRoot, "meta.ts"),
483
+ content: await renderTemplate("meta.ts.tpl", {
476
484
  PROVIDER_ID: options.name,
477
485
  DISPLAY_NAME: escapeTemplate(options.displayName),
478
486
  CATEGORY: options.category,
479
- RUNTIME: options.runtime,
480
- BROWSER_BLOCK:
481
- options.runtime === "browser"
482
- ? ',\n browser: {\n engine: "playwright-stealth",\n }'
483
- : "",
484
- SECRETS_BLOCK: renderSecretsBlock(options.authMode),
485
- CREDENTIAL_BLOCK: renderCredentialBlock(options.authMode),
486
- AUTH_BLOCK: renderAuthBlock(options.authMode),
487
487
  }),
488
488
  },
489
+ {
490
+ path: resolve(providerRoot, "operations", "index.ts"),
491
+ content: await renderTemplate("operations/index.ts.tpl", {}),
492
+ },
493
+ {
494
+ path: resolve(providerRoot, "operations", "ping.ts"),
495
+ content: await renderTemplate("operations/ping.ts.tpl", {
496
+ DISPLAY_NAME: escapeTemplate(options.displayName),
497
+ }),
498
+ },
499
+ {
500
+ path: resolve(providerRoot, "schemas", "ping.ts"),
501
+ content: await renderTemplate("schemas/ping.ts.tpl", {}),
502
+ },
503
+ {
504
+ path: resolve(providerRoot, "upstream", "README.md"),
505
+ content: await renderTemplate("upstream/README.md.tpl", {}),
506
+ },
507
+ {
508
+ path: resolve(providerRoot, "mappers", "README.md"),
509
+ content: await renderTemplate("mappers/README.md.tpl", {}),
510
+ },
511
+ {
512
+ path: resolve(providerRoot, "domain", "README.md"),
513
+ content: await renderTemplate("domain/README.md.tpl", {}),
514
+ },
515
+ {
516
+ path: resolve(providerRoot, "locales", "en.json"),
517
+ content: renderStarterLocaleCatalog(options.displayName, "en"),
518
+ },
519
+ {
520
+ path: resolve(providerRoot, "locales", "ko.json"),
521
+ content: renderStarterLocaleCatalog(options.displayName, "ko"),
522
+ },
489
523
  {
490
524
  path: resolve(providerRoot, "package.json"),
491
525
  content: renderPackageJson({
@@ -611,6 +645,56 @@ function renderTsconfig(): string {
611
645
  )}\n`;
612
646
  }
613
647
 
648
+ function renderStarterLocaleCatalog(
649
+ displayName: string,
650
+ locale: "en" | "ko",
651
+ ): string {
652
+ const catalog = {
653
+ meta: {
654
+ displayName,
655
+ description:
656
+ locale === "ko"
657
+ ? `${displayName} APIFuse 커뮤니티 기여용 provider starter입니다.`
658
+ : `${displayName} provider starter for APIFuse community contributions.`,
659
+ },
660
+ operations: {
661
+ ping: {
662
+ description:
663
+ locale === "ko"
664
+ ? "생성된 provider wiring이 APIFuse runtime contract를 통해 작은 샘플 payload를 정상적으로 round-trip하는지 확인합니다. 로컬 개발, baseline check, 첫 bounty scaffold 검증에 사용합니다. production data retrieval이나 upstream-specific workflow에는 사용하지 마세요. 이 starter operation은 생성된 프로젝트가 compile, serve, input/output round-trip을 수행하는지 증명하기 위한 용도입니다."
665
+ : "Confirms the generated provider wiring is operational by echoing a small sample payload through the APIFuse runtime contract. Use when validating local development, baseline checks, or first-pass bounty scaffolds. Do NOT use for production data retrieval or upstream-specific workflows because this starter operation exists only to prove the generated project compiles, serves, and round-trips input/output correctly.",
666
+ },
667
+ },
668
+ schemaDescriptions: {
669
+ input: {
670
+ root:
671
+ locale === "ko"
672
+ ? "생성된 ping operation의 입력 payload"
673
+ : "Input payload for the generated ping operation.",
674
+ value:
675
+ locale === "ko"
676
+ ? "생성된 provider scaffold wiring 검증에 사용하는 샘플 입력값"
677
+ : "Sample input value used to verify the generated provider scaffold is wired correctly.",
678
+ },
679
+ output: {
680
+ root:
681
+ locale === "ko"
682
+ ? "생성된 ping operation이 반환하는 출력 payload"
683
+ : "Output payload returned by the generated ping operation.",
684
+ ok:
685
+ locale === "ko"
686
+ ? "생성된 provider가 샘플 요청을 성공적으로 처리했는지 여부"
687
+ : "Whether the generated provider handled the sample request successfully.",
688
+ message:
689
+ locale === "ko"
690
+ ? "생성된 provider가 샘플 payload를 round-trip했음을 보여주는 사람이 읽을 수 있는 확인 메시지"
691
+ : "Human-readable confirmation that the generated provider round-tripped the sample payload.",
692
+ },
693
+ },
694
+ };
695
+ return `${JSON.stringify(catalog, null, 2)}\n`;
696
+ }
697
+
614
698
  function renderAuthBlock(authMode: CreateAuthMode): string {
615
699
  switch (authMode) {
616
700
  case "none":
@@ -719,11 +803,11 @@ export function toDisplayName(name: string): string {
719
803
  .join(" ");
720
804
  }
721
805
 
722
- function findWorkspaceRoot(cwd: string): string | undefined {
806
+ function findApifuseInternalWorkspaceRoot(cwd: string): string | undefined {
723
807
  let currentDirectory = cwd;
724
808
 
725
809
  while (true) {
726
- if (existsSync(resolve(currentDirectory, "providers"))) {
810
+ if (isApifuseInternalWorkspaceRoot(currentDirectory)) {
727
811
  return currentDirectory;
728
812
  }
729
813
 
@@ -736,6 +820,31 @@ function findWorkspaceRoot(cwd: string): string | undefined {
736
820
  }
737
821
  }
738
822
 
823
+ function isApifuseInternalWorkspaceRoot(workspaceRoot: string): boolean {
824
+ const providerSdkPackageJsonPath = resolve(
825
+ workspaceRoot,
826
+ "packages",
827
+ "provider-sdk",
828
+ "package.json",
829
+ );
830
+ if (!existsSync(providerSdkPackageJsonPath)) {
831
+ return false;
832
+ }
833
+ try {
834
+ const packageJson = JSON.parse(
835
+ readFileSync(providerSdkPackageJsonPath, "utf8"),
836
+ );
837
+ return (
838
+ typeof packageJson === "object" &&
839
+ packageJson !== null &&
840
+ "name" in packageJson &&
841
+ packageJson.name === "@apifuse/provider-sdk"
842
+ );
843
+ } catch {
844
+ return false;
845
+ }
846
+ }
847
+
739
848
  async function writePlan(plan: ProviderCreatePlan): Promise<void> {
740
849
  for (const file of plan.files) {
741
850
  await mkdir(dirname(file.path), { recursive: true });
@@ -12,6 +12,23 @@ bun run submit-check
12
12
  ```
13
13
 
14
14
 
15
+ ## Module layout
16
+
17
+ The generated provider uses the recommended split layout:
18
+
19
+ ```text
20
+ index.ts # composition root: defineProvider() and wiring only
21
+ meta.ts # provider metadata
22
+ operations/ # APIFuse operation contracts and handlers
23
+ schemas/ # public input/output schemas near operations
24
+ upstream/ # upstream ceremony: clients, auth, request builders
25
+ mappers/ # upstream-to-APIFuse normalization helpers
26
+ domain/ # shared provider-specific business ceremony
27
+ ```
28
+
29
+ Small providers may stay in one file, but larger providers are easier to
30
+ review when `index.ts` remains a short composition root.
31
+
15
32
  ## Pre-submission report
16
33
 
17
34
  Before posting bounty evidence, run:
@@ -93,18 +110,18 @@ Structured errors return an `error` object with `code`, `message`,
93
110
  `connection.secrets`, and read them with `ctx.credential`.
94
111
  - Auth flow: call `/auth/start`, then `/auth/continue` with the same `flowId`;
95
112
  carry returned `contextPatch` values into the next request's `context`.
96
- - TLS/browser runtime: if Bun blocks native dependency lifecycle scripts, run
97
- `bun pm untrusted` and trust SDK dependencies such as `koffi` before debugging
98
- `ctx.tls`; for TypeScript browser Providers use
99
- `browser.engine: "playwright-stealth"` (`nodriver` is Python-runtime only),
100
- then install local Chromium with `bunx playwright install chromium` or set
101
- `CDP_POOL_URL`.
113
+ - Stealth/browser runtime: keep access-sensitive operations on `ctx.stealth.fetch()` with an
114
+ SDK stealth `profile`; the TypeScript stealth runtime uses `impit` internally.
115
+ `ctx.stealth` supports Chrome/Firefox-style profiles. For TypeScript browser
116
+ Providers or Safari-specific behavior use `browser.engine: "playwright-stealth"`
117
+ (`nodriver` is Python-runtime only), then install local Chromium with
118
+ `bunx playwright install chromium` or set `APIFUSE__CDP_POOL__URL`.
102
119
 
103
120
  ## Next steps
104
121
 
105
122
  1. Replace the sample `ping` operation with real upstream logic.
106
123
  2. Once the real operation declares `upstream.baseUrl` and uses `ctx.http` or
107
- `ctx.tls`, record a fixture with:
124
+ `ctx.stealth`, record a fixture with:
108
125
  `bun run record -- --operation <operation> --params '<json-input>'`.
109
126
  3. Replace the starter `healthCheckUnsupported` with a real `healthCheck` for read-only upstream operations when safe.
110
127
  4. Extend tests and operation metadata until the provider is bounty-ready.
@@ -2,4 +2,4 @@ import { startDevServer } from "@apifuse/provider-sdk";
2
2
 
3
3
  import provider from "./index";
4
4
 
5
- startDevServer(provider, { port: Number(process.env.PORT) || 3900 });
5
+ startDevServer(provider, { port: Number(process.env.APIFUSE__RUNTIME__PORT) || 3900 });
@@ -0,0 +1,3 @@
1
+ # Domain
2
+
3
+ Put provider-specific business ceremony here when it is shared across operations and too complex to live inside one operation module.
@@ -1,23 +1,7 @@
1
- import { defineProvider, z } from "@apifuse/provider-sdk";
1
+ import { defineProvider } from "@apifuse/provider-sdk/provider";
2
2
 
3
- const InputSchema = z
4
- .object({
5
- value: z
6
- .string()
7
- .describe("Sample input value used to verify the generated provider scaffold is wired correctly."),
8
- })
9
- .describe("Input payload for the generated ping operation.");
10
-
11
- const OutputSchema = z
12
- .object({
13
- ok: z
14
- .boolean()
15
- .describe("Whether the generated provider handled the sample request successfully."),
16
- message: z
17
- .string()
18
- .describe("Human-readable confirmation that the generated provider round-tripped the sample payload."),
19
- })
20
- .describe("Output payload returned by the generated ping operation.");
3
+ import { providerMeta } from "./meta";
4
+ import { operations } from "./operations";
21
5
 
22
6
  export default defineProvider({
23
7
  id: "{{PROVIDER_ID}}",
@@ -26,32 +10,6 @@ export default defineProvider({
26
10
  allowedHosts: ["api.example.com"],
27
11
  reviewed: "community",
28
12
  {{SECRETS_BLOCK}}{{CREDENTIAL_BLOCK}}auth: {{AUTH_BLOCK}},
29
- meta: {
30
- displayName: "{{DISPLAY_NAME}}",
31
- description: "{{DISPLAY_NAME}} provider starter for ApiFuse community contributions.",
32
- category: "{{CATEGORY}}",
33
- tags: ["{{PROVIDER_ID}}", "starter", "community"],
34
- },
35
- operations: {
36
- ping: {
37
- description:
38
- "Confirms the generated provider wiring is operational by echoing a small sample payload through the ApiFuse runtime contract. Use when validating local development, baseline checks, or first-pass bounty scaffolds. Do NOT use for production data retrieval or upstream-specific workflows because this starter operation exists only to prove the generated project compiles, serves, and round-trips input/output correctly. Returns a success flag plus a message containing the supplied value.",
39
- input: InputSchema,
40
- output: OutputSchema,
41
- handler: async (_ctx, input) => {
42
- return {
43
- ok: true,
44
- message: "{{DISPLAY_NAME}} received: " + input.value,
45
- };
46
- },
47
- fixtures: {
48
- request: { value: "hello" },
49
- response: { ok: true, message: "{{DISPLAY_NAME}} received: hello" },
50
- },
51
- healthCheckUnsupported: {
52
- reason:
53
- "Generated local-only scaffold operation. Replace this with a real healthCheck for upstream-backed bounty operations when safe; keep healthCheckUnsupported only for destructive, paid, credential-sensitive, or otherwise unprobeable operations with a specific rationale.",
54
- },
55
- },
56
- },
13
+ meta: providerMeta,
14
+ operations: operations,
57
15
  });
@@ -0,0 +1,3 @@
1
+ # Mappers
2
+
3
+ Put normalization helpers here when upstream responses need to become public APIFuse operation outputs.
@@ -0,0 +1,7 @@
1
+ export const providerMeta = {
2
+ displayName: "{{PROVIDER_ID}}",
3
+ displayNameKey: "meta.displayName",
4
+ descriptionKey: "meta.description",
5
+ category: "{{CATEGORY}}",
6
+ tags: ["{{PROVIDER_ID}}", "starter", "community"],
7
+ } as const;
@@ -0,0 +1,5 @@
1
+ import { pingOperation } from "./ping";
2
+
3
+ export const operations = {
4
+ ping: pingOperation,
5
+ };
@@ -0,0 +1,23 @@
1
+ import { defineOperation } from "@apifuse/provider-sdk/provider";
2
+
3
+ import { pingInputSchema, pingOutputSchema } from "../schemas/ping";
4
+
5
+ export const pingOperation = defineOperation({
6
+ descriptionKey: "operations.ping.description",
7
+ input: pingInputSchema,
8
+ output: pingOutputSchema,
9
+ handler: async (_ctx, input) => {
10
+ return {
11
+ ok: true,
12
+ message: "{{DISPLAY_NAME}} received: " + input.value,
13
+ };
14
+ },
15
+ fixtures: {
16
+ request: { value: "hello" },
17
+ response: { ok: true, message: "{{DISPLAY_NAME}} received: hello" },
18
+ },
19
+ healthCheckUnsupported: {
20
+ reason:
21
+ "Generated local-only scaffold operation. Replace this with a real healthCheck for upstream-backed bounty operations when safe; keep healthCheckUnsupported only for destructive, paid, credential-sensitive, or otherwise unprobeable operations with a specific rationale.",
22
+ },
23
+ });