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.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/dist/SKILL.md +127 -0
- package/dist/api/catalog.js +637 -0
- package/dist/api/run.js +960 -0
- package/dist/api/search.js +171 -0
- package/dist/api/shortcuts.js +799 -0
- package/dist/bin.js +648 -0
- package/dist/commands/auth.js +513 -0
- package/dist/commands/doctor.js +410 -0
- package/dist/commands/init.js +306 -0
- package/dist/commands/sync.js +214 -0
- package/dist/detect.js +214 -0
- package/dist/env.js +339 -0
- package/dist/goLive.js +629 -0
- package/dist/keyLink.js +305 -0
- package/dist/mcp/server.js +206 -0
- package/dist/mcp/tools.js +689 -0
- package/dist/python/template.js +793 -0
- package/dist/schema/discover.js +324 -0
- package/dist/schema/helpers.js +396 -0
- package/dist/schema/prismaToJsonSchema.js +197 -0
- package/dist/schema/push.js +570 -0
- package/dist/schema/tsToJsonSchema.js +405 -0
- package/dist/schema/zodToJsonSchema.js +442 -0
- package/dist/templates/openapi.json +1 -0
- package/dist/templates/sdk/auth.ts +139 -0
- package/dist/templates/sdk/client.ts +1059 -0
- package/dist/templates/sdk/errors.ts +76 -0
- package/dist/templates/sdk/generated-types.ts +5746 -0
- package/dist/templates/sdk/http.ts +359 -0
- package/dist/templates/sdk/index.ts +84 -0
- package/dist/templates/sdk/json.ts +24 -0
- package/dist/templates/sdk/kit.ts +516 -0
- package/dist/templates/sdk/multipart.ts +99 -0
- package/dist/templates/sdk/sse.ts +131 -0
- package/dist/templates/sdk/verify.ts +766 -0
- package/dist/templates/sdk-js/auth.d.ts +20 -0
- package/dist/templates/sdk-js/auth.js +85 -0
- package/dist/templates/sdk-js/client.d.ts +324 -0
- package/dist/templates/sdk-js/client.js +607 -0
- package/dist/templates/sdk-js/errors.d.ts +51 -0
- package/dist/templates/sdk-js/errors.js +48 -0
- package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
- package/dist/templates/sdk-js/generated-types.js +5 -0
- package/dist/templates/sdk-js/http.d.ts +50 -0
- package/dist/templates/sdk-js/http.js +263 -0
- package/dist/templates/sdk-js/index.d.ts +9 -0
- package/dist/templates/sdk-js/index.js +7 -0
- package/dist/templates/sdk-js/json.d.ts +11 -0
- package/dist/templates/sdk-js/json.js +16 -0
- package/dist/templates/sdk-js/kit.d.ts +220 -0
- package/dist/templates/sdk-js/kit.js +208 -0
- package/dist/templates/sdk-js/multipart.d.ts +23 -0
- package/dist/templates/sdk-js/multipart.js +61 -0
- package/dist/templates/sdk-js/sse.d.ts +12 -0
- package/dist/templates/sdk-js/sse.js +99 -0
- package/dist/templates/sdk-js/verify.d.ts +114 -0
- package/dist/templates/sdk-js/verify.js +506 -0
- package/dist/templates.js +925 -0
- package/dist/ui.js +399 -0
- package/dist/webhooks/events.js +171 -0
- package/dist/webhooks/listen.js +772 -0
- package/package.json +32 -4
|
@@ -0,0 +1,925 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { CliError, DEFAULT_BASE_URL } from "./env.js";
|
|
6
|
+
const STAMP_PATTERN = /@pcific-generated\s+(\d{4}-\d{2}-\d{2})\s+mode=(copy|package)/;
|
|
7
|
+
/**
|
|
8
|
+
* Resolves `target` relative to `cwd` and rejects absolute paths or any path
|
|
9
|
+
* that escapes the workspace directory.
|
|
10
|
+
*/
|
|
11
|
+
export function resolveInsideWorkspace(cwd, target) {
|
|
12
|
+
const trimmed = target.trim();
|
|
13
|
+
if (!trimmed ||
|
|
14
|
+
trimmed.includes("\0") ||
|
|
15
|
+
path.isAbsolute(trimmed) ||
|
|
16
|
+
trimmed.startsWith("/") ||
|
|
17
|
+
trimmed.startsWith("\\") ||
|
|
18
|
+
/^[A-Za-z]:[\\/]/.test(trimmed)) {
|
|
19
|
+
throw new CliError(`Invalid target directory "${target}". Path must stay inside the project workspace.`, {
|
|
20
|
+
code: "INVALID_TARGET_DIR",
|
|
21
|
+
tryThis: "Pass a relative path inside your project directory, such as src/lib or lib.",
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
const root = path.resolve(cwd);
|
|
25
|
+
const resolved = path.resolve(root, trimmed);
|
|
26
|
+
const rel = path.relative(root, resolved);
|
|
27
|
+
if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
|
|
28
|
+
throw new CliError(`Target directory "${target}" escapes the project workspace.`, {
|
|
29
|
+
code: "INVALID_TARGET_DIR",
|
|
30
|
+
tryThis: "Pass a relative path inside your project directory without '..' segments escaping the repo root.",
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return resolved;
|
|
34
|
+
}
|
|
35
|
+
export function formatIsoDate(now = new Date()) {
|
|
36
|
+
return now.toISOString().slice(0, 10);
|
|
37
|
+
}
|
|
38
|
+
function makeStampHeader(date, mode) {
|
|
39
|
+
return `// @pcific-generated ${date} mode=${mode}\n`;
|
|
40
|
+
}
|
|
41
|
+
function toPosixRelative(fromFile, toFile) {
|
|
42
|
+
const rel = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, "/");
|
|
43
|
+
return rel.startsWith(".") ? rel : `./${rel}`;
|
|
44
|
+
}
|
|
45
|
+
function stripTsExtensionForImport(filePath) {
|
|
46
|
+
if (filePath.endsWith(".ts")) {
|
|
47
|
+
return `${filePath.slice(0, -3)}.js`;
|
|
48
|
+
}
|
|
49
|
+
return filePath;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Resolves the bundled SDK template directory, supporting both compiled `dist/`
|
|
53
|
+
* (from `npm pack`) and source-tree execution during Vitest/dev.
|
|
54
|
+
*/
|
|
55
|
+
export function resolveTemplateSourceDir(language) {
|
|
56
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
57
|
+
const candidates = language === "javascript"
|
|
58
|
+
? [
|
|
59
|
+
path.resolve(here, "templates/sdk-js"),
|
|
60
|
+
path.resolve(here, "../dist/templates/sdk-js"),
|
|
61
|
+
path.resolve(here, "../../sdk/dist"),
|
|
62
|
+
]
|
|
63
|
+
: [
|
|
64
|
+
path.resolve(here, "templates/sdk"),
|
|
65
|
+
path.resolve(here, "../dist/templates/sdk"),
|
|
66
|
+
path.resolve(here, "../../sdk/src"),
|
|
67
|
+
];
|
|
68
|
+
for (const candidate of candidates) {
|
|
69
|
+
if (existsSync(candidate)) {
|
|
70
|
+
return candidate;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
throw new CliError(`Could not locate bundled PCIFIC ${language} SDK templates.`, {
|
|
74
|
+
code: "MISSING_SDK_TEMPLATES",
|
|
75
|
+
tryThis: language === "javascript"
|
|
76
|
+
? "Build @pcific/sdk and pcific first (npm run build), or use --mode package."
|
|
77
|
+
: "Reinstall the pcific package or run npm run build inside packages/pcific-kit/cli.",
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function createCopyClientInstanceTs(date) {
|
|
81
|
+
return [
|
|
82
|
+
makeStampHeader(date, "copy").trimEnd(),
|
|
83
|
+
'import { createPcificClient, type PcificClient } from "./client.js";',
|
|
84
|
+
"",
|
|
85
|
+
"interface RuntimeProcessGlobal {",
|
|
86
|
+
" process?: { env?: Record<string, string | undefined> };",
|
|
87
|
+
"}",
|
|
88
|
+
"",
|
|
89
|
+
"function readRuntimeEnv(): Record<string, string | undefined> {",
|
|
90
|
+
' if (typeof globalThis !== "undefined" && "process" in globalThis) {',
|
|
91
|
+
" return (globalThis as RuntimeProcessGlobal).process?.env ?? {};",
|
|
92
|
+
" }",
|
|
93
|
+
"",
|
|
94
|
+
" return {};",
|
|
95
|
+
"}",
|
|
96
|
+
"",
|
|
97
|
+
"let cachedClient: PcificClient | undefined;",
|
|
98
|
+
"",
|
|
99
|
+
"/**",
|
|
100
|
+
" * Lazily returns a cached PCIFIC client configured from PCIFIC_TEST_KEY / PCIFIC_LIVE_KEY",
|
|
101
|
+
" * and optional PCIFIC_MARKETPLACE_ID in your runtime environment.",
|
|
102
|
+
" */",
|
|
103
|
+
"export function getPcific(): PcificClient {",
|
|
104
|
+
" if (!cachedClient) {",
|
|
105
|
+
" const runtimeEnv = readRuntimeEnv();",
|
|
106
|
+
" cachedClient = createPcificClient({",
|
|
107
|
+
" baseUrl: runtimeEnv.PCIFIC_BASE_URL,",
|
|
108
|
+
" marketplaceId: runtimeEnv.PCIFIC_MARKETPLACE_ID,",
|
|
109
|
+
" });",
|
|
110
|
+
" }",
|
|
111
|
+
"",
|
|
112
|
+
" return cachedClient;",
|
|
113
|
+
"}",
|
|
114
|
+
"",
|
|
115
|
+
'export { createPcificClient } from "./client.js";',
|
|
116
|
+
"",
|
|
117
|
+
].join("\n");
|
|
118
|
+
}
|
|
119
|
+
function createCopyClientInstanceJs(date) {
|
|
120
|
+
return [
|
|
121
|
+
makeStampHeader(date, "copy").trimEnd(),
|
|
122
|
+
'import { createPcificClient } from "./client.js";',
|
|
123
|
+
"",
|
|
124
|
+
"let cachedClient;",
|
|
125
|
+
"",
|
|
126
|
+
"export function getPcific() {",
|
|
127
|
+
" if (!cachedClient) {",
|
|
128
|
+
' const runtimeEnv = typeof globalThis !== "undefined" && globalThis.process?.env ? globalThis.process.env : {};',
|
|
129
|
+
" cachedClient = createPcificClient({",
|
|
130
|
+
" baseUrl: runtimeEnv.PCIFIC_BASE_URL,",
|
|
131
|
+
" marketplaceId: runtimeEnv.PCIFIC_MARKETPLACE_ID,",
|
|
132
|
+
" });",
|
|
133
|
+
" }",
|
|
134
|
+
"",
|
|
135
|
+
" return cachedClient;",
|
|
136
|
+
"}",
|
|
137
|
+
"",
|
|
138
|
+
'export { createPcificClient } from "./client.js";',
|
|
139
|
+
"",
|
|
140
|
+
].join("\n");
|
|
141
|
+
}
|
|
142
|
+
function createCopyClientInstanceDts(date) {
|
|
143
|
+
return [
|
|
144
|
+
makeStampHeader(date, "copy").trimEnd(),
|
|
145
|
+
'import type { PcificClient } from "./client.js";',
|
|
146
|
+
'export { createPcificClient } from "./client.js";',
|
|
147
|
+
"",
|
|
148
|
+
"export declare function getPcific(): PcificClient;",
|
|
149
|
+
"",
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
function createPackageClientTs(date, withKit) {
|
|
153
|
+
const lines = [
|
|
154
|
+
makeStampHeader(date, "package").trimEnd(),
|
|
155
|
+
'import { createPcificClient, type PcificClient } from "@pcific/sdk";',
|
|
156
|
+
];
|
|
157
|
+
if (withKit) {
|
|
158
|
+
lines.push('export { createPcificKit, loadPcificKit, onPcificEvent } from "@pcific/sdk/kit";');
|
|
159
|
+
}
|
|
160
|
+
lines.push("", "interface RuntimeProcessGlobal {", " process?: { env?: Record<string, string | undefined> };", "}", "", "function readRuntimeEnv(): Record<string, string | undefined> {", ' if (typeof globalThis !== "undefined" && "process" in globalThis) {', " return (globalThis as RuntimeProcessGlobal).process?.env ?? {};", " }", "", " return {};", "}", "", "let cachedClient: PcificClient | undefined;", "", "/**", " * Lazily returns a cached PCIFIC client configured from PCIFIC_TEST_KEY / PCIFIC_LIVE_KEY", " * and optional PCIFIC_MARKETPLACE_ID in your runtime environment.", " */", "export function getPcific(): PcificClient {", " if (!cachedClient) {", " const runtimeEnv = readRuntimeEnv();", " cachedClient = createPcificClient({", " baseUrl: runtimeEnv.PCIFIC_BASE_URL,", " marketplaceId: runtimeEnv.PCIFIC_MARKETPLACE_ID,", " });", " }", "", " return cachedClient;", "}", "", 'export { createPcificClient, PcificApiError, PcificConfigError } from "@pcific/sdk";', "");
|
|
161
|
+
return lines.join("\n");
|
|
162
|
+
}
|
|
163
|
+
function createPackageClientJs(date, withKit) {
|
|
164
|
+
const lines = [
|
|
165
|
+
makeStampHeader(date, "package").trimEnd(),
|
|
166
|
+
'import { createPcificClient } from "@pcific/sdk";',
|
|
167
|
+
];
|
|
168
|
+
if (withKit) {
|
|
169
|
+
lines.push('export { createPcificKit, loadPcificKit, onPcificEvent } from "@pcific/sdk/kit";');
|
|
170
|
+
}
|
|
171
|
+
lines.push("", "let cachedClient;", "", "export function getPcific() {", " if (!cachedClient) {", ' const runtimeEnv = typeof globalThis !== "undefined" && globalThis.process?.env ? globalThis.process.env : {};', " cachedClient = createPcificClient({", " baseUrl: runtimeEnv.PCIFIC_BASE_URL,", " marketplaceId: runtimeEnv.PCIFIC_MARKETPLACE_ID,", " });", " }", "", " return cachedClient;", "}", "", 'export { createPcificClient, PcificApiError, PcificConfigError } from "@pcific/sdk";', "");
|
|
172
|
+
return lines.join("\n");
|
|
173
|
+
}
|
|
174
|
+
export function shouldIncludeKitByDefault(framework) {
|
|
175
|
+
return framework !== "node" && framework !== "express" && framework !== "python";
|
|
176
|
+
}
|
|
177
|
+
export function shouldGenerateRouteByDefault(framework) {
|
|
178
|
+
return (framework === "nextjs-app" ||
|
|
179
|
+
framework === "nextjs-pages" ||
|
|
180
|
+
framework === "astro" ||
|
|
181
|
+
framework === "sveltekit" ||
|
|
182
|
+
framework === "remix" ||
|
|
183
|
+
framework === "express");
|
|
184
|
+
}
|
|
185
|
+
function resolveStarterRoutePath(cwd, framework, srcDir, libDir, language) {
|
|
186
|
+
const ext = language === "typescript" ? "ts" : "js";
|
|
187
|
+
const mjsExt = language === "typescript" ? "ts" : "mjs";
|
|
188
|
+
if (framework === "nextjs-app") {
|
|
189
|
+
const appBase = existsSync(path.join(cwd, "src", "app"))
|
|
190
|
+
? "src/app"
|
|
191
|
+
: existsSync(path.join(cwd, "app"))
|
|
192
|
+
? "app"
|
|
193
|
+
: srcDir
|
|
194
|
+
? "src/app"
|
|
195
|
+
: "app";
|
|
196
|
+
return path.join(appBase, "api", "pcific", "embed-session", `route.${ext}`);
|
|
197
|
+
}
|
|
198
|
+
if (framework === "nextjs-pages") {
|
|
199
|
+
const pagesBase = existsSync(path.join(cwd, "src", "pages"))
|
|
200
|
+
? "src/pages"
|
|
201
|
+
: existsSync(path.join(cwd, "pages"))
|
|
202
|
+
? "pages"
|
|
203
|
+
: srcDir
|
|
204
|
+
? "src/pages"
|
|
205
|
+
: "pages";
|
|
206
|
+
return path.join(pagesBase, "api", "pcific", `embed-session.${ext}`);
|
|
207
|
+
}
|
|
208
|
+
if (framework === "astro") {
|
|
209
|
+
return path.join("src", "pages", "api", "pcific", `embed-session.${ext}`);
|
|
210
|
+
}
|
|
211
|
+
if (framework === "sveltekit") {
|
|
212
|
+
return path.join("src", "routes", "api", "pcific", "embed-session", `+server.${ext}`);
|
|
213
|
+
}
|
|
214
|
+
if (framework === "remix") {
|
|
215
|
+
return path.join("app", "routes", `api.pcific.embed-session.${ext}`);
|
|
216
|
+
}
|
|
217
|
+
return path.join(libDir, `pcific-embed-route.${mjsExt}`);
|
|
218
|
+
}
|
|
219
|
+
function buildAllowedToolsBlock(isTs) {
|
|
220
|
+
if (isTs) {
|
|
221
|
+
return [
|
|
222
|
+
'type EmbedTool = "orbit" | "safeguard" | "ask-pcific" | "pixel-trace" | "message-check";',
|
|
223
|
+
"",
|
|
224
|
+
'const ALLOWED_TOOLS = new Set<EmbedTool>(["orbit", "safeguard", "ask-pcific", "pixel-trace", "message-check"]);',
|
|
225
|
+
'const DEFAULT_TOOLS: EmbedTool[] = ["orbit", "safeguard", "ask-pcific", "pixel-trace"];',
|
|
226
|
+
"",
|
|
227
|
+
"function isAllowedTool(value: unknown): value is EmbedTool {",
|
|
228
|
+
' return typeof value === "string" && ALLOWED_TOOLS.has(value as EmbedTool);',
|
|
229
|
+
"}",
|
|
230
|
+
"",
|
|
231
|
+
"function resolveRequestedTools(raw: unknown): EmbedTool[] | null {",
|
|
232
|
+
" if (raw === undefined) return [...DEFAULT_TOOLS];",
|
|
233
|
+
" if (!Array.isArray(raw) || raw.length === 0) return null;",
|
|
234
|
+
" const filtered: EmbedTool[] = [];",
|
|
235
|
+
" for (const entry of raw) {",
|
|
236
|
+
" if (!isAllowedTool(entry)) return null;",
|
|
237
|
+
" if (!filtered.includes(entry)) filtered.push(entry);",
|
|
238
|
+
" }",
|
|
239
|
+
" return filtered;",
|
|
240
|
+
"}",
|
|
241
|
+
"",
|
|
242
|
+
"function readAppOrigin(): string | undefined {",
|
|
243
|
+
" const runtime = globalThis as { process?: { env?: Record<string, string | undefined> } };",
|
|
244
|
+
" const value = runtime.process?.env?.APP_ORIGIN?.trim();",
|
|
245
|
+
" return value ? value : undefined;",
|
|
246
|
+
"}",
|
|
247
|
+
];
|
|
248
|
+
}
|
|
249
|
+
return [
|
|
250
|
+
'const ALLOWED_TOOLS = new Set(["orbit", "safeguard", "ask-pcific", "pixel-trace", "message-check"]);',
|
|
251
|
+
'const DEFAULT_TOOLS = ["orbit", "safeguard", "ask-pcific", "pixel-trace"];',
|
|
252
|
+
"",
|
|
253
|
+
"function resolveRequestedTools(raw) {",
|
|
254
|
+
" if (raw === undefined) return [...DEFAULT_TOOLS];",
|
|
255
|
+
" if (!Array.isArray(raw) || raw.length === 0) return null;",
|
|
256
|
+
" const filtered = [];",
|
|
257
|
+
" for (const entry of raw) {",
|
|
258
|
+
' if (typeof entry !== "string" || !ALLOWED_TOOLS.has(entry)) return null;',
|
|
259
|
+
" if (!filtered.includes(entry)) filtered.push(entry);",
|
|
260
|
+
" }",
|
|
261
|
+
" return filtered;",
|
|
262
|
+
"}",
|
|
263
|
+
"",
|
|
264
|
+
"function readAppOrigin() {",
|
|
265
|
+
" const runtime = globalThis;",
|
|
266
|
+
" const value = runtime.process?.env?.APP_ORIGIN?.trim();",
|
|
267
|
+
" return value ? value : undefined;",
|
|
268
|
+
"}",
|
|
269
|
+
];
|
|
270
|
+
}
|
|
271
|
+
function buildStarterRouteContent(framework, clientImport, language) {
|
|
272
|
+
const isTs = language === "typescript";
|
|
273
|
+
const toolHelpers = buildAllowedToolsBlock(isTs);
|
|
274
|
+
if (framework === "nextjs-app") {
|
|
275
|
+
return [
|
|
276
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
277
|
+
"",
|
|
278
|
+
...toolHelpers,
|
|
279
|
+
"",
|
|
280
|
+
`export async function POST(request${isTs ? ": Request" : ""}) {`,
|
|
281
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
282
|
+
" try {",
|
|
283
|
+
" const trustedOrigin = readAppOrigin() ?? new URL(request.url).origin;",
|
|
284
|
+
' const secFetchSite = request.headers.get("sec-fetch-site");',
|
|
285
|
+
' const requestOrigin = request.headers.get("origin");',
|
|
286
|
+
"",
|
|
287
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
288
|
+
" return Response.json(",
|
|
289
|
+
" {",
|
|
290
|
+
' error: "Cross-site embed session requests are not allowed.",',
|
|
291
|
+
' tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server.",',
|
|
292
|
+
" },",
|
|
293
|
+
" { status: 403 },",
|
|
294
|
+
" );",
|
|
295
|
+
" }",
|
|
296
|
+
"",
|
|
297
|
+
" const body = await request.json().catch(() => ({}));",
|
|
298
|
+
" const tools = resolveRequestedTools(body?.tools);",
|
|
299
|
+
"",
|
|
300
|
+
" if (!tools) {",
|
|
301
|
+
" return Response.json(",
|
|
302
|
+
" {",
|
|
303
|
+
' error: "One or more requested tools are not allowed.",',
|
|
304
|
+
' tryThis: "Request only tools included in ALLOWED_TOOLS.",',
|
|
305
|
+
" },",
|
|
306
|
+
" { status: 400 },",
|
|
307
|
+
" );",
|
|
308
|
+
" }",
|
|
309
|
+
"",
|
|
310
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
311
|
+
"",
|
|
312
|
+
" return Response.json(session, { status: 201 });",
|
|
313
|
+
" } catch (failure) {",
|
|
314
|
+
" if (failure instanceof PcificApiError) {",
|
|
315
|
+
" return Response.json(",
|
|
316
|
+
" { error: failure.error, code: failure.code, tryThis: failure.tryThis },",
|
|
317
|
+
" { status: failure.status },",
|
|
318
|
+
" );",
|
|
319
|
+
" }",
|
|
320
|
+
"",
|
|
321
|
+
" return Response.json(",
|
|
322
|
+
" {",
|
|
323
|
+
' error: "Could not create a PCIFIC embed session.",',
|
|
324
|
+
' tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor.",',
|
|
325
|
+
" },",
|
|
326
|
+
" { status: 500 },",
|
|
327
|
+
" );",
|
|
328
|
+
" }",
|
|
329
|
+
"}",
|
|
330
|
+
"",
|
|
331
|
+
].join("\n");
|
|
332
|
+
}
|
|
333
|
+
if (framework === "nextjs-pages") {
|
|
334
|
+
return [
|
|
335
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
336
|
+
"",
|
|
337
|
+
...toolHelpers,
|
|
338
|
+
"",
|
|
339
|
+
isTs
|
|
340
|
+
? "export default async function handler(req: { method?: string; headers: Record<string, string | string[] | undefined>; body?: { tools?: unknown } }, res: { status: (code: number) => { json: (body: Record<string, unknown>) => void } }) {"
|
|
341
|
+
: "export default async function handler(req, res) {",
|
|
342
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
343
|
+
' if (req.method !== "POST") {',
|
|
344
|
+
' res.status(405).json({ error: "Method not allowed.", tryThis: "Send a POST request to create an embed session." });',
|
|
345
|
+
" return;",
|
|
346
|
+
" }",
|
|
347
|
+
"",
|
|
348
|
+
" try {",
|
|
349
|
+
' const host = typeof req.headers.host === "string" ? req.headers.host : "localhost:3000";',
|
|
350
|
+
" const trustedOrigin = readAppOrigin() ?? `https://${host}`;",
|
|
351
|
+
' const secFetchSite = req.headers["sec-fetch-site"];',
|
|
352
|
+
' const requestOrigin = typeof req.headers.origin === "string" ? req.headers.origin : undefined;',
|
|
353
|
+
"",
|
|
354
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
355
|
+
" res.status(403).json({",
|
|
356
|
+
' error: "Cross-site embed session requests are not allowed.",',
|
|
357
|
+
' tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server.",',
|
|
358
|
+
" });",
|
|
359
|
+
" return;",
|
|
360
|
+
" }",
|
|
361
|
+
"",
|
|
362
|
+
" const tools = resolveRequestedTools(req.body?.tools);",
|
|
363
|
+
"",
|
|
364
|
+
" if (!tools) {",
|
|
365
|
+
" res.status(400).json({",
|
|
366
|
+
' error: "One or more requested tools are not allowed.",',
|
|
367
|
+
' tryThis: "Request only tools included in ALLOWED_TOOLS.",',
|
|
368
|
+
" });",
|
|
369
|
+
" return;",
|
|
370
|
+
" }",
|
|
371
|
+
"",
|
|
372
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
373
|
+
" res.status(201).json(session);",
|
|
374
|
+
" } catch (failure) {",
|
|
375
|
+
" if (failure instanceof PcificApiError) {",
|
|
376
|
+
" res.status(failure.status).json({ error: failure.error, code: failure.code, tryThis: failure.tryThis });",
|
|
377
|
+
" return;",
|
|
378
|
+
" }",
|
|
379
|
+
"",
|
|
380
|
+
' res.status(500).json({ error: "Could not create a PCIFIC embed session.", tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor." });',
|
|
381
|
+
" }",
|
|
382
|
+
"}",
|
|
383
|
+
"",
|
|
384
|
+
].join("\n");
|
|
385
|
+
}
|
|
386
|
+
if (framework === "astro") {
|
|
387
|
+
return [
|
|
388
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
389
|
+
"",
|
|
390
|
+
...toolHelpers,
|
|
391
|
+
"",
|
|
392
|
+
`export async function POST({ request }${isTs ? ": { request: Request }" : ""}) {`,
|
|
393
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
394
|
+
" try {",
|
|
395
|
+
" const trustedOrigin = readAppOrigin() ?? new URL(request.url).origin;",
|
|
396
|
+
' const secFetchSite = request.headers.get("sec-fetch-site");',
|
|
397
|
+
' const requestOrigin = request.headers.get("origin");',
|
|
398
|
+
"",
|
|
399
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
400
|
+
" return new Response(",
|
|
401
|
+
' JSON.stringify({ error: "Cross-site embed session requests are not allowed.", tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server." }),',
|
|
402
|
+
' { status: 403, headers: { "content-type": "application/json" } },',
|
|
403
|
+
" );",
|
|
404
|
+
" }",
|
|
405
|
+
"",
|
|
406
|
+
" const body = await request.json().catch(() => ({}));",
|
|
407
|
+
" const tools = resolveRequestedTools(body?.tools);",
|
|
408
|
+
"",
|
|
409
|
+
" if (!tools) {",
|
|
410
|
+
" return new Response(",
|
|
411
|
+
' JSON.stringify({ error: "One or more requested tools are not allowed.", tryThis: "Request only tools included in ALLOWED_TOOLS." }),',
|
|
412
|
+
' { status: 400, headers: { "content-type": "application/json" } },',
|
|
413
|
+
" );",
|
|
414
|
+
" }",
|
|
415
|
+
"",
|
|
416
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
417
|
+
"",
|
|
418
|
+
' return new Response(JSON.stringify(session), { status: 201, headers: { "content-type": "application/json" } });',
|
|
419
|
+
" } catch (failure) {",
|
|
420
|
+
" if (failure instanceof PcificApiError) {",
|
|
421
|
+
" return new Response(",
|
|
422
|
+
" JSON.stringify({ error: failure.error, code: failure.code, tryThis: failure.tryThis }),",
|
|
423
|
+
' { status: failure.status, headers: { "content-type": "application/json" } },',
|
|
424
|
+
" );",
|
|
425
|
+
" }",
|
|
426
|
+
"",
|
|
427
|
+
" return new Response(",
|
|
428
|
+
' JSON.stringify({ error: "Could not create a PCIFIC embed session.", tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor." }),',
|
|
429
|
+
' { status: 500, headers: { "content-type": "application/json" } },',
|
|
430
|
+
" );",
|
|
431
|
+
" }",
|
|
432
|
+
"}",
|
|
433
|
+
"",
|
|
434
|
+
].join("\n");
|
|
435
|
+
}
|
|
436
|
+
if (framework === "sveltekit") {
|
|
437
|
+
return [
|
|
438
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
439
|
+
"",
|
|
440
|
+
...toolHelpers,
|
|
441
|
+
"",
|
|
442
|
+
`export async function POST({ request, url }${isTs ? ": { request: Request; url: URL }" : ""}) {`,
|
|
443
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
444
|
+
" try {",
|
|
445
|
+
" const trustedOrigin = readAppOrigin() ?? url.origin;",
|
|
446
|
+
' const secFetchSite = request.headers.get("sec-fetch-site");',
|
|
447
|
+
' const requestOrigin = request.headers.get("origin");',
|
|
448
|
+
"",
|
|
449
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
450
|
+
" return Response.json(",
|
|
451
|
+
' { error: "Cross-site embed session requests are not allowed.", tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server." },',
|
|
452
|
+
" { status: 403 },",
|
|
453
|
+
" );",
|
|
454
|
+
" }",
|
|
455
|
+
"",
|
|
456
|
+
" const body = await request.json().catch(() => ({}));",
|
|
457
|
+
" const tools = resolveRequestedTools(body?.tools);",
|
|
458
|
+
"",
|
|
459
|
+
" if (!tools) {",
|
|
460
|
+
" return Response.json(",
|
|
461
|
+
' { error: "One or more requested tools are not allowed.", tryThis: "Request only tools included in ALLOWED_TOOLS." },',
|
|
462
|
+
" { status: 400 },",
|
|
463
|
+
" );",
|
|
464
|
+
" }",
|
|
465
|
+
"",
|
|
466
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
467
|
+
"",
|
|
468
|
+
" return Response.json(session, { status: 201 });",
|
|
469
|
+
" } catch (failure) {",
|
|
470
|
+
" if (failure instanceof PcificApiError) {",
|
|
471
|
+
" return Response.json({ error: failure.error, code: failure.code, tryThis: failure.tryThis }, { status: failure.status });",
|
|
472
|
+
" }",
|
|
473
|
+
"",
|
|
474
|
+
' return Response.json({ error: "Could not create a PCIFIC embed session.", tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor." }, { status: 500 });',
|
|
475
|
+
" }",
|
|
476
|
+
"}",
|
|
477
|
+
"",
|
|
478
|
+
].join("\n");
|
|
479
|
+
}
|
|
480
|
+
if (framework === "remix") {
|
|
481
|
+
return [
|
|
482
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
483
|
+
"",
|
|
484
|
+
...toolHelpers,
|
|
485
|
+
"",
|
|
486
|
+
`export async function action({ request }${isTs ? ": { request: Request }" : ""}) {`,
|
|
487
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
488
|
+
" try {",
|
|
489
|
+
" const trustedOrigin = readAppOrigin() ?? new URL(request.url).origin;",
|
|
490
|
+
' const secFetchSite = request.headers.get("sec-fetch-site");',
|
|
491
|
+
' const requestOrigin = request.headers.get("origin");',
|
|
492
|
+
"",
|
|
493
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
494
|
+
" return Response.json(",
|
|
495
|
+
' { error: "Cross-site embed session requests are not allowed.", tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server." },',
|
|
496
|
+
" { status: 403 },",
|
|
497
|
+
" );",
|
|
498
|
+
" }",
|
|
499
|
+
"",
|
|
500
|
+
" const body = await request.json().catch(() => ({}));",
|
|
501
|
+
" const tools = resolveRequestedTools(body?.tools);",
|
|
502
|
+
"",
|
|
503
|
+
" if (!tools) {",
|
|
504
|
+
" return Response.json(",
|
|
505
|
+
' { error: "One or more requested tools are not allowed.", tryThis: "Request only tools included in ALLOWED_TOOLS." },',
|
|
506
|
+
" { status: 400 },",
|
|
507
|
+
" );",
|
|
508
|
+
" }",
|
|
509
|
+
"",
|
|
510
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
511
|
+
"",
|
|
512
|
+
" return Response.json(session, { status: 201 });",
|
|
513
|
+
" } catch (failure) {",
|
|
514
|
+
" if (failure instanceof PcificApiError) {",
|
|
515
|
+
" return Response.json({ error: failure.error, code: failure.code, tryThis: failure.tryThis }, { status: failure.status });",
|
|
516
|
+
" }",
|
|
517
|
+
"",
|
|
518
|
+
' return Response.json({ error: "Could not create a PCIFIC embed session.", tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor." }, { status: 500 });',
|
|
519
|
+
" }",
|
|
520
|
+
"}",
|
|
521
|
+
"",
|
|
522
|
+
].join("\n");
|
|
523
|
+
}
|
|
524
|
+
return [
|
|
525
|
+
`import { getPcific, PcificApiError } from "${clientImport}";`,
|
|
526
|
+
"",
|
|
527
|
+
...toolHelpers,
|
|
528
|
+
"",
|
|
529
|
+
"/**",
|
|
530
|
+
" * Mount this handler on POST /api/pcific/embed-session in your server.",
|
|
531
|
+
" */",
|
|
532
|
+
isTs
|
|
533
|
+
? "export async function handlePcificEmbedSession(req: { headers?: Record<string, string | string[] | undefined>; protocol?: string; body?: { tools?: unknown } }, res?: { status: (code: number) => { json: (body: Record<string, unknown>) => void } }) {"
|
|
534
|
+
: "export async function handlePcificEmbedSession(req, res) {",
|
|
535
|
+
" // TODO: verify your signed-in user session before minting a PCIFIC embed session.",
|
|
536
|
+
" const respond = (status" + (isTs ? ": number" : "") + ", body" + (isTs ? ": Record<string, unknown>" : "") + ") => {",
|
|
537
|
+
" if (res) {",
|
|
538
|
+
" res.status(status).json(body);",
|
|
539
|
+
" }",
|
|
540
|
+
" return { status, body };",
|
|
541
|
+
" };",
|
|
542
|
+
"",
|
|
543
|
+
" try {",
|
|
544
|
+
' const headers = req?.headers ?? {};',
|
|
545
|
+
' const host = typeof headers.host === "string" ? headers.host : "localhost:3000";',
|
|
546
|
+
' const proto = req?.protocol ?? "https";',
|
|
547
|
+
" const trustedOrigin = readAppOrigin() ?? `${proto}://${host}`;",
|
|
548
|
+
' const secFetchSite = headers["sec-fetch-site"];',
|
|
549
|
+
' const requestOrigin = typeof headers.origin === "string" ? headers.origin : undefined;',
|
|
550
|
+
"",
|
|
551
|
+
' if (secFetchSite === "cross-site" || (requestOrigin && requestOrigin !== trustedOrigin)) {',
|
|
552
|
+
" return respond(403, {",
|
|
553
|
+
' error: "Cross-site embed session requests are not allowed.",',
|
|
554
|
+
' tryThis: "Call this endpoint from your own application origin and configure APP_ORIGIN on the server.",',
|
|
555
|
+
" });",
|
|
556
|
+
" }",
|
|
557
|
+
"",
|
|
558
|
+
" const tools = resolveRequestedTools(req?.body?.tools);",
|
|
559
|
+
"",
|
|
560
|
+
" if (!tools) {",
|
|
561
|
+
" return respond(400, {",
|
|
562
|
+
' error: "One or more requested tools are not allowed.",',
|
|
563
|
+
' tryThis: "Request only tools included in ALLOWED_TOOLS.",',
|
|
564
|
+
" });",
|
|
565
|
+
" }",
|
|
566
|
+
"",
|
|
567
|
+
" const session = await getPcific().embed.createSession({ origin: trustedOrigin, tools });",
|
|
568
|
+
"",
|
|
569
|
+
" return respond(201, session as Record<string, unknown>);".replace(isTs ? "" : " as Record<string, unknown>", ""),
|
|
570
|
+
" } catch (failure) {",
|
|
571
|
+
" if (failure instanceof PcificApiError) {",
|
|
572
|
+
" return respond(failure.status, {",
|
|
573
|
+
" error: failure.error,",
|
|
574
|
+
" code: failure.code,",
|
|
575
|
+
" tryThis: failure.tryThis,",
|
|
576
|
+
" });",
|
|
577
|
+
" }",
|
|
578
|
+
"",
|
|
579
|
+
" return respond(500, {",
|
|
580
|
+
' error: "Could not create a PCIFIC embed session.",',
|
|
581
|
+
' tryThis: "Check PCIFIC_TEST_KEY in .env and run npx pcific doctor.",',
|
|
582
|
+
" });",
|
|
583
|
+
" }",
|
|
584
|
+
"}",
|
|
585
|
+
"",
|
|
586
|
+
].join("\n");
|
|
587
|
+
}
|
|
588
|
+
export function buildPcificGuide(options) {
|
|
589
|
+
const lines = [
|
|
590
|
+
"# PCIFIC Integration Guide",
|
|
591
|
+
"",
|
|
592
|
+
`<!-- @pcific-generated ${options.date} mode=${options.mode} -->`,
|
|
593
|
+
"",
|
|
594
|
+
`- Mode: \`${options.mode}\``,
|
|
595
|
+
`- Generated: \`${options.date}\``,
|
|
596
|
+
`- Managed path: \`${options.targetDir}\``,
|
|
597
|
+
`- Client import: \`${options.clientImportPath}\``,
|
|
598
|
+
];
|
|
599
|
+
if (options.kitImportPath) {
|
|
600
|
+
lines.push(`- PCIFIC Kit import: \`${options.kitImportPath}\``);
|
|
601
|
+
}
|
|
602
|
+
if (options.routePath) {
|
|
603
|
+
lines.push(`- Embed session route: \`${options.routePath}\``);
|
|
604
|
+
}
|
|
605
|
+
lines.push("", "## Docs and Changelog", "", `- Full docs for agents: ${options.baseUrl}/llms.txt`, `- Changes since this setup: ${options.baseUrl}/changelog.txt?since=${options.date}`, "", "## CLI Commands", "", "- Verify keys, usage, and local setup: `npx pcific doctor`", "- Check changelog and refresh generated SDK files: `npx pcific sync`", "- Push listing field schemas: `npx pcific schema push`", "- Start the local MCP server for coding agents: `npx pcific mcp`", "", "## Environment Rules", "", "- Local development, CLI commands, and coding agents use `PCIFIC_TEST_KEY` only (never `pcific_live_...`).", "- `.env` holds your test key and must stay listed in `.gitignore`.", "- Set `PCIFIC_LIVE_KEY` only in your production deployment environment.", "");
|
|
606
|
+
return lines.join("\n");
|
|
607
|
+
}
|
|
608
|
+
function isKitTemplateEntry(entry) {
|
|
609
|
+
return entry === "kit.ts" || entry === "kit.js" || entry === "kit.d.ts";
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Generates PCIFIC client files, optional PCIFIC Kit export, optional starter route,
|
|
613
|
+
* and `PCIFIC.md` for Copy mode or Package mode.
|
|
614
|
+
*/
|
|
615
|
+
export function scaffoldProject(options) {
|
|
616
|
+
const date = options.date ?? formatIsoDate();
|
|
617
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
618
|
+
const rawLibDir = (options.libDir ?? options.project.defaultLibDir).replace(/\/+$/, "") || ".";
|
|
619
|
+
resolveInsideWorkspace(options.cwd, rawLibDir);
|
|
620
|
+
const libDir = rawLibDir;
|
|
621
|
+
const language = options.project.language;
|
|
622
|
+
const withKit = options.withKit ?? shouldIncludeKitByDefault(options.project.framework);
|
|
623
|
+
const withRoute = options.withRoute ?? shouldGenerateRouteByDefault(options.project.framework);
|
|
624
|
+
const filesWritten = [];
|
|
625
|
+
const filesSkipped = [];
|
|
626
|
+
let targetDir;
|
|
627
|
+
let clientFile;
|
|
628
|
+
let kitFile;
|
|
629
|
+
if (options.mode === "copy") {
|
|
630
|
+
const destDir = resolveInsideWorkspace(options.cwd, path.join(libDir, "pcific"));
|
|
631
|
+
mkdirSync(destDir, { recursive: true });
|
|
632
|
+
targetDir = path.relative(options.cwd, destDir).replace(/\\/g, "/");
|
|
633
|
+
const sourceDir = resolveTemplateSourceDir(language);
|
|
634
|
+
const stamp = makeStampHeader(date, "copy");
|
|
635
|
+
for (const entry of readdirSync(sourceDir)) {
|
|
636
|
+
if (!withKit && isKitTemplateEntry(entry)) {
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if (language === "typescript" && (!entry.endsWith(".ts") || entry.endsWith(".test.ts"))) {
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (language === "javascript" && !entry.endsWith(".js") && !entry.endsWith(".d.ts")) {
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
const raw = readFileSync(path.join(sourceDir, entry), "utf8");
|
|
646
|
+
let content = `${stamp}${raw}`;
|
|
647
|
+
if (entry === "index.ts" || entry === "index.js" || entry === "index.d.ts") {
|
|
648
|
+
content = `${content}\nexport { getPcific } from "./client-instance.js";\n`;
|
|
649
|
+
}
|
|
650
|
+
const outPath = path.join(destDir, entry);
|
|
651
|
+
writeFileSync(outPath, content, "utf8");
|
|
652
|
+
filesWritten.push(path.relative(options.cwd, outPath).replace(/\\/g, "/"));
|
|
653
|
+
}
|
|
654
|
+
if (language === "typescript") {
|
|
655
|
+
const instancePath = path.join(destDir, "client-instance.ts");
|
|
656
|
+
writeFileSync(instancePath, createCopyClientInstanceTs(date), "utf8");
|
|
657
|
+
filesWritten.push(path.relative(options.cwd, instancePath).replace(/\\/g, "/"));
|
|
658
|
+
clientFile = path.relative(options.cwd, path.join(destDir, "index.ts")).replace(/\\/g, "/");
|
|
659
|
+
kitFile = withKit
|
|
660
|
+
? path.relative(options.cwd, path.join(destDir, "kit.ts")).replace(/\\/g, "/")
|
|
661
|
+
: undefined;
|
|
662
|
+
}
|
|
663
|
+
else {
|
|
664
|
+
const instanceJsPath = path.join(destDir, "client-instance.js");
|
|
665
|
+
const instanceDtsPath = path.join(destDir, "client-instance.d.ts");
|
|
666
|
+
writeFileSync(instanceJsPath, createCopyClientInstanceJs(date), "utf8");
|
|
667
|
+
writeFileSync(instanceDtsPath, createCopyClientInstanceDts(date), "utf8");
|
|
668
|
+
filesWritten.push(path.relative(options.cwd, instanceJsPath).replace(/\\/g, "/"));
|
|
669
|
+
filesWritten.push(path.relative(options.cwd, instanceDtsPath).replace(/\\/g, "/"));
|
|
670
|
+
clientFile = path.relative(options.cwd, path.join(destDir, "index.js")).replace(/\\/g, "/");
|
|
671
|
+
kitFile = withKit
|
|
672
|
+
? path.relative(options.cwd, path.join(destDir, "kit.js")).replace(/\\/g, "/")
|
|
673
|
+
: undefined;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
const destDir = resolveInsideWorkspace(options.cwd, libDir);
|
|
678
|
+
mkdirSync(destDir, { recursive: true });
|
|
679
|
+
targetDir = path.relative(options.cwd, destDir).replace(/\\/g, "/") || ".";
|
|
680
|
+
const fileName = language === "typescript" ? "pcific.ts" : "pcific.mjs";
|
|
681
|
+
const outPath = path.join(destDir, fileName);
|
|
682
|
+
const content = language === "typescript"
|
|
683
|
+
? createPackageClientTs(date, withKit)
|
|
684
|
+
: createPackageClientJs(date, withKit);
|
|
685
|
+
writeFileSync(outPath, content, "utf8");
|
|
686
|
+
clientFile = path.relative(options.cwd, outPath).replace(/\\/g, "/");
|
|
687
|
+
filesWritten.push(clientFile);
|
|
688
|
+
kitFile = withKit ? "@pcific/sdk/kit" : undefined;
|
|
689
|
+
}
|
|
690
|
+
let routeFile;
|
|
691
|
+
if (withRoute) {
|
|
692
|
+
const relRoute = resolveStarterRoutePath(options.cwd, options.project.framework, options.project.srcDir, libDir, language);
|
|
693
|
+
const absRoute = resolveInsideWorkspace(options.cwd, relRoute);
|
|
694
|
+
routeFile = relRoute.replace(/\\/g, "/");
|
|
695
|
+
if (existsSync(absRoute) && !options.overwriteRoute) {
|
|
696
|
+
filesSkipped.push(routeFile);
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
mkdirSync(path.dirname(absRoute), { recursive: true });
|
|
700
|
+
const absClient = path.join(options.cwd, clientFile);
|
|
701
|
+
const clientImport = stripTsExtensionForImport(toPosixRelative(absRoute, absClient));
|
|
702
|
+
writeFileSync(absRoute, buildStarterRouteContent(options.project.framework, clientImport, language), "utf8");
|
|
703
|
+
filesWritten.push(routeFile);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
const guidePath = path.join(options.cwd, "PCIFIC.md");
|
|
707
|
+
const guideContent = buildPcificGuide({
|
|
708
|
+
mode: options.mode,
|
|
709
|
+
date,
|
|
710
|
+
baseUrl,
|
|
711
|
+
clientImportPath: `./${clientFile}`,
|
|
712
|
+
kitImportPath: kitFile?.startsWith("@") ? kitFile : kitFile ? `./${kitFile}` : undefined,
|
|
713
|
+
routePath: routeFile,
|
|
714
|
+
targetDir,
|
|
715
|
+
});
|
|
716
|
+
writeFileSync(guidePath, guideContent, "utf8");
|
|
717
|
+
filesWritten.push("PCIFIC.md");
|
|
718
|
+
return {
|
|
719
|
+
mode: options.mode,
|
|
720
|
+
date,
|
|
721
|
+
targetDir,
|
|
722
|
+
clientFile,
|
|
723
|
+
kitFile,
|
|
724
|
+
routeFile,
|
|
725
|
+
guideFile: "PCIFIC.md",
|
|
726
|
+
filesWritten,
|
|
727
|
+
filesSkipped,
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Returns the list of managed Copy-mode files that would be refreshed by `pcific sync`.
|
|
732
|
+
*/
|
|
733
|
+
export function listManagedCopyFiles(options) {
|
|
734
|
+
const absTarget = resolveInsideWorkspace(options.cwd, options.targetDir);
|
|
735
|
+
const sourceDir = resolveTemplateSourceDir(options.language);
|
|
736
|
+
const includeKit = options.withKit ??
|
|
737
|
+
(existsSync(path.join(absTarget, "kit.ts")) || existsSync(path.join(absTarget, "kit.js")));
|
|
738
|
+
const files = [];
|
|
739
|
+
for (const entry of readdirSync(sourceDir)) {
|
|
740
|
+
if (!includeKit && isKitTemplateEntry(entry)) {
|
|
741
|
+
continue;
|
|
742
|
+
}
|
|
743
|
+
if (options.language === "typescript" &&
|
|
744
|
+
(!entry.endsWith(".ts") || entry.endsWith(".test.ts"))) {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
if (options.language === "javascript" &&
|
|
748
|
+
!entry.endsWith(".js") &&
|
|
749
|
+
!entry.endsWith(".d.ts")) {
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
files.push(path.relative(options.cwd, path.join(absTarget, entry)).replace(/\\/g, "/"));
|
|
753
|
+
}
|
|
754
|
+
if (options.language === "typescript") {
|
|
755
|
+
files.push(path.relative(options.cwd, path.join(absTarget, "client-instance.ts")).replace(/\\/g, "/"));
|
|
756
|
+
}
|
|
757
|
+
else {
|
|
758
|
+
files.push(path.relative(options.cwd, path.join(absTarget, "client-instance.js")).replace(/\\/g, "/"));
|
|
759
|
+
files.push(path.relative(options.cwd, path.join(absTarget, "client-instance.d.ts")).replace(/\\/g, "/"));
|
|
760
|
+
}
|
|
761
|
+
if (existsSync(path.join(options.cwd, "PCIFIC.md"))) {
|
|
762
|
+
files.push("PCIFIC.md");
|
|
763
|
+
}
|
|
764
|
+
return files;
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Refreshes ONLY the managed generated SDK files inside `targetDir` during `pcific sync`.
|
|
768
|
+
* Never touches user starter routes or custom app files.
|
|
769
|
+
*/
|
|
770
|
+
export function refreshManagedCopyFiles(options) {
|
|
771
|
+
const date = options.date ?? formatIsoDate();
|
|
772
|
+
const absTarget = resolveInsideWorkspace(options.cwd, options.targetDir);
|
|
773
|
+
mkdirSync(absTarget, { recursive: true });
|
|
774
|
+
const includeKit = options.withKit ??
|
|
775
|
+
(existsSync(path.join(absTarget, "kit.ts")) || existsSync(path.join(absTarget, "kit.js")));
|
|
776
|
+
const sourceDir = resolveTemplateSourceDir(options.language);
|
|
777
|
+
const stamp = makeStampHeader(date, "copy");
|
|
778
|
+
const filesUpdated = [];
|
|
779
|
+
for (const entry of readdirSync(sourceDir)) {
|
|
780
|
+
if (!includeKit && isKitTemplateEntry(entry)) {
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
if (options.language === "typescript" &&
|
|
784
|
+
(!entry.endsWith(".ts") || entry.endsWith(".test.ts"))) {
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
if (options.language === "javascript" &&
|
|
788
|
+
!entry.endsWith(".js") &&
|
|
789
|
+
!entry.endsWith(".d.ts")) {
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
const raw = readFileSync(path.join(sourceDir, entry), "utf8");
|
|
793
|
+
let content = `${stamp}${raw}`;
|
|
794
|
+
if (entry === "index.ts" || entry === "index.js" || entry === "index.d.ts") {
|
|
795
|
+
content = `${content}\nexport { getPcific } from "./client-instance.js";\n`;
|
|
796
|
+
}
|
|
797
|
+
const outPath = path.join(absTarget, entry);
|
|
798
|
+
writeFileSync(outPath, content, "utf8");
|
|
799
|
+
filesUpdated.push(path.relative(options.cwd, outPath).replace(/\\/g, "/"));
|
|
800
|
+
}
|
|
801
|
+
if (options.language === "typescript") {
|
|
802
|
+
const instancePath = path.join(absTarget, "client-instance.ts");
|
|
803
|
+
writeFileSync(instancePath, createCopyClientInstanceTs(date), "utf8");
|
|
804
|
+
filesUpdated.push(path.relative(options.cwd, instancePath).replace(/\\/g, "/"));
|
|
805
|
+
}
|
|
806
|
+
else {
|
|
807
|
+
const instanceJsPath = path.join(absTarget, "client-instance.js");
|
|
808
|
+
const instanceDtsPath = path.join(absTarget, "client-instance.d.ts");
|
|
809
|
+
writeFileSync(instanceJsPath, createCopyClientInstanceJs(date), "utf8");
|
|
810
|
+
writeFileSync(instanceDtsPath, createCopyClientInstanceDts(date), "utf8");
|
|
811
|
+
filesUpdated.push(path.relative(options.cwd, instanceJsPath).replace(/\\/g, "/"));
|
|
812
|
+
filesUpdated.push(path.relative(options.cwd, instanceDtsPath).replace(/\\/g, "/"));
|
|
813
|
+
}
|
|
814
|
+
// Update PCIFIC.md generated date stamp if present.
|
|
815
|
+
const guidePath = path.join(options.cwd, "PCIFIC.md");
|
|
816
|
+
if (existsSync(guidePath)) {
|
|
817
|
+
const existing = readFileSync(guidePath, "utf8");
|
|
818
|
+
const updated = existing
|
|
819
|
+
.replace(/<!-- @pcific-generated \d{4}-\d{2}-\d{2} mode=copy -->/, `<!-- @pcific-generated ${date} mode=copy -->`)
|
|
820
|
+
.replace(/- Generated: `\d{4}-\d{2}-\d{2}`/, `- Generated: \`${date}\``)
|
|
821
|
+
.replace(/\?since=\d{4}-\d{2}-\d{2}/, `?since=${date}`);
|
|
822
|
+
writeFileSync(guidePath, updated, "utf8");
|
|
823
|
+
filesUpdated.push("PCIFIC.md");
|
|
824
|
+
}
|
|
825
|
+
return { date, filesUpdated };
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Reads generation metadata from `PCIFIC.md` or stamped files in the workspace.
|
|
829
|
+
*/
|
|
830
|
+
export function readPcificGenerationMeta(cwd, project) {
|
|
831
|
+
const guidePath = path.join(cwd, "PCIFIC.md");
|
|
832
|
+
if (existsSync(guidePath)) {
|
|
833
|
+
const content = readFileSync(guidePath, "utf8");
|
|
834
|
+
const stampMatch = content.match(STAMP_PATTERN);
|
|
835
|
+
const managedMatch = content.match(/^- Managed path: `([^`]+)`/m);
|
|
836
|
+
const clientMatch = content.match(/^- Client import: `([^`]+)`/m);
|
|
837
|
+
const kitMatch = content.match(/^- PCIFIC Kit import: `([^`]+)`/m);
|
|
838
|
+
const routeMatch = content.match(/^- Embed session route: `([^`]+)`/m);
|
|
839
|
+
if (stampMatch) {
|
|
840
|
+
const mode = stampMatch[2] === "package" ? "package" : "copy";
|
|
841
|
+
return {
|
|
842
|
+
mode,
|
|
843
|
+
date: stampMatch[1],
|
|
844
|
+
targetDir: managedMatch?.[1] ?? project.existingCopyDir,
|
|
845
|
+
clientFile: clientMatch?.[1],
|
|
846
|
+
kitFile: kitMatch?.[1],
|
|
847
|
+
routeFile: routeMatch?.[1],
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (project.existingCopyDir) {
|
|
852
|
+
const candidates = ["index.ts", "index.js", "client.ts", "client.js"];
|
|
853
|
+
for (const file of candidates) {
|
|
854
|
+
const candidatePath = path.join(cwd, project.existingCopyDir, file);
|
|
855
|
+
if (!existsSync(candidatePath))
|
|
856
|
+
continue;
|
|
857
|
+
const firstLine = readFileSync(candidatePath, "utf8").split(/\r?\n/, 1)[0] ?? "";
|
|
858
|
+
const match = firstLine.match(STAMP_PATTERN);
|
|
859
|
+
if (match) {
|
|
860
|
+
return {
|
|
861
|
+
mode: match[2] === "package" ? "package" : "copy",
|
|
862
|
+
date: match[1],
|
|
863
|
+
targetDir: project.existingCopyDir,
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
return {
|
|
868
|
+
mode: "copy",
|
|
869
|
+
targetDir: project.existingCopyDir,
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
if (project.existingMode === "package") {
|
|
873
|
+
return { mode: "package" };
|
|
874
|
+
}
|
|
875
|
+
return null;
|
|
876
|
+
}
|
|
877
|
+
export function packageInstallCommand(packageManager) {
|
|
878
|
+
if (packageManager === "pnpm") {
|
|
879
|
+
return { command: "pnpm", args: ["add", "@pcific/sdk"], display: "pnpm add @pcific/sdk" };
|
|
880
|
+
}
|
|
881
|
+
if (packageManager === "yarn") {
|
|
882
|
+
return { command: "yarn", args: ["add", "@pcific/sdk"], display: "yarn add @pcific/sdk" };
|
|
883
|
+
}
|
|
884
|
+
if (packageManager === "bun") {
|
|
885
|
+
return { command: "bun", args: ["add", "@pcific/sdk"], display: "bun add @pcific/sdk" };
|
|
886
|
+
}
|
|
887
|
+
return { command: "npm", args: ["install", "@pcific/sdk"], display: "npm install @pcific/sdk" };
|
|
888
|
+
}
|
|
889
|
+
export function packageUpdateCommand(packageManager) {
|
|
890
|
+
if (packageManager === "pnpm") {
|
|
891
|
+
return { command: "pnpm", args: ["update", "@pcific/sdk"], display: "pnpm update @pcific/sdk" };
|
|
892
|
+
}
|
|
893
|
+
if (packageManager === "yarn") {
|
|
894
|
+
return { command: "yarn", args: ["upgrade", "@pcific/sdk"], display: "yarn upgrade @pcific/sdk" };
|
|
895
|
+
}
|
|
896
|
+
if (packageManager === "bun") {
|
|
897
|
+
return { command: "bun", args: ["update", "@pcific/sdk"], display: "bun update @pcific/sdk" };
|
|
898
|
+
}
|
|
899
|
+
return { command: "npm", args: ["update", "@pcific/sdk"], display: "npm update @pcific/sdk" };
|
|
900
|
+
}
|
|
901
|
+
export function resolvePackageManagerBinary(command, platform = process.platform) {
|
|
902
|
+
if (platform === "win32" && (command === "npm" || command === "pnpm" || command === "yarn")) {
|
|
903
|
+
return `${command}.cmd`;
|
|
904
|
+
}
|
|
905
|
+
return command;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Runs the detected package manager to install or update `@pcific/sdk`.
|
|
909
|
+
*/
|
|
910
|
+
export function runPackageManagerCommand(cwd, command, args) {
|
|
911
|
+
const binary = resolvePackageManagerBinary(command);
|
|
912
|
+
return new Promise((resolve, reject) => {
|
|
913
|
+
execFile(binary, args, { cwd, timeout: 120_000 }, (error, _stdout, stderr) => {
|
|
914
|
+
if (error) {
|
|
915
|
+
const detail = stderr.trim() || error.message;
|
|
916
|
+
reject(new CliError(`Failed to run "${command} ${args.join(" ")}": ${detail}`, {
|
|
917
|
+
code: "PACKAGE_INSTALL_FAILED",
|
|
918
|
+
tryThis: `Run "${command} ${args.join(" ")}" manually, or use --mode copy for zero dependencies.`,
|
|
919
|
+
}));
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
resolve();
|
|
923
|
+
});
|
|
924
|
+
});
|
|
925
|
+
}
|