@gadicc/loom 1.33.1 → 1.35.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/README.md +108 -41
- package/esm/src/apiKeys/authorize.d.ts.map +1 -1
- package/esm/src/apiKeys/authorize.js +71 -0
- package/esm/src/apiKeys/betterAuth.d.ts +123 -0
- package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
- package/esm/src/apiKeys/betterAuth.js +164 -0
- package/esm/src/apiKeys/credentials.d.ts +37 -2
- package/esm/src/apiKeys/credentials.d.ts.map +1 -1
- package/esm/src/apiKeys/credentials.js +69 -8
- package/esm/src/apiKeys/lifecycle.d.ts +41 -0
- package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
- package/esm/src/apiKeys/lifecycle.js +6 -0
- package/esm/src/apiKeys/limits.d.ts +132 -0
- package/esm/src/apiKeys/limits.d.ts.map +1 -0
- package/esm/src/apiKeys/limits.js +246 -0
- package/esm/src/apiKeys/mod.d.ts +4 -0
- package/esm/src/apiKeys/mod.d.ts.map +1 -1
- package/esm/src/apiKeys/mod.js +4 -0
- package/esm/src/apiKeys/permissions.d.ts +56 -0
- package/esm/src/apiKeys/permissions.d.ts.map +1 -0
- package/esm/src/apiKeys/permissions.js +128 -0
- package/esm/src/apiKeys/policy.d.ts +3 -1
- package/esm/src/apiKeys/policy.d.ts.map +1 -1
- package/esm/src/apiKeys/policy.js +3 -1
- package/esm/src/apiKeys/types.d.ts +68 -1
- package/esm/src/apiKeys/types.d.ts.map +1 -1
- package/esm/src/cli/localDb.d.ts +28 -0
- package/esm/src/cli/localDb.d.ts.map +1 -0
- package/esm/src/cli/localDb.js +366 -0
- package/esm/src/cli/localDevLock.d.ts +97 -0
- package/esm/src/cli/localDevLock.d.ts.map +1 -0
- package/esm/src/cli/localDevLock.js +312 -0
- package/esm/src/cli/localDevPackage.d.ts +172 -0
- package/esm/src/cli/localDevPackage.d.ts.map +1 -0
- package/esm/src/cli/localDevPackage.js +617 -0
- package/esm/src/cli/migrationEnv.d.ts +19 -0
- package/esm/src/cli/migrationEnv.d.ts.map +1 -1
- package/esm/src/cli/migrationEnv.js +44 -1
- package/esm/src/cli/mod.d.ts +69 -4
- package/esm/src/cli/mod.d.ts.map +1 -1
- package/esm/src/cli/mod.js +2822 -419
- package/esm/src/cli/projectTooling.d.ts +19 -1
- package/esm/src/cli/projectTooling.d.ts.map +1 -1
- package/esm/src/cli/projectTooling.js +142 -12
- package/esm/src/mui/apiKeys.d.ts +123 -17
- package/esm/src/mui/apiKeys.d.ts.map +1 -1
- package/esm/src/mui/apiKeys.js +219 -78
- package/esm/src/mui/apiKeysView.d.ts +145 -0
- package/esm/src/mui/apiKeysView.d.ts.map +1 -1
- package/esm/src/mui/apiKeysView.js +278 -0
- package/esm/src/next/apiKeys/mod.d.ts +8 -1
- package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
- package/esm/src/next/apiKeys/mod.js +5 -2
- package/package.json +2 -6
- package/script/src/apiKeys/authorize.d.ts.map +1 -1
- package/script/src/apiKeys/authorize.js +71 -0
- package/script/src/apiKeys/betterAuth.d.ts +123 -0
- package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
- package/script/src/apiKeys/betterAuth.js +169 -0
- package/script/src/apiKeys/credentials.d.ts +37 -2
- package/script/src/apiKeys/credentials.d.ts.map +1 -1
- package/script/src/apiKeys/credentials.js +71 -8
- package/script/src/apiKeys/lifecycle.d.ts +41 -0
- package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
- package/script/src/apiKeys/lifecycle.js +7 -0
- package/script/src/apiKeys/limits.d.ts +132 -0
- package/script/src/apiKeys/limits.d.ts.map +1 -0
- package/script/src/apiKeys/limits.js +254 -0
- package/script/src/apiKeys/mod.d.ts +4 -0
- package/script/src/apiKeys/mod.d.ts.map +1 -1
- package/script/src/apiKeys/mod.js +4 -0
- package/script/src/apiKeys/permissions.d.ts +56 -0
- package/script/src/apiKeys/permissions.d.ts.map +1 -0
- package/script/src/apiKeys/permissions.js +136 -0
- package/script/src/apiKeys/policy.d.ts +3 -1
- package/script/src/apiKeys/policy.d.ts.map +1 -1
- package/script/src/apiKeys/policy.js +3 -1
- package/script/src/apiKeys/types.d.ts +68 -1
- package/script/src/apiKeys/types.d.ts.map +1 -1
- package/script/src/cli/localDb.d.ts +28 -0
- package/script/src/cli/localDb.d.ts.map +1 -0
- package/script/src/cli/localDb.js +370 -0
- package/script/src/cli/localDevLock.d.ts +97 -0
- package/script/src/cli/localDevLock.d.ts.map +1 -0
- package/script/src/cli/localDevLock.js +320 -0
- package/script/src/cli/localDevPackage.d.ts +172 -0
- package/script/src/cli/localDevPackage.d.ts.map +1 -0
- package/script/src/cli/localDevPackage.js +635 -0
- package/script/src/cli/migrationEnv.d.ts +19 -0
- package/script/src/cli/migrationEnv.d.ts.map +1 -1
- package/script/src/cli/migrationEnv.js +48 -1
- package/script/src/cli/mod.d.ts +69 -4
- package/script/src/cli/mod.d.ts.map +1 -1
- package/script/src/cli/mod.js +2823 -419
- package/script/src/cli/projectTooling.d.ts +19 -1
- package/script/src/cli/projectTooling.d.ts.map +1 -1
- package/script/src/cli/projectTooling.js +176 -12
- package/script/src/mui/apiKeys.d.ts +123 -17
- package/script/src/mui/apiKeys.d.ts.map +1 -1
- package/script/src/mui/apiKeys.js +220 -77
- package/script/src/mui/apiKeysView.d.ts +145 -0
- package/script/src/mui/apiKeysView.d.ts.map +1 -1
- package/script/src/mui/apiKeysView.js +291 -0
- package/script/src/next/apiKeys/mod.d.ts +8 -1
- package/script/src/next/apiKeys/mod.d.ts.map +1 -1
- package/script/src/next/apiKeys/mod.js +5 -2
- package/skills/loom/SKILL.md +116 -18
- package/skills/loom-api-keys/SKILL.md +101 -7
- package/skills/loom-auth/SKILL.md +9 -0
- package/skills/loom-db/SKILL.md +33 -1
package/esm/src/cli/mod.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { constants as fsConstants } from "node:fs";
|
|
4
|
-
import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
|
|
4
|
+
import { access, chmod, lstat, mkdir, mkdtemp, readdir, readFile, readlink, realpath, rm, stat, symlink, unlink, writeFile, } from "node:fs/promises";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
7
7
|
import process from "node:process";
|
|
@@ -12,12 +12,16 @@ import { filesR2PolicyIssues, parseWranglerR2Cors, r2CorsMatchesPolicy, } from "
|
|
|
12
12
|
import { resolveProductionBranch, } from "./releaseConfig.js";
|
|
13
13
|
import { configureGithubVercelReleaseCredential, } from "./releaseCredentials.js";
|
|
14
14
|
import { runGithubReleaseTrustCommand } from "./releaseTrustCommand.js";
|
|
15
|
+
import { checkLocalDatabase, setupLocalDatabase } from "./localDb.js";
|
|
16
|
+
import { BETTER_AUTH_API_KEY_HTTP_PATHS } from "../apiKeys/betterAuth.js";
|
|
15
17
|
import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
|
|
16
18
|
import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
|
|
17
19
|
import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
|
|
18
20
|
import { prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
|
|
19
21
|
import { parseVercelReleaseTimeout, prepareVercelProjectRelease, promoteVercelProjectRelease, } from "./vercelProjectRelease.js";
|
|
20
|
-
import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, mutateDenoLinks, mutateProjectDependencies, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
|
|
22
|
+
import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
|
|
23
|
+
import { withLocalDevLock, } from "./localDevLock.js";
|
|
24
|
+
import { computeLoomSourceFingerprint, computePackageContentDigest, computePackageTreeSignature, findNewPeerVariantDuplicates, findPackageTreeDifference, formatLoomBuildStamp, getLockfileOverride, getLockfileRootImporterDependency, hasLoomBuildProvenance, LOOM_BUILD_STAMP_FILE, LOOM_PACKAGE_RELEVANT_PATHS, readLoomBuildStamp, } from "./localDevPackage.js";
|
|
21
25
|
export const DEFAULT_LOOM_RANGE = "^1.0.0";
|
|
22
26
|
export const LOOM_DEPENDENCY = "@gadicc/loom";
|
|
23
27
|
export const LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
|
|
@@ -29,24 +33,21 @@ export const LOOM_MANAGED_DEV_OVERRIDE_START = "# loom-managed:dev:start";
|
|
|
29
33
|
export const LOOM_MANAGED_DEV_OVERRIDE_END = "# loom-managed:dev:end";
|
|
30
34
|
export const LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = ".loom/dev-state.json";
|
|
31
35
|
export const LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE = ".loom/dev-state.json";
|
|
36
|
+
/** Exclusive lock held while a local-dev sync checks, rebuilds, or installs. */
|
|
37
|
+
export const LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH = ".loom/dev-sync.lock";
|
|
38
|
+
/** Ignores the sync lock and the short-lived lock that guards breaking it. */
|
|
39
|
+
export const LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE = ".loom/dev-sync.lock*";
|
|
40
|
+
/** Set for commands a sync runs, so nested Loom commands skip the sync. */
|
|
41
|
+
const LOOM_DEV_SYNC_ACTIVE_ENV = "LOOM_DEV_SYNC_ACTIVE";
|
|
32
42
|
const DEFAULT_JOBS_MAX_DURATION_SECONDS = 1800;
|
|
33
43
|
const LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER = "// loom-managed:jobs-static-route";
|
|
34
44
|
/** @deprecated Public npm installs no longer require project registry config. */
|
|
35
45
|
export const LOOM_NPMRC_LINES = [];
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"bin",
|
|
42
|
-
"deno.json",
|
|
43
|
-
"deno.lock",
|
|
44
|
-
"mod.ts",
|
|
45
|
-
"runtime",
|
|
46
|
-
"scripts/build_npm.ts",
|
|
47
|
-
"skills",
|
|
48
|
-
"src",
|
|
49
|
-
];
|
|
46
|
+
/**
|
|
47
|
+
* Exit status for a command that refreshed the linked local Loom package and
|
|
48
|
+
* stopped before running stale in-process Loom code (EX_TEMPFAIL: retry).
|
|
49
|
+
*/
|
|
50
|
+
export const LOOM_LOCAL_DEV_RERUN_EXIT_CODE = 75;
|
|
50
51
|
const PRODUCTION_GITHUB_ENVIRONMENT = "production";
|
|
51
52
|
const REQUIRED_GITHUB_VERCEL_SECRET_NAMES = ["VERCEL_TOKEN"];
|
|
52
53
|
const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
|
|
@@ -318,14 +319,17 @@ async function writeTextIfChanged(path, text) {
|
|
|
318
319
|
}
|
|
319
320
|
export async function defaultCommandRunner(command, args, options) {
|
|
320
321
|
return await new Promise((resolvePromise) => {
|
|
321
|
-
const inherit = options.stdio === "inherit"
|
|
322
|
+
const inherit = options.stdio === "inherit" ||
|
|
323
|
+
options.stdio === "inherit-stderr";
|
|
322
324
|
const pipeInput = !inherit && options.input !== undefined;
|
|
323
325
|
const child = spawn(command, args, {
|
|
324
326
|
cwd: options.cwd,
|
|
325
327
|
env: options.env,
|
|
326
|
-
stdio: inherit
|
|
327
|
-
? "inherit"
|
|
328
|
-
:
|
|
328
|
+
stdio: options.stdio === "inherit-stderr"
|
|
329
|
+
? ["inherit", 2, 2]
|
|
330
|
+
: inherit
|
|
331
|
+
? "inherit"
|
|
332
|
+
: [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
|
|
329
333
|
});
|
|
330
334
|
const stdoutChunks = [];
|
|
331
335
|
const stderrChunks = [];
|
|
@@ -611,6 +615,215 @@ function getPublishedLoomDependencySpec(packageJson) {
|
|
|
611
615
|
}
|
|
612
616
|
return dependency;
|
|
613
617
|
}
|
|
618
|
+
function parseCatalogReference(spec) {
|
|
619
|
+
const match = spec?.match(/^catalog:(.*)$/);
|
|
620
|
+
return match ? match[1].trim() || "default" : null;
|
|
621
|
+
}
|
|
622
|
+
function parseYamlKeyLine(body) {
|
|
623
|
+
const match = body.match(/^(?:'([^']*)'|"([^"]*)"|([^\s#'"][^:]*?))\s*:(?:\s+(.*))?$/);
|
|
624
|
+
return match
|
|
625
|
+
? { key: match[1] ?? match[2] ?? match[3], rest: match[4] ?? "" }
|
|
626
|
+
: null;
|
|
627
|
+
}
|
|
628
|
+
function isYamlBlockHeader(rest) {
|
|
629
|
+
return rest.trim() === "" || rest.trim().startsWith("#");
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Returns the line indexes of the direct entries of the block map at `path`
|
|
633
|
+
* (for example `["catalogs", "loom"]`), or null when it is missing.
|
|
634
|
+
*/
|
|
635
|
+
function findYamlBlockMapEntries(lines, path) {
|
|
636
|
+
let start = -1;
|
|
637
|
+
let end = lines.length;
|
|
638
|
+
for (const key of path) {
|
|
639
|
+
let childIndent = null;
|
|
640
|
+
let found = -1;
|
|
641
|
+
for (let index = start + 1; index < end; index += 1) {
|
|
642
|
+
const line = lines[index];
|
|
643
|
+
const trimmed = line.trim();
|
|
644
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
645
|
+
continue;
|
|
646
|
+
const indent = line.length - line.trimStart().length;
|
|
647
|
+
childIndent ??= indent;
|
|
648
|
+
if (indent !== childIndent)
|
|
649
|
+
continue;
|
|
650
|
+
const entry = parseYamlKeyLine(trimmed);
|
|
651
|
+
if (entry?.key === key && isYamlBlockHeader(entry.rest)) {
|
|
652
|
+
found = index;
|
|
653
|
+
break;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
if (found === -1)
|
|
657
|
+
return null;
|
|
658
|
+
const headerIndent = lines[found].length - lines[found].trimStart().length;
|
|
659
|
+
start = found;
|
|
660
|
+
end = lines.length;
|
|
661
|
+
for (let index = found + 1; index < lines.length; index += 1) {
|
|
662
|
+
const line = lines[index];
|
|
663
|
+
const trimmed = line.trim();
|
|
664
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
665
|
+
continue;
|
|
666
|
+
if (line.length - line.trimStart().length <= headerIndent) {
|
|
667
|
+
end = index;
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
const entries = [];
|
|
673
|
+
let childIndent = null;
|
|
674
|
+
for (let index = start + 1; index < end; index += 1) {
|
|
675
|
+
const line = lines[index];
|
|
676
|
+
const trimmed = line.trim();
|
|
677
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
678
|
+
continue;
|
|
679
|
+
const indent = line.length - line.trimStart().length;
|
|
680
|
+
childIndent ??= indent;
|
|
681
|
+
if (indent === childIndent)
|
|
682
|
+
entries.push(index);
|
|
683
|
+
}
|
|
684
|
+
return entries;
|
|
685
|
+
}
|
|
686
|
+
function splitYamlScalarComment(rest) {
|
|
687
|
+
const trimmed = rest.trim();
|
|
688
|
+
const quoted = trimmed.match(/^(['"])(.*?)\1(\s+#.*)?$/);
|
|
689
|
+
if (quoted) {
|
|
690
|
+
return { comment: quoted[3] ?? "", quote: quoted[1], value: quoted[2] };
|
|
691
|
+
}
|
|
692
|
+
const plain = trimmed.match(/^(.*?)(\s+#.*)?$/);
|
|
693
|
+
return { comment: plain[2] ?? "", quote: "", value: plain[1] };
|
|
694
|
+
}
|
|
695
|
+
function catalogPaths(catalog) {
|
|
696
|
+
// The default catalog may live under `catalog:` or `catalogs.default:`.
|
|
697
|
+
return catalog === "default"
|
|
698
|
+
? [["catalog"], ["catalogs", "default"]]
|
|
699
|
+
: [["catalogs", catalog]];
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Finds the line of the map at `path` when it is written as a flow map
|
|
703
|
+
* (`catalog: { ... }`), with its content when it fits on that line, or
|
|
704
|
+
* `unsupported` for flow maps Loom cannot read (multi-line or nested).
|
|
705
|
+
*/
|
|
706
|
+
function findYamlFlowMapLine(lines, path) {
|
|
707
|
+
for (let depth = 0; depth < path.length; depth += 1) {
|
|
708
|
+
const parentEntries = findYamlBlockMapEntries(lines, path.slice(0, depth));
|
|
709
|
+
for (const line of parentEntries ?? []) {
|
|
710
|
+
const entry = parseYamlKeyLine(lines[line].trim());
|
|
711
|
+
if (entry?.key !== path[depth] || !entry.rest.trim().startsWith("{")) {
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
if (depth < path.length - 1)
|
|
715
|
+
return { line, unsupported: true };
|
|
716
|
+
const flow = entry.rest.trim().match(/^\{(.*)\}\s*(?:#.*)?$/);
|
|
717
|
+
return flow
|
|
718
|
+
? { content: flow[1], line, unsupported: false }
|
|
719
|
+
: { line, unsupported: true };
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return null;
|
|
723
|
+
}
|
|
724
|
+
function parseYamlFlowEntries(content) {
|
|
725
|
+
return content.split(",").flatMap((part) => {
|
|
726
|
+
const match = part.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:\s]+))\s*:\s*(.*?)\s*$/);
|
|
727
|
+
return match
|
|
728
|
+
? [{
|
|
729
|
+
key: match[1] ?? match[2] ?? match[3],
|
|
730
|
+
value: splitYamlScalarComment(match[4]).value,
|
|
731
|
+
}]
|
|
732
|
+
: [];
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
/** Finds the Loom entry of a pnpm catalog in pnpm-workspace.yaml text. */
|
|
736
|
+
function findLoomCatalogEntry(workspaceText, catalog) {
|
|
737
|
+
if (!workspaceText)
|
|
738
|
+
return null;
|
|
739
|
+
const lines = normalizeText(workspaceText).split("\n");
|
|
740
|
+
for (const path of catalogPaths(catalog)) {
|
|
741
|
+
const label = `${path.join(".")}:`;
|
|
742
|
+
for (const line of findYamlBlockMapEntries(lines, path) ?? []) {
|
|
743
|
+
const entry = parseYamlKeyLine(lines[line].trim());
|
|
744
|
+
if (entry?.key !== LOOM_DEPENDENCY)
|
|
745
|
+
continue;
|
|
746
|
+
return {
|
|
747
|
+
catalog,
|
|
748
|
+
flow: false,
|
|
749
|
+
label,
|
|
750
|
+
line,
|
|
751
|
+
spec: splitYamlScalarComment(entry.rest).value,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
const flow = findYamlFlowMapLine(lines, path);
|
|
755
|
+
if (flow && !flow.unsupported) {
|
|
756
|
+
const entry = parseYamlFlowEntries(flow.content).find((candidate) => candidate.key === LOOM_DEPENDENCY);
|
|
757
|
+
if (entry) {
|
|
758
|
+
return {
|
|
759
|
+
catalog,
|
|
760
|
+
flow: true,
|
|
761
|
+
label,
|
|
762
|
+
line: flow.line,
|
|
763
|
+
spec: entry.value,
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return null;
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Names a catalog that exists in a flow form Loom cannot read (multi-line
|
|
772
|
+
* or nested flow maps), so callers can say so instead of reporting a
|
|
773
|
+
* missing entry.
|
|
774
|
+
*/
|
|
775
|
+
function findUnreadableLoomCatalog(workspaceText, catalog) {
|
|
776
|
+
if (!workspaceText)
|
|
777
|
+
return null;
|
|
778
|
+
const lines = normalizeText(workspaceText).split("\n");
|
|
779
|
+
for (const path of catalogPaths(catalog)) {
|
|
780
|
+
if (findYamlFlowMapLine(lines, path)?.unsupported) {
|
|
781
|
+
return `${path.join(".")}:`;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return null;
|
|
785
|
+
}
|
|
786
|
+
/** Rewrites a catalog entry's version, keeping its key, quotes, and comment. */
|
|
787
|
+
function setLoomCatalogEntryText(workspaceText, entry, spec) {
|
|
788
|
+
const lines = normalizeText(workspaceText).split("\n");
|
|
789
|
+
const line = lines[entry.line];
|
|
790
|
+
if (entry.flow) {
|
|
791
|
+
const pattern = /((['"]?)@gadicc\/loom\2\s*:\s*)(['"]?)([^,}'"]*?)\3(\s*[,}])/;
|
|
792
|
+
if (!pattern.test(line))
|
|
793
|
+
return null;
|
|
794
|
+
lines[entry.line] = line.replace(pattern, (_match, prefix, _key, quote, _value, after) => `${prefix}${quote}${spec}${quote}${after}`);
|
|
795
|
+
return lines.join("\n");
|
|
796
|
+
}
|
|
797
|
+
const colon = line.match(/^(\s*(?:'[^']*'|"[^"]*"|[^\s#'"][^:]*?)\s*:\s+)(.*)$/);
|
|
798
|
+
if (!colon)
|
|
799
|
+
return null;
|
|
800
|
+
const { comment, quote } = splitYamlScalarComment(colon[2]);
|
|
801
|
+
lines[entry.line] = `${colon[1]}${quote}${spec}${quote}${comment}`;
|
|
802
|
+
return lines.join("\n");
|
|
803
|
+
}
|
|
804
|
+
async function resolveLoomDependencySpec(cwd, packageJson, options = {}) {
|
|
805
|
+
const raw = packageJson.dependencies?.[LOOM_DEPENDENCY] ??
|
|
806
|
+
(options.includeDev
|
|
807
|
+
? packageJson.devDependencies?.[LOOM_DEPENDENCY]
|
|
808
|
+
: undefined);
|
|
809
|
+
const catalogName = parseCatalogReference(raw);
|
|
810
|
+
if (!catalogName) {
|
|
811
|
+
return { catalogEntry: null, catalogName: null, effective: raw, raw };
|
|
812
|
+
}
|
|
813
|
+
const catalogEntry = findLoomCatalogEntry(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), catalogName);
|
|
814
|
+
return {
|
|
815
|
+
catalogEntry,
|
|
816
|
+
catalogName,
|
|
817
|
+
effective: catalogEntry?.spec,
|
|
818
|
+
raw,
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
/** Advice for moving a catalog-pinned Loom to `version`. */
|
|
822
|
+
function formatLoomCatalogPinAdvice(entry, catalogName, version) {
|
|
823
|
+
const map = entry?.label ??
|
|
824
|
+
(catalogName === "default" ? "catalog:" : `catalogs.${catalogName}:`);
|
|
825
|
+
return `Set ${LOOM_DEPENDENCY} to ${version} in the pnpm-workspace.yaml \`${map}\` map, then run \`pnpm install\` (\`pnpm add\` would replace the \`catalog:\` reference in package.json).`;
|
|
826
|
+
}
|
|
614
827
|
function isLocalPackageSpec(spec) {
|
|
615
828
|
return spec.startsWith("file:") || spec.startsWith("link:") ||
|
|
616
829
|
spec.startsWith("workspace:");
|
|
@@ -822,19 +1035,20 @@ function ensureLinguiGitignoreText(existingText, generatedCatalogs) {
|
|
|
822
1035
|
text: nextText,
|
|
823
1036
|
};
|
|
824
1037
|
}
|
|
825
|
-
function
|
|
1038
|
+
function loomDevGitignoreLineMatches(line, path) {
|
|
826
1039
|
const normalized = line.trim().replace(/^\/?/, "");
|
|
827
|
-
return normalized ===
|
|
828
|
-
normalized === ".loom
|
|
1040
|
+
return normalized === path || normalized === ".loom/" ||
|
|
1041
|
+
normalized === ".loom";
|
|
829
1042
|
}
|
|
830
1043
|
function ensureLoomDevStateGitignoreText(existingText) {
|
|
831
1044
|
const normalized = existingText ? normalizeText(existingText) : "";
|
|
832
1045
|
const lines = normalized
|
|
833
1046
|
.split("\n")
|
|
834
1047
|
.filter((line, index, array) => index < array.length - 1 || line !== "");
|
|
835
|
-
const missingLines =
|
|
836
|
-
|
|
837
|
-
|
|
1048
|
+
const missingLines = [
|
|
1049
|
+
LOOM_LOCAL_DEV_STATE_GITIGNORE_LINE,
|
|
1050
|
+
LOOM_LOCAL_DEV_LOCK_GITIGNORE_LINE,
|
|
1051
|
+
].filter((path) => !lines.some((line) => loomDevGitignoreLineMatches(line, path)));
|
|
838
1052
|
const nextText = missingLines.length
|
|
839
1053
|
? `${[...lines, ...missingLines].join("\n")}\n`
|
|
840
1054
|
: normalized;
|
|
@@ -1183,18 +1397,34 @@ function dependencyExecutable(tooling, executable) {
|
|
|
1183
1397
|
return `yarn ${executable}`;
|
|
1184
1398
|
}
|
|
1185
1399
|
}
|
|
1186
|
-
|
|
1400
|
+
/**
|
|
1401
|
+
* Command that moves one dependency to the given version without
|
|
1402
|
+
* re-resolving anything else. For pnpm, `pnpm add --save-exact` pins
|
|
1403
|
+
* package.json, replaces a local lockfile resolution left by an older
|
|
1404
|
+
* `pnpm update --no-save` link, and keeps every other locked version
|
|
1405
|
+
* (verified with pnpm 10.17); `pnpm update` would re-resolve the
|
|
1406
|
+
* dependency's subtree. Ranges get a plain install because `pnpm add`
|
|
1407
|
+
* rewrites a range's lower bound.
|
|
1408
|
+
*/
|
|
1409
|
+
function dependencyRefreshCommand(tooling, name, version, options = {}) {
|
|
1187
1410
|
switch (tooling.manager) {
|
|
1188
1411
|
case "deno":
|
|
1189
1412
|
return "deno install";
|
|
1190
1413
|
case "npm":
|
|
1191
1414
|
return `npm install --save-exact ${name}@${version}`;
|
|
1192
1415
|
case "pnpm":
|
|
1193
|
-
return
|
|
1416
|
+
return isExactSemverVersion(version)
|
|
1417
|
+
? `pnpm add${options.pnpmWorkspaceRoot ? " -w" : ""} --save-exact ${name}@${version}`
|
|
1418
|
+
: "pnpm install";
|
|
1194
1419
|
case "yarn":
|
|
1195
1420
|
return `yarn add --exact ${name}@${version}`;
|
|
1196
1421
|
}
|
|
1197
1422
|
}
|
|
1423
|
+
/** Whether pnpm treats this project root as a workspace root with packages. */
|
|
1424
|
+
async function pnpmWorkspaceDeclaresPackages(cwd) {
|
|
1425
|
+
const text = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
1426
|
+
return text !== null && /^packages:/m.test(normalizeText(text));
|
|
1427
|
+
}
|
|
1198
1428
|
function getDbExpectedScripts(config, tooling) {
|
|
1199
1429
|
const drizzleKit = dependencyExecutable(tooling.dependencies, "drizzle-kit");
|
|
1200
1430
|
return {
|
|
@@ -1684,6 +1914,10 @@ function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
|
|
|
1684
1914
|
? "src/api-lib/apiKeys"
|
|
1685
1915
|
: "api-lib/apiKeys";
|
|
1686
1916
|
return {
|
|
1917
|
+
// Recorded by the app; Loom never infers or rewrites this choice.
|
|
1918
|
+
...(featureConfig?.betterAuthHttpEndpoints !== undefined
|
|
1919
|
+
? { betterAuthHttpEndpoints: featureConfig.betterAuthHttpEndpoints }
|
|
1920
|
+
: {}),
|
|
1687
1921
|
entrypoints: {
|
|
1688
1922
|
adminPage: featureConfig?.entrypoints?.adminPage ??
|
|
1689
1923
|
`${appRoot}/admin/api-keys/page.tsx`,
|
|
@@ -1900,7 +2134,7 @@ export function ensureNextAgentsMdText(existingText) {
|
|
|
1900
2134
|
: "\n\n"}${block}`;
|
|
1901
2135
|
return { changed: text !== normalized, text };
|
|
1902
2136
|
}
|
|
1903
|
-
function getManagedDevOverrideBlock(overrideSpec, state) {
|
|
2137
|
+
function getManagedDevOverrideBlock(overrideSpec, state, layout = {}) {
|
|
1904
2138
|
// This is a workaround for current pnpm behavior around local package
|
|
1905
2139
|
// development. In testing with pnpm 10.x, direct `pnpm link` against Loom
|
|
1906
2140
|
// mutated pnpm-workspace overrides anyway and broke peer resolution from
|
|
@@ -1919,13 +2153,32 @@ function getManagedDevOverrideBlock(overrideSpec, state) {
|
|
|
1919
2153
|
: null,
|
|
1920
2154
|
].filter((line) => line !== null)
|
|
1921
2155
|
: [];
|
|
2156
|
+
const pad = " ".repeat(layout.indent ?? 2);
|
|
1922
2157
|
return [
|
|
1923
|
-
|
|
1924
|
-
...
|
|
1925
|
-
|
|
1926
|
-
|
|
2158
|
+
`${pad}${LOOM_MANAGED_DEV_OVERRIDE_START}`,
|
|
2159
|
+
...(layout.createdHeader === undefined ? [] : [
|
|
2160
|
+
`${pad}# overrides-header: ${layout.createdHeader ? "created" : "existing"}`,
|
|
2161
|
+
]),
|
|
2162
|
+
...(layout.replacedHeader
|
|
2163
|
+
? [`${pad}# replaced-header: ${layout.replacedHeader}`]
|
|
2164
|
+
: []),
|
|
2165
|
+
...stateLines.map((line) => `${pad}${line}`),
|
|
2166
|
+
`${pad}"${LOOM_DEPENDENCY}": ${JSON.stringify(overrideSpec)}`,
|
|
2167
|
+
`${pad}${LOOM_MANAGED_DEV_OVERRIDE_END}`,
|
|
1927
2168
|
].join("\n");
|
|
1928
2169
|
}
|
|
2170
|
+
/** Reads the layout markers and indentation of an existing managed block. */
|
|
2171
|
+
function getManagedDevOverrideBlockLayout(blockText) {
|
|
2172
|
+
if (!blockText)
|
|
2173
|
+
return {};
|
|
2174
|
+
const header = getManagedDevStateValue(blockText, "overrides-header");
|
|
2175
|
+
return {
|
|
2176
|
+
// Blocks from before this marker always removed an empty bare header.
|
|
2177
|
+
createdHeader: header === undefined ? undefined : header === "created",
|
|
2178
|
+
indent: blockText.length - blockText.trimStart().length,
|
|
2179
|
+
replacedHeader: getManagedDevStateValue(blockText, "replaced-header"),
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
1929
2182
|
function getManagedDevOverrideBlockRegex() {
|
|
1930
2183
|
return new RegExp(`^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_START)}\\n[\\s\\S]*?^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_END)}\\n?`, "m");
|
|
1931
2184
|
}
|
|
@@ -1935,24 +2188,149 @@ function formatYamlLines(lines) {
|
|
|
1935
2188
|
}
|
|
1936
2189
|
return lines.length ? `${lines.join("\n")}\n` : "";
|
|
1937
2190
|
}
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
2191
|
+
const OVERRIDES_KEY_PATTERN = /^(?:overrides|"overrides"|'overrides'):(?:\s|$)/;
|
|
2192
|
+
/**
|
|
2193
|
+
* Locates the top-level `overrides:` key (plain or quoted) of
|
|
2194
|
+
* pnpm-workspace.yaml lines and how its value is written: a block map
|
|
2195
|
+
* (`overrides:`, optionally with a comment), an empty flow map
|
|
2196
|
+
* (`overrides: {}`), or another flow/scalar form Loom cannot add entries
|
|
2197
|
+
* to. `end` is the index of the next top-level key and `indent` the
|
|
2198
|
+
* indentation of the map's entries.
|
|
2199
|
+
*/
|
|
2200
|
+
function findPnpmWorkspaceOverridesHeader(lines) {
|
|
2201
|
+
const index = lines.findIndex((line) => OVERRIDES_KEY_PATTERN.test(line));
|
|
2202
|
+
if (index === -1)
|
|
1942
2203
|
return null;
|
|
1943
|
-
|
|
2204
|
+
const value = lines[index].slice(lines[index].indexOf(":") + 1).trim();
|
|
2205
|
+
const style = value === "" || value.startsWith("#")
|
|
2206
|
+
? "block"
|
|
2207
|
+
: /^\{\s*\}\s*(?:#.*)?$/.test(value)
|
|
2208
|
+
? "empty-flow"
|
|
2209
|
+
: "other";
|
|
1944
2210
|
let end = lines.length;
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
2211
|
+
let indent = null;
|
|
2212
|
+
for (let line = index + 1; line < lines.length; line += 1) {
|
|
2213
|
+
const trimmed = lines[line].trim();
|
|
2214
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
2215
|
+
continue;
|
|
2216
|
+
if (!/^\s/.test(lines[line])) {
|
|
2217
|
+
end = line;
|
|
2218
|
+
break;
|
|
2219
|
+
}
|
|
2220
|
+
indent ??= lines[line].length - lines[line].trimStart().length;
|
|
2221
|
+
}
|
|
2222
|
+
return { end, indent: indent ?? 2, index, style };
|
|
2223
|
+
}
|
|
2224
|
+
/**
|
|
2225
|
+
* Lists the keys of the top-level `overrides:` map in pnpm-workspace.yaml
|
|
2226
|
+
* text, in block or single-line flow style. Other maps that can mention
|
|
2227
|
+
* Loom, such as `catalog:` and `catalogs:`, are not overrides.
|
|
2228
|
+
*/
|
|
2229
|
+
function getPnpmWorkspaceOverrideKeys(text) {
|
|
2230
|
+
const lines = normalizeText(text).split("\n");
|
|
2231
|
+
const start = findPnpmWorkspaceOverridesHeader(lines)?.index ?? -1;
|
|
2232
|
+
if (start === -1)
|
|
2233
|
+
return [];
|
|
2234
|
+
const flow = lines[start].slice(lines[start].indexOf(":") + 1).match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
|
|
2235
|
+
if (flow) {
|
|
2236
|
+
return flow[1].split(",").flatMap((entry) => {
|
|
2237
|
+
const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:/);
|
|
2238
|
+
return match ? [match[1] ?? match[2] ?? match[3]] : [];
|
|
2239
|
+
});
|
|
2240
|
+
}
|
|
2241
|
+
const keys = [];
|
|
2242
|
+
let indent = null;
|
|
2243
|
+
for (const line of lines.slice(start + 1)) {
|
|
2244
|
+
const trimmed = line.trim();
|
|
2245
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
2246
|
+
continue;
|
|
2247
|
+
// The next top-level key ends the map.
|
|
2248
|
+
if (!/^\s/.test(line))
|
|
1949
2249
|
break;
|
|
2250
|
+
const lineIndent = line.length - line.trimStart().length;
|
|
2251
|
+
indent ??= lineIndent;
|
|
2252
|
+
if (lineIndent !== indent)
|
|
2253
|
+
continue;
|
|
2254
|
+
const match = trimmed.match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:(?:\s|$)/);
|
|
2255
|
+
if (match)
|
|
2256
|
+
keys.push(match[1] ?? match[2] ?? match[3]);
|
|
2257
|
+
}
|
|
2258
|
+
return keys;
|
|
2259
|
+
}
|
|
2260
|
+
/** A YAML scalar without quotes or a trailing comment. */
|
|
2261
|
+
function plainYamlValue(value) {
|
|
2262
|
+
const trimmed = value.trim();
|
|
2263
|
+
if (/^["']/.test(trimmed)) {
|
|
2264
|
+
const quote = trimmed[0];
|
|
2265
|
+
const end = trimmed.indexOf(quote, 1);
|
|
2266
|
+
return end === -1 ? trimmed.slice(1) : trimmed.slice(1, end);
|
|
2267
|
+
}
|
|
2268
|
+
return trimmed.replace(/\s+#.*$/, "").trim();
|
|
2269
|
+
}
|
|
2270
|
+
/**
|
|
2271
|
+
* Local (`file:`/`link:`) Loom entries of the pnpm-workspace.yaml
|
|
2272
|
+
* `overrides:` map outside Loom's managed block, such as one written by
|
|
2273
|
+
* hand. `line` is the entry's line in `text` once the managed block is
|
|
2274
|
+
* removed, or null in flow style, which Loom does not edit.
|
|
2275
|
+
*/
|
|
2276
|
+
function getUnmanagedPnpmWorkspaceLoomOverrides(text) {
|
|
2277
|
+
const entries = [];
|
|
2278
|
+
if (!text)
|
|
2279
|
+
return entries;
|
|
2280
|
+
const lines = normalizeText(text).replace(getManagedDevOverrideBlockRegex(), "").split("\n");
|
|
2281
|
+
const header = findPnpmWorkspaceOverridesHeader(lines);
|
|
2282
|
+
if (!header)
|
|
2283
|
+
return entries;
|
|
2284
|
+
const add = (key, value, line) => {
|
|
2285
|
+
const spec = plainYamlValue(value);
|
|
2286
|
+
if (overrideKeyTargetsLoom(key) && /^(?:file|link):/.test(spec)) {
|
|
2287
|
+
entries.push({ key, line, spec });
|
|
2288
|
+
}
|
|
2289
|
+
};
|
|
2290
|
+
const flow = lines[header.index].slice(lines[header.index].indexOf(":") + 1)
|
|
2291
|
+
.match(/^\s*\{(.*)\}\s*(?:#.*)?$/);
|
|
2292
|
+
if (flow) {
|
|
2293
|
+
for (const entry of flow[1].split(",")) {
|
|
2294
|
+
const match = entry.trim().match(/^(?:'([^']*)'|"([^"]*)"|([^:]+?))\s*:\s*(.*)$/);
|
|
2295
|
+
if (match)
|
|
2296
|
+
add(match[1] ?? match[2] ?? match[3], match[4], null);
|
|
1950
2297
|
}
|
|
2298
|
+
return entries;
|
|
2299
|
+
}
|
|
2300
|
+
for (let index = header.index + 1; index < header.end; index += 1) {
|
|
2301
|
+
const line = lines[index];
|
|
2302
|
+
if (line.length - line.trimStart().length !== header.indent)
|
|
2303
|
+
continue;
|
|
2304
|
+
const match = line.trim().match(/^(?:'([^']+)'|"([^"]+)"|([^\s#'"][^:]*?))\s*:\s+(\S.*)$/);
|
|
2305
|
+
if (match)
|
|
2306
|
+
add(match[1] ?? match[2] ?? match[3], match[4], index);
|
|
2307
|
+
}
|
|
2308
|
+
return entries;
|
|
2309
|
+
}
|
|
2310
|
+
/**
|
|
2311
|
+
* Removes the block-style entries {@link getUnmanagedPnpmWorkspaceLoomOverrides}
|
|
2312
|
+
* finds, and a bare `overrides:` header left without entries. Expects text
|
|
2313
|
+
* without Loom's managed block. Flow-style entries stay and are returned.
|
|
2314
|
+
*/
|
|
2315
|
+
function removeUnmanagedPnpmWorkspaceLoomOverrides(text) {
|
|
2316
|
+
const entries = getUnmanagedPnpmWorkspaceLoomOverrides(text);
|
|
2317
|
+
const lines = normalizeText(text).split("\n");
|
|
2318
|
+
const removable = new Set(entries.flatMap((entry) => entry.line === null ? [] : [entry.line]));
|
|
2319
|
+
const kept = lines.filter((_, index) => !removable.has(index));
|
|
2320
|
+
const header = findPnpmWorkspaceOverridesHeader(kept);
|
|
2321
|
+
if (removable.size && header?.style === "block" &&
|
|
2322
|
+
kept[header.index] === "overrides:" &&
|
|
2323
|
+
!hasYamlEntries(kept.slice(header.index + 1, header.end))) {
|
|
2324
|
+
kept.splice(header.index, 1);
|
|
1951
2325
|
}
|
|
1952
|
-
return {
|
|
2326
|
+
return {
|
|
2327
|
+
changed: removable.size > 0,
|
|
2328
|
+
kept: entries.filter((entry) => entry.line === null),
|
|
2329
|
+
text: formatYamlLines(kept).replace(/\n{3,}/g, "\n\n"),
|
|
2330
|
+
};
|
|
1953
2331
|
}
|
|
1954
2332
|
function hasUnmanagedLoomOverride(text) {
|
|
1955
|
-
return
|
|
2333
|
+
return getPnpmWorkspaceOverrideKeys(text).some(overrideKeyTargetsLoom);
|
|
1956
2334
|
}
|
|
1957
2335
|
function getManagedDevOverrideSpec(text) {
|
|
1958
2336
|
if (!text) {
|
|
@@ -2002,7 +2380,7 @@ function getManagedDevState(text) {
|
|
|
2002
2380
|
}
|
|
2003
2381
|
function setManagedDevStateText(existingText, overrideSpec, state) {
|
|
2004
2382
|
const normalized = existingText ? normalizeText(existingText) : "";
|
|
2005
|
-
const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state)}\n`);
|
|
2383
|
+
const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state, getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized)))}\n`);
|
|
2006
2384
|
return {
|
|
2007
2385
|
changed: nextText !== normalized,
|
|
2008
2386
|
text: nextText,
|
|
@@ -2031,17 +2409,45 @@ export function ensurePnpmWorkspaceLocalDevText(existingText, overrideSpec) {
|
|
|
2031
2409
|
text: normalized,
|
|
2032
2410
|
};
|
|
2033
2411
|
}
|
|
2034
|
-
const blockLines = getManagedDevOverrideBlock(overrideSpec).split("\n");
|
|
2035
2412
|
const lines = baseText === "" ? [] : baseText.replace(/\n$/, "").split("\n");
|
|
2036
|
-
const
|
|
2037
|
-
|
|
2038
|
-
|
|
2413
|
+
const header = findPnpmWorkspaceOverridesHeader(lines);
|
|
2414
|
+
// Relinking: put back the `overrides: {}` line an earlier link rewrote.
|
|
2415
|
+
const previous = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
|
|
2416
|
+
if (header && previous.replacedHeader && lines[header.index] === "overrides:" &&
|
|
2417
|
+
!hasYamlEntries(lines.slice(header.index + 1, header.end))) {
|
|
2418
|
+
lines[header.index] = previous.replacedHeader;
|
|
2419
|
+
}
|
|
2420
|
+
const current = findPnpmWorkspaceOverridesHeader(lines);
|
|
2421
|
+
if (current?.style === "other") {
|
|
2422
|
+
return {
|
|
2423
|
+
changed: false,
|
|
2424
|
+
conflict: "pnpm-workspace.yaml writes `overrides` as a flow map or scalar. Rewrite it as a block map, one `name: version` entry per line under `overrides:`, so Loom can add its managed override.",
|
|
2425
|
+
text: normalized,
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
if (current) {
|
|
2429
|
+
const replacedHeader = current.style === "empty-flow"
|
|
2430
|
+
? lines[current.index]
|
|
2431
|
+
: undefined;
|
|
2432
|
+
if (replacedHeader)
|
|
2433
|
+
lines[current.index] = "overrides:";
|
|
2434
|
+
lines.splice(current.index + 1, 0, ...getManagedDevOverrideBlock(overrideSpec, undefined, {
|
|
2435
|
+
// A relink keeps what the first link recorded about the header,
|
|
2436
|
+
// including nothing at all for blocks written before the marker.
|
|
2437
|
+
createdHeader: previous.indent === undefined
|
|
2438
|
+
? false
|
|
2439
|
+
: previous.createdHeader,
|
|
2440
|
+
indent: current.style === "block" ? current.indent : 2,
|
|
2441
|
+
replacedHeader,
|
|
2442
|
+
}).split("\n"));
|
|
2039
2443
|
}
|
|
2040
2444
|
else {
|
|
2041
2445
|
if (lines.length && lines.at(-1) !== "") {
|
|
2042
2446
|
lines.push("");
|
|
2043
2447
|
}
|
|
2044
|
-
lines.push("overrides:", ...
|
|
2448
|
+
lines.push("overrides:", ...getManagedDevOverrideBlock(overrideSpec, undefined, {
|
|
2449
|
+
createdHeader: true,
|
|
2450
|
+
}).split("\n"));
|
|
2045
2451
|
}
|
|
2046
2452
|
const nextText = formatYamlLines(lines);
|
|
2047
2453
|
return {
|
|
@@ -2058,19 +2464,21 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
|
|
|
2058
2464
|
text: normalized,
|
|
2059
2465
|
};
|
|
2060
2466
|
}
|
|
2467
|
+
const { createdHeader, replacedHeader } = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
|
|
2061
2468
|
const withoutManaged = normalized.replace(getManagedDevOverrideBlockRegex(), "");
|
|
2062
2469
|
const lines = withoutManaged === ""
|
|
2063
2470
|
? []
|
|
2064
2471
|
: withoutManaged.replace(/\n$/, "").split("\n");
|
|
2065
|
-
const
|
|
2066
|
-
if (
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
lines.
|
|
2472
|
+
const header = findPnpmWorkspaceOverridesHeader(lines);
|
|
2473
|
+
if (header?.style === "block" &&
|
|
2474
|
+
!hasYamlEntries(lines.slice(header.index + 1, header.end))) {
|
|
2475
|
+
if (replacedHeader) {
|
|
2476
|
+
lines[header.index] = replacedHeader;
|
|
2477
|
+
}
|
|
2478
|
+
else if (createdHeader ??
|
|
2479
|
+
// Older blocks did not record it; Loom only added bare headers.
|
|
2480
|
+
lines[header.index] === "overrides:") {
|
|
2481
|
+
lines.splice(header.index, header.end - header.index);
|
|
2074
2482
|
}
|
|
2075
2483
|
}
|
|
2076
2484
|
const nextText = formatYamlLines(lines).replace(/\n{3,}/g, "\n\n");
|
|
@@ -2079,6 +2487,262 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
|
|
|
2079
2487
|
text: nextText,
|
|
2080
2488
|
};
|
|
2081
2489
|
}
|
|
2490
|
+
const PACKAGE_JSON_OVERRIDE_LOCATIONS = [
|
|
2491
|
+
{ field: "resolutions", location: "package.json#resolutions" },
|
|
2492
|
+
{ field: "pnpm.overrides", location: "package.json#pnpm.overrides" },
|
|
2493
|
+
];
|
|
2494
|
+
function formatPnpmOverrideLocation(location) {
|
|
2495
|
+
switch (location) {
|
|
2496
|
+
case "package.json#pnpm.overrides":
|
|
2497
|
+
return "package.json pnpm.overrides";
|
|
2498
|
+
case "package.json#resolutions":
|
|
2499
|
+
return "package.json resolutions";
|
|
2500
|
+
case "pnpm-workspace.yaml":
|
|
2501
|
+
return "pnpm-workspace.yaml";
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
function getPackageJsonOverrideMap(packageJson, field) {
|
|
2505
|
+
const value = field === "resolutions"
|
|
2506
|
+
? packageJson.resolutions
|
|
2507
|
+
: packageJson.pnpm?.overrides;
|
|
2508
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
2509
|
+
? value
|
|
2510
|
+
: {};
|
|
2511
|
+
}
|
|
2512
|
+
function isManagedPackageJsonLoomOverride(spec) {
|
|
2513
|
+
return typeof spec === "string" && spec.startsWith("file:");
|
|
2514
|
+
}
|
|
2515
|
+
/**
|
|
2516
|
+
* Lists local `file:` Loom overrides in package.json override maps. Loom only
|
|
2517
|
+
* writes `file:` specs there, and a local spec is never shippable, so these
|
|
2518
|
+
* entries are treated as the managed local-dev override.
|
|
2519
|
+
*/
|
|
2520
|
+
function getPackageJsonLocalLoomOverrides(packageJson) {
|
|
2521
|
+
return PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => {
|
|
2522
|
+
const spec = getPackageJsonOverrideMap(packageJson, field)[LOOM_DEPENDENCY];
|
|
2523
|
+
return isManagedPackageJsonLoomOverride(spec) ? [{ location, spec }] : [];
|
|
2524
|
+
});
|
|
2525
|
+
}
|
|
2526
|
+
/** Returns the managed local Loom override of a pnpm project, if active. */
|
|
2527
|
+
function getActivePnpmLocalDevOverride(workspaceText, packageJson) {
|
|
2528
|
+
const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
|
|
2529
|
+
if (workspaceSpec) {
|
|
2530
|
+
return { location: "pnpm-workspace.yaml", spec: workspaceSpec };
|
|
2531
|
+
}
|
|
2532
|
+
return getPackageJsonLocalLoomOverrides(packageJson)[0] ?? null;
|
|
2533
|
+
}
|
|
2534
|
+
function getUnmanagedPnpmWorkspaceOverrideNames(text) {
|
|
2535
|
+
const normalized = text ? normalizeText(text) : "";
|
|
2536
|
+
return getPnpmWorkspaceOverrideKeys(normalized.replace(getManagedDevOverrideBlockRegex(), ""));
|
|
2537
|
+
}
|
|
2538
|
+
/** First pnpm release that reads `overrides` from pnpm-workspace.yaml. */
|
|
2539
|
+
const PNPM_WORKSPACE_OVERRIDES_SINCE = [10, 5, 1];
|
|
2540
|
+
function parsePnpmVersion(value) {
|
|
2541
|
+
const match = value?.match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
2542
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
|
|
2543
|
+
}
|
|
2544
|
+
function pnpmVersionAtLeast(version, minimum) {
|
|
2545
|
+
for (let index = 0; index < 3; index += 1) {
|
|
2546
|
+
if (version[index] !== minimum[index]) {
|
|
2547
|
+
return version[index] > minimum[index];
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
return true;
|
|
2551
|
+
}
|
|
2552
|
+
async function detectPnpmVersion(cwd, packageJson, commandRunner, env) {
|
|
2553
|
+
const declared = parsePnpmVersion(packageJson.packageManager?.match(/^pnpm@(.+)$/)?.[1]);
|
|
2554
|
+
if (declared)
|
|
2555
|
+
return declared;
|
|
2556
|
+
// Not npm_config_user_agent: it names the pnpm running the current
|
|
2557
|
+
// script, which can differ from the `pnpm` this process spawns (a pnpm
|
|
2558
|
+
// devDependency in node_modules/.bin, say).
|
|
2559
|
+
const cached = spawnedPnpmVersions.get(commandRunner)?.get(cwd);
|
|
2560
|
+
if (cached)
|
|
2561
|
+
return await cached;
|
|
2562
|
+
const pending = detectSpawnedPnpmVersion(cwd, commandRunner, env);
|
|
2563
|
+
const byCwd = spawnedPnpmVersions.get(commandRunner) ?? new Map();
|
|
2564
|
+
byCwd.set(cwd, pending);
|
|
2565
|
+
spawnedPnpmVersions.set(commandRunner, byCwd);
|
|
2566
|
+
return await pending;
|
|
2567
|
+
}
|
|
2568
|
+
/**
|
|
2569
|
+
* `pnpm --version` results for this process, per command runner and
|
|
2570
|
+
* project, so one command spawns pnpm at most once per project.
|
|
2571
|
+
*/
|
|
2572
|
+
const spawnedPnpmVersions = new WeakMap();
|
|
2573
|
+
async function detectSpawnedPnpmVersion(cwd, commandRunner, env) {
|
|
2574
|
+
const result = await commandRunner("pnpm", ["--version"], { cwd, env })
|
|
2575
|
+
.catch(() => null);
|
|
2576
|
+
const running = result?.code === 0
|
|
2577
|
+
? parsePnpmVersion(result.stdout.trim())
|
|
2578
|
+
: null;
|
|
2579
|
+
if (running)
|
|
2580
|
+
return running;
|
|
2581
|
+
// The pnpm that last installed node_modules, when pnpm itself cannot run.
|
|
2582
|
+
const modules = await readTextIfExists(join(cwd, "node_modules", ".modules.yaml"));
|
|
2583
|
+
return parsePnpmVersion(modules?.match(/^\s*"?packageManager"?\s*:\s*"?pnpm@([^"\s]+)/m)?.[1]);
|
|
2584
|
+
}
|
|
2585
|
+
/**
|
|
2586
|
+
* Chooses the override map pnpm will actually apply. Verified with real
|
|
2587
|
+
* pnpm 9.7.0 through 11.25.0 on a local directory override:
|
|
2588
|
+
* - before 10.5.1, pnpm reads overrides only from package.json `resolutions`
|
|
2589
|
+
* and `pnpm.overrides` (Loom creates `resolutions` when neither exists);
|
|
2590
|
+
* - from 10.5.1, pnpm also reads pnpm-workspace.yaml `overrides`, but only
|
|
2591
|
+
* while both package.json maps are empty, never merged with them;
|
|
2592
|
+
* - pnpm 11 reads only pnpm-workspace.yaml `overrides`.
|
|
2593
|
+
* Writing the override anywhere else leaves pnpm reporting an up-to-date
|
|
2594
|
+
* lockfile that still resolves the published package. An unknown version is
|
|
2595
|
+
* treated as pnpm 10.5.1 or newer.
|
|
2596
|
+
*/
|
|
2597
|
+
async function resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env) {
|
|
2598
|
+
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
2599
|
+
const workspaceBase = workspaceText
|
|
2600
|
+
? normalizeText(workspaceText).replace(getManagedDevOverrideBlockRegex(), "")
|
|
2601
|
+
: "";
|
|
2602
|
+
const version = await detectPnpmVersion(cwd, packageJson, commandRunner, env);
|
|
2603
|
+
const pnpmVersion = version ? version.join(".") : null;
|
|
2604
|
+
const pnpmMajor = version ? version[0] : null;
|
|
2605
|
+
const pnpmLabel = pnpmVersion ? `pnpm ${pnpmVersion}` : "pnpm 10";
|
|
2606
|
+
const workspace = {
|
|
2607
|
+
conflict: hasUnmanagedLoomOverride(workspaceBase)
|
|
2608
|
+
? `pnpm-workspace.yaml already defines an unmanaged override for ${LOOM_DEPENDENCY}. Move that override aside before enabling loom local-dev mode.`
|
|
2609
|
+
: null,
|
|
2610
|
+
location: "pnpm-workspace.yaml",
|
|
2611
|
+
notes: [],
|
|
2612
|
+
pnpmMajor,
|
|
2613
|
+
pnpmVersion,
|
|
2614
|
+
};
|
|
2615
|
+
const packageJsonEntries = PACKAGE_JSON_OVERRIDE_LOCATIONS.map(({ field, location }) => {
|
|
2616
|
+
const map = getPackageJsonOverrideMap(packageJson, field);
|
|
2617
|
+
return {
|
|
2618
|
+
loomSpec: map[LOOM_DEPENDENCY],
|
|
2619
|
+
location,
|
|
2620
|
+
names: Object.keys(map).filter((name) => !(name === LOOM_DEPENDENCY &&
|
|
2621
|
+
isManagedPackageJsonLoomOverride(map[name]))),
|
|
2622
|
+
};
|
|
2623
|
+
});
|
|
2624
|
+
const packageJsonHasOverrides = packageJsonEntries.some((entry) => entry.names.length > 0);
|
|
2625
|
+
if (pnpmMajor !== null && pnpmMajor >= 11) {
|
|
2626
|
+
return {
|
|
2627
|
+
...workspace,
|
|
2628
|
+
notes: packageJsonHasOverrides
|
|
2629
|
+
? [
|
|
2630
|
+
`pnpm ${pnpmVersion} ignores package.json resolutions and pnpm.overrides, so the Loom override stays in pnpm-workspace.yaml. Move any of those package.json entries the project still needs into pnpm-workspace.yaml overrides.`,
|
|
2631
|
+
]
|
|
2632
|
+
: [],
|
|
2633
|
+
};
|
|
2634
|
+
}
|
|
2635
|
+
const readsWorkspaceOverrides = version === null ||
|
|
2636
|
+
pnpmVersionAtLeast(version, PNPM_WORKSPACE_OVERRIDES_SINCE);
|
|
2637
|
+
if (readsWorkspaceOverrides && !packageJsonHasOverrides)
|
|
2638
|
+
return workspace;
|
|
2639
|
+
const unmanagedLoom = packageJsonEntries.find((entry) => entry.loomSpec !== undefined &&
|
|
2640
|
+
!isManagedPackageJsonLoomOverride(entry.loomSpec));
|
|
2641
|
+
// pnpm 10 merges both package.json maps, so an override already in one of
|
|
2642
|
+
// them stays put rather than moving whenever the user edits the other.
|
|
2643
|
+
const location = packageJsonEntries.find((entry) => isManagedPackageJsonLoomOverride(entry.loomSpec))?.location ??
|
|
2644
|
+
packageJsonEntries.find((entry) => entry.names.length)?.location ??
|
|
2645
|
+
"package.json#resolutions";
|
|
2646
|
+
const label = formatPnpmOverrideLocation(location);
|
|
2647
|
+
const notes = [
|
|
2648
|
+
readsWorkspaceOverrides
|
|
2649
|
+
? `${pnpmLabel} applies package.json resolutions/pnpm.overrides instead of pnpm-workspace.yaml overrides while either has entries, so the Loom override is kept in ${label}. Do not commit it; \`loom dev published\` removes it.`
|
|
2650
|
+
: `${pnpmLabel} reads overrides only from package.json (pnpm-workspace.yaml overrides need pnpm ${PNPM_WORKSPACE_OVERRIDES_SINCE.join(".")} or newer), so the Loom override is kept in ${label}. Do not commit it; \`loom dev published\` removes it.`,
|
|
2651
|
+
];
|
|
2652
|
+
const ignoredWorkspaceNames = getUnmanagedPnpmWorkspaceOverrideNames(workspaceText);
|
|
2653
|
+
if (ignoredWorkspaceNames.length) {
|
|
2654
|
+
notes.push(`${pnpmLabel} also ignores these pnpm-workspace.yaml overrides: ${ignoredWorkspaceNames.join(", ")}. Keep all overrides in one place.`);
|
|
2655
|
+
}
|
|
2656
|
+
return {
|
|
2657
|
+
conflict: workspace.conflict ??
|
|
2658
|
+
(unmanagedLoom
|
|
2659
|
+
? `${formatPnpmOverrideLocation(unmanagedLoom.location)} already defines an unmanaged override for ${LOOM_DEPENDENCY} (${String(unmanagedLoom.loomSpec)}). Move that override aside before enabling loom local-dev mode.`
|
|
2660
|
+
: null),
|
|
2661
|
+
location,
|
|
2662
|
+
notes,
|
|
2663
|
+
pnpmMajor,
|
|
2664
|
+
pnpmVersion,
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
/**
|
|
2668
|
+
* Writes the managed override at one location, then removes managed
|
|
2669
|
+
* overrides from every other location, so pnpm sees exactly one Loom
|
|
2670
|
+
* override and an interrupted move never leaves none. An existing workspace
|
|
2671
|
+
* block for the same spec is kept with its sync state.
|
|
2672
|
+
*/
|
|
2673
|
+
async function placePnpmLocalDevOverride(cwd, overrideSpec, location) {
|
|
2674
|
+
const changedFiles = new Set();
|
|
2675
|
+
const workspacePath = join(cwd, "pnpm-workspace.yaml");
|
|
2676
|
+
const setPackageJsonOverride = async (field, value) => {
|
|
2677
|
+
const update = await mutatePackageJsonOverride(cwd, field, LOOM_DEPENDENCY, value);
|
|
2678
|
+
if (update.changed)
|
|
2679
|
+
changedFiles.add("package.json");
|
|
2680
|
+
};
|
|
2681
|
+
const workspaceText = await readTextIfExists(workspacePath);
|
|
2682
|
+
if (location === "pnpm-workspace.yaml") {
|
|
2683
|
+
if (getManagedDevOverrideSpec(workspaceText) !== overrideSpec) {
|
|
2684
|
+
const update = ensurePnpmWorkspaceLocalDevText(workspaceText, overrideSpec);
|
|
2685
|
+
if (update.conflict)
|
|
2686
|
+
throw new Error(update.conflict);
|
|
2687
|
+
if (update.changed) {
|
|
2688
|
+
await writeTextOrDeleteIfEmpty(workspacePath, update.text);
|
|
2689
|
+
changedFiles.add("pnpm-workspace.yaml");
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
else {
|
|
2694
|
+
const target = PACKAGE_JSON_OVERRIDE_LOCATIONS.find((entry) => entry.location === location);
|
|
2695
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2696
|
+
// Record, before writing, whether Loom is about to create the map (and
|
|
2697
|
+
// the `pnpm` object), so unlinking removes exactly what Loom added.
|
|
2698
|
+
const created = await readCreatedPackageJsonMaps(cwd);
|
|
2699
|
+
const pnpmField = target.field === "pnpm.overrides";
|
|
2700
|
+
if (getRawPackageJsonMap(packageJson, target.field) === undefined) {
|
|
2701
|
+
created[target.field] = true;
|
|
2702
|
+
if (pnpmField)
|
|
2703
|
+
created.pnpm = packageJson.pnpm === undefined;
|
|
2704
|
+
}
|
|
2705
|
+
else if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, target.field)[LOOM_DEPENDENCY])) {
|
|
2706
|
+
// A map without Loom's entry belongs to the project, even if an
|
|
2707
|
+
// earlier link created it: the user may have dropped Loom's entry by
|
|
2708
|
+
// hand and committed a map of their own since.
|
|
2709
|
+
created[target.field] = false;
|
|
2710
|
+
if (pnpmField)
|
|
2711
|
+
created.pnpm = false;
|
|
2712
|
+
}
|
|
2713
|
+
await setPackageJsonOverride(target.field, overrideSpec);
|
|
2714
|
+
await writeCreatedPackageJsonMaps(cwd, created, overrideSpec);
|
|
2715
|
+
}
|
|
2716
|
+
for (const { field, location: fieldLocation } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
|
|
2717
|
+
if (fieldLocation === location)
|
|
2718
|
+
continue;
|
|
2719
|
+
if (await removePackageJsonLoomOverride(cwd, field)) {
|
|
2720
|
+
changedFiles.add("package.json");
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
if (location !== "pnpm-workspace.yaml") {
|
|
2724
|
+
const update = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
|
|
2725
|
+
if (update.changed) {
|
|
2726
|
+
await writeTextOrDeleteIfEmpty(workspacePath, update.text);
|
|
2727
|
+
changedFiles.add("pnpm-workspace.yaml");
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
return [...changedFiles];
|
|
2731
|
+
}
|
|
2732
|
+
/**
|
|
2733
|
+
* Proves that pnpm applied the managed override: pnpm records the override
|
|
2734
|
+
* map it actually used in the lockfile's top-level `overrides:` section.
|
|
2735
|
+
*/
|
|
2736
|
+
function lockfileAppliesLocalDevOverride(lockfileText, overrideSpec) {
|
|
2737
|
+
return lockfileText !== null &&
|
|
2738
|
+
getLockfileOverride(lockfileText, LOOM_DEPENDENCY) === overrideSpec;
|
|
2739
|
+
}
|
|
2740
|
+
function hasYamlEntries(lines) {
|
|
2741
|
+
return lines.some((line) => {
|
|
2742
|
+
const trimmed = line.trim();
|
|
2743
|
+
return trimmed !== "" && !trimmed.startsWith("#");
|
|
2744
|
+
});
|
|
2745
|
+
}
|
|
2082
2746
|
function pnpmWorkspaceExcludesMinimumReleaseAge(text, dependency) {
|
|
2083
2747
|
if (!text)
|
|
2084
2748
|
return false;
|
|
@@ -2143,6 +2807,13 @@ async function writeTextOrDeleteIfEmpty(path, text) {
|
|
|
2143
2807
|
await mkdir(dirname(path), { recursive: true });
|
|
2144
2808
|
await writeFile(path, text, "utf8");
|
|
2145
2809
|
}
|
|
2810
|
+
async function isPnpmProject(cwd, packageJson) {
|
|
2811
|
+
if (packageJson.packageManager) {
|
|
2812
|
+
return packageJson.packageManager.startsWith("pnpm@");
|
|
2813
|
+
}
|
|
2814
|
+
return await exists(join(cwd, "pnpm-lock.yaml")) ||
|
|
2815
|
+
await exists(join(cwd, "pnpm-workspace.yaml"));
|
|
2816
|
+
}
|
|
2146
2817
|
async function ensurePnpmProject(cwd, packageJson) {
|
|
2147
2818
|
if (packageJson.packageManager?.startsWith("pnpm@") ||
|
|
2148
2819
|
await exists(join(cwd, "pnpm-lock.yaml")) ||
|
|
@@ -2255,33 +2926,49 @@ async function isLocalLoomBuildStale(sourceRoot, localPackagePath) {
|
|
|
2255
2926
|
if (!outputPackageStat) {
|
|
2256
2927
|
return true;
|
|
2257
2928
|
}
|
|
2929
|
+
// Builds record the content they started from. Compare content rather than
|
|
2930
|
+
// timestamps whenever that stamp exists; older builds lack it.
|
|
2931
|
+
const stamp = await readLoomBuildStamp(localPackagePath);
|
|
2932
|
+
if (stamp) {
|
|
2933
|
+
const fingerprint = await computeLoomSourceFingerprint(sourceRoot);
|
|
2934
|
+
if (!hasLoomBuildProvenance(stamp)) {
|
|
2935
|
+
// Rebuilt once per source fingerprint: a stamp without provenance or
|
|
2936
|
+
// digest is stale until a fresh build of this source shows that the
|
|
2937
|
+
// checkout's build script cannot write them (legacyBuildFingerprint).
|
|
2938
|
+
return stamp.legacyBuildFingerprint !== fingerprint;
|
|
2939
|
+
}
|
|
2940
|
+
// An output edited after the build no longer matches its digest.
|
|
2941
|
+
return stamp.sourceFingerprint !== fingerprint ||
|
|
2942
|
+
stamp.packageDigest !==
|
|
2943
|
+
await computePackageContentDigest(localPackagePath);
|
|
2944
|
+
}
|
|
2258
2945
|
const sourceNewest = await getNewestMtimeMs(sourceRoot);
|
|
2259
2946
|
const outputMtime = outputPackageStat.mtime?.getTime() ?? 0;
|
|
2260
2947
|
return sourceNewest > outputMtime;
|
|
2261
2948
|
}
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2949
|
+
/**
|
|
2950
|
+
* After a build, notes in its stamp when the checkout's build script
|
|
2951
|
+
* predates build provenance (the fresh stamp has none), together with the
|
|
2952
|
+
* source fingerprint that build started from, so sync stops rebuilding that
|
|
2953
|
+
* source on every run. Builds that record provenance are left alone.
|
|
2954
|
+
*/
|
|
2955
|
+
async function markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild) {
|
|
2956
|
+
const stamp = await readLoomBuildStamp(localPackagePath);
|
|
2957
|
+
if (!stamp || hasLoomBuildProvenance(stamp))
|
|
2958
|
+
return;
|
|
2959
|
+
const { version: _version, ...fields } = stamp;
|
|
2960
|
+
await writeFile(join(localPackagePath, LOOM_BUILD_STAMP_FILE), formatLoomBuildStamp({
|
|
2961
|
+
...fields,
|
|
2962
|
+
legacyBuildFingerprint: fingerprintBeforeBuild,
|
|
2963
|
+
}), "utf8");
|
|
2268
2964
|
}
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
join("script", "bin", "loom.js"),
|
|
2277
|
-
join("script", "src", "cli", "mod.js"),
|
|
2278
|
-
];
|
|
2279
|
-
for (const relativePath of sentinelFiles) {
|
|
2280
|
-
if (!await filesHaveSameText(join(localPackagePath, relativePath), join(installedPath, relativePath))) {
|
|
2281
|
-
return true;
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
return false;
|
|
2965
|
+
/**
|
|
2966
|
+
* Describes how the consumer's installed Loom differs from the local build,
|
|
2967
|
+
* by file list and content, or returns null when they match. Version numbers
|
|
2968
|
+
* alone cannot tell rebuilds of the same version apart.
|
|
2969
|
+
*/
|
|
2970
|
+
function findInstalledLocalLoomDifference(cwd, localPackagePath) {
|
|
2971
|
+
return findPackageTreeDifference(localPackagePath, join(cwd, "node_modules", LOOM_DEPENDENCY));
|
|
2285
2972
|
}
|
|
2286
2973
|
async function runCommandOrThrow(commandRunner, command, args, options) {
|
|
2287
2974
|
const result = await commandRunner(command, args, options);
|
|
@@ -2350,6 +3037,10 @@ async function readLocalDevState(cwd) {
|
|
|
2350
3037
|
if (state.version !== 1 || state.dependency !== LOOM_DEPENDENCY) {
|
|
2351
3038
|
return null;
|
|
2352
3039
|
}
|
|
3040
|
+
// Retired: whole-file package.json snapshots are never written back.
|
|
3041
|
+
const retired = state;
|
|
3042
|
+
delete retired.packageJsonBeforeOverride;
|
|
3043
|
+
delete retired.packageJsonWithOverride;
|
|
2353
3044
|
return state;
|
|
2354
3045
|
}
|
|
2355
3046
|
catch {
|
|
@@ -2403,15 +3094,17 @@ function compareParsedVersions(left, right) {
|
|
|
2403
3094
|
}
|
|
2404
3095
|
return left.prerelease.localeCompare(right.prerelease);
|
|
2405
3096
|
}
|
|
2406
|
-
async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec
|
|
3097
|
+
async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec,
|
|
3098
|
+
/** Names the commit in refusals, such as "Loom commit abc, which built X,". */
|
|
3099
|
+
subject) {
|
|
2407
3100
|
const publication = await resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRunner, env, preferredSpec);
|
|
2408
3101
|
switch (publication.status) {
|
|
2409
3102
|
case "published":
|
|
2410
3103
|
return publication;
|
|
2411
3104
|
case "not-on-origin-main":
|
|
2412
|
-
throw new Error(
|
|
3105
|
+
throw new Error(`${subject} is not reachable from origin/main. Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun \`loom dev published\`.`);
|
|
2413
3106
|
case "no-release-tag":
|
|
2414
|
-
throw new Error(
|
|
3107
|
+
throw new Error(`${subject} is on origin/main, but no published Loom version contains that commit or matches its package-relevant files. Publish Loom first, fetch tags, then rerun \`loom dev published\`.`);
|
|
2415
3108
|
}
|
|
2416
3109
|
}
|
|
2417
3110
|
function parseSemverTags(tags) {
|
|
@@ -2481,127 +3174,310 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
|
|
|
2481
3174
|
}
|
|
2482
3175
|
return { status: "no-release-tag" };
|
|
2483
3176
|
}
|
|
2484
|
-
|
|
3177
|
+
async function readPackageJsonIfExists(cwd) {
|
|
3178
|
+
const text = await readTextIfExists(join(cwd, "package.json"));
|
|
3179
|
+
if (text === null)
|
|
3180
|
+
return null;
|
|
3181
|
+
try {
|
|
3182
|
+
return JSON.parse(text);
|
|
3183
|
+
}
|
|
3184
|
+
catch {
|
|
3185
|
+
return null;
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
/** Marks a loaded-package signature that could not be taken. */
|
|
3189
|
+
export const UNKNOWN_PACKAGE_SIGNATURE = "unknown";
|
|
3190
|
+
/**
|
|
3191
|
+
* Signature of the installed Loom package when a command starts, taken when
|
|
3192
|
+
* the project is linked or a dev sync holds the lock (a `loom dev local`
|
|
3193
|
+
* running right now can replace the package). Unlinked projects with no
|
|
3194
|
+
* sync running skip the walk and yield {@link UNKNOWN_PACKAGE_SIGNATURE}, as
|
|
3195
|
+
* does a walk that fails: a project linked after this check is still
|
|
3196
|
+
* treated as refreshed when its sync had to wait for another one. Commands
|
|
3197
|
+
* a sync started return undefined, since they never sync themselves.
|
|
3198
|
+
*/
|
|
3199
|
+
export async function captureLoadedLocalLoomSignature(cwd, env) {
|
|
3200
|
+
if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
|
|
3201
|
+
return undefined;
|
|
3202
|
+
const linked = await detectLocalDevLink(cwd).then((link) => link.active, () => false);
|
|
3203
|
+
if (!linked && !await exists(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH))) {
|
|
3204
|
+
return UNKNOWN_PACKAGE_SIGNATURE;
|
|
3205
|
+
}
|
|
3206
|
+
return await computePackageTreeSignature(join(cwd, "node_modules", LOOM_DEPENDENCY)).catch(() => UNKNOWN_PACKAGE_SIGNATURE);
|
|
3207
|
+
}
|
|
3208
|
+
function formatPnpmOverrideNotAppliedMessage(override, pnpmVersion) {
|
|
3209
|
+
return `pnpm did not apply the Loom local-dev override in ${formatPnpmOverrideLocation(override.location)}: pnpm-lock.yaml does not record ${LOOM_DEPENDENCY}: ${override.spec} under overrides, so this app still resolves the published package. Loom placed it for ${pnpmVersion ? `pnpm ${pnpmVersion}` : "an unknown pnpm version"}: pnpm before 10.5.1 reads overrides only from package.json, pnpm 10.5.1 and later 10.x read pnpm-workspace.yaml overrides only while package.json has none, and pnpm 11 reads only pnpm-workspace.yaml. Make sure package.json packageManager names the pnpm version you run, then rerun \`loom dev sync\`.`;
|
|
3210
|
+
}
|
|
3211
|
+
/** The project's active local Loom link, read from its current files. */
|
|
3212
|
+
async function detectLocalDevLink(cwd) {
|
|
2485
3213
|
const manifest = await readManifestIfExists(cwd);
|
|
2486
3214
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
2487
3215
|
const denoMode = usesDenoTooling(tooling);
|
|
2488
|
-
const
|
|
2489
|
-
const workspaceText = await readTextIfExists(workspacePath);
|
|
2490
|
-
const overrideSpec = getManagedDevOverrideSpec(workspaceText);
|
|
3216
|
+
const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
|
|
2491
3217
|
const denoConfig = denoMode
|
|
2492
3218
|
? await getDenoConfigForLinks(cwd, tooling)
|
|
2493
3219
|
: null;
|
|
2494
3220
|
const denoLink = denoConfig
|
|
2495
3221
|
? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
|
|
2496
3222
|
: null;
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
3223
|
+
return {
|
|
3224
|
+
active: activePnpmOverride !== null || denoLink !== null,
|
|
3225
|
+
activePnpmOverride,
|
|
3226
|
+
denoLink,
|
|
3227
|
+
denoMode,
|
|
3228
|
+
};
|
|
3229
|
+
}
|
|
3230
|
+
const NO_LOCAL_DEV_LINK_MESSAGE = "No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.";
|
|
3231
|
+
export async function syncLocalDevPackage(cwd, options = {}) {
|
|
3232
|
+
const workspacePath = join(cwd, "pnpm-workspace.yaml");
|
|
3233
|
+
const inactive = (notes = []) => ({
|
|
3234
|
+
buildRan: false,
|
|
3235
|
+
changed: false,
|
|
3236
|
+
notes,
|
|
3237
|
+
packageRefreshRan: false,
|
|
3238
|
+
ranCommands: [],
|
|
3239
|
+
});
|
|
3240
|
+
if (!(await detectLocalDevLink(cwd)).active) {
|
|
3241
|
+
if (options.requireActive)
|
|
3242
|
+
throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
|
|
3243
|
+
return inactive();
|
|
2508
3244
|
}
|
|
2509
|
-
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2510
|
-
if (!denoMode)
|
|
2511
|
-
await ensurePnpmProject(cwd, packageJson);
|
|
2512
|
-
const commandRunner = options.commandRunner ?? defaultCommandRunner;
|
|
2513
3245
|
const env = options.env ?? process.env;
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
}
|
|
2532
|
-
await runCommandOrThrow(commandRunner, "deno", ["task", "build"], {
|
|
2533
|
-
cwd: sourceRoot,
|
|
2534
|
-
env: buildEnv,
|
|
2535
|
-
stdio: "inherit",
|
|
2536
|
-
});
|
|
2537
|
-
ranCommands.push("deno task build");
|
|
2538
|
-
buildRan = true;
|
|
2539
|
-
}
|
|
2540
|
-
const packageRefreshNeeded = buildRan ||
|
|
2541
|
-
await isInstalledLocalLoomPackageStale(cwd, localPackagePath);
|
|
2542
|
-
let packageRefreshRan = false;
|
|
2543
|
-
if (options.force || packageRefreshNeeded) {
|
|
2544
|
-
if (denoMode) {
|
|
2545
|
-
await runCommandOrThrow(commandRunner, "deno", ["install"], {
|
|
2546
|
-
cwd,
|
|
2547
|
-
env,
|
|
2548
|
-
stdio: "inherit",
|
|
2549
|
-
});
|
|
2550
|
-
ranCommands.push("deno install");
|
|
3246
|
+
if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1") {
|
|
3247
|
+
// A command started by a running sync (a package lifecycle script, say)
|
|
3248
|
+
// must not wait for the lock its own parent holds.
|
|
3249
|
+
return inactive([
|
|
3250
|
+
"Skipped the local Loom sync inside a running Loom dev sync.",
|
|
3251
|
+
]);
|
|
3252
|
+
}
|
|
3253
|
+
return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), async (lock) => {
|
|
3254
|
+
// Re-read under the lock: while this command waited, the user may have
|
|
3255
|
+
// switched back to the published package or linked another checkout.
|
|
3256
|
+
const { activePnpmOverride, denoLink, denoMode } = await detectLocalDevLink(cwd);
|
|
3257
|
+
if (!activePnpmOverride && !denoLink) {
|
|
3258
|
+
if (options.requireActive)
|
|
3259
|
+
throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
|
|
3260
|
+
return inactive([
|
|
3261
|
+
"The local Loom link was removed while this command waited.",
|
|
3262
|
+
]);
|
|
2551
3263
|
}
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
await
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
3264
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
3265
|
+
if (!denoMode)
|
|
3266
|
+
await ensurePnpmProject(cwd, packageJson);
|
|
3267
|
+
const commandRunner = options.commandRunner ?? defaultCommandRunner;
|
|
3268
|
+
const childEnv = { ...env, [LOOM_DEV_SYNC_ACTIVE_ENV]: "1" };
|
|
3269
|
+
const childStdio = options.commandOutput === "stderr"
|
|
3270
|
+
? "inherit-stderr"
|
|
3271
|
+
: "inherit";
|
|
3272
|
+
const notes = [];
|
|
3273
|
+
let pnpmVersion = null;
|
|
3274
|
+
// Whether this sync already changed the project, for lost-lock errors.
|
|
3275
|
+
let changesMade = false;
|
|
3276
|
+
let pnpmOverride = activePnpmOverride;
|
|
3277
|
+
if (pnpmOverride) {
|
|
3278
|
+
// Older Loom versions always wrote pnpm-workspace.yaml, which pnpm 10
|
|
3279
|
+
// ignores when package.json has overrides; move it where pnpm reads it.
|
|
3280
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
|
|
3281
|
+
if (placement.conflict)
|
|
3282
|
+
throw new Error(placement.conflict);
|
|
3283
|
+
pnpmVersion = placement.pnpmVersion;
|
|
3284
|
+
await lock.assertHeld(false);
|
|
3285
|
+
const movedFiles = await placePnpmLocalDevOverride(cwd, pnpmOverride.spec, placement.location);
|
|
3286
|
+
if (movedFiles.length) {
|
|
3287
|
+
changesMade = true;
|
|
3288
|
+
notes.push(`Moved the Loom local-dev override to ${formatPnpmOverrideLocation(placement.location)} (updated ${movedFiles.join(", ")}).`, ...placement.notes);
|
|
3289
|
+
}
|
|
3290
|
+
pnpmOverride = {
|
|
3291
|
+
location: placement.location,
|
|
3292
|
+
spec: pnpmOverride.spec,
|
|
3293
|
+
};
|
|
2562
3294
|
}
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
3295
|
+
const localPackagePath = denoLink?.path ??
|
|
3296
|
+
fileSpecToPath(cwd, pnpmOverride.spec);
|
|
3297
|
+
const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
|
|
3298
|
+
const configuredSpec = (await resolveLoomDependencySpec(cwd, packageJson, { includeDev: true })).effective;
|
|
3299
|
+
const desiredLocalVersion = await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
|
|
3300
|
+
await readPackageVersion(localPackagePath);
|
|
3301
|
+
const currentLocalVersion = await readPackageVersion(localPackagePath);
|
|
3302
|
+
const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
|
|
3303
|
+
? { ...childEnv, NPM_PACKAGE_VERSION: desiredLocalVersion }
|
|
3304
|
+
: childEnv;
|
|
3305
|
+
const ranCommands = [];
|
|
3306
|
+
let buildRan = false;
|
|
3307
|
+
if (options.force ||
|
|
3308
|
+
denoMode && currentLocalVersion !== desiredLocalVersion ||
|
|
3309
|
+
await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
|
|
3310
|
+
if (!sourceRoot) {
|
|
3311
|
+
throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
|
|
3312
|
+
}
|
|
3313
|
+
// Run in the Loom checkout with its own deno.json (and so its own
|
|
3314
|
+
// deno.lock). Deno discovers config and lockfile from the working
|
|
3315
|
+
// directory, so a build resolved from the consumer would write a
|
|
3316
|
+
// deno.lock listing the consumer's package.json into its root.
|
|
3317
|
+
await lock.assertHeld(changesMade);
|
|
3318
|
+
const fingerprintBeforeBuild = await computeLoomSourceFingerprint(sourceRoot);
|
|
3319
|
+
await runCommandOrThrow(commandRunner, "deno", ["task", "--config", join(sourceRoot, "deno.json"), "build"], { cwd: sourceRoot, env: buildEnv, stdio: childStdio });
|
|
3320
|
+
ranCommands.push("deno task build");
|
|
3321
|
+
buildRan = true;
|
|
3322
|
+
changesMade = true;
|
|
3323
|
+
await markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild);
|
|
3324
|
+
}
|
|
3325
|
+
const lockfilePath = join(cwd, "pnpm-lock.yaml");
|
|
3326
|
+
const lockfileBefore = pnpmOverride
|
|
3327
|
+
? await readTextIfExists(lockfilePath)
|
|
3328
|
+
: null;
|
|
3329
|
+
// A lockfile that does not record the override means pnpm has not linked
|
|
3330
|
+
// the local package yet (for example right after `loom dev local`).
|
|
3331
|
+
const overridePending = pnpmOverride !== null &&
|
|
3332
|
+
lockfileBefore !== null &&
|
|
3333
|
+
!lockfileAppliesLocalDevOverride(lockfileBefore, pnpmOverride.spec);
|
|
3334
|
+
const importerBefore = overridePending
|
|
3335
|
+
? getLockfileRootImporterDependency(lockfileBefore, LOOM_DEPENDENCY)
|
|
3336
|
+
: null;
|
|
3337
|
+
if (importerBefore?.version && isLocalPackageSpec(importerBefore.version) &&
|
|
3338
|
+
!isLocalPackageSpec(importerBefore.specifier ?? "")) {
|
|
3339
|
+
// Earlier Loom versions linked with `pnpm update --no-save`, which also
|
|
3340
|
+
// re-resolved Loom's dependencies; this sync cannot tell which of those
|
|
3341
|
+
// lockfile changes were intended.
|
|
3342
|
+
notes.push("pnpm-lock.yaml was linked by an earlier Loom through `pnpm update --no-save`, which can also update Loom's own dependencies and add duplicate peer variants. If pnpm-lock.yaml has no other intended changes, restore it from git and rerun `loom dev sync`.");
|
|
3343
|
+
}
|
|
3344
|
+
const packageRefreshNeeded = buildRan || overridePending ||
|
|
3345
|
+
await findInstalledLocalLoomDifference(cwd, localPackagePath) !== null;
|
|
3346
|
+
let packageRefreshRan = false;
|
|
3347
|
+
const warnings = [];
|
|
3348
|
+
if (options.force || packageRefreshNeeded) {
|
|
3349
|
+
await lock.assertHeld(changesMade);
|
|
3350
|
+
if (denoMode) {
|
|
3351
|
+
await runCommandOrThrow(commandRunner, "deno", ["install"], {
|
|
3352
|
+
cwd,
|
|
3353
|
+
env: childEnv,
|
|
3354
|
+
stdio: childStdio,
|
|
3355
|
+
});
|
|
3356
|
+
ranCommands.push("deno install");
|
|
2576
3357
|
}
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
3358
|
+
else {
|
|
3359
|
+
// A plain install applies the override and re-imports the local
|
|
3360
|
+
// directory package while reusing every other locked version.
|
|
3361
|
+
// `pnpm update` would re-resolve Loom's dependency subtree instead.
|
|
3362
|
+
await runCommandOrThrow(commandRunner, "pnpm", ["install", "--no-frozen-lockfile"], { cwd, env: childEnv, stdio: childStdio });
|
|
3363
|
+
ranCommands.push("pnpm install --no-frozen-lockfile");
|
|
3364
|
+
const lockfileAfter = await readTextIfExists(lockfilePath);
|
|
3365
|
+
if (lockfileAfter !== null &&
|
|
3366
|
+
!lockfileAppliesLocalDevOverride(lockfileAfter, pnpmOverride.spec)) {
|
|
3367
|
+
throw new Error(formatPnpmOverrideNotAppliedMessage(pnpmOverride, pnpmVersion));
|
|
3368
|
+
}
|
|
3369
|
+
if (lockfileBefore !== null && lockfileAfter !== null) {
|
|
3370
|
+
const duplicates = findNewPeerVariantDuplicates(lockfileBefore, lockfileAfter);
|
|
3371
|
+
if (duplicates.length) {
|
|
3372
|
+
warnings.push(`pnpm-lock.yaml gained duplicate peer variants: ${duplicates.map((duplicate) => `${duplicate.packageVersion} (${duplicate.before} -> ${duplicate.after})`).join(", ")}. Peer variants of one version load as separate module copies, which can break type checks and shared state; inspect them with \`pnpm why <package>\`.`);
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
const remainingDifference = await findInstalledLocalLoomDifference(cwd, localPackagePath);
|
|
3376
|
+
if (remainingDifference) {
|
|
3377
|
+
warnings.push(`node_modules/${LOOM_DEPENDENCY} still differs from ${localPackagePath} after pnpm install (${remainingDifference}).`);
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
3380
|
+
packageRefreshRan = true;
|
|
3381
|
+
}
|
|
3382
|
+
await lock.assertHeld(changesMade || packageRefreshRan);
|
|
3383
|
+
const currentWorkspaceText = await readTextIfExists(workspacePath);
|
|
3384
|
+
const currentState = denoMode
|
|
3385
|
+
? await readLocalDevState(cwd)
|
|
3386
|
+
: await getCurrentLocalDevState(cwd, currentWorkspaceText);
|
|
3387
|
+
let state = null;
|
|
3388
|
+
if (buildRan || packageRefreshRan || !currentState) {
|
|
3389
|
+
state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
|
|
3390
|
+
// Keep which package.json maps Loom created across syncs.
|
|
3391
|
+
const previous = await readLocalDevState(cwd);
|
|
3392
|
+
if (previous?.createdPackageJsonMaps !== undefined) {
|
|
3393
|
+
state.createdPackageJsonMaps = previous.createdPackageJsonMaps;
|
|
3394
|
+
}
|
|
3395
|
+
if (pnpmOverride?.location === "pnpm-workspace.yaml") {
|
|
3396
|
+
const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), pnpmOverride.spec, state);
|
|
3397
|
+
if (stateUpdate.changed) {
|
|
3398
|
+
await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
}
|
|
3402
|
+
if (state ?? currentState) {
|
|
3403
|
+
await writeLocalDevStateIfChanged(cwd, state ?? currentState);
|
|
3404
|
+
}
|
|
3405
|
+
// Another process may have replaced the package this process loaded,
|
|
3406
|
+
// while it waited for the lock or just before it took it; its
|
|
3407
|
+
// in-process Loom code is then stale.
|
|
3408
|
+
let refreshedElsewhere = false;
|
|
3409
|
+
if (!buildRan && !packageRefreshRan &&
|
|
3410
|
+
options.loadedPackageSignature !== undefined) {
|
|
3411
|
+
const current = options.loadedPackageSignature ===
|
|
3412
|
+
UNKNOWN_PACKAGE_SIGNATURE
|
|
3413
|
+
? UNKNOWN_PACKAGE_SIGNATURE
|
|
3414
|
+
: await computePackageTreeSignature(join(cwd, "node_modules", LOOM_DEPENDENCY)).catch(() => UNKNOWN_PACKAGE_SIGNATURE);
|
|
3415
|
+
// Without both signatures, only a sync this one waited for is
|
|
3416
|
+
// evidence of a replacement; assume one then rather than run code
|
|
3417
|
+
// that may be stale.
|
|
3418
|
+
refreshedElsewhere = current === UNKNOWN_PACKAGE_SIGNATURE
|
|
3419
|
+
? lock.waited
|
|
3420
|
+
: current !== options.loadedPackageSignature;
|
|
3421
|
+
}
|
|
3422
|
+
notes.push(packageRefreshRan
|
|
3423
|
+
? `Local Loom package refreshed from ${localPackagePath}.`
|
|
3424
|
+
: refreshedElsewhere
|
|
3425
|
+
? `Another Loom command refreshed the local Loom package from ${localPackagePath} after this one started.`
|
|
3426
|
+
: `Local Loom package is already fresh: ${localPackagePath}`, ...warnings.map((warning) => `Warning: ${warning}`));
|
|
3427
|
+
const recordedState = state ?? currentState;
|
|
3428
|
+
if (recordedState?.sourceCommit) {
|
|
3429
|
+
notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
|
|
3430
|
+
}
|
|
3431
|
+
// What `loom dev published` will check is the build's own stamp.
|
|
3432
|
+
const stamp = sourceRoot
|
|
3433
|
+
? await readLoomBuildStamp(localPackagePath)
|
|
3434
|
+
: null;
|
|
3435
|
+
if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
|
|
3436
|
+
notes.push(`The local Loom build in ${localPackagePath} comes from a Loom checkout whose build script predates build provenance, so \`loom dev published\` will refuse it; relink to a newer Loom checkout before switching back.`);
|
|
3437
|
+
}
|
|
3438
|
+
else if (sourceRoot && (!stamp || !hasLoomBuildProvenance(stamp))) {
|
|
3439
|
+
notes.push(`The local Loom build in ${localPackagePath} does not record which commit it was built from, so \`loom dev published\` will refuse it; rebuild it with \`loom dev sync --force\`.`);
|
|
3440
|
+
}
|
|
3441
|
+
else if (stamp && !stamp.sourceCommit) {
|
|
3442
|
+
notes.push(`The local Loom build in ${localPackagePath} was made where git could not read the Loom commit, so \`loom dev published\` will refuse it; rebuild it from a git checkout of Loom with \`loom dev sync --force\`.`);
|
|
3443
|
+
}
|
|
3444
|
+
else if (stamp && stamp.sourceDirty !== false) {
|
|
3445
|
+
notes.push(`The local Loom build in ${localPackagePath} was made from uncommitted Loom changes, so \`loom dev published\` will refuse it until you commit them and rebuild with \`loom dev sync --force\`.`);
|
|
3446
|
+
}
|
|
3447
|
+
return {
|
|
3448
|
+
buildRan,
|
|
3449
|
+
changed: buildRan || packageRefreshRan || refreshedElsewhere,
|
|
3450
|
+
localPackagePath,
|
|
3451
|
+
notes,
|
|
3452
|
+
packageRefreshRan,
|
|
3453
|
+
ranCommands,
|
|
3454
|
+
};
|
|
3455
|
+
}, localDevLockOptions(options));
|
|
3456
|
+
}
|
|
3457
|
+
function localDevLockOptions(options) {
|
|
2595
3458
|
return {
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
packageRefreshRan,
|
|
2601
|
-
ranCommands,
|
|
3459
|
+
...options.lock,
|
|
3460
|
+
onWait: (holder) => options.onLockWait?.(`Waiting for another Loom dev sync (${holder
|
|
3461
|
+
? `process ${holder.pid} on ${holder.hostname}`
|
|
3462
|
+
: "unknown process"}) to finish.`),
|
|
2602
3463
|
};
|
|
2603
3464
|
}
|
|
2604
|
-
|
|
3465
|
+
/**
|
|
3466
|
+
* Runs a local-dev config change under the project's sync lock, so it never
|
|
3467
|
+
* interleaves with a sync that reads and rewrites the same files. Commands a
|
|
3468
|
+
* sync started (LOOM_DEV_SYNC_ACTIVE) run without it to avoid waiting on
|
|
3469
|
+
* their own parent.
|
|
3470
|
+
*/
|
|
3471
|
+
async function withProjectLocalDevLock(cwd, options, run) {
|
|
3472
|
+
const env = options.env ?? process.env;
|
|
3473
|
+
if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
|
|
3474
|
+
return await run();
|
|
3475
|
+
return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), run, localDevLockOptions(options));
|
|
3476
|
+
}
|
|
3477
|
+
export async function useLocalDevPackage(cwd, inputPath, options = {}) {
|
|
3478
|
+
return await withProjectLocalDevLock(cwd, options, () => useLocalDevPackageLocked(cwd, inputPath, options));
|
|
3479
|
+
}
|
|
3480
|
+
async function useLocalDevPackageLocked(cwd, inputPath, options) {
|
|
2605
3481
|
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2606
3482
|
const manifest = await readManifestIfExists(cwd);
|
|
2607
3483
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -2614,8 +3490,23 @@ export async function useLocalDevPackage(cwd, inputPath) {
|
|
|
2614
3490
|
const denoConfig = await getDenoConfigForLinks(cwd, tooling);
|
|
2615
3491
|
const relativeLocalPackagePath = relative(cwd, localPackagePath)
|
|
2616
3492
|
.replaceAll("\\", "/");
|
|
3493
|
+
// A relink replaces the previous Loom link, found by its package name or,
|
|
3494
|
+
// when that package is gone, by the path dev state recorded for it.
|
|
3495
|
+
// Otherwise both stay linked and `loom dev published` removes only one.
|
|
3496
|
+
const recorded = await readLocalDevState(cwd);
|
|
3497
|
+
const previousLinks = [];
|
|
3498
|
+
for (const link of await readDenoLinks(cwd, denoConfig)) {
|
|
3499
|
+
if (link === relativeLocalPackagePath)
|
|
3500
|
+
continue;
|
|
3501
|
+
if (await findLocalLoomDenoLink(cwd, [link]) ||
|
|
3502
|
+
(recorded &&
|
|
3503
|
+
resolve(cwd, link) === resolve(cwd, recorded.localPackagePath))) {
|
|
3504
|
+
previousLinks.push(link);
|
|
3505
|
+
}
|
|
3506
|
+
}
|
|
2617
3507
|
const update = await mutateDenoLinks(cwd, denoConfig, {
|
|
2618
3508
|
add: relativeLocalPackagePath,
|
|
3509
|
+
remove: previousLinks,
|
|
2619
3510
|
});
|
|
2620
3511
|
const state = {
|
|
2621
3512
|
dependency: LOOM_DEPENDENCY,
|
|
@@ -2639,26 +3530,218 @@ export async function useLocalDevPackage(cwd, inputPath) {
|
|
|
2639
3530
|
}
|
|
2640
3531
|
await ensurePnpmProject(cwd, packageJson);
|
|
2641
3532
|
const overrideSpec = `file:${localPackagePath}`;
|
|
2642
|
-
const
|
|
2643
|
-
const
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
}
|
|
3533
|
+
const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
3534
|
+
const restoreSpec = loomDependency.catalogName
|
|
3535
|
+
? `${loomDependency.effective ?? publishedSpec} (from the pnpm-workspace.yaml catalog)`
|
|
3536
|
+
: publishedSpec;
|
|
3537
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, options.commandRunner ?? defaultCommandRunner, options.env ?? process.env);
|
|
3538
|
+
if (placement.conflict) {
|
|
3539
|
+
throw new Error(placement.conflict);
|
|
3540
|
+
}
|
|
3541
|
+
const changedFiles = await placePnpmLocalDevOverride(cwd, overrideSpec, placement.location);
|
|
2652
3542
|
return {
|
|
2653
3543
|
changedFiles,
|
|
2654
3544
|
notes: [
|
|
2655
|
-
`Local Loom dev override is active: ${overrideSpec}`,
|
|
3545
|
+
`Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
|
|
3546
|
+
...placement.notes,
|
|
2656
3547
|
"Run `loom dev sync` to rebuild the local Loom package and refresh this project's pnpm install when needed.",
|
|
2657
|
-
`Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm
|
|
3548
|
+
`Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm install\` to restore ${LOOM_DEPENDENCY}@${restoreSpec}.`,
|
|
2658
3549
|
],
|
|
2659
3550
|
};
|
|
2660
3551
|
}
|
|
3552
|
+
/** Turns a `file:` or `link:` spec into the absolute directory it names. */
|
|
3553
|
+
function localSpecToPath(cwd, spec) {
|
|
3554
|
+
const value = spec.replace(/^(?:file|link):/, "");
|
|
3555
|
+
if (value.startsWith("//"))
|
|
3556
|
+
return new URL(`file:${value}`).pathname;
|
|
3557
|
+
return resolve(cwd, value);
|
|
3558
|
+
}
|
|
3559
|
+
/** The local spec pnpm-lock.yaml resolves Loom to, if it is local. */
|
|
3560
|
+
function getLockfileLocalLoomSpec(lockfileText) {
|
|
3561
|
+
if (!lockfileText)
|
|
3562
|
+
return null;
|
|
3563
|
+
const version = getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)?.version?.replace(/\(.+$/, "");
|
|
3564
|
+
if (version !== undefined) {
|
|
3565
|
+
return isLocalPackageSpec(version) ? version : null;
|
|
3566
|
+
}
|
|
3567
|
+
return getLocalLoomLockfileResolution(lockfileText);
|
|
3568
|
+
}
|
|
3569
|
+
/**
|
|
3570
|
+
* The published Loom version pnpm has installed, when nothing local is
|
|
3571
|
+
* provably installed:
|
|
3572
|
+
* - pnpm-lock.yaml and pnpm's record of node_modules
|
|
3573
|
+
* (`node_modules/.pnpm/lock.yaml`) resolve Loom to the same registry
|
|
3574
|
+
* version, and the installed package has that version;
|
|
3575
|
+
* - `node_modules/@gadicc/loom` resolves into pnpm's virtual store entry for
|
|
3576
|
+
* that registry version, not a `file+`/`link+` entry. pnpm re-points it
|
|
3577
|
+
* before it writes either lockfile, so an interrupted install of a local
|
|
3578
|
+
* build (which carries the registry version) fails this check;
|
|
3579
|
+
* - when `localBuild` exists, the installed copy differs from it.
|
|
3580
|
+
* Null whenever any of that is uncertain, for example with
|
|
3581
|
+
* `node-linker=hoisted`, `enableGlobalVirtualStore` or a custom
|
|
3582
|
+
* `virtual-store-dir`, where no `node_modules/.pnpm` entry tells them apart.
|
|
3583
|
+
*/
|
|
3584
|
+
async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
|
|
3585
|
+
const resolvedVersion = (text) => text
|
|
3586
|
+
? getLockfileRootImporterDependency(text, LOOM_DEPENDENCY)?.version
|
|
3587
|
+
?.replace(/\(.+$/, "") ?? null
|
|
3588
|
+
: null;
|
|
3589
|
+
const version = resolvedVersion(lockfileText);
|
|
3590
|
+
if (!version || isLocalPackageSpec(version))
|
|
3591
|
+
return null;
|
|
3592
|
+
const installedLockfile = await readTextIfExists(join(cwd, "node_modules", ".pnpm", "lock.yaml"));
|
|
3593
|
+
if (resolvedVersion(installedLockfile) !== version)
|
|
3594
|
+
return null;
|
|
3595
|
+
const installedPath = join(cwd, "node_modules", LOOM_DEPENDENCY);
|
|
3596
|
+
if (await readPackageVersion(installedPath) !== version)
|
|
3597
|
+
return null;
|
|
3598
|
+
const [store, installed] = await Promise.all([
|
|
3599
|
+
realpath(join(cwd, "node_modules", ".pnpm")).catch(() => null),
|
|
3600
|
+
realpath(installedPath).catch(() => null),
|
|
3601
|
+
]);
|
|
3602
|
+
if (!store || !installed)
|
|
3603
|
+
return null;
|
|
3604
|
+
const entry = relative(store, installed).split(sep)[0];
|
|
3605
|
+
const registryEntry = `@gadicc+loom@${version}`;
|
|
3606
|
+
if (!(entry === registryEntry || entry.startsWith(`${registryEntry}_`) ||
|
|
3607
|
+
entry.startsWith(`${registryEntry}(`))) {
|
|
3608
|
+
return null;
|
|
3609
|
+
}
|
|
3610
|
+
if (await exists(join(localBuild, "package.json")) &&
|
|
3611
|
+
await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
|
|
3612
|
+
return null;
|
|
3613
|
+
}
|
|
3614
|
+
return version;
|
|
3615
|
+
}
|
|
3616
|
+
/**
|
|
3617
|
+
* Lists every local Loom package the project points at, merging entries for
|
|
3618
|
+
* the same directory. For pnpm these are the managed overrides and the
|
|
3619
|
+
* lockfile's local resolution; for Deno, each link whose package is Loom,
|
|
3620
|
+
* or whose path dev state recorded for Loom when that package is gone.
|
|
3621
|
+
* Dev state only identifies such a link; it never proves anything.
|
|
3622
|
+
*/
|
|
3623
|
+
async function collectLocalLoomTargets(cwd, project) {
|
|
3624
|
+
const targets = new Map();
|
|
3625
|
+
const add = async (path, source) => {
|
|
3626
|
+
const key = await realpath(path).catch(() => path);
|
|
3627
|
+
const target = targets.get(key) ?? { path: key, sources: [] };
|
|
3628
|
+
target.sources.push(source);
|
|
3629
|
+
targets.set(key, target);
|
|
3630
|
+
};
|
|
3631
|
+
const denoLinks = [];
|
|
3632
|
+
if (project.denoConfig) {
|
|
3633
|
+
const recorded = await readLocalDevState(cwd);
|
|
3634
|
+
const recordedPath = recorded?.localPackagePath
|
|
3635
|
+
? resolve(cwd, recorded.localPackagePath)
|
|
3636
|
+
: null;
|
|
3637
|
+
for (const link of await readDenoLinks(cwd, project.denoConfig)) {
|
|
3638
|
+
const path = resolve(cwd, link);
|
|
3639
|
+
if (await findLocalLoomDenoLink(cwd, [link]) || path === recordedPath) {
|
|
3640
|
+
denoLinks.push(link);
|
|
3641
|
+
await add(path, `${project.denoConfig} links ${link}`);
|
|
3642
|
+
}
|
|
3643
|
+
}
|
|
3644
|
+
return { denoLinks, targets: [...targets.values()] };
|
|
3645
|
+
}
|
|
3646
|
+
const workspaceSpec = getManagedDevOverrideSpec(project.workspaceText);
|
|
3647
|
+
if (workspaceSpec && isManagedPackageJsonLoomOverride(workspaceSpec)) {
|
|
3648
|
+
await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
|
|
3649
|
+
}
|
|
3650
|
+
for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
|
|
3651
|
+
await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
|
|
3652
|
+
}
|
|
3653
|
+
for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
|
|
3654
|
+
await add(localSpecToPath(cwd, spec), `the ${formatPnpmOverrideLocation(location)} override`);
|
|
3655
|
+
}
|
|
3656
|
+
const lockfileSpec = getLockfileLocalLoomSpec(project.lockfileText);
|
|
3657
|
+
if (lockfileSpec?.startsWith("workspace:")) {
|
|
3658
|
+
throw new Error(`pnpm-lock.yaml resolves ${LOOM_DEPENDENCY} to ${lockfileSpec}, a workspace package Loom cannot trace to a build, so it cannot prove that the installed Loom is published. Install a published ${LOOM_DEPENDENCY} instead.`);
|
|
3659
|
+
}
|
|
3660
|
+
if (lockfileSpec) {
|
|
3661
|
+
await add(localSpecToPath(cwd, lockfileSpec), "pnpm-lock.yaml");
|
|
3662
|
+
}
|
|
3663
|
+
return { denoLinks, targets: [...targets.values()] };
|
|
3664
|
+
}
|
|
3665
|
+
/**
|
|
3666
|
+
* Proves that the local Loom build this project has installed is published,
|
|
3667
|
+
* from that build's own stamp: the build must record a clean source commit,
|
|
3668
|
+
* the installed copy must match it (and, for pnpm, the lockfile must resolve
|
|
3669
|
+
* to it), and the commit must be covered by a release. Dev state and the
|
|
3670
|
+
* checkout's current git state are never consulted. Throws a refusal that
|
|
3671
|
+
* says what to do otherwise.
|
|
3672
|
+
*/
|
|
3673
|
+
async function proveLocalLoomBuildPublished(cwd, target, options) {
|
|
3674
|
+
const { path } = target;
|
|
3675
|
+
const rerun = "then rerun `loom dev published`";
|
|
3676
|
+
if (!await exists(join(path, "package.json"))) {
|
|
3677
|
+
const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
|
|
3678
|
+
throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
|
|
3679
|
+
? "If the app does not need that build, restore pnpm-lock.yaml from git and run `pnpm install`; otherwise restore that Loom checkout, link it with `loom dev local` and run `loom dev sync`"
|
|
3680
|
+
: "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
|
|
3681
|
+
}
|
|
3682
|
+
const stamp = await readLoomBuildStamp(path);
|
|
3683
|
+
if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
|
|
3684
|
+
throw new Error(`The Loom build in ${path} comes from a Loom checkout whose build script predates build provenance, so \`loom dev published\` cannot prove that it is published. Relink to a newer Loom checkout with \`loom dev local\` and run \`loom dev sync\`, or confirm by other means that it is equivalent to a published Loom release and remove the override yourself.`);
|
|
3685
|
+
}
|
|
3686
|
+
if (!stamp || !hasLoomBuildProvenance(stamp)) {
|
|
3687
|
+
throw new Error(`The Loom build in ${path} does not record which commit it was built from (it has no build stamp, or one from before builds recorded it). Run \`loom dev sync\` to rebuild and install it, ${rerun}.`);
|
|
3688
|
+
}
|
|
3689
|
+
if (stamp.packageDigest !== await computePackageContentDigest(path)) {
|
|
3690
|
+
throw new Error(`${path} was modified after it was built. Run \`loom dev sync --force\`, ${rerun}.`);
|
|
3691
|
+
}
|
|
3692
|
+
if (!stamp.sourceCommit) {
|
|
3693
|
+
throw new Error(`The Loom build in ${path} was made where git could not read the Loom commit. Rebuild it from a git checkout of Loom with \`loom dev sync --force\`, ${rerun}.`);
|
|
3694
|
+
}
|
|
3695
|
+
const shortCommit = stamp.sourceCommit.slice(0, 12);
|
|
3696
|
+
if (stamp.sourceDirty !== false) {
|
|
3697
|
+
throw new Error(stamp.sourceDirty
|
|
3698
|
+
? `The Loom build in ${path} was made from commit ${shortCommit} with uncommitted changes. Commit your Loom changes and rebuild with \`loom dev sync --force\`, publish Loom if needed, ${rerun}.`
|
|
3699
|
+
: `The Loom build in ${path} was made from commit ${shortCommit}, but git could not tell whether that checkout had uncommitted changes. Rebuild it with \`loom dev sync --force\`, ${rerun}.`);
|
|
3700
|
+
}
|
|
3701
|
+
// Deno loads a node_modules copy whenever its effective nodeModulesDir is
|
|
3702
|
+
// auto or manual, and manual is its default next to a package.json. So any
|
|
3703
|
+
// copy is compared unless the config says "none", where Deno loads the
|
|
3704
|
+
// linked directory itself.
|
|
3705
|
+
const nodeModulesDir = options.denoConfig
|
|
3706
|
+
? parseJsonc(await readTextIfExists(join(cwd, options.denoConfig)) ?? "{}", options.denoConfig).nodeModulesDir
|
|
3707
|
+
: undefined;
|
|
3708
|
+
const installedCopy = !options.denoConfig ||
|
|
3709
|
+
(nodeModulesDir !== "none" &&
|
|
3710
|
+
await exists(join(cwd, "node_modules", LOOM_DEPENDENCY, "package.json")));
|
|
3711
|
+
const difference = installedCopy
|
|
3712
|
+
? await findInstalledLocalLoomDifference(cwd, path)
|
|
3713
|
+
: null;
|
|
3714
|
+
if (difference) {
|
|
3715
|
+
throw new Error(`The installed Loom differs from ${path} (${difference}). Run \`loom dev sync\`, ${rerun}.`);
|
|
3716
|
+
}
|
|
3717
|
+
if (!options.denoConfig) {
|
|
3718
|
+
const lockfileSpec = getLockfileLocalLoomSpec(options.lockfileText);
|
|
3719
|
+
if (!lockfileSpec) {
|
|
3720
|
+
throw new Error(`pnpm-lock.yaml does not resolve ${LOOM_DEPENDENCY} to ${path}. Run \`loom dev sync\`, ${rerun}.`);
|
|
3721
|
+
}
|
|
3722
|
+
}
|
|
3723
|
+
const sourceRoot = await resolveLocalLoomSourceRoot(path);
|
|
3724
|
+
if (!sourceRoot) {
|
|
3725
|
+
throw new Error(`${path} is not inside a Loom source checkout, so Loom cannot check its build commit ${shortCommit} against Loom releases. Link the npm output of a Loom git checkout with \`loom dev local\` and run \`loom dev sync\`, ${rerun}.`);
|
|
3726
|
+
}
|
|
3727
|
+
const publication = await findPublishedLoomPublicationForCommit(sourceRoot, stamp.sourceCommit, options.commandRunner, options.env, options.preferredSpec, `Loom commit ${shortCommit}, which built ${path},`);
|
|
3728
|
+
return {
|
|
3729
|
+
note: publication.reason === "contains-commit"
|
|
3730
|
+
? `The Loom build in ${path} comes from commit ${shortCommit}, which is included in published ${LOOM_DEPENDENCY}@${publication.version}.`
|
|
3731
|
+
: `The Loom build in ${path} comes from commit ${shortCommit}, which has no package-relevant changes after ${publication.tag}, so published ${LOOM_DEPENDENCY}@${publication.version} covers it.`,
|
|
3732
|
+
publication,
|
|
3733
|
+
};
|
|
3734
|
+
}
|
|
2661
3735
|
export async function usePublishedDevPackage(cwd, options = {}) {
|
|
3736
|
+
// A project that was never linked has nothing a sync could be changing,
|
|
3737
|
+
// so it does not need the lock (or a new `.loom/` directory).
|
|
3738
|
+
if (!(await detectLocalDevLink(cwd)).active &&
|
|
3739
|
+
!await exists(join(cwd, ".loom"))) {
|
|
3740
|
+
return await usePublishedDevPackageLocked(cwd, options);
|
|
3741
|
+
}
|
|
3742
|
+
return await withProjectLocalDevLock(cwd, options, () => usePublishedDevPackageLocked(cwd, options));
|
|
3743
|
+
}
|
|
3744
|
+
async function usePublishedDevPackageLocked(cwd, options) {
|
|
2662
3745
|
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2663
3746
|
const manifest = await readManifestIfExists(cwd);
|
|
2664
3747
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -2672,75 +3755,227 @@ export async function usePublishedDevPackage(cwd, options = {}) {
|
|
|
2672
3755
|
const denoConfig = denoMode
|
|
2673
3756
|
? await getDenoConfigForLinks(cwd, tooling)
|
|
2674
3757
|
: null;
|
|
2675
|
-
const
|
|
2676
|
-
? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
|
|
2677
|
-
: null;
|
|
2678
|
-
const activeOverrideSpec = denoLink?.link ??
|
|
2679
|
-
getManagedDevOverrideSpec(workspaceText);
|
|
2680
|
-
const localLockfileResolution = denoMode
|
|
3758
|
+
const lockfileText = denoMode
|
|
2681
3759
|
? null
|
|
2682
|
-
: await
|
|
2683
|
-
const
|
|
2684
|
-
?
|
|
2685
|
-
:
|
|
3760
|
+
: await readTextIfExists(join(cwd, "pnpm-lock.yaml"));
|
|
3761
|
+
const localLockfileResolution = lockfileText
|
|
3762
|
+
? getLocalLoomLockfileResolution(lockfileText)
|
|
3763
|
+
: null;
|
|
2686
3764
|
const notes = [];
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
3765
|
+
const { denoLinks, targets } = await collectLocalLoomTargets(cwd, {
|
|
3766
|
+
denoConfig,
|
|
3767
|
+
lockfileText,
|
|
3768
|
+
packageJson,
|
|
3769
|
+
workspaceText,
|
|
3770
|
+
});
|
|
3771
|
+
if (targets.length > 1) {
|
|
3772
|
+
throw new Error(`This project points at more than one local Loom package:\n${targets.map((target) => `- ${target.path} (${target.sources.join(", ")})`).join("\n")}\nKeep one: link it with \`loom dev local <path>\` and run \`loom dev sync\`, then rerun \`loom dev published\`.`);
|
|
3773
|
+
}
|
|
3774
|
+
// A `catalog:` reference keeps its version in pnpm-workspace.yaml, which is
|
|
3775
|
+
// where the published version has to go too.
|
|
3776
|
+
const catalogDependency = denoMode
|
|
3777
|
+
? null
|
|
3778
|
+
: await resolveLoomDependencySpec(cwd, packageJson);
|
|
3779
|
+
const catalog = catalogDependency?.catalogName ? catalogDependency : null;
|
|
3780
|
+
let publishedSpec = catalog
|
|
3781
|
+
? catalog.effective && !isLocalPackageSpec(catalog.effective)
|
|
3782
|
+
? catalog.effective
|
|
3783
|
+
: DEFAULT_LOOM_RANGE
|
|
3784
|
+
: getPublishedLoomDependencySpec(packageJson);
|
|
3785
|
+
// A pnpm link that was never installed left nothing local to prove: the
|
|
3786
|
+
// app still runs the published Loom it had. Deno reads a link directly or
|
|
3787
|
+
// copies it into node_modules on its next install or run, so Deno links
|
|
3788
|
+
// are always proved.
|
|
3789
|
+
const registryVersion = denoMode || targets.length !== 1
|
|
3790
|
+
? null
|
|
3791
|
+
: await findInstalledRegistryLoomVersion(cwd, lockfileText, targets[0].path);
|
|
3792
|
+
if (registryVersion) {
|
|
3793
|
+
notes.push(`No local Loom build was installed (pnpm-lock.yaml and node_modules hold published ${LOOM_DEPENDENCY}@${registryVersion}), so the pin stays at ${publishedSpec}.`);
|
|
3794
|
+
}
|
|
3795
|
+
else if (targets.length === 1) {
|
|
3796
|
+
const proof = await proveLocalLoomBuildPublished(cwd, targets[0], {
|
|
3797
|
+
commandRunner,
|
|
3798
|
+
denoConfig,
|
|
3799
|
+
env,
|
|
3800
|
+
lockfileText,
|
|
3801
|
+
preferredSpec: publishedSpec,
|
|
3802
|
+
});
|
|
3803
|
+
publishedSpec = proof.publication.version;
|
|
3804
|
+
notes.push(proof.note);
|
|
3805
|
+
}
|
|
3806
|
+
const changedFiles = [];
|
|
3807
|
+
let catalogChanged = false;
|
|
3808
|
+
if (catalog) {
|
|
3809
|
+
const currentText = await readTextIfExists(workspacePath);
|
|
3810
|
+
const entry = findLoomCatalogEntry(currentText, catalog.catalogName);
|
|
3811
|
+
const unreadable = entry
|
|
3812
|
+
? null
|
|
3813
|
+
: findUnreadableLoomCatalog(currentText, catalog.catalogName);
|
|
3814
|
+
if (unreadable) {
|
|
3815
|
+
notes.push(`pnpm-workspace.yaml writes the \`${unreadable}\` catalog as a multi-line or nested flow map, which Loom cannot edit; set ${LOOM_DEPENDENCY} to ${publishedSpec} there yourself.`);
|
|
2695
3816
|
}
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
if (publication.reason === "contains-commit") {
|
|
2699
|
-
notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} is included in published ${LOOM_DEPENDENCY}@${publication.version}.`);
|
|
3817
|
+
else if (!entry) {
|
|
3818
|
+
notes.push(`package.json uses \`${catalog.raw}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog; add \`${LOOM_DEPENDENCY}: ${publishedSpec}\` there.`);
|
|
2700
3819
|
}
|
|
2701
|
-
else {
|
|
2702
|
-
|
|
3820
|
+
else if (entry.spec !== publishedSpec) {
|
|
3821
|
+
const updated = setLoomCatalogEntryText(currentText, entry, publishedSpec);
|
|
3822
|
+
if (updated !== null) {
|
|
3823
|
+
await writeFile(workspacePath, updated, "utf8");
|
|
3824
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
3825
|
+
catalogChanged = true;
|
|
3826
|
+
}
|
|
2703
3827
|
}
|
|
2704
3828
|
}
|
|
2705
|
-
else
|
|
2706
|
-
|
|
3829
|
+
else {
|
|
3830
|
+
const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, {
|
|
3831
|
+
dependencies: { [LOOM_DEPENDENCY]: publishedSpec },
|
|
3832
|
+
replace: true,
|
|
3833
|
+
});
|
|
3834
|
+
if (dependencyUpdate.changed) {
|
|
3835
|
+
changedFiles.push(dependencyUpdate.config);
|
|
3836
|
+
}
|
|
2707
3837
|
}
|
|
2708
|
-
const
|
|
2709
|
-
|
|
2710
|
-
replace: true,
|
|
2711
|
-
});
|
|
2712
|
-
const denoUpdate = denoConfig && denoLink
|
|
2713
|
-
? await mutateDenoLinks(cwd, denoConfig, { remove: denoLink.link })
|
|
3838
|
+
const denoUpdate = denoConfig && denoLinks.length
|
|
3839
|
+
? await mutateDenoLinks(cwd, denoConfig, { remove: denoLinks })
|
|
2714
3840
|
: null;
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
if (update.changed) {
|
|
2723
|
-
if (denoMode) {
|
|
2724
|
-
changedFiles.push(denoConfig);
|
|
3841
|
+
let overrideRemoved = false;
|
|
3842
|
+
if (denoMode) {
|
|
3843
|
+
if (denoUpdate?.changed) {
|
|
3844
|
+
// The dependency pin may have changed the same file already.
|
|
3845
|
+
if (!changedFiles.includes(denoConfig))
|
|
3846
|
+
changedFiles.push(denoConfig);
|
|
3847
|
+
overrideRemoved = true;
|
|
2725
3848
|
}
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
3849
|
+
}
|
|
3850
|
+
else {
|
|
3851
|
+
for (const file of await clearPnpmLocalDevOverrides(cwd)) {
|
|
3852
|
+
if (!changedFiles.includes(file))
|
|
3853
|
+
changedFiles.push(file);
|
|
3854
|
+
overrideRemoved = true;
|
|
3855
|
+
}
|
|
3856
|
+
// Entries written by hand point pnpm at a local Loom just the same.
|
|
3857
|
+
const workspaceNow = await readTextIfExists(workspacePath);
|
|
3858
|
+
if (workspaceNow && !getManagedDevOverrideBlockText(workspaceNow)) {
|
|
3859
|
+
const update = removeUnmanagedPnpmWorkspaceLoomOverrides(workspaceNow);
|
|
3860
|
+
if (update.changed) {
|
|
3861
|
+
await writeTextOrDeleteIfEmpty(workspacePath, update.text);
|
|
3862
|
+
if (!changedFiles.includes("pnpm-workspace.yaml")) {
|
|
3863
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
3864
|
+
}
|
|
3865
|
+
overrideRemoved = true;
|
|
3866
|
+
}
|
|
3867
|
+
for (const { key, spec } of update.kept) {
|
|
3868
|
+
notes.push(`pnpm-workspace.yaml still overrides ${key} with ${spec} in a flow-style map, which Loom does not edit; remove that entry yourself before running \`pnpm install\`.`);
|
|
3869
|
+
}
|
|
2729
3870
|
}
|
|
2730
3871
|
}
|
|
2731
|
-
if (
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
3872
|
+
if (denoMode) {
|
|
3873
|
+
if (overrideRemoved || localLockfileResolution) {
|
|
3874
|
+
notes.push(`Run \`deno install\` in this project to return node_modules and deno.lock to published ${LOOM_DEPENDENCY}@${publishedSpec}.`);
|
|
3875
|
+
}
|
|
2735
3876
|
}
|
|
2736
|
-
if (localLockfileResolution) {
|
|
2737
|
-
|
|
3877
|
+
else if (overrideRemoved || localLockfileResolution) {
|
|
3878
|
+
const importer = lockfileText
|
|
3879
|
+
? getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)
|
|
3880
|
+
: null;
|
|
3881
|
+
// Earlier Loom versions linked through `pnpm update --no-save`, which
|
|
3882
|
+
// leaves the published specifier with a local version. While that
|
|
3883
|
+
// specifier still matches package.json, pnpm install treats the lockfile
|
|
3884
|
+
// as up to date and keeps the local resolution.
|
|
3885
|
+
const specifierUnchanged = catalog
|
|
3886
|
+
? importer?.specifier === catalog.raw && !catalogChanged
|
|
3887
|
+
: importer?.specifier === publishedSpec;
|
|
3888
|
+
const legacyLocalResolution = importer?.version &&
|
|
3889
|
+
isLocalPackageSpec(importer.version) && specifierUnchanged
|
|
3890
|
+
? localLockfileResolution ?? importer.version
|
|
3891
|
+
: null;
|
|
3892
|
+
if (legacyLocalResolution && catalog) {
|
|
3893
|
+
notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${legacyLocalResolution} from an older \`pnpm update --no-save\` link, which a plain \`pnpm install\` keeps while the catalog version is unchanged. Restore pnpm-lock.yaml from git and run \`pnpm install\`.`);
|
|
3894
|
+
}
|
|
3895
|
+
else if (legacyLocalResolution) {
|
|
3896
|
+
const pinCommand = isExactSemverVersion(publishedSpec)
|
|
3897
|
+
? `\`${dependencyRefreshCommand(tooling.dependencies, LOOM_DEPENDENCY, publishedSpec, { pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd) })}\``
|
|
3898
|
+
: `\`pnpm add --save-exact ${LOOM_DEPENDENCY}@<version>\` with the exact version to ship`;
|
|
3899
|
+
notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${legacyLocalResolution} from an older \`pnpm update --no-save\` link, which a plain \`pnpm install\` keeps. If pnpm-lock.yaml has no other intended changes, restore it from git and run \`pnpm install\`, which also undoes dependency updates that link made; otherwise run ${pinCommand}, which replaces only the Loom resolution (\`pnpm add\` may re-sort package.json dependencies).`);
|
|
3900
|
+
}
|
|
3901
|
+
else {
|
|
3902
|
+
notes.push(`Run \`pnpm install\` in this project to return node_modules and pnpm-lock.yaml to published ${LOOM_DEPENDENCY}@${publishedSpec}; it keeps every other locked version.`);
|
|
3903
|
+
if (localLockfileResolution) {
|
|
3904
|
+
notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${localLockfileResolution} until that install is run.`);
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
2738
3907
|
}
|
|
2739
3908
|
return {
|
|
2740
3909
|
changedFiles,
|
|
2741
3910
|
notes,
|
|
2742
3911
|
};
|
|
2743
3912
|
}
|
|
3913
|
+
/** Removes every managed local Loom override from a pnpm project. */
|
|
3914
|
+
async function clearPnpmLocalDevOverrides(cwd) {
|
|
3915
|
+
const changedFiles = [];
|
|
3916
|
+
const workspacePath = join(cwd, "pnpm-workspace.yaml");
|
|
3917
|
+
const workspaceUpdate = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
|
|
3918
|
+
if (workspaceUpdate.changed) {
|
|
3919
|
+
await writeTextOrDeleteIfEmpty(workspacePath, workspaceUpdate.text);
|
|
3920
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
3921
|
+
}
|
|
3922
|
+
for (const { field } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
|
|
3923
|
+
if (await removePackageJsonLoomOverride(cwd, field) &&
|
|
3924
|
+
!changedFiles.includes("package.json")) {
|
|
3925
|
+
changedFiles.push("package.json");
|
|
3926
|
+
}
|
|
3927
|
+
}
|
|
3928
|
+
// Flags for maps whose Loom entry was already gone would otherwise
|
|
3929
|
+
// outlive the link and claim maps the project has since added.
|
|
3930
|
+
await writeCreatedPackageJsonMaps(cwd, {});
|
|
3931
|
+
return changedFiles;
|
|
3932
|
+
}
|
|
3933
|
+
function getRawPackageJsonMap(packageJson, field) {
|
|
3934
|
+
return field === "resolutions"
|
|
3935
|
+
? packageJson.resolutions
|
|
3936
|
+
: packageJson.pnpm?.overrides;
|
|
3937
|
+
}
|
|
3938
|
+
async function readCreatedPackageJsonMaps(cwd) {
|
|
3939
|
+
return { ...(await readLocalDevState(cwd))?.createdPackageJsonMaps };
|
|
3940
|
+
}
|
|
3941
|
+
async function writeCreatedPackageJsonMaps(cwd, created, overrideSpec) {
|
|
3942
|
+
const state = await readLocalDevState(cwd);
|
|
3943
|
+
const { createdPackageJsonMaps: _previous, ...rest } = state ?? {
|
|
3944
|
+
dependency: LOOM_DEPENDENCY,
|
|
3945
|
+
localPackagePath: overrideSpec ? fileSpecToPath(cwd, overrideSpec) : "",
|
|
3946
|
+
syncedAt: new Date().toISOString(),
|
|
3947
|
+
version: 1,
|
|
3948
|
+
};
|
|
3949
|
+
if (!state && Object.keys(created).length === 0)
|
|
3950
|
+
return;
|
|
3951
|
+
await writeLocalDevStateIfChanged(cwd, Object.keys(created).length
|
|
3952
|
+
? { ...rest, createdPackageJsonMaps: created }
|
|
3953
|
+
: rest);
|
|
3954
|
+
}
|
|
3955
|
+
/**
|
|
3956
|
+
* Removes Loom's managed (`file:`) override from one package.json map with
|
|
3957
|
+
* a minimal text edit. The map (and the `pnpm` object) is removed as well
|
|
3958
|
+
* only when it ends up empty and dev state records that Loom created it;
|
|
3959
|
+
* maps the project already had, or whose origin is unknown, always stay.
|
|
3960
|
+
* Never writes back a whole-file snapshot. Returns whether package.json
|
|
3961
|
+
* changed.
|
|
3962
|
+
*/
|
|
3963
|
+
async function removePackageJsonLoomOverride(cwd, field) {
|
|
3964
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
3965
|
+
if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, field)[LOOM_DEPENDENCY])) {
|
|
3966
|
+
return false;
|
|
3967
|
+
}
|
|
3968
|
+
const created = await readCreatedPackageJsonMaps(cwd);
|
|
3969
|
+
const update = await mutatePackageJsonOverride(cwd, field, LOOM_DEPENDENCY, undefined, {
|
|
3970
|
+
removeEmptyMap: created[field] === true,
|
|
3971
|
+
removeEmptyPnpm: field === "pnpm.overrides" && created.pnpm === true,
|
|
3972
|
+
});
|
|
3973
|
+
delete created[field];
|
|
3974
|
+
if (field === "pnpm.overrides")
|
|
3975
|
+
delete created.pnpm;
|
|
3976
|
+
await writeCreatedPackageJsonMaps(cwd, created);
|
|
3977
|
+
return update.changed;
|
|
3978
|
+
}
|
|
2744
3979
|
async function ensureManagedAgentsFile(cwd) {
|
|
2745
3980
|
const relativePath = "AGENTS.md";
|
|
2746
3981
|
const agentsPath = join(cwd, relativePath);
|
|
@@ -2955,7 +4190,15 @@ async function checkManagedAgentsFile(cwd) {
|
|
|
2955
4190
|
warnings: [],
|
|
2956
4191
|
};
|
|
2957
4192
|
}
|
|
2958
|
-
|
|
4193
|
+
/** Matches override keys that select Loom, including pnpm/yarn selectors. */
|
|
4194
|
+
function overrideKeyTargetsLoom(key) {
|
|
4195
|
+
const target = key.split(">").pop().trim();
|
|
4196
|
+
return target === LOOM_DEPENDENCY ||
|
|
4197
|
+
target.startsWith(`${LOOM_DEPENDENCY}@`) ||
|
|
4198
|
+
target.endsWith(`/${LOOM_DEPENDENCY}`) ||
|
|
4199
|
+
target.includes(`/${LOOM_DEPENDENCY}@`);
|
|
4200
|
+
}
|
|
4201
|
+
async function checkManagedLocalDevOverride(cwd, production, commandRunner, env) {
|
|
2959
4202
|
const manifest = await readManifestIfExists(cwd);
|
|
2960
4203
|
let denoLink = null;
|
|
2961
4204
|
let denoConfig = null;
|
|
@@ -2970,8 +4213,17 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
|
|
|
2970
4213
|
// The main project tooling check reports invalid configuration separately.
|
|
2971
4214
|
}
|
|
2972
4215
|
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
2973
|
-
const
|
|
2974
|
-
|
|
4216
|
+
const packageJson = denoLink ? null : await readPackageJsonIfExists(cwd);
|
|
4217
|
+
const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
|
|
4218
|
+
// Any local spec for Loom in a package.json override map is a local-dev
|
|
4219
|
+
// link, whoever wrote it and whatever selector it uses, and must not ship.
|
|
4220
|
+
const packageJsonOverride = packageJson
|
|
4221
|
+
? PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => Object.entries(getPackageJsonOverrideMap(packageJson, field)).flatMap(([key, spec]) => overrideKeyTargetsLoom(key) && typeof spec === "string" &&
|
|
4222
|
+
isLocalPackageSpec(spec)
|
|
4223
|
+
? [`${formatPnpmOverrideLocation(location)}: ${spec}`]
|
|
4224
|
+
: []))[0]
|
|
4225
|
+
: undefined;
|
|
4226
|
+
if (!workspaceSpec && !packageJsonOverride && !denoLink) {
|
|
2975
4227
|
return {
|
|
2976
4228
|
issues: [],
|
|
2977
4229
|
suggestions: [],
|
|
@@ -2980,19 +4232,45 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
|
|
|
2980
4232
|
}
|
|
2981
4233
|
const location = denoLink
|
|
2982
4234
|
? `${denoConfig} links: ${denoLink.link}`
|
|
2983
|
-
:
|
|
4235
|
+
: workspaceSpec
|
|
4236
|
+
? `pnpm-workspace.yaml: ${workspaceSpec}`
|
|
4237
|
+
: packageJsonOverride;
|
|
2984
4238
|
const restore = denoLink
|
|
2985
4239
|
? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
|
|
2986
|
-
:
|
|
4240
|
+
: "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
|
|
4241
|
+
const warnings = [];
|
|
4242
|
+
const suggestions = [restore];
|
|
4243
|
+
const activePnpmOverride = packageJson
|
|
4244
|
+
? getActivePnpmLocalDevOverride(workspaceText, packageJson)
|
|
4245
|
+
: null;
|
|
4246
|
+
if (activePnpmOverride && packageJson) {
|
|
4247
|
+
// Use the same placement decision as `loom dev sync`, so the advice here
|
|
4248
|
+
// is exactly what the next sync does.
|
|
4249
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
|
|
4250
|
+
const pnpmLabel = placement.pnpmVersion === null
|
|
4251
|
+
? "pnpm (version unknown, assumed 10.5.1 or newer)"
|
|
4252
|
+
: `pnpm ${placement.pnpmVersion}`;
|
|
4253
|
+
if (placement.conflict) {
|
|
4254
|
+
warnings.push(placement.conflict);
|
|
4255
|
+
}
|
|
4256
|
+
else if (activePnpmOverride.location === "pnpm-workspace.yaml"
|
|
4257
|
+
? placement.location !== "pnpm-workspace.yaml"
|
|
4258
|
+
: placement.location === "pnpm-workspace.yaml" &&
|
|
4259
|
+
placement.pnpmMajor !== null && placement.pnpmMajor >= 11) {
|
|
4260
|
+
warnings.push(`${pnpmLabel} does not apply the Loom override in ${formatPnpmOverrideLocation(activePnpmOverride.location)}, so this app may still use the published Loom package.`);
|
|
4261
|
+
suggestions.push(`Run \`loom dev sync\` to move the override to ${formatPnpmOverrideLocation(placement.location)}, where pnpm applies it.`);
|
|
4262
|
+
}
|
|
4263
|
+
}
|
|
2987
4264
|
return {
|
|
2988
4265
|
issues: production
|
|
2989
4266
|
? [
|
|
2990
4267
|
`Local Loom dev override is active in ${location}`,
|
|
2991
4268
|
]
|
|
2992
4269
|
: [],
|
|
2993
|
-
suggestions
|
|
2994
|
-
warnings: production ?
|
|
4270
|
+
suggestions,
|
|
4271
|
+
warnings: production ? warnings : [
|
|
2995
4272
|
`Local Loom dev override is active in ${location}`,
|
|
4273
|
+
...warnings,
|
|
2996
4274
|
],
|
|
2997
4275
|
};
|
|
2998
4276
|
}
|
|
@@ -3031,7 +4309,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3031
4309
|
const issues = [];
|
|
3032
4310
|
const suggestions = new Set();
|
|
3033
4311
|
const warnings = [];
|
|
3034
|
-
const dependency = packageJson.dependencies?.[LOOM_DEPENDENCY];
|
|
3035
4312
|
const production = options.production;
|
|
3036
4313
|
const projectMetadata = await readProjectPackageMetadata(cwd);
|
|
3037
4314
|
let dependencyTooling = {
|
|
@@ -3045,8 +4322,38 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3045
4322
|
catch {
|
|
3046
4323
|
// The main tooling check owns the validation error; release hints can fall back.
|
|
3047
4324
|
}
|
|
4325
|
+
// A pnpm `catalog:` reference pins Loom in pnpm-workspace.yaml instead.
|
|
4326
|
+
// Other managers' catalogs (Yarn 4) are not read.
|
|
4327
|
+
const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
4328
|
+
const dependency = dependencyTooling.manager === "pnpm"
|
|
4329
|
+
? loomDependency.effective
|
|
4330
|
+
: loomDependency.raw;
|
|
3048
4331
|
const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
|
|
3049
4332
|
const devState = await readLocalDevState(cwd);
|
|
4333
|
+
const refreshOptions = {
|
|
4334
|
+
pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd),
|
|
4335
|
+
};
|
|
4336
|
+
const catalogName = dependencyTooling.manager === "pnpm"
|
|
4337
|
+
? loomDependency.catalogName
|
|
4338
|
+
: null;
|
|
4339
|
+
const pinLocation = catalogName
|
|
4340
|
+
? `the pnpm-workspace.yaml \`${loomDependency.catalogEntry?.label ?? "catalog:"}\` map`
|
|
4341
|
+
: dependencyTooling.config;
|
|
4342
|
+
// A pnpm pin change is a manual package.json edit plus `pnpm install`,
|
|
4343
|
+
// which gives the same lockfile as `pnpm add --save-exact` without
|
|
4344
|
+
// re-sorting package.json. Only a lockfile an older `pnpm update --no-save`
|
|
4345
|
+
// link left behind, under an unchanged pin, needs `pnpm add`.
|
|
4346
|
+
const pinSuggestion = (version) => catalogName
|
|
4347
|
+
? formatLoomCatalogPinAdvice(loomDependency.catalogEntry, catalogName, version)
|
|
4348
|
+
: dependencyTooling.manager !== "pnpm"
|
|
4349
|
+
? `Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, version, refreshOptions)}.`
|
|
4350
|
+
: version === dependency
|
|
4351
|
+
? `Restore pnpm-lock.yaml from git if it has no other intended changes and run \`pnpm install\`; otherwise run \`${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, version, refreshOptions)}\` (\`pnpm add\` may re-sort package.json dependencies).`
|
|
4352
|
+
: `Set ${LOOM_DEPENDENCY} to ${version} in package.json, then run \`pnpm install\`.`;
|
|
4353
|
+
// While the override is active it forces the local package whatever the
|
|
4354
|
+
// pin says, so it has to be removed before any refresh can help.
|
|
4355
|
+
const pnpmOverrideActive = dependencyTooling.manager === "pnpm" &&
|
|
4356
|
+
getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), packageJson) !== null;
|
|
3050
4357
|
if (localLockfileResolution) {
|
|
3051
4358
|
addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
|
|
3052
4359
|
suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
|
|
@@ -3078,8 +4385,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3078
4385
|
"package-equivalent"
|
|
3079
4386
|
? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
|
|
3080
4387
|
: `it is published as ${LOOM_DEPENDENCY}@${publication.version}`;
|
|
3081
|
-
addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${
|
|
3082
|
-
suggestions.add(
|
|
4388
|
+
addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
|
|
4389
|
+
suggestions.add(pnpmOverrideActive
|
|
4390
|
+
? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
|
|
4391
|
+
: pinSuggestion(publication.version));
|
|
3083
4392
|
}
|
|
3084
4393
|
else if (localLockfileResolution) {
|
|
3085
4394
|
const publicationDescription = publication.reason ===
|
|
@@ -3087,7 +4396,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3087
4396
|
? `has no package-relevant changes after ${publication.tag}, so ${LOOM_DEPENDENCY}@${publication.version} covers it`
|
|
3088
4397
|
: `is published as ${LOOM_DEPENDENCY}@${publication.version}`;
|
|
3089
4398
|
warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
|
|
3090
|
-
suggestions.add(
|
|
4399
|
+
suggestions.add(pnpmOverrideActive
|
|
4400
|
+
? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
|
|
4401
|
+
: catalogName && dependency === publication.version
|
|
4402
|
+
// pnpm keeps a local resolution while the catalog version
|
|
4403
|
+
// it was linked under is unchanged.
|
|
4404
|
+
? "Restore pnpm-lock.yaml from git and run `pnpm install`."
|
|
4405
|
+
: pinSuggestion(publication.version));
|
|
3091
4406
|
}
|
|
3092
4407
|
break;
|
|
3093
4408
|
}
|
|
@@ -3112,8 +4427,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3112
4427
|
else {
|
|
3113
4428
|
const installedPackage = parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"));
|
|
3114
4429
|
if (installedPackage.version !== dependency) {
|
|
3115
|
-
issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${
|
|
3116
|
-
suggestions.add(
|
|
4430
|
+
issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${pinLocation} ${dependency}.`);
|
|
4431
|
+
suggestions.add(pnpmOverrideActive
|
|
4432
|
+
? "Run `loom dev published`, then run `pnpm install`."
|
|
4433
|
+
: dependencyTooling.manager === "pnpm"
|
|
4434
|
+
? "Run `pnpm install`."
|
|
4435
|
+
: pinSuggestion(dependency));
|
|
3117
4436
|
}
|
|
3118
4437
|
}
|
|
3119
4438
|
}
|
|
@@ -4691,6 +6010,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
|
|
|
4691
6010
|
import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
|
|
4692
6011
|
|
|
4693
6012
|
// Generated verifier stub: adapt Better Auth verifyApiKey() exactly once here.
|
|
6013
|
+
// Replace it with Loom's shared verifier, which checks the requested
|
|
6014
|
+
// permission itself so a scope miss is denied as insufficient_permission:
|
|
6015
|
+
//
|
|
6016
|
+
// import { createBetterAuthApiKeyVerifier } from "@gadicc/loom/apiKeys";
|
|
6017
|
+
// import { auth } from "<the app's Better Auth module>";
|
|
6018
|
+
// import { apiKeyScopes } from "<the app's defineApiKeyScopes registry>";
|
|
6019
|
+
//
|
|
6020
|
+
// export const apiKeyVerifier = createBetterAuthApiKeyVerifier({
|
|
6021
|
+
// auth,
|
|
6022
|
+
// configId: "default", // the api-key plugin configId these keys use
|
|
6023
|
+
// scopes: apiKeyScopes,
|
|
6024
|
+
// });
|
|
4694
6025
|
export const apiKeyVerifier: ApiKeyVerifier = {
|
|
4695
6026
|
verify() {
|
|
4696
6027
|
return Promise.resolve({ ok: false, code: "invalid_credential" });
|
|
@@ -6094,9 +7425,11 @@ async function ensureMinioBucket(cwd, commandRunner, env, endpoint, bucket, acce
|
|
|
6094
7425
|
ok: false,
|
|
6095
7426
|
};
|
|
6096
7427
|
}
|
|
6097
|
-
async function promptForLocalFilesValue(question, secret = false) {
|
|
7428
|
+
async function promptForLocalFilesValue(question, secret = false, context = "MinIO") {
|
|
6098
7429
|
if (!process.stdin.isTTY) {
|
|
6099
|
-
throw new Error(
|
|
7430
|
+
throw new Error(context === "MinIO"
|
|
7431
|
+
? "MinIO admin credentials are required. Run interactively or set MINIO_ROOT_USER and MINIO_ROOT_PASSWORD in the command environment."
|
|
7432
|
+
: "PostgreSQL admin credentials are required. Run interactively or set LOOM_DB_LOCAL_ADMIN_PASSWORD in the command environment.");
|
|
6100
7433
|
}
|
|
6101
7434
|
if (!secret) {
|
|
6102
7435
|
const input = createInterface({
|
|
@@ -6128,7 +7461,7 @@ async function promptForLocalFilesValue(question, secret = false) {
|
|
|
6128
7461
|
}
|
|
6129
7462
|
if (character === "\u0003") {
|
|
6130
7463
|
stdin.off("data", onData);
|
|
6131
|
-
rejectPromise(new Error(
|
|
7464
|
+
rejectPromise(new Error(`${context} setup was cancelled.`));
|
|
6132
7465
|
return;
|
|
6133
7466
|
}
|
|
6134
7467
|
if (character === "\u007f" || character === "\b") {
|
|
@@ -8510,7 +9843,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
|
|
|
8510
9843
|
changedFiles.push(...materialized.changedFiles);
|
|
8511
9844
|
notes.push(...materialized.notes);
|
|
8512
9845
|
config.schema = materialized.schema;
|
|
8513
|
-
notes.push("No migration was generated. Review the audit schema diff, reconcile the Better Auth API-key table, then generate the app-local migration deliberately.", "Install compatible matching `better-auth` and `@better-auth/api-key` versions, configure user-owned keys, keep API-key sessions disabled, and disable the plugin's built-in per-key rate limit for this release.");
|
|
9846
|
+
notes.push("No migration was generated. Review the audit schema diff, reconcile the Better Auth API-key table, then generate the app-local migration deliberately.", "Install compatible matching `better-auth` and `@better-auth/api-key` versions, configure user-owned keys, keep API-key sessions disabled, and disable the plugin's built-in per-key rate limit for this release.", "Disable the api-key plugin's HTTP endpoints in the app-owned Better Auth options with `disabledPaths: withBetterAuthApiKeyHttpPathsDisabled()` from `@gadicc/loom/apiKeys`. Otherwise any signed-in user can call them to re-enable revoked keys, remove expiry, or hard-delete keys; server actions calling `auth.api.*` keep working.");
|
|
8514
9847
|
}
|
|
8515
9848
|
const scaffolds = [
|
|
8516
9849
|
[config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
|
|
@@ -9547,160 +10880,1100 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
|
|
|
9547
10880
|
}
|
|
9548
10881
|
}
|
|
9549
10882
|
}
|
|
9550
|
-
return {
|
|
9551
|
-
issues,
|
|
9552
|
-
suggestions: [...suggestions],
|
|
9553
|
-
warnings,
|
|
9554
|
-
};
|
|
10883
|
+
return {
|
|
10884
|
+
issues,
|
|
10885
|
+
suggestions: [...suggestions],
|
|
10886
|
+
warnings,
|
|
10887
|
+
};
|
|
10888
|
+
}
|
|
10889
|
+
async function checkMailFeature(cwd, framework, manifest, options) {
|
|
10890
|
+
const issues = [];
|
|
10891
|
+
const suggestions = new Set();
|
|
10892
|
+
const warnings = [];
|
|
10893
|
+
const feature = manifest.features.mail;
|
|
10894
|
+
if (!feature || feature.status !== "active") {
|
|
10895
|
+
return { issues, suggestions: [], warnings };
|
|
10896
|
+
}
|
|
10897
|
+
for (const dependency of ["auth", "db"]) {
|
|
10898
|
+
if (manifest.features[dependency]?.status !== "active") {
|
|
10899
|
+
issues.push(`Mail feature requires the active ${dependency} feature.`);
|
|
10900
|
+
suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
|
|
10901
|
+
}
|
|
10902
|
+
}
|
|
10903
|
+
if (issues.length)
|
|
10904
|
+
return { issues, suggestions: [...suggestions], warnings };
|
|
10905
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
10906
|
+
const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
|
|
10907
|
+
const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
|
|
10908
|
+
const schema = config.schema;
|
|
10909
|
+
const latestSchema = getLatestManagedSchemaConfig(schema);
|
|
10910
|
+
if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
|
|
10911
|
+
issues.push("Mail must use the managed-local mail schema blueprint.");
|
|
10912
|
+
suggestions.add("Run `loom add mail` to restore the mail schema config.");
|
|
10913
|
+
}
|
|
10914
|
+
if (schema.exports.length !== 3) {
|
|
10915
|
+
issues.push("Mail schema must configure message, delivery, and event exports.");
|
|
10916
|
+
}
|
|
10917
|
+
if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
10918
|
+
issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
|
|
10919
|
+
}
|
|
10920
|
+
else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
10921
|
+
warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
|
|
10922
|
+
suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
|
|
10923
|
+
}
|
|
10924
|
+
const schemaText = await readTextIfExists(join(cwd, schema.module));
|
|
10925
|
+
if (!schemaText) {
|
|
10926
|
+
issues.push(`Mail schema file is missing: ${schema.module}`);
|
|
10927
|
+
suggestions.add("Run `loom db schemas sync`.");
|
|
10928
|
+
}
|
|
10929
|
+
else {
|
|
10930
|
+
const currentHash = hashManagedSchemaText(schemaText);
|
|
10931
|
+
if (currentHash !== schema.hash) {
|
|
10932
|
+
if (currentHash === latestSchema.hash) {
|
|
10933
|
+
warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
|
|
10934
|
+
suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
|
|
10935
|
+
}
|
|
10936
|
+
else {
|
|
10937
|
+
issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
|
|
10938
|
+
suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
|
|
10939
|
+
}
|
|
10940
|
+
}
|
|
10941
|
+
const barrelText = await readTextIfExists(join(cwd, dbConfig.dirs.schemaDir, "index.ts"));
|
|
10942
|
+
if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
|
|
10943
|
+
issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
|
|
10944
|
+
suggestions.add("Run `loom db schemas sync`.");
|
|
10945
|
+
}
|
|
10946
|
+
}
|
|
10947
|
+
const requiredFiles = [
|
|
10948
|
+
config.modules.accessModule,
|
|
10949
|
+
config.modules.actionsModule,
|
|
10950
|
+
config.modules.repositoryModule,
|
|
10951
|
+
config.modules.serviceModule,
|
|
10952
|
+
config.modules.transportModule,
|
|
10953
|
+
config.entrypoints.adminPage,
|
|
10954
|
+
config.entrypoints.webhookRoute,
|
|
10955
|
+
...(config.jobs.enabled ? [config.modules.jobModule] : []),
|
|
10956
|
+
];
|
|
10957
|
+
for (const relativePath of requiredFiles) {
|
|
10958
|
+
if (!await exists(join(cwd, relativePath))) {
|
|
10959
|
+
issues.push(`Mail scaffold file is missing: ${relativePath}`);
|
|
10960
|
+
suggestions.add("Run `loom add mail` to restore missing scaffolds.");
|
|
10961
|
+
}
|
|
10962
|
+
}
|
|
10963
|
+
const accessText = await readTextIfExists(join(cwd, config.modules.accessModule));
|
|
10964
|
+
if (accessText && !accessText.includes("authorizeMailAdmin")) {
|
|
10965
|
+
issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
|
|
10966
|
+
}
|
|
10967
|
+
const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
|
|
10968
|
+
if (generatedDenyAll) {
|
|
10969
|
+
const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
|
|
10970
|
+
if (options.production)
|
|
10971
|
+
issues.push(message);
|
|
10972
|
+
else
|
|
10973
|
+
warnings.push(message);
|
|
10974
|
+
suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
|
|
10975
|
+
}
|
|
10976
|
+
const contentChecks = [
|
|
10977
|
+
[
|
|
10978
|
+
config.modules.repositoryModule,
|
|
10979
|
+
"@gadicc/loom/mail",
|
|
10980
|
+
"Mail repository is not typed against the shared mail contract",
|
|
10981
|
+
],
|
|
10982
|
+
[
|
|
10983
|
+
config.modules.serviceModule,
|
|
10984
|
+
"createLoomMailService",
|
|
10985
|
+
"Mail service is not wired to the shared durable service",
|
|
10986
|
+
],
|
|
10987
|
+
[
|
|
10988
|
+
config.modules.transportModule,
|
|
10989
|
+
"createPostalMailTransport",
|
|
10990
|
+
"Mail transport is not wired to the Postal adapter",
|
|
10991
|
+
],
|
|
10992
|
+
[
|
|
10993
|
+
config.modules.transportModule,
|
|
10994
|
+
"POSTAL_WEBHOOK_PUBLIC_KEYS",
|
|
10995
|
+
"Mail transport does not configure Postal webhook public keys",
|
|
10996
|
+
],
|
|
10997
|
+
[
|
|
10998
|
+
config.entrypoints.webhookRoute,
|
|
10999
|
+
"createPostalWebhookRouteHandler",
|
|
11000
|
+
"Mail webhook route does not use the signed shared route handler",
|
|
11001
|
+
],
|
|
11002
|
+
[
|
|
11003
|
+
config.modules.actionsModule,
|
|
11004
|
+
"authorizeMailAdmin",
|
|
11005
|
+
"Mail admin actions do not enforce the app-owned admin boundary",
|
|
11006
|
+
],
|
|
11007
|
+
[
|
|
11008
|
+
config.entrypoints.adminPage,
|
|
11009
|
+
"authorizeMailAdmin",
|
|
11010
|
+
"Mail admin page does not enforce the app-owned admin boundary",
|
|
11011
|
+
],
|
|
11012
|
+
];
|
|
11013
|
+
for (const [relativePath, snippet, label] of contentChecks) {
|
|
11014
|
+
const text = await readTextIfExists(join(cwd, relativePath));
|
|
11015
|
+
if (text && !text.includes(snippet)) {
|
|
11016
|
+
issues.push(`${label}: ${relativePath}`);
|
|
11017
|
+
suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
|
|
11018
|
+
}
|
|
11019
|
+
}
|
|
11020
|
+
if (config.ui.adapter === "mui" &&
|
|
11021
|
+
!hasPackageDependency(packageJson, "@mui/material")) {
|
|
11022
|
+
issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
|
|
11023
|
+
}
|
|
11024
|
+
if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
|
|
11025
|
+
warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
|
|
11026
|
+
suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
|
|
11027
|
+
}
|
|
11028
|
+
return { issues, suggestions: [...suggestions], warnings };
|
|
11029
|
+
}
|
|
11030
|
+
function packageDependencySpec(packageJson, dependencyName) {
|
|
11031
|
+
return packageJson.dependencies?.[dependencyName] ??
|
|
11032
|
+
packageJson.devDependencies?.[dependencyName];
|
|
11033
|
+
}
|
|
11034
|
+
function dependencyMajorMinor(spec) {
|
|
11035
|
+
const match = spec?.match(/(\d+)\.(\d+)/);
|
|
11036
|
+
return match ? `${match[1]}.${match[2]}` : undefined;
|
|
11037
|
+
}
|
|
11038
|
+
/**
|
|
11039
|
+
* Blanks JavaScript/TypeScript comments while keeping string and template
|
|
11040
|
+
* literals, so advisory text checks ignore commented-out code. Newlines are
|
|
11041
|
+
* kept. Regular-expression literals are not recognised; one containing a
|
|
11042
|
+
* quote or comment opener can confuse it, which only affects these checks.
|
|
11043
|
+
*/
|
|
11044
|
+
function stripJsComments(text) {
|
|
11045
|
+
let output = "";
|
|
11046
|
+
let index = 0;
|
|
11047
|
+
while (index < text.length) {
|
|
11048
|
+
const char = text[index];
|
|
11049
|
+
const next = text[index + 1];
|
|
11050
|
+
if (char === "/" && next === "/") {
|
|
11051
|
+
const end = text.indexOf("\n", index);
|
|
11052
|
+
output += " ";
|
|
11053
|
+
if (end === -1)
|
|
11054
|
+
break;
|
|
11055
|
+
index = end;
|
|
11056
|
+
continue;
|
|
11057
|
+
}
|
|
11058
|
+
if (char === "/" && next === "*") {
|
|
11059
|
+
const end = text.indexOf("*/", index + 2);
|
|
11060
|
+
const comment = end === -1
|
|
11061
|
+
? text.slice(index)
|
|
11062
|
+
: text.slice(index, end + 2);
|
|
11063
|
+
output += comment.replace(/[^\n]/g, " ");
|
|
11064
|
+
index += comment.length;
|
|
11065
|
+
continue;
|
|
11066
|
+
}
|
|
11067
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
11068
|
+
const end = skipJsStringLiteral(text, index);
|
|
11069
|
+
output += text.slice(index, end);
|
|
11070
|
+
index = end;
|
|
11071
|
+
continue;
|
|
11072
|
+
}
|
|
11073
|
+
output += char;
|
|
11074
|
+
index += 1;
|
|
11075
|
+
}
|
|
11076
|
+
return output;
|
|
11077
|
+
}
|
|
11078
|
+
/** Returns the index just past the string literal that starts at `start`. */
|
|
11079
|
+
function skipJsStringLiteral(text, start) {
|
|
11080
|
+
const quote = text[start];
|
|
11081
|
+
let index = start + 1;
|
|
11082
|
+
while (index < text.length) {
|
|
11083
|
+
const char = text[index];
|
|
11084
|
+
if (char === "\\") {
|
|
11085
|
+
index += 2;
|
|
11086
|
+
continue;
|
|
11087
|
+
}
|
|
11088
|
+
index += 1;
|
|
11089
|
+
if (char === quote)
|
|
11090
|
+
break;
|
|
11091
|
+
if (quote !== "`" && char === "\n")
|
|
11092
|
+
break;
|
|
11093
|
+
}
|
|
11094
|
+
return Math.min(index, text.length);
|
|
11095
|
+
}
|
|
11096
|
+
/**
|
|
11097
|
+
* Replaces the contents of string and template literals with spaces, keeping
|
|
11098
|
+
* quotes, newlines, and offsets, so searches only see code.
|
|
11099
|
+
*/
|
|
11100
|
+
function blankJsStrings(text) {
|
|
11101
|
+
let output = "";
|
|
11102
|
+
let index = 0;
|
|
11103
|
+
while (index < text.length) {
|
|
11104
|
+
const char = text[index];
|
|
11105
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
11106
|
+
const end = skipJsStringLiteral(text, index);
|
|
11107
|
+
output += char + text.slice(index + 1, end).replace(/[^\n]/g, " ");
|
|
11108
|
+
if (end - index >= 2 && text[end - 1] === char) {
|
|
11109
|
+
output = output.slice(0, -1) + char;
|
|
11110
|
+
}
|
|
11111
|
+
index = end;
|
|
11112
|
+
continue;
|
|
11113
|
+
}
|
|
11114
|
+
output += char;
|
|
11115
|
+
index += 1;
|
|
11116
|
+
}
|
|
11117
|
+
return output;
|
|
11118
|
+
}
|
|
11119
|
+
/** Comment-free text plus a same-length copy whose string contents are blank. */
|
|
11120
|
+
function prepareJsText(text) {
|
|
11121
|
+
const code = stripJsComments(text);
|
|
11122
|
+
return { blanked: blankJsStrings(code), code };
|
|
11123
|
+
}
|
|
11124
|
+
/**
|
|
11125
|
+
* Reads one expression starting at `start` until a top-level `,`, `;`, or
|
|
11126
|
+
* closing bracket, skipping string literals. A top-level line break ends it
|
|
11127
|
+
* unless the neighbouring lines continue it (an operator or `.` on either
|
|
11128
|
+
* side), so a chained `.filter()` stays part of the expression. Expects
|
|
11129
|
+
* comment-free text.
|
|
11130
|
+
*/
|
|
11131
|
+
function readJsExpression(text, start) {
|
|
11132
|
+
const blanked = blankJsStrings(text);
|
|
11133
|
+
let index = start;
|
|
11134
|
+
while (index < blanked.length && /\s/.test(blanked[index]))
|
|
11135
|
+
index += 1;
|
|
11136
|
+
const begin = index;
|
|
11137
|
+
let depth = 0;
|
|
11138
|
+
while (index < blanked.length) {
|
|
11139
|
+
const char = blanked[index];
|
|
11140
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11141
|
+
depth += 1;
|
|
11142
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11143
|
+
if (depth === 0)
|
|
11144
|
+
break;
|
|
11145
|
+
depth -= 1;
|
|
11146
|
+
}
|
|
11147
|
+
else if (depth === 0 && (char === "," || char === ";")) {
|
|
11148
|
+
break;
|
|
11149
|
+
}
|
|
11150
|
+
else if (depth === 0 && char === "\n") {
|
|
11151
|
+
const before = blanked.slice(begin, index).trimEnd();
|
|
11152
|
+
const after = blanked.slice(index).trimStart();
|
|
11153
|
+
const continued = /[=([{,?:+\-*/%&|^!<>~.]$/.test(before) ||
|
|
11154
|
+
/^(?:[.?:+\-*/%&|^<>=([]|as\s|satisfies\s)/.test(after);
|
|
11155
|
+
if (!continued)
|
|
11156
|
+
break;
|
|
11157
|
+
}
|
|
11158
|
+
index += 1;
|
|
11159
|
+
}
|
|
11160
|
+
return text.slice(begin, index).trim();
|
|
11161
|
+
}
|
|
11162
|
+
/** Index of the bracket closing the one at `open` in blanked text, or -1. */
|
|
11163
|
+
function findJsClosingBracket(blanked, open) {
|
|
11164
|
+
let depth = 0;
|
|
11165
|
+
for (let index = open; index < blanked.length; index += 1) {
|
|
11166
|
+
const char = blanked[index];
|
|
11167
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11168
|
+
depth += 1;
|
|
11169
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11170
|
+
depth -= 1;
|
|
11171
|
+
if (depth === 0)
|
|
11172
|
+
return index;
|
|
11173
|
+
}
|
|
11174
|
+
}
|
|
11175
|
+
return -1;
|
|
11176
|
+
}
|
|
11177
|
+
/** Splits list or object-literal contents on top-level commas. */
|
|
11178
|
+
function splitJsTopLevel(text) {
|
|
11179
|
+
const blanked = blankJsStrings(text);
|
|
11180
|
+
const parts = [];
|
|
11181
|
+
let depth = 0;
|
|
11182
|
+
let start = 0;
|
|
11183
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11184
|
+
const char = blanked[index];
|
|
11185
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11186
|
+
depth += 1;
|
|
11187
|
+
else if (char === ")" || char === "]" || char === "}")
|
|
11188
|
+
depth -= 1;
|
|
11189
|
+
else if (char === "," && depth === 0) {
|
|
11190
|
+
parts.push(text.slice(start, index).trim());
|
|
11191
|
+
start = index + 1;
|
|
11192
|
+
}
|
|
11193
|
+
}
|
|
11194
|
+
parts.push(text.slice(start).trim());
|
|
11195
|
+
return parts.filter(Boolean);
|
|
11196
|
+
}
|
|
11197
|
+
/** Drops wrapping parentheses and a top-level `as T`/`satisfies T` suffix. */
|
|
11198
|
+
function unwrapJsExpression(expression) {
|
|
11199
|
+
let current = expression.trim();
|
|
11200
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
11201
|
+
const blanked = blankJsStrings(current);
|
|
11202
|
+
let depth = 0;
|
|
11203
|
+
let cut = -1;
|
|
11204
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11205
|
+
const char = blanked[index];
|
|
11206
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11207
|
+
depth += 1;
|
|
11208
|
+
else if (char === ")" || char === "]" || char === "}")
|
|
11209
|
+
depth -= 1;
|
|
11210
|
+
else if (depth === 0 && /\s/.test(char) &&
|
|
11211
|
+
/^\s+(?:as|satisfies)\s/.test(blanked.slice(index))) {
|
|
11212
|
+
cut = index;
|
|
11213
|
+
break;
|
|
11214
|
+
}
|
|
11215
|
+
}
|
|
11216
|
+
if (cut !== -1) {
|
|
11217
|
+
current = current.slice(0, cut).trim();
|
|
11218
|
+
continue;
|
|
11219
|
+
}
|
|
11220
|
+
if (current.startsWith("(") &&
|
|
11221
|
+
findJsClosingBracket(blanked, 0) === current.length - 1) {
|
|
11222
|
+
current = current.slice(1, -1).trim();
|
|
11223
|
+
continue;
|
|
11224
|
+
}
|
|
11225
|
+
break;
|
|
11226
|
+
}
|
|
11227
|
+
return current;
|
|
11228
|
+
}
|
|
11229
|
+
/** `{ callee, args }` when the whole expression is one call, else null. */
|
|
11230
|
+
function parseWholeJsCall(expression) {
|
|
11231
|
+
const match = expression.match(/^([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/);
|
|
11232
|
+
if (!match)
|
|
11233
|
+
return null;
|
|
11234
|
+
const open = match[0].length - 1;
|
|
11235
|
+
if (findJsClosingBracket(blankJsStrings(expression), open) !==
|
|
11236
|
+
expression.length - 1) {
|
|
11237
|
+
return null;
|
|
11238
|
+
}
|
|
11239
|
+
return {
|
|
11240
|
+
args: expression.slice(open + 1, -1),
|
|
11241
|
+
callee: match[1].replace(/\s+/g, ""),
|
|
11242
|
+
};
|
|
11243
|
+
}
|
|
11244
|
+
/** The contents of a whole `[...]` or `{...}` literal, else null. */
|
|
11245
|
+
function wholeJsBracketContents(expression, open) {
|
|
11246
|
+
if (!expression.startsWith(open) ||
|
|
11247
|
+
findJsClosingBracket(blankJsStrings(expression), 0) !==
|
|
11248
|
+
expression.length - 1) {
|
|
11249
|
+
return null;
|
|
11250
|
+
}
|
|
11251
|
+
return expression.slice(1, -1);
|
|
11252
|
+
}
|
|
11253
|
+
/** The value of a plain string literal (no template substitutions). */
|
|
11254
|
+
function jsStringLiteralValue(expression) {
|
|
11255
|
+
const quote = expression[0];
|
|
11256
|
+
if (quote !== '"' && quote !== "'" && quote !== "`")
|
|
11257
|
+
return null;
|
|
11258
|
+
if (skipJsStringLiteral(expression, 0) !== expression.length)
|
|
11259
|
+
return null;
|
|
11260
|
+
const value = expression.slice(1, -1);
|
|
11261
|
+
return value.includes("\\") || (quote === "`" && value.includes("${"))
|
|
11262
|
+
? null
|
|
11263
|
+
: value;
|
|
11264
|
+
}
|
|
11265
|
+
const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
11266
|
+
const JS_IDENTIFIER_SOURCE = String.raw `[A-Za-z_$][\w$]*`;
|
|
11267
|
+
const LOOM_API_KEYS_IMPORT_SOURCES = new Set([
|
|
11268
|
+
"@gadicc/loom",
|
|
11269
|
+
"@gadicc/loom/api-keys",
|
|
11270
|
+
"@gadicc/loom/apiKeys",
|
|
11271
|
+
]);
|
|
11272
|
+
const NO_JS_ENV = new Map();
|
|
11273
|
+
async function loadJsSourceModule(context, relativePath) {
|
|
11274
|
+
if (!context.modules.has(relativePath)) {
|
|
11275
|
+
const text = await readTextIfExists(join(context.cwd, relativePath));
|
|
11276
|
+
context.modules.set(relativePath, text === null
|
|
11277
|
+
? null
|
|
11278
|
+
: { path: relativePath, prepared: prepareJsText(text) });
|
|
11279
|
+
}
|
|
11280
|
+
return context.modules.get(relativePath) ?? null;
|
|
11281
|
+
}
|
|
11282
|
+
/**
|
|
11283
|
+
* Value imports of a module: `imported` is `"*"` for a namespace import and
|
|
11284
|
+
* `"default"` for a default import.
|
|
11285
|
+
*/
|
|
11286
|
+
function parseJsValueImports(module) {
|
|
11287
|
+
const { blanked, code } = module.prepared;
|
|
11288
|
+
const imports = [];
|
|
11289
|
+
const pattern = /(?<![\w$.])import\s+(type\s+)?([^;]*?)\s*from\s*(["'])([^"']+)\3/g;
|
|
11290
|
+
for (const match of code.matchAll(pattern)) {
|
|
11291
|
+
if (match[1] || !blanked.startsWith("import", match.index ?? 0))
|
|
11292
|
+
continue;
|
|
11293
|
+
const clause = match[2].trim();
|
|
11294
|
+
const source = match[4];
|
|
11295
|
+
const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)\s*(?:,|$)/);
|
|
11296
|
+
if (defaultImport) {
|
|
11297
|
+
imports.push({ imported: "default", local: defaultImport[1], source });
|
|
11298
|
+
}
|
|
11299
|
+
const namespace = clause.match(/\*\s*as\s+([A-Za-z_$][\w$]*)/);
|
|
11300
|
+
if (namespace) {
|
|
11301
|
+
imports.push({ imported: "*", local: namespace[1], source });
|
|
11302
|
+
}
|
|
11303
|
+
const named = clause.match(/\{([^}]*)\}/);
|
|
11304
|
+
for (const specifier of named ? named[1].split(",") : []) {
|
|
11305
|
+
const trimmed = specifier.trim();
|
|
11306
|
+
if (!trimmed || /^type\s/.test(trimmed))
|
|
11307
|
+
continue;
|
|
11308
|
+
const [imported, local = imported] = trimmed.split(/\s+as\s+/);
|
|
11309
|
+
if (JS_IDENTIFIER.test(imported) && JS_IDENTIFIER.test(local)) {
|
|
11310
|
+
imports.push({ imported, local, source });
|
|
11311
|
+
}
|
|
11312
|
+
}
|
|
11313
|
+
}
|
|
11314
|
+
return imports;
|
|
11315
|
+
}
|
|
11316
|
+
/** Bracket depth before each offset of blanked text. */
|
|
11317
|
+
function jsBracketDepths(blanked) {
|
|
11318
|
+
const depths = new Int32Array(blanked.length + 1);
|
|
11319
|
+
let depth = 0;
|
|
11320
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11321
|
+
depths[index] = depth;
|
|
11322
|
+
const char = blanked[index];
|
|
11323
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11324
|
+
depth += 1;
|
|
11325
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11326
|
+
depth = Math.max(0, depth - 1);
|
|
11327
|
+
}
|
|
11328
|
+
}
|
|
11329
|
+
depths[blanked.length] = depth;
|
|
11330
|
+
return depths;
|
|
11331
|
+
}
|
|
11332
|
+
function addJsIdentifiers(names, text) {
|
|
11333
|
+
for (const match of text.matchAll(/[A-Za-z_$][\w$]*/g))
|
|
11334
|
+
names.add(match[0]);
|
|
11335
|
+
}
|
|
11336
|
+
/**
|
|
11337
|
+
* Offset of a function body: after a parameter list's closing parenthesis,
|
|
11338
|
+
* an optional return type, then `{` or `=>`. Returns -1 otherwise.
|
|
11339
|
+
*/
|
|
11340
|
+
function jsFunctionBodyStart(blanked, close) {
|
|
11341
|
+
const after = blanked.slice(close + 1).match(/^\s*(?::[^{};=]*?)?\s*(=>|\{)/);
|
|
11342
|
+
if (!after)
|
|
11343
|
+
return -1;
|
|
11344
|
+
return close + 1 + after[0].length - after[1].length;
|
|
11345
|
+
}
|
|
11346
|
+
/** Start and end offsets of a function body that begins at `start`. */
|
|
11347
|
+
function jsFunctionBodyRange(module, start) {
|
|
11348
|
+
const { blanked, code } = module.prepared;
|
|
11349
|
+
let index = start;
|
|
11350
|
+
if (blanked.startsWith("=>", index)) {
|
|
11351
|
+
index += 2;
|
|
11352
|
+
while (index < blanked.length && /\s/.test(blanked[index]))
|
|
11353
|
+
index += 1;
|
|
11354
|
+
if (blanked[index] !== "{") {
|
|
11355
|
+
const expression = readJsExpression(code, index);
|
|
11356
|
+
return { end: index + expression.length, start: index };
|
|
11357
|
+
}
|
|
11358
|
+
}
|
|
11359
|
+
const end = findJsClosingBracket(blanked, index);
|
|
11360
|
+
return end === -1 ? null : { end, start: index };
|
|
11361
|
+
}
|
|
11362
|
+
/** The first parameter's name when it is a plain identifier. */
|
|
11363
|
+
function firstJsParameterName(parameters) {
|
|
11364
|
+
const [first] = splitJsTopLevel(parameters);
|
|
11365
|
+
const name = first?.replace(/\s*=[\s\S]*$/, "").replace(/\s*:[\s\S]*$/, "")
|
|
11366
|
+
.replace(/\?$/, "").trim();
|
|
11367
|
+
return name && JS_IDENTIFIER.test(name) ? name : undefined;
|
|
11368
|
+
}
|
|
11369
|
+
/** Computes, once per module, the facts used for identifier resolution. */
|
|
11370
|
+
function analyzeJsModule(module) {
|
|
11371
|
+
if (module.scope)
|
|
11372
|
+
return module.scope;
|
|
11373
|
+
const { blanked, code } = module.prepared;
|
|
11374
|
+
const depths = jsBracketDepths(blanked);
|
|
11375
|
+
const nestedNames = new Set();
|
|
11376
|
+
const topLevel = new Map();
|
|
11377
|
+
const functions = [];
|
|
11378
|
+
const addTopLevel = (name, binding) => {
|
|
11379
|
+
topLevel.set(name, [...(topLevel.get(name) ?? []), binding]);
|
|
11380
|
+
};
|
|
11381
|
+
for (const match of blanked.matchAll(/(?<![\w$.])(const|let|var)\s+([A-Za-z_$][\w$]*|[{[])/g)) {
|
|
11382
|
+
const index = match.index ?? 0;
|
|
11383
|
+
const target = match[2];
|
|
11384
|
+
const nested = depths[index] > 0;
|
|
11385
|
+
if (target === "{" || target === "[") {
|
|
11386
|
+
// Destructuring: every identifier in the pattern may be bound.
|
|
11387
|
+
const open = index + match[0].length - 1;
|
|
11388
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11389
|
+
const names = new Set();
|
|
11390
|
+
addJsIdentifiers(names, blanked.slice(open, close + 1));
|
|
11391
|
+
for (const name of names) {
|
|
11392
|
+
if (nested)
|
|
11393
|
+
nestedNames.add(name);
|
|
11394
|
+
else
|
|
11395
|
+
addTopLevel(name, { kind: "other" });
|
|
11396
|
+
}
|
|
11397
|
+
continue;
|
|
11398
|
+
}
|
|
11399
|
+
if (nested) {
|
|
11400
|
+
nestedNames.add(target);
|
|
11401
|
+
continue;
|
|
11402
|
+
}
|
|
11403
|
+
const initializer = new RegExp(String.raw `^\s*(?::[^=;]*)?=(?![=>])`).exec(blanked.slice(index + match[0].length));
|
|
11404
|
+
addTopLevel(target, match[1] === "const" && initializer
|
|
11405
|
+
? {
|
|
11406
|
+
initializer: index + match[0].length + initializer[0].length,
|
|
11407
|
+
kind: "const",
|
|
11408
|
+
}
|
|
11409
|
+
: { kind: "other" });
|
|
11410
|
+
}
|
|
11411
|
+
for (const match of blanked.matchAll(/(?<![\w$.])(?:function\s*\*?|class)\s+([A-Za-z_$][\w$]*)/g)) {
|
|
11412
|
+
if (depths[match.index ?? 0] > 0)
|
|
11413
|
+
nestedNames.add(match[1]);
|
|
11414
|
+
else
|
|
11415
|
+
addTopLevel(match[1], { kind: "other" });
|
|
11416
|
+
}
|
|
11417
|
+
for (const entry of parseJsValueImports(module)) {
|
|
11418
|
+
addTopLevel(entry.local, entry.imported === "*" || entry.imported === "default"
|
|
11419
|
+
? { kind: "other" }
|
|
11420
|
+
: { imported: entry.imported, kind: "import", source: entry.source });
|
|
11421
|
+
}
|
|
11422
|
+
// Parameter-like lists (functions, arrows, methods, catch clauses, and
|
|
11423
|
+
// control-flow headers) all count as nested bindings.
|
|
11424
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11425
|
+
if (blanked[index] !== "(")
|
|
11426
|
+
continue;
|
|
11427
|
+
const close = findJsClosingBracket(blanked, index);
|
|
11428
|
+
if (close === -1 || jsFunctionBodyStart(blanked, close) === -1)
|
|
11429
|
+
continue;
|
|
11430
|
+
addJsIdentifiers(nestedNames, blanked.slice(index + 1, close));
|
|
11431
|
+
}
|
|
11432
|
+
for (const match of blanked.matchAll(/([A-Za-z_$][\w$]*)\s*=>/g)) {
|
|
11433
|
+
nestedNames.add(match[1]);
|
|
11434
|
+
}
|
|
11435
|
+
// Top-level functions, for factories that forward their first parameter.
|
|
11436
|
+
const definitions = [
|
|
11437
|
+
/(?<![\w$.])(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g,
|
|
11438
|
+
/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?(?:function\s*\*?\s*[\w$]*\s*)?\(/g,
|
|
11439
|
+
];
|
|
11440
|
+
for (const pattern of definitions) {
|
|
11441
|
+
for (const match of blanked.matchAll(pattern)) {
|
|
11442
|
+
const index = match.index ?? 0;
|
|
11443
|
+
if (depths[index] > 0)
|
|
11444
|
+
continue;
|
|
11445
|
+
const open = index + match[0].length - 1;
|
|
11446
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11447
|
+
const bodyStart = close === -1 ? -1 : jsFunctionBodyStart(blanked, close);
|
|
11448
|
+
const body = bodyStart === -1
|
|
11449
|
+
? null
|
|
11450
|
+
: jsFunctionBodyRange(module, bodyStart);
|
|
11451
|
+
if (!body)
|
|
11452
|
+
continue;
|
|
11453
|
+
functions.push({
|
|
11454
|
+
bodyEnd: body.end,
|
|
11455
|
+
bodyStart: body.start,
|
|
11456
|
+
name: match[1],
|
|
11457
|
+
parameter: firstJsParameterName(code.slice(open + 1, close)),
|
|
11458
|
+
});
|
|
11459
|
+
}
|
|
11460
|
+
}
|
|
11461
|
+
for (const match of blanked.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/g)) {
|
|
11462
|
+
const index = match.index ?? 0;
|
|
11463
|
+
if (depths[index] > 0)
|
|
11464
|
+
continue;
|
|
11465
|
+
const body = jsFunctionBodyRange(module, index + match[0].length - 2);
|
|
11466
|
+
if (body) {
|
|
11467
|
+
functions.push({
|
|
11468
|
+
bodyEnd: body.end,
|
|
11469
|
+
bodyStart: body.start,
|
|
11470
|
+
name: match[1],
|
|
11471
|
+
parameter: match[2],
|
|
11472
|
+
});
|
|
11473
|
+
}
|
|
11474
|
+
}
|
|
11475
|
+
module.scope = { functions, nestedNames, topLevel };
|
|
11476
|
+
return module.scope;
|
|
11477
|
+
}
|
|
11478
|
+
/**
|
|
11479
|
+
* Whether a module mutates `name` after binding it: member assignment
|
|
11480
|
+
* (`name.disabledPaths = …`, `name.length = 0`), a removing array method,
|
|
11481
|
+
* `delete`, `Object.assign` and similar, or reassignment.
|
|
11482
|
+
*/
|
|
11483
|
+
function isJsBindingMutated(module, name) {
|
|
11484
|
+
const { blanked } = module.prepared;
|
|
11485
|
+
const id = escapeRegExp(name);
|
|
11486
|
+
const member = String
|
|
11487
|
+
.raw `(?:\s*\??\.\s*${JS_IDENTIFIER_SOURCE}|\s*\[[^\]]*\])`;
|
|
11488
|
+
const assignment = String
|
|
11489
|
+
.raw `\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?![=>])`;
|
|
11490
|
+
return [
|
|
11491
|
+
new RegExp(String.raw `(?<![\w$.])${id}${member}+${assignment}`),
|
|
11492
|
+
new RegExp(String
|
|
11493
|
+
.raw `(?<![\w$.])${id}${member}*\s*\??\.\s*(?:splice|pop|shift|fill|copyWithin)\s*\(`),
|
|
11494
|
+
new RegExp(String.raw `\bdelete\s+${id}\b`),
|
|
11495
|
+
new RegExp(String
|
|
11496
|
+
.raw `\bObject\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)\s*\(\s*${id}\b`),
|
|
11497
|
+
new RegExp(String.raw `(?<![\w$.]|(?:const|let|var)\s+)${id}${assignment}`),
|
|
11498
|
+
].some((pattern) => pattern.test(blanked));
|
|
11499
|
+
}
|
|
11500
|
+
/**
|
|
11501
|
+
* Local names under which a module imported a Loom API-key export, including
|
|
11502
|
+
* aliases and `namespace.name` for namespace imports. A name that is also
|
|
11503
|
+
* bound elsewhere in the module is left out.
|
|
11504
|
+
*/
|
|
11505
|
+
function loomApiKeyExportNames(module, exportName) {
|
|
11506
|
+
const scope = analyzeJsModule(module);
|
|
11507
|
+
const names = new Set();
|
|
11508
|
+
for (const entry of parseJsValueImports(module)) {
|
|
11509
|
+
if (!LOOM_API_KEYS_IMPORT_SOURCES.has(entry.source))
|
|
11510
|
+
continue;
|
|
11511
|
+
if (scope.nestedNames.has(entry.local) ||
|
|
11512
|
+
(scope.topLevel.get(entry.local)?.length ?? 0) !== 1) {
|
|
11513
|
+
continue;
|
|
11514
|
+
}
|
|
11515
|
+
if (entry.imported === exportName)
|
|
11516
|
+
names.add(entry.local);
|
|
11517
|
+
if (entry.imported === "*")
|
|
11518
|
+
names.add(`${entry.local}.${exportName}`);
|
|
11519
|
+
}
|
|
11520
|
+
return names;
|
|
11521
|
+
}
|
|
11522
|
+
/**
|
|
11523
|
+
* Resolves an identifier, proven or not at all: an enclosing factory
|
|
11524
|
+
* parameter, or the single top-level `const` (or one relative/`@/` import of
|
|
11525
|
+
* one while hops remain) that nothing nested shadows and nothing mutates.
|
|
11526
|
+
*/
|
|
11527
|
+
async function resolveJsName(context, binding, name) {
|
|
11528
|
+
if (binding.env.has(name)) {
|
|
11529
|
+
const parameter = binding.env.get(name) ?? null;
|
|
11530
|
+
return parameter && !isJsBindingMutated(binding.module, name)
|
|
11531
|
+
? parameter
|
|
11532
|
+
: null;
|
|
11533
|
+
}
|
|
11534
|
+
const module = binding.module;
|
|
11535
|
+
const scope = analyzeJsModule(module);
|
|
11536
|
+
const sites = scope.topLevel.get(name) ?? [];
|
|
11537
|
+
if (scope.nestedNames.has(name) || sites.length !== 1)
|
|
11538
|
+
return null;
|
|
11539
|
+
if (isJsBindingMutated(module, name))
|
|
11540
|
+
return null;
|
|
11541
|
+
const [site] = sites;
|
|
11542
|
+
if (site.kind === "const") {
|
|
11543
|
+
return {
|
|
11544
|
+
env: NO_JS_ENV,
|
|
11545
|
+
expression: readJsExpression(module.prepared.code, site.initializer),
|
|
11546
|
+
importHops: binding.importHops,
|
|
11547
|
+
module,
|
|
11548
|
+
};
|
|
11549
|
+
}
|
|
11550
|
+
if (site.kind !== "import" || binding.importHops <= 0)
|
|
11551
|
+
return null;
|
|
11552
|
+
const resolved = await resolveLocalSourceImport(context.cwd, context.framework, resolve(context.cwd, module.path), site.source);
|
|
11553
|
+
if (!resolved)
|
|
11554
|
+
return null;
|
|
11555
|
+
const target = await loadJsSourceModule(context, relative(context.cwd, resolved).replaceAll("\\", "/"));
|
|
11556
|
+
return target
|
|
11557
|
+
? await resolveJsName(context, {
|
|
11558
|
+
env: NO_JS_ENV,
|
|
11559
|
+
expression: site.imported,
|
|
11560
|
+
importHops: binding.importHops - 1,
|
|
11561
|
+
module: target,
|
|
11562
|
+
}, site.imported)
|
|
11563
|
+
: null;
|
|
11564
|
+
}
|
|
11565
|
+
/**
|
|
11566
|
+
* Whether a `disabledPaths` value provably contains every api-key plugin path:
|
|
11567
|
+
* the whole value is Loom's helper call (any arguments) or constant, an array
|
|
11568
|
+
* literal that spreads either, an array literal listing every path, or
|
|
11569
|
+
* `<options>.disabledPaths` of options that prove it. Anything else, such as
|
|
11570
|
+
* a conditional or a filtered list, is unproven.
|
|
11571
|
+
*/
|
|
11572
|
+
async function jsValueDisablesApiKeyPaths(context, binding, depth = 0) {
|
|
11573
|
+
if (depth > 12)
|
|
11574
|
+
return false;
|
|
11575
|
+
const expression = unwrapJsExpression(binding.expression);
|
|
11576
|
+
const compact = expression.replace(/\s+/g, "");
|
|
11577
|
+
const shadowed = (name) => binding.env.has(name.split(".")[0]);
|
|
11578
|
+
const constants = loomApiKeyExportNames(binding.module, "BETTER_AUTH_API_KEY_HTTP_PATHS");
|
|
11579
|
+
if (constants.has(compact) && !shadowed(compact))
|
|
11580
|
+
return true;
|
|
11581
|
+
if (JS_IDENTIFIER.test(expression)) {
|
|
11582
|
+
const resolved = await resolveJsName(context, binding, expression);
|
|
11583
|
+
return resolved
|
|
11584
|
+
? await jsValueDisablesApiKeyPaths(context, resolved, depth + 1)
|
|
11585
|
+
: false;
|
|
11586
|
+
}
|
|
11587
|
+
const member = compact.match(/^([A-Za-z_$][\w$]*)\??\.disabledPaths$/);
|
|
11588
|
+
if (member) {
|
|
11589
|
+
return await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: member[1] }, depth + 1) === true;
|
|
11590
|
+
}
|
|
11591
|
+
const call = parseWholeJsCall(expression);
|
|
11592
|
+
if (call) {
|
|
11593
|
+
return loomApiKeyExportNames(binding.module, "withBetterAuthApiKeyHttpPathsDisabled").has(call.callee) && !shadowed(call.callee);
|
|
11594
|
+
}
|
|
11595
|
+
const list = wholeJsBracketContents(expression, "[");
|
|
11596
|
+
if (list === null)
|
|
11597
|
+
return false;
|
|
11598
|
+
const literals = new Set();
|
|
11599
|
+
for (const element of splitJsTopLevel(list)) {
|
|
11600
|
+
if (element.startsWith("...")) {
|
|
11601
|
+
if (await jsValueDisablesApiKeyPaths(context, { ...binding, expression: element.slice(3) }, depth + 1)) {
|
|
11602
|
+
return true;
|
|
11603
|
+
}
|
|
11604
|
+
continue;
|
|
11605
|
+
}
|
|
11606
|
+
const literal = jsStringLiteralValue(element);
|
|
11607
|
+
if (literal !== null)
|
|
11608
|
+
literals.add(literal);
|
|
11609
|
+
}
|
|
11610
|
+
return BETTER_AUTH_API_KEY_HTTP_PATHS.every((path) => literals.has(path));
|
|
9555
11611
|
}
|
|
9556
|
-
|
|
9557
|
-
|
|
9558
|
-
|
|
9559
|
-
|
|
9560
|
-
|
|
9561
|
-
|
|
9562
|
-
|
|
9563
|
-
|
|
9564
|
-
|
|
9565
|
-
|
|
9566
|
-
|
|
9567
|
-
|
|
11612
|
+
/**
|
|
11613
|
+
* Evaluates Better Auth options for `disabledPaths`: `true` when proven,
|
|
11614
|
+
* `false` when set to something unproven, `undefined` when not set. Entries
|
|
11615
|
+
* apply in order, so a later key or spread overrides an earlier one. Options
|
|
11616
|
+
* or spreads that do not resolve to an object literal, computed keys, and
|
|
11617
|
+
* accessors are unproven.
|
|
11618
|
+
*/
|
|
11619
|
+
async function jsOptionsDisableApiKeyPaths(context, binding, depth = 0) {
|
|
11620
|
+
if (depth > 12)
|
|
11621
|
+
return false;
|
|
11622
|
+
const expression = unwrapJsExpression(binding.expression);
|
|
11623
|
+
if (JS_IDENTIFIER.test(expression)) {
|
|
11624
|
+
const resolved = await resolveJsName(context, binding, expression);
|
|
11625
|
+
return resolved
|
|
11626
|
+
? await jsOptionsDisableApiKeyPaths(context, resolved, depth + 1)
|
|
11627
|
+
: false;
|
|
11628
|
+
}
|
|
11629
|
+
const contents = wholeJsBracketContents(expression, "{");
|
|
11630
|
+
if (contents === null)
|
|
11631
|
+
return false;
|
|
11632
|
+
let result;
|
|
11633
|
+
for (const entry of splitJsTopLevel(contents)) {
|
|
11634
|
+
if (entry.startsWith("...")) {
|
|
11635
|
+
const spread = await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: entry.slice(3) }, depth + 1);
|
|
11636
|
+
if (spread !== undefined)
|
|
11637
|
+
result = spread;
|
|
11638
|
+
continue;
|
|
11639
|
+
}
|
|
11640
|
+
if (entry.startsWith("[")) {
|
|
11641
|
+
// A computed key may evaluate to "disabledPaths".
|
|
11642
|
+
result = false;
|
|
11643
|
+
continue;
|
|
11644
|
+
}
|
|
11645
|
+
if (entry === "disabledPaths") {
|
|
11646
|
+
result = await jsValueDisablesApiKeyPaths(context, { ...binding, expression: entry }, depth + 1);
|
|
11647
|
+
continue;
|
|
11648
|
+
}
|
|
11649
|
+
const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:/);
|
|
11650
|
+
if (property?.[2] === "disabledPaths") {
|
|
11651
|
+
result = await jsValueDisablesApiKeyPaths(context, {
|
|
11652
|
+
...binding,
|
|
11653
|
+
expression: entry.slice(property[0].length),
|
|
11654
|
+
}, depth + 1);
|
|
11655
|
+
}
|
|
11656
|
+
else if (!property &&
|
|
11657
|
+
/^(?:async\s+|get\s+|set\s+)?["']?disabledPaths\b/.test(entry)) {
|
|
11658
|
+
// A getter or method cannot be checked statically.
|
|
11659
|
+
result = false;
|
|
9568
11660
|
}
|
|
9569
11661
|
}
|
|
9570
|
-
|
|
9571
|
-
|
|
9572
|
-
|
|
9573
|
-
|
|
9574
|
-
|
|
9575
|
-
|
|
9576
|
-
|
|
9577
|
-
|
|
9578
|
-
|
|
9579
|
-
|
|
9580
|
-
}
|
|
9581
|
-
|
|
9582
|
-
|
|
11662
|
+
return result;
|
|
11663
|
+
}
|
|
11664
|
+
/**
|
|
11665
|
+
* Every `callee(` call outside strings and comments. Member calls such as
|
|
11666
|
+
* `x.callee(` count only when `allowMember` is set; a function declaration
|
|
11667
|
+
* `function callee(` never counts.
|
|
11668
|
+
*/
|
|
11669
|
+
function findJsCalls(module, callee, options = {}) {
|
|
11670
|
+
const { blanked, code } = module.prepared;
|
|
11671
|
+
const calls = [];
|
|
11672
|
+
const pattern = new RegExp(`${options.allowMember ? "\\b" : "(?<![\\w$.])"}${escapeRegExp(callee)}\\s*\\(`, "g");
|
|
11673
|
+
for (const match of blanked.matchAll(pattern)) {
|
|
11674
|
+
const index = match.index ?? 0;
|
|
11675
|
+
if (/\bfunction\s*\*?\s*$/.test(blanked.slice(0, index)))
|
|
11676
|
+
continue;
|
|
11677
|
+
const open = index + match[0].length - 1;
|
|
11678
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11679
|
+
if (close === -1)
|
|
11680
|
+
continue;
|
|
11681
|
+
calls.push({
|
|
11682
|
+
firstArgument: splitJsTopLevel(code.slice(open + 1, close))[0],
|
|
11683
|
+
open,
|
|
11684
|
+
});
|
|
9583
11685
|
}
|
|
9584
|
-
|
|
9585
|
-
|
|
11686
|
+
return calls;
|
|
11687
|
+
}
|
|
11688
|
+
/**
|
|
11689
|
+
* Reads the app's Better Auth configuration and decides whether it provably
|
|
11690
|
+
* disables every api-key plugin HTTP endpoint.
|
|
11691
|
+
*
|
|
11692
|
+
* Every `betterAuth(` call in the auth module and, when it imports the auth
|
|
11693
|
+
* module, the auth runtime module must be proven; there must be at least one.
|
|
11694
|
+
* A call inside a top-level factory is evaluated once per call of that factory
|
|
11695
|
+
* in those modules, with the factory's first parameter bound to the call's
|
|
11696
|
+
* argument, so options the factory ignores are not credited. Identifiers
|
|
11697
|
+
* resolve only to unshadowed, unmutated top-level `const` initializers,
|
|
11698
|
+
* following one relative or `@/` import. `modules` lists every file read.
|
|
11699
|
+
*/
|
|
11700
|
+
async function inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest) {
|
|
11701
|
+
const authConfig = await mergeAuthConfig(cwd, framework, manifest.features.auth?.config);
|
|
11702
|
+
const authModulePath = authConfig.modules.authModule;
|
|
11703
|
+
const context = { cwd, framework, modules: new Map() };
|
|
11704
|
+
const authModule = await loadJsSourceModule(context, authModulePath);
|
|
11705
|
+
const scanned = authModule ? [authModule] : [];
|
|
11706
|
+
let runtimeModule = null;
|
|
11707
|
+
/** Local names of auth-module exports imported by the runtime module. */
|
|
11708
|
+
const runtimeAliases = new Map();
|
|
11709
|
+
const runtimePath = authConfig.modules.authRuntimeModule;
|
|
11710
|
+
const runtimeText = runtimePath
|
|
11711
|
+
? await readTextIfExists(join(cwd, runtimePath))
|
|
11712
|
+
: null;
|
|
11713
|
+
if (authModule && runtimePath && runtimeText &&
|
|
11714
|
+
matchesImportSource(runtimeText, getImportSpecifierCandidates(runtimePath, authModulePath))) {
|
|
11715
|
+
runtimeModule = await loadJsSourceModule(context, runtimePath);
|
|
11716
|
+
if (runtimeModule) {
|
|
11717
|
+
scanned.push(runtimeModule);
|
|
11718
|
+
const authModuleAbsolute = resolve(cwd, authModulePath);
|
|
11719
|
+
for (const entry of parseJsValueImports(runtimeModule)) {
|
|
11720
|
+
if (entry.imported === "*" || entry.imported === "default")
|
|
11721
|
+
continue;
|
|
11722
|
+
const resolved = await resolveLocalSourceImport(cwd, framework, resolve(cwd, runtimePath), entry.source);
|
|
11723
|
+
if (resolved === authModuleAbsolute) {
|
|
11724
|
+
runtimeAliases.set(entry.imported, entry.local);
|
|
11725
|
+
}
|
|
11726
|
+
}
|
|
11727
|
+
}
|
|
9586
11728
|
}
|
|
9587
|
-
|
|
9588
|
-
|
|
9589
|
-
|
|
11729
|
+
const factoryCalls = (module, factory) => {
|
|
11730
|
+
const calls = findJsCalls(module, factory).map((call) => ({
|
|
11731
|
+
call,
|
|
11732
|
+
module,
|
|
11733
|
+
}));
|
|
11734
|
+
const alias = runtimeAliases.get(factory);
|
|
11735
|
+
const runtime = runtimeModule;
|
|
11736
|
+
if (module === authModule && alias && runtime) {
|
|
11737
|
+
calls.push(...findJsCalls(runtime, alias).map((call) => ({
|
|
11738
|
+
call,
|
|
11739
|
+
module: runtime,
|
|
11740
|
+
})));
|
|
11741
|
+
}
|
|
11742
|
+
return calls;
|
|
11743
|
+
};
|
|
11744
|
+
let calls = 0;
|
|
11745
|
+
let disabled = true;
|
|
11746
|
+
for (const module of scanned) {
|
|
11747
|
+
const functions = analyzeJsModule(module).functions;
|
|
11748
|
+
for (const call of findJsCalls(module, "betterAuth")) {
|
|
11749
|
+
calls += 1;
|
|
11750
|
+
const options = (env) => call.firstArgument === undefined
|
|
11751
|
+
? Promise.resolve(false)
|
|
11752
|
+
: jsOptionsDisableApiKeyPaths(context, {
|
|
11753
|
+
env,
|
|
11754
|
+
expression: call.firstArgument,
|
|
11755
|
+
importHops: 1,
|
|
11756
|
+
module,
|
|
11757
|
+
}).then((result) => result === true);
|
|
11758
|
+
const factory = functions.find((item) => call.open >= item.bodyStart && call.open < item.bodyEnd);
|
|
11759
|
+
const uses = factory ? factoryCalls(module, factory.name) : [];
|
|
11760
|
+
let proven;
|
|
11761
|
+
if (factory && uses.length) {
|
|
11762
|
+
proven = true;
|
|
11763
|
+
for (const use of uses) {
|
|
11764
|
+
const argument = use.call.firstArgument;
|
|
11765
|
+
const env = new Map(factory.parameter
|
|
11766
|
+
? [[
|
|
11767
|
+
factory.parameter,
|
|
11768
|
+
argument === undefined ? null : {
|
|
11769
|
+
env: NO_JS_ENV,
|
|
11770
|
+
expression: argument,
|
|
11771
|
+
importHops: 1,
|
|
11772
|
+
module: use.module,
|
|
11773
|
+
},
|
|
11774
|
+
]]
|
|
11775
|
+
: []);
|
|
11776
|
+
if (!await options(env)) {
|
|
11777
|
+
proven = false;
|
|
11778
|
+
break;
|
|
11779
|
+
}
|
|
11780
|
+
}
|
|
11781
|
+
}
|
|
11782
|
+
else {
|
|
11783
|
+
proven = await options(NO_JS_ENV);
|
|
11784
|
+
}
|
|
11785
|
+
if (!proven)
|
|
11786
|
+
disabled = false;
|
|
11787
|
+
}
|
|
9590
11788
|
}
|
|
9591
|
-
const
|
|
9592
|
-
|
|
9593
|
-
|
|
9594
|
-
|
|
11789
|
+
const loaded = [...context.modules.values()].filter((module) => module !== null);
|
|
11790
|
+
return {
|
|
11791
|
+
authModuleRead: authModule !== null,
|
|
11792
|
+
authModulePath,
|
|
11793
|
+
disabled: calls > 0 && disabled,
|
|
11794
|
+
modules: loaded,
|
|
11795
|
+
};
|
|
11796
|
+
}
|
|
11797
|
+
/**
|
|
11798
|
+
* Advisory, single-module object reading for the authorizer warnings: an
|
|
11799
|
+
* identifier resolves to its initializer only when the module declares that
|
|
11800
|
+
* name exactly once (`const`, at any depth) and nowhere else.
|
|
11801
|
+
*/
|
|
11802
|
+
function readJsObjectShape(module, expression, depth = 0) {
|
|
11803
|
+
if (depth > 8)
|
|
11804
|
+
return null;
|
|
11805
|
+
const unwrapped = unwrapJsExpression(expression);
|
|
11806
|
+
if (JS_IDENTIFIER.test(unwrapped)) {
|
|
11807
|
+
const { blanked, code } = module.prepared;
|
|
11808
|
+
const id = escapeRegExp(unwrapped);
|
|
11809
|
+
const declarations = [
|
|
11810
|
+
...blanked.matchAll(new RegExp(String
|
|
11811
|
+
.raw `(?<![\w$.])(?:const|let|var|function|class)\s+${id}\b|\bimport\b[^;]*\b${id}\b[^;]*\bfrom\b`, "g")),
|
|
11812
|
+
];
|
|
11813
|
+
if (declarations.length !== 1)
|
|
11814
|
+
return null;
|
|
11815
|
+
const declaration = new RegExp(String.raw `(?<![\w$.])const\s+${id}\s*(?::[^=;]*)?=(?![=>])`).exec(blanked);
|
|
11816
|
+
return declaration
|
|
11817
|
+
? readJsObjectShape(module, readJsExpression(code, declaration.index + declaration[0].length), depth + 1)
|
|
11818
|
+
: null;
|
|
9595
11819
|
}
|
|
9596
|
-
|
|
9597
|
-
|
|
9598
|
-
|
|
9599
|
-
|
|
9600
|
-
|
|
9601
|
-
|
|
9602
|
-
|
|
11820
|
+
const contents = wholeJsBracketContents(unwrapped, "{");
|
|
11821
|
+
if (contents === null)
|
|
11822
|
+
return null;
|
|
11823
|
+
const shape = { complete: true, entries: [] };
|
|
11824
|
+
for (const entry of splitJsTopLevel(contents)) {
|
|
11825
|
+
if (entry.startsWith("...")) {
|
|
11826
|
+
const spread = readJsObjectShape(module, entry.slice(3), depth + 1);
|
|
11827
|
+
if (!spread)
|
|
11828
|
+
shape.complete = false;
|
|
9603
11829
|
else {
|
|
9604
|
-
|
|
9605
|
-
|
|
11830
|
+
shape.entries.push(...spread.entries);
|
|
11831
|
+
shape.complete &&= spread.complete;
|
|
9606
11832
|
}
|
|
11833
|
+
continue;
|
|
9607
11834
|
}
|
|
9608
|
-
const
|
|
9609
|
-
if (!
|
|
9610
|
-
|
|
9611
|
-
|
|
11835
|
+
const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*(:)?/);
|
|
11836
|
+
if (!property) {
|
|
11837
|
+
shape.complete = false;
|
|
11838
|
+
continue;
|
|
9612
11839
|
}
|
|
11840
|
+
shape.entries.push({
|
|
11841
|
+
key: property[2],
|
|
11842
|
+
value: property[3] ? entry.slice(property[0].length) : property[2],
|
|
11843
|
+
});
|
|
9613
11844
|
}
|
|
9614
|
-
|
|
9615
|
-
|
|
9616
|
-
|
|
9617
|
-
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9623
|
-
|
|
9624
|
-
|
|
9625
|
-
|
|
9626
|
-
|
|
9627
|
-
|
|
11845
|
+
return shape;
|
|
11846
|
+
}
|
|
11847
|
+
const PERMISSION_CODE_LITERAL = String
|
|
11848
|
+
.raw `(["'\x60])[A-Z0-9_]*PERMISSION[A-Z0-9_]*\1`;
|
|
11849
|
+
const JS_EQUALITY = String.raw `(?:===|!==|==|!=)`;
|
|
11850
|
+
/**
|
|
11851
|
+
* Comparisons of an error `code` with a PERMISSION code, and a PERMISSION
|
|
11852
|
+
* code list checked with `.includes(…code)`. `token` is checked against
|
|
11853
|
+
* string-blanked text so matches inside strings do not count.
|
|
11854
|
+
*/
|
|
11855
|
+
const PERMISSION_CODE_MAPPINGS = [
|
|
11856
|
+
{
|
|
11857
|
+
pattern: new RegExp(String
|
|
11858
|
+
.raw `\bcode\s*${JS_EQUALITY}\s*(?:${PERMISSION_CODE_LITERAL}|[\w$.?]*\b[A-Z0-9_]*PERMISSION[A-Z0-9_]*\b)`, "g"),
|
|
11859
|
+
token: "code",
|
|
11860
|
+
},
|
|
11861
|
+
{
|
|
11862
|
+
pattern: new RegExp(String
|
|
11863
|
+
.raw `${PERMISSION_CODE_LITERAL}\s*${JS_EQUALITY}\s*[\w$.?]*\bcode\b`, "g"),
|
|
11864
|
+
token: "code",
|
|
11865
|
+
},
|
|
11866
|
+
{
|
|
11867
|
+
pattern: new RegExp(String
|
|
11868
|
+
.raw `\[[^\]]*PERMISSION[^\]]*\]\s*\.\s*includes\s*\(\s*[\w$.?]*\bcode\s*\)`, "g"),
|
|
11869
|
+
token: "includes",
|
|
11870
|
+
},
|
|
11871
|
+
];
|
|
11872
|
+
/** Whether a `switch` on an error `code` has a PERMISSION `case` label. */
|
|
11873
|
+
function hasPermissionCodeCase(prepared) {
|
|
11874
|
+
const { blanked, code } = prepared;
|
|
11875
|
+
for (const match of blanked.matchAll(/\bswitch\s*\(/g)) {
|
|
11876
|
+
const open = (match.index ?? 0) + match[0].length - 1;
|
|
11877
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11878
|
+
if (close === -1 || !/\bcode\s*$/.test(blanked.slice(open + 1, close))) {
|
|
11879
|
+
continue;
|
|
9628
11880
|
}
|
|
9629
|
-
|
|
9630
|
-
|
|
9631
|
-
|
|
9632
|
-
|
|
9633
|
-
|
|
9634
|
-
|
|
9635
|
-
|
|
9636
|
-
const
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
|
|
9640
|
-
warnings.push(message);
|
|
9641
|
-
suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
|
|
9642
|
-
}
|
|
9643
|
-
const contentChecks = [
|
|
9644
|
-
[
|
|
9645
|
-
config.modules.repositoryModule,
|
|
9646
|
-
"@gadicc/loom/mail",
|
|
9647
|
-
"Mail repository is not typed against the shared mail contract",
|
|
9648
|
-
],
|
|
9649
|
-
[
|
|
9650
|
-
config.modules.serviceModule,
|
|
9651
|
-
"createLoomMailService",
|
|
9652
|
-
"Mail service is not wired to the shared durable service",
|
|
9653
|
-
],
|
|
9654
|
-
[
|
|
9655
|
-
config.modules.transportModule,
|
|
9656
|
-
"createPostalMailTransport",
|
|
9657
|
-
"Mail transport is not wired to the Postal adapter",
|
|
9658
|
-
],
|
|
9659
|
-
[
|
|
9660
|
-
config.modules.transportModule,
|
|
9661
|
-
"POSTAL_WEBHOOK_PUBLIC_KEYS",
|
|
9662
|
-
"Mail transport does not configure Postal webhook public keys",
|
|
9663
|
-
],
|
|
9664
|
-
[
|
|
9665
|
-
config.entrypoints.webhookRoute,
|
|
9666
|
-
"createPostalWebhookRouteHandler",
|
|
9667
|
-
"Mail webhook route does not use the signed shared route handler",
|
|
9668
|
-
],
|
|
9669
|
-
[
|
|
9670
|
-
config.modules.actionsModule,
|
|
9671
|
-
"authorizeMailAdmin",
|
|
9672
|
-
"Mail admin actions do not enforce the app-owned admin boundary",
|
|
9673
|
-
],
|
|
9674
|
-
[
|
|
9675
|
-
config.entrypoints.adminPage,
|
|
9676
|
-
"authorizeMailAdmin",
|
|
9677
|
-
"Mail admin page does not enforce the app-owned admin boundary",
|
|
9678
|
-
],
|
|
9679
|
-
];
|
|
9680
|
-
for (const [relativePath, snippet, label] of contentChecks) {
|
|
9681
|
-
const text = await readTextIfExists(join(cwd, relativePath));
|
|
9682
|
-
if (text && !text.includes(snippet)) {
|
|
9683
|
-
issues.push(`${label}: ${relativePath}`);
|
|
9684
|
-
suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
|
|
11881
|
+
const bodyOpen = blanked.indexOf("{", close);
|
|
11882
|
+
const bodyClose = bodyOpen === -1
|
|
11883
|
+
? -1
|
|
11884
|
+
: findJsClosingBracket(blanked, bodyOpen);
|
|
11885
|
+
if (bodyClose === -1 || blanked.slice(close + 1, bodyOpen).trim())
|
|
11886
|
+
continue;
|
|
11887
|
+
const pattern = new RegExp(String.raw `\bcase\s+${PERMISSION_CODE_LITERAL}\s*:`, "g");
|
|
11888
|
+
for (const label of code.slice(bodyOpen, bodyClose).matchAll(pattern)) {
|
|
11889
|
+
if (blanked.startsWith("case", bodyOpen + (label.index ?? 0))) {
|
|
11890
|
+
return true;
|
|
11891
|
+
}
|
|
9685
11892
|
}
|
|
9686
11893
|
}
|
|
9687
|
-
|
|
9688
|
-
|
|
9689
|
-
|
|
11894
|
+
return false;
|
|
11895
|
+
}
|
|
11896
|
+
/** Advisory findings for an app-owned Better Auth api-key verifier. */
|
|
11897
|
+
function checkApiKeysAuthorizerText(modulePath, text) {
|
|
11898
|
+
const warnings = [];
|
|
11899
|
+
const module = {
|
|
11900
|
+
path: modulePath,
|
|
11901
|
+
prepared: prepareJsText(text),
|
|
11902
|
+
};
|
|
11903
|
+
for (const call of findJsCalls(module, "verifyApiKey", { allowMember: true })) {
|
|
11904
|
+
const outer = call.firstArgument === undefined
|
|
11905
|
+
? null
|
|
11906
|
+
: readJsObjectShape(module, call.firstArgument);
|
|
11907
|
+
let bodyValue;
|
|
11908
|
+
for (const entry of outer?.entries ?? []) {
|
|
11909
|
+
if (entry.key === "body")
|
|
11910
|
+
bodyValue = entry.value;
|
|
11911
|
+
}
|
|
11912
|
+
// Skip both warnings when the body cannot be read, rather than guess.
|
|
11913
|
+
const body = bodyValue === undefined
|
|
11914
|
+
? null
|
|
11915
|
+
: readJsObjectShape(module, bodyValue);
|
|
11916
|
+
if (!body)
|
|
11917
|
+
continue;
|
|
11918
|
+
if (body.entries.some((entry) => entry.key === "permissions")) {
|
|
11919
|
+
warnings.push(`API-key authorizer passes permissions to verifyApiKey(); Better Auth then reports a valid key that lacks the permission as KEY_NOT_FOUND, so a scope miss is audited as invalid_credential instead of insufficient_permission: ${modulePath}`);
|
|
11920
|
+
}
|
|
11921
|
+
if (body.complete && !body.entries.some((entry) => entry.key === "configId")) {
|
|
11922
|
+
warnings.push(`API-key authorizer calls verifyApiKey() without configId, so keys from any api-key plugin configuration verify: ${modulePath}`);
|
|
11923
|
+
}
|
|
9690
11924
|
}
|
|
9691
|
-
|
|
9692
|
-
|
|
9693
|
-
|
|
11925
|
+
const { blanked, code } = module.prepared;
|
|
11926
|
+
const mapsPermissionCode = hasPermissionCodeCase(module.prepared) ||
|
|
11927
|
+
PERMISSION_CODE_MAPPINGS.some(({ pattern, token }) => [...code.matchAll(pattern)].some((match) => {
|
|
11928
|
+
const tokenIndex = (match.index ?? 0) +
|
|
11929
|
+
match[0].search(new RegExp(`\\b${token}\\b`));
|
|
11930
|
+
return blanked.startsWith(token, tokenIndex);
|
|
11931
|
+
}));
|
|
11932
|
+
if (mapsPermissionCode) {
|
|
11933
|
+
warnings.push(`API-key authorizer maps a Better Auth PERMISSION error code that verifyApiKey() never returns; a missing permission arrives as KEY_NOT_FOUND: ${modulePath}`);
|
|
9694
11934
|
}
|
|
9695
|
-
return
|
|
9696
|
-
}
|
|
9697
|
-
function packageDependencySpec(packageJson, dependencyName) {
|
|
9698
|
-
return packageJson.dependencies?.[dependencyName] ??
|
|
9699
|
-
packageJson.devDependencies?.[dependencyName];
|
|
11935
|
+
return [...new Set(warnings)];
|
|
9700
11936
|
}
|
|
9701
|
-
|
|
9702
|
-
|
|
9703
|
-
|
|
11937
|
+
/**
|
|
11938
|
+
* The props an identifier belongs to in blanked text: the enclosing JSX
|
|
11939
|
+
* opening tag (`<Name ... >`) or, outside JSX, the innermost enclosing
|
|
11940
|
+
* `{...}` or `(...)`. Returns null for JSX children text.
|
|
11941
|
+
*/
|
|
11942
|
+
function jsEnclosingPropsRegion(blanked, index) {
|
|
11943
|
+
let depth = 0;
|
|
11944
|
+
for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
|
|
11945
|
+
const char = blanked[cursor];
|
|
11946
|
+
if (char === ")" || char === "]" || char === "}")
|
|
11947
|
+
depth += 1;
|
|
11948
|
+
else if (char === "(" || char === "[" || char === "{") {
|
|
11949
|
+
if (depth === 0) {
|
|
11950
|
+
if (char === "[")
|
|
11951
|
+
continue;
|
|
11952
|
+
const close = findJsClosingBracket(blanked, cursor);
|
|
11953
|
+
return blanked.slice(cursor, close === -1 ? undefined : close + 1);
|
|
11954
|
+
}
|
|
11955
|
+
depth -= 1;
|
|
11956
|
+
}
|
|
11957
|
+
else if (depth === 0 && char === ">" && blanked[cursor - 1] !== "=") {
|
|
11958
|
+
// The identifier follows a closed tag: it is JSX text, not a prop.
|
|
11959
|
+
return null;
|
|
11960
|
+
}
|
|
11961
|
+
else if (depth === 0 && char === "<" && /[A-Za-z]/.test(blanked[cursor + 1] ?? "")) {
|
|
11962
|
+
let end = index;
|
|
11963
|
+
let inner = 0;
|
|
11964
|
+
for (; end < blanked.length; end += 1) {
|
|
11965
|
+
const next = blanked[end];
|
|
11966
|
+
if (next === "(" || next === "[" || next === "{")
|
|
11967
|
+
inner += 1;
|
|
11968
|
+
else if (next === ")" || next === "]" || next === "}")
|
|
11969
|
+
inner -= 1;
|
|
11970
|
+
else if (inner === 0 && next === ">" && blanked[end - 1] !== "=")
|
|
11971
|
+
break;
|
|
11972
|
+
}
|
|
11973
|
+
return blanked.slice(cursor, end + 1);
|
|
11974
|
+
}
|
|
11975
|
+
}
|
|
11976
|
+
return blanked;
|
|
9704
11977
|
}
|
|
9705
11978
|
async function checkApiKeysFeature(cwd, framework, manifest, options) {
|
|
9706
11979
|
const issues = [];
|
|
@@ -9846,6 +12119,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
|
|
|
9846
12119
|
if (issues.length || warnings.length) {
|
|
9847
12120
|
suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
|
|
9848
12121
|
}
|
|
12122
|
+
// Development hint only: the deprecated flag cannot describe Bearer or
|
|
12123
|
+
// header transports, so its copy can contradict the authorizer.
|
|
12124
|
+
if (!options.production) {
|
|
12125
|
+
for (const pagePath of [
|
|
12126
|
+
config.entrypoints.userPage,
|
|
12127
|
+
config.entrypoints.adminPage,
|
|
12128
|
+
]) {
|
|
12129
|
+
const text = await readTextIfExists(join(cwd, pagePath));
|
|
12130
|
+
const blanked = text ? prepareJsText(text).blanked : "";
|
|
12131
|
+
const uncovered = [
|
|
12132
|
+
...blanked.matchAll(/\bqueryCredentialsEnabled\b/g),
|
|
12133
|
+
].some((match) => {
|
|
12134
|
+
const region = jsEnclosingPropsRegion(blanked, match.index ?? 0);
|
|
12135
|
+
return region !== null && !/\bcredentialOptions\b/.test(region);
|
|
12136
|
+
});
|
|
12137
|
+
if (uncovered) {
|
|
12138
|
+
warnings.push(`API-key page passes the deprecated queryCredentialsEnabled without credentialOptions, so its transport guidance can contradict the authorizer: ${pagePath}`);
|
|
12139
|
+
suggestions.add("Pass the authorizer's credentialOptions to ApiKeysManager (and ApiKeyTransportGuidance), keeping that object in a small import-free module both import.");
|
|
12140
|
+
}
|
|
12141
|
+
}
|
|
12142
|
+
}
|
|
12143
|
+
const authorizerText = await readTextIfExists(join(cwd, config.modules.authorizerModule));
|
|
12144
|
+
if (authorizerText) {
|
|
12145
|
+
const authorizerWarnings = checkApiKeysAuthorizerText(config.modules.authorizerModule, authorizerText);
|
|
12146
|
+
if (authorizerWarnings.length) {
|
|
12147
|
+
warnings.push(...authorizerWarnings);
|
|
12148
|
+
suggestions.add("Use `createBetterAuthApiKeyVerifier` from `@gadicc/loom/apiKeys`: it verifies with a configId and without permissions, then checks the permission itself.");
|
|
12149
|
+
}
|
|
12150
|
+
}
|
|
12151
|
+
const httpEndpoints = config.betterAuthHttpEndpoints;
|
|
12152
|
+
if (httpEndpoints !== undefined && httpEndpoints !== "disabled" &&
|
|
12153
|
+
httpEndpoints !== "app-owned") {
|
|
12154
|
+
issues.push(`Unknown api-keys betterAuthHttpEndpoints value in loom.json: ${JSON.stringify(httpEndpoints)}. Use "disabled" or "app-owned".`);
|
|
12155
|
+
}
|
|
12156
|
+
const authConfig = await inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest);
|
|
12157
|
+
if (httpEndpoints !== "app-owned" && !authConfig.disabled) {
|
|
12158
|
+
const location = authConfig.authModuleRead
|
|
12159
|
+
? `no disabledPaths covering ${BETTER_AUTH_API_KEY_HTTP_PATHS.join(", ")} was proven in the Better Auth options read from: ${authConfig.modules.map((module) => module.path).join(", ")}`
|
|
12160
|
+
: `the auth module could not be read: ${authConfig.authModulePath}`;
|
|
12161
|
+
const message = `Better Auth api-key HTTP endpoints are reachable by any signed-in user (re-enable revoked keys, remove expiry, hard-delete); ${location}`;
|
|
12162
|
+
if (options.production)
|
|
12163
|
+
issues.push(message);
|
|
12164
|
+
else
|
|
12165
|
+
warnings.push(message);
|
|
12166
|
+
suggestions.add('Pass `disabledPaths: withBetterAuthApiKeyHttpPathsDisabled()` (imported from `@gadicc/loom/apiKeys`) after any spreads in every betterAuth() call, or in a top-level const options object in the auth module or one module it imports; a factory must forward its options parameter. Record `betterAuthHttpEndpoints: "app-owned"` under the api-keys config in loom.json only when the app deliberately serves and guards those endpoints itself.');
|
|
12167
|
+
}
|
|
12168
|
+
for (const module of authConfig.modules) {
|
|
12169
|
+
if (/\benableSessionForAPIKeys\s*:\s*true\b/.test(module.prepared.blanked)) {
|
|
12170
|
+
warnings.push(`Better Auth api-key sessions are enabled (enableSessionForAPIKeys: true), so an API key acts as a full user session outside Loom's scope checks and audit: ${module.path}`);
|
|
12171
|
+
}
|
|
12172
|
+
}
|
|
9849
12173
|
return { issues, suggestions: [...suggestions], warnings };
|
|
9850
12174
|
}
|
|
9851
12175
|
async function checkAuthFeature(cwd, framework, manifest) {
|
|
@@ -10636,6 +12960,22 @@ export async function checkProject(cwd, env = process.env, options = {}) {
|
|
|
10636
12960
|
else if (isLocalPackageSpec(dependency)) {
|
|
10637
12961
|
issues.push(`${LOOM_DEPENDENCY} is set to ${dependency}. Keep the committed dependency on a published version and use \`loom dev local <path>\` for local development instead.`);
|
|
10638
12962
|
}
|
|
12963
|
+
else if (parseCatalogReference(dependency) && await isPnpmProject(cwd, packageJson)) {
|
|
12964
|
+
// Only pnpm catalogs live in pnpm-workspace.yaml (Yarn 4 has its own).
|
|
12965
|
+
const catalogDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
12966
|
+
const unreadable = catalogDependency.catalogEntry
|
|
12967
|
+
? null
|
|
12968
|
+
: findUnreadableLoomCatalog(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), catalogDependency.catalogName);
|
|
12969
|
+
if (unreadable) {
|
|
12970
|
+
issues.push(`pnpm-workspace.yaml writes the \`${unreadable}\` catalog as a multi-line or nested flow map, which Loom cannot read. Write it as a block map or a single-line flow map.`);
|
|
12971
|
+
}
|
|
12972
|
+
else if (!catalogDependency.catalogEntry) {
|
|
12973
|
+
issues.push(`${LOOM_DEPENDENCY} uses \`${dependency}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog.`);
|
|
12974
|
+
}
|
|
12975
|
+
else if (isLocalPackageSpec(catalogDependency.catalogEntry.spec)) {
|
|
12976
|
+
issues.push(`The pnpm-workspace.yaml \`${catalogDependency.catalogEntry.label}\` map sets ${LOOM_DEPENDENCY} to ${catalogDependency.catalogEntry.spec}. Keep the committed catalog on a published version and use \`loom dev local <path>\` for local development instead.`);
|
|
12977
|
+
}
|
|
12978
|
+
}
|
|
10639
12979
|
const manifestPath = join(cwd, "loom.json");
|
|
10640
12980
|
const manifestText = await readTextIfExists(manifestPath);
|
|
10641
12981
|
let manifest = null;
|
|
@@ -10719,7 +13059,7 @@ export async function checkProject(cwd, env = process.env, options = {}) {
|
|
|
10719
13059
|
for (const suggestion of nextGuidanceCheck.suggestions) {
|
|
10720
13060
|
suggestions.add(suggestion);
|
|
10721
13061
|
}
|
|
10722
|
-
const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
|
|
13062
|
+
const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
|
|
10723
13063
|
warnings.push(...localDevCheck.warnings);
|
|
10724
13064
|
issues.push(...localDevCheck.issues);
|
|
10725
13065
|
for (const suggestion of localDevCheck.suggestions) {
|
|
@@ -11126,7 +13466,7 @@ async function runStatus(cwd, io) {
|
|
|
11126
13466
|
? parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"))
|
|
11127
13467
|
: null;
|
|
11128
13468
|
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
11129
|
-
const
|
|
13469
|
+
const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
|
|
11130
13470
|
let denoOverride = null;
|
|
11131
13471
|
try {
|
|
11132
13472
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -11148,13 +13488,22 @@ async function runStatus(cwd, io) {
|
|
|
11148
13488
|
io.out(`Loom status for ${projectName}`);
|
|
11149
13489
|
io.out("");
|
|
11150
13490
|
io.out("Package:");
|
|
11151
|
-
|
|
13491
|
+
const catalogEntry = parseCatalogReference(dependencySpec)
|
|
13492
|
+
? findLoomCatalogEntry(workspaceText, parseCatalogReference(dependencySpec))
|
|
13493
|
+
: null;
|
|
13494
|
+
io.out(` ${projectMetadata.config}: ${dependencySpec
|
|
13495
|
+
? `${LOOM_DEPENDENCY} ${dependencySpec}${catalogEntry
|
|
13496
|
+
? ` (${catalogEntry.spec} from pnpm-workspace.yaml ${catalogEntry.label})`
|
|
13497
|
+
: ""}`
|
|
13498
|
+
: "not declared"}`);
|
|
11152
13499
|
io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
|
|
11153
13500
|
io.out(` local dev override: ${denoOverride
|
|
11154
13501
|
? `active (${denoOverride.config} links ${denoOverride.link})`
|
|
11155
|
-
:
|
|
11156
|
-
? `active (${
|
|
11157
|
-
:
|
|
13502
|
+
: pnpmOverride?.location === "pnpm-workspace.yaml"
|
|
13503
|
+
? `active (${pnpmOverride.spec})`
|
|
13504
|
+
: pnpmOverride
|
|
13505
|
+
? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
|
|
13506
|
+
: "none"}`);
|
|
11158
13507
|
io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
|
|
11159
13508
|
io.out("");
|
|
11160
13509
|
io.out("Project:");
|
|
@@ -11268,6 +13617,7 @@ function printHelp({ out }) {
|
|
|
11268
13617
|
out(" db fixtures Run the Loom-managed DB fixture dump script for the active DB feature.");
|
|
11269
13618
|
out(" db schema-gen Run the Loom-managed Valibot generator workflow for the active DB feature. Pass extra generator args after `--`.");
|
|
11270
13619
|
out(" db schemas sync Materialize active Loom-managed DB schema blueprints into app-local schema files.");
|
|
13620
|
+
out(" db local setup|check Provision or verify a restricted project database on existing local PostgreSQL.");
|
|
11271
13621
|
out(" db neon setup Provision and connect a Vercel-managed Neon database for Production and Preview.");
|
|
11272
13622
|
out(" db neon check Run the DB/Neon network checks registered for the active DB feature.");
|
|
11273
13623
|
out(" db migrations verify-env Validate migration URL precedence and role metadata without printing credentials. Add --connect for a live access preflight.");
|
|
@@ -11290,8 +13640,12 @@ function printHelp({ out }) {
|
|
|
11290
13640
|
out(" --network Run registered network checks after the local project checks.");
|
|
11291
13641
|
out(" --production Treat local Loom dev overrides and local lockfile resolutions as release-blocking check failures.");
|
|
11292
13642
|
out(" --no-progress Disable the interactive network progress renderer.");
|
|
13643
|
+
out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
|
|
13644
|
+
out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
|
|
13645
|
+
out(" --replace-local-target Replace an existing development URL during local DB setup.");
|
|
13646
|
+
out(" --cwd <dir> Run in <dir>, resolved from the current directory.");
|
|
11293
13647
|
out(" --no-color Disable colored CLI output.");
|
|
11294
|
-
out(" --no-sync Skip automatic local-dev package sync.");
|
|
13648
|
+
out(" --no-sync Skip automatic local-dev package sync. After a sync that refreshes the package, `loom env` still runs its command; other commands exit 75 and ask for a rerun.");
|
|
11295
13649
|
out(" --force Force `loom dev sync` to rebuild and reinstall.");
|
|
11296
13650
|
out(" --name <name> Override the resource name for `loom db neon setup`.");
|
|
11297
13651
|
out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
|
|
@@ -12057,6 +14411,27 @@ async function runDb(cwd, command, args, io, options = {}) {
|
|
|
12057
14411
|
return 1;
|
|
12058
14412
|
}
|
|
12059
14413
|
switch (command) {
|
|
14414
|
+
case "local": {
|
|
14415
|
+
const localOptions = {
|
|
14416
|
+
commandRunner: defaultCommandRunner,
|
|
14417
|
+
host: options.localDbHost,
|
|
14418
|
+
port: options.localDbPort,
|
|
14419
|
+
replaceLocalTarget: options.replaceLocalTarget,
|
|
14420
|
+
promptSecret: async (question) => await promptForLocalFilesValue(question, true, "PostgreSQL"),
|
|
14421
|
+
};
|
|
14422
|
+
if (args[0] === "setup") {
|
|
14423
|
+
const result = await setupLocalDatabase(cwd, localOptions);
|
|
14424
|
+
io.out(`Local PostgreSQL is ready: ${result.database} at ${result.host}:${result.port}.`);
|
|
14425
|
+
return 0;
|
|
14426
|
+
}
|
|
14427
|
+
if (args[0] === "check") {
|
|
14428
|
+
const result = await checkLocalDatabase(cwd, localOptions);
|
|
14429
|
+
io.out(`Local PostgreSQL check passed: ${result.database} as ${result.role}.`);
|
|
14430
|
+
return 0;
|
|
14431
|
+
}
|
|
14432
|
+
io.err("Usage: loom db local setup|check");
|
|
14433
|
+
return 1;
|
|
14434
|
+
}
|
|
12060
14435
|
case "fixtures":
|
|
12061
14436
|
return await runDbFixtures(cwd, args);
|
|
12062
14437
|
case "schema-gen":
|
|
@@ -12086,7 +14461,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12086
14461
|
io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
|
|
12087
14462
|
return 1;
|
|
12088
14463
|
}
|
|
12089
|
-
const result = await useLocalDevPackage(cwd, pathInput
|
|
14464
|
+
const result = await useLocalDevPackage(cwd, pathInput, {
|
|
14465
|
+
onLockWait: io.err,
|
|
14466
|
+
});
|
|
12090
14467
|
if (result.changedFiles.length) {
|
|
12091
14468
|
io.out(`Updated ${result.changedFiles.join(", ")}.`);
|
|
12092
14469
|
}
|
|
@@ -12098,6 +14475,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12098
14475
|
}
|
|
12099
14476
|
if (!options.noSync) {
|
|
12100
14477
|
const syncResult = await syncLocalDevPackage(cwd, {
|
|
14478
|
+
onLockWait: io.err,
|
|
12101
14479
|
requireActive: true,
|
|
12102
14480
|
});
|
|
12103
14481
|
for (const note of syncResult.notes) {
|
|
@@ -12109,6 +14487,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12109
14487
|
case "sync": {
|
|
12110
14488
|
const result = await syncLocalDevPackage(cwd, {
|
|
12111
14489
|
force: options.force,
|
|
14490
|
+
onLockWait: io.err,
|
|
12112
14491
|
requireActive: true,
|
|
12113
14492
|
});
|
|
12114
14493
|
if (result.changed) {
|
|
@@ -12123,7 +14502,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12123
14502
|
return 0;
|
|
12124
14503
|
}
|
|
12125
14504
|
case "published": {
|
|
12126
|
-
const result = await usePublishedDevPackage(cwd
|
|
14505
|
+
const result = await usePublishedDevPackage(cwd, {
|
|
14506
|
+
onLockWait: io.err,
|
|
14507
|
+
});
|
|
12127
14508
|
if (result.changedFiles.length) {
|
|
12128
14509
|
io.out(`Updated ${result.changedFiles.join(", ")}.`);
|
|
12129
14510
|
}
|
|
@@ -12201,7 +14582,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
|
|
|
12201
14582
|
export async function runCli(args = process.argv.slice(2), io = {
|
|
12202
14583
|
err: (line) => console.error(line),
|
|
12203
14584
|
out: (line) => console.log(line),
|
|
12204
|
-
}) {
|
|
14585
|
+
}, options = {}) {
|
|
12205
14586
|
const parsed = parseArgs({
|
|
12206
14587
|
allowPositionals: true,
|
|
12207
14588
|
args,
|
|
@@ -12221,6 +14602,8 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12221
14602
|
help: { short: "h", type: "boolean" },
|
|
12222
14603
|
jurisdiction: { type: "string" },
|
|
12223
14604
|
"local-bucket": { type: "string" },
|
|
14605
|
+
"local-db-host": { type: "string" },
|
|
14606
|
+
"local-db-port": { type: "string" },
|
|
12224
14607
|
"local-endpoint": { type: "string" },
|
|
12225
14608
|
"local-provider": { type: "string" },
|
|
12226
14609
|
"location-hint": { type: "string" },
|
|
@@ -12237,6 +14620,7 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12237
14620
|
"production-bucket": { type: "string" },
|
|
12238
14621
|
"preview-bucket": { type: "string" },
|
|
12239
14622
|
repair: { type: "boolean" },
|
|
14623
|
+
"replace-local-target": { type: "boolean" },
|
|
12240
14624
|
region: { type: "string" },
|
|
12241
14625
|
resource: { type: "string" },
|
|
12242
14626
|
"strict-skills": { type: "boolean" },
|
|
@@ -12268,13 +14652,29 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12268
14652
|
!addListOnly &&
|
|
12269
14653
|
!productionCheck &&
|
|
12270
14654
|
!parsed.values["no-sync"]) {
|
|
12271
|
-
|
|
14655
|
+
// Taken before waiting on another sync, so a refresh by that sync shows
|
|
14656
|
+
// up as a change and this process does not run the code it replaced.
|
|
14657
|
+
const loadedPackageSignature = await captureLoadedLocalLoomSignature(cwd, process.env);
|
|
14658
|
+
const syncResult = await syncLocalDevPackage(cwd, {
|
|
14659
|
+
commandOutput: command === "env" ? "stderr" : "stdout",
|
|
14660
|
+
commandRunner: options.commandRunner,
|
|
14661
|
+
loadedPackageSignature,
|
|
14662
|
+
onLockWait: io.err,
|
|
14663
|
+
});
|
|
12272
14664
|
if (syncResult.changed) {
|
|
14665
|
+
// `loom env` only loads env files before spawning the wrapped command,
|
|
14666
|
+
// a new process that loads the refreshed package, so it continues.
|
|
14667
|
+
// Every other command would run this process's stale Loom code, so it
|
|
14668
|
+
// stops with a retry status instead of reporting success.
|
|
14669
|
+
const report = command === "env" ? io.err : io.out;
|
|
12273
14670
|
for (const note of syncResult.notes) {
|
|
12274
|
-
|
|
14671
|
+
report(`Note: ${note}`);
|
|
12275
14672
|
}
|
|
12276
|
-
|
|
12277
|
-
|
|
14673
|
+
if (command !== "env") {
|
|
14674
|
+
io.err(`The linked local Loom package was refreshed, so \`loom ${[command, arg1].filter(Boolean).join(" ")}\` did not run. Re-run it to use the refreshed package (exit status ${LOOM_LOCAL_DEV_RERUN_EXIT_CODE}).`);
|
|
14675
|
+
return LOOM_LOCAL_DEV_RERUN_EXIT_CODE;
|
|
14676
|
+
}
|
|
14677
|
+
io.err("Running the wrapped command with the refreshed Loom package.");
|
|
12278
14678
|
}
|
|
12279
14679
|
}
|
|
12280
14680
|
switch (command) {
|
|
@@ -12319,10 +14719,13 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12319
14719
|
acceptUnknownLicense: parsed.values["accept-unknown-license"],
|
|
12320
14720
|
});
|
|
12321
14721
|
case "env":
|
|
12322
|
-
return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io);
|
|
14722
|
+
return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io, { commandRunner: options.commandRunner });
|
|
12323
14723
|
case "db":
|
|
12324
14724
|
return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
|
|
12325
14725
|
connect: parsed.values.connect,
|
|
14726
|
+
localDbHost: parsed.values["local-db-host"],
|
|
14727
|
+
localDbPort: parsed.values["local-db-port"],
|
|
14728
|
+
replaceLocalTarget: parsed.values["replace-local-target"],
|
|
12326
14729
|
name: parsed.values.name,
|
|
12327
14730
|
environment: parsed.values.environment,
|
|
12328
14731
|
envFile: parsed.values["env-file"],
|