critiqs-react 0.3.0 → 0.5.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/AGENT_SETUP.md +198 -66
- package/README.md +214 -31
- package/bin/critiqs.mjs +3 -1
- package/dist/index.js +16877 -4770
- package/dist/server/index.d.ts +1 -87
- package/dist/server/index.js +1 -4889
- package/package.json +6 -5
- package/bin/cli.d.mts +0 -21
- package/bin/cli.mjs +0 -293
- package/bin/env.d.mts +0 -41
- package/bin/env.mjs +0 -384
- package/bin/init.d.mts +0 -126
- package/bin/init.mjs +0 -965
- package/bin/mcp.d.mts +0 -20
- package/bin/mcp.mjs +0 -314
- package/bin/setup.d.mts +0 -183
- package/bin/setup.mjs +0 -1054
- package/dist/backend/convex/_generated/api.d.ts +0 -95
- package/dist/backend/convex/_generated/api.js +0 -23
- package/dist/backend/convex/_generated/dataModel.d.ts +0 -60
- package/dist/backend/convex/_generated/server.d.ts +0 -162
- package/dist/backend/convex/_generated/server.js +0 -101
- package/dist/backend/convex/ai.ts +0 -93
- package/dist/backend/convex/aiSettings.ts +0 -43
- package/dist/backend/convex/auth.config.ts +0 -18
- package/dist/backend/convex/captureHttp.ts +0 -96
- package/dist/backend/convex/captures.ts +0 -167
- package/dist/backend/convex/crons.ts +0 -14
- package/dist/backend/convex/deviceSignIn.ts +0 -151
- package/dist/backend/convex/grouping.ts +0 -41
- package/dist/backend/convex/http.ts +0 -724
- package/dist/backend/convex/lib/ai.ts +0 -6
- package/dist/backend/convex/lib/links.ts +0 -12
- package/dist/backend/convex/lib/pages.ts +0 -207
- package/dist/backend/convex/lib/r2.ts +0 -75
- package/dist/backend/convex/lib/store.ts +0 -509
- package/dist/backend/convex/lib/tokens.ts +0 -101
- package/dist/backend/convex/lib/validators.ts +0 -73
- package/dist/backend/convex/lib/vendor/aws4fetch.js +0 -289
- package/dist/backend/convex/lib/vendor/critiqs_ai.js +0 -49081
- package/dist/backend/convex/lib/vendor/critiqs_core.js +0 -385
- package/dist/backend/convex/lib/vendor/critiqs_server.js +0 -3108
- package/dist/backend/convex/notificationEmails.ts +0 -61
- package/dist/backend/convex/notifications.ts +0 -182
- package/dist/backend/convex/plans.ts +0 -67
- package/dist/backend/convex/projects.ts +0 -46
- package/dist/backend/convex/schema.ts +0 -343
- package/dist/backend/convex/search.ts +0 -26
- package/dist/backend/convex/signIn.ts +0 -368
- package/dist/backend/convex/tags.ts +0 -68
- package/dist/backend/convex/threads.ts +0 -146
- package/dist/backend/convex/users.ts +0 -13
- package/dist/server/chunks/driver-n9zpr0k3.js +0 -21
- package/dist/server/chunks/index-9bg7tmnq.js +0 -522
- package/dist/server/chunks/index-askcfn7t.js +0 -148
- package/dist/server/chunks/providers-rv184xvj.js +0 -48444
- package/dist/server/chunks/token-kzddms7r.js +0 -63
- package/dist/server/chunks/token-util-k8bee1wc.js +0 -4
package/bin/setup.mjs
DELETED
|
@@ -1,1054 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Critiqs's setup steps, shared by `critiqs init`, `critiqs doctor`, and the MCP
|
|
3
|
-
* server so people and coding agents set up Critiqs the same way. Dependency-free
|
|
4
|
-
* so it runs under Node and Bun without a build.
|
|
5
|
-
*/
|
|
6
|
-
import { spawn } from "node:child_process";
|
|
7
|
-
import { randomBytes } from "node:crypto";
|
|
8
|
-
import { accessSync, constants, cpSync, existsSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { createServer } from "node:http";
|
|
10
|
-
import { createRequire } from "node:module";
|
|
11
|
-
import { dirname, join, relative, resolve } from "node:path";
|
|
12
|
-
import { fileURLToPath } from "node:url";
|
|
13
|
-
import { applyEnv, checkWritable, describeApp, envVariableOf, gitIgnored, planEnv, readEnvValue } from "./env.mjs";
|
|
14
|
-
import {
|
|
15
|
-
applyPlan,
|
|
16
|
-
chooseWiring,
|
|
17
|
-
connectionProps,
|
|
18
|
-
deploymentAdvice,
|
|
19
|
-
findCritiqsUsages,
|
|
20
|
-
isValidProjectId,
|
|
21
|
-
MOUNT_KINDS,
|
|
22
|
-
planComponent,
|
|
23
|
-
propsText,
|
|
24
|
-
readProp,
|
|
25
|
-
refusal,
|
|
26
|
-
workspaceApps,
|
|
27
|
-
workspaceRefusal,
|
|
28
|
-
} from "./init.mjs";
|
|
29
|
-
|
|
30
|
-
/** Critiqs Cloud's deployment, the component's default backend. Matches `HOSTED_BACKEND_URL`. */
|
|
31
|
-
export const CLOUD_BACKEND_URL = "https://brazen-snail-591.convex.cloud";
|
|
32
|
-
/** The backend version this package needs. Matches `BACKEND_PROTOCOL`. */
|
|
33
|
-
export const BACKEND_PROTOCOL = 5;
|
|
34
|
-
/** The sign-in service version this package needs, unchanged since protocol 4. Matches `SIGN_IN_PROTOCOL`. */
|
|
35
|
-
export const SIGN_IN_PROTOCOL = 4;
|
|
36
|
-
|
|
37
|
-
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
38
|
-
|
|
39
|
-
export class SetupError extends Error {}
|
|
40
|
-
|
|
41
|
-
/** A path as people read it: relative inside the current folder, absolute outside it. */
|
|
42
|
-
function shown(cwd, path) {
|
|
43
|
-
const near = relative(cwd, path);
|
|
44
|
-
return near === "" ? "this folder" : near.startsWith("..") ? path : near;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** The HTTP address Convex pairs with a deployment URL. */
|
|
48
|
-
export function siteUrlOf(backendUrl) {
|
|
49
|
-
const url = new URL(backendUrl);
|
|
50
|
-
// A server in the host app answers at the path it is mounted at.
|
|
51
|
-
if (url.pathname !== "/" && !url.hostname.endsWith(".convex.cloud")) return `${url.origin}${url.pathname.replace(/\/$/, "")}`;
|
|
52
|
-
if (url.hostname.endsWith(".convex.cloud")) url.hostname = url.hostname.replace(/\.convex\.cloud$/, ".convex.site");
|
|
53
|
-
else if (url.port !== "") url.port = String(Number(url.port) + 1);
|
|
54
|
-
return url.origin;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function getJson(url, fetchFn, unreachable) {
|
|
58
|
-
let response;
|
|
59
|
-
try {
|
|
60
|
-
response = await fetchFn(url);
|
|
61
|
-
} catch {
|
|
62
|
-
throw new SetupError(`${unreachable}.`);
|
|
63
|
-
}
|
|
64
|
-
if (!response.ok) throw new SetupError(`${unreachable} (${response.status}).`);
|
|
65
|
-
return await response.json();
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* The backend's sign-in service, after checking both are recent enough for
|
|
70
|
-
* this package, as the component does.
|
|
71
|
-
*/
|
|
72
|
-
export async function resolveBackend(backendUrl, { fetchFn = fetch } = {}) {
|
|
73
|
-
const url = backendUrl.replace(/\/$/, "");
|
|
74
|
-
const siteUrl = siteUrlOf(url);
|
|
75
|
-
const config = await getJson(`${siteUrl}/critiqs/config`, fetchFn, `Can't reach the Critiqs backend at ${url}`);
|
|
76
|
-
if (typeof config.protocol !== "number" || config.protocol < BACKEND_PROTOCOL) {
|
|
77
|
-
throw new SetupError(
|
|
78
|
-
url === CLOUD_BACKEND_URL
|
|
79
|
-
? "Critiqs Cloud isn't ready for this version of Critiqs yet."
|
|
80
|
-
: `The Critiqs backend at ${url} runs an older version. Deploy the current Critiqs functions to it.`,
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
const signInUrl = String(config.signInUrl).replace(/\/$/, "");
|
|
84
|
-
const transport = config.transport === "http" ? "http" : "convex";
|
|
85
|
-
if (transport === "convex" && new URL(signInUrl).origin !== siteUrl) {
|
|
86
|
-
const signIn = await getJson(`${new URL(signInUrl).origin}/critiqs/config`, fetchFn, `Can't reach Critiqs's sign-in service at ${signInUrl}`);
|
|
87
|
-
if (typeof signIn.protocol !== "number" || signIn.protocol < SIGN_IN_PROTOCOL) {
|
|
88
|
-
throw new SetupError(`Critiqs's sign-in service at ${signInUrl} isn't ready for this version of Critiqs yet.`);
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return { backendUrl: url, siteUrl, signInUrl, transport };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
// ---------------------------------------------------------------------------
|
|
95
|
-
// Signing in from the command line
|
|
96
|
-
|
|
97
|
-
/** Tries to open a URL in the default browser; the URL is also printed, so failure is fine. */
|
|
98
|
-
export function openBrowser(url) {
|
|
99
|
-
const [command, args] =
|
|
100
|
-
process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
101
|
-
try {
|
|
102
|
-
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
103
|
-
child.on("error", () => {});
|
|
104
|
-
child.unref();
|
|
105
|
-
} catch {}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
109
|
-
|
|
110
|
-
function bridgePage(signInUrl, key) {
|
|
111
|
-
const data = JSON.stringify({ signInUrl, key }).replace(/</g, "\\u003c");
|
|
112
|
-
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Sign in to set up Critiqs</title>
|
|
113
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
114
|
-
<style>body{font:15px/1.5 system-ui,sans-serif;max-width:28rem;margin:4rem auto;padding:0 1rem;color:#1d1d1f}
|
|
115
|
-
button{font:inherit;font-weight:600;background:#0d63f3;color:#fff;border:0;border-radius:8px;padding:.6rem 1rem;cursor:pointer}
|
|
116
|
-
.note{color:#555}</style></head><body>
|
|
117
|
-
<h1>Set up Critiqs</h1>
|
|
118
|
-
<p id="status">Sign in so the command line can create your Critiqs project. Sign-in opens in a small window.</p>
|
|
119
|
-
<p><button id="go" type="button">Sign in to Critiqs</button></p>
|
|
120
|
-
<p class="note">Signing in from <strong>${escapeHtml(signInUrl)}</strong>. This page only works on this computer.</p>
|
|
121
|
-
<script>
|
|
122
|
-
const { signInUrl, key } = ${data};
|
|
123
|
-
const status = document.getElementById("status");
|
|
124
|
-
const button = document.getElementById("go");
|
|
125
|
-
button.addEventListener("click", () => {
|
|
126
|
-
const state = crypto.randomUUID();
|
|
127
|
-
const url = new URL("/auth/start", signInUrl);
|
|
128
|
-
url.search = new URLSearchParams({ origin: location.origin, state }).toString();
|
|
129
|
-
const popup = window.open(url, "critiqs-sign-in", "popup,width=480,height=640");
|
|
130
|
-
if (popup === null) { status.textContent = "Your browser blocked the sign-in window. Allow pop-ups for this page and try again."; return; }
|
|
131
|
-
const onMessage = async (event) => {
|
|
132
|
-
const data = event.data;
|
|
133
|
-
if (event.source !== popup || event.origin !== new URL(signInUrl).origin || data?.type !== "critiqs:sign-in" || data.state !== state) return;
|
|
134
|
-
window.removeEventListener("message", onMessage);
|
|
135
|
-
if (typeof data.accessToken !== "string") { status.textContent = "Sign-in was cancelled. Try again."; return; }
|
|
136
|
-
const response = await fetch("/done/" + key, { method: "POST", headers: { "Content-Type": "application/json" },
|
|
137
|
-
body: JSON.stringify({ accessToken: data.accessToken, refreshToken: data.refreshToken }) });
|
|
138
|
-
button.hidden = true;
|
|
139
|
-
status.textContent = response.ok ? "Signed in. Return to your terminal or coding agent; you can close this page." : "Setup stopped waiting. Run it again.";
|
|
140
|
-
};
|
|
141
|
-
window.addEventListener("message", onMessage);
|
|
142
|
-
});
|
|
143
|
-
</script></body></html>`;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* Serves a page on this computer that signs in through Critiqs's usual sign-in
|
|
148
|
-
* window, then hands the tokens to this process. Sign-in sees the page as a
|
|
149
|
-
* site at a loopback address, so it asks the person to allow it.
|
|
150
|
-
* Returns the page's URL and a promise for the tokens; `close` stops waiting.
|
|
151
|
-
*/
|
|
152
|
-
export async function startBrowserSignIn({ signInUrl, timeoutMs = 10 * 60_000, port = 4874 } = {}) {
|
|
153
|
-
const key = randomBytes(24).toString("hex");
|
|
154
|
-
let settle;
|
|
155
|
-
const tokens = new Promise((resolveTokens, reject) => {
|
|
156
|
-
settle = { resolve: resolveTokens, reject };
|
|
157
|
-
});
|
|
158
|
-
let done = false;
|
|
159
|
-
const server = createServer((request, response) => {
|
|
160
|
-
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
161
|
-
if (request.method === "GET" && url.pathname === `/${key}`) {
|
|
162
|
-
response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" });
|
|
163
|
-
response.end(bridgePage(signInUrl, key));
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
if (request.method === "POST" && url.pathname === `/done/${key}` && !done) {
|
|
167
|
-
let body = "";
|
|
168
|
-
request.on("data", (chunk) => {
|
|
169
|
-
body += chunk;
|
|
170
|
-
if (body.length > 20_000) request.destroy();
|
|
171
|
-
});
|
|
172
|
-
request.on("end", () => {
|
|
173
|
-
try {
|
|
174
|
-
const parsed = JSON.parse(body);
|
|
175
|
-
if (typeof parsed.accessToken !== "string" || typeof parsed.refreshToken !== "string") throw new Error("Bad tokens");
|
|
176
|
-
done = true;
|
|
177
|
-
response.writeHead(204);
|
|
178
|
-
response.end();
|
|
179
|
-
settle.resolve({ accessToken: parsed.accessToken, refreshToken: parsed.refreshToken });
|
|
180
|
-
close();
|
|
181
|
-
} catch {
|
|
182
|
-
response.writeHead(400);
|
|
183
|
-
response.end();
|
|
184
|
-
}
|
|
185
|
-
});
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
response.writeHead(404);
|
|
189
|
-
response.end();
|
|
190
|
-
});
|
|
191
|
-
const listen = (candidate) =>
|
|
192
|
-
new Promise((resolveListen, reject) => {
|
|
193
|
-
server.once("error", reject);
|
|
194
|
-
server.listen(candidate, "127.0.0.1", () => {
|
|
195
|
-
server.off("error", reject);
|
|
196
|
-
resolveListen();
|
|
197
|
-
});
|
|
198
|
-
});
|
|
199
|
-
// A fixed port lets the sign-in window remember that this page was allowed.
|
|
200
|
-
await listen(port).catch(() => listen(0));
|
|
201
|
-
const timer = setTimeout(() => {
|
|
202
|
-
settle.reject(new SetupError("Sign-in took too long. Run setup again."));
|
|
203
|
-
close();
|
|
204
|
-
}, timeoutMs);
|
|
205
|
-
function close() {
|
|
206
|
-
clearTimeout(timer);
|
|
207
|
-
server.close();
|
|
208
|
-
server.closeAllConnections?.();
|
|
209
|
-
}
|
|
210
|
-
const address = server.address();
|
|
211
|
-
return {
|
|
212
|
-
url: `http://127.0.0.1:${address.port}/${key}`,
|
|
213
|
-
tokens,
|
|
214
|
-
close: () => {
|
|
215
|
-
if (!done) settle.reject(new SetupError("Setup stopped waiting for sign-in."));
|
|
216
|
-
close();
|
|
217
|
-
},
|
|
218
|
-
};
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* Whether this process probably can't open a browser the person sees: a
|
|
223
|
-
* remote shell, or Linux without a desktop session. Setup then asks for
|
|
224
|
-
* approval from another device, where the sign-in service supports it.
|
|
225
|
-
*/
|
|
226
|
-
export function isHeadless(env = process.env, platform = process.platform) {
|
|
227
|
-
if (env.SSH_CONNECTION || env.SSH_TTY || env.CODESPACES || env.GITPOD_WORKSPACE_ID) return true;
|
|
228
|
-
return platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
const wait = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
232
|
-
|
|
233
|
-
/**
|
|
234
|
-
* Asks the sign-in service to approve this setup from any browser, on any
|
|
235
|
-
* device: the person opens `url`, types `userCode`, signs in, and approves.
|
|
236
|
-
* Meanwhile this process polls with a device secret it never shows. Resolves
|
|
237
|
-
* `tokens` with a short-lived access token (no refresh token) once approved.
|
|
238
|
-
* Refuses clearly when the sign-in service doesn't offer this yet.
|
|
239
|
-
*/
|
|
240
|
-
export async function startRemoteSignIn({ signInUrl, fetchFn = fetch, sleep = wait, now = Date.now } = {}) {
|
|
241
|
-
const service = new URL(signInUrl).origin;
|
|
242
|
-
const config = await getJson(`${service}/critiqs/config`, fetchFn, `Can't reach Critiqs's sign-in service at ${signInUrl}`);
|
|
243
|
-
if (config.deviceSignIn !== true) {
|
|
244
|
-
throw new SetupError(
|
|
245
|
-
`Critiqs's sign-in service at ${signInUrl} doesn't support approving setup from another device yet. ` +
|
|
246
|
-
"Run setup where a browser can open on the same computer (with --browser), or create the project in the matching prototype's Critiqs sidebar and set its projectId on the existing component, keeping its backend.",
|
|
247
|
-
);
|
|
248
|
-
}
|
|
249
|
-
let response;
|
|
250
|
-
try {
|
|
251
|
-
response = await fetchFn(`${signInUrl}/auth/device/start`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
|
|
252
|
-
} catch {
|
|
253
|
-
throw new SetupError(`Can't reach Critiqs's sign-in service at ${signInUrl}.`);
|
|
254
|
-
}
|
|
255
|
-
if (response.status === 429) throw new SetupError("Too many setups are waiting for approval right now. Try again in a minute.");
|
|
256
|
-
if (!response.ok) throw new SetupError(`Critiqs's sign-in service can't start an approval (${response.status}).`);
|
|
257
|
-
const started = await response.json();
|
|
258
|
-
let stopped = false;
|
|
259
|
-
const expiresAt = now() + started.expiresIn * 1000;
|
|
260
|
-
const tokens = (async () => {
|
|
261
|
-
let interval = Math.max(1, Number(started.interval) || 5);
|
|
262
|
-
for (;;) {
|
|
263
|
-
await sleep(interval * 1000);
|
|
264
|
-
if (stopped) throw new SetupError("Setup stopped waiting for approval.");
|
|
265
|
-
if (now() > expiresAt) throw new SetupError("The setup code expired before it was approved. Run setup again.");
|
|
266
|
-
let answer;
|
|
267
|
-
try {
|
|
268
|
-
const polled = await fetchFn(`${signInUrl}/auth/device/token`, {
|
|
269
|
-
method: "POST",
|
|
270
|
-
headers: { "Content-Type": "application/json" },
|
|
271
|
-
body: JSON.stringify({ deviceCode: started.deviceCode }),
|
|
272
|
-
});
|
|
273
|
-
answer = { status: polled.status, body: await polled.json() };
|
|
274
|
-
} catch {
|
|
275
|
-
// The network may come back before the code expires.
|
|
276
|
-
continue;
|
|
277
|
-
}
|
|
278
|
-
if (answer.status === 200 && typeof answer.body.accessToken === "string") {
|
|
279
|
-
return { accessToken: answer.body.accessToken, refreshToken: null, reviewer: answer.body.reviewer ?? null };
|
|
280
|
-
}
|
|
281
|
-
const error = answer.body?.error;
|
|
282
|
-
if (error === "authorization_pending") continue;
|
|
283
|
-
if (error === "slow_down") {
|
|
284
|
-
interval = Math.max(interval + 5, Number(answer.body.interval) || 0);
|
|
285
|
-
continue;
|
|
286
|
-
}
|
|
287
|
-
if (error === "access_denied") throw new SetupError("Setup was denied in the browser. Run setup again to retry.");
|
|
288
|
-
if (error === "expired_token") throw new SetupError("The setup code expired before it was approved. Run setup again.");
|
|
289
|
-
throw new SetupError("The setup approval is no longer valid. Run setup again.");
|
|
290
|
-
}
|
|
291
|
-
})();
|
|
292
|
-
tokens.catch(() => {});
|
|
293
|
-
return {
|
|
294
|
-
url: started.verificationUrl,
|
|
295
|
-
userCode: started.userCode,
|
|
296
|
-
expiresAt,
|
|
297
|
-
tokens,
|
|
298
|
-
close: () => {
|
|
299
|
-
stopped = true;
|
|
300
|
-
},
|
|
301
|
-
};
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
/** Calls a Convex function over Convex's HTTP API as the signed-in person. */
|
|
305
|
-
export async function callConvex(backendUrl, kind, path, args, accessToken, { fetchFn = fetch } = {}) {
|
|
306
|
-
let response;
|
|
307
|
-
try {
|
|
308
|
-
response = await fetchFn(`${backendUrl}/api/${kind}`, {
|
|
309
|
-
method: "POST",
|
|
310
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` },
|
|
311
|
-
body: JSON.stringify({ path, args, format: "json" }),
|
|
312
|
-
});
|
|
313
|
-
} catch {
|
|
314
|
-
throw new SetupError(`Can't reach the Critiqs backend at ${backendUrl}.`);
|
|
315
|
-
}
|
|
316
|
-
const result = await response.json().catch(() => null);
|
|
317
|
-
if (result?.status === "success") return result.value;
|
|
318
|
-
const message = result?.errorData?.message ?? result?.errorMessage ?? `The Critiqs backend answered ${response.status}.`;
|
|
319
|
-
throw new SetupError(String(message));
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/** Creates a project as the signed-in person; returns its ID. */
|
|
323
|
-
export async function createProject({ backendUrl, accessToken, name, reviewUrl = null, fetchFn = fetch }) {
|
|
324
|
-
await callConvex(backendUrl, "mutation", "users:sync", {}, accessToken, { fetchFn });
|
|
325
|
-
return await callConvex(backendUrl, "mutation", "projects:create", { name, reviewUrl }, accessToken, { fetchFn });
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/** Complete discovery, or an error: partial results cannot establish that a project is absent. */
|
|
329
|
-
export async function listMyProjects({ backendUrl, accessToken, fetchFn = fetch }) {
|
|
330
|
-
const projects = [];
|
|
331
|
-
const seen = new Set();
|
|
332
|
-
let cursor = null;
|
|
333
|
-
for (let page = 0; page < 100; page++) {
|
|
334
|
-
// The shared Convex/SQLite contract permits at most 40 items per page.
|
|
335
|
-
const result = await callConvex(backendUrl, "query", "projects:listMine", { paginationOpts: { numItems: 40, cursor } }, accessToken, { fetchFn });
|
|
336
|
-
if (!Array.isArray(result?.page) || typeof result.isDone !== "boolean") throw new SetupError("The backend returned an invalid project page.");
|
|
337
|
-
projects.push(...result.page);
|
|
338
|
-
if (result.isDone) return projects;
|
|
339
|
-
if (typeof result.continueCursor !== "string" || result.continueCursor === "" || seen.has(result.continueCursor)) {
|
|
340
|
-
throw new SetupError("Project discovery couldn't finish because its cursor didn't advance.");
|
|
341
|
-
}
|
|
342
|
-
seen.add(result.continueCursor);
|
|
343
|
-
cursor = result.continueCursor;
|
|
344
|
-
}
|
|
345
|
-
throw new SetupError("Project discovery exceeded its page budget without finishing. Choose an existing project ID, or explicitly create a new project with --new-project.");
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
/**
|
|
349
|
-
* Ends the command line's sign-in session; it is only needed to create the
|
|
350
|
-
* project. `origin` is the sign-in page's, which the session belongs to.
|
|
351
|
-
*/
|
|
352
|
-
export async function signOut(signInUrl, refreshToken, { origin, fetchFn = fetch } = {}) {
|
|
353
|
-
await fetchFn(`${signInUrl}/auth/sign-out`, {
|
|
354
|
-
method: "POST",
|
|
355
|
-
headers: { "Content-Type": "application/json", ...(origin ? { Origin: origin } : {}) },
|
|
356
|
-
body: JSON.stringify({ refreshToken }),
|
|
357
|
-
}).catch(() => undefined);
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// ---------------------------------------------------------------------------
|
|
361
|
-
// The prototype's code
|
|
362
|
-
|
|
363
|
-
/** The prototype's one `<Critiqs />` component, or a message saying why there isn't one. */
|
|
364
|
-
export function locateComponent(root, cwd = root) {
|
|
365
|
-
let isDirectory = false;
|
|
366
|
-
try {
|
|
367
|
-
isDirectory = statSync(root).isDirectory();
|
|
368
|
-
} catch {}
|
|
369
|
-
if (!isDirectory) return { error: `${shown(cwd, root)} is not a folder.` };
|
|
370
|
-
const usages = findCritiqsUsages(root);
|
|
371
|
-
if (usages.length === 0) {
|
|
372
|
-
return {
|
|
373
|
-
error:
|
|
374
|
-
`No <Critiqs /> component found in ${shown(cwd, root)}. ` +
|
|
375
|
-
`Add it where the prototype renders, imported with import { Critiqs } from "critiqs-react": <Critiqs />`,
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
if (usages.length > 1) {
|
|
379
|
-
const list = usages.map(({ file, element }) => `${shown(cwd, file)}:${element.line}`).join(", ");
|
|
380
|
-
return { error: `Found ${usages.length} <Critiqs /> components (${list}), so nothing was changed. Keep one where the prototype renders.` };
|
|
381
|
-
}
|
|
382
|
-
return { usage: usages[0] };
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/** Complete public connection values for manual recovery; no credentials. */
|
|
386
|
-
function componentSnippet(props) {
|
|
387
|
-
return `<Critiqs${Object.entries(props).map(([key, value]) => (typeof value === "string" ? ` ${key}=${JSON.stringify(value)}` : propsText({ [key]: value }))).join("")} />`;
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* Sets properties on the prototype's Critiqs component, adding it when
|
|
392
|
-
* absent. Reads, planning and writes all return a recoverable failure; `also`
|
|
393
|
-
* completes the recovery instructions with anything else the connection needs.
|
|
394
|
-
*/
|
|
395
|
-
export function writeComponentProps({ root, cwd = root, props, dryRun = false, entry = null, mount = null, also = "" }) {
|
|
396
|
-
const snippet = componentSnippet(props);
|
|
397
|
-
const placement = entry === null ? "where the app renders" : `in ${shown(cwd, resolve(root, entry))}${mount === null ? "" : ` beside <${mount}>`}`;
|
|
398
|
-
try {
|
|
399
|
-
const plan = planComponent(root, props, { entry, mount });
|
|
400
|
-
const where = (file, line) => `${shown(cwd, file)}:${line}`;
|
|
401
|
-
if (!plan.ok) return { ok: false, message: `${refusal(plan, props, where, shown(cwd, root))}${also === "" ? "" : `\nThen${also}.`}` };
|
|
402
|
-
const at = where(plan.file, plan.line);
|
|
403
|
-
if (plan.action === "unchanged") return { ok: true, file: plan.file, line: plan.line, changed: [], installed: false, message: `${at} already has these settings.` };
|
|
404
|
-
if (!dryRun) applyPlan(plan);
|
|
405
|
-
const dry = dryRun ? " (dry run, nothing written)" : "";
|
|
406
|
-
if (plan.action === "install") {
|
|
407
|
-
return {
|
|
408
|
-
ok: true,
|
|
409
|
-
file: plan.file,
|
|
410
|
-
line: plan.line,
|
|
411
|
-
changed: plan.changed,
|
|
412
|
-
installed: true,
|
|
413
|
-
preview: plan.preview,
|
|
414
|
-
message: `${dryRun ? "Would add" : "Added"} <Critiqs /> with ${plan.changed.join(" and ")} to ${at} (${MOUNT_KINDS[plan.kind]})${plan.imported ? ", importing it from critiqs-react" : ""}${dry}.`,
|
|
415
|
-
};
|
|
416
|
-
}
|
|
417
|
-
return { ok: true, file: plan.file, line: plan.line, changed: plan.changed, installed: false, message: `${dryRun ? "Would set" : "Set"} ${plan.changed.join(" and ")} in ${at}${dry}.` };
|
|
418
|
-
} catch {
|
|
419
|
-
return { ok: false, message: `Couldn't read or write the app's source. Restore file access, then set this complete connection ${placement}: ${snippet}${also}. Update an existing Critiqs component instead of adding a second one.` };
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
/**
|
|
424
|
-
* Connects the app to a project the way `wiring` says (see `chooseWiring`):
|
|
425
|
-
* the component's properties, and for an environment-backed ID, its setting
|
|
426
|
-
* in this computer's `.env` file. The component is written first, so a
|
|
427
|
-
* failure leaves either nothing or a component whose setting is still to add;
|
|
428
|
-
* both failures say exactly what remains.
|
|
429
|
-
*/
|
|
430
|
-
export function writeConnection({ root, cwd = root, wiring, projectId, backend, dryRun = false, entry = null, mount = null }) {
|
|
431
|
-
const props = connectionProps(wiring, projectId, backend);
|
|
432
|
-
if (wiring.mode !== "env") return writeComponentProps({ root, cwd, props, dryRun, entry, mount });
|
|
433
|
-
const line = `${wiring.variable}=${projectId}`;
|
|
434
|
-
let env;
|
|
435
|
-
try {
|
|
436
|
-
env = planEnv(wiring.app, wiring.variable, projectId);
|
|
437
|
-
} catch {
|
|
438
|
-
const placement = entry === null ? "where the app renders" : `in ${shown(cwd, resolve(root, entry))}${mount === null ? "" : ` beside <${mount}>`}`;
|
|
439
|
-
return {
|
|
440
|
-
ok: false,
|
|
441
|
-
message: `Couldn't read this app's .env files. Restore access, then set this complete connection ${placement}: ${componentSnippet(props)}, and add ${line} to the .env.local file it loads. Update an existing Critiqs component instead of adding a second one.`,
|
|
442
|
-
};
|
|
443
|
-
}
|
|
444
|
-
const file = shown(cwd, env.file);
|
|
445
|
-
const setting = { name: wiring.variable, file: env.file, advice: deploymentAdvice(wiring) };
|
|
446
|
-
const component = writeComponentProps({ root, cwd, props, dryRun, entry, mount, also: `, and add ${line} to ${file}` });
|
|
447
|
-
if (!component.ok) return { ...component, env: setting };
|
|
448
|
-
if (dryRun) {
|
|
449
|
-
try {
|
|
450
|
-
if (env.changed) checkWritable(env.file);
|
|
451
|
-
} catch {
|
|
452
|
-
return { ok: false, message: `Can't write ${file}. Check its permissions (or choose another file with --project-env-file), then run setup again; no project was created.`, env: setting };
|
|
453
|
-
}
|
|
454
|
-
return { ...component, env: setting, message: `${component.message} Would set ${line} in ${file}.` };
|
|
455
|
-
}
|
|
456
|
-
if (env.changed) {
|
|
457
|
-
try {
|
|
458
|
-
applyEnv(env);
|
|
459
|
-
} catch {
|
|
460
|
-
return { ...component, ok: false, env: setting, message: `${component.message} Couldn't write ${file}: add this line to it yourself, keeping the component as it is:\n ${line}` };
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
const ignored = gitIgnored(env.file);
|
|
464
|
-
const keepOut = ignored === false ? ` Keep ${file} out of Git (add it to .gitignore): it holds this computer's setting, and each deployment sets its own.` : "";
|
|
465
|
-
return {
|
|
466
|
-
...component,
|
|
467
|
-
env: { ...setting, ignored },
|
|
468
|
-
message: `${component.message} ${env.changed ? "Set" : "Kept"} ${line} in ${file} for this computer.${keepOut}`,
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/** The `projectId` and `backend` the prototype's code gives its `<Critiqs />`. */
|
|
473
|
-
export function readComponentProps(root, cwd = root) {
|
|
474
|
-
const located = locateComponent(root, cwd);
|
|
475
|
-
if ("error" in located) return located;
|
|
476
|
-
const { file, source, element } = located.usage;
|
|
477
|
-
// Spread props may set or override a property unless it comes after them, so its value is then unknown.
|
|
478
|
-
const settled = (name) => {
|
|
479
|
-
const attribute = element.attributes.find((candidate) => candidate.name === name);
|
|
480
|
-
if (element.spreadEnd !== null && (attribute === undefined || attribute.start < element.spreadEnd)) return { kind: "expression" };
|
|
481
|
-
return readProp(source, element, name);
|
|
482
|
-
};
|
|
483
|
-
const required = element.attributes.some((attribute) => attribute.name === "requireProjectId");
|
|
484
|
-
return { file, line: element.line, projectId: settled("projectId"), backend: settled("backend"), requireProjectId: required };
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
// ---------------------------------------------------------------------------
|
|
488
|
-
// A team's own Convex deployment
|
|
489
|
-
|
|
490
|
-
/** The `convex` package this package depends on. */
|
|
491
|
-
function convexPackage() {
|
|
492
|
-
const require = createRequire(join(PACKAGE_ROOT, "package.json"));
|
|
493
|
-
const manifest = require.resolve("convex/package.json");
|
|
494
|
-
return { cli: join(dirname(manifest), "bin", "main.js"), version: require(manifest).version };
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
function runConvex(args, { cwd, env, input }) {
|
|
498
|
-
return new Promise((resolveRun, reject) => {
|
|
499
|
-
const child = spawn(process.execPath, [convexPackage().cli, ...args], { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
|
|
500
|
-
let output = "";
|
|
501
|
-
child.stdout.on("data", (chunk) => (output += chunk));
|
|
502
|
-
child.stderr.on("data", (chunk) => (output += chunk));
|
|
503
|
-
child.on("error", reject);
|
|
504
|
-
child.on("close", (code) => (code === 0 ? resolveRun(output) : reject(new SetupError(`convex ${args[0]} failed:\n${output.trim()}`))));
|
|
505
|
-
child.stdin.end(input ?? "");
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
/**
|
|
510
|
-
* The deployment a key or self-hosted address names: a production deploy key
|
|
511
|
-
* (`prod:<name>|…`) from the Convex dashboard, or a self-hosted Convex backend.
|
|
512
|
-
*/
|
|
513
|
-
export function targetDeployment(env) {
|
|
514
|
-
if (env.CONVEX_DEPLOYMENT_TOKEN && !env.CONVEX_DEPLOY_KEY) {
|
|
515
|
-
throw new SetupError("Set CONVEX_DEPLOY_KEY rather than CONVEX_DEPLOYMENT_TOKEN, so it's clear which deployment Critiqs deploys to.");
|
|
516
|
-
}
|
|
517
|
-
if ((env.CONVEX_SELF_HOSTED_URL || env.CONVEX_SELF_HOSTED_ADMIN_KEY) && env.CONVEX_DEPLOY_KEY) {
|
|
518
|
-
throw new SetupError("Set either CONVEX_DEPLOY_KEY, or CONVEX_SELF_HOSTED_URL with CONVEX_SELF_HOSTED_ADMIN_KEY, not both.");
|
|
519
|
-
}
|
|
520
|
-
if (env.CONVEX_SELF_HOSTED_URL && env.CONVEX_SELF_HOSTED_ADMIN_KEY) {
|
|
521
|
-
return { backendUrl: env.CONVEX_SELF_HOSTED_URL.replace(/\/$/, ""), env: { CONVEX_SELF_HOSTED_URL: env.CONVEX_SELF_HOSTED_URL, CONVEX_SELF_HOSTED_ADMIN_KEY: env.CONVEX_SELF_HOSTED_ADMIN_KEY } };
|
|
522
|
-
}
|
|
523
|
-
const key = env.CONVEX_DEPLOY_KEY ?? "";
|
|
524
|
-
const match = /^prod:([a-z0-9-]+)\|/.exec(key);
|
|
525
|
-
if (match === null) {
|
|
526
|
-
throw new SetupError(
|
|
527
|
-
key === ""
|
|
528
|
-
? "Set CONVEX_DEPLOY_KEY to a production deploy key from your Convex project's settings."
|
|
529
|
-
: "CONVEX_DEPLOY_KEY must be a production deploy key (it starts with prod:).",
|
|
530
|
-
);
|
|
531
|
-
}
|
|
532
|
-
return { backendUrl: `https://${match[1]}.convex.cloud`, env: { CONVEX_DEPLOY_KEY: key } };
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
/** The environment for the Convex CLI: only the chosen deployment's credentials, since the CLI would prefer any other it finds. */
|
|
536
|
-
export function convexEnv(target, base = process.env) {
|
|
537
|
-
const env = { ...base };
|
|
538
|
-
for (const name of [
|
|
539
|
-
"CONVEX_DEPLOYMENT",
|
|
540
|
-
"CONVEX_DEPLOY_KEY",
|
|
541
|
-
// Convex treats this as another name for the deploy key, and prefers it.
|
|
542
|
-
"CONVEX_DEPLOYMENT_TOKEN",
|
|
543
|
-
"CONVEX_SELF_HOSTED_URL",
|
|
544
|
-
"CONVEX_SELF_HOSTED_ADMIN_KEY",
|
|
545
|
-
"CONVEX_URL",
|
|
546
|
-
]) {
|
|
547
|
-
delete env[name];
|
|
548
|
-
}
|
|
549
|
-
return { ...env, ...target.env };
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/**
|
|
553
|
-
* Deploys Critiqs's functions to a team's own Convex deployment and sets the
|
|
554
|
-
* only settings it needs: which sign-in service to trust (Critiqs Cloud's
|
|
555
|
-
* unless `signInUrl` names another), and Resend's key and sender for mention
|
|
556
|
-
* emails when given. Secrets go to Convex through standard input, never
|
|
557
|
-
* command arguments. Returns the deployment URL.
|
|
558
|
-
*/
|
|
559
|
-
export async function deployOwnConvex({ env = process.env, signInUrl, resendApiKey, emailFrom, log = () => {} }) {
|
|
560
|
-
const target = targetDeployment(env);
|
|
561
|
-
const bundle = join(PACKAGE_ROOT, "dist", "backend", "convex");
|
|
562
|
-
if (!existsSync(bundle)) throw new SetupError("This copy of critiqs-react has no backend functions. Build the package first.");
|
|
563
|
-
const issuer = (signInUrl ?? (await resolveBackend(CLOUD_BACKEND_URL)).signInUrl).replace(/\/$/, "");
|
|
564
|
-
// Inside the package, so the functions resolve `convex` from its dependencies.
|
|
565
|
-
const work = mkdtempSync(join(PACKAGE_ROOT, ".deploy-"));
|
|
566
|
-
const childEnv = convexEnv(target);
|
|
567
|
-
try {
|
|
568
|
-
cpSync(bundle, join(work, "convex"), { recursive: true });
|
|
569
|
-
// The Convex CLI expects an app folder; `convex` itself resolves from this package's dependencies.
|
|
570
|
-
writeFileSync(join(work, "package.json"), JSON.stringify({ name: "critiqs-backend", private: true, type: "module", dependencies: { convex: convexPackage().version } }));
|
|
571
|
-
log("Configuring the deployment…");
|
|
572
|
-
await runConvex(["env", "set", "CRITIQS_AUTH_ISSUER"], { cwd: work, env: childEnv, input: issuer });
|
|
573
|
-
if (resendApiKey) await runConvex(["env", "set", "RESEND_API_KEY"], { cwd: work, env: childEnv, input: resendApiKey });
|
|
574
|
-
if (emailFrom) await runConvex(["env", "set", "CRITIQS_EMAIL_FROM"], { cwd: work, env: childEnv, input: emailFrom });
|
|
575
|
-
log("Deploying Critiqs's functions…");
|
|
576
|
-
await runConvex(["deploy", "--typecheck", "disable", "--codegen", "disable", "-y"], { cwd: work, env: childEnv });
|
|
577
|
-
} finally {
|
|
578
|
-
rmSync(work, { recursive: true, force: true });
|
|
579
|
-
}
|
|
580
|
-
await resolveBackend(target.backendUrl);
|
|
581
|
-
return target.backendUrl;
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// ---------------------------------------------------------------------------
|
|
585
|
-
// Checking a setup
|
|
586
|
-
|
|
587
|
-
/** What doctor did and didn't do, so a pass is read for what it proves. */
|
|
588
|
-
export const DOCTOR_NOTE =
|
|
589
|
-
"Doctor reads the code and the backend's own health report. It doesn't send a sign-in code or email, upload a screenshot, or post a comment: " +
|
|
590
|
-
'"configured" checks mean the settings are there, and "observed" checks report what the backend has actually done.';
|
|
591
|
-
|
|
592
|
-
/** Whether an address only opens on this computer or a private network. */
|
|
593
|
-
export function isLocalAddress(address) {
|
|
594
|
-
let host;
|
|
595
|
-
try {
|
|
596
|
-
host = new URL(address).hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
597
|
-
} catch {
|
|
598
|
-
return false;
|
|
599
|
-
}
|
|
600
|
-
return (
|
|
601
|
-
host === "localhost" ||
|
|
602
|
-
host.endsWith(".localhost") ||
|
|
603
|
-
host.endsWith(".local") ||
|
|
604
|
-
host.endsWith(".internal") ||
|
|
605
|
-
host === "::1" ||
|
|
606
|
-
(/^\d+(?:\.\d+){3}$/.test(host) && /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|169\.254\.)/.test(host)) ||
|
|
607
|
-
(host.includes(":") && /^(f[cd]|fe[89ab])/.test(host))
|
|
608
|
-
);
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
/**
|
|
612
|
-
* Checks that the prototype's Critiqs setup works, not only that it connects:
|
|
613
|
-
* the component and its settings, the backend and its version, sign-in, the
|
|
614
|
-
* project, email, and that scheduled mention emails are going out.
|
|
615
|
-
* Each check is pass, warn, fail, or info (an optional feature that is off),
|
|
616
|
-
* with what to do. `stage` says which part of setup it is about, and `basis`
|
|
617
|
-
* whether it reports configuration or something the backend observed.
|
|
618
|
-
*/
|
|
619
|
-
export async function doctor({ root, cwd = root, backendUrl: chosenBackend, fetchFn = fetch, now = Date.now(), env: shell = process.env, envFile = null }) {
|
|
620
|
-
const checks = [];
|
|
621
|
-
const add = (status, name, detail, stage, basis = "configuration") => checks.push({ status, name, detail, stage, basis });
|
|
622
|
-
let apps = null;
|
|
623
|
-
try {
|
|
624
|
-
apps = workspaceApps(root);
|
|
625
|
-
} catch {}
|
|
626
|
-
if (apps !== null && apps.length > 0) {
|
|
627
|
-
const commands = apps.map((dir) => ` npx critiqs-react doctor --dir ${shown(cwd, dir)}`).join("\n");
|
|
628
|
-
add("fail", "Component", `${shown(cwd, root)} is a workspace; each app has its own Critiqs setup. Check one app:\n${commands}`, "code");
|
|
629
|
-
return checks;
|
|
630
|
-
}
|
|
631
|
-
const props = readComponentProps(root, cwd);
|
|
632
|
-
if ("error" in props) {
|
|
633
|
-
add("fail", "Component", `${props.error} Run critiqs init to add it.`, "code");
|
|
634
|
-
return checks;
|
|
635
|
-
}
|
|
636
|
-
const at = `${shown(cwd, props.file)}:${props.line}`;
|
|
637
|
-
add("pass", "Component", `<Critiqs /> at ${at}.`, "code");
|
|
638
|
-
|
|
639
|
-
let backendUrl = CLOUD_BACKEND_URL;
|
|
640
|
-
if (chosenBackend !== undefined) {
|
|
641
|
-
backendUrl = chosenBackend;
|
|
642
|
-
} else if (props.backend?.kind === "expression") {
|
|
643
|
-
add("warn", "Backend", `${at} sets backend from code, so doctor checks Critiqs Cloud. Run doctor with --backend <url> to check another.`, "service");
|
|
644
|
-
} else if (props.backend?.kind === "literal" && props.backend.value.startsWith("/")) {
|
|
645
|
-
add("fail", "Backend", `${at} uses Critiqs inside your app's server at ${props.backend.value}. Start the app and run doctor with --backend http://localhost:<port>${props.backend.value}.`, "service");
|
|
646
|
-
return checks;
|
|
647
|
-
} else if (props.backend?.kind === "literal") {
|
|
648
|
-
backendUrl = props.backend.value;
|
|
649
|
-
}
|
|
650
|
-
let resolved;
|
|
651
|
-
try {
|
|
652
|
-
resolved = await resolveBackend(backendUrl, { fetchFn });
|
|
653
|
-
add("pass", "Backend", `${resolved.backendUrl === CLOUD_BACKEND_URL ? "Critiqs Cloud" : resolved.backendUrl} answered and runs a current version.`, "service", "observed");
|
|
654
|
-
} catch (error) {
|
|
655
|
-
add("fail", "Backend", error.message, "service", "observed");
|
|
656
|
-
return checks;
|
|
657
|
-
}
|
|
658
|
-
|
|
659
|
-
// An environment-backed ID: what this computer's .env files set. Deployments set their own, which doctor can't see.
|
|
660
|
-
let setting = null;
|
|
661
|
-
if (props.projectId?.kind === "expression") {
|
|
662
|
-
const app = describeApp(root, { envFile });
|
|
663
|
-
const variable = envVariableOf(props.projectId.text, app);
|
|
664
|
-
if (variable !== null) {
|
|
665
|
-
let found = null;
|
|
666
|
-
let problem = app.problem;
|
|
667
|
-
if (problem === null) {
|
|
668
|
-
try {
|
|
669
|
-
found = readEnvValue(app, variable);
|
|
670
|
-
} catch (error) {
|
|
671
|
-
problem = error.message;
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
setting = { variable, found, problem, where: found === null ? null : shown(cwd, found.file) };
|
|
675
|
-
}
|
|
676
|
-
}
|
|
677
|
-
const projectId = props.projectId?.kind === "literal" ? props.projectId.value : setting?.found?.value ?? null;
|
|
678
|
-
const query = projectId !== null && isValidProjectId(projectId) ? `?projectId=${encodeURIComponent(projectId)}` : "";
|
|
679
|
-
let health;
|
|
680
|
-
try {
|
|
681
|
-
health = await getJson(`${resolved.siteUrl}/critiqs/health${query}`, fetchFn, "Can't read the backend's health");
|
|
682
|
-
} catch (error) {
|
|
683
|
-
add("fail", "Health", error.message, "service", "observed");
|
|
684
|
-
return checks;
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
const hidden = props.requireProjectId ? "Critiqs stays hidden" : "Critiqs shows project setup";
|
|
688
|
-
if (props.projectId === null) add("fail", "Project", `${at} has no projectId. Run critiqs init to create a project and write its ID.`, "project");
|
|
689
|
-
else if (setting !== null && setting.problem !== null) {
|
|
690
|
-
add("warn", "Project", `${at} reads ${setting.variable}, but doctor can't determine its local value: ${setting.problem} Check with doctor --project-env-file <the .env file this app loads>.`, "project");
|
|
691
|
-
} else if (setting !== null && setting.found === null) {
|
|
692
|
-
add("warn", "Project", `${at} reads projectId from ${setting.variable}, which no .env file here sets, so ${hidden} on this computer. Run critiqs init to create or connect a project and set it.`, "project");
|
|
693
|
-
} else if (setting !== null && !isValidProjectId(projectId)) {
|
|
694
|
-
add("fail", "Project", `${setting.variable} in ${setting.where} is ${JSON.stringify(projectId.slice(0, 80))}, not a Critiqs project ID, so ${hidden} wherever it's used. Set it to the ID from project setup in the Critiqs sidebar, or run critiqs init.`, "project");
|
|
695
|
-
} else if (setting !== null && health.project === "found") {
|
|
696
|
-
add("pass", "Project", `${projectId} (${setting.variable} in ${setting.where}) exists on this backend.`, "project", "observed");
|
|
697
|
-
} else if (setting !== null) {
|
|
698
|
-
add("fail", "Project", `${projectId} (${setting.variable} in ${setting.where}) doesn't exist on this backend. Check the ID, or the backend it points to.`, "project", "observed");
|
|
699
|
-
} else if (props.projectId.kind === "expression") add("warn", "Project", `${at} sets projectId from code, so doctor can't check it.`, "project");
|
|
700
|
-
else if (!isValidProjectId(projectId)) add("fail", "Project", `"${projectId}" is not a Critiqs project ID.`, "project");
|
|
701
|
-
else if (health.project === "found") add("pass", "Project", `${projectId} exists on this backend.`, "project", "observed");
|
|
702
|
-
else add("fail", "Project", `${projectId} doesn't exist on this backend. Check the ID, or the backend it points to.`, "project", "observed");
|
|
703
|
-
|
|
704
|
-
if (setting !== null) {
|
|
705
|
-
const committed = setting.found !== null && !/\.local$/.test(setting.found.file);
|
|
706
|
-
const overridden = typeof shell[setting.variable] === "string" && shell[setting.variable] !== setting.found?.value;
|
|
707
|
-
add(
|
|
708
|
-
committed ? "warn" : "info",
|
|
709
|
-
"Deployments",
|
|
710
|
-
((committed
|
|
711
|
-
? `${setting.variable} is set in ${setting.where}, which is usually committed, so deployments built from this repository use it unless their build settings override it. Move it to .env.local and set it per deployment. `
|
|
712
|
-
: `Each deployment reads ${setting.variable} from its own build settings, which doctor can't see; where it's unset, ${hidden}. `) +
|
|
713
|
-
(overridden ? `This shell also sets ${setting.variable}, which builds started here use instead of the .env files. ` : "") +
|
|
714
|
-
(props.requireProjectId ? "" : "Add requireProjectId to <Critiqs /> so copies without a project show nothing instead of project setup.")
|
|
715
|
-
).trim(),
|
|
716
|
-
"reviewers",
|
|
717
|
-
);
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
if (health.project === "found") {
|
|
721
|
-
if (health.reviewAddress === false) {
|
|
722
|
-
add("warn", "Review address", "The project has no review address, so mention emails can't link to comments. Run critiqs init --review-url https://<deployed address>, or add it in the Critiqs sidebar's Project setup.", "reviewers");
|
|
723
|
-
} else if (health.reviewAddressLocal === true) {
|
|
724
|
-
add("warn", "Review address", "The project's review address only opens on one computer or network, so reviewers elsewhere can't follow mention emails. Once the prototype is deployed, run critiqs init --review-url https://<deployed address>.", "reviewers");
|
|
725
|
-
} else if (health.reviewAddressLocal === false) {
|
|
726
|
-
add("pass", "Review address", "Mention emails link to a public address. Deploy the commit with this project ID there.", "reviewers");
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
// A backend that trusts another's sign-in is only as ready as that service.
|
|
731
|
-
let signIn = health.signIn;
|
|
732
|
-
if (signIn === "external") {
|
|
733
|
-
try {
|
|
734
|
-
signIn = (await getJson(`${new URL(resolved.signInUrl).origin}/critiqs/health`, fetchFn, "Can't read the sign-in service's health")).signIn;
|
|
735
|
-
} catch {
|
|
736
|
-
signIn = "unreachable";
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
const via = health.signIn === "external" ? `Critiqs's sign-in service at ${resolved.signInUrl}` : "The backend";
|
|
740
|
-
const signInCheck = (status, detail) => add(status, "Sign-in", detail, "service");
|
|
741
|
-
if (signIn === "unconfigured") signInCheck("fail", `${via} doesn't name a sign-in service. Set CRITIQS_AUTH_ISSUER on it.`);
|
|
742
|
-
else if (signIn === "unreachable") signInCheck("fail", `Can't reach Critiqs's sign-in service at ${resolved.signInUrl}.`);
|
|
743
|
-
else if (signIn === "unavailable" || signIn === "external") {
|
|
744
|
-
signInCheck(
|
|
745
|
-
"fail",
|
|
746
|
-
resolved.transport === "http"
|
|
747
|
-
? "Your app's Critiqs server can't sign anyone in: pass email to createCritiqsHandler, or identify to use your app's own sign-in."
|
|
748
|
-
: `${via} can't sign anyone in. It needs CRITIQS_AUTH_PRIVATE_KEY, RESEND_API_KEY, and CRITIQS_EMAIL_FROM.`,
|
|
749
|
-
);
|
|
750
|
-
} else if (signIn === "host") signInCheck("pass", "Reviewers are whoever is signed in to your app.");
|
|
751
|
-
else if (signIn === "development") signInCheck("warn", `${via} shows sign-in codes on screen; use it only on this computer.`);
|
|
752
|
-
else signInCheck("pass", `${via} is configured to email sign-in codes.`);
|
|
753
|
-
|
|
754
|
-
if (health.captures) {
|
|
755
|
-
add(
|
|
756
|
-
health.captures.configured ? "pass" : "fail",
|
|
757
|
-
"Screenshots",
|
|
758
|
-
health.captures.configured
|
|
759
|
-
? `Screenshot storage is configured (${health.captures.provider}); the first comment with a screenshot exercises it.`
|
|
760
|
-
: "Screenshot storage is not configured. Check CRITIQS_CAPTURE_STORAGE and the CRITIQS_R2_* settings on the backend.",
|
|
761
|
-
"service",
|
|
762
|
-
);
|
|
763
|
-
}
|
|
764
|
-
if (health.ai) {
|
|
765
|
-
const provider = health.ai.defaultProvider;
|
|
766
|
-
const aiCheck = (status, detail) => add(status, "AI", detail, "optional");
|
|
767
|
-
if (health.ai.managed) aiCheck("pass", "Critiqs-managed AI is configured; project owners can also connect their own provider.");
|
|
768
|
-
else if (provider) aiCheck("pass", `Projects use ${provider} as configured on the backend${health.ai.keysStorable ? "; owners can connect their own provider too" : ""}.`);
|
|
769
|
-
else if (health.ai.keysStorable) aiCheck("pass", "Project owners can connect their own AI provider in Critiqs. Search and grouping work without one.");
|
|
770
|
-
else {
|
|
771
|
-
const off = "AI is off, which is fine: comments work, search matches words and tags, and tags are grouped by hand.";
|
|
772
|
-
aiCheck(
|
|
773
|
-
"info",
|
|
774
|
-
resolved.transport === "http"
|
|
775
|
-
? `${off} Pass ai to createCritiqsHandler to add a provider.`
|
|
776
|
-
: resolved.backendUrl === CLOUD_BACKEND_URL
|
|
777
|
-
? `${off} Critiqs Cloud hasn't turned AI on; there's nothing to set up in your app.`
|
|
778
|
-
: `${off} Set CRITIQS_AI_ENCRYPTION_KEY on the backend so owners can connect a provider.`,
|
|
779
|
-
);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
const mentions = health.mentionEmails ?? {};
|
|
783
|
-
if (!health.email) {
|
|
784
|
-
add(
|
|
785
|
-
"warn",
|
|
786
|
-
"Email",
|
|
787
|
-
resolved.transport === "http"
|
|
788
|
-
? "Mention emails are off: pass email: { resendApiKey, from } to createCritiqsHandler to send them."
|
|
789
|
-
: "Mention emails are off: set RESEND_API_KEY and CRITIQS_EMAIL_FROM on the backend to send them.",
|
|
790
|
-
"service",
|
|
791
|
-
);
|
|
792
|
-
} else if (mentions.overdue) {
|
|
793
|
-
const minutes = Math.round((now - mentions.waitingSince) / 60_000);
|
|
794
|
-
add("fail", "Email", `Mention emails have waited ${minutes} minutes, so scheduled sending isn't running. Check the deployment's scheduled functions.`, "service", "observed");
|
|
795
|
-
} else if (mentions.last?.status === "failed") {
|
|
796
|
-
add("fail", "Email", "The last mention email failed. Check the Resend key and that the sender's domain is verified in Resend.", "service", "observed");
|
|
797
|
-
} else if (mentions.last?.status === "sent") {
|
|
798
|
-
add("pass", "Email", "Mention emails are going out: the last one was sent.", "service", "observed");
|
|
799
|
-
} else {
|
|
800
|
-
add("pass", "Email", "Email is configured; no mention email has been sent yet, so delivery isn't proven.", "service");
|
|
801
|
-
}
|
|
802
|
-
return checks;
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
/** A doctor report for agents and scripts: every check, whether any failed, and what doctor didn't do. */
|
|
806
|
-
export function doctorReport(checks) {
|
|
807
|
-
return { ok: !checks.some((check) => check.status === "fail"), checks, note: DOCTOR_NOTE };
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
/**
|
|
811
|
-
* Where setup stands after init, in stages: the code, the project, trying it
|
|
812
|
-
* locally, and reviewers on other computers. Each is pass, warn, fail, or
|
|
813
|
-
* next (a step only the person can take, such as deploying).
|
|
814
|
-
*/
|
|
815
|
-
export function readiness({ written, projectId, projectName, backendUrl, reviewAddress, reused = false, connected = false }) {
|
|
816
|
-
const stages = [];
|
|
817
|
-
const add = (status, name, detail) => stages.push({ status, name, detail });
|
|
818
|
-
if (written.ok) add("pass", "Code", written.message);
|
|
819
|
-
else add("fail", "Code", `${written.message}\nThe project ${projectId} already exists on ${backendUrl}. Preserve both its project ID and backend when reconnecting.`);
|
|
820
|
-
const where = backendUrl === CLOUD_BACKEND_URL ? "Critiqs Cloud" : backendUrl;
|
|
821
|
-
add("pass", "Project", `${connected ? "Already connected to" : reused ? "Reusing your project" : "Created"} "${projectName}" (${projectId}) on ${where}.`);
|
|
822
|
-
add("next", "Try it locally", `Start the app's dev server${written.env ? " (restart it if it's running, so it reads the new setting)" : ""}, open it in a browser, and sign in from the Critiqs toolbar to leave a comment.`);
|
|
823
|
-
if (written.env) add("next", "Deployments", written.env.advice);
|
|
824
|
-
if (reviewAddress === null || reviewAddress === undefined) {
|
|
825
|
-
add("warn", "Reviewers elsewhere", "Commit and deploy this change. The project has no review address, so mention emails can't link to comments: once deployed, run critiqs init --review-url https://<deployed address>.");
|
|
826
|
-
} else if (isLocalAddress(reviewAddress)) {
|
|
827
|
-
add("warn", "Reviewers elsewhere", `Commit and deploy this change. The review address ${reviewAddress} only opens on this computer or network: once deployed, run critiqs init --review-url https://<deployed address>.`);
|
|
828
|
-
} else {
|
|
829
|
-
add("next", "Reviewers elsewhere", `Commit and deploy this change to ${reviewAddress}; every copy with this project ID (local, preview, deployed) shares its feedback.`);
|
|
830
|
-
}
|
|
831
|
-
return stages;
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
// ---------------------------------------------------------------------------
|
|
835
|
-
// The whole setup
|
|
836
|
-
|
|
837
|
-
/**
|
|
838
|
-
* A name for the project: the app's package name, or its folder's. In a
|
|
839
|
-
* workspace it also names the workspace, and the app's path when another
|
|
840
|
-
* package shares its name, so each app finds and reuses only its own project.
|
|
841
|
-
*/
|
|
842
|
-
export function defaultProjectName(root) {
|
|
843
|
-
return describeApp(root).projectName;
|
|
844
|
-
}
|
|
845
|
-
|
|
846
|
-
/**
|
|
847
|
-
* The project the code already names: a literal ID, or for environment-backed
|
|
848
|
-
* wiring (see `chooseWiring`), the ID this computer's `.env` files set, with
|
|
849
|
-
* where. A missing or malformed setting names no project.
|
|
850
|
-
*/
|
|
851
|
-
function connectedProject(root, wiring) {
|
|
852
|
-
const settings = readComponentProps(root);
|
|
853
|
-
if ("error" in settings) return null;
|
|
854
|
-
const id = settings.projectId;
|
|
855
|
-
const backend = settings.backend;
|
|
856
|
-
if (backend !== null && backend.kind !== "literal") return null;
|
|
857
|
-
const backendUrl = backend?.value.replace(/\/$/, "") ?? CLOUD_BACKEND_URL;
|
|
858
|
-
if (id?.kind === "literal") return isValidProjectId(id.value) ? { projectId: id.value, backendUrl } : null;
|
|
859
|
-
if (wiring.mode !== "env" || id?.kind !== "expression" || envVariableOf(id.text, wiring.app) !== wiring.variable) return null;
|
|
860
|
-
const found = readEnvValue(wiring.app, wiring.variable);
|
|
861
|
-
if (found === null || !isValidProjectId(found.value)) return null;
|
|
862
|
-
return { projectId: found.value, backendUrl, env: { name: wiring.variable, file: found.file } };
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
/**
|
|
866
|
-
* Sets up Critiqs for the prototype in `root`, in two halves so a coding agent
|
|
867
|
-
* can hand the sign-in to a person between them:
|
|
868
|
-
* - `beginSetup` checks the code can take the result (adding `<Critiqs />`
|
|
869
|
-
* where the app renders when it has none), deploys to the team's own Convex
|
|
870
|
-
* when asked (`target: "own-convex"`), checks the backend, and starts
|
|
871
|
-
* sign-in: a page on this computer (`signIn: "browser"`), or approval from
|
|
872
|
-
* any device (`"remote"`); `"auto"` picks remote when this computer seems to
|
|
873
|
-
* have no browser and the service supports it.
|
|
874
|
-
* `target: "cloud"` uses Critiqs Cloud; a URL uses an existing Critiqs backend.
|
|
875
|
-
* - `finish()` waits for sign-in, reuses the person's project with this name
|
|
876
|
-
* (unless `newProject`) or creates one, ends the command line's session,
|
|
877
|
-
* and writes `projectId` (and `backend`, unless Critiqs Cloud).
|
|
878
|
-
* When the code already names a project, it is kept: setup returns
|
|
879
|
-
* `{ connected }` without signing in, or with `reviewUrl`, signs in only to
|
|
880
|
-
* set that project's review address.
|
|
881
|
-
*/
|
|
882
|
-
export async function beginSetup({
|
|
883
|
-
root,
|
|
884
|
-
cwd = root,
|
|
885
|
-
target = null,
|
|
886
|
-
name,
|
|
887
|
-
reviewUrl,
|
|
888
|
-
keys = {},
|
|
889
|
-
env = process.env,
|
|
890
|
-
log = () => {},
|
|
891
|
-
fetchFn = fetch,
|
|
892
|
-
entry = null,
|
|
893
|
-
mount = null,
|
|
894
|
-
newProject = false,
|
|
895
|
-
signIn: method = "browser",
|
|
896
|
-
envFile = null,
|
|
897
|
-
sleep,
|
|
898
|
-
}) {
|
|
899
|
-
if (reviewUrl !== undefined && reviewUrl !== null && !/^https:\/\/|^http:\/\/(localhost|127\.0\.0\.1)[:/]/.test(reviewUrl)) {
|
|
900
|
-
throw new SetupError("The review address must be the prototype's https:// address (or http://localhost while testing).");
|
|
901
|
-
}
|
|
902
|
-
// Which app, and how its code names the project, before anything is read from or sent to a backend.
|
|
903
|
-
let apps = null;
|
|
904
|
-
try {
|
|
905
|
-
apps = workspaceApps(root);
|
|
906
|
-
} catch {}
|
|
907
|
-
if (apps !== null && apps.length > 0) throw new SetupError(workspaceRefusal(apps, shown(cwd, root), (dir) => shown(cwd, dir), "npx critiqs-react init"));
|
|
908
|
-
const wiring = chooseWiring(root, { envFile });
|
|
909
|
-
if (wiring.problem) throw new SetupError(wiring.problem);
|
|
910
|
-
let configured;
|
|
911
|
-
try {
|
|
912
|
-
configured = connectedProject(root, wiring);
|
|
913
|
-
} catch {
|
|
914
|
-
throw new SetupError("Couldn't read this app's .env files. Restore access, then run setup again; no project was created.");
|
|
915
|
-
}
|
|
916
|
-
const existing = newProject ? null : configured;
|
|
917
|
-
const settings = readComponentProps(root);
|
|
918
|
-
const configuredBackend = !("error" in settings) && settings.backend?.kind === "literal"
|
|
919
|
-
? settings.backend.value.replace(/\/$/, "")
|
|
920
|
-
: null;
|
|
921
|
-
// Without an explicit choice, a project the code names stays where it is, and a new one goes to Critiqs Cloud.
|
|
922
|
-
const explicit = target !== null && target !== undefined;
|
|
923
|
-
target = explicit ? target : (configuredBackend ?? "cloud");
|
|
924
|
-
if (existing !== null) {
|
|
925
|
-
const asked = target === "cloud" ? CLOUD_BACKEND_URL : target;
|
|
926
|
-
if (explicit && (target === "own-convex" || asked.replace(/\/$/, "") !== existing.backendUrl)) {
|
|
927
|
-
throw new SetupError(
|
|
928
|
-
`The code already uses project ${existing.projectId} on ${existing.backendUrl === CLOUD_BACKEND_URL ? "Critiqs Cloud" : existing.backendUrl}, so setup didn't create another. Pass --new-project to replace it with a new one.`,
|
|
929
|
-
);
|
|
930
|
-
}
|
|
931
|
-
if (reviewUrl === undefined || reviewUrl === null) return { connected: existing, backendUrl: existing.backendUrl };
|
|
932
|
-
}
|
|
933
|
-
|
|
934
|
-
// Check the component can take the settings before anyone signs in or anything is created.
|
|
935
|
-
// Capture this before sign-in; source permissions may change while approval
|
|
936
|
-
// is pending, and a later read failure must not discard a created project.
|
|
937
|
-
const named = !("error" in settings) && settings.backend !== null;
|
|
938
|
-
const backendProp = (backendUrl) => (backendUrl === CLOUD_BACKEND_URL && !named ? undefined : backendUrl);
|
|
939
|
-
const props = (projectId, backendUrl) => connectionProps(wiring, projectId, backendProp(backendUrl));
|
|
940
|
-
const connect = (projectId, backendUrl, placed = {}) => writeConnection({ root, cwd, wiring, projectId, backend: backendProp(backendUrl), ...placed });
|
|
941
|
-
if (existing === null) {
|
|
942
|
-
const planned = target === "cloud" ? CLOUD_BACKEND_URL : target === "own-convex" ? "https://example.convex.cloud" : target;
|
|
943
|
-
const precheck = connect("p".repeat(32), planned, { dryRun: true, entry, mount });
|
|
944
|
-
if (!precheck.ok) throw new SetupError(precheck.message.replaceAll("p".repeat(32), "<the new project ID>"));
|
|
945
|
-
// Environment-backed wiring that is already in place leaves the source as it is.
|
|
946
|
-
if (wiring.mode !== "env" || precheck.changed.length > 0) {
|
|
947
|
-
try {
|
|
948
|
-
accessSync(precheck.file, constants.W_OK);
|
|
949
|
-
} catch {
|
|
950
|
-
throw new SetupError(`Can't write ${shown(cwd, precheck.file)}. Check the file's permissions, then run setup again; no project was created.`);
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
let backendUrl;
|
|
956
|
-
if (existing !== null) backendUrl = existing.backendUrl;
|
|
957
|
-
else if (target === "cloud") backendUrl = CLOUD_BACKEND_URL;
|
|
958
|
-
else if (target === "own-convex") {
|
|
959
|
-
backendUrl = await deployOwnConvex({
|
|
960
|
-
env: { ...env, ...(keys.convexDeployKey ? { CONVEX_DEPLOY_KEY: keys.convexDeployKey } : {}) },
|
|
961
|
-
signInUrl: env.CRITIQS_SIGN_IN_URL,
|
|
962
|
-
resendApiKey: keys.resendApiKey ?? env.RESEND_API_KEY,
|
|
963
|
-
emailFrom: keys.emailFrom ?? env.CRITIQS_EMAIL_FROM,
|
|
964
|
-
log,
|
|
965
|
-
});
|
|
966
|
-
} else backendUrl = target;
|
|
967
|
-
if (backendUrl.startsWith("/")) {
|
|
968
|
-
throw new SetupError(
|
|
969
|
-
`The app uses Critiqs inside its own server at ${backendUrl}. ${existing !== null ? "Change this project's review address" : "Create a new project"} in the Critiqs sidebar on the running app${existing !== null ? "." : `, then set its projectId on the existing component, keeping backend=${JSON.stringify(backendUrl)}.`} No Cloud project was created.`,
|
|
970
|
-
);
|
|
971
|
-
}
|
|
972
|
-
const backend = await resolveBackend(backendUrl, { fetchFn });
|
|
973
|
-
if (backend.transport === "http") {
|
|
974
|
-
throw new SetupError(
|
|
975
|
-
`${backend.backendUrl} is Critiqs inside your app's own server. Set backend=${JSON.stringify(backend.backendUrl)} on the existing Critiqs component. If the app has none, import { Critiqs } from "critiqs-react" and add ${componentSnippet({ backend: backend.backendUrl })} once. Create the project in its Critiqs sidebar, then set its projectId on that same component, keeping its backend.`,
|
|
976
|
-
);
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
let remote = method === "remote";
|
|
980
|
-
if (method === "auto" && isHeadless(env)) {
|
|
981
|
-
try {
|
|
982
|
-
const config = await getJson(`${new URL(backend.signInUrl).origin}/critiqs/config`, fetchFn, "Can't reach the sign-in service");
|
|
983
|
-
remote = config.deviceSignIn === true;
|
|
984
|
-
if (!remote) log("This computer may not show a browser, and the sign-in service can't approve setup from another device yet; opening sign-in here.");
|
|
985
|
-
} catch {}
|
|
986
|
-
}
|
|
987
|
-
const signIn = remote
|
|
988
|
-
? await startRemoteSignIn({ signInUrl: backend.signInUrl, fetchFn, ...(sleep ? { sleep } : {}) })
|
|
989
|
-
: await startBrowserSignIn({ signInUrl: backend.signInUrl });
|
|
990
|
-
const projectName = (name ?? defaultProjectName(root)).trim() || "Prototype";
|
|
991
|
-
return {
|
|
992
|
-
url: signIn.url,
|
|
993
|
-
method: remote ? "remote" : "browser",
|
|
994
|
-
userCode: signIn.userCode ?? null,
|
|
995
|
-
backendUrl: backend.backendUrl,
|
|
996
|
-
cancel: signIn.close,
|
|
997
|
-
finish: async () => {
|
|
998
|
-
const { accessToken, refreshToken, reviewer = null } = await signIn.tokens;
|
|
999
|
-
try {
|
|
1000
|
-
if (existing !== null) {
|
|
1001
|
-
log("Setting the review address…");
|
|
1002
|
-
await callConvex(backend.backendUrl, "mutation", "projects:setReviewUrl", { projectId: existing.projectId, reviewUrl }, accessToken, { fetchFn });
|
|
1003
|
-
const project = await callConvex(backend.backendUrl, "query", "projects:get", { projectId: existing.projectId }, accessToken, { fetchFn });
|
|
1004
|
-
const written = connect(existing.projectId, backend.backendUrl);
|
|
1005
|
-
return { projectId: existing.projectId, projectName: project.name, backendUrl: backend.backendUrl, written, reviewAddress: reviewUrl, reused: true, connected: true, approvedBy: reviewer };
|
|
1006
|
-
}
|
|
1007
|
-
let projectId = null;
|
|
1008
|
-
let reused = false;
|
|
1009
|
-
let reviewAddress = reviewUrl ?? null;
|
|
1010
|
-
if (!newProject) {
|
|
1011
|
-
// A retry after a failed write finds the project the first try created.
|
|
1012
|
-
let mine = [];
|
|
1013
|
-
try {
|
|
1014
|
-
mine = (await listMyProjects({ backendUrl: backend.backendUrl, accessToken, fetchFn })).filter((project) => project.name === projectName);
|
|
1015
|
-
} catch {
|
|
1016
|
-
throw new SetupError("Couldn't check your existing projects. Run setup again when the backend is reachable; no new project was created.");
|
|
1017
|
-
}
|
|
1018
|
-
if (mine.length > 1) {
|
|
1019
|
-
throw new SetupError(
|
|
1020
|
-
`You already have ${mine.length} projects named "${projectName}". No project or source was changed. ` +
|
|
1021
|
-
(wiring.mode === "env"
|
|
1022
|
-
? `Choose one project below: add the import and component where the app renders (once; update an existing Critiqs component instead of adding another), preserving the backend, and set ${wiring.variable} to that project's ID in this app's .env.local. `
|
|
1023
|
-
: "Choose one complete connection below and add its import and component where the app renders, preserving the backend. Update an existing Critiqs component instead of adding another. ") +
|
|
1024
|
-
(entry === null ? "" : `Use ${shown(cwd, resolve(root, entry))}${mount === null ? "" : ` beside <${mount}>`}. `) +
|
|
1025
|
-
"Or pass --new-project to create another.\n" +
|
|
1026
|
-
'import { Critiqs } from "critiqs-react";\n' +
|
|
1027
|
-
(wiring.mode === "env"
|
|
1028
|
-
? `${componentSnippet(props(mine[0]._id, backend.backendUrl))}\n${mine.map((project) => `${wiring.variable}=${project._id}`).join("\n")}`
|
|
1029
|
-
: mine.map((project) => componentSnippet(props(project._id, backend.backendUrl))).join("\n")),
|
|
1030
|
-
);
|
|
1031
|
-
}
|
|
1032
|
-
if (mine.length === 1) {
|
|
1033
|
-
projectId = mine[0]._id;
|
|
1034
|
-
reused = true;
|
|
1035
|
-
reviewAddress = mine[0].reviewUrl ?? null;
|
|
1036
|
-
if (reviewUrl !== undefined && reviewUrl !== null && reviewUrl !== reviewAddress) {
|
|
1037
|
-
await callConvex(backend.backendUrl, "mutation", "projects:setReviewUrl", { projectId, reviewUrl }, accessToken, { fetchFn });
|
|
1038
|
-
reviewAddress = reviewUrl;
|
|
1039
|
-
}
|
|
1040
|
-
log(`Reusing your project "${projectName}" (${projectId}). Pass --new-project to create another.`);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
if (projectId === null) {
|
|
1044
|
-
log("Creating the project…");
|
|
1045
|
-
projectId = await createProject({ backendUrl: backend.backendUrl, accessToken, name: projectName, reviewUrl: reviewUrl ?? null, fetchFn });
|
|
1046
|
-
}
|
|
1047
|
-
const written = connect(projectId, backend.backendUrl, { entry, mount });
|
|
1048
|
-
return { projectId, projectName, backendUrl: backend.backendUrl, written, reviewAddress, reused, connected: false, approvedBy: reviewer };
|
|
1049
|
-
} finally {
|
|
1050
|
-
if (refreshToken) await signOut(backend.signInUrl, refreshToken, { origin: new URL(signIn.url).origin, fetchFn });
|
|
1051
|
-
}
|
|
1052
|
-
},
|
|
1053
|
-
};
|
|
1054
|
-
}
|