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,359 @@
1
+ import { PcificApiError, type PcificProblem } from "./errors.js";
2
+ import { isBoolean, isJsonObject, isString, parseJsonValue, type JsonValue } from "./json.js";
3
+ import { serializeFormData } from "./multipart.js";
4
+ import { signRequest } from "./verify.js";
5
+
6
+ export interface RequestOptions {
7
+ marketplaceId?: string;
8
+ idempotencyKey?: string | false;
9
+ signal?: AbortSignal;
10
+ headers?: Record<string, string>;
11
+ testAiStub?: boolean;
12
+ }
13
+
14
+ export interface HttpClientConfig {
15
+ baseUrl: string;
16
+ apiKey: string;
17
+ signingSecret?: string;
18
+ marketplaceId?: string;
19
+ testAiStub?: boolean;
20
+ fetch: typeof globalThis.fetch;
21
+ maxRetries: number;
22
+ baseDelayMs: number;
23
+ maxDelayMs: number;
24
+ sleep: (ms: number) => Promise<void>;
25
+ now: () => number;
26
+ random: () => number;
27
+ }
28
+
29
+ interface InternalRequestParams extends RequestOptions {
30
+ method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
31
+ path: string;
32
+ query?: Record<string, string | number | boolean | undefined | null>;
33
+ jsonBody?: JsonValue | object;
34
+ formData?: FormData;
35
+ binaryBody?: { bytes: Uint8Array; contentType: string };
36
+ accept?: string;
37
+ auth?: boolean;
38
+ }
39
+
40
+ const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
41
+
42
+ const TEXT_ENCODER = new TextEncoder();
43
+
44
+ function isExplicitIdempotencyKey(value: string | false | undefined): value is string {
45
+ return typeof value === "string";
46
+ }
47
+
48
+ function parseRetryAfterMs(headerValue: string | null, nowMs: number): number | null {
49
+ if (!headerValue) return null;
50
+ const trimmed = headerValue.trim();
51
+
52
+ if (/^\d+$/u.test(trimmed)) {
53
+ return Number(trimmed) * 1000;
54
+ }
55
+
56
+ const dateMs = Date.parse(trimmed);
57
+
58
+ if (!Number.isNaN(dateMs)) {
59
+ return Math.max(0, dateMs - nowMs);
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ function isRetryableStatus(status: number): boolean {
66
+ return status === 408 || status === 429 || (status >= 500 && status <= 599);
67
+ }
68
+
69
+ function defaultSleep(ms: number): Promise<void> {
70
+ return new Promise((resolve) => {
71
+ setTimeout(resolve, ms);
72
+ });
73
+ }
74
+
75
+ function decodeProblems(value: JsonValue | undefined): PcificProblem[] {
76
+ if (!Array.isArray(value)) return [];
77
+ const problems: PcificProblem[] = [];
78
+
79
+ for (const item of value) {
80
+ if (!isJsonObject(item)) continue;
81
+ const problem: PcificProblem = {};
82
+
83
+ if (isString(item.path)) problem.path = item.path;
84
+
85
+ if (isString(item.where)) problem.where = item.where;
86
+
87
+ if (isString(item.problem)) problem.problem = item.problem;
88
+
89
+ if (isString(item.tryThis)) problem.tryThis = item.tryThis;
90
+
91
+ if (isString(item.category)) problem.category = item.category;
92
+ problems.push(problem);
93
+ }
94
+
95
+ return problems;
96
+ }
97
+
98
+ async function parseApiError(response: Response): Promise<PcificApiError> {
99
+ const requestIdFromHeader = response.headers.get("x-request-id") ?? undefined;
100
+ let rawBody: JsonValue | undefined;
101
+
102
+ try {
103
+ const text = await response.text();
104
+
105
+ if (text.length > 0) {
106
+ try {
107
+ rawBody = parseJsonValue(text);
108
+ } catch {
109
+ rawBody = text;
110
+ }
111
+ }
112
+ } catch {
113
+ rawBody = undefined;
114
+ }
115
+
116
+ if (isJsonObject(rawBody)) {
117
+ return new PcificApiError({
118
+ status: response.status,
119
+ code: isString(rawBody.code) ? rawBody.code : `HTTP_${response.status}`,
120
+ error: isString(rawBody.error)
121
+ ? rawBody.error
122
+ : `PCIFIC API request failed with HTTP ${response.status}.`,
123
+ tryThis: isString(rawBody.tryThis)
124
+ ? rawBody.tryThis
125
+ : "Inspect the response status and request parameters, then try again.",
126
+ where: isString(rawBody.where) ? rawBody.where : undefined,
127
+ retryable: isBoolean(rawBody.retryable) ? rawBody.retryable : isRetryableStatus(response.status),
128
+ problems: decodeProblems(rawBody.problems),
129
+ requestId: isString(rawBody.requestId) ? rawBody.requestId : requestIdFromHeader,
130
+ existingId: isString(rawBody.existingId) ? rawBody.existingId : undefined,
131
+ rawBody,
132
+ });
133
+ }
134
+
135
+ return new PcificApiError({
136
+ status: response.status,
137
+ code: `HTTP_${response.status}`,
138
+ error: `PCIFIC API request failed with HTTP ${response.status}.`,
139
+ tryThis: "Retry the request if it is a transient server error, or contact PCIFIC support with the requestId.",
140
+ retryable: isRetryableStatus(response.status),
141
+ requestId: requestIdFromHeader,
142
+ rawBody,
143
+ });
144
+ }
145
+
146
+ export class PcificHttpClient {
147
+ readonly config: HttpClientConfig;
148
+
149
+ constructor(config: Partial<HttpClientConfig> & { apiKey: string }) {
150
+ this.config = {
151
+ baseUrl: (config.baseUrl ?? "https://business.pcific.ai").replace(/\/+$/u, ""),
152
+ apiKey: config.apiKey,
153
+ signingSecret: config.signingSecret,
154
+ marketplaceId: config.marketplaceId,
155
+ testAiStub: config.testAiStub,
156
+ fetch: config.fetch ?? globalThis.fetch,
157
+ maxRetries: config.maxRetries ?? 3,
158
+ baseDelayMs: config.baseDelayMs ?? 250,
159
+ maxDelayMs: config.maxDelayMs ?? 10_000,
160
+ sleep: config.sleep ?? defaultSleep,
161
+ now: config.now ?? (() => Date.now()),
162
+ random: config.random ?? (() => Math.random()),
163
+ };
164
+ }
165
+
166
+ private buildUrl(
167
+ path: string,
168
+ query?: Record<string, string | number | boolean | undefined | null>,
169
+ marketplaceId?: string,
170
+ ): string {
171
+ const url = new URL(`${this.config.baseUrl}${path}`);
172
+ const effectiveMarketplace = marketplaceId ?? this.config.marketplaceId;
173
+
174
+ if (effectiveMarketplace && (!query || query.marketplaceId === undefined)) {
175
+ url.searchParams.set("marketplaceId", effectiveMarketplace);
176
+ }
177
+
178
+ if (query) {
179
+ for (const [key, value] of Object.entries(query)) {
180
+ if (value !== undefined && value !== null) {
181
+ url.searchParams.set(key, String(value));
182
+ }
183
+ }
184
+ }
185
+
186
+ return url.toString();
187
+ }
188
+
189
+ private computeBackoffMs(attempt: number, retryAfterHeader: string | null): number {
190
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader, this.config.now());
191
+
192
+ if (retryAfterMs !== null) {
193
+ return Math.min(retryAfterMs, Math.max(this.config.maxDelayMs, retryAfterMs));
194
+ }
195
+
196
+ const exp = Math.min(this.config.maxDelayMs, this.config.baseDelayMs * 2 ** attempt);
197
+ const jitter = Math.floor(exp * 0.25 * this.config.random());
198
+
199
+ return Math.min(this.config.maxDelayMs, exp + jitter);
200
+ }
201
+
202
+ private async prepareBody(params: InternalRequestParams): Promise<{
203
+ bodyBytes: Uint8Array | undefined;
204
+ contentType: string | undefined;
205
+ }> {
206
+ if (params.formData) {
207
+ const serialized = await serializeFormData(params.formData);
208
+
209
+ return { bodyBytes: serialized.body, contentType: serialized.contentType };
210
+ }
211
+
212
+ if (params.binaryBody) {
213
+ return { bodyBytes: params.binaryBody.bytes, contentType: params.binaryBody.contentType };
214
+ }
215
+
216
+ if (params.jsonBody !== undefined) {
217
+ return {
218
+ bodyBytes: TEXT_ENCODER.encode(JSON.stringify(params.jsonBody)),
219
+ contentType: "application/json",
220
+ };
221
+ }
222
+
223
+ return { bodyBytes: undefined, contentType: undefined };
224
+ }
225
+
226
+ async send(params: InternalRequestParams): Promise<Response> {
227
+ const url = this.buildUrl(params.path, params.query, params.marketplaceId);
228
+ const { bodyBytes, contentType } = await this.prepareBody(params);
229
+
230
+ const isMutating = MUTATING_METHODS.has(params.method);
231
+
232
+ const idempotencyKey =
233
+ params.idempotencyKey === false
234
+ ? undefined
235
+ : isExplicitIdempotencyKey(params.idempotencyKey)
236
+ ? params.idempotencyKey
237
+ : isMutating
238
+ ? crypto.randomUUID()
239
+ : undefined;
240
+
241
+ const useAuth = params.auth !== false;
242
+ const useStub = params.testAiStub ?? this.config.testAiStub;
243
+
244
+ let attempt = 0;
245
+
246
+ while (true) {
247
+ const headers = new Headers(params.headers);
248
+
249
+ if (useAuth) {
250
+ headers.set("Authorization", `Bearer ${this.config.apiKey}`);
251
+ }
252
+
253
+ if (contentType) {
254
+ headers.set("Content-Type", contentType);
255
+ }
256
+
257
+ if (params.accept) {
258
+ headers.set("Accept", params.accept);
259
+ } else if (!headers.has("Accept")) {
260
+ headers.set("Accept", "application/json");
261
+ }
262
+
263
+ if (idempotencyKey) {
264
+ headers.set("Idempotency-Key", idempotencyKey);
265
+ }
266
+
267
+ if (useStub) {
268
+ headers.set("X-PCIFIC-Test-AI", "stub");
269
+ }
270
+
271
+ if (useAuth && this.config.signingSecret) {
272
+ const signature = await signRequest({
273
+ method: params.method,
274
+ url,
275
+ bodyBytes,
276
+ secret: this.config.signingSecret,
277
+ timestamp: Math.floor(this.config.now() / 1000),
278
+ });
279
+
280
+ headers.set("PCIFIC-Signature", signature);
281
+ }
282
+
283
+ let response: Response;
284
+
285
+ try {
286
+ // SAFETY: Uint8Array is a valid Fetch BodyInit buffer view in standard Fetch APIs.
287
+ const bodyInit = bodyBytes as BodyInit | undefined;
288
+ response = await this.config.fetch(url, {
289
+ method: params.method,
290
+ headers,
291
+ body: bodyInit,
292
+ signal: params.signal,
293
+ });
294
+ } catch (networkError) {
295
+ if (params.signal?.aborted || attempt >= this.config.maxRetries) {
296
+ throw networkError;
297
+ }
298
+
299
+ const delayMs = this.computeBackoffMs(attempt, null);
300
+ attempt += 1;
301
+ await this.config.sleep(delayMs);
302
+ continue;
303
+ }
304
+
305
+ if (response.ok) {
306
+ return response;
307
+ }
308
+
309
+ if (isRetryableStatus(response.status) && attempt < this.config.maxRetries && !params.signal?.aborted) {
310
+ const delayMs = this.computeBackoffMs(attempt, response.headers.get("retry-after"));
311
+
312
+ try {
313
+ await response.arrayBuffer();
314
+ } catch {
315
+ // Ignore drain errors on retryable failures.
316
+ }
317
+
318
+ attempt += 1;
319
+ await this.config.sleep(delayMs);
320
+ continue;
321
+ }
322
+
323
+ throw await parseApiError(response);
324
+ }
325
+ }
326
+
327
+ async requestJson<T>(params: InternalRequestParams): Promise<T> {
328
+ const response = await this.send(params);
329
+ const text = await response.text();
330
+
331
+ // SAFETY: Caller requests the documented response type T for this endpoint; 204 endpoints use requestVoid.
332
+ return parseJsonValue(text) as T;
333
+ }
334
+
335
+ async requestBinary(params: InternalRequestParams): Promise<Uint8Array> {
336
+ const response = await this.send(params);
337
+
338
+ return new Uint8Array(await response.arrayBuffer());
339
+ }
340
+
341
+ async requestVoid(params: InternalRequestParams): Promise<void> {
342
+ await this.send(params);
343
+ }
344
+
345
+ async requestStream(params: InternalRequestParams): Promise<ReadableStream<Uint8Array>> {
346
+ const response = await this.send({ ...params, accept: "text/event-stream" });
347
+
348
+ if (!response.body) {
349
+ throw new PcificApiError({
350
+ status: response.status,
351
+ code: "EMPTY_STREAM",
352
+ error: "PCIFIC returned an empty response body for the event stream.",
353
+ tryThis: "Retry the request or fall back to polling GET.",
354
+ });
355
+ }
356
+
357
+ return response.body;
358
+ }
359
+ }
@@ -0,0 +1,84 @@
1
+ export {
2
+ resolvePcificAuth,
3
+ type PcificMode,
4
+ type ResolvedPcificAuth,
5
+ type ResolvePcificAuthOptions,
6
+ } from "./auth.js";
7
+
8
+ export {
9
+ createPcificClient,
10
+ PcificClient,
11
+ type AskPcificInput,
12
+ type CreateListingInput,
13
+ type CreateReviewInput,
14
+ type DisputePackCreateDisputeInput,
15
+ type DisputePackPushListingInput,
16
+ type DisputePackRecordMessageInput,
17
+ type DisputePackRecordSaleInput,
18
+ type DisputePackRecordTrackingInput,
19
+ type EmbedSessionInput,
20
+ type GetAiNoticeOptions,
21
+ type MessageCheckInput,
22
+ type MessageCheckPresentInput,
23
+ type MessageCheckSender,
24
+ type MessageCheckVerifyOnlineInput,
25
+ type MoneyMinorUnits,
26
+ type PcificClientOptions,
27
+ type WaitOptions,
28
+ } from "./client.js";
29
+
30
+ export {
31
+ PcificApiError,
32
+ PcificConfigError,
33
+ PcificStreamError,
34
+ type PcificApiErrorInit,
35
+ type PcificProblem,
36
+ } from "./errors.js";
37
+
38
+ export { PcificHttpClient, type HttpClientConfig, type RequestOptions } from "./http.js";
39
+
40
+ export type { JsonObject, JsonValue } from "./json.js";
41
+
42
+ export {
43
+ normalizeUpload,
44
+ serializeFormData,
45
+ type NormalizedUpload,
46
+ type UploadFileDescriptor,
47
+ type UploadInput,
48
+ } from "./multipart.js";
49
+
50
+ export { parseSseStream, type SseFrame } from "./sse.js";
51
+
52
+ export {
53
+ clearJwksCache,
54
+ parseMessageCheckReceipt,
55
+ signRequest,
56
+ verifyMessageCheckReceipt,
57
+ verifyPixelTraceManifest,
58
+ verifyWebhookSignature,
59
+ type Ed25519Jwk,
60
+ type JsonWebKeySet,
61
+ type ParsedMcr1Receipt,
62
+ type SignRequestOptions,
63
+ type VerifyMessageCheckReceiptOptions,
64
+ type VerifyMessageCheckReceiptResult,
65
+ type VerifyPixelTraceManifestOptions,
66
+ type VerifyPixelTraceManifestResult,
67
+ type VerifyWebhookSignatureOptions,
68
+ type VerifyWebhookSignatureResult,
69
+ } from "./verify.js";
70
+
71
+ export type {
72
+ Error as PcificErrorResponse,
73
+ OrbitCancelled,
74
+ OrbitFailed,
75
+ OrbitListing,
76
+ OrbitQuestions,
77
+ OrbitWorking,
78
+ PcificPaths,
79
+ SafeguardDone,
80
+ SafeguardFailed,
81
+ SafeguardWorking,
82
+ ToolError,
83
+ WebhookEvent,
84
+ } from "./generated-types.js";
@@ -0,0 +1,24 @@
1
+ export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
2
+
3
+ export type JsonObject = { [key: string]: JsonValue };
4
+
5
+ export function isString(value: JsonValue | undefined): value is string {
6
+ return typeof value === "string";
7
+ }
8
+
9
+ export function isNumber(value: JsonValue | undefined): value is number {
10
+ return typeof value === "number";
11
+ }
12
+
13
+ export function isBoolean(value: JsonValue | undefined): value is boolean {
14
+ return typeof value === "boolean";
15
+ }
16
+
17
+ export function isJsonObject(value: JsonValue | undefined): value is JsonObject {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+
21
+ export function parseJsonValue(text: string): JsonValue {
22
+ // SAFETY: JSON.parse returns only JSON primitives, arrays, or plain objects matching JsonValue.
23
+ return JSON.parse(text) as JsonValue;
24
+ }