@gadicc/loom 1.34.0 → 1.35.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +126 -49
- 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/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 +3060 -451
- 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/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 +3061 -451
- 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 +125 -18
- package/skills/loom-api-keys/SKILL.md +101 -7
- package/skills/loom-auth/SKILL.md +9 -0
- package/skills/loom-db/SKILL.md +3 -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";
|
|
@@ -13,12 +13,15 @@ import { resolveProductionBranch, } from "./releaseConfig.js";
|
|
|
13
13
|
import { configureGithubVercelReleaseCredential, } from "./releaseCredentials.js";
|
|
14
14
|
import { runGithubReleaseTrustCommand } from "./releaseTrustCommand.js";
|
|
15
15
|
import { checkLocalDatabase, setupLocalDatabase } from "./localDb.js";
|
|
16
|
+
import { BETTER_AUTH_API_KEY_HTTP_PATHS } from "../apiKeys/betterAuth.js";
|
|
16
17
|
import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
|
|
17
18
|
import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
|
|
18
19
|
import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
|
|
19
20
|
import { prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
|
|
20
21
|
import { parseVercelReleaseTimeout, prepareVercelProjectRelease, promoteVercelProjectRelease, } from "./vercelProjectRelease.js";
|
|
21
|
-
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";
|
|
22
25
|
export const DEFAULT_LOOM_RANGE = "^1.0.0";
|
|
23
26
|
export const LOOM_DEPENDENCY = "@gadicc/loom";
|
|
24
27
|
export const LOOM_MANIFEST_SCHEMA = "https://loom.gadicc.local/project-manifest.schema.json";
|
|
@@ -30,24 +33,21 @@ export const LOOM_MANAGED_DEV_OVERRIDE_START = "# loom-managed:dev:start";
|
|
|
30
33
|
export const LOOM_MANAGED_DEV_OVERRIDE_END = "# loom-managed:dev:end";
|
|
31
34
|
export const LOOM_LOCAL_DEV_STATE_RELATIVE_PATH = ".loom/dev-state.json";
|
|
32
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";
|
|
33
42
|
const DEFAULT_JOBS_MAX_DURATION_SECONDS = 1800;
|
|
34
43
|
const LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER = "// loom-managed:jobs-static-route";
|
|
35
44
|
/** @deprecated Public npm installs no longer require project registry config. */
|
|
36
45
|
export const LOOM_NPMRC_LINES = [];
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
"bin",
|
|
43
|
-
"deno.json",
|
|
44
|
-
"deno.lock",
|
|
45
|
-
"mod.ts",
|
|
46
|
-
"runtime",
|
|
47
|
-
"scripts/build_npm.ts",
|
|
48
|
-
"skills",
|
|
49
|
-
"src",
|
|
50
|
-
];
|
|
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;
|
|
51
51
|
const PRODUCTION_GITHUB_ENVIRONMENT = "production";
|
|
52
52
|
const REQUIRED_GITHUB_VERCEL_SECRET_NAMES = ["VERCEL_TOKEN"];
|
|
53
53
|
const REQUIRED_GITHUB_VERCEL_ID_NAMES = [
|
|
@@ -319,14 +319,17 @@ async function writeTextIfChanged(path, text) {
|
|
|
319
319
|
}
|
|
320
320
|
export async function defaultCommandRunner(command, args, options) {
|
|
321
321
|
return await new Promise((resolvePromise) => {
|
|
322
|
-
const inherit = options.stdio === "inherit"
|
|
322
|
+
const inherit = options.stdio === "inherit" ||
|
|
323
|
+
options.stdio === "inherit-stderr";
|
|
323
324
|
const pipeInput = !inherit && options.input !== undefined;
|
|
324
325
|
const child = spawn(command, args, {
|
|
325
326
|
cwd: options.cwd,
|
|
326
327
|
env: options.env,
|
|
327
|
-
stdio: inherit
|
|
328
|
-
? "inherit"
|
|
329
|
-
:
|
|
328
|
+
stdio: options.stdio === "inherit-stderr"
|
|
329
|
+
? ["inherit", 2, 2]
|
|
330
|
+
: inherit
|
|
331
|
+
? "inherit"
|
|
332
|
+
: [pipeInput ? "pipe" : "ignore", "pipe", "pipe"],
|
|
330
333
|
});
|
|
331
334
|
const stdoutChunks = [];
|
|
332
335
|
const stderrChunks = [];
|
|
@@ -612,6 +615,215 @@ function getPublishedLoomDependencySpec(packageJson) {
|
|
|
612
615
|
}
|
|
613
616
|
return dependency;
|
|
614
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
|
+
}
|
|
615
827
|
function isLocalPackageSpec(spec) {
|
|
616
828
|
return spec.startsWith("file:") || spec.startsWith("link:") ||
|
|
617
829
|
spec.startsWith("workspace:");
|
|
@@ -823,19 +1035,20 @@ function ensureLinguiGitignoreText(existingText, generatedCatalogs) {
|
|
|
823
1035
|
text: nextText,
|
|
824
1036
|
};
|
|
825
1037
|
}
|
|
826
|
-
function
|
|
1038
|
+
function loomDevGitignoreLineMatches(line, path) {
|
|
827
1039
|
const normalized = line.trim().replace(/^\/?/, "");
|
|
828
|
-
return normalized ===
|
|
829
|
-
normalized === ".loom
|
|
1040
|
+
return normalized === path || normalized === ".loom/" ||
|
|
1041
|
+
normalized === ".loom";
|
|
830
1042
|
}
|
|
831
1043
|
function ensureLoomDevStateGitignoreText(existingText) {
|
|
832
1044
|
const normalized = existingText ? normalizeText(existingText) : "";
|
|
833
1045
|
const lines = normalized
|
|
834
1046
|
.split("\n")
|
|
835
1047
|
.filter((line, index, array) => index < array.length - 1 || line !== "");
|
|
836
|
-
const missingLines =
|
|
837
|
-
|
|
838
|
-
|
|
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)));
|
|
839
1052
|
const nextText = missingLines.length
|
|
840
1053
|
? `${[...lines, ...missingLines].join("\n")}\n`
|
|
841
1054
|
: normalized;
|
|
@@ -1184,18 +1397,34 @@ function dependencyExecutable(tooling, executable) {
|
|
|
1184
1397
|
return `yarn ${executable}`;
|
|
1185
1398
|
}
|
|
1186
1399
|
}
|
|
1187
|
-
|
|
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 = {}) {
|
|
1188
1410
|
switch (tooling.manager) {
|
|
1189
1411
|
case "deno":
|
|
1190
1412
|
return "deno install";
|
|
1191
1413
|
case "npm":
|
|
1192
1414
|
return `npm install --save-exact ${name}@${version}`;
|
|
1193
1415
|
case "pnpm":
|
|
1194
|
-
return
|
|
1416
|
+
return isExactSemverVersion(version)
|
|
1417
|
+
? `pnpm add${options.pnpmWorkspaceRoot ? " -w" : ""} --save-exact ${name}@${version}`
|
|
1418
|
+
: "pnpm install";
|
|
1195
1419
|
case "yarn":
|
|
1196
1420
|
return `yarn add --exact ${name}@${version}`;
|
|
1197
1421
|
}
|
|
1198
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
|
+
}
|
|
1199
1428
|
function getDbExpectedScripts(config, tooling) {
|
|
1200
1429
|
const drizzleKit = dependencyExecutable(tooling.dependencies, "drizzle-kit");
|
|
1201
1430
|
return {
|
|
@@ -1685,6 +1914,10 @@ function getApiKeysConfig(framework, dbConfig, packageJson, featureConfig) {
|
|
|
1685
1914
|
? "src/api-lib/apiKeys"
|
|
1686
1915
|
: "api-lib/apiKeys";
|
|
1687
1916
|
return {
|
|
1917
|
+
// Recorded by the app; Loom never infers or rewrites this choice.
|
|
1918
|
+
...(featureConfig?.betterAuthHttpEndpoints !== undefined
|
|
1919
|
+
? { betterAuthHttpEndpoints: featureConfig.betterAuthHttpEndpoints }
|
|
1920
|
+
: {}),
|
|
1688
1921
|
entrypoints: {
|
|
1689
1922
|
adminPage: featureConfig?.entrypoints?.adminPage ??
|
|
1690
1923
|
`${appRoot}/admin/api-keys/page.tsx`,
|
|
@@ -1901,7 +2134,7 @@ export function ensureNextAgentsMdText(existingText) {
|
|
|
1901
2134
|
: "\n\n"}${block}`;
|
|
1902
2135
|
return { changed: text !== normalized, text };
|
|
1903
2136
|
}
|
|
1904
|
-
function getManagedDevOverrideBlock(overrideSpec, state) {
|
|
2137
|
+
function getManagedDevOverrideBlock(overrideSpec, state, layout = {}) {
|
|
1905
2138
|
// This is a workaround for current pnpm behavior around local package
|
|
1906
2139
|
// development. In testing with pnpm 10.x, direct `pnpm link` against Loom
|
|
1907
2140
|
// mutated pnpm-workspace overrides anyway and broke peer resolution from
|
|
@@ -1920,13 +2153,32 @@ function getManagedDevOverrideBlock(overrideSpec, state) {
|
|
|
1920
2153
|
: null,
|
|
1921
2154
|
].filter((line) => line !== null)
|
|
1922
2155
|
: [];
|
|
2156
|
+
const pad = " ".repeat(layout.indent ?? 2);
|
|
1923
2157
|
return [
|
|
1924
|
-
|
|
1925
|
-
...
|
|
1926
|
-
|
|
1927
|
-
|
|
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}`,
|
|
1928
2168
|
].join("\n");
|
|
1929
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
|
+
}
|
|
1930
2182
|
function getManagedDevOverrideBlockRegex() {
|
|
1931
2183
|
return new RegExp(`^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_START)}\\n[\\s\\S]*?^[ \\t]*${escapeRegExp(LOOM_MANAGED_DEV_OVERRIDE_END)}\\n?`, "m");
|
|
1932
2184
|
}
|
|
@@ -1936,24 +2188,149 @@ function formatYamlLines(lines) {
|
|
|
1936
2188
|
}
|
|
1937
2189
|
return lines.length ? `${lines.join("\n")}\n` : "";
|
|
1938
2190
|
}
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
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)
|
|
1943
2203
|
return null;
|
|
1944
|
-
|
|
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";
|
|
1945
2210
|
let end = lines.length;
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
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))
|
|
1950
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:`/`workspace:`) 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) && isLocalPackageSpec(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);
|
|
1951
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);
|
|
1952
2325
|
}
|
|
1953
|
-
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
|
+
};
|
|
1954
2331
|
}
|
|
1955
2332
|
function hasUnmanagedLoomOverride(text) {
|
|
1956
|
-
return
|
|
2333
|
+
return getPnpmWorkspaceOverrideKeys(text).some(overrideKeyTargetsLoom);
|
|
1957
2334
|
}
|
|
1958
2335
|
function getManagedDevOverrideSpec(text) {
|
|
1959
2336
|
if (!text) {
|
|
@@ -2003,7 +2380,7 @@ function getManagedDevState(text) {
|
|
|
2003
2380
|
}
|
|
2004
2381
|
function setManagedDevStateText(existingText, overrideSpec, state) {
|
|
2005
2382
|
const normalized = existingText ? normalizeText(existingText) : "";
|
|
2006
|
-
const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state)}\n`);
|
|
2383
|
+
const nextText = normalized.replace(getManagedDevOverrideBlockRegex(), `${getManagedDevOverrideBlock(overrideSpec, state, getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized)))}\n`);
|
|
2007
2384
|
return {
|
|
2008
2385
|
changed: nextText !== normalized,
|
|
2009
2386
|
text: nextText,
|
|
@@ -2032,17 +2409,45 @@ export function ensurePnpmWorkspaceLocalDevText(existingText, overrideSpec) {
|
|
|
2032
2409
|
text: normalized,
|
|
2033
2410
|
};
|
|
2034
2411
|
}
|
|
2035
|
-
const blockLines = getManagedDevOverrideBlock(overrideSpec).split("\n");
|
|
2036
2412
|
const lines = baseText === "" ? [] : baseText.replace(/\n$/, "").split("\n");
|
|
2037
|
-
const
|
|
2038
|
-
|
|
2039
|
-
|
|
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"));
|
|
2040
2443
|
}
|
|
2041
2444
|
else {
|
|
2042
2445
|
if (lines.length && lines.at(-1) !== "") {
|
|
2043
2446
|
lines.push("");
|
|
2044
2447
|
}
|
|
2045
|
-
lines.push("overrides:", ...
|
|
2448
|
+
lines.push("overrides:", ...getManagedDevOverrideBlock(overrideSpec, undefined, {
|
|
2449
|
+
createdHeader: true,
|
|
2450
|
+
}).split("\n"));
|
|
2046
2451
|
}
|
|
2047
2452
|
const nextText = formatYamlLines(lines);
|
|
2048
2453
|
return {
|
|
@@ -2059,19 +2464,21 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
|
|
|
2059
2464
|
text: normalized,
|
|
2060
2465
|
};
|
|
2061
2466
|
}
|
|
2467
|
+
const { createdHeader, replacedHeader } = getManagedDevOverrideBlockLayout(getManagedDevOverrideBlockText(normalized));
|
|
2062
2468
|
const withoutManaged = normalized.replace(getManagedDevOverrideBlockRegex(), "");
|
|
2063
2469
|
const lines = withoutManaged === ""
|
|
2064
2470
|
? []
|
|
2065
2471
|
: withoutManaged.replace(/\n$/, "").split("\n");
|
|
2066
|
-
const
|
|
2067
|
-
if (
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
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);
|
|
2075
2482
|
}
|
|
2076
2483
|
}
|
|
2077
2484
|
const nextText = formatYamlLines(lines).replace(/\n{3,}/g, "\n\n");
|
|
@@ -2080,6 +2487,262 @@ export function clearPnpmWorkspaceLocalDevText(existingText) {
|
|
|
2080
2487
|
text: nextText,
|
|
2081
2488
|
};
|
|
2082
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
|
+
}
|
|
2083
2746
|
function pnpmWorkspaceExcludesMinimumReleaseAge(text, dependency) {
|
|
2084
2747
|
if (!text)
|
|
2085
2748
|
return false;
|
|
@@ -2144,6 +2807,13 @@ async function writeTextOrDeleteIfEmpty(path, text) {
|
|
|
2144
2807
|
await mkdir(dirname(path), { recursive: true });
|
|
2145
2808
|
await writeFile(path, text, "utf8");
|
|
2146
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
|
+
}
|
|
2147
2817
|
async function ensurePnpmProject(cwd, packageJson) {
|
|
2148
2818
|
if (packageJson.packageManager?.startsWith("pnpm@") ||
|
|
2149
2819
|
await exists(join(cwd, "pnpm-lock.yaml")) ||
|
|
@@ -2256,33 +2926,49 @@ async function isLocalLoomBuildStale(sourceRoot, localPackagePath) {
|
|
|
2256
2926
|
if (!outputPackageStat) {
|
|
2257
2927
|
return true;
|
|
2258
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
|
+
}
|
|
2259
2945
|
const sourceNewest = await getNewestMtimeMs(sourceRoot);
|
|
2260
2946
|
const outputMtime = outputPackageStat.mtime?.getTime() ?? 0;
|
|
2261
2947
|
return sourceNewest > outputMtime;
|
|
2262
2948
|
}
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
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");
|
|
2269
2964
|
}
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
join("script", "bin", "loom.js"),
|
|
2278
|
-
join("script", "src", "cli", "mod.js"),
|
|
2279
|
-
];
|
|
2280
|
-
for (const relativePath of sentinelFiles) {
|
|
2281
|
-
if (!await filesHaveSameText(join(localPackagePath, relativePath), join(installedPath, relativePath))) {
|
|
2282
|
-
return true;
|
|
2283
|
-
}
|
|
2284
|
-
}
|
|
2285
|
-
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));
|
|
2286
2972
|
}
|
|
2287
2973
|
async function runCommandOrThrow(commandRunner, command, args, options) {
|
|
2288
2974
|
const result = await commandRunner(command, args, options);
|
|
@@ -2351,6 +3037,10 @@ async function readLocalDevState(cwd) {
|
|
|
2351
3037
|
if (state.version !== 1 || state.dependency !== LOOM_DEPENDENCY) {
|
|
2352
3038
|
return null;
|
|
2353
3039
|
}
|
|
3040
|
+
// Retired: whole-file package.json snapshots are never written back.
|
|
3041
|
+
const retired = state;
|
|
3042
|
+
delete retired.packageJsonBeforeOverride;
|
|
3043
|
+
delete retired.packageJsonWithOverride;
|
|
2354
3044
|
return state;
|
|
2355
3045
|
}
|
|
2356
3046
|
catch {
|
|
@@ -2404,15 +3094,17 @@ function compareParsedVersions(left, right) {
|
|
|
2404
3094
|
}
|
|
2405
3095
|
return left.prerelease.localeCompare(right.prerelease);
|
|
2406
3096
|
}
|
|
2407
|
-
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) {
|
|
2408
3100
|
const publication = await resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRunner, env, preferredSpec);
|
|
2409
3101
|
switch (publication.status) {
|
|
2410
3102
|
case "published":
|
|
2411
3103
|
return publication;
|
|
2412
3104
|
case "not-on-origin-main":
|
|
2413
|
-
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\`.`);
|
|
2414
3106
|
case "no-release-tag":
|
|
2415
|
-
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\`.`);
|
|
2416
3108
|
}
|
|
2417
3109
|
}
|
|
2418
3110
|
function parseSemverTags(tags) {
|
|
@@ -2482,127 +3174,512 @@ async function resolveLoomCommitPublication(sourceRoot, sourceCommit, commandRun
|
|
|
2482
3174
|
}
|
|
2483
3175
|
return { status: "no-release-tag" };
|
|
2484
3176
|
}
|
|
2485
|
-
|
|
2486
|
-
const
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
const overrideSpec = getManagedDevOverrideSpec(workspaceText);
|
|
2492
|
-
const denoConfig = denoMode
|
|
2493
|
-
? await getDenoConfigForLinks(cwd, tooling)
|
|
2494
|
-
: null;
|
|
2495
|
-
const denoLink = denoConfig
|
|
2496
|
-
? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
|
|
2497
|
-
: null;
|
|
2498
|
-
if (!overrideSpec && !denoLink) {
|
|
2499
|
-
if (options.requireActive) {
|
|
2500
|
-
throw new Error("No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.");
|
|
2501
|
-
}
|
|
2502
|
-
return {
|
|
2503
|
-
buildRan: false,
|
|
2504
|
-
changed: false,
|
|
2505
|
-
notes: [],
|
|
2506
|
-
packageRefreshRan: false,
|
|
2507
|
-
ranCommands: [],
|
|
2508
|
-
};
|
|
2509
|
-
}
|
|
2510
|
-
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2511
|
-
if (!denoMode)
|
|
2512
|
-
await ensurePnpmProject(cwd, packageJson);
|
|
2513
|
-
const commandRunner = options.commandRunner ?? defaultCommandRunner;
|
|
2514
|
-
const env = options.env ?? process.env;
|
|
2515
|
-
const localPackagePath = denoLink?.path ??
|
|
2516
|
-
fileSpecToPath(cwd, overrideSpec);
|
|
2517
|
-
const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
|
|
2518
|
-
const configuredSpec = packageJson.dependencies?.[LOOM_DEPENDENCY] ??
|
|
2519
|
-
packageJson.devDependencies?.[LOOM_DEPENDENCY];
|
|
2520
|
-
const desiredLocalVersion = await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
|
|
2521
|
-
await readPackageVersion(localPackagePath);
|
|
2522
|
-
const currentLocalVersion = await readPackageVersion(localPackagePath);
|
|
2523
|
-
const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
|
|
2524
|
-
? { ...env, NPM_PACKAGE_VERSION: desiredLocalVersion }
|
|
2525
|
-
: env;
|
|
2526
|
-
const ranCommands = [];
|
|
2527
|
-
let buildRan = false;
|
|
2528
|
-
if (options.force || denoMode && currentLocalVersion !== desiredLocalVersion ||
|
|
2529
|
-
await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
|
|
2530
|
-
if (!sourceRoot) {
|
|
2531
|
-
throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
|
|
2532
|
-
}
|
|
2533
|
-
await runCommandOrThrow(commandRunner, "deno", ["task", "build"], {
|
|
2534
|
-
cwd: sourceRoot,
|
|
2535
|
-
env: buildEnv,
|
|
2536
|
-
stdio: "inherit",
|
|
2537
|
-
});
|
|
2538
|
-
ranCommands.push("deno task build");
|
|
2539
|
-
buildRan = true;
|
|
2540
|
-
}
|
|
2541
|
-
const packageRefreshNeeded = buildRan ||
|
|
2542
|
-
await isInstalledLocalLoomPackageStale(cwd, localPackagePath);
|
|
2543
|
-
let packageRefreshRan = false;
|
|
2544
|
-
if (options.force || packageRefreshNeeded) {
|
|
2545
|
-
if (denoMode) {
|
|
2546
|
-
await runCommandOrThrow(commandRunner, "deno", ["install"], {
|
|
2547
|
-
cwd,
|
|
2548
|
-
env,
|
|
2549
|
-
stdio: "inherit",
|
|
2550
|
-
});
|
|
2551
|
-
ranCommands.push("deno install");
|
|
2552
|
-
}
|
|
2553
|
-
else {
|
|
2554
|
-
const packageSpec = `${LOOM_DEPENDENCY}@file:${localPackagePath}`;
|
|
2555
|
-
await runCommandOrThrow(commandRunner, "pnpm", ["update", "--no-save", packageSpec], { cwd, env, stdio: "inherit" });
|
|
2556
|
-
ranCommands.push(`pnpm update --no-save ${packageSpec}`);
|
|
2557
|
-
await runCommandOrThrow(commandRunner, "pnpm", ["install"], {
|
|
2558
|
-
cwd,
|
|
2559
|
-
env,
|
|
2560
|
-
stdio: "inherit",
|
|
2561
|
-
});
|
|
2562
|
-
ranCommands.push("pnpm install");
|
|
2563
|
-
}
|
|
2564
|
-
packageRefreshRan = true;
|
|
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);
|
|
2565
3183
|
}
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
? await readLocalDevState(cwd)
|
|
2569
|
-
: await getCurrentLocalDevState(cwd, currentWorkspaceText);
|
|
2570
|
-
let state = null;
|
|
2571
|
-
if (buildRan || packageRefreshRan || !currentState) {
|
|
2572
|
-
state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
|
|
2573
|
-
if (!denoMode) {
|
|
2574
|
-
const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), overrideSpec, state);
|
|
2575
|
-
if (stateUpdate.changed) {
|
|
2576
|
-
await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
|
|
2577
|
-
}
|
|
2578
|
-
}
|
|
3184
|
+
catch {
|
|
3185
|
+
return null;
|
|
2579
3186
|
}
|
|
2580
|
-
|
|
2581
|
-
|
|
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;
|
|
2582
3205
|
}
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
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
|
+
/** Whether deno.lock records a `links` entry for Loom. */
|
|
3212
|
+
async function denoLockLinksLoom(cwd) {
|
|
3213
|
+
const text = await readTextIfExists(join(cwd, "deno.lock"));
|
|
3214
|
+
if (!text)
|
|
3215
|
+
return false;
|
|
3216
|
+
let lock;
|
|
3217
|
+
try {
|
|
3218
|
+
lock = JSON.parse(text);
|
|
2592
3219
|
}
|
|
2593
|
-
|
|
2594
|
-
|
|
3220
|
+
catch {
|
|
3221
|
+
// Unreadable: assume it may record one.
|
|
3222
|
+
return true;
|
|
2595
3223
|
}
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
3224
|
+
const linkKeys = (scope) => scope && typeof scope === "object" &&
|
|
3225
|
+
scope.links &&
|
|
3226
|
+
typeof scope.links === "object"
|
|
3227
|
+
? Object.keys(scope.links)
|
|
3228
|
+
: [];
|
|
3229
|
+
const members = lock.workspace?.members &&
|
|
3230
|
+
typeof lock.workspace.members === "object"
|
|
3231
|
+
? Object.values(lock.workspace.members)
|
|
3232
|
+
: [];
|
|
3233
|
+
return [lock.workspace, ...members].flatMap(linkKeys).some((key) => key === LOOM_DEPENDENCY || key.startsWith(`npm:${LOOM_DEPENDENCY}@`) ||
|
|
3234
|
+
key.startsWith(`${LOOM_DEPENDENCY}@`));
|
|
3235
|
+
}
|
|
3236
|
+
/**
|
|
3237
|
+
* Every Deno `links` entry that is, or may be, Loom's: its package is named
|
|
3238
|
+
* Loom, or its package is gone. A dangling entry may be Loom's whatever
|
|
3239
|
+
* identifies it (the path dev state recorded, a Loom link in deno.lock, or
|
|
3240
|
+
* nothing at all): node_modules can still hold what Deno copied from it,
|
|
3241
|
+
* and a broken link cannot ship anyway.
|
|
3242
|
+
*/
|
|
3243
|
+
async function findLoomDenoLinks(cwd, denoConfig) {
|
|
3244
|
+
const links = [];
|
|
3245
|
+
for (const link of await readDenoLinks(cwd, denoConfig)) {
|
|
3246
|
+
const path = resolve(cwd, link);
|
|
3247
|
+
const dangling = !await exists(join(path, "package.json"));
|
|
3248
|
+
if (dangling || await findLocalLoomDenoLink(cwd, [link])) {
|
|
3249
|
+
links.push({ dangling, link, path });
|
|
3250
|
+
}
|
|
3251
|
+
}
|
|
3252
|
+
return links;
|
|
3253
|
+
}
|
|
3254
|
+
/**
|
|
3255
|
+
* Local Loom overrides and links in the project's config: Loom overrides
|
|
3256
|
+
* with a local (`file:`/`link:`/`workspace:`) spec under any selector, in
|
|
3257
|
+
* package.json maps or pnpm-workspace.yaml (managed or hand-written), a local
|
|
3258
|
+
* Loom catalog entry, and Deno links to Loom, dangling ones included. Each
|
|
3259
|
+
* is described for messages.
|
|
3260
|
+
*/
|
|
3261
|
+
async function findLocalLoomLinks(cwd) {
|
|
3262
|
+
const manifest = await readManifestIfExists(cwd);
|
|
3263
|
+
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
3264
|
+
const packageJson = await readPackageJsonIfExists(cwd) ?? {};
|
|
3265
|
+
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
3266
|
+
const links = [];
|
|
3267
|
+
// Reported by the catalog check itself; still local Loom in use.
|
|
3268
|
+
const catalogLinks = [];
|
|
3269
|
+
for (const { field, location } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
|
|
3270
|
+
for (const [key, spec] of Object.entries(getPackageJsonOverrideMap(packageJson, field))) {
|
|
3271
|
+
if (overrideKeyTargetsLoom(key) && typeof spec === "string" &&
|
|
3272
|
+
isLocalPackageSpec(spec)) {
|
|
3273
|
+
links.push(`${formatPnpmOverrideLocation(location)}: ${spec}`);
|
|
3274
|
+
}
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
const managedSpec = getManagedDevOverrideSpec(workspaceText);
|
|
3278
|
+
if (managedSpec)
|
|
3279
|
+
links.push(`pnpm-workspace.yaml: ${managedSpec}`);
|
|
3280
|
+
for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(workspaceText)) {
|
|
3281
|
+
links.push(`pnpm-workspace.yaml overrides ${key}: ${spec}`);
|
|
3282
|
+
}
|
|
3283
|
+
const dependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
3284
|
+
if (dependency.catalogName && dependency.effective &&
|
|
3285
|
+
isLocalPackageSpec(dependency.effective)) {
|
|
3286
|
+
catalogLinks.push(`pnpm-workspace.yaml catalog ${dependency.catalogName}: ${dependency.effective}`);
|
|
3287
|
+
}
|
|
3288
|
+
if (usesDenoTooling(tooling)) {
|
|
3289
|
+
const denoConfig = await getDenoConfigForLinks(cwd, tooling);
|
|
3290
|
+
for (const { dangling, link } of await findLoomDenoLinks(cwd, denoConfig)) {
|
|
3291
|
+
links.push(`${denoConfig} links: ${link}${dangling ? " (its package is gone; it may be Loom's)" : ""}`);
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
return {
|
|
3295
|
+
catalogLinks,
|
|
3296
|
+
denoMode: usesDenoTooling(tooling),
|
|
3297
|
+
links,
|
|
3298
|
+
packageJson,
|
|
3299
|
+
};
|
|
3300
|
+
}
|
|
3301
|
+
/**
|
|
3302
|
+
* The published Loom version a Deno project's node_modules copy came from,
|
|
3303
|
+
* when deno.lock proves it: the lock records no Loom link, resolves the
|
|
3304
|
+
* project's `npm:@gadicc/loom@<pin>` specifier to a version installed from
|
|
3305
|
+
* the registry (its npm entry carries an integrity hash, which a linked
|
|
3306
|
+
* package's entry lacks), and node_modules holds that version. Null
|
|
3307
|
+
* otherwise, including without a deno.lock.
|
|
3308
|
+
*/
|
|
3309
|
+
async function findInstalledDenoRegistryLoomVersion(cwd, packageJson) {
|
|
3310
|
+
const text = await readTextIfExists(join(cwd, "deno.lock"));
|
|
3311
|
+
if (!text || await denoLockLinksLoom(cwd))
|
|
3312
|
+
return null;
|
|
3313
|
+
let lock;
|
|
3314
|
+
try {
|
|
3315
|
+
lock = JSON.parse(text);
|
|
3316
|
+
}
|
|
3317
|
+
catch {
|
|
3318
|
+
return null;
|
|
3319
|
+
}
|
|
3320
|
+
const manifest = await readManifestIfExists(cwd);
|
|
3321
|
+
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
3322
|
+
const denoConfig = await getDenoConfigForLinks(cwd, tooling);
|
|
3323
|
+
const imports = parseJsonc(await readTextIfExists(join(cwd, denoConfig)) ?? "{}", denoConfig).imports ?? {};
|
|
3324
|
+
const pinned = [
|
|
3325
|
+
imports[LOOM_DEPENDENCY],
|
|
3326
|
+
packageJson.dependencies?.[LOOM_DEPENDENCY] &&
|
|
3327
|
+
`npm:${LOOM_DEPENDENCY}@${packageJson.dependencies[LOOM_DEPENDENCY]}`,
|
|
3328
|
+
].find((spec) => typeof spec === "string" && spec.startsWith(`npm:${LOOM_DEPENDENCY}@`) &&
|
|
3329
|
+
lock.specifiers?.[spec] !== undefined);
|
|
3330
|
+
const resolved = pinned ? lock.specifiers[pinned] : undefined;
|
|
3331
|
+
if (!resolved)
|
|
3332
|
+
return null;
|
|
3333
|
+
const entry = lock.npm?.[`${LOOM_DEPENDENCY}@${resolved}`];
|
|
3334
|
+
if (typeof entry?.integrity !== "string")
|
|
3335
|
+
return null;
|
|
3336
|
+
const version = resolved.replace(/_.*$/, "");
|
|
3337
|
+
return await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ===
|
|
3338
|
+
version
|
|
3339
|
+
? version
|
|
3340
|
+
: null;
|
|
3341
|
+
}
|
|
3342
|
+
/**
|
|
3343
|
+
* Why this project may still run local Loom code; empty only when it
|
|
3344
|
+
* provably does not. One predicate decides this for `loom dev published`
|
|
3345
|
+
* (whether to drop the sync record) and `loom check` (whether that record
|
|
3346
|
+
* is stale):
|
|
3347
|
+
* - any local Loom override, catalog entry or Deno link
|
|
3348
|
+
* ({@link findLocalLoomLinks});
|
|
3349
|
+
* - pnpm-lock.yaml resolving Loom locally, or deno.lock recording a Loom link;
|
|
3350
|
+
* - an installed node_modules/@gadicc/loom that is not provably the
|
|
3351
|
+
* published package: for pnpm, unless it is pnpm's registry store entry
|
|
3352
|
+
* ({@link findInstalledRegistryLoomVersion}); for Deno, any copy, since a
|
|
3353
|
+
* copied link looks like a registry install. A missing one is not
|
|
3354
|
+
* installed.
|
|
3355
|
+
* Errors while finding out count as in use. Loom reads overrides,
|
|
3356
|
+
* lockfiles and node_modules from this directory only, so a member of an
|
|
3357
|
+
* enclosing pnpm workspace, whose root holds them, always counts as in use.
|
|
3358
|
+
*/
|
|
3359
|
+
async function findLocalLoomUse(cwd) {
|
|
3360
|
+
try {
|
|
3361
|
+
const { catalogLinks, denoMode, links, packageJson } = await findLocalLoomLinks(cwd);
|
|
3362
|
+
const uses = [...links, ...catalogLinks].map((reason) => ({
|
|
3363
|
+
kind: "link",
|
|
3364
|
+
reason,
|
|
3365
|
+
}));
|
|
3366
|
+
if (!denoMode && !await exists(join(cwd, "pnpm-workspace.yaml"))) {
|
|
3367
|
+
for (let parent = dirname(resolve(cwd)); parent !== dirname(parent); parent = dirname(parent)) {
|
|
3368
|
+
if (await exists(join(parent, "pnpm-workspace.yaml"))) {
|
|
3369
|
+
uses.push({
|
|
3370
|
+
kind: "workspace",
|
|
3371
|
+
reason: `this project is in the pnpm workspace at ${parent}, whose overrides and lockfile Loom does not read`,
|
|
3372
|
+
});
|
|
3373
|
+
break;
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
}
|
|
3377
|
+
const lockfileText = await readTextIfExists(join(cwd, "pnpm-lock.yaml"));
|
|
3378
|
+
const lockfileResolution = lockfileText
|
|
3379
|
+
? getLocalLoomLockfileResolution(lockfileText)
|
|
3380
|
+
: null;
|
|
3381
|
+
if (lockfileResolution) {
|
|
3382
|
+
uses.push({
|
|
3383
|
+
kind: "lockfile",
|
|
3384
|
+
reason: `pnpm-lock.yaml resolves Loom to ${lockfileResolution}`,
|
|
3385
|
+
});
|
|
3386
|
+
}
|
|
3387
|
+
if (await denoLockLinksLoom(cwd)) {
|
|
3388
|
+
uses.push({
|
|
3389
|
+
kind: "lockfile",
|
|
3390
|
+
reason: "deno.lock records a link for Loom",
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
if (await exists(join(cwd, "node_modules", LOOM_DEPENDENCY, "package.json"))) {
|
|
3394
|
+
const proven = denoMode
|
|
3395
|
+
? await findInstalledDenoRegistryLoomVersion(cwd, packageJson)
|
|
3396
|
+
: await findInstalledRegistryLoomVersion(cwd, lockfileText, (await readLocalDevState(cwd))?.localPackagePath);
|
|
3397
|
+
if (!proven) {
|
|
3398
|
+
uses.push({
|
|
3399
|
+
kind: "installed",
|
|
3400
|
+
reason: "node_modules/@gadicc/loom is not provably the published package",
|
|
3401
|
+
});
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
return uses;
|
|
3405
|
+
}
|
|
3406
|
+
catch (error) {
|
|
3407
|
+
return [{
|
|
3408
|
+
kind: "error",
|
|
3409
|
+
reason: `Loom could not tell whether local Loom is in use: ${error.message}`,
|
|
3410
|
+
}];
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
/** The project's active local Loom link, read from its current files. */
|
|
3414
|
+
async function detectLocalDevLink(cwd) {
|
|
3415
|
+
const manifest = await readManifestIfExists(cwd);
|
|
3416
|
+
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
3417
|
+
const denoMode = usesDenoTooling(tooling);
|
|
3418
|
+
const activePnpmOverride = denoMode ? null : getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), await readPackageJsonIfExists(cwd) ?? {});
|
|
3419
|
+
const denoConfig = denoMode
|
|
3420
|
+
? await getDenoConfigForLinks(cwd, tooling)
|
|
3421
|
+
: null;
|
|
3422
|
+
const denoLink = denoConfig
|
|
3423
|
+
? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
|
|
3424
|
+
: null;
|
|
3425
|
+
return {
|
|
3426
|
+
active: activePnpmOverride !== null || denoLink !== null,
|
|
3427
|
+
activePnpmOverride,
|
|
3428
|
+
denoLink,
|
|
3429
|
+
denoMode,
|
|
3430
|
+
};
|
|
3431
|
+
}
|
|
3432
|
+
const NO_LOCAL_DEV_LINK_MESSAGE = "No managed Loom local-dev override is active. Run `loom dev local /path/to/loom` first.";
|
|
3433
|
+
export async function syncLocalDevPackage(cwd, options = {}) {
|
|
3434
|
+
const workspacePath = join(cwd, "pnpm-workspace.yaml");
|
|
3435
|
+
const inactive = (notes = []) => ({
|
|
3436
|
+
buildRan: false,
|
|
3437
|
+
changed: false,
|
|
3438
|
+
notes,
|
|
3439
|
+
packageRefreshRan: false,
|
|
3440
|
+
ranCommands: [],
|
|
3441
|
+
});
|
|
3442
|
+
if (!(await detectLocalDevLink(cwd)).active) {
|
|
3443
|
+
if (options.requireActive)
|
|
3444
|
+
throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
|
|
3445
|
+
return inactive();
|
|
3446
|
+
}
|
|
3447
|
+
const env = options.env ?? process.env;
|
|
3448
|
+
if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1") {
|
|
3449
|
+
// A command started by a running sync (a package lifecycle script, say)
|
|
3450
|
+
// must not wait for the lock its own parent holds.
|
|
3451
|
+
return inactive([
|
|
3452
|
+
"Skipped the local Loom sync inside a running Loom dev sync.",
|
|
3453
|
+
]);
|
|
3454
|
+
}
|
|
3455
|
+
return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), async (lock) => {
|
|
3456
|
+
// Re-read under the lock: while this command waited, the user may have
|
|
3457
|
+
// switched back to the published package or linked another checkout.
|
|
3458
|
+
const { activePnpmOverride, denoLink, denoMode } = await detectLocalDevLink(cwd);
|
|
3459
|
+
if (!activePnpmOverride && !denoLink) {
|
|
3460
|
+
if (options.requireActive)
|
|
3461
|
+
throw new Error(NO_LOCAL_DEV_LINK_MESSAGE);
|
|
3462
|
+
return inactive([
|
|
3463
|
+
"The local Loom link was removed while this command waited.",
|
|
3464
|
+
]);
|
|
3465
|
+
}
|
|
3466
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
3467
|
+
if (!denoMode)
|
|
3468
|
+
await ensurePnpmProject(cwd, packageJson);
|
|
3469
|
+
const commandRunner = options.commandRunner ?? defaultCommandRunner;
|
|
3470
|
+
const childEnv = { ...env, [LOOM_DEV_SYNC_ACTIVE_ENV]: "1" };
|
|
3471
|
+
const childStdio = options.commandOutput === "stderr"
|
|
3472
|
+
? "inherit-stderr"
|
|
3473
|
+
: "inherit";
|
|
3474
|
+
const notes = [];
|
|
3475
|
+
let pnpmVersion = null;
|
|
3476
|
+
// Whether this sync already changed the project, for lost-lock errors.
|
|
3477
|
+
let changesMade = false;
|
|
3478
|
+
let pnpmOverride = activePnpmOverride;
|
|
3479
|
+
if (pnpmOverride) {
|
|
3480
|
+
// Older Loom versions always wrote pnpm-workspace.yaml, which pnpm 10
|
|
3481
|
+
// ignores when package.json has overrides; move it where pnpm reads it.
|
|
3482
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
|
|
3483
|
+
if (placement.conflict)
|
|
3484
|
+
throw new Error(placement.conflict);
|
|
3485
|
+
pnpmVersion = placement.pnpmVersion;
|
|
3486
|
+
await lock.assertHeld(false);
|
|
3487
|
+
const movedFiles = await placePnpmLocalDevOverride(cwd, pnpmOverride.spec, placement.location);
|
|
3488
|
+
if (movedFiles.length) {
|
|
3489
|
+
changesMade = true;
|
|
3490
|
+
notes.push(`Moved the Loom local-dev override to ${formatPnpmOverrideLocation(placement.location)} (updated ${movedFiles.join(", ")}).`, ...placement.notes);
|
|
3491
|
+
}
|
|
3492
|
+
pnpmOverride = {
|
|
3493
|
+
location: placement.location,
|
|
3494
|
+
spec: pnpmOverride.spec,
|
|
3495
|
+
};
|
|
3496
|
+
}
|
|
3497
|
+
const localPackagePath = denoLink?.path ??
|
|
3498
|
+
fileSpecToPath(cwd, pnpmOverride.spec);
|
|
3499
|
+
const sourceRoot = await resolveLocalLoomSourceRoot(localPackagePath);
|
|
3500
|
+
const configuredSpec = (await resolveLoomDependencySpec(cwd, packageJson, { includeDev: true })).effective;
|
|
3501
|
+
const desiredLocalVersion = await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ?? versionFromDependencySpec(configuredSpec) ??
|
|
3502
|
+
await readPackageVersion(localPackagePath);
|
|
3503
|
+
const currentLocalVersion = await readPackageVersion(localPackagePath);
|
|
3504
|
+
const buildEnv = desiredLocalVersion && !env.NPM_PACKAGE_VERSION
|
|
3505
|
+
? { ...childEnv, NPM_PACKAGE_VERSION: desiredLocalVersion }
|
|
3506
|
+
: childEnv;
|
|
3507
|
+
const ranCommands = [];
|
|
3508
|
+
let buildRan = false;
|
|
3509
|
+
if (options.force ||
|
|
3510
|
+
denoMode && currentLocalVersion !== desiredLocalVersion ||
|
|
3511
|
+
await isLocalLoomBuildStale(sourceRoot, localPackagePath)) {
|
|
3512
|
+
if (!sourceRoot) {
|
|
3513
|
+
throw new Error(`Could not find the Loom source checkout for ${localPackagePath}; cannot rebuild the local package.`);
|
|
3514
|
+
}
|
|
3515
|
+
// Run in the Loom checkout with its own deno.json (and so its own
|
|
3516
|
+
// deno.lock). Deno discovers config and lockfile from the working
|
|
3517
|
+
// directory, so a build resolved from the consumer would write a
|
|
3518
|
+
// deno.lock listing the consumer's package.json into its root.
|
|
3519
|
+
await lock.assertHeld(changesMade);
|
|
3520
|
+
const fingerprintBeforeBuild = await computeLoomSourceFingerprint(sourceRoot);
|
|
3521
|
+
await runCommandOrThrow(commandRunner, "deno", ["task", "--config", join(sourceRoot, "deno.json"), "build"], { cwd: sourceRoot, env: buildEnv, stdio: childStdio });
|
|
3522
|
+
ranCommands.push("deno task build");
|
|
3523
|
+
buildRan = true;
|
|
3524
|
+
changesMade = true;
|
|
3525
|
+
await markLegacyLoomBuild(localPackagePath, fingerprintBeforeBuild);
|
|
3526
|
+
}
|
|
3527
|
+
const lockfilePath = join(cwd, "pnpm-lock.yaml");
|
|
3528
|
+
const lockfileBefore = pnpmOverride
|
|
3529
|
+
? await readTextIfExists(lockfilePath)
|
|
3530
|
+
: null;
|
|
3531
|
+
// A lockfile that does not record the override means pnpm has not linked
|
|
3532
|
+
// the local package yet (for example right after `loom dev local`).
|
|
3533
|
+
const overridePending = pnpmOverride !== null &&
|
|
3534
|
+
lockfileBefore !== null &&
|
|
3535
|
+
!lockfileAppliesLocalDevOverride(lockfileBefore, pnpmOverride.spec);
|
|
3536
|
+
const importerBefore = overridePending
|
|
3537
|
+
? getLockfileRootImporterDependency(lockfileBefore, LOOM_DEPENDENCY)
|
|
3538
|
+
: null;
|
|
3539
|
+
if (importerBefore?.version && isLocalPackageSpec(importerBefore.version) &&
|
|
3540
|
+
!isLocalPackageSpec(importerBefore.specifier ?? "")) {
|
|
3541
|
+
// Earlier Loom versions linked with `pnpm update --no-save`, which also
|
|
3542
|
+
// re-resolved Loom's dependencies; this sync cannot tell which of those
|
|
3543
|
+
// lockfile changes were intended.
|
|
3544
|
+
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`.");
|
|
3545
|
+
}
|
|
3546
|
+
const packageRefreshNeeded = buildRan || overridePending ||
|
|
3547
|
+
await findInstalledLocalLoomDifference(cwd, localPackagePath) !== null;
|
|
3548
|
+
let packageRefreshRan = false;
|
|
3549
|
+
const warnings = [];
|
|
3550
|
+
if (options.force || packageRefreshNeeded) {
|
|
3551
|
+
await lock.assertHeld(changesMade);
|
|
3552
|
+
if (denoMode) {
|
|
3553
|
+
await runCommandOrThrow(commandRunner, "deno", ["install"], {
|
|
3554
|
+
cwd,
|
|
3555
|
+
env: childEnv,
|
|
3556
|
+
stdio: childStdio,
|
|
3557
|
+
});
|
|
3558
|
+
ranCommands.push("deno install");
|
|
3559
|
+
}
|
|
3560
|
+
else {
|
|
3561
|
+
// A plain install applies the override and re-imports the local
|
|
3562
|
+
// directory package while reusing every other locked version.
|
|
3563
|
+
// `pnpm update` would re-resolve Loom's dependency subtree instead.
|
|
3564
|
+
await runCommandOrThrow(commandRunner, "pnpm", ["install", "--no-frozen-lockfile"], { cwd, env: childEnv, stdio: childStdio });
|
|
3565
|
+
ranCommands.push("pnpm install --no-frozen-lockfile");
|
|
3566
|
+
const lockfileAfter = await readTextIfExists(lockfilePath);
|
|
3567
|
+
if (lockfileAfter !== null &&
|
|
3568
|
+
!lockfileAppliesLocalDevOverride(lockfileAfter, pnpmOverride.spec)) {
|
|
3569
|
+
throw new Error(formatPnpmOverrideNotAppliedMessage(pnpmOverride, pnpmVersion));
|
|
3570
|
+
}
|
|
3571
|
+
if (lockfileBefore !== null && lockfileAfter !== null) {
|
|
3572
|
+
const duplicates = findNewPeerVariantDuplicates(lockfileBefore, lockfileAfter);
|
|
3573
|
+
if (duplicates.length) {
|
|
3574
|
+
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>\`.`);
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
const remainingDifference = await findInstalledLocalLoomDifference(cwd, localPackagePath);
|
|
3578
|
+
if (remainingDifference) {
|
|
3579
|
+
warnings.push(`node_modules/${LOOM_DEPENDENCY} still differs from ${localPackagePath} after pnpm install (${remainingDifference}).`);
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
packageRefreshRan = true;
|
|
3583
|
+
}
|
|
3584
|
+
await lock.assertHeld(changesMade || packageRefreshRan);
|
|
3585
|
+
const currentWorkspaceText = await readTextIfExists(workspacePath);
|
|
3586
|
+
const currentState = denoMode
|
|
3587
|
+
? await readLocalDevState(cwd)
|
|
3588
|
+
: await getCurrentLocalDevState(cwd, currentWorkspaceText);
|
|
3589
|
+
let state = null;
|
|
3590
|
+
if (buildRan || packageRefreshRan || !currentState) {
|
|
3591
|
+
state = await buildLocalDevState(localPackagePath, sourceRoot, commandRunner, env);
|
|
3592
|
+
// Keep which package.json maps Loom created across syncs.
|
|
3593
|
+
const previous = await readLocalDevState(cwd);
|
|
3594
|
+
if (previous?.createdPackageJsonMaps !== undefined) {
|
|
3595
|
+
state.createdPackageJsonMaps = previous.createdPackageJsonMaps;
|
|
3596
|
+
}
|
|
3597
|
+
if (pnpmOverride?.location === "pnpm-workspace.yaml") {
|
|
3598
|
+
const stateUpdate = setManagedDevStateText(await readTextIfExists(workspacePath), pnpmOverride.spec, state);
|
|
3599
|
+
if (stateUpdate.changed) {
|
|
3600
|
+
await writeTextOrDeleteIfEmpty(workspacePath, stateUpdate.text);
|
|
3601
|
+
}
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
if (state ?? currentState) {
|
|
3605
|
+
await writeLocalDevStateIfChanged(cwd, state ?? currentState);
|
|
3606
|
+
}
|
|
3607
|
+
// Another process may have replaced the package this process loaded,
|
|
3608
|
+
// while it waited for the lock or just before it took it; its
|
|
3609
|
+
// in-process Loom code is then stale.
|
|
3610
|
+
let refreshedElsewhere = false;
|
|
3611
|
+
if (!buildRan && !packageRefreshRan &&
|
|
3612
|
+
options.loadedPackageSignature !== undefined) {
|
|
3613
|
+
const current = options.loadedPackageSignature ===
|
|
3614
|
+
UNKNOWN_PACKAGE_SIGNATURE
|
|
3615
|
+
? UNKNOWN_PACKAGE_SIGNATURE
|
|
3616
|
+
: await computePackageTreeSignature(join(cwd, "node_modules", LOOM_DEPENDENCY)).catch(() => UNKNOWN_PACKAGE_SIGNATURE);
|
|
3617
|
+
// Without both signatures, only a sync this one waited for is
|
|
3618
|
+
// evidence of a replacement; assume one then rather than run code
|
|
3619
|
+
// that may be stale.
|
|
3620
|
+
refreshedElsewhere = current === UNKNOWN_PACKAGE_SIGNATURE
|
|
3621
|
+
? lock.waited
|
|
3622
|
+
: current !== options.loadedPackageSignature;
|
|
3623
|
+
}
|
|
3624
|
+
notes.push(packageRefreshRan
|
|
3625
|
+
? `Local Loom package refreshed from ${localPackagePath}.`
|
|
3626
|
+
: refreshedElsewhere
|
|
3627
|
+
? `Another Loom command refreshed the local Loom package from ${localPackagePath} after this one started.`
|
|
3628
|
+
: `Local Loom package is already fresh: ${localPackagePath}`, ...warnings.map((warning) => `Warning: ${warning}`));
|
|
3629
|
+
const recordedState = state ?? currentState;
|
|
3630
|
+
if (recordedState?.sourceCommit) {
|
|
3631
|
+
notes.push(`Recorded local Loom sync at commit ${recordedState.sourceCommit.slice(0, 12)}${recordedState.sourceDirty ? " with a dirty source tree" : ""}.`);
|
|
3632
|
+
}
|
|
3633
|
+
// What `loom dev published` will check is the build's own stamp.
|
|
3634
|
+
const stamp = sourceRoot
|
|
3635
|
+
? await readLoomBuildStamp(localPackagePath)
|
|
3636
|
+
: null;
|
|
3637
|
+
if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
|
|
3638
|
+
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.`);
|
|
3639
|
+
}
|
|
3640
|
+
else if (sourceRoot && (!stamp || !hasLoomBuildProvenance(stamp))) {
|
|
3641
|
+
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\`.`);
|
|
3642
|
+
}
|
|
3643
|
+
else if (stamp && !stamp.sourceCommit) {
|
|
3644
|
+
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\`.`);
|
|
3645
|
+
}
|
|
3646
|
+
else if (stamp && stamp.sourceDirty !== false) {
|
|
3647
|
+
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\`.`);
|
|
3648
|
+
}
|
|
3649
|
+
return {
|
|
3650
|
+
buildRan,
|
|
3651
|
+
changed: buildRan || packageRefreshRan || refreshedElsewhere,
|
|
3652
|
+
localPackagePath,
|
|
3653
|
+
notes,
|
|
3654
|
+
packageRefreshRan,
|
|
3655
|
+
ranCommands,
|
|
3656
|
+
};
|
|
3657
|
+
}, localDevLockOptions(options));
|
|
3658
|
+
}
|
|
3659
|
+
function localDevLockOptions(options) {
|
|
3660
|
+
return {
|
|
3661
|
+
...options.lock,
|
|
3662
|
+
onWait: (holder) => options.onLockWait?.(`Waiting for another Loom dev sync (${holder
|
|
3663
|
+
? `process ${holder.pid} on ${holder.hostname}`
|
|
3664
|
+
: "unknown process"}) to finish.`),
|
|
2603
3665
|
};
|
|
2604
3666
|
}
|
|
2605
|
-
|
|
3667
|
+
/**
|
|
3668
|
+
* Runs a local-dev config change under the project's sync lock, so it never
|
|
3669
|
+
* interleaves with a sync that reads and rewrites the same files. Commands a
|
|
3670
|
+
* sync started (LOOM_DEV_SYNC_ACTIVE) run without it to avoid waiting on
|
|
3671
|
+
* their own parent.
|
|
3672
|
+
*/
|
|
3673
|
+
async function withProjectLocalDevLock(cwd, options, run) {
|
|
3674
|
+
const env = options.env ?? process.env;
|
|
3675
|
+
if (env[LOOM_DEV_SYNC_ACTIVE_ENV] === "1")
|
|
3676
|
+
return await run();
|
|
3677
|
+
return await withLocalDevLock(join(cwd, LOOM_LOCAL_DEV_LOCK_RELATIVE_PATH), run, localDevLockOptions(options));
|
|
3678
|
+
}
|
|
3679
|
+
export async function useLocalDevPackage(cwd, inputPath, options = {}) {
|
|
3680
|
+
return await withProjectLocalDevLock(cwd, options, () => useLocalDevPackageLocked(cwd, inputPath, options));
|
|
3681
|
+
}
|
|
3682
|
+
async function useLocalDevPackageLocked(cwd, inputPath, options) {
|
|
2606
3683
|
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2607
3684
|
const manifest = await readManifestIfExists(cwd);
|
|
2608
3685
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -2615,8 +3692,23 @@ export async function useLocalDevPackage(cwd, inputPath) {
|
|
|
2615
3692
|
const denoConfig = await getDenoConfigForLinks(cwd, tooling);
|
|
2616
3693
|
const relativeLocalPackagePath = relative(cwd, localPackagePath)
|
|
2617
3694
|
.replaceAll("\\", "/");
|
|
3695
|
+
// A relink replaces the previous Loom link, found by its package name or,
|
|
3696
|
+
// when that package is gone, by the path dev state recorded for it.
|
|
3697
|
+
// Otherwise both stay linked and `loom dev published` removes only one.
|
|
3698
|
+
const recorded = await readLocalDevState(cwd);
|
|
3699
|
+
const previousLinks = [];
|
|
3700
|
+
for (const link of await readDenoLinks(cwd, denoConfig)) {
|
|
3701
|
+
if (link === relativeLocalPackagePath)
|
|
3702
|
+
continue;
|
|
3703
|
+
if (await findLocalLoomDenoLink(cwd, [link]) ||
|
|
3704
|
+
(recorded &&
|
|
3705
|
+
resolve(cwd, link) === resolve(cwd, recorded.localPackagePath))) {
|
|
3706
|
+
previousLinks.push(link);
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
2618
3709
|
const update = await mutateDenoLinks(cwd, denoConfig, {
|
|
2619
3710
|
add: relativeLocalPackagePath,
|
|
3711
|
+
remove: previousLinks,
|
|
2620
3712
|
});
|
|
2621
3713
|
const state = {
|
|
2622
3714
|
dependency: LOOM_DEPENDENCY,
|
|
@@ -2640,26 +3732,216 @@ export async function useLocalDevPackage(cwd, inputPath) {
|
|
|
2640
3732
|
}
|
|
2641
3733
|
await ensurePnpmProject(cwd, packageJson);
|
|
2642
3734
|
const overrideSpec = `file:${localPackagePath}`;
|
|
2643
|
-
const
|
|
2644
|
-
const
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
}
|
|
3735
|
+
const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
3736
|
+
const restoreSpec = loomDependency.catalogName
|
|
3737
|
+
? `${loomDependency.effective ?? publishedSpec} (from the pnpm-workspace.yaml catalog)`
|
|
3738
|
+
: publishedSpec;
|
|
3739
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, options.commandRunner ?? defaultCommandRunner, options.env ?? process.env);
|
|
3740
|
+
if (placement.conflict) {
|
|
3741
|
+
throw new Error(placement.conflict);
|
|
3742
|
+
}
|
|
3743
|
+
const changedFiles = await placePnpmLocalDevOverride(cwd, overrideSpec, placement.location);
|
|
2653
3744
|
return {
|
|
2654
3745
|
changedFiles,
|
|
2655
3746
|
notes: [
|
|
2656
|
-
`Local Loom dev override is active: ${overrideSpec}`,
|
|
3747
|
+
`Local Loom dev override is active in ${formatPnpmOverrideLocation(placement.location)}: ${overrideSpec}`,
|
|
3748
|
+
...placement.notes,
|
|
2657
3749
|
"Run `loom dev sync` to rebuild the local Loom package and refresh this project's pnpm install when needed.",
|
|
2658
|
-
`Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm
|
|
3750
|
+
`Before committing or shipping a published build, run \`loom dev published\`, then \`pnpm install\` to restore ${LOOM_DEPENDENCY}@${restoreSpec}.`,
|
|
2659
3751
|
],
|
|
2660
3752
|
};
|
|
2661
3753
|
}
|
|
3754
|
+
/** Turns a `file:` or `link:` spec into the absolute directory it names. */
|
|
3755
|
+
function localSpecToPath(cwd, spec) {
|
|
3756
|
+
const value = spec.replace(/^(?:file|link):/, "");
|
|
3757
|
+
if (value.startsWith("//"))
|
|
3758
|
+
return new URL(`file:${value}`).pathname;
|
|
3759
|
+
return resolve(cwd, value);
|
|
3760
|
+
}
|
|
3761
|
+
/** The local spec pnpm-lock.yaml resolves Loom to, if it is local. */
|
|
3762
|
+
function getLockfileLocalLoomSpec(lockfileText) {
|
|
3763
|
+
if (!lockfileText)
|
|
3764
|
+
return null;
|
|
3765
|
+
const version = getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)?.version?.replace(/\(.+$/, "");
|
|
3766
|
+
if (version !== undefined) {
|
|
3767
|
+
return isLocalPackageSpec(version) ? version : null;
|
|
3768
|
+
}
|
|
3769
|
+
return getLocalLoomLockfileResolution(lockfileText);
|
|
3770
|
+
}
|
|
3771
|
+
/**
|
|
3772
|
+
* The published Loom version pnpm has installed, when nothing local is
|
|
3773
|
+
* provably installed:
|
|
3774
|
+
* - pnpm-lock.yaml and pnpm's record of node_modules
|
|
3775
|
+
* (`node_modules/.pnpm/lock.yaml`) resolve Loom to the same registry
|
|
3776
|
+
* version, and the installed package has that version;
|
|
3777
|
+
* - `node_modules/@gadicc/loom` resolves into pnpm's virtual store entry for
|
|
3778
|
+
* that registry version, not a `file+`/`link+` entry. pnpm re-points it
|
|
3779
|
+
* before it writes either lockfile, so an interrupted install of a local
|
|
3780
|
+
* build (which carries the registry version) fails this check;
|
|
3781
|
+
* - when `localBuild` exists, the installed copy differs from it.
|
|
3782
|
+
* Null whenever any of that is uncertain, for example with
|
|
3783
|
+
* `node-linker=hoisted`, `enableGlobalVirtualStore` or a custom
|
|
3784
|
+
* `virtual-store-dir`, where no `node_modules/.pnpm` entry tells them apart.
|
|
3785
|
+
*/
|
|
3786
|
+
async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
|
|
3787
|
+
const resolvedVersion = (text) => text
|
|
3788
|
+
? getLockfileRootImporterDependency(text, LOOM_DEPENDENCY)?.version
|
|
3789
|
+
?.replace(/\(.+$/, "") ?? null
|
|
3790
|
+
: null;
|
|
3791
|
+
const version = resolvedVersion(lockfileText);
|
|
3792
|
+
if (!version || isLocalPackageSpec(version))
|
|
3793
|
+
return null;
|
|
3794
|
+
const installedLockfile = await readTextIfExists(join(cwd, "node_modules", ".pnpm", "lock.yaml"));
|
|
3795
|
+
if (resolvedVersion(installedLockfile) !== version)
|
|
3796
|
+
return null;
|
|
3797
|
+
const installedPath = join(cwd, "node_modules", LOOM_DEPENDENCY);
|
|
3798
|
+
if (await readPackageVersion(installedPath) !== version)
|
|
3799
|
+
return null;
|
|
3800
|
+
const [store, installed] = await Promise.all([
|
|
3801
|
+
realpath(join(cwd, "node_modules", ".pnpm")).catch(() => null),
|
|
3802
|
+
realpath(installedPath).catch(() => null),
|
|
3803
|
+
]);
|
|
3804
|
+
if (!store || !installed)
|
|
3805
|
+
return null;
|
|
3806
|
+
const entry = relative(store, installed).split(sep)[0];
|
|
3807
|
+
const registryEntry = `@gadicc+loom@${version}`;
|
|
3808
|
+
if (!(entry === registryEntry || entry.startsWith(`${registryEntry}_`) ||
|
|
3809
|
+
entry.startsWith(`${registryEntry}(`))) {
|
|
3810
|
+
return null;
|
|
3811
|
+
}
|
|
3812
|
+
if (localBuild && await exists(join(localBuild, "package.json")) &&
|
|
3813
|
+
await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
|
|
3814
|
+
return null;
|
|
3815
|
+
}
|
|
3816
|
+
return version;
|
|
3817
|
+
}
|
|
3818
|
+
/**
|
|
3819
|
+
* Lists every local Loom package the project points at, merging entries for
|
|
3820
|
+
* the same directory. For pnpm these are the managed overrides and the
|
|
3821
|
+
* lockfile's local resolution; for Deno, each link whose package is Loom,
|
|
3822
|
+
* or whose path dev state recorded for Loom when that package is gone.
|
|
3823
|
+
* Dev state only identifies such a link; it never proves anything.
|
|
3824
|
+
*/
|
|
3825
|
+
async function collectLocalLoomTargets(cwd, project) {
|
|
3826
|
+
const targets = new Map();
|
|
3827
|
+
const add = async (path, source) => {
|
|
3828
|
+
const key = await realpath(path).catch(() => path);
|
|
3829
|
+
const target = targets.get(key) ?? { path: key, sources: [] };
|
|
3830
|
+
target.sources.push(source);
|
|
3831
|
+
targets.set(key, target);
|
|
3832
|
+
};
|
|
3833
|
+
const denoLinks = [];
|
|
3834
|
+
if (project.denoConfig) {
|
|
3835
|
+
for (const { link, path } of await findLoomDenoLinks(cwd, project.denoConfig)) {
|
|
3836
|
+
denoLinks.push(link);
|
|
3837
|
+
await add(path, `${project.denoConfig} links ${link}`);
|
|
3838
|
+
}
|
|
3839
|
+
return { denoLinks, targets: [...targets.values()] };
|
|
3840
|
+
}
|
|
3841
|
+
const workspaceSpec = getManagedDevOverrideSpec(project.workspaceText);
|
|
3842
|
+
if (workspaceSpec && isManagedPackageJsonLoomOverride(workspaceSpec)) {
|
|
3843
|
+
await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
|
|
3844
|
+
}
|
|
3845
|
+
for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
|
|
3846
|
+
if (spec.startsWith("workspace:")) {
|
|
3847
|
+
throw new Error(`pnpm-workspace.yaml overrides ${key} with ${spec}, a workspace package Loom cannot trace to a build, so it cannot prove that the installed Loom is published. Remove that override and install a published ${LOOM_DEPENDENCY} instead.`);
|
|
3848
|
+
}
|
|
3849
|
+
await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
|
|
3850
|
+
}
|
|
3851
|
+
for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
|
|
3852
|
+
await add(localSpecToPath(cwd, spec), `the ${formatPnpmOverrideLocation(location)} override`);
|
|
3853
|
+
}
|
|
3854
|
+
const lockfileSpec = getLockfileLocalLoomSpec(project.lockfileText);
|
|
3855
|
+
if (lockfileSpec?.startsWith("workspace:")) {
|
|
3856
|
+
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.`);
|
|
3857
|
+
}
|
|
3858
|
+
if (lockfileSpec) {
|
|
3859
|
+
await add(localSpecToPath(cwd, lockfileSpec), "pnpm-lock.yaml");
|
|
3860
|
+
}
|
|
3861
|
+
return { denoLinks, targets: [...targets.values()] };
|
|
3862
|
+
}
|
|
3863
|
+
/**
|
|
3864
|
+
* Proves that the local Loom build this project has installed is published,
|
|
3865
|
+
* from that build's own stamp: the build must record a clean source commit,
|
|
3866
|
+
* the installed copy must match it (and, for pnpm, the lockfile must resolve
|
|
3867
|
+
* to it), and the commit must be covered by a release. Dev state and the
|
|
3868
|
+
* checkout's current git state are never consulted. Throws a refusal that
|
|
3869
|
+
* says what to do otherwise.
|
|
3870
|
+
*/
|
|
3871
|
+
async function proveLocalLoomBuildPublished(cwd, target, options) {
|
|
3872
|
+
const { path } = target;
|
|
3873
|
+
const rerun = "then rerun `loom dev published`";
|
|
3874
|
+
if (!await exists(join(path, "package.json"))) {
|
|
3875
|
+
const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
|
|
3876
|
+
throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
|
|
3877
|
+
? "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`"
|
|
3878
|
+
: options.denoConfig
|
|
3879
|
+
? `Restore that Loom checkout and run \`loom dev sync\`, or link another with \`loom dev local\`; if the app does not need that build, remove the link from ${options.denoConfig} yourself and run \`deno install\``
|
|
3880
|
+
: "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
|
|
3881
|
+
}
|
|
3882
|
+
const stamp = await readLoomBuildStamp(path);
|
|
3883
|
+
if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
|
|
3884
|
+
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.`);
|
|
3885
|
+
}
|
|
3886
|
+
if (!stamp || !hasLoomBuildProvenance(stamp)) {
|
|
3887
|
+
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}.`);
|
|
3888
|
+
}
|
|
3889
|
+
if (stamp.packageDigest !== await computePackageContentDigest(path)) {
|
|
3890
|
+
throw new Error(`${path} was modified after it was built. Run \`loom dev sync --force\`, ${rerun}.`);
|
|
3891
|
+
}
|
|
3892
|
+
if (!stamp.sourceCommit) {
|
|
3893
|
+
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}.`);
|
|
3894
|
+
}
|
|
3895
|
+
const shortCommit = stamp.sourceCommit.slice(0, 12);
|
|
3896
|
+
if (stamp.sourceDirty !== false) {
|
|
3897
|
+
throw new Error(stamp.sourceDirty
|
|
3898
|
+
? `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}.`
|
|
3899
|
+
: `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}.`);
|
|
3900
|
+
}
|
|
3901
|
+
// Deno loads a node_modules copy whenever its effective nodeModulesDir is
|
|
3902
|
+
// auto or manual, and manual is its default next to a package.json. So any
|
|
3903
|
+
// copy is compared unless the config says "none", where Deno loads the
|
|
3904
|
+
// linked directory itself.
|
|
3905
|
+
const nodeModulesDir = options.denoConfig
|
|
3906
|
+
? parseJsonc(await readTextIfExists(join(cwd, options.denoConfig)) ?? "{}", options.denoConfig).nodeModulesDir
|
|
3907
|
+
: undefined;
|
|
3908
|
+
const installedCopy = !options.denoConfig ||
|
|
3909
|
+
(nodeModulesDir !== "none" &&
|
|
3910
|
+
await exists(join(cwd, "node_modules", LOOM_DEPENDENCY, "package.json")));
|
|
3911
|
+
const difference = installedCopy
|
|
3912
|
+
? await findInstalledLocalLoomDifference(cwd, path)
|
|
3913
|
+
: null;
|
|
3914
|
+
if (difference) {
|
|
3915
|
+
throw new Error(`The installed Loom differs from ${path} (${difference}). Run \`loom dev sync\`, ${rerun}.`);
|
|
3916
|
+
}
|
|
3917
|
+
if (!options.denoConfig) {
|
|
3918
|
+
const lockfileSpec = getLockfileLocalLoomSpec(options.lockfileText);
|
|
3919
|
+
if (!lockfileSpec) {
|
|
3920
|
+
throw new Error(`pnpm-lock.yaml does not resolve ${LOOM_DEPENDENCY} to ${path}. Run \`loom dev sync\`, ${rerun}.`);
|
|
3921
|
+
}
|
|
3922
|
+
}
|
|
3923
|
+
const sourceRoot = await resolveLocalLoomSourceRoot(path);
|
|
3924
|
+
if (!sourceRoot) {
|
|
3925
|
+
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}.`);
|
|
3926
|
+
}
|
|
3927
|
+
const publication = await findPublishedLoomPublicationForCommit(sourceRoot, stamp.sourceCommit, options.commandRunner, options.env, options.preferredSpec, `Loom commit ${shortCommit}, which built ${path},`);
|
|
3928
|
+
return {
|
|
3929
|
+
note: publication.reason === "contains-commit"
|
|
3930
|
+
? `The Loom build in ${path} comes from commit ${shortCommit}, which is included in published ${LOOM_DEPENDENCY}@${publication.version}.`
|
|
3931
|
+
: `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.`,
|
|
3932
|
+
publication,
|
|
3933
|
+
};
|
|
3934
|
+
}
|
|
2662
3935
|
export async function usePublishedDevPackage(cwd, options = {}) {
|
|
3936
|
+
// A project that was never linked has nothing a sync could be changing,
|
|
3937
|
+
// so it does not need the lock (or a new `.loom/` directory).
|
|
3938
|
+
if (!(await detectLocalDevLink(cwd)).active &&
|
|
3939
|
+
!await exists(join(cwd, ".loom"))) {
|
|
3940
|
+
return await usePublishedDevPackageLocked(cwd, options);
|
|
3941
|
+
}
|
|
3942
|
+
return await withProjectLocalDevLock(cwd, options, () => usePublishedDevPackageLocked(cwd, options));
|
|
3943
|
+
}
|
|
3944
|
+
async function usePublishedDevPackageLocked(cwd, options) {
|
|
2663
3945
|
const { packageJson } = await readProjectPackageJson(cwd);
|
|
2664
3946
|
const manifest = await readManifestIfExists(cwd);
|
|
2665
3947
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -2673,75 +3955,235 @@ export async function usePublishedDevPackage(cwd, options = {}) {
|
|
|
2673
3955
|
const denoConfig = denoMode
|
|
2674
3956
|
? await getDenoConfigForLinks(cwd, tooling)
|
|
2675
3957
|
: null;
|
|
2676
|
-
const
|
|
2677
|
-
? await findLocalLoomDenoLink(cwd, await readDenoLinks(cwd, denoConfig))
|
|
2678
|
-
: null;
|
|
2679
|
-
const activeOverrideSpec = denoLink?.link ??
|
|
2680
|
-
getManagedDevOverrideSpec(workspaceText);
|
|
2681
|
-
const localLockfileResolution = denoMode
|
|
3958
|
+
const lockfileText = denoMode
|
|
2682
3959
|
? null
|
|
2683
|
-
: await
|
|
2684
|
-
const
|
|
2685
|
-
?
|
|
2686
|
-
:
|
|
3960
|
+
: await readTextIfExists(join(cwd, "pnpm-lock.yaml"));
|
|
3961
|
+
const localLockfileResolution = lockfileText
|
|
3962
|
+
? getLocalLoomLockfileResolution(lockfileText)
|
|
3963
|
+
: null;
|
|
2687
3964
|
const notes = [];
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
3965
|
+
const { denoLinks, targets } = await collectLocalLoomTargets(cwd, {
|
|
3966
|
+
denoConfig,
|
|
3967
|
+
lockfileText,
|
|
3968
|
+
packageJson,
|
|
3969
|
+
workspaceText,
|
|
3970
|
+
});
|
|
3971
|
+
if (targets.length > 1) {
|
|
3972
|
+
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\`.`);
|
|
3973
|
+
}
|
|
3974
|
+
// A `catalog:` reference keeps its version in pnpm-workspace.yaml, which is
|
|
3975
|
+
// where the published version has to go too.
|
|
3976
|
+
const catalogDependency = denoMode
|
|
3977
|
+
? null
|
|
3978
|
+
: await resolveLoomDependencySpec(cwd, packageJson);
|
|
3979
|
+
const catalog = catalogDependency?.catalogName ? catalogDependency : null;
|
|
3980
|
+
let publishedSpec = catalog
|
|
3981
|
+
? catalog.effective && !isLocalPackageSpec(catalog.effective)
|
|
3982
|
+
? catalog.effective
|
|
3983
|
+
: DEFAULT_LOOM_RANGE
|
|
3984
|
+
: getPublishedLoomDependencySpec(packageJson);
|
|
3985
|
+
// A pnpm link that was never installed left nothing local to prove: the
|
|
3986
|
+
// app still runs the published Loom it had. Deno reads a link directly or
|
|
3987
|
+
// copies it into node_modules on its next install or run, so Deno links
|
|
3988
|
+
// are always proved.
|
|
3989
|
+
const registryVersion = denoMode || targets.length !== 1
|
|
3990
|
+
? null
|
|
3991
|
+
: await findInstalledRegistryLoomVersion(cwd, lockfileText, targets[0].path);
|
|
3992
|
+
if (registryVersion) {
|
|
3993
|
+
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}.`);
|
|
3994
|
+
}
|
|
3995
|
+
else if (targets.length === 1) {
|
|
3996
|
+
const proof = await proveLocalLoomBuildPublished(cwd, targets[0], {
|
|
3997
|
+
commandRunner,
|
|
3998
|
+
denoConfig,
|
|
3999
|
+
env,
|
|
4000
|
+
lockfileText,
|
|
4001
|
+
preferredSpec: publishedSpec,
|
|
4002
|
+
});
|
|
4003
|
+
publishedSpec = proof.publication.version;
|
|
4004
|
+
notes.push(proof.note);
|
|
4005
|
+
}
|
|
4006
|
+
const changedFiles = [];
|
|
4007
|
+
let catalogChanged = false;
|
|
4008
|
+
if (catalog) {
|
|
4009
|
+
const currentText = await readTextIfExists(workspacePath);
|
|
4010
|
+
const entry = findLoomCatalogEntry(currentText, catalog.catalogName);
|
|
4011
|
+
const unreadable = entry
|
|
4012
|
+
? null
|
|
4013
|
+
: findUnreadableLoomCatalog(currentText, catalog.catalogName);
|
|
4014
|
+
if (unreadable) {
|
|
4015
|
+
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.`);
|
|
2696
4016
|
}
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
if (publication.reason === "contains-commit") {
|
|
2700
|
-
notes.push(`Local Loom commit ${state.sourceCommit.slice(0, 12)} is included in published ${LOOM_DEPENDENCY}@${publication.version}.`);
|
|
4017
|
+
else if (!entry) {
|
|
4018
|
+
notes.push(`package.json uses \`${catalog.raw}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog; add \`${LOOM_DEPENDENCY}: ${publishedSpec}\` there.`);
|
|
2701
4019
|
}
|
|
2702
|
-
else {
|
|
2703
|
-
|
|
4020
|
+
else if (entry.spec !== publishedSpec) {
|
|
4021
|
+
const updated = setLoomCatalogEntryText(currentText, entry, publishedSpec);
|
|
4022
|
+
if (updated !== null) {
|
|
4023
|
+
await writeFile(workspacePath, updated, "utf8");
|
|
4024
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
4025
|
+
catalogChanged = true;
|
|
4026
|
+
}
|
|
2704
4027
|
}
|
|
2705
4028
|
}
|
|
2706
|
-
else
|
|
2707
|
-
|
|
4029
|
+
else {
|
|
4030
|
+
const dependencyUpdate = await mutateProjectDependencies(cwd, tooling.dependencies, {
|
|
4031
|
+
dependencies: { [LOOM_DEPENDENCY]: publishedSpec },
|
|
4032
|
+
replace: true,
|
|
4033
|
+
});
|
|
4034
|
+
if (dependencyUpdate.changed) {
|
|
4035
|
+
changedFiles.push(dependencyUpdate.config);
|
|
4036
|
+
}
|
|
2708
4037
|
}
|
|
2709
|
-
const
|
|
2710
|
-
|
|
2711
|
-
replace: true,
|
|
2712
|
-
});
|
|
2713
|
-
const denoUpdate = denoConfig && denoLink
|
|
2714
|
-
? await mutateDenoLinks(cwd, denoConfig, { remove: denoLink.link })
|
|
4038
|
+
const denoUpdate = denoConfig && denoLinks.length
|
|
4039
|
+
? await mutateDenoLinks(cwd, denoConfig, { remove: denoLinks })
|
|
2715
4040
|
: null;
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
4041
|
+
let overrideRemoved = false;
|
|
4042
|
+
if (denoMode) {
|
|
4043
|
+
if (denoUpdate?.changed) {
|
|
4044
|
+
// The dependency pin may have changed the same file already.
|
|
4045
|
+
if (!changedFiles.includes(denoConfig))
|
|
4046
|
+
changedFiles.push(denoConfig);
|
|
4047
|
+
overrideRemoved = true;
|
|
4048
|
+
}
|
|
2722
4049
|
}
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
changedFiles.
|
|
4050
|
+
else {
|
|
4051
|
+
for (const file of await clearPnpmLocalDevOverrides(cwd)) {
|
|
4052
|
+
if (!changedFiles.includes(file))
|
|
4053
|
+
changedFiles.push(file);
|
|
4054
|
+
overrideRemoved = true;
|
|
4055
|
+
}
|
|
4056
|
+
// Entries written by hand point pnpm at a local Loom just the same.
|
|
4057
|
+
const workspaceNow = await readTextIfExists(workspacePath);
|
|
4058
|
+
if (workspaceNow && !getManagedDevOverrideBlockText(workspaceNow)) {
|
|
4059
|
+
const update = removeUnmanagedPnpmWorkspaceLoomOverrides(workspaceNow);
|
|
4060
|
+
if (update.changed) {
|
|
4061
|
+
await writeTextOrDeleteIfEmpty(workspacePath, update.text);
|
|
4062
|
+
if (!changedFiles.includes("pnpm-workspace.yaml")) {
|
|
4063
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
4064
|
+
}
|
|
4065
|
+
overrideRemoved = true;
|
|
4066
|
+
}
|
|
4067
|
+
for (const { key, spec } of update.kept) {
|
|
4068
|
+
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\`.`);
|
|
4069
|
+
}
|
|
2726
4070
|
}
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
4071
|
+
}
|
|
4072
|
+
if (denoMode) {
|
|
4073
|
+
if (overrideRemoved || localLockfileResolution) {
|
|
4074
|
+
notes.push(`Run \`deno install\` in this project to return node_modules and deno.lock to published ${LOOM_DEPENDENCY}@${publishedSpec}.`);
|
|
2730
4075
|
}
|
|
2731
4076
|
}
|
|
2732
|
-
if (
|
|
2733
|
-
|
|
2734
|
-
?
|
|
2735
|
-
:
|
|
4077
|
+
else if (overrideRemoved || localLockfileResolution) {
|
|
4078
|
+
const importer = lockfileText
|
|
4079
|
+
? getLockfileRootImporterDependency(lockfileText, LOOM_DEPENDENCY)
|
|
4080
|
+
: null;
|
|
4081
|
+
// Earlier Loom versions linked through `pnpm update --no-save`, which
|
|
4082
|
+
// leaves the published specifier with a local version. While that
|
|
4083
|
+
// specifier still matches package.json, pnpm install treats the lockfile
|
|
4084
|
+
// as up to date and keeps the local resolution.
|
|
4085
|
+
const specifierUnchanged = catalog
|
|
4086
|
+
? importer?.specifier === catalog.raw && !catalogChanged
|
|
4087
|
+
: importer?.specifier === publishedSpec;
|
|
4088
|
+
const legacyLocalResolution = importer?.version &&
|
|
4089
|
+
isLocalPackageSpec(importer.version) && specifierUnchanged
|
|
4090
|
+
? localLockfileResolution ?? importer.version
|
|
4091
|
+
: null;
|
|
4092
|
+
if (legacyLocalResolution && catalog) {
|
|
4093
|
+
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\`.`);
|
|
4094
|
+
}
|
|
4095
|
+
else if (legacyLocalResolution) {
|
|
4096
|
+
const pinCommand = isExactSemverVersion(publishedSpec)
|
|
4097
|
+
? `\`${dependencyRefreshCommand(tooling.dependencies, LOOM_DEPENDENCY, publishedSpec, { pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd) })}\``
|
|
4098
|
+
: `\`pnpm add --save-exact ${LOOM_DEPENDENCY}@<version>\` with the exact version to ship`;
|
|
4099
|
+
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).`);
|
|
4100
|
+
}
|
|
4101
|
+
else {
|
|
4102
|
+
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.`);
|
|
4103
|
+
if (localLockfileResolution) {
|
|
4104
|
+
notes.push(`pnpm-lock.yaml still resolves ${LOOM_DEPENDENCY} to ${localLockfileResolution} until that install is run.`);
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
2736
4107
|
}
|
|
2737
|
-
|
|
2738
|
-
|
|
4108
|
+
// Once nothing local can be in use, the sync record describes code the app
|
|
4109
|
+
// no longer runs; kept, `loom check` would go on checking a commit in a
|
|
4110
|
+
// checkout that may since be gone. Until then (typically until the
|
|
4111
|
+
// `pnpm install` this command asks for), it stays. Created-map flags were
|
|
4112
|
+
// cleared above.
|
|
4113
|
+
if ((await findLocalLoomUse(cwd)).length === 0) {
|
|
4114
|
+
await rm(join(cwd, LOOM_LOCAL_DEV_STATE_RELATIVE_PATH), { force: true });
|
|
2739
4115
|
}
|
|
2740
4116
|
return {
|
|
2741
4117
|
changedFiles,
|
|
2742
4118
|
notes,
|
|
2743
4119
|
};
|
|
2744
4120
|
}
|
|
4121
|
+
/** Removes every managed local Loom override from a pnpm project. */
|
|
4122
|
+
async function clearPnpmLocalDevOverrides(cwd) {
|
|
4123
|
+
const changedFiles = [];
|
|
4124
|
+
const workspacePath = join(cwd, "pnpm-workspace.yaml");
|
|
4125
|
+
const workspaceUpdate = clearPnpmWorkspaceLocalDevText(await readTextIfExists(workspacePath));
|
|
4126
|
+
if (workspaceUpdate.changed) {
|
|
4127
|
+
await writeTextOrDeleteIfEmpty(workspacePath, workspaceUpdate.text);
|
|
4128
|
+
changedFiles.push("pnpm-workspace.yaml");
|
|
4129
|
+
}
|
|
4130
|
+
for (const { field } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
|
|
4131
|
+
if (await removePackageJsonLoomOverride(cwd, field) &&
|
|
4132
|
+
!changedFiles.includes("package.json")) {
|
|
4133
|
+
changedFiles.push("package.json");
|
|
4134
|
+
}
|
|
4135
|
+
}
|
|
4136
|
+
// Flags for maps whose Loom entry was already gone would otherwise
|
|
4137
|
+
// outlive the link and claim maps the project has since added.
|
|
4138
|
+
await writeCreatedPackageJsonMaps(cwd, {});
|
|
4139
|
+
return changedFiles;
|
|
4140
|
+
}
|
|
4141
|
+
function getRawPackageJsonMap(packageJson, field) {
|
|
4142
|
+
return field === "resolutions"
|
|
4143
|
+
? packageJson.resolutions
|
|
4144
|
+
: packageJson.pnpm?.overrides;
|
|
4145
|
+
}
|
|
4146
|
+
async function readCreatedPackageJsonMaps(cwd) {
|
|
4147
|
+
return { ...(await readLocalDevState(cwd))?.createdPackageJsonMaps };
|
|
4148
|
+
}
|
|
4149
|
+
async function writeCreatedPackageJsonMaps(cwd, created, overrideSpec) {
|
|
4150
|
+
const state = await readLocalDevState(cwd);
|
|
4151
|
+
const { createdPackageJsonMaps: _previous, ...rest } = state ?? {
|
|
4152
|
+
dependency: LOOM_DEPENDENCY,
|
|
4153
|
+
localPackagePath: overrideSpec ? fileSpecToPath(cwd, overrideSpec) : "",
|
|
4154
|
+
syncedAt: new Date().toISOString(),
|
|
4155
|
+
version: 1,
|
|
4156
|
+
};
|
|
4157
|
+
if (!state && Object.keys(created).length === 0)
|
|
4158
|
+
return;
|
|
4159
|
+
await writeLocalDevStateIfChanged(cwd, Object.keys(created).length
|
|
4160
|
+
? { ...rest, createdPackageJsonMaps: created }
|
|
4161
|
+
: rest);
|
|
4162
|
+
}
|
|
4163
|
+
/**
|
|
4164
|
+
* Removes Loom's managed (`file:`) override from one package.json map with
|
|
4165
|
+
* a minimal text edit. The map (and the `pnpm` object) is removed as well
|
|
4166
|
+
* only when it ends up empty and dev state records that Loom created it;
|
|
4167
|
+
* maps the project already had, or whose origin is unknown, always stay.
|
|
4168
|
+
* Never writes back a whole-file snapshot. Returns whether package.json
|
|
4169
|
+
* changed.
|
|
4170
|
+
*/
|
|
4171
|
+
async function removePackageJsonLoomOverride(cwd, field) {
|
|
4172
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
4173
|
+
if (!isManagedPackageJsonLoomOverride(getPackageJsonOverrideMap(packageJson, field)[LOOM_DEPENDENCY])) {
|
|
4174
|
+
return false;
|
|
4175
|
+
}
|
|
4176
|
+
const created = await readCreatedPackageJsonMaps(cwd);
|
|
4177
|
+
const update = await mutatePackageJsonOverride(cwd, field, LOOM_DEPENDENCY, undefined, {
|
|
4178
|
+
removeEmptyMap: created[field] === true,
|
|
4179
|
+
removeEmptyPnpm: field === "pnpm.overrides" && created.pnpm === true,
|
|
4180
|
+
});
|
|
4181
|
+
delete created[field];
|
|
4182
|
+
if (field === "pnpm.overrides")
|
|
4183
|
+
delete created.pnpm;
|
|
4184
|
+
await writeCreatedPackageJsonMaps(cwd, created);
|
|
4185
|
+
return update.changed;
|
|
4186
|
+
}
|
|
2745
4187
|
async function ensureManagedAgentsFile(cwd) {
|
|
2746
4188
|
const relativePath = "AGENTS.md";
|
|
2747
4189
|
const agentsPath = join(cwd, relativePath);
|
|
@@ -2956,7 +4398,15 @@ async function checkManagedAgentsFile(cwd) {
|
|
|
2956
4398
|
warnings: [],
|
|
2957
4399
|
};
|
|
2958
4400
|
}
|
|
2959
|
-
|
|
4401
|
+
/** Matches override keys that select Loom, including pnpm/yarn selectors. */
|
|
4402
|
+
function overrideKeyTargetsLoom(key) {
|
|
4403
|
+
const target = key.split(">").pop().trim();
|
|
4404
|
+
return target === LOOM_DEPENDENCY ||
|
|
4405
|
+
target.startsWith(`${LOOM_DEPENDENCY}@`) ||
|
|
4406
|
+
target.endsWith(`/${LOOM_DEPENDENCY}`) ||
|
|
4407
|
+
target.includes(`/${LOOM_DEPENDENCY}@`);
|
|
4408
|
+
}
|
|
4409
|
+
async function checkManagedLocalDevOverride(cwd, production, commandRunner, env) {
|
|
2960
4410
|
const manifest = await readManifestIfExists(cwd);
|
|
2961
4411
|
let denoLink = null;
|
|
2962
4412
|
let denoConfig = null;
|
|
@@ -2971,8 +4421,15 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
|
|
|
2971
4421
|
// The main project tooling check reports invalid configuration separately.
|
|
2972
4422
|
}
|
|
2973
4423
|
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
2974
|
-
const
|
|
2975
|
-
|
|
4424
|
+
const denoMode = denoConfig !== null;
|
|
4425
|
+
const packageJson = denoMode ? null : await readPackageJsonIfExists(cwd);
|
|
4426
|
+
// Any local spec for Loom in an override map, whoever wrote it and
|
|
4427
|
+
// whatever selector it uses, is a local-dev link and must not ship; so is
|
|
4428
|
+
// a Deno link to Loom, even one whose package is gone. The same finder
|
|
4429
|
+
// decides whether a sync record is stale. A local catalog entry has its
|
|
4430
|
+
// own, clearer issue.
|
|
4431
|
+
const links = await findLocalLoomLinks(cwd).then((found) => found.links, () => []);
|
|
4432
|
+
if (!links.length && !denoLink) {
|
|
2976
4433
|
return {
|
|
2977
4434
|
issues: [],
|
|
2978
4435
|
suggestions: [],
|
|
@@ -2981,19 +4438,43 @@ async function checkManagedLocalDevOverride(cwd, production = false) {
|
|
|
2981
4438
|
}
|
|
2982
4439
|
const location = denoLink
|
|
2983
4440
|
? `${denoConfig} links: ${denoLink.link}`
|
|
2984
|
-
:
|
|
2985
|
-
const restore =
|
|
4441
|
+
: links[0];
|
|
4442
|
+
const restore = denoMode
|
|
2986
4443
|
? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
|
|
2987
|
-
:
|
|
4444
|
+
: "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
|
|
4445
|
+
const warnings = [];
|
|
4446
|
+
const suggestions = [restore];
|
|
4447
|
+
const activePnpmOverride = packageJson
|
|
4448
|
+
? getActivePnpmLocalDevOverride(workspaceText, packageJson)
|
|
4449
|
+
: null;
|
|
4450
|
+
if (activePnpmOverride && packageJson) {
|
|
4451
|
+
// Use the same placement decision as `loom dev sync`, so the advice here
|
|
4452
|
+
// is exactly what the next sync does.
|
|
4453
|
+
const placement = await resolvePnpmLocalDevOverrideLocation(cwd, packageJson, commandRunner, env);
|
|
4454
|
+
const pnpmLabel = placement.pnpmVersion === null
|
|
4455
|
+
? "pnpm (version unknown, assumed 10.5.1 or newer)"
|
|
4456
|
+
: `pnpm ${placement.pnpmVersion}`;
|
|
4457
|
+
if (placement.conflict) {
|
|
4458
|
+
warnings.push(placement.conflict);
|
|
4459
|
+
}
|
|
4460
|
+
else if (activePnpmOverride.location === "pnpm-workspace.yaml"
|
|
4461
|
+
? placement.location !== "pnpm-workspace.yaml"
|
|
4462
|
+
: placement.location === "pnpm-workspace.yaml" &&
|
|
4463
|
+
placement.pnpmMajor !== null && placement.pnpmMajor >= 11) {
|
|
4464
|
+
warnings.push(`${pnpmLabel} does not apply the Loom override in ${formatPnpmOverrideLocation(activePnpmOverride.location)}, so this app may still use the published Loom package.`);
|
|
4465
|
+
suggestions.push(`Run \`loom dev sync\` to move the override to ${formatPnpmOverrideLocation(placement.location)}, where pnpm applies it.`);
|
|
4466
|
+
}
|
|
4467
|
+
}
|
|
2988
4468
|
return {
|
|
2989
4469
|
issues: production
|
|
2990
4470
|
? [
|
|
2991
4471
|
`Local Loom dev override is active in ${location}`,
|
|
2992
4472
|
]
|
|
2993
4473
|
: [],
|
|
2994
|
-
suggestions
|
|
2995
|
-
warnings: production ?
|
|
4474
|
+
suggestions,
|
|
4475
|
+
warnings: production ? warnings : [
|
|
2996
4476
|
`Local Loom dev override is active in ${location}`,
|
|
4477
|
+
...warnings,
|
|
2997
4478
|
],
|
|
2998
4479
|
};
|
|
2999
4480
|
}
|
|
@@ -3032,7 +4513,6 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3032
4513
|
const issues = [];
|
|
3033
4514
|
const suggestions = new Set();
|
|
3034
4515
|
const warnings = [];
|
|
3035
|
-
const dependency = packageJson.dependencies?.[LOOM_DEPENDENCY];
|
|
3036
4516
|
const production = options.production;
|
|
3037
4517
|
const projectMetadata = await readProjectPackageMetadata(cwd);
|
|
3038
4518
|
let dependencyTooling = {
|
|
@@ -3046,16 +4526,82 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3046
4526
|
catch {
|
|
3047
4527
|
// The main tooling check owns the validation error; release hints can fall back.
|
|
3048
4528
|
}
|
|
4529
|
+
// A pnpm `catalog:` reference pins Loom in pnpm-workspace.yaml instead.
|
|
4530
|
+
// Other managers' catalogs (Yarn 4) are not read.
|
|
4531
|
+
const loomDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
4532
|
+
const dependency = dependencyTooling.manager === "pnpm"
|
|
4533
|
+
? loomDependency.effective
|
|
4534
|
+
: loomDependency.raw;
|
|
3049
4535
|
const localLockfileResolution = await getProjectLocalLoomLockfileResolution(cwd);
|
|
3050
4536
|
const devState = await readLocalDevState(cwd);
|
|
4537
|
+
const refreshOptions = {
|
|
4538
|
+
pnpmWorkspaceRoot: await pnpmWorkspaceDeclaresPackages(cwd),
|
|
4539
|
+
};
|
|
4540
|
+
const catalogName = dependencyTooling.manager === "pnpm"
|
|
4541
|
+
? loomDependency.catalogName
|
|
4542
|
+
: null;
|
|
4543
|
+
const pinLocation = catalogName
|
|
4544
|
+
? `the pnpm-workspace.yaml \`${loomDependency.catalogEntry?.label ?? "catalog:"}\` map`
|
|
4545
|
+
: dependencyTooling.config;
|
|
4546
|
+
// A pnpm pin change is a manual package.json edit plus `pnpm install`,
|
|
4547
|
+
// which gives the same lockfile as `pnpm add --save-exact` without
|
|
4548
|
+
// re-sorting package.json. Only a lockfile an older `pnpm update --no-save`
|
|
4549
|
+
// link left behind, under an unchanged pin, needs `pnpm add`.
|
|
4550
|
+
const pinSuggestion = (version) => catalogName
|
|
4551
|
+
? formatLoomCatalogPinAdvice(loomDependency.catalogEntry, catalogName, version)
|
|
4552
|
+
: dependencyTooling.manager !== "pnpm"
|
|
4553
|
+
? `Run ${dependencyRefreshCommand(dependencyTooling, LOOM_DEPENDENCY, version, refreshOptions)}.`
|
|
4554
|
+
: version === dependency
|
|
4555
|
+
? `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).`
|
|
4556
|
+
: `Set ${LOOM_DEPENDENCY} to ${version} in package.json, then run \`pnpm install\`.`;
|
|
4557
|
+
// While the override is active it forces the local package whatever the
|
|
4558
|
+
// pin says, so it has to be removed before any refresh can help.
|
|
4559
|
+
const pnpmOverrideActive = dependencyTooling.manager === "pnpm" &&
|
|
4560
|
+
getActivePnpmLocalDevOverride(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), packageJson) !== null;
|
|
3051
4561
|
if (localLockfileResolution) {
|
|
3052
4562
|
addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
|
|
3053
4563
|
suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
|
|
3054
4564
|
}
|
|
3055
|
-
|
|
4565
|
+
// The sync record only matters while the app can still run local Loom
|
|
4566
|
+
// code. Without a link, an override or a local lockfile resolution, the
|
|
4567
|
+
// app runs a published Loom, and the record (perhaps naming a checkout
|
|
4568
|
+
// that is gone) is stale.
|
|
4569
|
+
const localLoomUses = await findLocalLoomUse(cwd);
|
|
4570
|
+
const localLoomInUse = localLoomUses.length > 0;
|
|
4571
|
+
// Only an installed copy Loom cannot prove published, with no link or
|
|
4572
|
+
// lockfile pointing at local Loom, is too weak to fail a release by
|
|
4573
|
+
// itself: the record's findings stay warnings then.
|
|
4574
|
+
const recordGatesRelease = production &&
|
|
4575
|
+
localLoomUses.some((use) => use.kind !== "installed");
|
|
4576
|
+
if (devState?.sourceCommit && !localLoomInUse) {
|
|
4577
|
+
const shortCommit = devState.sourceCommit.slice(0, 12);
|
|
4578
|
+
warnings.push(`${LOOM_LOCAL_DEV_STATE_RELATIVE_PATH} still records a local Loom sync at commit ${shortCommit}, but no local Loom is linked, locked or installed any more, so it is stale and can be deleted.`);
|
|
4579
|
+
// The app may still rely on what that sync contained: advise, never
|
|
4580
|
+
// fail, when a newer release covers it than the app pins. A checkout
|
|
4581
|
+
// that is gone is not looked up at all.
|
|
4582
|
+
if (devState.sourceRoot && !devState.sourceDirty &&
|
|
4583
|
+
dependency && isExactSemverVersion(dependency) &&
|
|
4584
|
+
await exists(devState.sourceRoot)) {
|
|
4585
|
+
const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, dependency);
|
|
4586
|
+
if (publication.status === "published" &&
|
|
4587
|
+
publication.version !== dependency) {
|
|
4588
|
+
warnings.push(`This app was last synced against Loom commit ${shortCommit}; ${publication.reason === "package-equivalent"
|
|
4589
|
+
? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
|
|
4590
|
+
: `it is published as ${LOOM_DEPENDENCY}@${publication.version}`}, but ${pinLocation} is pinned to ${dependency}.`);
|
|
4591
|
+
suggestions.add(pinSuggestion(publication.version));
|
|
4592
|
+
}
|
|
4593
|
+
}
|
|
4594
|
+
}
|
|
4595
|
+
else if (devState?.sourceCommit && devState.sourceRoot &&
|
|
4596
|
+
!devState.sourceDirty && !await exists(devState.sourceRoot)) {
|
|
4597
|
+
// A deleted checkout is not evidence of unpublished code; the active
|
|
4598
|
+
// link or lockfile already fails the release check on its own.
|
|
4599
|
+
warnings.push(`This app was last synced against Loom commit ${devState.sourceCommit.slice(0, 12)} in ${devState.sourceRoot}, which no longer exists, so Loom cannot check that commit.`);
|
|
4600
|
+
}
|
|
4601
|
+
else if (devState?.sourceCommit) {
|
|
3056
4602
|
const shortCommit = devState.sourceCommit.slice(0, 12);
|
|
3057
4603
|
if (devState.sourceDirty) {
|
|
3058
|
-
addReleaseCheckMessage(issues, warnings,
|
|
4604
|
+
addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
|
|
3059
4605
|
suggestions.add("Commit or discard the Loom changes, rerun `loom dev sync`, and publish Loom if the app depends on those changes.");
|
|
3060
4606
|
}
|
|
3061
4607
|
else if (!devState.sourceRoot) {
|
|
@@ -3065,11 +4611,11 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3065
4611
|
const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, isExactSemverVersion(dependency ?? "") ? dependency : undefined);
|
|
3066
4612
|
switch (publication.status) {
|
|
3067
4613
|
case "not-on-origin-main":
|
|
3068
|
-
addReleaseCheckMessage(issues, warnings,
|
|
4614
|
+
addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
|
|
3069
4615
|
suggestions.add("Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun `loom dev published`.");
|
|
3070
4616
|
break;
|
|
3071
4617
|
case "no-release-tag":
|
|
3072
|
-
addReleaseCheckMessage(issues, warnings,
|
|
4618
|
+
addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, but no published Loom version contains that commit or matches its package-relevant files.`);
|
|
3073
4619
|
suggestions.add("Publish Loom first, fetch tags, then rerun `loom dev published`.");
|
|
3074
4620
|
break;
|
|
3075
4621
|
case "published":
|
|
@@ -3079,8 +4625,10 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3079
4625
|
"package-equivalent"
|
|
3080
4626
|
? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
|
|
3081
4627
|
: `it is published as ${LOOM_DEPENDENCY}@${publication.version}`;
|
|
3082
|
-
addReleaseCheckMessage(issues, warnings,
|
|
3083
|
-
suggestions.add(
|
|
4628
|
+
addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
|
|
4629
|
+
suggestions.add(pnpmOverrideActive
|
|
4630
|
+
? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
|
|
4631
|
+
: pinSuggestion(publication.version));
|
|
3084
4632
|
}
|
|
3085
4633
|
else if (localLockfileResolution) {
|
|
3086
4634
|
const publicationDescription = publication.reason ===
|
|
@@ -3088,7 +4636,13 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3088
4636
|
? `has no package-relevant changes after ${publication.tag}, so ${LOOM_DEPENDENCY}@${publication.version} covers it`
|
|
3089
4637
|
: `is published as ${LOOM_DEPENDENCY}@${publication.version}`;
|
|
3090
4638
|
warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
|
|
3091
|
-
suggestions.add(
|
|
4639
|
+
suggestions.add(pnpmOverrideActive
|
|
4640
|
+
? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
|
|
4641
|
+
: catalogName && dependency === publication.version
|
|
4642
|
+
// pnpm keeps a local resolution while the catalog version
|
|
4643
|
+
// it was linked under is unchanged.
|
|
4644
|
+
? "Restore pnpm-lock.yaml from git and run `pnpm install`."
|
|
4645
|
+
: pinSuggestion(publication.version));
|
|
3092
4646
|
}
|
|
3093
4647
|
break;
|
|
3094
4648
|
}
|
|
@@ -3113,8 +4667,12 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
|
|
|
3113
4667
|
else {
|
|
3114
4668
|
const installedPackage = parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"));
|
|
3115
4669
|
if (installedPackage.version !== dependency) {
|
|
3116
|
-
issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${
|
|
3117
|
-
suggestions.add(
|
|
4670
|
+
issues.push(`Installed ${LOOM_DEPENDENCY} version ${installedPackage.version} does not match ${pinLocation} ${dependency}.`);
|
|
4671
|
+
suggestions.add(pnpmOverrideActive
|
|
4672
|
+
? "Run `loom dev published`, then run `pnpm install`."
|
|
4673
|
+
: dependencyTooling.manager === "pnpm"
|
|
4674
|
+
? "Run `pnpm install`."
|
|
4675
|
+
: pinSuggestion(dependency));
|
|
3118
4676
|
}
|
|
3119
4677
|
}
|
|
3120
4678
|
}
|
|
@@ -4692,6 +6250,18 @@ import { apiKeyPolicy } from "${toAliasImportPath(config.modules.policyModule)}"
|
|
|
4692
6250
|
import { apiKeyAuditRepository } from "${toAliasImportPath(config.modules.repositoryModule)}";
|
|
4693
6251
|
|
|
4694
6252
|
// Generated verifier stub: adapt Better Auth verifyApiKey() exactly once here.
|
|
6253
|
+
// Replace it with Loom's shared verifier, which checks the requested
|
|
6254
|
+
// permission itself so a scope miss is denied as insufficient_permission:
|
|
6255
|
+
//
|
|
6256
|
+
// import { createBetterAuthApiKeyVerifier } from "@gadicc/loom/apiKeys";
|
|
6257
|
+
// import { auth } from "<the app's Better Auth module>";
|
|
6258
|
+
// import { apiKeyScopes } from "<the app's defineApiKeyScopes registry>";
|
|
6259
|
+
//
|
|
6260
|
+
// export const apiKeyVerifier = createBetterAuthApiKeyVerifier({
|
|
6261
|
+
// auth,
|
|
6262
|
+
// configId: "default", // the api-key plugin configId these keys use
|
|
6263
|
+
// scopes: apiKeyScopes,
|
|
6264
|
+
// });
|
|
4695
6265
|
export const apiKeyVerifier: ApiKeyVerifier = {
|
|
4696
6266
|
verify() {
|
|
4697
6267
|
return Promise.resolve({ ok: false, code: "invalid_credential" });
|
|
@@ -8513,7 +10083,7 @@ async function applyApiKeysFeature(cwd, framework, manifest, activate) {
|
|
|
8513
10083
|
changedFiles.push(...materialized.changedFiles);
|
|
8514
10084
|
notes.push(...materialized.notes);
|
|
8515
10085
|
config.schema = materialized.schema;
|
|
8516
|
-
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.");
|
|
10086
|
+
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.");
|
|
8517
10087
|
}
|
|
8518
10088
|
const scaffolds = [
|
|
8519
10089
|
[config.modules.policyModule, apiKeysPolicyTemplate(), "policy"],
|
|
@@ -9526,184 +11096,1124 @@ async function checkFilesFeature(cwd, framework, manifest, options) {
|
|
|
9526
11096
|
for (const suggestion of local.suggestions)
|
|
9527
11097
|
suggestions.add(suggestion);
|
|
9528
11098
|
}
|
|
9529
|
-
const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
|
|
9530
|
-
if (!routeText) {
|
|
9531
|
-
issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
|
|
9532
|
-
suggestions.add("Run `loom add files` to scaffold the files route handler.");
|
|
11099
|
+
const routeText = await readTextIfExists(join(cwd, config.entrypoints.routeHandler));
|
|
11100
|
+
if (!routeText) {
|
|
11101
|
+
issues.push(`Files route handler is missing: ${config.entrypoints.routeHandler}`);
|
|
11102
|
+
suggestions.add("Run `loom add files` to scaffold the files route handler.");
|
|
11103
|
+
}
|
|
11104
|
+
else {
|
|
11105
|
+
if (!matchesImportSource(routeText, ["@gadicc/loom/next/files"])) {
|
|
11106
|
+
issues.push(`Files route handler is not wired to @gadicc/loom/next/files: ${config.entrypoints.routeHandler}`);
|
|
11107
|
+
}
|
|
11108
|
+
if (!routeText.includes("createFilesRouteHandlers")) {
|
|
11109
|
+
issues.push(`Files route handler does not call createFilesRouteHandlers: ${config.entrypoints.routeHandler}`);
|
|
11110
|
+
}
|
|
11111
|
+
const routeImportChecks = [
|
|
11112
|
+
[config.modules.accessModule, "access policy"],
|
|
11113
|
+
[config.modules.repositoryModule, "repository"],
|
|
11114
|
+
[config.modules.storageModule, "storage adapter"],
|
|
11115
|
+
];
|
|
11116
|
+
for (const [modulePath, label] of routeImportChecks) {
|
|
11117
|
+
if (!matchesImportSource(routeText, getImportSpecifierCandidates(config.entrypoints.routeHandler, modulePath))) {
|
|
11118
|
+
issues.push(`Files route handler does not import the configured ${label}: ${config.entrypoints.routeHandler}`);
|
|
11119
|
+
suggestions.add(`Import the files ${label} from ${modulePath} in the route handler.`);
|
|
11120
|
+
}
|
|
11121
|
+
}
|
|
11122
|
+
}
|
|
11123
|
+
return {
|
|
11124
|
+
issues,
|
|
11125
|
+
suggestions: [...suggestions],
|
|
11126
|
+
warnings,
|
|
11127
|
+
};
|
|
11128
|
+
}
|
|
11129
|
+
async function checkMailFeature(cwd, framework, manifest, options) {
|
|
11130
|
+
const issues = [];
|
|
11131
|
+
const suggestions = new Set();
|
|
11132
|
+
const warnings = [];
|
|
11133
|
+
const feature = manifest.features.mail;
|
|
11134
|
+
if (!feature || feature.status !== "active") {
|
|
11135
|
+
return { issues, suggestions: [], warnings };
|
|
11136
|
+
}
|
|
11137
|
+
for (const dependency of ["auth", "db"]) {
|
|
11138
|
+
if (manifest.features[dependency]?.status !== "active") {
|
|
11139
|
+
issues.push(`Mail feature requires the active ${dependency} feature.`);
|
|
11140
|
+
suggestions.add(`Run \`loom add ${dependency}\` before using mail.`);
|
|
11141
|
+
}
|
|
11142
|
+
}
|
|
11143
|
+
if (issues.length)
|
|
11144
|
+
return { issues, suggestions: [...suggestions], warnings };
|
|
11145
|
+
const { packageJson } = await readProjectPackageJson(cwd);
|
|
11146
|
+
const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
|
|
11147
|
+
const config = getMailConfig(framework, dbConfig, packageJson, feature.config, manifest.features.jobs?.status === "active");
|
|
11148
|
+
const schema = config.schema;
|
|
11149
|
+
const latestSchema = getLatestManagedSchemaConfig(schema);
|
|
11150
|
+
if (schema.mode !== "managed-local" || schema.blueprint !== "mail") {
|
|
11151
|
+
issues.push("Mail must use the managed-local mail schema blueprint.");
|
|
11152
|
+
suggestions.add("Run `loom add mail` to restore the mail schema config.");
|
|
11153
|
+
}
|
|
11154
|
+
if (schema.exports.length !== 3) {
|
|
11155
|
+
issues.push("Mail schema must configure message, delivery, and event exports.");
|
|
11156
|
+
}
|
|
11157
|
+
if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
11158
|
+
issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
|
|
11159
|
+
}
|
|
11160
|
+
else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
11161
|
+
warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
|
|
11162
|
+
suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
|
|
11163
|
+
}
|
|
11164
|
+
const schemaText = await readTextIfExists(join(cwd, schema.module));
|
|
11165
|
+
if (!schemaText) {
|
|
11166
|
+
issues.push(`Mail schema file is missing: ${schema.module}`);
|
|
11167
|
+
suggestions.add("Run `loom db schemas sync`.");
|
|
11168
|
+
}
|
|
11169
|
+
else {
|
|
11170
|
+
const currentHash = hashManagedSchemaText(schemaText);
|
|
11171
|
+
if (currentHash !== schema.hash) {
|
|
11172
|
+
if (currentHash === latestSchema.hash) {
|
|
11173
|
+
warnings.push(`Mail schema manifest hash is stale for ${schema.module}.`);
|
|
11174
|
+
suggestions.add("Run `loom db schemas sync` to refresh loom.json.");
|
|
11175
|
+
}
|
|
11176
|
+
else {
|
|
11177
|
+
issues.push(`Mail schema file has local edits outside the managed hash: ${schema.module}`);
|
|
11178
|
+
suggestions.add("Move app-specific mail schema additions to a separate file, then run `loom db schemas sync`.");
|
|
11179
|
+
}
|
|
11180
|
+
}
|
|
11181
|
+
const barrelText = await readTextIfExists(join(cwd, dbConfig.dirs.schemaDir, "index.ts"));
|
|
11182
|
+
if (!barrelText || !schemaBarrelExportsModule(barrelText, schema, dbConfig)) {
|
|
11183
|
+
issues.push(`DB schema barrel does not export the managed mail schema: ${dbConfig.dirs.schemaDir}/index.ts`);
|
|
11184
|
+
suggestions.add("Run `loom db schemas sync`.");
|
|
11185
|
+
}
|
|
11186
|
+
}
|
|
11187
|
+
const requiredFiles = [
|
|
11188
|
+
config.modules.accessModule,
|
|
11189
|
+
config.modules.actionsModule,
|
|
11190
|
+
config.modules.repositoryModule,
|
|
11191
|
+
config.modules.serviceModule,
|
|
11192
|
+
config.modules.transportModule,
|
|
11193
|
+
config.entrypoints.adminPage,
|
|
11194
|
+
config.entrypoints.webhookRoute,
|
|
11195
|
+
...(config.jobs.enabled ? [config.modules.jobModule] : []),
|
|
11196
|
+
];
|
|
11197
|
+
for (const relativePath of requiredFiles) {
|
|
11198
|
+
if (!await exists(join(cwd, relativePath))) {
|
|
11199
|
+
issues.push(`Mail scaffold file is missing: ${relativePath}`);
|
|
11200
|
+
suggestions.add("Run `loom add mail` to restore missing scaffolds.");
|
|
11201
|
+
}
|
|
11202
|
+
}
|
|
11203
|
+
const accessText = await readTextIfExists(join(cwd, config.modules.accessModule));
|
|
11204
|
+
if (accessText && !accessText.includes("authorizeMailAdmin")) {
|
|
11205
|
+
issues.push(`Mail access module does not export authorizeMailAdmin: ${config.modules.accessModule}`);
|
|
11206
|
+
}
|
|
11207
|
+
const generatedDenyAll = accessText?.includes("Mail admin access policy is not configured.") ?? false;
|
|
11208
|
+
if (generatedDenyAll) {
|
|
11209
|
+
const message = `Mail admin access still uses the generated deny-all stub: ${config.modules.accessModule}`;
|
|
11210
|
+
if (options.production)
|
|
11211
|
+
issues.push(message);
|
|
11212
|
+
else
|
|
11213
|
+
warnings.push(message);
|
|
11214
|
+
suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
|
|
11215
|
+
}
|
|
11216
|
+
const contentChecks = [
|
|
11217
|
+
[
|
|
11218
|
+
config.modules.repositoryModule,
|
|
11219
|
+
"@gadicc/loom/mail",
|
|
11220
|
+
"Mail repository is not typed against the shared mail contract",
|
|
11221
|
+
],
|
|
11222
|
+
[
|
|
11223
|
+
config.modules.serviceModule,
|
|
11224
|
+
"createLoomMailService",
|
|
11225
|
+
"Mail service is not wired to the shared durable service",
|
|
11226
|
+
],
|
|
11227
|
+
[
|
|
11228
|
+
config.modules.transportModule,
|
|
11229
|
+
"createPostalMailTransport",
|
|
11230
|
+
"Mail transport is not wired to the Postal adapter",
|
|
11231
|
+
],
|
|
11232
|
+
[
|
|
11233
|
+
config.modules.transportModule,
|
|
11234
|
+
"POSTAL_WEBHOOK_PUBLIC_KEYS",
|
|
11235
|
+
"Mail transport does not configure Postal webhook public keys",
|
|
11236
|
+
],
|
|
11237
|
+
[
|
|
11238
|
+
config.entrypoints.webhookRoute,
|
|
11239
|
+
"createPostalWebhookRouteHandler",
|
|
11240
|
+
"Mail webhook route does not use the signed shared route handler",
|
|
11241
|
+
],
|
|
11242
|
+
[
|
|
11243
|
+
config.modules.actionsModule,
|
|
11244
|
+
"authorizeMailAdmin",
|
|
11245
|
+
"Mail admin actions do not enforce the app-owned admin boundary",
|
|
11246
|
+
],
|
|
11247
|
+
[
|
|
11248
|
+
config.entrypoints.adminPage,
|
|
11249
|
+
"authorizeMailAdmin",
|
|
11250
|
+
"Mail admin page does not enforce the app-owned admin boundary",
|
|
11251
|
+
],
|
|
11252
|
+
];
|
|
11253
|
+
for (const [relativePath, snippet, label] of contentChecks) {
|
|
11254
|
+
const text = await readTextIfExists(join(cwd, relativePath));
|
|
11255
|
+
if (text && !text.includes(snippet)) {
|
|
11256
|
+
issues.push(`${label}: ${relativePath}`);
|
|
11257
|
+
suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
|
|
11258
|
+
}
|
|
11259
|
+
}
|
|
11260
|
+
if (config.ui.adapter === "mui" &&
|
|
11261
|
+
!hasPackageDependency(packageJson, "@mui/material")) {
|
|
11262
|
+
issues.push("Mail's MUI adapter is active but @mui/material is not installed.");
|
|
11263
|
+
}
|
|
11264
|
+
if (config.jobs.enabled && manifest.features.jobs?.status !== "active") {
|
|
11265
|
+
warnings.push("Mail drain job is enabled while the Loom jobs feature is inactive.");
|
|
11266
|
+
suggestions.add("Run `loom add jobs` or disable features.mail.config.jobs.enabled.");
|
|
11267
|
+
}
|
|
11268
|
+
return { issues, suggestions: [...suggestions], warnings };
|
|
11269
|
+
}
|
|
11270
|
+
function packageDependencySpec(packageJson, dependencyName) {
|
|
11271
|
+
return packageJson.dependencies?.[dependencyName] ??
|
|
11272
|
+
packageJson.devDependencies?.[dependencyName];
|
|
11273
|
+
}
|
|
11274
|
+
function dependencyMajorMinor(spec) {
|
|
11275
|
+
const match = spec?.match(/(\d+)\.(\d+)/);
|
|
11276
|
+
return match ? `${match[1]}.${match[2]}` : undefined;
|
|
11277
|
+
}
|
|
11278
|
+
/**
|
|
11279
|
+
* Blanks JavaScript/TypeScript comments while keeping string and template
|
|
11280
|
+
* literals, so advisory text checks ignore commented-out code. Newlines are
|
|
11281
|
+
* kept. Regular-expression literals are not recognised; one containing a
|
|
11282
|
+
* quote or comment opener can confuse it, which only affects these checks.
|
|
11283
|
+
*/
|
|
11284
|
+
function stripJsComments(text) {
|
|
11285
|
+
let output = "";
|
|
11286
|
+
let index = 0;
|
|
11287
|
+
while (index < text.length) {
|
|
11288
|
+
const char = text[index];
|
|
11289
|
+
const next = text[index + 1];
|
|
11290
|
+
if (char === "/" && next === "/") {
|
|
11291
|
+
const end = text.indexOf("\n", index);
|
|
11292
|
+
output += " ";
|
|
11293
|
+
if (end === -1)
|
|
11294
|
+
break;
|
|
11295
|
+
index = end;
|
|
11296
|
+
continue;
|
|
11297
|
+
}
|
|
11298
|
+
if (char === "/" && next === "*") {
|
|
11299
|
+
const end = text.indexOf("*/", index + 2);
|
|
11300
|
+
const comment = end === -1
|
|
11301
|
+
? text.slice(index)
|
|
11302
|
+
: text.slice(index, end + 2);
|
|
11303
|
+
output += comment.replace(/[^\n]/g, " ");
|
|
11304
|
+
index += comment.length;
|
|
11305
|
+
continue;
|
|
11306
|
+
}
|
|
11307
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
11308
|
+
const end = skipJsStringLiteral(text, index);
|
|
11309
|
+
output += text.slice(index, end);
|
|
11310
|
+
index = end;
|
|
11311
|
+
continue;
|
|
11312
|
+
}
|
|
11313
|
+
output += char;
|
|
11314
|
+
index += 1;
|
|
11315
|
+
}
|
|
11316
|
+
return output;
|
|
11317
|
+
}
|
|
11318
|
+
/** Returns the index just past the string literal that starts at `start`. */
|
|
11319
|
+
function skipJsStringLiteral(text, start) {
|
|
11320
|
+
const quote = text[start];
|
|
11321
|
+
let index = start + 1;
|
|
11322
|
+
while (index < text.length) {
|
|
11323
|
+
const char = text[index];
|
|
11324
|
+
if (char === "\\") {
|
|
11325
|
+
index += 2;
|
|
11326
|
+
continue;
|
|
11327
|
+
}
|
|
11328
|
+
index += 1;
|
|
11329
|
+
if (char === quote)
|
|
11330
|
+
break;
|
|
11331
|
+
if (quote !== "`" && char === "\n")
|
|
11332
|
+
break;
|
|
11333
|
+
}
|
|
11334
|
+
return Math.min(index, text.length);
|
|
11335
|
+
}
|
|
11336
|
+
/**
|
|
11337
|
+
* Replaces the contents of string and template literals with spaces, keeping
|
|
11338
|
+
* quotes, newlines, and offsets, so searches only see code.
|
|
11339
|
+
*/
|
|
11340
|
+
function blankJsStrings(text) {
|
|
11341
|
+
let output = "";
|
|
11342
|
+
let index = 0;
|
|
11343
|
+
while (index < text.length) {
|
|
11344
|
+
const char = text[index];
|
|
11345
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
11346
|
+
const end = skipJsStringLiteral(text, index);
|
|
11347
|
+
output += char + text.slice(index + 1, end).replace(/[^\n]/g, " ");
|
|
11348
|
+
if (end - index >= 2 && text[end - 1] === char) {
|
|
11349
|
+
output = output.slice(0, -1) + char;
|
|
11350
|
+
}
|
|
11351
|
+
index = end;
|
|
11352
|
+
continue;
|
|
11353
|
+
}
|
|
11354
|
+
output += char;
|
|
11355
|
+
index += 1;
|
|
11356
|
+
}
|
|
11357
|
+
return output;
|
|
11358
|
+
}
|
|
11359
|
+
/** Comment-free text plus a same-length copy whose string contents are blank. */
|
|
11360
|
+
function prepareJsText(text) {
|
|
11361
|
+
const code = stripJsComments(text);
|
|
11362
|
+
return { blanked: blankJsStrings(code), code };
|
|
11363
|
+
}
|
|
11364
|
+
/**
|
|
11365
|
+
* Reads one expression starting at `start` until a top-level `,`, `;`, or
|
|
11366
|
+
* closing bracket, skipping string literals. A top-level line break ends it
|
|
11367
|
+
* unless the neighbouring lines continue it (an operator or `.` on either
|
|
11368
|
+
* side), so a chained `.filter()` stays part of the expression. Expects
|
|
11369
|
+
* comment-free text.
|
|
11370
|
+
*/
|
|
11371
|
+
function readJsExpression(text, start) {
|
|
11372
|
+
const blanked = blankJsStrings(text);
|
|
11373
|
+
let index = start;
|
|
11374
|
+
while (index < blanked.length && /\s/.test(blanked[index]))
|
|
11375
|
+
index += 1;
|
|
11376
|
+
const begin = index;
|
|
11377
|
+
let depth = 0;
|
|
11378
|
+
while (index < blanked.length) {
|
|
11379
|
+
const char = blanked[index];
|
|
11380
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11381
|
+
depth += 1;
|
|
11382
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11383
|
+
if (depth === 0)
|
|
11384
|
+
break;
|
|
11385
|
+
depth -= 1;
|
|
11386
|
+
}
|
|
11387
|
+
else if (depth === 0 && (char === "," || char === ";")) {
|
|
11388
|
+
break;
|
|
11389
|
+
}
|
|
11390
|
+
else if (depth === 0 && char === "\n") {
|
|
11391
|
+
const before = blanked.slice(begin, index).trimEnd();
|
|
11392
|
+
const after = blanked.slice(index).trimStart();
|
|
11393
|
+
const continued = /[=([{,?:+\-*/%&|^!<>~.]$/.test(before) ||
|
|
11394
|
+
/^(?:[.?:+\-*/%&|^<>=([]|as\s|satisfies\s)/.test(after);
|
|
11395
|
+
if (!continued)
|
|
11396
|
+
break;
|
|
11397
|
+
}
|
|
11398
|
+
index += 1;
|
|
11399
|
+
}
|
|
11400
|
+
return text.slice(begin, index).trim();
|
|
11401
|
+
}
|
|
11402
|
+
/** Index of the bracket closing the one at `open` in blanked text, or -1. */
|
|
11403
|
+
function findJsClosingBracket(blanked, open) {
|
|
11404
|
+
let depth = 0;
|
|
11405
|
+
for (let index = open; index < blanked.length; index += 1) {
|
|
11406
|
+
const char = blanked[index];
|
|
11407
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11408
|
+
depth += 1;
|
|
11409
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11410
|
+
depth -= 1;
|
|
11411
|
+
if (depth === 0)
|
|
11412
|
+
return index;
|
|
11413
|
+
}
|
|
11414
|
+
}
|
|
11415
|
+
return -1;
|
|
11416
|
+
}
|
|
11417
|
+
/** Splits list or object-literal contents on top-level commas. */
|
|
11418
|
+
function splitJsTopLevel(text) {
|
|
11419
|
+
const blanked = blankJsStrings(text);
|
|
11420
|
+
const parts = [];
|
|
11421
|
+
let depth = 0;
|
|
11422
|
+
let start = 0;
|
|
11423
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11424
|
+
const char = blanked[index];
|
|
11425
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11426
|
+
depth += 1;
|
|
11427
|
+
else if (char === ")" || char === "]" || char === "}")
|
|
11428
|
+
depth -= 1;
|
|
11429
|
+
else if (char === "," && depth === 0) {
|
|
11430
|
+
parts.push(text.slice(start, index).trim());
|
|
11431
|
+
start = index + 1;
|
|
11432
|
+
}
|
|
11433
|
+
}
|
|
11434
|
+
parts.push(text.slice(start).trim());
|
|
11435
|
+
return parts.filter(Boolean);
|
|
11436
|
+
}
|
|
11437
|
+
/** Drops wrapping parentheses and a top-level `as T`/`satisfies T` suffix. */
|
|
11438
|
+
function unwrapJsExpression(expression) {
|
|
11439
|
+
let current = expression.trim();
|
|
11440
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
11441
|
+
const blanked = blankJsStrings(current);
|
|
11442
|
+
let depth = 0;
|
|
11443
|
+
let cut = -1;
|
|
11444
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11445
|
+
const char = blanked[index];
|
|
11446
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11447
|
+
depth += 1;
|
|
11448
|
+
else if (char === ")" || char === "]" || char === "}")
|
|
11449
|
+
depth -= 1;
|
|
11450
|
+
else if (depth === 0 && /\s/.test(char) &&
|
|
11451
|
+
/^\s+(?:as|satisfies)\s/.test(blanked.slice(index))) {
|
|
11452
|
+
cut = index;
|
|
11453
|
+
break;
|
|
11454
|
+
}
|
|
11455
|
+
}
|
|
11456
|
+
if (cut !== -1) {
|
|
11457
|
+
current = current.slice(0, cut).trim();
|
|
11458
|
+
continue;
|
|
11459
|
+
}
|
|
11460
|
+
if (current.startsWith("(") &&
|
|
11461
|
+
findJsClosingBracket(blanked, 0) === current.length - 1) {
|
|
11462
|
+
current = current.slice(1, -1).trim();
|
|
11463
|
+
continue;
|
|
11464
|
+
}
|
|
11465
|
+
break;
|
|
11466
|
+
}
|
|
11467
|
+
return current;
|
|
11468
|
+
}
|
|
11469
|
+
/** `{ callee, args }` when the whole expression is one call, else null. */
|
|
11470
|
+
function parseWholeJsCall(expression) {
|
|
11471
|
+
const match = expression.match(/^([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*)\s*\(/);
|
|
11472
|
+
if (!match)
|
|
11473
|
+
return null;
|
|
11474
|
+
const open = match[0].length - 1;
|
|
11475
|
+
if (findJsClosingBracket(blankJsStrings(expression), open) !==
|
|
11476
|
+
expression.length - 1) {
|
|
11477
|
+
return null;
|
|
11478
|
+
}
|
|
11479
|
+
return {
|
|
11480
|
+
args: expression.slice(open + 1, -1),
|
|
11481
|
+
callee: match[1].replace(/\s+/g, ""),
|
|
11482
|
+
};
|
|
11483
|
+
}
|
|
11484
|
+
/** The contents of a whole `[...]` or `{...}` literal, else null. */
|
|
11485
|
+
function wholeJsBracketContents(expression, open) {
|
|
11486
|
+
if (!expression.startsWith(open) ||
|
|
11487
|
+
findJsClosingBracket(blankJsStrings(expression), 0) !==
|
|
11488
|
+
expression.length - 1) {
|
|
11489
|
+
return null;
|
|
11490
|
+
}
|
|
11491
|
+
return expression.slice(1, -1);
|
|
11492
|
+
}
|
|
11493
|
+
/** The value of a plain string literal (no template substitutions). */
|
|
11494
|
+
function jsStringLiteralValue(expression) {
|
|
11495
|
+
const quote = expression[0];
|
|
11496
|
+
if (quote !== '"' && quote !== "'" && quote !== "`")
|
|
11497
|
+
return null;
|
|
11498
|
+
if (skipJsStringLiteral(expression, 0) !== expression.length)
|
|
11499
|
+
return null;
|
|
11500
|
+
const value = expression.slice(1, -1);
|
|
11501
|
+
return value.includes("\\") || (quote === "`" && value.includes("${"))
|
|
11502
|
+
? null
|
|
11503
|
+
: value;
|
|
11504
|
+
}
|
|
11505
|
+
const JS_IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
|
11506
|
+
const JS_IDENTIFIER_SOURCE = String.raw `[A-Za-z_$][\w$]*`;
|
|
11507
|
+
const LOOM_API_KEYS_IMPORT_SOURCES = new Set([
|
|
11508
|
+
"@gadicc/loom",
|
|
11509
|
+
"@gadicc/loom/api-keys",
|
|
11510
|
+
"@gadicc/loom/apiKeys",
|
|
11511
|
+
]);
|
|
11512
|
+
const NO_JS_ENV = new Map();
|
|
11513
|
+
async function loadJsSourceModule(context, relativePath) {
|
|
11514
|
+
if (!context.modules.has(relativePath)) {
|
|
11515
|
+
const text = await readTextIfExists(join(context.cwd, relativePath));
|
|
11516
|
+
context.modules.set(relativePath, text === null
|
|
11517
|
+
? null
|
|
11518
|
+
: { path: relativePath, prepared: prepareJsText(text) });
|
|
11519
|
+
}
|
|
11520
|
+
return context.modules.get(relativePath) ?? null;
|
|
11521
|
+
}
|
|
11522
|
+
/**
|
|
11523
|
+
* Value imports of a module: `imported` is `"*"` for a namespace import and
|
|
11524
|
+
* `"default"` for a default import.
|
|
11525
|
+
*/
|
|
11526
|
+
function parseJsValueImports(module) {
|
|
11527
|
+
const { blanked, code } = module.prepared;
|
|
11528
|
+
const imports = [];
|
|
11529
|
+
const pattern = /(?<![\w$.])import\s+(type\s+)?([^;]*?)\s*from\s*(["'])([^"']+)\3/g;
|
|
11530
|
+
for (const match of code.matchAll(pattern)) {
|
|
11531
|
+
if (match[1] || !blanked.startsWith("import", match.index ?? 0))
|
|
11532
|
+
continue;
|
|
11533
|
+
const clause = match[2].trim();
|
|
11534
|
+
const source = match[4];
|
|
11535
|
+
const defaultImport = clause.match(/^([A-Za-z_$][\w$]*)\s*(?:,|$)/);
|
|
11536
|
+
if (defaultImport) {
|
|
11537
|
+
imports.push({ imported: "default", local: defaultImport[1], source });
|
|
11538
|
+
}
|
|
11539
|
+
const namespace = clause.match(/\*\s*as\s+([A-Za-z_$][\w$]*)/);
|
|
11540
|
+
if (namespace) {
|
|
11541
|
+
imports.push({ imported: "*", local: namespace[1], source });
|
|
11542
|
+
}
|
|
11543
|
+
const named = clause.match(/\{([^}]*)\}/);
|
|
11544
|
+
for (const specifier of named ? named[1].split(",") : []) {
|
|
11545
|
+
const trimmed = specifier.trim();
|
|
11546
|
+
if (!trimmed || /^type\s/.test(trimmed))
|
|
11547
|
+
continue;
|
|
11548
|
+
const [imported, local = imported] = trimmed.split(/\s+as\s+/);
|
|
11549
|
+
if (JS_IDENTIFIER.test(imported) && JS_IDENTIFIER.test(local)) {
|
|
11550
|
+
imports.push({ imported, local, source });
|
|
11551
|
+
}
|
|
11552
|
+
}
|
|
11553
|
+
}
|
|
11554
|
+
return imports;
|
|
11555
|
+
}
|
|
11556
|
+
/** Bracket depth before each offset of blanked text. */
|
|
11557
|
+
function jsBracketDepths(blanked) {
|
|
11558
|
+
const depths = new Int32Array(blanked.length + 1);
|
|
11559
|
+
let depth = 0;
|
|
11560
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11561
|
+
depths[index] = depth;
|
|
11562
|
+
const char = blanked[index];
|
|
11563
|
+
if (char === "(" || char === "[" || char === "{")
|
|
11564
|
+
depth += 1;
|
|
11565
|
+
else if (char === ")" || char === "]" || char === "}") {
|
|
11566
|
+
depth = Math.max(0, depth - 1);
|
|
11567
|
+
}
|
|
11568
|
+
}
|
|
11569
|
+
depths[blanked.length] = depth;
|
|
11570
|
+
return depths;
|
|
11571
|
+
}
|
|
11572
|
+
function addJsIdentifiers(names, text) {
|
|
11573
|
+
for (const match of text.matchAll(/[A-Za-z_$][\w$]*/g))
|
|
11574
|
+
names.add(match[0]);
|
|
11575
|
+
}
|
|
11576
|
+
/**
|
|
11577
|
+
* Offset of a function body: after a parameter list's closing parenthesis,
|
|
11578
|
+
* an optional return type, then `{` or `=>`. Returns -1 otherwise.
|
|
11579
|
+
*/
|
|
11580
|
+
function jsFunctionBodyStart(blanked, close) {
|
|
11581
|
+
const after = blanked.slice(close + 1).match(/^\s*(?::[^{};=]*?)?\s*(=>|\{)/);
|
|
11582
|
+
if (!after)
|
|
11583
|
+
return -1;
|
|
11584
|
+
return close + 1 + after[0].length - after[1].length;
|
|
11585
|
+
}
|
|
11586
|
+
/** Start and end offsets of a function body that begins at `start`. */
|
|
11587
|
+
function jsFunctionBodyRange(module, start) {
|
|
11588
|
+
const { blanked, code } = module.prepared;
|
|
11589
|
+
let index = start;
|
|
11590
|
+
if (blanked.startsWith("=>", index)) {
|
|
11591
|
+
index += 2;
|
|
11592
|
+
while (index < blanked.length && /\s/.test(blanked[index]))
|
|
11593
|
+
index += 1;
|
|
11594
|
+
if (blanked[index] !== "{") {
|
|
11595
|
+
const expression = readJsExpression(code, index);
|
|
11596
|
+
return { end: index + expression.length, start: index };
|
|
11597
|
+
}
|
|
11598
|
+
}
|
|
11599
|
+
const end = findJsClosingBracket(blanked, index);
|
|
11600
|
+
return end === -1 ? null : { end, start: index };
|
|
11601
|
+
}
|
|
11602
|
+
/** The first parameter's name when it is a plain identifier. */
|
|
11603
|
+
function firstJsParameterName(parameters) {
|
|
11604
|
+
const [first] = splitJsTopLevel(parameters);
|
|
11605
|
+
const name = first?.replace(/\s*=[\s\S]*$/, "").replace(/\s*:[\s\S]*$/, "")
|
|
11606
|
+
.replace(/\?$/, "").trim();
|
|
11607
|
+
return name && JS_IDENTIFIER.test(name) ? name : undefined;
|
|
11608
|
+
}
|
|
11609
|
+
/** Computes, once per module, the facts used for identifier resolution. */
|
|
11610
|
+
function analyzeJsModule(module) {
|
|
11611
|
+
if (module.scope)
|
|
11612
|
+
return module.scope;
|
|
11613
|
+
const { blanked, code } = module.prepared;
|
|
11614
|
+
const depths = jsBracketDepths(blanked);
|
|
11615
|
+
const nestedNames = new Set();
|
|
11616
|
+
const topLevel = new Map();
|
|
11617
|
+
const functions = [];
|
|
11618
|
+
const addTopLevel = (name, binding) => {
|
|
11619
|
+
topLevel.set(name, [...(topLevel.get(name) ?? []), binding]);
|
|
11620
|
+
};
|
|
11621
|
+
for (const match of blanked.matchAll(/(?<![\w$.])(const|let|var)\s+([A-Za-z_$][\w$]*|[{[])/g)) {
|
|
11622
|
+
const index = match.index ?? 0;
|
|
11623
|
+
const target = match[2];
|
|
11624
|
+
const nested = depths[index] > 0;
|
|
11625
|
+
if (target === "{" || target === "[") {
|
|
11626
|
+
// Destructuring: every identifier in the pattern may be bound.
|
|
11627
|
+
const open = index + match[0].length - 1;
|
|
11628
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11629
|
+
const names = new Set();
|
|
11630
|
+
addJsIdentifiers(names, blanked.slice(open, close + 1));
|
|
11631
|
+
for (const name of names) {
|
|
11632
|
+
if (nested)
|
|
11633
|
+
nestedNames.add(name);
|
|
11634
|
+
else
|
|
11635
|
+
addTopLevel(name, { kind: "other" });
|
|
11636
|
+
}
|
|
11637
|
+
continue;
|
|
11638
|
+
}
|
|
11639
|
+
if (nested) {
|
|
11640
|
+
nestedNames.add(target);
|
|
11641
|
+
continue;
|
|
11642
|
+
}
|
|
11643
|
+
const initializer = new RegExp(String.raw `^\s*(?::[^=;]*)?=(?![=>])`).exec(blanked.slice(index + match[0].length));
|
|
11644
|
+
addTopLevel(target, match[1] === "const" && initializer
|
|
11645
|
+
? {
|
|
11646
|
+
initializer: index + match[0].length + initializer[0].length,
|
|
11647
|
+
kind: "const",
|
|
11648
|
+
}
|
|
11649
|
+
: { kind: "other" });
|
|
11650
|
+
}
|
|
11651
|
+
for (const match of blanked.matchAll(/(?<![\w$.])(?:function\s*\*?|class)\s+([A-Za-z_$][\w$]*)/g)) {
|
|
11652
|
+
if (depths[match.index ?? 0] > 0)
|
|
11653
|
+
nestedNames.add(match[1]);
|
|
11654
|
+
else
|
|
11655
|
+
addTopLevel(match[1], { kind: "other" });
|
|
11656
|
+
}
|
|
11657
|
+
for (const entry of parseJsValueImports(module)) {
|
|
11658
|
+
addTopLevel(entry.local, entry.imported === "*" || entry.imported === "default"
|
|
11659
|
+
? { kind: "other" }
|
|
11660
|
+
: { imported: entry.imported, kind: "import", source: entry.source });
|
|
11661
|
+
}
|
|
11662
|
+
// Parameter-like lists (functions, arrows, methods, catch clauses, and
|
|
11663
|
+
// control-flow headers) all count as nested bindings.
|
|
11664
|
+
for (let index = 0; index < blanked.length; index += 1) {
|
|
11665
|
+
if (blanked[index] !== "(")
|
|
11666
|
+
continue;
|
|
11667
|
+
const close = findJsClosingBracket(blanked, index);
|
|
11668
|
+
if (close === -1 || jsFunctionBodyStart(blanked, close) === -1)
|
|
11669
|
+
continue;
|
|
11670
|
+
addJsIdentifiers(nestedNames, blanked.slice(index + 1, close));
|
|
11671
|
+
}
|
|
11672
|
+
for (const match of blanked.matchAll(/([A-Za-z_$][\w$]*)\s*=>/g)) {
|
|
11673
|
+
nestedNames.add(match[1]);
|
|
11674
|
+
}
|
|
11675
|
+
// Top-level functions, for factories that forward their first parameter.
|
|
11676
|
+
const definitions = [
|
|
11677
|
+
/(?<![\w$.])(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(/g,
|
|
11678
|
+
/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?(?:function\s*\*?\s*[\w$]*\s*)?\(/g,
|
|
11679
|
+
];
|
|
11680
|
+
for (const pattern of definitions) {
|
|
11681
|
+
for (const match of blanked.matchAll(pattern)) {
|
|
11682
|
+
const index = match.index ?? 0;
|
|
11683
|
+
if (depths[index] > 0)
|
|
11684
|
+
continue;
|
|
11685
|
+
const open = index + match[0].length - 1;
|
|
11686
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11687
|
+
const bodyStart = close === -1 ? -1 : jsFunctionBodyStart(blanked, close);
|
|
11688
|
+
const body = bodyStart === -1
|
|
11689
|
+
? null
|
|
11690
|
+
: jsFunctionBodyRange(module, bodyStart);
|
|
11691
|
+
if (!body)
|
|
11692
|
+
continue;
|
|
11693
|
+
functions.push({
|
|
11694
|
+
bodyEnd: body.end,
|
|
11695
|
+
bodyStart: body.start,
|
|
11696
|
+
name: match[1],
|
|
11697
|
+
parameter: firstJsParameterName(code.slice(open + 1, close)),
|
|
11698
|
+
});
|
|
11699
|
+
}
|
|
11700
|
+
}
|
|
11701
|
+
for (const match of blanked.matchAll(/(?<![\w$.])const\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]*)?=\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/g)) {
|
|
11702
|
+
const index = match.index ?? 0;
|
|
11703
|
+
if (depths[index] > 0)
|
|
11704
|
+
continue;
|
|
11705
|
+
const body = jsFunctionBodyRange(module, index + match[0].length - 2);
|
|
11706
|
+
if (body) {
|
|
11707
|
+
functions.push({
|
|
11708
|
+
bodyEnd: body.end,
|
|
11709
|
+
bodyStart: body.start,
|
|
11710
|
+
name: match[1],
|
|
11711
|
+
parameter: match[2],
|
|
11712
|
+
});
|
|
11713
|
+
}
|
|
11714
|
+
}
|
|
11715
|
+
module.scope = { functions, nestedNames, topLevel };
|
|
11716
|
+
return module.scope;
|
|
11717
|
+
}
|
|
11718
|
+
/**
|
|
11719
|
+
* Whether a module mutates `name` after binding it: member assignment
|
|
11720
|
+
* (`name.disabledPaths = …`, `name.length = 0`), a removing array method,
|
|
11721
|
+
* `delete`, `Object.assign` and similar, or reassignment.
|
|
11722
|
+
*/
|
|
11723
|
+
function isJsBindingMutated(module, name) {
|
|
11724
|
+
const { blanked } = module.prepared;
|
|
11725
|
+
const id = escapeRegExp(name);
|
|
11726
|
+
const member = String
|
|
11727
|
+
.raw `(?:\s*\??\.\s*${JS_IDENTIFIER_SOURCE}|\s*\[[^\]]*\])`;
|
|
11728
|
+
const assignment = String
|
|
11729
|
+
.raw `\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|\?\?|&&|\|\|)?=(?![=>])`;
|
|
11730
|
+
return [
|
|
11731
|
+
new RegExp(String.raw `(?<![\w$.])${id}${member}+${assignment}`),
|
|
11732
|
+
new RegExp(String
|
|
11733
|
+
.raw `(?<![\w$.])${id}${member}*\s*\??\.\s*(?:splice|pop|shift|fill|copyWithin)\s*\(`),
|
|
11734
|
+
new RegExp(String.raw `\bdelete\s+${id}\b`),
|
|
11735
|
+
new RegExp(String
|
|
11736
|
+
.raw `\bObject\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)\s*\(\s*${id}\b`),
|
|
11737
|
+
new RegExp(String.raw `(?<![\w$.]|(?:const|let|var)\s+)${id}${assignment}`),
|
|
11738
|
+
].some((pattern) => pattern.test(blanked));
|
|
11739
|
+
}
|
|
11740
|
+
/**
|
|
11741
|
+
* Local names under which a module imported a Loom API-key export, including
|
|
11742
|
+
* aliases and `namespace.name` for namespace imports. A name that is also
|
|
11743
|
+
* bound elsewhere in the module is left out.
|
|
11744
|
+
*/
|
|
11745
|
+
function loomApiKeyExportNames(module, exportName) {
|
|
11746
|
+
const scope = analyzeJsModule(module);
|
|
11747
|
+
const names = new Set();
|
|
11748
|
+
for (const entry of parseJsValueImports(module)) {
|
|
11749
|
+
if (!LOOM_API_KEYS_IMPORT_SOURCES.has(entry.source))
|
|
11750
|
+
continue;
|
|
11751
|
+
if (scope.nestedNames.has(entry.local) ||
|
|
11752
|
+
(scope.topLevel.get(entry.local)?.length ?? 0) !== 1) {
|
|
11753
|
+
continue;
|
|
11754
|
+
}
|
|
11755
|
+
if (entry.imported === exportName)
|
|
11756
|
+
names.add(entry.local);
|
|
11757
|
+
if (entry.imported === "*")
|
|
11758
|
+
names.add(`${entry.local}.${exportName}`);
|
|
11759
|
+
}
|
|
11760
|
+
return names;
|
|
11761
|
+
}
|
|
11762
|
+
/**
|
|
11763
|
+
* Resolves an identifier, proven or not at all: an enclosing factory
|
|
11764
|
+
* parameter, or the single top-level `const` (or one relative/`@/` import of
|
|
11765
|
+
* one while hops remain) that nothing nested shadows and nothing mutates.
|
|
11766
|
+
*/
|
|
11767
|
+
async function resolveJsName(context, binding, name) {
|
|
11768
|
+
if (binding.env.has(name)) {
|
|
11769
|
+
const parameter = binding.env.get(name) ?? null;
|
|
11770
|
+
return parameter && !isJsBindingMutated(binding.module, name)
|
|
11771
|
+
? parameter
|
|
11772
|
+
: null;
|
|
11773
|
+
}
|
|
11774
|
+
const module = binding.module;
|
|
11775
|
+
const scope = analyzeJsModule(module);
|
|
11776
|
+
const sites = scope.topLevel.get(name) ?? [];
|
|
11777
|
+
if (scope.nestedNames.has(name) || sites.length !== 1)
|
|
11778
|
+
return null;
|
|
11779
|
+
if (isJsBindingMutated(module, name))
|
|
11780
|
+
return null;
|
|
11781
|
+
const [site] = sites;
|
|
11782
|
+
if (site.kind === "const") {
|
|
11783
|
+
return {
|
|
11784
|
+
env: NO_JS_ENV,
|
|
11785
|
+
expression: readJsExpression(module.prepared.code, site.initializer),
|
|
11786
|
+
importHops: binding.importHops,
|
|
11787
|
+
module,
|
|
11788
|
+
};
|
|
11789
|
+
}
|
|
11790
|
+
if (site.kind !== "import" || binding.importHops <= 0)
|
|
11791
|
+
return null;
|
|
11792
|
+
const resolved = await resolveLocalSourceImport(context.cwd, context.framework, resolve(context.cwd, module.path), site.source);
|
|
11793
|
+
if (!resolved)
|
|
11794
|
+
return null;
|
|
11795
|
+
const target = await loadJsSourceModule(context, relative(context.cwd, resolved).replaceAll("\\", "/"));
|
|
11796
|
+
return target
|
|
11797
|
+
? await resolveJsName(context, {
|
|
11798
|
+
env: NO_JS_ENV,
|
|
11799
|
+
expression: site.imported,
|
|
11800
|
+
importHops: binding.importHops - 1,
|
|
11801
|
+
module: target,
|
|
11802
|
+
}, site.imported)
|
|
11803
|
+
: null;
|
|
11804
|
+
}
|
|
11805
|
+
/**
|
|
11806
|
+
* Whether a `disabledPaths` value provably contains every api-key plugin path:
|
|
11807
|
+
* the whole value is Loom's helper call (any arguments) or constant, an array
|
|
11808
|
+
* literal that spreads either, an array literal listing every path, or
|
|
11809
|
+
* `<options>.disabledPaths` of options that prove it. Anything else, such as
|
|
11810
|
+
* a conditional or a filtered list, is unproven.
|
|
11811
|
+
*/
|
|
11812
|
+
async function jsValueDisablesApiKeyPaths(context, binding, depth = 0) {
|
|
11813
|
+
if (depth > 12)
|
|
11814
|
+
return false;
|
|
11815
|
+
const expression = unwrapJsExpression(binding.expression);
|
|
11816
|
+
const compact = expression.replace(/\s+/g, "");
|
|
11817
|
+
const shadowed = (name) => binding.env.has(name.split(".")[0]);
|
|
11818
|
+
const constants = loomApiKeyExportNames(binding.module, "BETTER_AUTH_API_KEY_HTTP_PATHS");
|
|
11819
|
+
if (constants.has(compact) && !shadowed(compact))
|
|
11820
|
+
return true;
|
|
11821
|
+
if (JS_IDENTIFIER.test(expression)) {
|
|
11822
|
+
const resolved = await resolveJsName(context, binding, expression);
|
|
11823
|
+
return resolved
|
|
11824
|
+
? await jsValueDisablesApiKeyPaths(context, resolved, depth + 1)
|
|
11825
|
+
: false;
|
|
11826
|
+
}
|
|
11827
|
+
const member = compact.match(/^([A-Za-z_$][\w$]*)\??\.disabledPaths$/);
|
|
11828
|
+
if (member) {
|
|
11829
|
+
return await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: member[1] }, depth + 1) === true;
|
|
11830
|
+
}
|
|
11831
|
+
const call = parseWholeJsCall(expression);
|
|
11832
|
+
if (call) {
|
|
11833
|
+
return loomApiKeyExportNames(binding.module, "withBetterAuthApiKeyHttpPathsDisabled").has(call.callee) && !shadowed(call.callee);
|
|
11834
|
+
}
|
|
11835
|
+
const list = wholeJsBracketContents(expression, "[");
|
|
11836
|
+
if (list === null)
|
|
11837
|
+
return false;
|
|
11838
|
+
const literals = new Set();
|
|
11839
|
+
for (const element of splitJsTopLevel(list)) {
|
|
11840
|
+
if (element.startsWith("...")) {
|
|
11841
|
+
if (await jsValueDisablesApiKeyPaths(context, { ...binding, expression: element.slice(3) }, depth + 1)) {
|
|
11842
|
+
return true;
|
|
11843
|
+
}
|
|
11844
|
+
continue;
|
|
11845
|
+
}
|
|
11846
|
+
const literal = jsStringLiteralValue(element);
|
|
11847
|
+
if (literal !== null)
|
|
11848
|
+
literals.add(literal);
|
|
11849
|
+
}
|
|
11850
|
+
return BETTER_AUTH_API_KEY_HTTP_PATHS.every((path) => literals.has(path));
|
|
11851
|
+
}
|
|
11852
|
+
/**
|
|
11853
|
+
* Evaluates Better Auth options for `disabledPaths`: `true` when proven,
|
|
11854
|
+
* `false` when set to something unproven, `undefined` when not set. Entries
|
|
11855
|
+
* apply in order, so a later key or spread overrides an earlier one. Options
|
|
11856
|
+
* or spreads that do not resolve to an object literal, computed keys, and
|
|
11857
|
+
* accessors are unproven.
|
|
11858
|
+
*/
|
|
11859
|
+
async function jsOptionsDisableApiKeyPaths(context, binding, depth = 0) {
|
|
11860
|
+
if (depth > 12)
|
|
11861
|
+
return false;
|
|
11862
|
+
const expression = unwrapJsExpression(binding.expression);
|
|
11863
|
+
if (JS_IDENTIFIER.test(expression)) {
|
|
11864
|
+
const resolved = await resolveJsName(context, binding, expression);
|
|
11865
|
+
return resolved
|
|
11866
|
+
? await jsOptionsDisableApiKeyPaths(context, resolved, depth + 1)
|
|
11867
|
+
: false;
|
|
11868
|
+
}
|
|
11869
|
+
const contents = wholeJsBracketContents(expression, "{");
|
|
11870
|
+
if (contents === null)
|
|
11871
|
+
return false;
|
|
11872
|
+
let result;
|
|
11873
|
+
for (const entry of splitJsTopLevel(contents)) {
|
|
11874
|
+
if (entry.startsWith("...")) {
|
|
11875
|
+
const spread = await jsOptionsDisableApiKeyPaths(context, { ...binding, expression: entry.slice(3) }, depth + 1);
|
|
11876
|
+
if (spread !== undefined)
|
|
11877
|
+
result = spread;
|
|
11878
|
+
continue;
|
|
11879
|
+
}
|
|
11880
|
+
if (entry.startsWith("[")) {
|
|
11881
|
+
// A computed key may evaluate to "disabledPaths".
|
|
11882
|
+
result = false;
|
|
11883
|
+
continue;
|
|
11884
|
+
}
|
|
11885
|
+
if (entry === "disabledPaths") {
|
|
11886
|
+
result = await jsValueDisablesApiKeyPaths(context, { ...binding, expression: entry }, depth + 1);
|
|
11887
|
+
continue;
|
|
11888
|
+
}
|
|
11889
|
+
const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:/);
|
|
11890
|
+
if (property?.[2] === "disabledPaths") {
|
|
11891
|
+
result = await jsValueDisablesApiKeyPaths(context, {
|
|
11892
|
+
...binding,
|
|
11893
|
+
expression: entry.slice(property[0].length),
|
|
11894
|
+
}, depth + 1);
|
|
11895
|
+
}
|
|
11896
|
+
else if (!property &&
|
|
11897
|
+
/^(?:async\s+|get\s+|set\s+)?["']?disabledPaths\b/.test(entry)) {
|
|
11898
|
+
// A getter or method cannot be checked statically.
|
|
11899
|
+
result = false;
|
|
11900
|
+
}
|
|
11901
|
+
}
|
|
11902
|
+
return result;
|
|
11903
|
+
}
|
|
11904
|
+
/**
|
|
11905
|
+
* Every `callee(` call outside strings and comments. Member calls such as
|
|
11906
|
+
* `x.callee(` count only when `allowMember` is set; a function declaration
|
|
11907
|
+
* `function callee(` never counts.
|
|
11908
|
+
*/
|
|
11909
|
+
function findJsCalls(module, callee, options = {}) {
|
|
11910
|
+
const { blanked, code } = module.prepared;
|
|
11911
|
+
const calls = [];
|
|
11912
|
+
const pattern = new RegExp(`${options.allowMember ? "\\b" : "(?<![\\w$.])"}${escapeRegExp(callee)}\\s*\\(`, "g");
|
|
11913
|
+
for (const match of blanked.matchAll(pattern)) {
|
|
11914
|
+
const index = match.index ?? 0;
|
|
11915
|
+
if (/\bfunction\s*\*?\s*$/.test(blanked.slice(0, index)))
|
|
11916
|
+
continue;
|
|
11917
|
+
const open = index + match[0].length - 1;
|
|
11918
|
+
const close = findJsClosingBracket(blanked, open);
|
|
11919
|
+
if (close === -1)
|
|
11920
|
+
continue;
|
|
11921
|
+
calls.push({
|
|
11922
|
+
firstArgument: splitJsTopLevel(code.slice(open + 1, close))[0],
|
|
11923
|
+
open,
|
|
11924
|
+
});
|
|
9533
11925
|
}
|
|
9534
|
-
|
|
9535
|
-
|
|
9536
|
-
|
|
11926
|
+
return calls;
|
|
11927
|
+
}
|
|
11928
|
+
/**
|
|
11929
|
+
* Reads the app's Better Auth configuration and decides whether it provably
|
|
11930
|
+
* disables every api-key plugin HTTP endpoint.
|
|
11931
|
+
*
|
|
11932
|
+
* Every `betterAuth(` call in the auth module and, when it imports the auth
|
|
11933
|
+
* module, the auth runtime module must be proven; there must be at least one.
|
|
11934
|
+
* A call inside a top-level factory is evaluated once per call of that factory
|
|
11935
|
+
* in those modules, with the factory's first parameter bound to the call's
|
|
11936
|
+
* argument, so options the factory ignores are not credited. Identifiers
|
|
11937
|
+
* resolve only to unshadowed, unmutated top-level `const` initializers,
|
|
11938
|
+
* following one relative or `@/` import. `modules` lists every file read.
|
|
11939
|
+
*/
|
|
11940
|
+
async function inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest) {
|
|
11941
|
+
const authConfig = await mergeAuthConfig(cwd, framework, manifest.features.auth?.config);
|
|
11942
|
+
const authModulePath = authConfig.modules.authModule;
|
|
11943
|
+
const context = { cwd, framework, modules: new Map() };
|
|
11944
|
+
const authModule = await loadJsSourceModule(context, authModulePath);
|
|
11945
|
+
const scanned = authModule ? [authModule] : [];
|
|
11946
|
+
let runtimeModule = null;
|
|
11947
|
+
/** Local names of auth-module exports imported by the runtime module. */
|
|
11948
|
+
const runtimeAliases = new Map();
|
|
11949
|
+
const runtimePath = authConfig.modules.authRuntimeModule;
|
|
11950
|
+
const runtimeText = runtimePath
|
|
11951
|
+
? await readTextIfExists(join(cwd, runtimePath))
|
|
11952
|
+
: null;
|
|
11953
|
+
if (authModule && runtimePath && runtimeText &&
|
|
11954
|
+
matchesImportSource(runtimeText, getImportSpecifierCandidates(runtimePath, authModulePath))) {
|
|
11955
|
+
runtimeModule = await loadJsSourceModule(context, runtimePath);
|
|
11956
|
+
if (runtimeModule) {
|
|
11957
|
+
scanned.push(runtimeModule);
|
|
11958
|
+
const authModuleAbsolute = resolve(cwd, authModulePath);
|
|
11959
|
+
for (const entry of parseJsValueImports(runtimeModule)) {
|
|
11960
|
+
if (entry.imported === "*" || entry.imported === "default")
|
|
11961
|
+
continue;
|
|
11962
|
+
const resolved = await resolveLocalSourceImport(cwd, framework, resolve(cwd, runtimePath), entry.source);
|
|
11963
|
+
if (resolved === authModuleAbsolute) {
|
|
11964
|
+
runtimeAliases.set(entry.imported, entry.local);
|
|
11965
|
+
}
|
|
11966
|
+
}
|
|
9537
11967
|
}
|
|
9538
|
-
|
|
9539
|
-
|
|
11968
|
+
}
|
|
11969
|
+
const factoryCalls = (module, factory) => {
|
|
11970
|
+
const calls = findJsCalls(module, factory).map((call) => ({
|
|
11971
|
+
call,
|
|
11972
|
+
module,
|
|
11973
|
+
}));
|
|
11974
|
+
const alias = runtimeAliases.get(factory);
|
|
11975
|
+
const runtime = runtimeModule;
|
|
11976
|
+
if (module === authModule && alias && runtime) {
|
|
11977
|
+
calls.push(...findJsCalls(runtime, alias).map((call) => ({
|
|
11978
|
+
call,
|
|
11979
|
+
module: runtime,
|
|
11980
|
+
})));
|
|
9540
11981
|
}
|
|
9541
|
-
|
|
9542
|
-
|
|
9543
|
-
|
|
9544
|
-
|
|
9545
|
-
|
|
9546
|
-
|
|
9547
|
-
|
|
9548
|
-
|
|
9549
|
-
|
|
11982
|
+
return calls;
|
|
11983
|
+
};
|
|
11984
|
+
let calls = 0;
|
|
11985
|
+
let disabled = true;
|
|
11986
|
+
for (const module of scanned) {
|
|
11987
|
+
const functions = analyzeJsModule(module).functions;
|
|
11988
|
+
for (const call of findJsCalls(module, "betterAuth")) {
|
|
11989
|
+
calls += 1;
|
|
11990
|
+
const options = (env) => call.firstArgument === undefined
|
|
11991
|
+
? Promise.resolve(false)
|
|
11992
|
+
: jsOptionsDisableApiKeyPaths(context, {
|
|
11993
|
+
env,
|
|
11994
|
+
expression: call.firstArgument,
|
|
11995
|
+
importHops: 1,
|
|
11996
|
+
module,
|
|
11997
|
+
}).then((result) => result === true);
|
|
11998
|
+
const factory = functions.find((item) => call.open >= item.bodyStart && call.open < item.bodyEnd);
|
|
11999
|
+
const uses = factory ? factoryCalls(module, factory.name) : [];
|
|
12000
|
+
let proven;
|
|
12001
|
+
if (factory && uses.length) {
|
|
12002
|
+
proven = true;
|
|
12003
|
+
for (const use of uses) {
|
|
12004
|
+
const argument = use.call.firstArgument;
|
|
12005
|
+
const env = new Map(factory.parameter
|
|
12006
|
+
? [[
|
|
12007
|
+
factory.parameter,
|
|
12008
|
+
argument === undefined ? null : {
|
|
12009
|
+
env: NO_JS_ENV,
|
|
12010
|
+
expression: argument,
|
|
12011
|
+
importHops: 1,
|
|
12012
|
+
module: use.module,
|
|
12013
|
+
},
|
|
12014
|
+
]]
|
|
12015
|
+
: []);
|
|
12016
|
+
if (!await options(env)) {
|
|
12017
|
+
proven = false;
|
|
12018
|
+
break;
|
|
12019
|
+
}
|
|
12020
|
+
}
|
|
12021
|
+
}
|
|
12022
|
+
else {
|
|
12023
|
+
proven = await options(NO_JS_ENV);
|
|
9550
12024
|
}
|
|
12025
|
+
if (!proven)
|
|
12026
|
+
disabled = false;
|
|
9551
12027
|
}
|
|
9552
12028
|
}
|
|
12029
|
+
const loaded = [...context.modules.values()].filter((module) => module !== null);
|
|
9553
12030
|
return {
|
|
9554
|
-
|
|
9555
|
-
|
|
9556
|
-
|
|
12031
|
+
authModuleRead: authModule !== null,
|
|
12032
|
+
authModulePath,
|
|
12033
|
+
disabled: calls > 0 && disabled,
|
|
12034
|
+
modules: loaded,
|
|
9557
12035
|
};
|
|
9558
12036
|
}
|
|
9559
|
-
|
|
9560
|
-
|
|
9561
|
-
|
|
9562
|
-
|
|
9563
|
-
|
|
9564
|
-
|
|
9565
|
-
|
|
9566
|
-
|
|
9567
|
-
|
|
9568
|
-
|
|
9569
|
-
|
|
9570
|
-
|
|
9571
|
-
|
|
9572
|
-
|
|
9573
|
-
|
|
9574
|
-
|
|
9575
|
-
|
|
9576
|
-
|
|
9577
|
-
|
|
9578
|
-
|
|
9579
|
-
|
|
9580
|
-
|
|
9581
|
-
issues.push("Mail must use the managed-local mail schema blueprint.");
|
|
9582
|
-
suggestions.add("Run `loom add mail` to restore the mail schema config.");
|
|
9583
|
-
}
|
|
9584
|
-
if (schema.exports.length !== 3) {
|
|
9585
|
-
issues.push("Mail schema must configure message, delivery, and event exports.");
|
|
9586
|
-
}
|
|
9587
|
-
if (schema.version > MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
9588
|
-
issues.push(`Mail schema blueprint version ${schema.version} is newer than this Loom package supports.`);
|
|
9589
|
-
}
|
|
9590
|
-
else if (schema.version < MAIL_SCHEMA_BLUEPRINT_VERSION) {
|
|
9591
|
-
warnings.push(`Mail schema blueprint is stale: ${schema.version} < ${MAIL_SCHEMA_BLUEPRINT_VERSION}.`);
|
|
9592
|
-
suggestions.add("Run `loom db schemas sync`, then review and migrate the diff.");
|
|
9593
|
-
}
|
|
9594
|
-
const schemaText = await readTextIfExists(join(cwd, schema.module));
|
|
9595
|
-
if (!schemaText) {
|
|
9596
|
-
issues.push(`Mail schema file is missing: ${schema.module}`);
|
|
9597
|
-
suggestions.add("Run `loom db schemas sync`.");
|
|
12037
|
+
/**
|
|
12038
|
+
* Advisory, single-module object reading for the authorizer warnings: an
|
|
12039
|
+
* identifier resolves to its initializer only when the module declares that
|
|
12040
|
+
* name exactly once (`const`, at any depth) and nowhere else.
|
|
12041
|
+
*/
|
|
12042
|
+
function readJsObjectShape(module, expression, depth = 0) {
|
|
12043
|
+
if (depth > 8)
|
|
12044
|
+
return null;
|
|
12045
|
+
const unwrapped = unwrapJsExpression(expression);
|
|
12046
|
+
if (JS_IDENTIFIER.test(unwrapped)) {
|
|
12047
|
+
const { blanked, code } = module.prepared;
|
|
12048
|
+
const id = escapeRegExp(unwrapped);
|
|
12049
|
+
const declarations = [
|
|
12050
|
+
...blanked.matchAll(new RegExp(String
|
|
12051
|
+
.raw `(?<![\w$.])(?:const|let|var|function|class)\s+${id}\b|\bimport\b[^;]*\b${id}\b[^;]*\bfrom\b`, "g")),
|
|
12052
|
+
];
|
|
12053
|
+
if (declarations.length !== 1)
|
|
12054
|
+
return null;
|
|
12055
|
+
const declaration = new RegExp(String.raw `(?<![\w$.])const\s+${id}\s*(?::[^=;]*)?=(?![=>])`).exec(blanked);
|
|
12056
|
+
return declaration
|
|
12057
|
+
? readJsObjectShape(module, readJsExpression(code, declaration.index + declaration[0].length), depth + 1)
|
|
12058
|
+
: null;
|
|
9598
12059
|
}
|
|
9599
|
-
|
|
9600
|
-
|
|
9601
|
-
|
|
9602
|
-
|
|
9603
|
-
|
|
9604
|
-
|
|
9605
|
-
|
|
12060
|
+
const contents = wholeJsBracketContents(unwrapped, "{");
|
|
12061
|
+
if (contents === null)
|
|
12062
|
+
return null;
|
|
12063
|
+
const shape = { complete: true, entries: [] };
|
|
12064
|
+
for (const entry of splitJsTopLevel(contents)) {
|
|
12065
|
+
if (entry.startsWith("...")) {
|
|
12066
|
+
const spread = readJsObjectShape(module, entry.slice(3), depth + 1);
|
|
12067
|
+
if (!spread)
|
|
12068
|
+
shape.complete = false;
|
|
9606
12069
|
else {
|
|
9607
|
-
|
|
9608
|
-
|
|
12070
|
+
shape.entries.push(...spread.entries);
|
|
12071
|
+
shape.complete &&= spread.complete;
|
|
9609
12072
|
}
|
|
12073
|
+
continue;
|
|
9610
12074
|
}
|
|
9611
|
-
const
|
|
9612
|
-
if (!
|
|
9613
|
-
|
|
9614
|
-
|
|
12075
|
+
const property = entry.match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*(:)?/);
|
|
12076
|
+
if (!property) {
|
|
12077
|
+
shape.complete = false;
|
|
12078
|
+
continue;
|
|
9615
12079
|
}
|
|
12080
|
+
shape.entries.push({
|
|
12081
|
+
key: property[2],
|
|
12082
|
+
value: property[3] ? entry.slice(property[0].length) : property[2],
|
|
12083
|
+
});
|
|
9616
12084
|
}
|
|
9617
|
-
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9623
|
-
|
|
9624
|
-
|
|
9625
|
-
|
|
9626
|
-
|
|
9627
|
-
|
|
9628
|
-
|
|
9629
|
-
|
|
9630
|
-
|
|
12085
|
+
return shape;
|
|
12086
|
+
}
|
|
12087
|
+
const PERMISSION_CODE_LITERAL = String
|
|
12088
|
+
.raw `(["'\x60])[A-Z0-9_]*PERMISSION[A-Z0-9_]*\1`;
|
|
12089
|
+
const JS_EQUALITY = String.raw `(?:===|!==|==|!=)`;
|
|
12090
|
+
/**
|
|
12091
|
+
* Comparisons of an error `code` with a PERMISSION code, and a PERMISSION
|
|
12092
|
+
* code list checked with `.includes(…code)`. `token` is checked against
|
|
12093
|
+
* string-blanked text so matches inside strings do not count.
|
|
12094
|
+
*/
|
|
12095
|
+
const PERMISSION_CODE_MAPPINGS = [
|
|
12096
|
+
{
|
|
12097
|
+
pattern: new RegExp(String
|
|
12098
|
+
.raw `\bcode\s*${JS_EQUALITY}\s*(?:${PERMISSION_CODE_LITERAL}|[\w$.?]*\b[A-Z0-9_]*PERMISSION[A-Z0-9_]*\b)`, "g"),
|
|
12099
|
+
token: "code",
|
|
12100
|
+
},
|
|
12101
|
+
{
|
|
12102
|
+
pattern: new RegExp(String
|
|
12103
|
+
.raw `${PERMISSION_CODE_LITERAL}\s*${JS_EQUALITY}\s*[\w$.?]*\bcode\b`, "g"),
|
|
12104
|
+
token: "code",
|
|
12105
|
+
},
|
|
12106
|
+
{
|
|
12107
|
+
pattern: new RegExp(String
|
|
12108
|
+
.raw `\[[^\]]*PERMISSION[^\]]*\]\s*\.\s*includes\s*\(\s*[\w$.?]*\bcode\s*\)`, "g"),
|
|
12109
|
+
token: "includes",
|
|
12110
|
+
},
|
|
12111
|
+
];
|
|
12112
|
+
/** Whether a `switch` on an error `code` has a PERMISSION `case` label. */
|
|
12113
|
+
function hasPermissionCodeCase(prepared) {
|
|
12114
|
+
const { blanked, code } = prepared;
|
|
12115
|
+
for (const match of blanked.matchAll(/\bswitch\s*\(/g)) {
|
|
12116
|
+
const open = (match.index ?? 0) + match[0].length - 1;
|
|
12117
|
+
const close = findJsClosingBracket(blanked, open);
|
|
12118
|
+
if (close === -1 || !/\bcode\s*$/.test(blanked.slice(open + 1, close))) {
|
|
12119
|
+
continue;
|
|
9631
12120
|
}
|
|
9632
|
-
|
|
9633
|
-
|
|
9634
|
-
|
|
9635
|
-
|
|
9636
|
-
|
|
9637
|
-
|
|
9638
|
-
|
|
9639
|
-
const
|
|
9640
|
-
|
|
9641
|
-
|
|
9642
|
-
|
|
9643
|
-
warnings.push(message);
|
|
9644
|
-
suggestions.add("Connect authorizeMailAdmin() to the app's fresh session/admin-role check.");
|
|
9645
|
-
}
|
|
9646
|
-
const contentChecks = [
|
|
9647
|
-
[
|
|
9648
|
-
config.modules.repositoryModule,
|
|
9649
|
-
"@gadicc/loom/mail",
|
|
9650
|
-
"Mail repository is not typed against the shared mail contract",
|
|
9651
|
-
],
|
|
9652
|
-
[
|
|
9653
|
-
config.modules.serviceModule,
|
|
9654
|
-
"createLoomMailService",
|
|
9655
|
-
"Mail service is not wired to the shared durable service",
|
|
9656
|
-
],
|
|
9657
|
-
[
|
|
9658
|
-
config.modules.transportModule,
|
|
9659
|
-
"createPostalMailTransport",
|
|
9660
|
-
"Mail transport is not wired to the Postal adapter",
|
|
9661
|
-
],
|
|
9662
|
-
[
|
|
9663
|
-
config.modules.transportModule,
|
|
9664
|
-
"POSTAL_WEBHOOK_PUBLIC_KEYS",
|
|
9665
|
-
"Mail transport does not configure Postal webhook public keys",
|
|
9666
|
-
],
|
|
9667
|
-
[
|
|
9668
|
-
config.entrypoints.webhookRoute,
|
|
9669
|
-
"createPostalWebhookRouteHandler",
|
|
9670
|
-
"Mail webhook route does not use the signed shared route handler",
|
|
9671
|
-
],
|
|
9672
|
-
[
|
|
9673
|
-
config.modules.actionsModule,
|
|
9674
|
-
"authorizeMailAdmin",
|
|
9675
|
-
"Mail admin actions do not enforce the app-owned admin boundary",
|
|
9676
|
-
],
|
|
9677
|
-
[
|
|
9678
|
-
config.entrypoints.adminPage,
|
|
9679
|
-
"authorizeMailAdmin",
|
|
9680
|
-
"Mail admin page does not enforce the app-owned admin boundary",
|
|
9681
|
-
],
|
|
9682
|
-
];
|
|
9683
|
-
for (const [relativePath, snippet, label] of contentChecks) {
|
|
9684
|
-
const text = await readTextIfExists(join(cwd, relativePath));
|
|
9685
|
-
if (text && !text.includes(snippet)) {
|
|
9686
|
-
issues.push(`${label}: ${relativePath}`);
|
|
9687
|
-
suggestions.add("Run `loom add mail` or update loom.json for intentional paths.");
|
|
12121
|
+
const bodyOpen = blanked.indexOf("{", close);
|
|
12122
|
+
const bodyClose = bodyOpen === -1
|
|
12123
|
+
? -1
|
|
12124
|
+
: findJsClosingBracket(blanked, bodyOpen);
|
|
12125
|
+
if (bodyClose === -1 || blanked.slice(close + 1, bodyOpen).trim())
|
|
12126
|
+
continue;
|
|
12127
|
+
const pattern = new RegExp(String.raw `\bcase\s+${PERMISSION_CODE_LITERAL}\s*:`, "g");
|
|
12128
|
+
for (const label of code.slice(bodyOpen, bodyClose).matchAll(pattern)) {
|
|
12129
|
+
if (blanked.startsWith("case", bodyOpen + (label.index ?? 0))) {
|
|
12130
|
+
return true;
|
|
12131
|
+
}
|
|
9688
12132
|
}
|
|
9689
12133
|
}
|
|
9690
|
-
|
|
9691
|
-
|
|
9692
|
-
|
|
12134
|
+
return false;
|
|
12135
|
+
}
|
|
12136
|
+
/** Advisory findings for an app-owned Better Auth api-key verifier. */
|
|
12137
|
+
function checkApiKeysAuthorizerText(modulePath, text) {
|
|
12138
|
+
const warnings = [];
|
|
12139
|
+
const module = {
|
|
12140
|
+
path: modulePath,
|
|
12141
|
+
prepared: prepareJsText(text),
|
|
12142
|
+
};
|
|
12143
|
+
for (const call of findJsCalls(module, "verifyApiKey", { allowMember: true })) {
|
|
12144
|
+
const outer = call.firstArgument === undefined
|
|
12145
|
+
? null
|
|
12146
|
+
: readJsObjectShape(module, call.firstArgument);
|
|
12147
|
+
let bodyValue;
|
|
12148
|
+
for (const entry of outer?.entries ?? []) {
|
|
12149
|
+
if (entry.key === "body")
|
|
12150
|
+
bodyValue = entry.value;
|
|
12151
|
+
}
|
|
12152
|
+
// Skip both warnings when the body cannot be read, rather than guess.
|
|
12153
|
+
const body = bodyValue === undefined
|
|
12154
|
+
? null
|
|
12155
|
+
: readJsObjectShape(module, bodyValue);
|
|
12156
|
+
if (!body)
|
|
12157
|
+
continue;
|
|
12158
|
+
if (body.entries.some((entry) => entry.key === "permissions")) {
|
|
12159
|
+
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}`);
|
|
12160
|
+
}
|
|
12161
|
+
if (body.complete && !body.entries.some((entry) => entry.key === "configId")) {
|
|
12162
|
+
warnings.push(`API-key authorizer calls verifyApiKey() without configId, so keys from any api-key plugin configuration verify: ${modulePath}`);
|
|
12163
|
+
}
|
|
9693
12164
|
}
|
|
9694
|
-
|
|
9695
|
-
|
|
9696
|
-
|
|
12165
|
+
const { blanked, code } = module.prepared;
|
|
12166
|
+
const mapsPermissionCode = hasPermissionCodeCase(module.prepared) ||
|
|
12167
|
+
PERMISSION_CODE_MAPPINGS.some(({ pattern, token }) => [...code.matchAll(pattern)].some((match) => {
|
|
12168
|
+
const tokenIndex = (match.index ?? 0) +
|
|
12169
|
+
match[0].search(new RegExp(`\\b${token}\\b`));
|
|
12170
|
+
return blanked.startsWith(token, tokenIndex);
|
|
12171
|
+
}));
|
|
12172
|
+
if (mapsPermissionCode) {
|
|
12173
|
+
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}`);
|
|
9697
12174
|
}
|
|
9698
|
-
return
|
|
9699
|
-
}
|
|
9700
|
-
function packageDependencySpec(packageJson, dependencyName) {
|
|
9701
|
-
return packageJson.dependencies?.[dependencyName] ??
|
|
9702
|
-
packageJson.devDependencies?.[dependencyName];
|
|
12175
|
+
return [...new Set(warnings)];
|
|
9703
12176
|
}
|
|
9704
|
-
|
|
9705
|
-
|
|
9706
|
-
|
|
12177
|
+
/**
|
|
12178
|
+
* The props an identifier belongs to in blanked text: the enclosing JSX
|
|
12179
|
+
* opening tag (`<Name ... >`) or, outside JSX, the innermost enclosing
|
|
12180
|
+
* `{...}` or `(...)`. Returns null for JSX children text.
|
|
12181
|
+
*/
|
|
12182
|
+
function jsEnclosingPropsRegion(blanked, index) {
|
|
12183
|
+
let depth = 0;
|
|
12184
|
+
for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
|
|
12185
|
+
const char = blanked[cursor];
|
|
12186
|
+
if (char === ")" || char === "]" || char === "}")
|
|
12187
|
+
depth += 1;
|
|
12188
|
+
else if (char === "(" || char === "[" || char === "{") {
|
|
12189
|
+
if (depth === 0) {
|
|
12190
|
+
if (char === "[")
|
|
12191
|
+
continue;
|
|
12192
|
+
const close = findJsClosingBracket(blanked, cursor);
|
|
12193
|
+
return blanked.slice(cursor, close === -1 ? undefined : close + 1);
|
|
12194
|
+
}
|
|
12195
|
+
depth -= 1;
|
|
12196
|
+
}
|
|
12197
|
+
else if (depth === 0 && char === ">" && blanked[cursor - 1] !== "=") {
|
|
12198
|
+
// The identifier follows a closed tag: it is JSX text, not a prop.
|
|
12199
|
+
return null;
|
|
12200
|
+
}
|
|
12201
|
+
else if (depth === 0 && char === "<" && /[A-Za-z]/.test(blanked[cursor + 1] ?? "")) {
|
|
12202
|
+
let end = index;
|
|
12203
|
+
let inner = 0;
|
|
12204
|
+
for (; end < blanked.length; end += 1) {
|
|
12205
|
+
const next = blanked[end];
|
|
12206
|
+
if (next === "(" || next === "[" || next === "{")
|
|
12207
|
+
inner += 1;
|
|
12208
|
+
else if (next === ")" || next === "]" || next === "}")
|
|
12209
|
+
inner -= 1;
|
|
12210
|
+
else if (inner === 0 && next === ">" && blanked[end - 1] !== "=")
|
|
12211
|
+
break;
|
|
12212
|
+
}
|
|
12213
|
+
return blanked.slice(cursor, end + 1);
|
|
12214
|
+
}
|
|
12215
|
+
}
|
|
12216
|
+
return blanked;
|
|
9707
12217
|
}
|
|
9708
12218
|
async function checkApiKeysFeature(cwd, framework, manifest, options) {
|
|
9709
12219
|
const issues = [];
|
|
@@ -9849,6 +12359,57 @@ async function checkApiKeysFeature(cwd, framework, manifest, options) {
|
|
|
9849
12359
|
if (issues.length || warnings.length) {
|
|
9850
12360
|
suggestions.add("Run `loom add api-keys` to restore missing foundation files without overwriting custom modules.");
|
|
9851
12361
|
}
|
|
12362
|
+
// Development hint only: the deprecated flag cannot describe Bearer or
|
|
12363
|
+
// header transports, so its copy can contradict the authorizer.
|
|
12364
|
+
if (!options.production) {
|
|
12365
|
+
for (const pagePath of [
|
|
12366
|
+
config.entrypoints.userPage,
|
|
12367
|
+
config.entrypoints.adminPage,
|
|
12368
|
+
]) {
|
|
12369
|
+
const text = await readTextIfExists(join(cwd, pagePath));
|
|
12370
|
+
const blanked = text ? prepareJsText(text).blanked : "";
|
|
12371
|
+
const uncovered = [
|
|
12372
|
+
...blanked.matchAll(/\bqueryCredentialsEnabled\b/g),
|
|
12373
|
+
].some((match) => {
|
|
12374
|
+
const region = jsEnclosingPropsRegion(blanked, match.index ?? 0);
|
|
12375
|
+
return region !== null && !/\bcredentialOptions\b/.test(region);
|
|
12376
|
+
});
|
|
12377
|
+
if (uncovered) {
|
|
12378
|
+
warnings.push(`API-key page passes the deprecated queryCredentialsEnabled without credentialOptions, so its transport guidance can contradict the authorizer: ${pagePath}`);
|
|
12379
|
+
suggestions.add("Pass the authorizer's credentialOptions to ApiKeysManager (and ApiKeyTransportGuidance), keeping that object in a small import-free module both import.");
|
|
12380
|
+
}
|
|
12381
|
+
}
|
|
12382
|
+
}
|
|
12383
|
+
const authorizerText = await readTextIfExists(join(cwd, config.modules.authorizerModule));
|
|
12384
|
+
if (authorizerText) {
|
|
12385
|
+
const authorizerWarnings = checkApiKeysAuthorizerText(config.modules.authorizerModule, authorizerText);
|
|
12386
|
+
if (authorizerWarnings.length) {
|
|
12387
|
+
warnings.push(...authorizerWarnings);
|
|
12388
|
+
suggestions.add("Use `createBetterAuthApiKeyVerifier` from `@gadicc/loom/apiKeys`: it verifies with a configId and without permissions, then checks the permission itself.");
|
|
12389
|
+
}
|
|
12390
|
+
}
|
|
12391
|
+
const httpEndpoints = config.betterAuthHttpEndpoints;
|
|
12392
|
+
if (httpEndpoints !== undefined && httpEndpoints !== "disabled" &&
|
|
12393
|
+
httpEndpoints !== "app-owned") {
|
|
12394
|
+
issues.push(`Unknown api-keys betterAuthHttpEndpoints value in loom.json: ${JSON.stringify(httpEndpoints)}. Use "disabled" or "app-owned".`);
|
|
12395
|
+
}
|
|
12396
|
+
const authConfig = await inspectBetterAuthApiKeyHttpPaths(cwd, framework, manifest);
|
|
12397
|
+
if (httpEndpoints !== "app-owned" && !authConfig.disabled) {
|
|
12398
|
+
const location = authConfig.authModuleRead
|
|
12399
|
+
? `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(", ")}`
|
|
12400
|
+
: `the auth module could not be read: ${authConfig.authModulePath}`;
|
|
12401
|
+
const message = `Better Auth api-key HTTP endpoints are reachable by any signed-in user (re-enable revoked keys, remove expiry, hard-delete); ${location}`;
|
|
12402
|
+
if (options.production)
|
|
12403
|
+
issues.push(message);
|
|
12404
|
+
else
|
|
12405
|
+
warnings.push(message);
|
|
12406
|
+
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.');
|
|
12407
|
+
}
|
|
12408
|
+
for (const module of authConfig.modules) {
|
|
12409
|
+
if (/\benableSessionForAPIKeys\s*:\s*true\b/.test(module.prepared.blanked)) {
|
|
12410
|
+
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}`);
|
|
12411
|
+
}
|
|
12412
|
+
}
|
|
9852
12413
|
return { issues, suggestions: [...suggestions], warnings };
|
|
9853
12414
|
}
|
|
9854
12415
|
async function checkAuthFeature(cwd, framework, manifest) {
|
|
@@ -10639,6 +13200,22 @@ export async function checkProject(cwd, env = process.env, options = {}) {
|
|
|
10639
13200
|
else if (isLocalPackageSpec(dependency)) {
|
|
10640
13201
|
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.`);
|
|
10641
13202
|
}
|
|
13203
|
+
else if (parseCatalogReference(dependency) && await isPnpmProject(cwd, packageJson)) {
|
|
13204
|
+
// Only pnpm catalogs live in pnpm-workspace.yaml (Yarn 4 has its own).
|
|
13205
|
+
const catalogDependency = await resolveLoomDependencySpec(cwd, packageJson);
|
|
13206
|
+
const unreadable = catalogDependency.catalogEntry
|
|
13207
|
+
? null
|
|
13208
|
+
: findUnreadableLoomCatalog(await readTextIfExists(join(cwd, "pnpm-workspace.yaml")), catalogDependency.catalogName);
|
|
13209
|
+
if (unreadable) {
|
|
13210
|
+
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.`);
|
|
13211
|
+
}
|
|
13212
|
+
else if (!catalogDependency.catalogEntry) {
|
|
13213
|
+
issues.push(`${LOOM_DEPENDENCY} uses \`${dependency}\`, but pnpm-workspace.yaml has no ${LOOM_DEPENDENCY} entry in that catalog.`);
|
|
13214
|
+
}
|
|
13215
|
+
else if (isLocalPackageSpec(catalogDependency.catalogEntry.spec)) {
|
|
13216
|
+
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.`);
|
|
13217
|
+
}
|
|
13218
|
+
}
|
|
10642
13219
|
const manifestPath = join(cwd, "loom.json");
|
|
10643
13220
|
const manifestText = await readTextIfExists(manifestPath);
|
|
10644
13221
|
let manifest = null;
|
|
@@ -10722,7 +13299,7 @@ export async function checkProject(cwd, env = process.env, options = {}) {
|
|
|
10722
13299
|
for (const suggestion of nextGuidanceCheck.suggestions) {
|
|
10723
13300
|
suggestions.add(suggestion);
|
|
10724
13301
|
}
|
|
10725
|
-
const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false);
|
|
13302
|
+
const localDevCheck = await checkManagedLocalDevOverride(cwd, options.production ?? false, options.commandRunner ?? defaultCommandRunner, env);
|
|
10726
13303
|
warnings.push(...localDevCheck.warnings);
|
|
10727
13304
|
issues.push(...localDevCheck.issues);
|
|
10728
13305
|
for (const suggestion of localDevCheck.suggestions) {
|
|
@@ -11129,7 +13706,7 @@ async function runStatus(cwd, io) {
|
|
|
11129
13706
|
? parseJson(installedPackageText, join("node_modules", LOOM_DEPENDENCY, "package.json"))
|
|
11130
13707
|
: null;
|
|
11131
13708
|
const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
|
|
11132
|
-
const
|
|
13709
|
+
const pnpmOverride = getActivePnpmLocalDevOverride(workspaceText, packageJson);
|
|
11133
13710
|
let denoOverride = null;
|
|
11134
13711
|
try {
|
|
11135
13712
|
const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
|
|
@@ -11151,13 +13728,22 @@ async function runStatus(cwd, io) {
|
|
|
11151
13728
|
io.out(`Loom status for ${projectName}`);
|
|
11152
13729
|
io.out("");
|
|
11153
13730
|
io.out("Package:");
|
|
11154
|
-
|
|
13731
|
+
const catalogEntry = parseCatalogReference(dependencySpec)
|
|
13732
|
+
? findLoomCatalogEntry(workspaceText, parseCatalogReference(dependencySpec))
|
|
13733
|
+
: null;
|
|
13734
|
+
io.out(` ${projectMetadata.config}: ${dependencySpec
|
|
13735
|
+
? `${LOOM_DEPENDENCY} ${dependencySpec}${catalogEntry
|
|
13736
|
+
? ` (${catalogEntry.spec} from pnpm-workspace.yaml ${catalogEntry.label})`
|
|
13737
|
+
: ""}`
|
|
13738
|
+
: "not declared"}`);
|
|
11155
13739
|
io.out(` installed: ${installedPackage?.version ?? "not installed"}`);
|
|
11156
13740
|
io.out(` local dev override: ${denoOverride
|
|
11157
13741
|
? `active (${denoOverride.config} links ${denoOverride.link})`
|
|
11158
|
-
:
|
|
11159
|
-
? `active (${
|
|
11160
|
-
:
|
|
13742
|
+
: pnpmOverride?.location === "pnpm-workspace.yaml"
|
|
13743
|
+
? `active (${pnpmOverride.spec})`
|
|
13744
|
+
: pnpmOverride
|
|
13745
|
+
? `active (${formatPnpmOverrideLocation(pnpmOverride.location)}: ${pnpmOverride.spec})`
|
|
13746
|
+
: "none"}`);
|
|
11161
13747
|
io.out(` lockfile local resolution: ${localLockfileResolution ?? "none"}`);
|
|
11162
13748
|
io.out("");
|
|
11163
13749
|
io.out("Project:");
|
|
@@ -11297,8 +13883,9 @@ function printHelp({ out }) {
|
|
|
11297
13883
|
out(" --local-db-host <host> Local PostgreSQL host (default: db.localtest.me).");
|
|
11298
13884
|
out(" --local-db-port <port> Local PostgreSQL port (default: 5432).");
|
|
11299
13885
|
out(" --replace-local-target Replace an existing development URL during local DB setup.");
|
|
13886
|
+
out(" --cwd <dir> Run in <dir>, resolved from the current directory.");
|
|
11300
13887
|
out(" --no-color Disable colored CLI output.");
|
|
11301
|
-
out(" --no-sync Skip automatic local-dev package sync.");
|
|
13888
|
+
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.");
|
|
11302
13889
|
out(" --force Force `loom dev sync` to rebuild and reinstall.");
|
|
11303
13890
|
out(" --name <name> Override the resource name for `loom db neon setup`.");
|
|
11304
13891
|
out(" --plan <plan> Pass a Vercel Marketplace plan id to Neon setup.");
|
|
@@ -12114,7 +14701,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12114
14701
|
io.err("Missing local package path. Example: `loom dev local /path/to/loom`.");
|
|
12115
14702
|
return 1;
|
|
12116
14703
|
}
|
|
12117
|
-
const result = await useLocalDevPackage(cwd, pathInput
|
|
14704
|
+
const result = await useLocalDevPackage(cwd, pathInput, {
|
|
14705
|
+
onLockWait: io.err,
|
|
14706
|
+
});
|
|
12118
14707
|
if (result.changedFiles.length) {
|
|
12119
14708
|
io.out(`Updated ${result.changedFiles.join(", ")}.`);
|
|
12120
14709
|
}
|
|
@@ -12126,6 +14715,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12126
14715
|
}
|
|
12127
14716
|
if (!options.noSync) {
|
|
12128
14717
|
const syncResult = await syncLocalDevPackage(cwd, {
|
|
14718
|
+
onLockWait: io.err,
|
|
12129
14719
|
requireActive: true,
|
|
12130
14720
|
});
|
|
12131
14721
|
for (const note of syncResult.notes) {
|
|
@@ -12137,6 +14727,7 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12137
14727
|
case "sync": {
|
|
12138
14728
|
const result = await syncLocalDevPackage(cwd, {
|
|
12139
14729
|
force: options.force,
|
|
14730
|
+
onLockWait: io.err,
|
|
12140
14731
|
requireActive: true,
|
|
12141
14732
|
});
|
|
12142
14733
|
if (result.changed) {
|
|
@@ -12151,7 +14742,9 @@ async function runDev(cwd, mode, pathInput, io, options = {}) {
|
|
|
12151
14742
|
return 0;
|
|
12152
14743
|
}
|
|
12153
14744
|
case "published": {
|
|
12154
|
-
const result = await usePublishedDevPackage(cwd
|
|
14745
|
+
const result = await usePublishedDevPackage(cwd, {
|
|
14746
|
+
onLockWait: io.err,
|
|
14747
|
+
});
|
|
12155
14748
|
if (result.changedFiles.length) {
|
|
12156
14749
|
io.out(`Updated ${result.changedFiles.join(", ")}.`);
|
|
12157
14750
|
}
|
|
@@ -12229,7 +14822,7 @@ async function runCheck(cwd, strictSkills, production, network, noProgress, noCo
|
|
|
12229
14822
|
export async function runCli(args = process.argv.slice(2), io = {
|
|
12230
14823
|
err: (line) => console.error(line),
|
|
12231
14824
|
out: (line) => console.log(line),
|
|
12232
|
-
}) {
|
|
14825
|
+
}, options = {}) {
|
|
12233
14826
|
const parsed = parseArgs({
|
|
12234
14827
|
allowPositionals: true,
|
|
12235
14828
|
args,
|
|
@@ -12299,13 +14892,29 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12299
14892
|
!addListOnly &&
|
|
12300
14893
|
!productionCheck &&
|
|
12301
14894
|
!parsed.values["no-sync"]) {
|
|
12302
|
-
|
|
14895
|
+
// Taken before waiting on another sync, so a refresh by that sync shows
|
|
14896
|
+
// up as a change and this process does not run the code it replaced.
|
|
14897
|
+
const loadedPackageSignature = await captureLoadedLocalLoomSignature(cwd, process.env);
|
|
14898
|
+
const syncResult = await syncLocalDevPackage(cwd, {
|
|
14899
|
+
commandOutput: command === "env" ? "stderr" : "stdout",
|
|
14900
|
+
commandRunner: options.commandRunner,
|
|
14901
|
+
loadedPackageSignature,
|
|
14902
|
+
onLockWait: io.err,
|
|
14903
|
+
});
|
|
12303
14904
|
if (syncResult.changed) {
|
|
14905
|
+
// `loom env` only loads env files before spawning the wrapped command,
|
|
14906
|
+
// a new process that loads the refreshed package, so it continues.
|
|
14907
|
+
// Every other command would run this process's stale Loom code, so it
|
|
14908
|
+
// stops with a retry status instead of reporting success.
|
|
14909
|
+
const report = command === "env" ? io.err : io.out;
|
|
12304
14910
|
for (const note of syncResult.notes) {
|
|
12305
|
-
|
|
14911
|
+
report(`Note: ${note}`);
|
|
12306
14912
|
}
|
|
12307
|
-
|
|
12308
|
-
|
|
14913
|
+
if (command !== "env") {
|
|
14914
|
+
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}).`);
|
|
14915
|
+
return LOOM_LOCAL_DEV_RERUN_EXIT_CODE;
|
|
14916
|
+
}
|
|
14917
|
+
io.err("Running the wrapped command with the refreshed Loom package.");
|
|
12309
14918
|
}
|
|
12310
14919
|
}
|
|
12311
14920
|
switch (command) {
|
|
@@ -12350,7 +14959,7 @@ export async function runCli(args = process.argv.slice(2), io = {
|
|
|
12350
14959
|
acceptUnknownLicense: parsed.values["accept-unknown-license"],
|
|
12351
14960
|
});
|
|
12352
14961
|
case "env":
|
|
12353
|
-
return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io);
|
|
14962
|
+
return await runEnvCommand(cwd, arg1, [arg2, ...rest].filter((arg) => arg !== undefined), io, { commandRunner: options.commandRunner });
|
|
12354
14963
|
case "db":
|
|
12355
14964
|
return await runDb(cwd, arg1, [arg2, ...rest].filter(Boolean), io, {
|
|
12356
14965
|
connect: parsed.values.connect,
|