@coswic/aipay 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-guide.d.ts +18 -0
  3. package/dist/agent-guide.js +60 -0
  4. package/dist/args.d.ts +15 -0
  5. package/dist/args.js +47 -0
  6. package/dist/auth-store.d.ts +47 -0
  7. package/dist/auth-store.js +176 -0
  8. package/dist/bin.d.ts +2 -0
  9. package/dist/bin.js +8 -0
  10. package/dist/browser.d.ts +1 -0
  11. package/dist/browser.js +18 -0
  12. package/dist/commands/apps.d.ts +15 -0
  13. package/dist/commands/apps.js +53 -0
  14. package/dist/commands/doctor.d.ts +17 -0
  15. package/dist/commands/doctor.js +153 -0
  16. package/dist/commands/init.d.ts +18 -0
  17. package/dist/commands/init.js +269 -0
  18. package/dist/commands/login.d.ts +34 -0
  19. package/dist/commands/login.js +189 -0
  20. package/dist/commands/session.d.ts +6 -0
  21. package/dist/commands/session.js +63 -0
  22. package/dist/commands/status.d.ts +3 -0
  23. package/dist/commands/status.js +24 -0
  24. package/dist/commands/test.d.ts +12 -0
  25. package/dist/commands/test.js +162 -0
  26. package/dist/commands/unlink.d.ts +5 -0
  27. package/dist/commands/unlink.js +73 -0
  28. package/dist/detect.d.ts +27 -0
  29. package/dist/detect.js +83 -0
  30. package/dist/developer-api.d.ts +14 -0
  31. package/dist/developer-api.js +74 -0
  32. package/dist/device.d.ts +38 -0
  33. package/dist/device.js +122 -0
  34. package/dist/gate.d.ts +13 -0
  35. package/dist/gate.js +29 -0
  36. package/dist/index.d.ts +22 -0
  37. package/dist/index.js +22 -0
  38. package/dist/loopback.d.ts +37 -0
  39. package/dist/loopback.js +95 -0
  40. package/dist/main.d.ts +5 -0
  41. package/dist/main.js +91 -0
  42. package/dist/output.d.ts +36 -0
  43. package/dist/output.js +52 -0
  44. package/dist/project.d.ts +61 -0
  45. package/dist/project.js +127 -0
  46. package/dist/remote.d.ts +21 -0
  47. package/dist/remote.js +41 -0
  48. package/dist/setup-events.d.ts +3 -0
  49. package/dist/setup-events.js +28 -0
  50. package/dist/templates.d.ts +24 -0
  51. package/dist/templates.js +333 -0
  52. package/dist/version.d.ts +1 -0
  53. package/dist/version.js +10 -0
  54. package/package.json +1 -1
@@ -0,0 +1,22 @@
1
+ /** Programmatic surface (used by tests and by anyone embedding the commands). */
2
+ export { AGENT_GUIDE_FILE, agentGuide } from './agent-guide.js';
3
+ export { type ParsedArgs, parseArgs } from './args.js';
4
+ export { configDir, createAuthStore, fileStore, type StoredAuth } from './auth-store.js';
5
+ export { createApp, runApps } from './commands/apps.js';
6
+ export { collectChecks, runDoctor } from './commands/doctor.js';
7
+ export { DEFAULT_CALLBACK, runInit, SDK_PACKAGE } from './commands/init.js';
8
+ export { fetchCliConfig, managementAuthorizeUrl, resolveApiBase, runLogin, } from './commands/login.js';
9
+ export { runLogout, runWhoami } from './commands/session.js';
10
+ export { runStatus } from './commands/status.js';
11
+ export { formatUusd, pickModel, runTest } from './commands/test.js';
12
+ export { runUnlink, stripEnvKeys } from './commands/unlink.js';
13
+ export { detectFramework, detectPackageManager, detectProject, installCommand } from './detect.js';
14
+ export { openDeveloperApi } from './developer-api.js';
15
+ export { GATE_ENV, gatedFetch, gateHeaders, looksGated } from './gate.js';
16
+ export { parseCallback, startLoopback } from './loopback.js';
17
+ export { main } from './main.js';
18
+ export { CliError, createReporter, EXIT, type Reporter } from './output.js';
19
+ export { ENV_KEYS, isProjectConfig, mergeEnvFile, mergeGitignore, type ProjectConfig, readProject, writeProject, } from './project.js';
20
+ export { createRemote, docsUrl, type Remote } from './remote.js';
21
+ export { scaffoldFiles, startPathFor } from './templates.js';
22
+ export { cliVersion } from './version.js';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ /** Programmatic surface (used by tests and by anyone embedding the commands). */
2
+ export { AGENT_GUIDE_FILE, agentGuide } from './agent-guide.js';
3
+ export { parseArgs } from './args.js';
4
+ export { configDir, createAuthStore, fileStore } from './auth-store.js';
5
+ export { createApp, runApps } from './commands/apps.js';
6
+ export { collectChecks, runDoctor } from './commands/doctor.js';
7
+ export { DEFAULT_CALLBACK, runInit, SDK_PACKAGE } from './commands/init.js';
8
+ export { fetchCliConfig, managementAuthorizeUrl, resolveApiBase, runLogin, } from './commands/login.js';
9
+ export { runLogout, runWhoami } from './commands/session.js';
10
+ export { runStatus } from './commands/status.js';
11
+ export { formatUusd, pickModel, runTest } from './commands/test.js';
12
+ export { runUnlink, stripEnvKeys } from './commands/unlink.js';
13
+ export { detectFramework, detectPackageManager, detectProject, installCommand } from './detect.js';
14
+ export { openDeveloperApi } from './developer-api.js';
15
+ export { GATE_ENV, gatedFetch, gateHeaders, looksGated } from './gate.js';
16
+ export { parseCallback, startLoopback } from './loopback.js';
17
+ export { main } from './main.js';
18
+ export { CliError, createReporter, EXIT } from './output.js';
19
+ export { ENV_KEYS, isProjectConfig, mergeEnvFile, mergeGitignore, readProject, writeProject, } from './project.js';
20
+ export { createRemote, docsUrl } from './remote.js';
21
+ export { scaffoldFiles, startPathFor } from './templates.js';
22
+ export { cliVersion } from './version.js';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Loopback redirect receiver (RFC 8252 §7.3) for `aipay test`: listens on the exact
3
+ * registered callback URI (host + port + path), captures ONE redirect, answers the
4
+ * browser with a small HTML page, then closes. The authorization code never touches
5
+ * disk; the token exchange happens in the caller's memory.
6
+ */
7
+ import { type Server } from 'node:http';
8
+ export interface LoopbackTarget {
9
+ host: string;
10
+ port: number;
11
+ path: string;
12
+ }
13
+ /**
14
+ * Hydra compares loopback redirect URIs per RFC 8252 §7.3: for 127.0.0.1 / [::1] the port
15
+ * is ignored, so the CLI may receive the callback on any free port while the app keeps
16
+ * its registered URI. `localhost` is NOT treated as loopback by the server — exact port.
17
+ */
18
+ export declare function portIsVariable(target: LoopbackTarget): boolean;
19
+ /** The redirect_uri to send for a receiver bound to `port` (same host + path). */
20
+ export declare function redirectUriFor(target: LoopbackTarget, port: number): string;
21
+ export declare function parseCallback(callback: string): LoopbackTarget;
22
+ export interface LoopbackResult {
23
+ /** Full callback URL as received (query included) — hand it to the SDK's handleCallback. */
24
+ url: string;
25
+ }
26
+ export interface LoopbackHandle {
27
+ /** Resolves with the first request on the callback path; rejects on timeout. */
28
+ waitForCallback: Promise<LoopbackResult>;
29
+ close(): Promise<void>;
30
+ server: Server;
31
+ /** Port actually bound (differs from target.port when target.port is 0 = ephemeral). */
32
+ port: number;
33
+ }
34
+ export declare function startLoopback(target: LoopbackTarget, opts?: {
35
+ timeoutMs?: number;
36
+ pageHtml?: (ok: boolean) => string;
37
+ }): Promise<LoopbackHandle>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Loopback redirect receiver (RFC 8252 §7.3) for `aipay test`: listens on the exact
3
+ * registered callback URI (host + port + path), captures ONE redirect, answers the
4
+ * browser with a small HTML page, then closes. The authorization code never touches
5
+ * disk; the token exchange happens in the caller's memory.
6
+ */
7
+ import { createServer } from 'node:http';
8
+ /**
9
+ * Hydra compares loopback redirect URIs per RFC 8252 §7.3: for 127.0.0.1 / [::1] the port
10
+ * is ignored, so the CLI may receive the callback on any free port while the app keeps
11
+ * its registered URI. `localhost` is NOT treated as loopback by the server — exact port.
12
+ */
13
+ export function portIsVariable(target) {
14
+ return target.host === '127.0.0.1' || target.host === '::1';
15
+ }
16
+ /** The redirect_uri to send for a receiver bound to `port` (same host + path). */
17
+ export function redirectUriFor(target, port) {
18
+ const host = target.host === '::1' ? '[::1]' : target.host;
19
+ return `http://${host}:${port}${target.path}`;
20
+ }
21
+ export function parseCallback(callback) {
22
+ const u = new URL(callback);
23
+ if (u.protocol !== 'http:')
24
+ throw new Error(`callback must be http:// on a loopback host (got ${callback})`);
25
+ const host = u.hostname;
26
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '[::1]' && host !== '::1')
27
+ throw new Error(`callback host must be a loopback address (got ${host})`);
28
+ const port = u.port ? Number(u.port) : 80;
29
+ return { host: host === '[::1]' ? '::1' : host, port, path: u.pathname || '/' };
30
+ }
31
+ export function startLoopback(target, opts = {}) {
32
+ const timeoutMs = opts.timeoutMs ?? 5 * 60_000;
33
+ const page = opts.pageHtml ?? defaultPage;
34
+ return new Promise((resolve, reject) => {
35
+ let settle = null;
36
+ let fail = null;
37
+ const waitForCallback = new Promise((res, rej) => {
38
+ settle = res;
39
+ fail = rej;
40
+ });
41
+ const server = createServer((req, res) => {
42
+ const addr = server.address();
43
+ const boundPort = typeof addr === 'object' && addr ? addr.port : target.port;
44
+ const url = new URL(req.url ?? '/', redirectUriFor(target, boundPort));
45
+ if (url.pathname !== target.path) {
46
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
47
+ res.end('not the callback path');
48
+ return;
49
+ }
50
+ const ok = !url.searchParams.get('error');
51
+ res.writeHead(200, {
52
+ 'content-type': 'text/html; charset=utf-8',
53
+ 'cache-control': 'no-store',
54
+ 'referrer-policy': 'no-referrer',
55
+ });
56
+ res.end(page(ok));
57
+ settle?.({ url: url.toString() });
58
+ settle = null;
59
+ });
60
+ const timer = setTimeout(() => {
61
+ fail?.(new Error(`no callback received within ${Math.round(timeoutMs / 1000)}s`));
62
+ fail = null;
63
+ }, timeoutMs);
64
+ server.on('error', (err) => {
65
+ clearTimeout(timer);
66
+ reject(err);
67
+ });
68
+ server.listen(target.port, target.host, () => {
69
+ const addr = server.address();
70
+ const port = typeof addr === 'object' && addr ? addr.port : target.port;
71
+ resolve({
72
+ waitForCallback,
73
+ server,
74
+ port,
75
+ close: () => new Promise((done) => {
76
+ clearTimeout(timer);
77
+ server.close(() => done());
78
+ // Keep-alive connections would otherwise hold the process open.
79
+ server.closeAllConnections?.();
80
+ }),
81
+ });
82
+ });
83
+ });
84
+ }
85
+ function defaultPage(ok) {
86
+ const title = ok ? 'AI-Pay: signed in' : 'AI-Pay: authorization failed';
87
+ const body = ok
88
+ ? 'You can close this tab and return to the terminal.'
89
+ : 'The terminal shows the error. You can close this tab.';
90
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>
91
+ <style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;background:#f6f7f9;color:#1b1f24}
92
+ main{padding:32px 40px;border-radius:12px;background:#fff;box-shadow:0 2px 12px rgba(0,0,0,.08);text-align:center}
93
+ h1{font-size:20px;margin:0 0 8px}</style></head>
94
+ <body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;
95
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare const HELP = "aipay \u2014 AI-Pay CLI\n\nUsage\n aipay login [--api <base>] [--device] [--json] developer sign-in for the CLI itself\n aipay whoami [--json] \u00B7 aipay logout [--json]\n aipay apps list [--json]\n aipay apps create --name <name> [--callback <url>] [--json]\n aipay init --app <client_id> [--auth <origin>] [--api <base>] [--callback <url>] [--name <app name>]\n [--framework next|express|fastify|hono|vite|node] override detection\n [--dir <path>] [--dry-run] [--no-install] [--json]\n aipay init --create <app name> [--api <base>] ... create the app (needs login) and link it\n aipay test [--model <id>] [--port <n>] [--no-open] [--timeout <seconds>] [--dir <path>] [--json]\n aipay doctor [--offline] [--dir <path>] [--json]\n aipay status [--dir <path>] [--json]\n aipay unlink [--dry-run] [--dir <path>] [--json]\n\nlogin sign in as a developer (loopback PKCE, audience aipay-developer-api); tokens go to the\n OS keychain or a 0600 file \u2014 never into the project\napps list your apps / create one (Idempotency-Key: a retried create never makes a second app)\ninit link this project to an app: .aipay/project.json, .env.local, .gitignore,\n a callback route for your framework, aipay-agent.md, and the SDK install\n (--auth/--api are optional once you are signed in; --create makes the app first)\ntest real sign-in via a loopback callback (any free port on 127.0.0.1) + one chat completion \u2192 receipt\ndoctor check the link, files, SDK, and that AI-Pay is reachable\nstatus what this directory is linked to\nunlink forget the link (keeps your code)\n\nExit codes: 0 ok \u00B7 1 problem you can fix \u00B7 2 usage \u00B7 3 network/auth\nPilot gate: export AIPAY_GATE_TOKEN=<token from the Console>; never write it to files.\n";
2
+ export declare function main(argv: string[], io?: {
3
+ stdout?: (s: string) => void;
4
+ stderr?: (s: string) => void;
5
+ }): Promise<number>;
package/dist/main.js ADDED
@@ -0,0 +1,91 @@
1
+ import { flagBool, parseArgs } from './args.js';
2
+ import { runApps } from './commands/apps.js';
3
+ import { runDoctor } from './commands/doctor.js';
4
+ import { runInit } from './commands/init.js';
5
+ import { runLogin } from './commands/login.js';
6
+ import { runLogout, runWhoami } from './commands/session.js';
7
+ import { runStatus } from './commands/status.js';
8
+ import { runTest } from './commands/test.js';
9
+ import { runUnlink } from './commands/unlink.js';
10
+ import { CliError, createReporter, EXIT } from './output.js';
11
+ import { cliVersion } from './version.js';
12
+ export const HELP = `aipay — AI-Pay CLI
13
+
14
+ Usage
15
+ aipay login [--api <base>] [--device] [--json] developer sign-in for the CLI itself
16
+ aipay whoami [--json] · aipay logout [--json]
17
+ aipay apps list [--json]
18
+ aipay apps create --name <name> [--callback <url>] [--json]
19
+ aipay init --app <client_id> [--auth <origin>] [--api <base>] [--callback <url>] [--name <app name>]
20
+ [--framework next|express|fastify|hono|vite|node] override detection
21
+ [--dir <path>] [--dry-run] [--no-install] [--json]
22
+ aipay init --create <app name> [--api <base>] ... create the app (needs login) and link it
23
+ aipay test [--model <id>] [--port <n>] [--no-open] [--timeout <seconds>] [--dir <path>] [--json]
24
+ aipay doctor [--offline] [--dir <path>] [--json]
25
+ aipay status [--dir <path>] [--json]
26
+ aipay unlink [--dry-run] [--dir <path>] [--json]
27
+
28
+ login sign in as a developer (loopback PKCE, audience aipay-developer-api); tokens go to the
29
+ OS keychain or a 0600 file — never into the project
30
+ apps list your apps / create one (Idempotency-Key: a retried create never makes a second app)
31
+ init link this project to an app: .aipay/project.json, .env.local, .gitignore,
32
+ a callback route for your framework, aipay-agent.md, and the SDK install
33
+ (--auth/--api are optional once you are signed in; --create makes the app first)
34
+ test real sign-in via a loopback callback (any free port on 127.0.0.1) + one chat completion → receipt
35
+ doctor check the link, files, SDK, and that AI-Pay is reachable
36
+ status what this directory is linked to
37
+ unlink forget the link (keeps your code)
38
+
39
+ Exit codes: 0 ok · 1 problem you can fix · 2 usage · 3 network/auth
40
+ Pilot gate: export AIPAY_GATE_TOKEN=<token from the Console>; never write it to files.
41
+ `;
42
+ export async function main(argv, io) {
43
+ const args = parseArgs(argv);
44
+ const json = flagBool(args.flags, 'json');
45
+ const out = createReporter({ json, ...(io ?? {}) });
46
+ if (args.flags.version || args.command === 'version') {
47
+ ;
48
+ (io?.stdout ?? ((s) => process.stdout.write(`${s}\n`)))(json ? JSON.stringify({ version: cliVersion() }) : cliVersion());
49
+ return EXIT.ok;
50
+ }
51
+ if (!args.command || args.flags.help || args.command === 'help') {
52
+ ;
53
+ (io?.stdout ?? ((s) => process.stdout.write(`${s}\n`)))(HELP);
54
+ return args.command || args.flags.help ? EXIT.ok : EXIT.usage;
55
+ }
56
+ try {
57
+ switch (args.command) {
58
+ case 'login':
59
+ return await runLogin(args, out);
60
+ case 'logout':
61
+ return await runLogout(args, out);
62
+ case 'whoami':
63
+ return await runWhoami(args, out);
64
+ case 'apps':
65
+ return await runApps(args, out);
66
+ case 'init':
67
+ return await runInit(args, out);
68
+ case 'test':
69
+ return await runTest(args, out);
70
+ case 'doctor':
71
+ return await runDoctor(args, out);
72
+ case 'status':
73
+ return runStatus(args, out);
74
+ case 'unlink':
75
+ return runUnlink(args, out);
76
+ default:
77
+ throw new CliError('usage', `unknown command "${args.command}" (see \`aipay help\`)`, EXIT.usage);
78
+ }
79
+ }
80
+ catch (e) {
81
+ if (e instanceof CliError) {
82
+ out.line('bad', e.message);
83
+ out.result({ ok: false, error: { code: e.code, message: e.message } });
84
+ return e.exitCode;
85
+ }
86
+ const msg = e instanceof Error ? e.message : String(e);
87
+ out.line('bad', msg);
88
+ out.result({ ok: false, error: { code: 'unexpected', message: msg } });
89
+ return EXIT.problem;
90
+ }
91
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Output channel: human-readable lines on stderr-ish stdout, or one JSON document when
3
+ * `--json` is set (agents parse it; humans read the other one). Both go to stdout so
4
+ * `aipay status --json | jq` works; diagnostics that must never pollute JSON go to stderr.
5
+ */
6
+ export type Level = 'ok' | 'warn' | 'bad' | 'info';
7
+ export interface Reporter {
8
+ readonly json: boolean;
9
+ line(level: Level, text: string): void;
10
+ kv(label: string, value: string): void;
11
+ blank(): void;
12
+ /** Final structured result — printed as JSON in --json mode, ignored otherwise. */
13
+ result(doc: Record<string, unknown>): void;
14
+ /** Debug/diagnostic text — always stderr, never in JSON. */
15
+ debug(text: string): void;
16
+ }
17
+ export declare function createReporter(opts: {
18
+ json: boolean;
19
+ stdout?: (s: string) => void;
20
+ stderr?: (s: string) => void;
21
+ }): Reporter;
22
+ /** Exit codes are part of the contract (agents branch on them). */
23
+ export declare const EXIT: {
24
+ readonly ok: 0;
25
+ /** Something in the project/config is wrong and the user can fix it. */
26
+ readonly problem: 1;
27
+ /** Bad invocation (unknown command/flag, missing required flag). */
28
+ readonly usage: 2;
29
+ /** Network/auth failure talking to AI-Pay. */
30
+ readonly remote: 3;
31
+ };
32
+ export declare class CliError extends Error {
33
+ readonly exitCode: number;
34
+ readonly code: string;
35
+ constructor(code: string, message: string, exitCode?: number);
36
+ }
package/dist/output.js ADDED
@@ -0,0 +1,52 @@
1
+ const GLYPH = { ok: '✔', warn: '⚠', bad: '✘', info: '·' };
2
+ export function createReporter(opts) {
3
+ const stdout = opts.stdout ?? ((s) => process.stdout.write(`${s}\n`));
4
+ const stderr = opts.stderr ?? ((s) => process.stderr.write(`${s}\n`));
5
+ const json = opts.json;
6
+ return {
7
+ json,
8
+ line(level, text) {
9
+ if (json)
10
+ return;
11
+ stdout(`${GLYPH[level]} ${text}`);
12
+ },
13
+ kv(label, value) {
14
+ if (json)
15
+ return;
16
+ stdout(` ${label.padEnd(14)} ${value}`);
17
+ },
18
+ blank() {
19
+ if (json)
20
+ return;
21
+ stdout('');
22
+ },
23
+ result(doc) {
24
+ if (!json)
25
+ return;
26
+ stdout(JSON.stringify(doc, null, 2));
27
+ },
28
+ debug(text) {
29
+ stderr(text);
30
+ },
31
+ };
32
+ }
33
+ /** Exit codes are part of the contract (agents branch on them). */
34
+ export const EXIT = {
35
+ ok: 0,
36
+ /** Something in the project/config is wrong and the user can fix it. */
37
+ problem: 1,
38
+ /** Bad invocation (unknown command/flag, missing required flag). */
39
+ usage: 2,
40
+ /** Network/auth failure talking to AI-Pay. */
41
+ remote: 3,
42
+ };
43
+ export class CliError extends Error {
44
+ exitCode;
45
+ code;
46
+ constructor(code, message, exitCode = EXIT.problem) {
47
+ super(message);
48
+ this.name = 'CliError';
49
+ this.code = code;
50
+ this.exitCode = exitCode;
51
+ }
52
+ }
@@ -0,0 +1,61 @@
1
+ export interface ProjectConfig {
2
+ /** Schema version of this file. */
3
+ version: 1;
4
+ app: {
5
+ client_id: string;
6
+ name: string | null;
7
+ };
8
+ /** Authorization server origin (Hydra public), e.g. https://auth.ai-pay.example */
9
+ auth_origin: string;
10
+ /** API base for the SDK client, e.g. https://api.ai-pay.example */
11
+ api_base: string;
12
+ /** Registered loopback callback the CLI and the sample route use. */
13
+ callback: string;
14
+ /** What `aipay init` detected/scaffolded, for `doctor`/`status` and for humans. */
15
+ scaffold: {
16
+ package_manager: 'pnpm' | 'npm' | 'yarn' | 'bun' | null;
17
+ framework: Framework | null;
18
+ files: string[];
19
+ };
20
+ linked_at: string;
21
+ }
22
+ export type Framework = 'next' | 'express' | 'fastify' | 'hono' | 'vite' | 'node';
23
+ /** Accepted by `--framework`; detection picks server frameworks first, then Vite, then plain Node. */
24
+ export declare const FRAMEWORKS: readonly Framework[];
25
+ export declare function isFramework(v: unknown): v is Framework;
26
+ export declare const PROJECT_DIR = ".aipay";
27
+ export declare const PROJECT_FILE = "project.json";
28
+ export declare const ENV_FILE = ".env.local";
29
+ export declare function projectPath(dir: string): string;
30
+ export declare function readProject(dir: string): ProjectConfig | null;
31
+ export declare function writeProject(dir: string, cfg: ProjectConfig): string;
32
+ export declare function isProjectConfig(v: unknown): v is ProjectConfig;
33
+ /** Env var names the SDK samples and the scaffolded route read. Public values only. */
34
+ export declare const ENV_KEYS: {
35
+ readonly clientId: 'AIPAY_CLIENT_ID';
36
+ readonly authOrigin: 'AIPAY_AUTH_ORIGIN';
37
+ readonly apiBase: 'AIPAY_API_BASE';
38
+ readonly callback: 'AIPAY_CALLBACK_URL';
39
+ };
40
+ /** Vite only exposes VITE_-prefixed values to browser code, so a Vite project gets the same four
41
+ * public values twice: the plain names (for any server-side tooling) and these aliases. */
42
+ export declare const VITE_ENV_KEYS: {
43
+ readonly clientId: 'VITE_AIPAY_CLIENT_ID';
44
+ readonly authOrigin: 'VITE_AIPAY_AUTH_ORIGIN';
45
+ readonly apiBase: 'VITE_AIPAY_API_BASE';
46
+ readonly callback: 'VITE_AIPAY_CALLBACK_URL';
47
+ };
48
+ /**
49
+ * Merge our keys into `.env.local` without touching anything else in it: existing lines
50
+ * for our keys are replaced in place, missing ones appended under a marker comment.
51
+ * Returns the keys that actually changed (so `--dry-run` and `status` can report).
52
+ */
53
+ export declare function mergeEnvFile(existing: string | null, values: Record<string, string>): {
54
+ content: string;
55
+ changed: string[];
56
+ };
57
+ /** Append missing ignore entries; never reorder or remove anything. */
58
+ export declare function mergeGitignore(existing: string | null, entries: string[]): {
59
+ content: string;
60
+ added: string[];
61
+ };
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Local artifacts (consultant report §6.5):
3
+ * .aipay/project.json — committable: which app this project is linked to (no secrets)
4
+ * .env.local — NOT committed: only public values today (client_id, URLs); the
5
+ * gate token is read from the environment and never written
6
+ * .gitignore — gets `.env.local` and `.aipay/local/` appended once
7
+ *
8
+ * Tokens live only in memory for the duration of `aipay test`. Nothing here writes them.
9
+ */
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ /** Accepted by `--framework`; detection picks server frameworks first, then Vite, then plain Node. */
13
+ export const FRAMEWORKS = [
14
+ 'next',
15
+ 'express',
16
+ 'fastify',
17
+ 'hono',
18
+ 'vite',
19
+ 'node',
20
+ ];
21
+ export function isFramework(v) {
22
+ return typeof v === 'string' && FRAMEWORKS.includes(v);
23
+ }
24
+ export const PROJECT_DIR = '.aipay';
25
+ export const PROJECT_FILE = 'project.json';
26
+ export const ENV_FILE = '.env.local';
27
+ export function projectPath(dir) {
28
+ return join(dir, PROJECT_DIR, PROJECT_FILE);
29
+ }
30
+ export function readProject(dir) {
31
+ const p = projectPath(dir);
32
+ if (!existsSync(p))
33
+ return null;
34
+ const raw = readFileSync(p, 'utf8');
35
+ const parsed = JSON.parse(raw);
36
+ if (!isProjectConfig(parsed))
37
+ throw new Error(`${p} is not a valid AI-Pay project file`);
38
+ return parsed;
39
+ }
40
+ export function writeProject(dir, cfg) {
41
+ mkdirSync(join(dir, PROJECT_DIR), { recursive: true });
42
+ const p = projectPath(dir);
43
+ writeFileSync(p, `${JSON.stringify(cfg, null, 2)}\n`);
44
+ return p;
45
+ }
46
+ export function isProjectConfig(v) {
47
+ if (!v || typeof v !== 'object')
48
+ return false;
49
+ const o = v;
50
+ const app = o.app;
51
+ return (o.version === 1 &&
52
+ !!app &&
53
+ typeof app.client_id === 'string' &&
54
+ typeof o.auth_origin === 'string' &&
55
+ typeof o.api_base === 'string' &&
56
+ typeof o.callback === 'string');
57
+ }
58
+ /** Env var names the SDK samples and the scaffolded route read. Public values only. */
59
+ export const ENV_KEYS = {
60
+ clientId: 'AIPAY_CLIENT_ID',
61
+ authOrigin: 'AIPAY_AUTH_ORIGIN',
62
+ apiBase: 'AIPAY_API_BASE',
63
+ callback: 'AIPAY_CALLBACK_URL',
64
+ };
65
+ /** Vite only exposes VITE_-prefixed values to browser code, so a Vite project gets the same four
66
+ * public values twice: the plain names (for any server-side tooling) and these aliases. */
67
+ export const VITE_ENV_KEYS = {
68
+ clientId: 'VITE_AIPAY_CLIENT_ID',
69
+ authOrigin: 'VITE_AIPAY_AUTH_ORIGIN',
70
+ apiBase: 'VITE_AIPAY_API_BASE',
71
+ callback: 'VITE_AIPAY_CALLBACK_URL',
72
+ };
73
+ /**
74
+ * Merge our keys into `.env.local` without touching anything else in it: existing lines
75
+ * for our keys are replaced in place, missing ones appended under a marker comment.
76
+ * Returns the keys that actually changed (so `--dry-run` and `status` can report).
77
+ */
78
+ export function mergeEnvFile(existing, values) {
79
+ const lines = existing ? existing.split(/\r?\n/) : [];
80
+ if (lines.length && lines[lines.length - 1] === '')
81
+ lines.pop();
82
+ const changed = [];
83
+ const seen = new Set();
84
+ const out = lines.map((line) => {
85
+ const m = /^\s*(?:export\s+)?([A-Z0-9_]+)\s*=(.*)$/.exec(line);
86
+ if (!m)
87
+ return line;
88
+ const key = m[1];
89
+ if (!(key in values))
90
+ return line;
91
+ seen.add(key);
92
+ const want = values[key];
93
+ if (unquote(m[2] ?? '') === want)
94
+ return line;
95
+ changed.push(key);
96
+ return `${key}=${want}`;
97
+ });
98
+ const missing = Object.keys(values).filter((k) => !seen.has(k));
99
+ if (missing.length) {
100
+ if (out.length)
101
+ out.push('');
102
+ out.push('# AI-Pay (written by `aipay init`; public values, safe to keep local)');
103
+ for (const k of missing) {
104
+ out.push(`${k}=${values[k]}`);
105
+ changed.push(k);
106
+ }
107
+ }
108
+ return { content: `${out.join('\n')}\n`, changed };
109
+ }
110
+ function unquote(s) {
111
+ const t = s.trim();
112
+ if (t.length >= 2 &&
113
+ ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))))
114
+ return t.slice(1, -1);
115
+ return t;
116
+ }
117
+ /** Append missing ignore entries; never reorder or remove anything. */
118
+ export function mergeGitignore(existing, entries) {
119
+ const lines = existing ? existing.split(/\r?\n/) : [];
120
+ const have = new Set(lines.map((l) => l.trim()));
121
+ const added = entries.filter((e) => !have.has(e));
122
+ if (!added.length)
123
+ return { content: existing ?? '', added };
124
+ const base = existing ? (existing.endsWith('\n') ? existing : `${existing}\n`) : '';
125
+ const block = `${base}${base ? '\n' : ''}# AI-Pay local files (never commit)\n${added.join('\n')}\n`;
126
+ return { content: block, added };
127
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Everything that talks to AI-Pay over the network, in one place so the commands stay
3
+ * readable and tests can stub it. Gate header via the environment (see gate.ts).
4
+ */
5
+ import { GATE_HINT } from './gate.js';
6
+ export interface Remote {
7
+ fetchDocs(apiBase: string, locale?: 'en' | 'zh-Hant'): Promise<{
8
+ markdown: string | null;
9
+ gated: boolean;
10
+ status: number;
11
+ }>;
12
+ probe(url: string): Promise<{
13
+ ok: boolean;
14
+ status: number;
15
+ gated: boolean;
16
+ error?: string;
17
+ }>;
18
+ }
19
+ export declare function createRemote(env?: NodeJS.ProcessEnv): Remote;
20
+ export declare function docsUrl(apiBase: string, locale?: 'en' | 'zh-Hant'): string;
21
+ export { GATE_HINT };
package/dist/remote.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Everything that talks to AI-Pay over the network, in one place so the commands stay
3
+ * readable and tests can stub it. Gate header via the environment (see gate.ts).
4
+ */
5
+ import { GATE_HINT, gatedFetch, looksGated } from './gate.js';
6
+ import { CliError, EXIT } from './output.js';
7
+ export function createRemote(env = process.env) {
8
+ const f = gatedFetch(env);
9
+ return {
10
+ async fetchDocs(apiBase, locale = 'en') {
11
+ const url = docsUrl(apiBase, locale);
12
+ let res;
13
+ try {
14
+ res = await f(url, { headers: { accept: 'text/markdown, text/plain' } });
15
+ }
16
+ catch (e) {
17
+ throw new CliError('network', `cannot reach ${url}: ${e.message}`, EXIT.remote);
18
+ }
19
+ const text = await res.text();
20
+ if (res.ok)
21
+ return { markdown: text, gated: false, status: res.status };
22
+ return { markdown: null, gated: looksGated(res.status, text), status: res.status };
23
+ },
24
+ async probe(url) {
25
+ try {
26
+ const res = await f(url, { method: 'GET', redirect: 'manual' });
27
+ const text = await res.text();
28
+ return { ok: res.ok, status: res.status, gated: looksGated(res.status, text) };
29
+ }
30
+ catch (e) {
31
+ return { ok: false, status: 0, gated: false, error: e.message };
32
+ }
33
+ },
34
+ };
35
+ }
36
+ export function docsUrl(apiBase, locale = 'en') {
37
+ const u = new URL('/docs.md', apiBase);
38
+ u.searchParams.set('lang', locale);
39
+ return u.toString();
40
+ }
41
+ export { GATE_HINT };
@@ -0,0 +1,3 @@
1
+ import type { Reporter } from './output.js';
2
+ export type SetupEventKind = 'cli.init' | 'cli.test' | 'cli.doctor';
3
+ export declare function reportSetupEvent(appId: string, kind: SetupEventKind, detail: Record<string, string | number | boolean | string[]>, out: Reporter, env?: NodeJS.ProcessEnv): Promise<boolean>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Setup-session events (consultant §6.3): after `init` / `test` the CLI tells the Console
3
+ * what happened so the "waiting for the tool" line turns into "the CLI finished init".
4
+ * Best effort and strictly opt-in by state: only when the developer is signed in with the
5
+ * CLI (`aipay login`); never blocks the command, never sends tokens or file contents.
6
+ */
7
+ import { createAuthStore } from './auth-store.js';
8
+ import { openDeveloperApi } from './developer-api.js';
9
+ export async function reportSetupEvent(appId, kind, detail, out, env = process.env) {
10
+ const store = createAuthStore(env);
11
+ if (!store.load())
12
+ return false; // not signed in with the CLI → the Console still sees server facts
13
+ try {
14
+ const api = await openDeveloperApi(store, env);
15
+ const res = await api.request('POST', `/v1/developer/apps/${encodeURIComponent(appId)}/setup-events`, {
16
+ body: { kind, detail },
17
+ });
18
+ if (res.status === 201) {
19
+ out.line('info', `reported ${kind} to the Console`);
20
+ return true;
21
+ }
22
+ out.debug(`setup event ${kind} not recorded (HTTP ${res.status})`);
23
+ }
24
+ catch (e) {
25
+ out.debug(`setup event ${kind} skipped: ${e.message}`);
26
+ }
27
+ return false;
28
+ }