@stallforge/cli 0.0.0-stage → 0.2.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 (42) hide show
  1. package/README.md +39 -2
  2. package/bin/cli.mjs +4 -0
  3. package/package.json +58 -4
  4. package/src/commands/create.mjs +117 -0
  5. package/src/commands/dev.mjs +106 -0
  6. package/src/commands/doctor.mjs +48 -0
  7. package/src/commands/publish.mjs +43 -0
  8. package/src/commands/test.mjs +83 -0
  9. package/src/commands/validate.mjs +35 -0
  10. package/src/index.mjs +9 -0
  11. package/src/lib/build.mjs +35 -0
  12. package/src/lib/bundle.mjs +132 -0
  13. package/src/lib/check.mjs +105 -0
  14. package/src/lib/inspect.mjs +38 -0
  15. package/src/lib/names.mjs +6 -0
  16. package/src/lib/package-info.mjs +19 -0
  17. package/src/lib/report.mjs +4 -0
  18. package/src/lib/templates.mjs +5 -0
  19. package/src/lib/usage.mjs +1 -0
  20. package/src/main.mjs +61 -0
  21. package/template/src/index.mjs +69 -0
  22. package/template/templates/_common/README.md.tpl +11 -0
  23. package/template/templates/_common/gitignore.tpl +2 -0
  24. package/template/templates/_common/package.json.tpl +18 -0
  25. package/template/templates/_common/test/manifest.test.ts.tpl +15 -0
  26. package/template/templates/_common/tsconfig.json.tpl +15 -0
  27. package/template/templates/example/plugin.json.tpl +13 -0
  28. package/template/templates/example/src/index.ts.tpl +15 -0
  29. package/template/templates/example/test/plugin.test.ts.tpl +23 -0
  30. package/template/templates/payment/plugin.json.tpl +136 -0
  31. package/template/templates/payment/src/index.ts.tpl +248 -0
  32. package/types/bundle.d.ts +39 -0
  33. package/types/index.d.ts +24 -0
  34. package/types/shims/brand.d.ts +8 -0
  35. package/types/shims/conformance.d.ts +11 -0
  36. package/types/shims/contracts.d.ts +22 -0
  37. package/types/shims/sdk-range.d.ts +2 -0
  38. package/types/shims/sdk-scan.d.ts +8 -0
  39. package/types/shims/sdk.d.ts +1 -0
  40. package/types/shims/slot-shapes.d.ts +4 -0
  41. package/types/shims/slot-suites.d.ts +9 -0
  42. package/types/shims/validate.d.ts +14 -0
@@ -0,0 +1,136 @@
1
+ {
2
+ "manifest_version": 0,
3
+ "name": "__PLUGIN_NAME__",
4
+ "version": "0.1.0",
5
+ "license": "__LICENSE__",
6
+ "type": "payment",
7
+ "sdk": "__SDK_RANGE__",
8
+ "entry": "src/index.ts",
9
+ "capabilities": [
10
+ "data:own",
11
+ "events:emit",
12
+ "crypto:use"
13
+ ],
14
+ "slots": [
15
+ {
16
+ "slot": "payment",
17
+ "mode": "multi"
18
+ }
19
+ ],
20
+ "settings": [
21
+ {
22
+ "key": "webhook_secret",
23
+ "type": "secret",
24
+ "label": "Webhook secret",
25
+ "required": true
26
+ }
27
+ ],
28
+ "tables": [
29
+ {
30
+ "name": "sessions",
31
+ "columns": [
32
+ {
33
+ "name": "session_id",
34
+ "type": "text"
35
+ },
36
+ {
37
+ "name": "order_id",
38
+ "type": "text"
39
+ },
40
+ {
41
+ "name": "status",
42
+ "type": "text"
43
+ },
44
+ {
45
+ "name": "amount",
46
+ "type": "money"
47
+ },
48
+ {
49
+ "name": "currency",
50
+ "type": "text"
51
+ },
52
+ {
53
+ "name": "capture_method",
54
+ "type": "text"
55
+ },
56
+ {
57
+ "name": "captured",
58
+ "type": "money"
59
+ }
60
+ ],
61
+ "unique": [
62
+ [
63
+ "session_id"
64
+ ],
65
+ [
66
+ "order_id"
67
+ ]
68
+ ],
69
+ "indexes": [
70
+ {
71
+ "columns": [
72
+ "order_id"
73
+ ]
74
+ }
75
+ ]
76
+ },
77
+ {
78
+ "name": "refunds",
79
+ "columns": [
80
+ {
81
+ "name": "refund_key",
82
+ "type": "text"
83
+ },
84
+ {
85
+ "name": "session_id",
86
+ "type": "text"
87
+ },
88
+ {
89
+ "name": "amount",
90
+ "type": "money"
91
+ },
92
+ {
93
+ "name": "status",
94
+ "type": "text"
95
+ }
96
+ ],
97
+ "unique": [
98
+ [
99
+ "refund_key"
100
+ ]
101
+ ],
102
+ "indexes": [
103
+ {
104
+ "columns": [
105
+ "session_id"
106
+ ]
107
+ }
108
+ ]
109
+ },
110
+ {
111
+ "name": "events",
112
+ "columns": [
113
+ {
114
+ "name": "event_id",
115
+ "type": "text"
116
+ }
117
+ ],
118
+ "unique": [
119
+ [
120
+ "event_id"
121
+ ]
122
+ ]
123
+ }
124
+ ],
125
+ "events": {
126
+ "emits": [
127
+ "payment.status_changed"
128
+ ]
129
+ },
130
+ "webhooks": [
131
+ {
132
+ "name": "provider",
133
+ "handler": "handleWebhook"
134
+ }
135
+ ]
136
+ }
@@ -0,0 +1,248 @@
1
+ // A fake payment provider plugin. It stores sessions in its own table and shows the patterns the payment
2
+ // contract asks for: the signature checked with hmac, a duplicate event removed by one batch, status events.
3
+ // It implements the payment contract, not the provider's own vocabulary. How the fake provider's behaviour maps:
4
+ // token tok_ok -> automatic capture gives status captured with the whole amount in captured (provider
5
+ // succeeded); manual capture gives authorized (provider requires_capture)
6
+ // token tok_decline -> a declined result with code card_declined (the provider answers 402 card_declined; a
7
+ // decline is a result here, not an error)
8
+ // token tok_3ds -> status requires_action and redirect_url set to the relative path
9
+ // /fake-payment/return/<session_id>; completeAction settles it like tok_ok and is refused
10
+ // in any other status
11
+ // token pending -> status pending (asynchronous acceptance; neither authorized nor captured)
12
+ // provider_payload -> same settlement as tok_ok when the map is present
13
+ // order_id no-void -> voidPayment answers not_supported
14
+ // a new session -> created (provider requires_confirmation) plus a public client map
15
+ // refund over the captured amount, or on a session that is not captured -> the error code refund_rejected
16
+ // (provider 422 refund_exceeds_captured)
17
+ // a webhook event -> carries the contract status directly; a captured event also sets captured
18
+ const STATUSES = [
19
+ 'created',
20
+ 'requires_action',
21
+ 'pending',
22
+ 'authorized',
23
+ 'captured',
24
+ 'declined',
25
+ 'canceled',
26
+ 'refunded',
27
+ ];
28
+ const MINOR = /^(0|[1-9][0-9]{0,18})$/;
29
+ const fail = (code, message) => Object.assign(new Error(message), { code });
30
+ const minor = (value, label) => {
31
+ if (typeof value !== 'string' || !MINOR.test(value))
32
+ throw fail('bad_input', `${label} must be a string of minor units`);
33
+ return BigInt(value);
34
+ };
35
+
36
+ async function load(ctx, sessionId) {
37
+ const page = await ctx.sdk.data.list({ table: 'sessions', where: { session_id: String(sessionId) }, limit: 1 });
38
+ if (page.items.length === 0) throw fail('not_found', `session ${sessionId} was not found`);
39
+ return page.items[0];
40
+ }
41
+
42
+ async function setStatus(ctx, row, patch) {
43
+ const next = await ctx.sdk.data.update({ table: 'sessions', id: row.id, patch, expected_version: row.version });
44
+ await ctx.sdk.events.emit('payment.status_changed', { session_id: next.session_id, status: next.status });
45
+ return next;
46
+ }
47
+
48
+ // A token that works: automatic capture captures the whole amount, manual capture only authorizes.
49
+ async function settle(ctx, row) {
50
+ const patch =
51
+ row.capture_method === 'manual' ? { status: 'authorized' } : { status: 'captured', captured: row.amount };
52
+ const next = await setStatus(ctx, row, patch);
53
+ return { status: next.status, code: null, redirect_url: null };
54
+ }
55
+
56
+ // The row patch for a provider event. A captured event also sets the captured amount (the event may carry a
57
+ // smaller one as a string of minor units, never more than the amount), so a later refund is checked against it.
58
+ function patchFor(row, event) {
59
+ if (event.status !== 'captured') return { status: event.status };
60
+ const captured = event.captured === undefined ? row.amount : event.captured;
61
+ if (minor(captured, 'captured') > minor(row.amount, 'amount'))
62
+ throw fail('bad_input', 'captured is more than the amount');
63
+ return { status: 'captured', captured };
64
+ }
65
+
66
+ async function refundedSoFar(ctx, sessionId) {
67
+ let total = 0n;
68
+ let cursor = null;
69
+ do {
70
+ const page = await ctx.sdk.data.list({ table: 'refunds', where: { session_id: sessionId }, limit: 200, cursor });
71
+ for (const item of page.items) total += BigInt(String(item.amount));
72
+ cursor = page.next_cursor;
73
+ } while (cursor);
74
+ return total;
75
+ }
76
+
77
+ export default {
78
+ async activate() {},
79
+ async dispose() {},
80
+ };
81
+
82
+ export const handlers = {
83
+ async createSession(input, ctx) {
84
+ minor(input.amount, 'amount');
85
+ if (input.test_mode === true) {
86
+ // Sandbox credentials are always available for this fixture.
87
+ }
88
+ const suffix = (await ctx.sdk.crypto.random_bytes({ length: 9 })).replace(/[^A-Za-z0-9]/g, 'x');
89
+ const orderId = String(input.order_id);
90
+ const currency = String(input.currency);
91
+ const captureMethod = input.capture_method === 'manual' ? 'manual' : 'automatic';
92
+ const made = await ctx.sdk.data.insert_if_absent({
93
+ table: 'sessions',
94
+ key: ['order_id'],
95
+ row: {
96
+ session_id: `ps_${suffix}`,
97
+ order_id: orderId,
98
+ status: 'created',
99
+ amount: input.amount,
100
+ currency,
101
+ capture_method: captureMethod,
102
+ captured: '0',
103
+ },
104
+ });
105
+ const row = made.row;
106
+ if (row.amount !== input.amount || row.currency !== currency) {
107
+ throw fail('conflict', 'this order already has a payment session with different details');
108
+ }
109
+ if (made.inserted) {
110
+ await ctx.sdk.events.emit('payment.status_changed', { session_id: row.session_id, status: 'created' });
111
+ }
112
+ return {
113
+ session_id: row.session_id,
114
+ status: row.status,
115
+ client: { order_id: `prov_${orderId}`, key_id: 'pk_test' },
116
+ };
117
+ },
118
+ async authorize(input, ctx) {
119
+ const row = await load(ctx, input.session_id);
120
+ const hasToken = typeof input.token === 'string' && input.token.length > 0;
121
+ const hasPayload = input.provider_payload !== undefined && input.provider_payload !== null;
122
+ if (!hasToken && !hasPayload) throw fail('bad_input', 'authorize needs token or provider_payload');
123
+ if (hasPayload) return settle(ctx, row);
124
+ if (input.token === 'pending') {
125
+ await setStatus(ctx, row, { status: 'pending' });
126
+ return { status: 'pending', code: null, redirect_url: null };
127
+ }
128
+ if (input.token === 'tok_3ds') {
129
+ await setStatus(ctx, row, { status: 'requires_action' });
130
+ return { status: 'requires_action', code: null, redirect_url: `/fake-payment/return/${row.session_id}` };
131
+ }
132
+ if (input.token !== 'tok_ok') {
133
+ await setStatus(ctx, row, { status: 'declined' });
134
+ return { status: 'declined', code: 'card_declined', redirect_url: null };
135
+ }
136
+ return settle(ctx, row);
137
+ },
138
+ async completeAction(input, ctx) {
139
+ const row = await load(ctx, input.session_id);
140
+ if (row.status !== 'requires_action') throw fail('bad_input', 'the session is not waiting for an action');
141
+ const settled = await settle(ctx, row);
142
+ return { status: settled.status };
143
+ },
144
+ async capture(input, ctx) {
145
+ const row = await load(ctx, input.session_id);
146
+ if (row.status !== 'authorized') throw fail('bad_input', 'only an authorized session can be captured');
147
+ const amount = input.amount === undefined ? row.amount : input.amount;
148
+ if (minor(amount, 'amount') > minor(row.amount, 'amount'))
149
+ throw fail('bad_input', 'capture is more than the authorized amount');
150
+ const next = await setStatus(ctx, row, { status: 'captured', captured: amount });
151
+ return { status: next.status, captured: next.captured };
152
+ },
153
+ async voidPayment(input, ctx) {
154
+ const row = await load(ctx, input.session_id);
155
+ if (row.order_id === 'no-void') throw fail('not_supported', 'this provider cannot void a payment');
156
+ const next = await setStatus(ctx, row, { status: 'canceled' });
157
+ return { status: next.status };
158
+ },
159
+ async refund(input, ctx) {
160
+ const row = await load(ctx, input.session_id);
161
+ const amount = String(input.amount);
162
+ const refundKey = String(input.refund_key);
163
+ if (refundKey === '') throw fail('bad_input', 'refund needs a refund_key');
164
+ const prior = await ctx.sdk.data.list({ table: 'refunds', where: { refund_key: refundKey }, limit: 1 });
165
+ if (prior.items.length > 0) {
166
+ const first = prior.items[0];
167
+ if (first.session_id !== row.session_id || first.amount !== amount) {
168
+ throw fail('conflict', 'this refund_key was already used for another refund');
169
+ }
170
+ return { status: first.status, refunded: first.amount };
171
+ }
172
+ if (row.status !== 'captured' && row.status !== 'refunded') {
173
+ throw fail('refund_rejected', 'only a captured session can be refunded');
174
+ }
175
+ const wanted = minor(amount, 'amount');
176
+ const already = await refundedSoFar(ctx, row.session_id);
177
+ if (wanted + already > minor(row.captured, 'captured')) {
178
+ throw fail('refund_rejected', 'the refund is more than the captured amount');
179
+ }
180
+ const nextStatus = wanted + already >= minor(row.captured, 'captured') ? 'refunded' : row.status;
181
+ const made = await ctx.sdk.data.insert_if_absent({
182
+ table: 'refunds',
183
+ key: ['refund_key'],
184
+ row: {
185
+ refund_key: refundKey,
186
+ session_id: row.session_id,
187
+ amount,
188
+ status: nextStatus,
189
+ },
190
+ });
191
+ if (!made.inserted) {
192
+ const existing = made.row;
193
+ if (existing.session_id !== row.session_id || existing.amount !== amount) {
194
+ throw fail('conflict', 'this refund_key was already used for another refund');
195
+ }
196
+ return { status: existing.status, refunded: existing.amount };
197
+ }
198
+ const next = nextStatus === row.status ? row : await setStatus(ctx, row, { status: nextStatus });
199
+ return { status: next.status, refunded: amount };
200
+ },
201
+ async getStatus(input, ctx) {
202
+ const row = await load(ctx, input.session_id);
203
+ return {
204
+ session_id: row.session_id,
205
+ order_id: row.order_id,
206
+ status: row.status,
207
+ amount: row.amount,
208
+ currency: row.currency,
209
+ captured: row.captured,
210
+ };
211
+ },
212
+ async handleWebhook(input, ctx) {
213
+ const expected = await ctx.sdk.crypto.hmac({ secret: 'webhook_secret', data_text: input.body_text });
214
+ if (!(await ctx.sdk.crypto.compare({ a: expected, b: input.headers['x-signature'] ?? '' }))) {
215
+ return { status: 401, body_text: '{"error":"bad_signature"}' };
216
+ }
217
+ let event;
218
+ try {
219
+ event = JSON.parse(input.body_text);
220
+ } catch {
221
+ return { status: 400, body_text: '{"error":"bad_json"}' };
222
+ }
223
+ if (typeof event?.id !== 'string' || typeof event.session_id !== 'string' || !STATUSES.includes(event.status)) {
224
+ return { status: 400, body_text: '{"error":"bad_event"}' };
225
+ }
226
+ const row = await load(ctx, event.session_id);
227
+ let patch;
228
+ try {
229
+ patch = patchFor(row, event);
230
+ } catch {
231
+ return { status: 400, body_text: '{"error":"bad_event"}' };
232
+ }
233
+ try {
234
+ await ctx.sdk.data.batch({
235
+ preconditions: [{ kind: 'row_absent', table: 'events', key: { event_id: event.id } }],
236
+ operations: [
237
+ { op: 'insert', table: 'events', row: { event_id: event.id } },
238
+ { op: 'update', table: 'sessions', id: row.id, patch, expected_version: row.version },
239
+ ],
240
+ });
241
+ } catch (error) {
242
+ if (error.code === 'precondition_failed') return { status: 200, body_text: '{"duplicate":true}' };
243
+ throw error;
244
+ }
245
+ await ctx.sdk.events.emit('payment.status_changed', { session_id: event.session_id, status: event.status });
246
+ return { status: 200, body_text: '{"duplicate":false}' };
247
+ },
248
+ };
@@ -0,0 +1,39 @@
1
+ export declare const BUNDLE_FORMAT: 1;
2
+ export declare const BUNDLE_FILES: {
3
+ readonly bundle: 'index.mjs';
4
+ readonly manifest: 'plugin.json';
5
+ readonly entry: 'registry-entry.json';
6
+ };
7
+ export declare function sha256(data: string | Uint8Array): string;
8
+ export declare function bundleDirName(manifest: { name: string; version: string }): string;
9
+ export declare function manifestText(raw: Record<string, unknown>): string;
10
+ export interface RegistryEntry {
11
+ format: 1;
12
+ name: string;
13
+ version: string;
14
+ type: string;
15
+ license: string;
16
+ sdk: string;
17
+ capabilities: string[];
18
+ network_domains: string[];
19
+ slots: { slot: string; mode: 'exclusive' | 'multi' | 'fan-out' }[];
20
+ bundle: { file: 'index.mjs'; sha256: string; bytes: number };
21
+ manifest: { file: 'plugin.json'; sha256: string; bytes: number };
22
+ toolchain: { bundler: string; version: string; format: 'esm'; minify: true };
23
+ source_tag: string | null;
24
+ }
25
+ export declare function registryEntry(input: {
26
+ manifest: Record<string, unknown>;
27
+ bundle: Uint8Array;
28
+ manifestBytes: Uint8Array;
29
+ sourceTag?: string | null;
30
+ }): RegistryEntry;
31
+ export declare function writeBundle(input: {
32
+ outRoot: string;
33
+ raw: Record<string, unknown>;
34
+ manifest: Record<string, unknown>;
35
+ bundle: Uint8Array;
36
+ sourceTag?: string | null;
37
+ sourceDir?: string | null;
38
+ }): { dir: string; entry: RegistryEntry };
39
+ export declare function verifyBundle(dir: string): { ok: boolean; problems: string[]; entry: RegistryEntry | null };
@@ -0,0 +1,24 @@
1
+ export interface CommandContext {
2
+ cwd: string;
3
+ out(line: string): void;
4
+ err(line: string): void;
5
+ signal?: AbortSignal;
6
+ }
7
+ export interface PluginCheck {
8
+ name: string;
9
+ raw: Record<string, unknown> | null;
10
+ manifest: Record<string, unknown> | null;
11
+ errors: string[];
12
+ warnings: string[];
13
+ bundle: Buffer | null;
14
+ used: string[];
15
+ }
16
+ export declare function cliVersion(): string;
17
+ export declare function run(argv: string[], context?: Partial<CommandContext>): Promise<number>;
18
+ export declare function checkPlugin(dir: string, options?: { builds?: number }): Promise<PluginCheck>;
19
+ export declare function readManifest(dir: string): {
20
+ name: string;
21
+ raw: Record<string, unknown> | null;
22
+ manifest: Record<string, unknown> | null;
23
+ errors: string[];
24
+ };
@@ -0,0 +1,8 @@
1
+ declare const brand: {
2
+ displayName: string;
3
+ slug: string;
4
+ packageScope: string;
5
+ cliName: string;
6
+ };
7
+ export default brand;
8
+ export { brand };
@@ -0,0 +1,11 @@
1
+ export interface HostHandle {
2
+ load(dir: string): Promise<{ state: string; errors: string[] }>;
3
+ unload(name: string): Promise<unknown>;
4
+ callHandler(plugin: string, handler: string, input?: unknown): Promise<unknown>;
5
+ audit(): Promise<{ plugin: string; action: string; outcome: string; details: unknown }[]>;
6
+ close(): Promise<void>;
7
+ }
8
+ export interface HostAdapter {
9
+ create(): Promise<HostHandle>;
10
+ }
11
+ export function createTestkitAdapter(): HostAdapter;
@@ -0,0 +1,22 @@
1
+ export const SLOTS: {
2
+ slots: { name: string; mode: string; handlers?: string[] | null; scope?: string | null }[];
3
+ };
4
+ export function sdkSatisfies(range: string, version: string): boolean;
5
+ export function explainRange(range: string, version: string): string;
6
+ export function validateManifestText(text: string): {
7
+ ok: boolean;
8
+ errors: string[];
9
+ // Shim for checkJs only; real contracts types are richer.
10
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
11
+ manifest?: any;
12
+ };
13
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
14
+ export function getShape(slot: string): any;
15
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
16
+ export function exampleOf(slot: string, handler: string): any;
17
+ export const brand: {
18
+ displayName: string;
19
+ slug: string;
20
+ packageScope: string;
21
+ cliName: string;
22
+ };
@@ -0,0 +1,2 @@
1
+ export function sdkSatisfies(range: string, version: string): boolean;
2
+ export function explainRange(range: string, version: string): string;
@@ -0,0 +1,8 @@
1
+ export function scan(
2
+ text: string,
3
+ options?: { capabilities?: string[]; allowRelative?: boolean; profile?: 'database-driver' | 'storage' },
4
+ ): {
5
+ errors: { line: number; column: number; rule: string; message: string }[];
6
+ used_capabilities: string[];
7
+ imports: string[];
8
+ };
@@ -0,0 +1 @@
1
+ export const SDK_VERSION: string;
@@ -0,0 +1,4 @@
1
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
2
+ export function getShape(slot: string): any;
3
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
4
+ export function exampleOf(slot: string, handler: string): any;
@@ -0,0 +1,9 @@
1
+ export function runSlotSuite(
2
+ slot: string,
3
+ dir: string,
4
+ options?: unknown,
5
+ ): Promise<{
6
+ slot: string;
7
+ ok: boolean;
8
+ results: { id: string; status: string; message: string; part: string }[];
9
+ }>;
@@ -0,0 +1,14 @@
1
+ export const SLOTS: {
2
+ slots: {
3
+ name: string;
4
+ mode: string;
5
+ handlers?: string[] | null;
6
+ scope?: string | null;
7
+ }[];
8
+ };
9
+ export function validateManifestText(text: string): {
10
+ ok: boolean;
11
+ errors: string[];
12
+ // biome-ignore lint/suspicious/noExplicitAny: checkJs shim for sibling contracts surface
13
+ manifest?: any;
14
+ };