pcific 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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,570 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { BaseUrlError, DEFAULT_BASE_URL, normalizeBaseUrl, redactSecrets, } from "../api/run.js";
3
+ import { discoverSchemas } from "./discover.js";
4
+ import { isJsonObjectValue, loadLocalEnv, parseJsonText, } from "./helpers.js";
5
+ function isWritableStreamSink(sink) {
6
+ return "write" in sink;
7
+ }
8
+ function createLineWriter(sink, fallback) {
9
+ if (sink && !isWritableStreamSink(sink)) {
10
+ return (line) => {
11
+ sink(redactSecrets(line));
12
+ };
13
+ }
14
+ const stream = sink ?? fallback;
15
+ return (line) => {
16
+ stream.write(`${redactSecrets(line)}\n`);
17
+ };
18
+ }
19
+ function readSchemaFlagValue(args, index, flag, tryThis) {
20
+ const token = args[index];
21
+ if (token.startsWith(`${flag}=`)) {
22
+ const value = token.slice(flag.length + 1);
23
+ if (!value) {
24
+ return { ok: false, error: `Missing value for ${flag}.`, tryThis };
25
+ }
26
+ return { ok: true, value, nextIndex: index };
27
+ }
28
+ const next = args[index + 1];
29
+ if (!next || next.startsWith("-")) {
30
+ return { ok: false, error: `Missing value for ${flag}.`, tryThis };
31
+ }
32
+ return { ok: true, value: next, nextIndex: index + 1 };
33
+ }
34
+ function parseSchemaArgs(args, options) {
35
+ const wantsJson = Boolean(options.json) || args.includes("--json");
36
+ const parsed = {
37
+ subcommand: "help",
38
+ publish: false,
39
+ dryRun: false,
40
+ yes: false,
41
+ plain: Boolean(options.plain),
42
+ json: wantsJson,
43
+ help: false,
44
+ };
45
+ const positionals = [];
46
+ for (let index = 0; index < args.length; index += 1) {
47
+ const arg = args[index];
48
+ if (arg === "--help" || arg === "-h") {
49
+ parsed.help = true;
50
+ }
51
+ else if (arg === "--publish") {
52
+ parsed.publish = true;
53
+ }
54
+ else if (arg === "--dry-run") {
55
+ parsed.dryRun = true;
56
+ }
57
+ else if (arg === "--yes" || arg === "-y") {
58
+ parsed.yes = true;
59
+ }
60
+ else if (arg === "--plain") {
61
+ parsed.plain = true;
62
+ }
63
+ else if (arg === "--json") {
64
+ parsed.json = true;
65
+ }
66
+ else if (arg === "--file" || arg.startsWith("--file=")) {
67
+ const read = readSchemaFlagValue(args, index, "--file", "Pass a schema file path, for example --file schemas/phones.json.");
68
+ if (!read.ok) {
69
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
70
+ }
71
+ parsed.file = read.value;
72
+ index = read.nextIndex;
73
+ }
74
+ else if (arg === "--model" || arg.startsWith("--model=")) {
75
+ const read = readSchemaFlagValue(args, index, "--model", "Pass a model or symbol name, for example --model PhoneListing.");
76
+ if (!read.ok) {
77
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
78
+ }
79
+ parsed.model = read.value;
80
+ index = read.nextIndex;
81
+ }
82
+ else if (arg === "--category" || arg.startsWith("--category=")) {
83
+ const read = readSchemaFlagValue(args, index, "--category", "Pass a category name, for example --category Phones.");
84
+ if (!read.ok) {
85
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
86
+ }
87
+ parsed.category = read.value;
88
+ index = read.nextIndex;
89
+ }
90
+ else if (arg === "--parent" || arg.startsWith("--parent=")) {
91
+ const read = readSchemaFlagValue(args, index, "--parent", "Pass a parent category name, for example --parent Electronics.");
92
+ if (!read.ok) {
93
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
94
+ }
95
+ parsed.parent = read.value;
96
+ index = read.nextIndex;
97
+ }
98
+ else if (arg === "--about" || arg.startsWith("--about=")) {
99
+ const read = readSchemaFlagValue(args, index, "--about", 'Pass a short description of your shop, for example --about "Used phones shop".');
100
+ if (!read.ok) {
101
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
102
+ }
103
+ parsed.about = read.value;
104
+ index = read.nextIndex;
105
+ }
106
+ else if (arg === "--base-url" || arg.startsWith("--base-url=")) {
107
+ const read = readSchemaFlagValue(args, index, "--base-url", `Pass an http:// or https:// URL, for example --base-url ${DEFAULT_BASE_URL}.`);
108
+ if (!read.ok) {
109
+ return { ok: false, code: "MISSING_FLAG_VALUE", error: read.error, tryThis: read.tryThis, json: wantsJson };
110
+ }
111
+ parsed.baseUrl = read.value;
112
+ index = read.nextIndex;
113
+ }
114
+ else if (arg.startsWith("-")) {
115
+ return {
116
+ ok: false,
117
+ code: "UNKNOWN_FLAG",
118
+ error: `Unknown flag "${arg}" for pcific schema.`,
119
+ tryThis: "Run pcific schema --help to see supported options.",
120
+ json: wantsJson,
121
+ };
122
+ }
123
+ else {
124
+ positionals.push(arg);
125
+ }
126
+ }
127
+ if (positionals.length > 0) {
128
+ parsed.subcommand = positionals[0];
129
+ }
130
+ return { ok: true, parsed };
131
+ }
132
+ function parseApiError(status, rawBody) {
133
+ let payload = null;
134
+ try {
135
+ const parsed = parseJsonText(rawBody);
136
+ if (isJsonObjectValue(parsed)) {
137
+ // SAFETY: Verified parsed JSON payload is a plain object; every field on ApiErrorPayload is optional.
138
+ payload = parsed;
139
+ }
140
+ }
141
+ catch {
142
+ payload = null;
143
+ }
144
+ if (!payload) {
145
+ const cleanBody = redactSecrets(rawBody || "Request failed.");
146
+ const tryThis = "Check your API key, parameters, and base URL, then try again.";
147
+ return {
148
+ code: `HTTP_${status}`,
149
+ error: `HTTP ${status}: ${cleanBody}`,
150
+ tryThis,
151
+ formattedText: `HTTP ${status}: ${cleanBody}`,
152
+ };
153
+ }
154
+ const code = payload.code ?? `HTTP_${status}`;
155
+ const errorText = redactSecrets(payload.error ?? "Request failed.");
156
+ const tryThis = redactSecrets(payload.tryThis ?? "Fix the reported schema error and re-run pcific schema push.");
157
+ const lines = [];
158
+ const heading = payload.code ? `${payload.code} (HTTP ${status})` : `HTTP ${status}`;
159
+ lines.push(`${heading}: ${errorText}`);
160
+ if (Array.isArray(payload.problems) && payload.problems.length > 0) {
161
+ lines.push("Problems:");
162
+ for (const item of payload.problems) {
163
+ const place = item.path ?? item.where ?? "(root)";
164
+ const desc = redactSecrets(item.problem ?? "Invalid field");
165
+ const fix = item.tryThis ? ` -> ${redactSecrets(item.tryThis)}` : "";
166
+ lines.push(` - ${place}: ${desc}${fix}`);
167
+ }
168
+ }
169
+ return {
170
+ code,
171
+ error: errorText,
172
+ tryThis,
173
+ formattedText: lines.join("\n"),
174
+ problems: payload.problems,
175
+ };
176
+ }
177
+ function emitSchemaError(out, err, asJson, payload) {
178
+ const cleanError = redactSecrets(payload.error);
179
+ const cleanTryThis = redactSecrets(payload.tryThis);
180
+ if (asJson) {
181
+ const jsonPayload = {
182
+ ok: false,
183
+ code: payload.code,
184
+ error: cleanError,
185
+ tryThis: cleanTryThis,
186
+ };
187
+ if (payload.stage !== undefined)
188
+ jsonPayload.stage = payload.stage;
189
+ if (payload.category !== undefined)
190
+ jsonPayload.category = payload.category;
191
+ if (payload.status !== undefined)
192
+ jsonPayload.status = payload.status;
193
+ if (payload.warnings !== undefined)
194
+ jsonPayload.warnings = payload.warnings;
195
+ if (payload.problems !== undefined)
196
+ jsonPayload.problems = payload.problems;
197
+ if (payload.uploaded !== undefined)
198
+ jsonPayload.uploaded = payload.uploaded;
199
+ out(JSON.stringify(jsonPayload, null, 2));
200
+ return;
201
+ }
202
+ err(redactSecrets(payload.textHeading ?? cleanError));
203
+ err(`Next: ${cleanTryThis}`);
204
+ if (payload.warnings) {
205
+ for (const warning of payload.warnings) {
206
+ err(`Warning: ${warning}`);
207
+ }
208
+ }
209
+ }
210
+ function buildApiUrl(baseUrl, path, query) {
211
+ const cleanBase = baseUrl.replace(/\/+$/u, "");
212
+ const url = new URL(`${cleanBase}${path}`);
213
+ for (const [key, value] of Object.entries(query)) {
214
+ if (value !== undefined && value.length > 0) {
215
+ url.searchParams.set(key, value);
216
+ }
217
+ }
218
+ return url.toString();
219
+ }
220
+ function printDiscoverySummary(schemas, warnings, out, asJson) {
221
+ if (asJson) {
222
+ out(JSON.stringify({
223
+ schemas: schemas.map((entry) => ({
224
+ category: entry.category,
225
+ source: entry.source,
226
+ filePath: entry.filePath,
227
+ symbolName: entry.symbolName,
228
+ fieldCount: entry.fieldCount,
229
+ inferredDescriptions: entry.inferredDescriptions,
230
+ schema: entry.schema,
231
+ })),
232
+ warnings,
233
+ }, null, 2));
234
+ return;
235
+ }
236
+ if (schemas.length === 0) {
237
+ out("No listing schemas found.");
238
+ out("Tip: Pass --file <path> pointing to a JSON Schema, Zod, TypeScript, or Prisma file.");
239
+ }
240
+ else {
241
+ out(`Discovered ${schemas.length} schema${schemas.length === 1 ? "" : "s"}:`);
242
+ for (const entry of schemas) {
243
+ out(` - ${entry.category} (${entry.fieldCount} field${entry.fieldCount === 1 ? "" : "s"}, source: ${entry.source}, file: ${entry.filePath})`);
244
+ if (entry.inferredDescriptions.length > 0) {
245
+ out(` Auto-generated descriptions (${entry.inferredDescriptions.length}): ${entry.inferredDescriptions.join(", ")}`);
246
+ }
247
+ }
248
+ }
249
+ for (const warning of warnings) {
250
+ out(`Warning: ${warning}`);
251
+ }
252
+ }
253
+ function printUsage(out) {
254
+ out("Usage:");
255
+ out(" pcific schema discover [--file <path>] [--model <name>] [--category <name>] [--json]");
256
+ out(" pcific schema push [--file <path>] [--model <name>] [--category <name>] [--parent <name>]");
257
+ out(" [--publish] [--about \"...\"] [--dry-run] [--yes] [--plain] [--json]");
258
+ }
259
+ function resolveTestApiKey(env) {
260
+ const testKey = env.get("PCIFIC_TEST_KEY")?.trim();
261
+ const apiKey = env.get("PCIFIC_API_KEY")?.trim();
262
+ if (testKey && testKey.startsWith("pcific_live_")) {
263
+ return {
264
+ ok: false,
265
+ code: "LIVE_KEY_REFUSED",
266
+ error: "Refusing to run schema push with a live API key (pcific_live_***).",
267
+ tryThis: "Set PCIFIC_TEST_KEY to a test key (pcific_test_...) with the listing-fields permission, or run `npx pcific init` to link one.",
268
+ };
269
+ }
270
+ if (apiKey && apiKey.startsWith("pcific_live_") && !testKey) {
271
+ return {
272
+ ok: false,
273
+ code: "LIVE_KEY_REFUSED",
274
+ error: "Refusing to run schema push with a live API key in PCIFIC_API_KEY (pcific_live_***).",
275
+ tryThis: "Set PCIFIC_TEST_KEY to a test key (pcific_test_...) and keep live keys only in your production host's secret manager.",
276
+ };
277
+ }
278
+ if (!testKey) {
279
+ if (env.get("PCIFIC_LIVE_KEY")?.trim()) {
280
+ return {
281
+ ok: false,
282
+ code: "LIVE_KEY_REFUSED",
283
+ error: "PCIFIC_TEST_KEY is not set, and schema push never uses PCIFIC_LIVE_KEY.",
284
+ tryThis: "Set PCIFIC_TEST_KEY to a test key (pcific_test_...) in your environment or .env file, then re-run pcific schema push.",
285
+ };
286
+ }
287
+ return {
288
+ ok: false,
289
+ code: "MISSING_TEST_KEY",
290
+ error: "Missing PCIFIC_TEST_KEY.",
291
+ tryThis: "Set PCIFIC_TEST_KEY in your environment or .env file to a test key (pcific_test_...) with the listing-fields permission.",
292
+ };
293
+ }
294
+ return { ok: true, apiKey: testKey };
295
+ }
296
+ export async function runSchemaCommand(args, options = {}) {
297
+ const cwd = options.cwd ?? process.cwd();
298
+ const fetchFn = options.fetch ?? globalThis.fetch;
299
+ const out = createLineWriter(options.stdout, process.stdout);
300
+ const err = createLineWriter(options.stderr, process.stderr);
301
+ const parsedResult = parseSchemaArgs(args, options);
302
+ if (!parsedResult.ok) {
303
+ emitSchemaError(out, err, parsedResult.json, {
304
+ code: parsedResult.code,
305
+ error: parsedResult.error,
306
+ tryThis: parsedResult.tryThis,
307
+ });
308
+ return 1;
309
+ }
310
+ const parsed = parsedResult.parsed;
311
+ if (parsed.help || parsed.subcommand === "help") {
312
+ printUsage(out);
313
+ return 0;
314
+ }
315
+ if (parsed.subcommand !== "discover" && parsed.subcommand !== "push") {
316
+ emitSchemaError(out, err, parsed.json, {
317
+ code: "UNKNOWN_SUBCOMMAND",
318
+ error: `Unknown schema subcommand "${parsed.subcommand}". Expected "discover" or "push".`,
319
+ tryThis: 'Run "pcific schema discover", "pcific schema push", or "pcific schema --help".',
320
+ });
321
+ return 1;
322
+ }
323
+ const env = loadLocalEnv(cwd, options.env);
324
+ // Refuse live keys even on `push --dry-run`.
325
+ if (parsed.subcommand === "push") {
326
+ const precheckKey = resolveTestApiKey(env);
327
+ if (!precheckKey.ok && precheckKey.code === "LIVE_KEY_REFUSED") {
328
+ emitSchemaError(out, err, parsed.json, {
329
+ code: precheckKey.code,
330
+ error: precheckKey.error,
331
+ tryThis: precheckKey.tryThis,
332
+ });
333
+ return 1;
334
+ }
335
+ }
336
+ const discovery = discoverSchemas({
337
+ cwd,
338
+ file: parsed.file,
339
+ model: parsed.model,
340
+ category: parsed.category,
341
+ });
342
+ if (parsed.subcommand === "discover" || parsed.dryRun) {
343
+ printDiscoverySummary(discovery.schemas, discovery.warnings, out, parsed.json);
344
+ return discovery.schemas.length > 0 ? 0 : 1;
345
+ }
346
+ // `push` requires discovered schemas and a test key
347
+ if (discovery.schemas.length === 0) {
348
+ emitSchemaError(out, err, parsed.json, {
349
+ code: "NO_SCHEMAS_FOUND",
350
+ error: "No listing schemas were discovered to push.",
351
+ tryThis: "Pass --file <path> pointing to a JSON Schema, Zod, TypeScript, or Prisma file, or add schemas under schemas/.",
352
+ warnings: discovery.warnings,
353
+ });
354
+ return 1;
355
+ }
356
+ const keyResult = resolveTestApiKey(env);
357
+ if (!keyResult.ok) {
358
+ emitSchemaError(out, err, parsed.json, {
359
+ code: keyResult.code,
360
+ error: keyResult.error,
361
+ tryThis: keyResult.tryThis,
362
+ });
363
+ return 1;
364
+ }
365
+ let baseUrl;
366
+ try {
367
+ baseUrl = normalizeBaseUrl(parsed.baseUrl ?? options.baseUrl ?? env.get("PCIFIC_BASE_URL")?.trim() ?? DEFAULT_BASE_URL);
368
+ }
369
+ catch (error) {
370
+ if (error instanceof BaseUrlError) {
371
+ emitSchemaError(out, err, parsed.json, {
372
+ code: error.code,
373
+ error: error.message,
374
+ tryThis: error.tryThis,
375
+ });
376
+ return 1;
377
+ }
378
+ throw error;
379
+ }
380
+ const apiKey = keyResult.apiKey;
381
+ const marketplaceId = env.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined;
382
+ const baseHeaders = () => new Headers({
383
+ Authorization: `Bearer ${apiKey}`,
384
+ Accept: "application/json",
385
+ });
386
+ // 1. Fetch existing draft to compare
387
+ const beforeUrl = buildApiUrl(baseUrl, "/api/v1/schema-draft", { marketplaceId });
388
+ let existingDraft = null;
389
+ try {
390
+ const draftRes = await fetchFn(beforeUrl, {
391
+ method: "GET",
392
+ headers: baseHeaders(),
393
+ });
394
+ if (!draftRes.ok) {
395
+ const bodyText = await draftRes.text();
396
+ const apiErr = parseApiError(draftRes.status, bodyText);
397
+ emitSchemaError(out, err, parsed.json, {
398
+ code: apiErr.code,
399
+ error: apiErr.error,
400
+ tryThis: apiErr.tryThis,
401
+ textHeading: `Could not read current schema draft:\n${apiErr.formattedText}`,
402
+ stage: "get-draft",
403
+ status: draftRes.status,
404
+ problems: apiErr.problems,
405
+ });
406
+ return 1;
407
+ }
408
+ // SAFETY: GET /api/v1/schema-draft returns DraftResponse JSON on HTTP 200.
409
+ existingDraft = (await draftRes.json());
410
+ }
411
+ catch (error) {
412
+ const message = `Failed to reach ${beforeUrl}: ${error instanceof Error ? error.message : String(error)}`;
413
+ emitSchemaError(out, err, parsed.json, {
414
+ code: "NETWORK_ERROR",
415
+ error: message,
416
+ tryThis: `Check your network connection and base URL (${baseUrl}), then retry.`,
417
+ stage: "get-draft",
418
+ });
419
+ return 1;
420
+ }
421
+ const uploaded = [];
422
+ // 2. Upload each category to draft
423
+ for (const item of discovery.schemas) {
424
+ const categoryName = item.category;
425
+ const putUrl = buildApiUrl(baseUrl, `/api/v1/schema-draft/categories/${encodeURIComponent(categoryName)}`, {
426
+ parent: parsed.parent,
427
+ marketplaceId,
428
+ });
429
+ const headers = baseHeaders();
430
+ headers.set("Content-Type", "application/json");
431
+ headers.set("Idempotency-Key", randomUUID());
432
+ let putRes;
433
+ try {
434
+ putRes = await fetchFn(putUrl, {
435
+ method: "PUT",
436
+ headers,
437
+ body: JSON.stringify(item.schema),
438
+ });
439
+ }
440
+ catch (error) {
441
+ const message = `Failed to upload category "${categoryName}": ${error instanceof Error ? error.message : String(error)}`;
442
+ emitSchemaError(out, err, parsed.json, {
443
+ code: "NETWORK_ERROR",
444
+ error: message,
445
+ tryThis: `Check your network connection and base URL (${baseUrl}), then retry.`,
446
+ stage: "put-category",
447
+ category: categoryName,
448
+ });
449
+ return 1;
450
+ }
451
+ if (!putRes.ok) {
452
+ const bodyText = await putRes.text();
453
+ const apiErr = parseApiError(putRes.status, bodyText);
454
+ emitSchemaError(out, err, parsed.json, {
455
+ code: apiErr.code,
456
+ error: apiErr.error,
457
+ tryThis: apiErr.tryThis,
458
+ textHeading: `Upload failed for category "${categoryName}":\n${apiErr.formattedText}`,
459
+ stage: "put-category",
460
+ category: categoryName,
461
+ status: putRes.status,
462
+ problems: apiErr.problems,
463
+ });
464
+ return 1;
465
+ }
466
+ // SAFETY: PUT /api/v1/schema-draft/categories/:category returns PutCategoryResponse JSON on HTTP 200.
467
+ const putPayload = (await putRes.json());
468
+ uploaded.push({
469
+ category: putPayload.category ?? categoryName,
470
+ parent: putPayload.parent ?? parsed.parent ?? null,
471
+ fieldCount: putPayload.fieldCount ?? item.fieldCount,
472
+ inferredDescriptions: item.inferredDescriptions,
473
+ warnings: putPayload.warnings ?? [],
474
+ });
475
+ }
476
+ // 3. Re-read draft to retrieve server comparison
477
+ let afterDraft = existingDraft;
478
+ try {
479
+ const afterRes = await fetchFn(beforeUrl, {
480
+ method: "GET",
481
+ headers: baseHeaders(),
482
+ });
483
+ if (afterRes.ok) {
484
+ // SAFETY: GET /api/v1/schema-draft returns DraftResponse JSON on HTTP 200.
485
+ afterDraft = (await afterRes.json());
486
+ }
487
+ }
488
+ catch {
489
+ // Keep prior draft info if the follow-up read fails transiently.
490
+ }
491
+ // 4. Optionally publish version
492
+ let published = null;
493
+ if (parsed.publish) {
494
+ const publishUrl = buildApiUrl(baseUrl, "/api/v1/schema-versions", { marketplaceId });
495
+ const publishBody = parsed.about !== undefined ? { about: parsed.about } : {};
496
+ let pubRes;
497
+ const publishHeaders = baseHeaders();
498
+ publishHeaders.set("Content-Type", "application/json");
499
+ publishHeaders.set("Idempotency-Key", randomUUID());
500
+ try {
501
+ pubRes = await fetchFn(publishUrl, {
502
+ method: "POST",
503
+ headers: publishHeaders,
504
+ body: JSON.stringify(publishBody),
505
+ });
506
+ }
507
+ catch (error) {
508
+ const message = `Failed to publish schema version: ${error instanceof Error ? error.message : String(error)}`;
509
+ emitSchemaError(out, err, parsed.json, {
510
+ code: "NETWORK_ERROR",
511
+ error: message,
512
+ tryThis: `Check your network connection and base URL (${baseUrl}), then re-run pcific schema push --publish.`,
513
+ stage: "publish",
514
+ uploaded,
515
+ });
516
+ return 1;
517
+ }
518
+ if (!pubRes.ok) {
519
+ const bodyText = await pubRes.text();
520
+ const apiErr = parseApiError(pubRes.status, bodyText);
521
+ emitSchemaError(out, err, parsed.json, {
522
+ code: apiErr.code,
523
+ error: apiErr.error,
524
+ tryThis: apiErr.tryThis,
525
+ textHeading: `Schema publish failed:\n${apiErr.formattedText}`,
526
+ stage: "publish",
527
+ status: pubRes.status,
528
+ problems: apiErr.problems,
529
+ uploaded,
530
+ });
531
+ return 1;
532
+ }
533
+ // SAFETY: POST /api/v1/schema-versions returns PublishVersionResponse JSON on HTTP 201.
534
+ published = (await pubRes.json());
535
+ }
536
+ if (parsed.json) {
537
+ out(JSON.stringify({
538
+ ok: true,
539
+ uploaded,
540
+ comparison: afterDraft?.comparison ?? null,
541
+ published,
542
+ }, null, 2));
543
+ return 0;
544
+ }
545
+ for (const entry of uploaded) {
546
+ const parentNote = entry.parent ? ` (parent: ${entry.parent})` : "";
547
+ out(`Uploaded "${entry.category}"${parentNote}: ${entry.fieldCount} fields.`);
548
+ if (entry.inferredDescriptions.length > 0) {
549
+ out(` Note: auto-generated descriptions for ${entry.inferredDescriptions.join(", ")}. Refine them in your source schema for better AI accuracy.`);
550
+ }
551
+ for (const warning of entry.warnings) {
552
+ const place = warning.path || "(category)";
553
+ out(` Warning at ${place}: ${warning.problem ?? "Check schema"}${warning.tryThis ? ` (${warning.tryThis})` : ""}`);
554
+ }
555
+ }
556
+ if (afterDraft?.comparison) {
557
+ const cmp = afterDraft.comparison;
558
+ out(`Draft comparison (${cmp.message ?? `published v${cmp.publishedVersion ?? "none"}`}):`);
559
+ out(` added: ${cmp.added.length > 0 ? cmp.added.join(", ") : "none"}`);
560
+ out(` changed: ${cmp.changed.length > 0 ? cmp.changed.join(", ") : "none"}`);
561
+ out(` notInDraft: ${cmp.notInDraft.length > 0 ? cmp.notInDraft.join(", ") : "none"}`);
562
+ }
563
+ if (published) {
564
+ out(`Published schema version ${published.version}.`);
565
+ for (const warning of published.warnings ?? []) {
566
+ out(` Publish warning: ${warning.problem ?? ""}`);
567
+ }
568
+ }
569
+ return 0;
570
+ }