@lago-morph/prototype-framework 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +4 -2
  2. package/dist/cli/cloudflare-settings.d.ts +30 -0
  3. package/dist/cli/cloudflare-settings.js +47 -0
  4. package/dist/cli/commands/admins.js +1 -1
  5. package/dist/cli/commands/check-login.js +1 -1
  6. package/dist/cli/commands/cloudflare-setup.d.ts +11 -0
  7. package/dist/cli/commands/cloudflare-setup.js +34 -0
  8. package/dist/cli/commands/mail.js +1 -1
  9. package/dist/cli/commands/operations.js +4 -1
  10. package/dist/cli/commands/upgrade.d.ts +38 -0
  11. package/dist/cli/commands/upgrade.js +170 -0
  12. package/dist/cli/commands/verify.d.ts +6 -0
  13. package/dist/cli/commands/verify.js +14 -0
  14. package/dist/cli/commands/version-check.d.ts +31 -0
  15. package/dist/cli/commands/version-check.js +127 -0
  16. package/dist/cli/commands/versions.d.ts +30 -0
  17. package/dist/cli/commands/versions.js +117 -0
  18. package/dist/cli/main.js +14 -13
  19. package/dist/cli/wiring.d.ts +14 -0
  20. package/dist/cli/wiring.js +21 -5
  21. package/dist/provision/cloudflare/account-settings.d.ts +5 -1
  22. package/dist/provision/cloudflare/account-settings.js +14 -2
  23. package/dist/provision/cloudflare/account.d.ts +20 -2
  24. package/dist/provision/cloudflare/account.js +62 -28
  25. package/dist/provision/cloudflare/api.d.ts +19 -0
  26. package/dist/provision/cloudflare/api.js +60 -0
  27. package/dist/provision/cloudflare/backup.d.ts +3 -3
  28. package/dist/provision/cloudflare/backup.js +3 -8
  29. package/dist/provision/cloudflare/cloudflare-setup.d.ts +82 -0
  30. package/dist/provision/cloudflare/cloudflare-setup.js +710 -0
  31. package/dist/provision/cloudflare/email-permissions.d.ts +2 -1
  32. package/dist/provision/cloudflare/email-permissions.js +4 -2
  33. package/dist/provision/cloudflare/email.d.ts +24 -1
  34. package/dist/provision/cloudflare/email.js +120 -18
  35. package/dist/provision/cloudflare/environment.d.ts +5 -1
  36. package/dist/provision/cloudflare/environment.js +2 -2
  37. package/dist/provision/cloudflare/git-safety.d.ts +31 -0
  38. package/dist/provision/cloudflare/git-safety.js +113 -0
  39. package/dist/provision/cloudflare/permissions.d.ts +141 -0
  40. package/dist/provision/cloudflare/permissions.js +187 -0
  41. package/dist/provision/cloudflare/plan.d.ts +5 -2
  42. package/dist/provision/cloudflare/plan.js +19 -2
  43. package/dist/provision/cloudflare/r2-token.d.ts +2 -1
  44. package/dist/provision/cloudflare/r2-token.js +4 -3
  45. package/dist/provision/cloudflare/setup-record.d.ts +42 -0
  46. package/dist/provision/cloudflare/setup-record.js +103 -0
  47. package/dist/provision/cloudflare/setup-steps.d.ts +60 -0
  48. package/dist/provision/cloudflare/setup-steps.js +167 -0
  49. package/dist/provision/cloudflare/target.d.ts +4 -0
  50. package/dist/provision/cloudflare/target.js +34 -8
  51. package/dist/provision/cloudflare/token-sources.d.ts +56 -0
  52. package/dist/provision/cloudflare/token-sources.js +255 -0
  53. package/dist/provision/core/local-setup.d.ts +32 -0
  54. package/dist/provision/core/local-setup.js +134 -0
  55. package/dist/provision/public.d.ts +6 -1
  56. package/dist/provision/public.js +6 -1
  57. package/dist/testing/connect.js +1 -1
  58. package/package.json +5 -3
  59. package/skill/SKILL.md +67 -0
  60. package/skill/VERSION +1 -0
  61. package/skill/examples/admin-and-current-user.md +105 -0
  62. package/skill/examples/configuration.md +100 -0
  63. package/skill/examples/endpoint-and-page.md +194 -0
  64. package/skill/examples/files-tickets.md +152 -0
  65. package/skill/examples/notes-sql.md +218 -0
  66. package/skill/examples/secrets.md +190 -0
  67. package/skill/examples/status-kv.md +74 -0
  68. package/skill/examples/tests.md +287 -0
  69. package/skill/reference/configuration.md +62 -0
  70. package/skill/reference/current-user.md +65 -0
  71. package/skill/reference/deploying.md +122 -0
  72. package/skill/reference/files.md +65 -0
  73. package/skill/reference/http-and-validation.md +91 -0
  74. package/skill/reference/kv.md +41 -0
  75. package/skill/reference/local-development.md +73 -0
  76. package/skill/reference/log.md +54 -0
  77. package/skill/reference/owner-tasks.md +158 -0
  78. package/skill/reference/secrets.md +42 -0
  79. package/skill/reference/sql-and-migrations.md +104 -0
  80. package/skill/reference/testing.md +55 -0
  81. package/skill/reference/troubleshooting.md +137 -0
  82. package/skill/templates/FRAMEWORK-ISSUE.md +14 -0
  83. package/skill/templates/README.md +10 -0
  84. package/skill/templates/production-stage.json +6 -0
package/README.md CHANGED
@@ -26,9 +26,11 @@ The other subpaths (`/targets/*`, `/provision`, `/check`) are used by the comman
26
26
 
27
27
  ## Commands
28
28
 
29
- Run them in an app's folder as `npx prototype-framework <command>` or `npm run <command>`:
29
+ Run them in an app's folder as `npm run <command>` or `npm exec --no -- prototype-framework <command>` (not plain `npx`, which, before `npm install`, would fetch an unrelated package of that name):
30
30
 
31
- `dev`, `verify`, `build`, `generate-migration`, `deploy`, `smoke`, `remove`, `secrets`, `setup-account`, `check-login`, `mail`, `admins`, `reset-local`.
31
+ `dev`, `verify`, `build`, `generate-migration`, `deploy`, `smoke`, `remove`, `stop`, `start`, `secrets`, `cloudflare-setup`, `setup-account`, `check-login`, `mail`, `admins`, `reset-local`, `version-check`, `upgrade`.
32
+
33
+ `cloudflare-setup` sets up Cloudflare from two pre-filled token links; see the [quickstart](https://github.com/lago-morph/cloud-app/blob/main/QUICKSTART.md).
32
34
 
33
35
  `verify` runs the type check, the portability lint, the app's tests and the migration checks. Run it before calling a change done.
34
36
 
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Every Cloudflare command's settings (plan-setup-wizard §4.2 and §4.5; DEC-0570, DEC-0572): a
3
+ * command run with `--target cloudflare` gets the process environment merged with the project's
4
+ * `.env.cloudflare` (`cloudflareEnvironment`, the environment winning), so nobody exports the
5
+ * variables by hand. Before the command runs, its notices (a setting that differs between the two
6
+ * sources, by name) and the file's git warnings (not ignored, tracked) are printed to standard
7
+ * error, on every run. They never fail the command. A command on another target reads no file.
8
+ * The file's bootstrap token is left out (DEC-0574): these commands work with the everyday token,
9
+ * and a token they do not use does not reach their tools' processes (SST).
10
+ */
11
+ export interface CloudflareSettingsOptions {
12
+ /** Opt out of DEC-0574: also pass the file's `CLOUDFLARE_BOOTSTRAP_TOKEN` (`cloudflare-setup` only). */
13
+ readonly withBootstrapToken?: boolean;
14
+ }
15
+ import type { CliIo, Command } from "./io.js";
16
+ import { type ProcessEnvironment } from "./commands/smoke-cloud.js";
17
+ /** A warning set off so that it is not lost in a command's output. */
18
+ export declare function formatGitWarning(command: string, warning: string): string;
19
+ /** Prints the git warnings for `.env.cloudflare` in `dir` (none outside a repository). Never throws. */
20
+ export declare function printGitSafetyWarnings(command: string, dir: string, io: Pick<CliIo, "stderr">): void;
21
+ /**
22
+ * The environment a Cloudflare command runs with, after printing the sources' notices and the
23
+ * file's warnings to `io` (only when the file exists or is tracked, inside a repository).
24
+ */
25
+ export declare function commandCloudflareEnvironment(command: string, env: ProcessEnvironment, io: Pick<CliIo, "cwd" | "stderr">, options?: CloudflareSettingsOptions): ProcessEnvironment;
26
+ /**
27
+ * `load`'s command, built with the merged environment when the arguments name `--target cloudflare`
28
+ * and with `env` unchanged otherwise.
29
+ */
30
+ export declare function withCloudflareSettings(command: string, load: (env: ProcessEnvironment) => Command | Promise<Command>, env?: ProcessEnvironment, options?: CloudflareSettingsOptions): Command;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Every Cloudflare command's settings (plan-setup-wizard §4.2 and §4.5; DEC-0570, DEC-0572): a
3
+ * command run with `--target cloudflare` gets the process environment merged with the project's
4
+ * `.env.cloudflare` (`cloudflareEnvironment`, the environment winning), so nobody exports the
5
+ * variables by hand. Before the command runs, its notices (a setting that differs between the two
6
+ * sources, by name) and the file's git warnings (not ignored, tracked) are printed to standard
7
+ * error, on every run. They never fail the command. A command on another target reads no file.
8
+ * The file's bootstrap token is left out (DEC-0574): these commands work with the everyday token,
9
+ * and a token they do not use does not reach their tools' processes (SST).
10
+ */
11
+ import { commandGitSafetyWarnings, inspectGitSafety } from "../provision/cloudflare/git-safety.js";
12
+ import { mergeCloudflareSettings, readCloudflareSettings } from "../provision/cloudflare/token-sources.js";
13
+ import { targetArgument } from "./commands/smoke-cloud.js";
14
+ const RULE = "=".repeat(78);
15
+ /** A warning set off so that it is not lost in a command's output. */
16
+ export function formatGitWarning(command, warning) {
17
+ return `${RULE}\n${command}: WARNING: ${warning}\n${RULE}\n`;
18
+ }
19
+ /** Prints the git warnings for `.env.cloudflare` in `dir` (none outside a repository). Never throws. */
20
+ export function printGitSafetyWarnings(command, dir, io) {
21
+ for (const warning of commandGitSafetyWarnings(inspectGitSafety(dir)))
22
+ io.stderr(formatGitWarning(command, warning));
23
+ }
24
+ /**
25
+ * The environment a Cloudflare command runs with, after printing the sources' notices and the
26
+ * file's warnings to `io` (only when the file exists or is tracked, inside a repository).
27
+ */
28
+ export function commandCloudflareEnvironment(command, env, io, options = {}) {
29
+ const settings = readCloudflareSettings(io.cwd, env);
30
+ for (const notice of settings.notices)
31
+ io.stderr(`${command}: note: ${notice}\n`);
32
+ printGitSafetyWarnings(command, io.cwd, io);
33
+ if (options.withBootstrapToken === true)
34
+ return mergeCloudflareSettings(env, settings);
35
+ const everyday = Object.fromEntries(Object.entries(settings.values).filter(([name]) => name !== "CLOUDFLARE_BOOTSTRAP_TOKEN"));
36
+ return mergeCloudflareSettings(env, { ...settings, values: everyday });
37
+ }
38
+ /**
39
+ * `load`'s command, built with the merged environment when the arguments name `--target cloudflare`
40
+ * and with `env` unchanged otherwise.
41
+ */
42
+ export function withCloudflareSettings(command, load, env = process.env, options = {}) {
43
+ return async (args, io) => {
44
+ const merged = targetArgument(args) === "cloudflare" ? commandCloudflareEnvironment(command, env, io, options) : env;
45
+ return (await load(merged))(args, io);
46
+ };
47
+ }
@@ -102,7 +102,7 @@ export function adminsCommand(deps) {
102
102
  return refused;
103
103
  const missing = deps.missingCredentials?.() ?? [];
104
104
  if (missing.length > 0) {
105
- io.stderr(`admins failed: missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment; values are never printed)\n`);
105
+ io.stderr(`admins failed: missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment or in .env.cloudflare; values are never printed)\n`);
106
106
  return EXIT.failed;
107
107
  }
108
108
  }
@@ -301,7 +301,7 @@ export function checkLoginCommand(deps) {
301
301
  return refused;
302
302
  const missing = deps.missingCredentials();
303
303
  if (missing.length > 0)
304
- return fail(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment; values are never printed)`);
304
+ return fail(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment or in .env.cloudflare; values are never printed)`);
305
305
  let repo;
306
306
  let commit;
307
307
  try {
@@ -0,0 +1,11 @@
1
+ import { type CloudflareSetupDeps } from "../../provision/cloudflare/cloudflare-setup.js";
2
+ import type { Command } from "../io.js";
3
+ import { type ProcessEnvironment } from "./smoke-cloud.js";
4
+ /** PAR-360: how long the network check waits for each host. */
5
+ export declare const NETWORK_CHECK_TIMEOUT_MS = 10000;
6
+ export type CloudflareSetupCommandDeps = Omit<CloudflareSetupDeps, "projectDir">;
7
+ export declare function cloudflareSetupCommand(deps: CloudflareSetupCommandDeps): Command;
8
+ /** Any HTTPS answer means the host is reachable; a request that gets none rejects. */
9
+ export declare function reachWith(doFetch?: typeof fetch, timeoutMs?: number): (url: string) => Promise<void>;
10
+ /** `cloudflare-setup` bound to the real Cloudflare API and network. */
11
+ export declare function cloudflareSetupBinding(env?: ProcessEnvironment): Command;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * `cloudflare-setup [--email-domain <domain>] [--switch-account]` (CLI-REQ-001; plan-setup-wizard
3
+ * §4.3; DEC-0584): the re-runnable Cloudflare setup (`runCloudflareSetup`). It has no `--target`:
4
+ * it reads `.env.cloudflare` itself, bootstrap token included (DEC-0574's opt-out, DEC-0584), after
5
+ * running the local setup, so it is bound with `lazy`, not `cloud`. The template's npm script
6
+ * `cloudflare-setup` runs it.
7
+ */
8
+ import { createCloudflareApi } from "../../provision/cloudflare/api.js";
9
+ import { runCloudflareSetup } from "../../provision/cloudflare/cloudflare-setup.js";
10
+ import { parseOptions } from "../args.js";
11
+ import { cloudProcessProblems } from "./smoke-cloud.js";
12
+ /** PAR-360: how long the network check waits for each host. */
13
+ export const NETWORK_CHECK_TIMEOUT_MS = 10_000;
14
+ export function cloudflareSetupCommand(deps) {
15
+ return async (args, io) => {
16
+ const switchAccount = args.includes("--switch-account");
17
+ const options = parseOptions(args.filter((a) => a !== "--switch-account"), ["email-domain", "switch-account"]);
18
+ const emailDomain = options.get("email-domain");
19
+ // The process check (D-05) stops the run only before its first request, so the local setup and the no-token instructions still run.
20
+ const problems = cloudProcessProblems(deps.env);
21
+ const unreachable = problems.length === 0 ? {} : { unreachable: problems.join("; ") };
22
+ return runCloudflareSetup({ ...deps, ...unreachable, projectDir: io.cwd }, { ...(emailDomain === undefined ? {} : { emailDomain }), switchAccount }, io);
23
+ };
24
+ }
25
+ /** Any HTTPS answer means the host is reachable; a request that gets none rejects. */
26
+ export function reachWith(doFetch = fetch, timeoutMs = NETWORK_CHECK_TIMEOUT_MS) {
27
+ return async (url) => {
28
+ await doFetch(url, { method: "HEAD", redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
29
+ };
30
+ }
31
+ /** `cloudflare-setup` bound to the real Cloudflare API and network. */
32
+ export function cloudflareSetupBinding(env = process.env) {
33
+ return cloudflareSetupCommand({ env, apiFor: (token) => createCloudflareApi({ token }), reach: reachWith() });
34
+ }
@@ -26,7 +26,7 @@ export function cloudflareSinkReader(env, fetchImpl) {
26
26
  ]);
27
27
  const missing = missingCredentials(env);
28
28
  if (missing.length > 0)
29
- throw new Error(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment; values are never printed)`);
29
+ throw new Error(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment or in .env.cloudflare; values are never printed)`);
30
30
  const api = createCloudflareApi({ token: env.CLOUDFLARE_API_TOKEN ?? "", ...(fetchImpl === undefined ? {} : { fetch: fetchImpl }) });
31
31
  return readSinkMail(api, env.CLOUDFLARE_ACCOUNT_ID ?? "", address);
32
32
  };
@@ -4,6 +4,7 @@ import { fetchTransfer } from "../../provision/cloudflare/d1/native-copy.js";
4
4
  import { workersPlanReader } from "../../provision/cloudflare/plan.js";
5
5
  import { d1DatabaseOperations } from "../../provision/cloudflare/d1/operations.js";
6
6
  import { missingCredentials } from "../../provision/cloudflare/environment.js";
7
+ import { ACCOUNT_SETUP_VERSION } from "../../provision/cloudflare/permissions.js";
7
8
  import { createCloudflareTarget } from "../../provision/cloudflare/target.js";
8
9
  /** The cloud target's PROV operations from the process environment (Cloudflare: D-03 with D-04's databases and D-02's CORS parts). */
9
10
  export const cloudflareOperations = (options) => ({ appDir, target, code }) => {
@@ -13,7 +14,7 @@ export const cloudflareOperations = (options) => ({ appDir, target, code }) => {
13
14
  if (options.requireCredentials) {
14
15
  const missing = missingCredentials(env);
15
16
  if (missing.length > 0)
16
- throw new Error(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment; values are never printed)`);
17
+ throw new Error(`missing Cloudflare credentials: ${missing.join(", ")} (set them in the environment or in .env.cloudflare; values are never printed)`);
17
18
  }
18
19
  const accountId = env.CLOUDFLARE_ACCOUNT_ID ?? "";
19
20
  const withFetch = options.fetch === undefined ? {} : { fetch: options.fetch };
@@ -35,6 +36,8 @@ export const cloudflareOperations = (options) => ({ appDir, target, code }) => {
35
36
  storagePreflight: ({ accountId: account, bucket, origin }) => checkStorageCors({ accountId: account, bucket, publicOrigin: origin, ...withFetch }),
36
37
  },
37
38
  ...(code === undefined ? {} : { code: code }),
39
+ // setup-account records this release's account setup version (DEC-0577, PAR-332).
40
+ setupVersion: ACCOUNT_SETUP_VERSION,
38
41
  ...withFetch,
39
42
  });
40
43
  };
@@ -0,0 +1,38 @@
1
+ import { type Command } from "../io.js";
2
+ /** The app pins that move with the framework: the versions its own package.json depends on (skill hard rule 5). */
3
+ export declare const COMPANION_PINS: readonly string[];
4
+ /** What `npm view <framework>@<spec>` says about a release. */
5
+ export interface Release {
6
+ readonly version: string;
7
+ readonly dependencies: Readonly<Record<string, string>>;
8
+ }
9
+ /** The versions a release's Cloudflare setup expects (batch 1's `permissions.ts`, exported from `./provision`). */
10
+ export interface SetupVersions {
11
+ readonly permissions?: number;
12
+ readonly accountSetup?: number;
13
+ }
14
+ export interface UpgradeDeps {
15
+ /** The release `spec` names (`latest`, `next` or an exact version). */
16
+ view(spec: string): Promise<Release>;
17
+ /** `npm install` in the app directory. */
18
+ install(appDir: string): Promise<void>;
19
+ /** `npm run verify` in the app directory; true when it passed. */
20
+ verify(appDir: string): Promise<boolean>;
21
+ /** The installed framework's setup versions; undefined when it is not installed or exports neither. */
22
+ setupVersions(appDir: string): Promise<SetupVersions | undefined>;
23
+ }
24
+ interface AppPackage {
25
+ dependencies?: Record<string, string>;
26
+ devDependencies?: Record<string, string>;
27
+ [key: string]: unknown;
28
+ }
29
+ /** The app's package.json with the framework and its companions pinned at `release`; the names changed. */
30
+ export declare function repin(pkg: AppPackage, release: Release): {
31
+ pkg: AppPackage;
32
+ changed: string[];
33
+ };
34
+ /** Step 4's sentence. */
35
+ export declare function cloudflareVerdict(before: SetupVersions | undefined, after: SetupVersions | undefined): string;
36
+ export declare function upgradeCommand(deps: UpgradeDeps): Command;
37
+ export declare function upgradeBinding(): Command;
38
+ export {};
@@ -0,0 +1,170 @@
1
+ /**
2
+ * `upgrade [<version>]` (`npm run upgrade`; plan-setup-wizard §4.8a; DEC-0595), run deliberately by
3
+ * the owner or the agent:
4
+ * 1. pins `@lago-morph/prototype-framework` at the version named (default: npm's `latest`), and
5
+ * the app's companion pins (hono, zod, typescript, vite, vitest) at the versions that release
6
+ * depends on, then runs `npm install`;
7
+ * 2. replaces `.claude/skills/prototype-framework` with the installed framework's `skill/` copy;
8
+ * 3. runs `npm run verify`;
9
+ * 4. says whether Cloudflare setup needs re-running, comparing PERMISSIONS_VERSION and
10
+ * ACCOUNT_SETUP_VERSION of the framework the app had with the new one's (`./provision`
11
+ * exports, read in a child process; absent means unknown);
12
+ * 5. prints the cloud environment's setup script at the new version (pinned; DEC-0593).
13
+ * Exit status 0 when every step passed, 1 otherwise (the upgrade stays applied; the message says
14
+ * how to go back), 2 on a usage mistake.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { cpSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { UsageError } from "../args.js";
20
+ import { EXIT } from "../io.js";
21
+ import { compareVersions, FRAMEWORK_PACKAGE, installedFrameworkDir, isExactVersion, setupScriptLines, SKILL_DIR } from "./versions.js";
22
+ /** The app pins that move with the framework: the versions its own package.json depends on (skill hard rule 5). */
23
+ export const COMPANION_PINS = ["hono", "zod", "typescript", "vite", "vitest"];
24
+ const SPEC = /^(latest|next|\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?)$/;
25
+ function parseArgs(args) {
26
+ if (args.length > 1)
27
+ throw new UsageError("upgrade takes at most one argument: the version (default: latest)");
28
+ const spec = args[0] ?? "latest";
29
+ if (!SPEC.test(spec))
30
+ throw new UsageError("the version must be latest, next or an exact version such as 0.2.0");
31
+ return spec;
32
+ }
33
+ /** The app's package.json with the framework and its companions pinned at `release`; the names changed. */
34
+ export function repin(pkg, release) {
35
+ const next = { ...pkg, dependencies: { ...(pkg.dependencies ?? {}) }, ...(pkg.devDependencies === undefined ? {} : { devDependencies: { ...pkg.devDependencies } }) };
36
+ const changed = [];
37
+ const set = (name, version) => {
38
+ for (const group of [next.dependencies, next.devDependencies]) {
39
+ if (group?.[name] !== undefined && group[name] !== version) {
40
+ group[name] = version;
41
+ changed.push(`${name} ${version}`);
42
+ }
43
+ }
44
+ };
45
+ set(FRAMEWORK_PACKAGE, release.version);
46
+ for (const name of COMPANION_PINS) {
47
+ const version = release.dependencies[name];
48
+ if (version !== undefined && isExactVersion(version))
49
+ set(name, version);
50
+ }
51
+ return { pkg: next, changed };
52
+ }
53
+ /** Step 4's sentence. */
54
+ export function cloudflareVerdict(before, after) {
55
+ const unknown = "Cloudflare setup: unknown whether this release needs more; run `npm run cloudflare-setup` to check (it does only what is missing).";
56
+ if (after?.permissions === undefined || after.accountSetup === undefined || before?.permissions === undefined || before.accountSetup === undefined)
57
+ return unknown;
58
+ const raised = [];
59
+ if (after.permissions > before.permissions)
60
+ raised.push(`token permissions ${before.permissions} → ${after.permissions}`);
61
+ if (after.accountSetup > before.accountSetup)
62
+ raised.push(`account setup ${before.accountSetup} → ${after.accountSetup}`);
63
+ if (raised.length === 0)
64
+ return "Cloudflare setup: nothing new is needed; no need to re-run it.";
65
+ return `Cloudflare setup needs re-running (${raised.join(", ")}): run \`npm run cloudflare-setup\`. It needs the bootstrap token once.`;
66
+ }
67
+ export function upgradeCommand(deps) {
68
+ return async (args, io) => {
69
+ const spec = parseArgs(args);
70
+ const pkgFile = join(io.cwd, "package.json");
71
+ const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
72
+ if (pkg.dependencies?.[FRAMEWORK_PACKAGE] === undefined) {
73
+ io.stderr(`upgrade: this app's package.json does not depend on ${FRAMEWORK_PACKAGE}\n`);
74
+ return EXIT.failed;
75
+ }
76
+ const goBack = "To go back: `git checkout -- package.json package-lock.json .claude/skills/prototype-framework`, then `npm install`.";
77
+ const before = await deps.setupVersions(io.cwd).catch(() => undefined);
78
+ const release = await deps.view(spec);
79
+ if (!isExactVersion(release.version))
80
+ throw new Error(`npm named an unexpected version for ${FRAMEWORK_PACKAGE}@${spec}`);
81
+ const from = pkg.dependencies[FRAMEWORK_PACKAGE];
82
+ if (isExactVersion(from) && compareVersions(release.version, from) < 0) {
83
+ io.stdout(`note: ${release.version} is older than the app's ${from}; moving to it as asked.\n`);
84
+ }
85
+ // 1. Pins and install.
86
+ const { pkg: next, changed } = repin(pkg, release);
87
+ if (changed.length > 0)
88
+ writeFileSync(pkgFile, `${JSON.stringify(next, null, 2)}\n`);
89
+ io.stdout(changed.length === 0 ? `1. ${FRAMEWORK_PACKAGE} is already pinned at ${release.version}; running npm install\n` : `1. pinned ${changed.join(", ")}; running npm install\n`);
90
+ try {
91
+ await deps.install(io.cwd);
92
+ }
93
+ catch (error) {
94
+ io.stderr(`upgrade: npm install failed: ${error instanceof Error ? error.message : String(error)}\n${goBack}\n`);
95
+ return EXIT.failed;
96
+ }
97
+ // 2. The committed skill copy.
98
+ let ok = true;
99
+ const installed = installedFrameworkDir(io.cwd);
100
+ const source = installed === undefined ? undefined : join(installed, "skill");
101
+ const target = join(io.cwd, SKILL_DIR);
102
+ if (source === undefined || !existsSync(join(source, "SKILL.md"))) {
103
+ io.stdout(`2. WARNING: the installed framework has no skill/ copy, so ${SKILL_DIR} was left as it was\n`);
104
+ ok = false;
105
+ }
106
+ else {
107
+ rmSync(target, { recursive: true, force: true });
108
+ cpSync(source, target, { recursive: true });
109
+ io.stdout(`2. refreshed ${SKILL_DIR} from the installed framework\n`);
110
+ }
111
+ // 3. verify.
112
+ io.stdout("3. running npm run verify\n");
113
+ const verified = await deps.verify(io.cwd).catch(() => false);
114
+ if (!verified) {
115
+ io.stdout(` verify failed: the upgrade is applied; fix what verify reports, or go back. ${goBack}\n`);
116
+ ok = false;
117
+ }
118
+ else
119
+ io.stdout(" verify passed\n");
120
+ // 4. Cloudflare.
121
+ const after = await deps.setupVersions(io.cwd).catch(() => undefined);
122
+ io.stdout(`4. ${cloudflareVerdict(before, after)}\n`);
123
+ // 5. The setup script.
124
+ io.stdout(`5. ${setupScriptLines(release.version)}`);
125
+ io.stdout(ok ? `upgraded to ${release.version}\n` : `upgrade to ${release.version} finished with problems (above)\n`);
126
+ return ok ? EXIT.ok : EXIT.failed;
127
+ };
128
+ }
129
+ /** Runs `command args` in `cwd`, output shown; resolves to its exit status. */
130
+ function run(command, args, cwd, capture = false) {
131
+ return new Promise((done, fail) => {
132
+ const child = spawn(command, args, { cwd, stdio: capture ? ["ignore", "pipe", "inherit"] : "inherit", shell: process.platform === "win32" });
133
+ let out = "";
134
+ child.stdout?.on("data", (chunk) => (out += chunk.toString("utf8")));
135
+ child.on("error", fail);
136
+ child.on("exit", (code) => done({ status: code ?? 1, out }));
137
+ });
138
+ }
139
+ /** Reads the setup versions in a fresh Node process, so the newly installed files are the ones read. */
140
+ const READ_SETUP_VERSIONS = `import(${JSON.stringify(`${FRAMEWORK_PACKAGE}/provision`)}).then((m) => process.stdout.write(JSON.stringify({ permissions: m.PERMISSIONS_VERSION, accountSetup: m.ACCOUNT_SETUP_VERSION })), () => process.stdout.write("{}"));`;
141
+ export function upgradeBinding() {
142
+ return upgradeCommand({
143
+ view: async (spec) => {
144
+ const r = await run("npm", ["view", `${FRAMEWORK_PACKAGE}@${spec}`, "version", "dependencies", "--json"], process.cwd(), true);
145
+ if (r.status !== 0)
146
+ throw new Error(`npm view ${FRAMEWORK_PACKAGE}@${spec} failed (status ${r.status}); check the version and the network`);
147
+ const parsed = JSON.parse(r.out);
148
+ const one = (Array.isArray(parsed) ? parsed.at(-1) : parsed);
149
+ if (typeof one?.version !== "string")
150
+ throw new Error(`npm view ${FRAMEWORK_PACKAGE}@${spec} named no version`);
151
+ return { version: one.version, dependencies: (one.dependencies ?? {}) };
152
+ },
153
+ install: async (appDir) => {
154
+ const r = await run("npm", ["install", "--no-audit", "--no-fund"], appDir);
155
+ if (r.status !== 0)
156
+ throw new Error(`exit status ${r.status}`);
157
+ },
158
+ verify: async (appDir) => (await run("npm", ["run", "verify"], appDir)).status === 0,
159
+ setupVersions: async (appDir) => {
160
+ if (installedFrameworkDir(appDir) === undefined)
161
+ return undefined;
162
+ const r = await run(process.execPath, ["--input-type=module", "-e", READ_SETUP_VERSIONS], appDir, true);
163
+ const v = JSON.parse(r.out === "" ? "{}" : r.out);
164
+ const n = (x) => (typeof x === "number" ? x : undefined);
165
+ const permissions = n(v.permissions);
166
+ const accountSetup = n(v.accountSetup);
167
+ return permissions === undefined && accountSetup === undefined ? undefined : { ...(permissions === undefined ? {} : { permissions }), ...(accountSetup === undefined ? {} : { accountSetup }) };
168
+ },
169
+ });
170
+ }
@@ -6,6 +6,10 @@
6
6
  * test-runner process. Every step runs and reports, so one run shows every problem
7
7
  * (DEC-0238); `verify` fails if any step fails or no test ran. Output holds no clock
8
8
  * times or durations, so two runs on the same app print the same text.
9
+ *
10
+ * Before the first step and again before the verdict, `verify` prints the git warnings for the
11
+ * app's `.env.cloudflare` (not ignored, tracked; plan-setup-wizard §4.5, DEC-0572), on every run.
12
+ * They never fail `verify` and never change its exit status.
9
13
  */
10
14
  import type { Dialect } from "../../sql/dialect.js";
11
15
  import { type Command } from "../io.js";
@@ -48,6 +52,8 @@ export interface VerifyDeps {
48
52
  readonly installed: string | undefined;
49
53
  }>;
50
54
  runTests(appDir: string, dialect: Dialect): Promise<TestRun>;
55
+ /** The git warnings for the app's `.env.cloudflare` (DEC-0572); printed, never a failure. */
56
+ gitSafetyWarnings?(appDir: string): readonly string[];
51
57
  }
52
58
  export declare const VERIFY_DIALECTS: readonly Dialect[];
53
59
  /** One line per diagnostic, the layout of CHECK's `formatDiagnostic` (CHECK-REQ-003). */
@@ -1,4 +1,5 @@
1
1
  import { parseOptions } from "../args.js";
2
+ import { formatGitWarning } from "../cloudflare-settings.js";
2
3
  import { EXIT } from "../io.js";
3
4
  export const VERIFY_DIALECTS = ["sqlite", "postgres"];
4
5
  /** One line per diagnostic, the layout of CHECK's `formatDiagnostic` (CHECK-REQ-003). */
@@ -54,6 +55,18 @@ export function verifyCommand(deps) {
54
55
  parseOptions(args, []);
55
56
  const dir = io.cwd;
56
57
  const failed = [];
58
+ let gitWarnings = [];
59
+ try {
60
+ gitWarnings = deps.gitSafetyWarnings?.(dir) ?? [];
61
+ }
62
+ catch {
63
+ // The git check never fails verify (DEC-0572).
64
+ }
65
+ const printGitWarnings = () => {
66
+ for (const w of gitWarnings)
67
+ io.stdout(formatGitWarning("verify", w));
68
+ };
69
+ printGitWarnings();
57
70
  const staticStep = async (label, run) => {
58
71
  io.stdout(`verify: ${label}\n`);
59
72
  const diagnostics = sorted(await run());
@@ -88,6 +101,7 @@ export function verifyCommand(deps) {
88
101
  failed.push(label);
89
102
  io.stdout(`verify: ${label}: ${problem ?? "passed"} (${testCounts(run)})\n`);
90
103
  }
104
+ printGitWarnings();
91
105
  if (failed.length > 0) {
92
106
  io.stdout(`verify failed: ${failed.join(", ")}\n`);
93
107
  return EXIT.failed;
@@ -0,0 +1,31 @@
1
+ import { type Command } from "../io.js";
2
+ import { type SkillCopy } from "./versions.js";
3
+ /** PAR-371: time limit of each network lookup (the npm registry, the CHANGELOG). */
4
+ export declare const LOOKUP_TIMEOUT_MS = 5000;
5
+ export interface VersionCheckDeps {
6
+ /** The home directory, whose `.claude/skills/prototype-framework` is the setup script's copy. */
7
+ home(): string;
8
+ /** The framework's latest version on npm; undefined (or a rejection) when it cannot be read. */
9
+ latestRelease(): Promise<string | undefined>;
10
+ /** The headline of `version`'s CHANGELOG section; undefined when it cannot be read. */
11
+ headline(version: string): Promise<string | undefined>;
12
+ }
13
+ export interface VersionFindings {
14
+ readonly app?: string;
15
+ /** The app's dependency spec, when the framework is not installed. */
16
+ readonly pinned?: string;
17
+ readonly committed: SkillCopy;
18
+ readonly setupScript: SkillCopy;
19
+ }
20
+ /** The app's framework and skill versions, read from files only. */
21
+ export declare function readFindings(appDir: string, home: string): VersionFindings;
22
+ /** The suggestions for `findings` and npm's latest release (undefined: skipped). */
23
+ export declare function suggestions(findings: VersionFindings, latest: string | undefined, deps: Pick<VersionCheckDeps, "headline">): Promise<string[]>;
24
+ export declare function versionCheckCommand(deps: VersionCheckDeps): Command;
25
+ /** The first line of `version`'s section in a Keep-a-Changelog text, cut to 200 characters. */
26
+ export declare function changelogHeadline(changelog: string, version: string): string | undefined;
27
+ /**
28
+ * The real lookups: the npm registry and the release tag's CHANGELOG, through the environment's
29
+ * proxy (`fetchImpl` replaces the network in tests). Nothing is written.
30
+ */
31
+ export declare function versionCheckBinding(env?: Readonly<Record<string, string | undefined>>, fetchImpl?: typeof fetch): Promise<Command>;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * `version-check` (plan-setup-wizard §4.8a; DEC-0594): the skill's first step. It never changes
3
+ * anything in the app or the environment; it only prints suggestions, one per finding:
4
+ *
5
+ * | Finding | Suggestion |
6
+ * | the skill is newer than the app's installed framework | `npm run upgrade` |
7
+ * | the app's framework is newer than the setup-script skill (`~/.claude/skills/prototype-framework`) | use the app's committed copy this session; the setup script at the new version |
8
+ * | npm has a newer release than both | printed with its CHANGELOG headline |
9
+ *
10
+ * Stateless: it reads files and makes two network reads, and writes nothing anywhere (no mark
11
+ * file), so the npm row is printed on every run while it holds; the skill mentions it once per
12
+ * session. A failed npm lookup (no network, a blocked host, PAR-371's time limit) skips the last
13
+ * row quietly. Exit status 0 whatever it finds; 2 on a usage mistake.
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { parseOptions } from "../args.js";
19
+ import { EXIT } from "../io.js";
20
+ import { compareVersions, FRAMEWORK_PACKAGE, installedFrameworkVersion, isExactVersion, readSkillCopy, setupScriptLines, SKILL_DIR } from "./versions.js";
21
+ /** PAR-371: time limit of each network lookup (the npm registry, the CHANGELOG). */
22
+ export const LOOKUP_TIMEOUT_MS = 5_000;
23
+ const label = (copy) => (copy.present ? (copy.version ?? "a version without a marker (older)") : "none");
24
+ /** The app's framework and skill versions, read from files only. */
25
+ export function readFindings(appDir, home) {
26
+ const app = installedFrameworkVersion(appDir);
27
+ let pinned;
28
+ if (app === undefined) {
29
+ try {
30
+ const pkg = JSON.parse(readFileSync(join(appDir, "package.json"), "utf8"));
31
+ pinned = pkg.dependencies?.[FRAMEWORK_PACKAGE];
32
+ }
33
+ catch {
34
+ pinned = undefined;
35
+ }
36
+ }
37
+ return {
38
+ ...(app === undefined ? {} : { app }),
39
+ ...(pinned === undefined ? {} : { pinned }),
40
+ committed: readSkillCopy(join(appDir, SKILL_DIR)),
41
+ setupScript: readSkillCopy(join(home, SKILL_DIR)),
42
+ };
43
+ }
44
+ /** The suggestions for `findings` and npm's latest release (undefined: skipped). */
45
+ export async function suggestions(findings, latest, deps) {
46
+ const out = [];
47
+ const app = findings.app ?? (findings.pinned !== undefined && isExactVersion(findings.pinned) ? findings.pinned : undefined);
48
+ if (findings.app === undefined)
49
+ out.push("The framework is not installed in this app: run `npm install` first.");
50
+ const skills = [
51
+ ["The committed skill (.claude/skills/prototype-framework)", findings.committed],
52
+ ["The setup-script skill (~/.claude/skills/prototype-framework)", findings.setupScript],
53
+ ];
54
+ if (app !== undefined) {
55
+ for (const [where, copy] of skills) {
56
+ if (copy.present && copy.version !== undefined && compareVersions(copy.version, app) > 0) {
57
+ out.push(`${where} is ${copy.version}, newer than this app's framework ${app}: run \`npm run upgrade\` to move the app to it.`);
58
+ }
59
+ }
60
+ const script = findings.setupScript;
61
+ if (script.present && (script.version === undefined || compareVersions(app, script.version) > 0)) {
62
+ out.push(`This app's framework ${app} is newer than the setup-script skill (${label(script)}): use the app's committed copy (.claude/skills/prototype-framework) for this session. ` +
63
+ `To update the setup-script skill, paste this into the cloud environment's settings:\n${setupScriptLines(app)}`);
64
+ }
65
+ }
66
+ if (latest !== undefined && isExactVersion(latest)) {
67
+ const known = [app, ...skills.map(([, c]) => (c.present ? c.version : undefined))].filter((v) => v !== undefined);
68
+ const newer = known.length > 0 && known.every((v) => compareVersions(latest, v) > 0);
69
+ if (newer) {
70
+ const headline = await deps.headline(latest).catch(() => undefined);
71
+ out.push(`A newer release, ${latest}, is on npm${headline === undefined ? "" : `: ${headline.replace(/\.$/, "")}`}. To move this app to it: \`npm run upgrade\`.`);
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+ export function versionCheckCommand(deps) {
77
+ return async (args, io) => {
78
+ parseOptions(args, []);
79
+ const findings = readFindings(io.cwd, deps.home());
80
+ const latest = await deps.latestRelease().catch(() => undefined);
81
+ const found = await suggestions(findings, latest, deps);
82
+ io.stdout(`version-check: framework ${findings.app ?? "not installed"}; committed skill ${label(findings.committed)}; setup-script skill ${label(findings.setupScript)}\n`);
83
+ io.stdout(found.length === 0 ? "Nothing to do: the versions agree.\n" : found.map((s) => `- ${s}${s.endsWith("\n") ? "" : "\n"}`).join(""));
84
+ return EXIT.ok;
85
+ };
86
+ }
87
+ /** The first line of `version`'s section in a Keep-a-Changelog text, cut to 200 characters. */
88
+ export function changelogHeadline(changelog, version) {
89
+ const lines = changelog.split(/\r?\n/);
90
+ const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
91
+ if (start < 0)
92
+ return undefined;
93
+ for (const l of lines.slice(start + 1)) {
94
+ if (l.startsWith("## "))
95
+ return undefined;
96
+ const t = l.trim();
97
+ if (t === "" || t.startsWith("#"))
98
+ continue;
99
+ return t.length > 200 ? `${t.slice(0, 199)}…` : t;
100
+ }
101
+ return undefined;
102
+ }
103
+ /**
104
+ * The real lookups: the npm registry and the release tag's CHANGELOG, through the environment's
105
+ * proxy (`fetchImpl` replaces the network in tests). Nothing is written.
106
+ */
107
+ export async function versionCheckBinding(env = process.env, fetchImpl) {
108
+ const { fetchOver, oneConnectionDispatcher } = await import("../one-connection.js");
109
+ const get = fetchImpl ?? fetchOver(oneConnectionDispatcher(env));
110
+ const text = async (url) => {
111
+ const r = await get(url, { signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS) });
112
+ return r.ok ? await r.text() : undefined;
113
+ };
114
+ const registry = (env.npm_config_registry ?? "https://registry.npmjs.org/").replace(/\/?$/, "/");
115
+ return versionCheckCommand({
116
+ home: homedir,
117
+ latestRelease: async () => {
118
+ const body = await text(`${registry}${FRAMEWORK_PACKAGE.replace("/", "%2F")}/latest`);
119
+ const version = body === undefined ? undefined : JSON.parse(body).version;
120
+ return typeof version === "string" ? version : undefined;
121
+ },
122
+ headline: async (version) => {
123
+ const body = await text(`https://raw.githubusercontent.com/lago-morph/cloud-app/v${version}/CHANGELOG.md`);
124
+ return body === undefined ? undefined : changelogHeadline(body, version);
125
+ },
126
+ });
127
+ }