@context-forge/core 0.19.1 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/config/ConfigKeys.js +2 -2
  2. package/dist/config/ConfigKeys.js.map +1 -1
  3. package/dist/config/guideExclude.d.ts +7 -1
  4. package/dist/config/guideExclude.d.ts.map +1 -1
  5. package/dist/config/guideExclude.js +27 -7
  6. package/dist/config/guideExclude.js.map +1 -1
  7. package/dist/guides/GuideDetector.d.ts.map +1 -1
  8. package/dist/guides/GuideDetector.js +8 -39
  9. package/dist/guides/GuideDetector.js.map +1 -1
  10. package/dist/guides/GuideManager.d.ts +15 -6
  11. package/dist/guides/GuideManager.d.ts.map +1 -1
  12. package/dist/guides/GuideManager.js +37 -7
  13. package/dist/guides/GuideManager.js.map +1 -1
  14. package/dist/guides/configExcludeCommit.d.ts +23 -0
  15. package/dist/guides/configExcludeCommit.d.ts.map +1 -0
  16. package/dist/guides/configExcludeCommit.js +65 -0
  17. package/dist/guides/configExcludeCommit.js.map +1 -0
  18. package/dist/guides/gitExec.d.ts +1 -1
  19. package/dist/guides/gitExec.d.ts.map +1 -1
  20. package/dist/guides/gitExec.js +1 -1
  21. package/dist/guides/gitExec.js.map +1 -1
  22. package/dist/guides/guideTreeDiff.d.ts +8 -0
  23. package/dist/guides/guideTreeDiff.d.ts.map +1 -0
  24. package/dist/guides/guideTreeDiff.js +86 -0
  25. package/dist/guides/guideTreeDiff.js.map +1 -0
  26. package/dist/guides/index.d.ts +1 -1
  27. package/dist/guides/index.d.ts.map +1 -1
  28. package/dist/guides/index.js.map +1 -1
  29. package/dist/guides/strategies/TarballStrategy.d.ts +20 -38
  30. package/dist/guides/strategies/TarballStrategy.d.ts.map +1 -1
  31. package/dist/guides/strategies/TarballStrategy.js +119 -172
  32. package/dist/guides/strategies/TarballStrategy.js.map +1 -1
  33. package/dist/guides/strategies/tarballSwap.d.ts +12 -0
  34. package/dist/guides/strategies/tarballSwap.d.ts.map +1 -0
  35. package/dist/guides/strategies/tarballSwap.js +66 -0
  36. package/dist/guides/strategies/tarballSwap.js.map +1 -0
  37. package/dist/guides/tarballSource.d.ts +68 -0
  38. package/dist/guides/tarballSource.d.ts.map +1 -0
  39. package/dist/guides/tarballSource.js +171 -0
  40. package/dist/guides/tarballSource.js.map +1 -0
  41. package/dist/guides/types.d.ts +41 -4
  42. package/dist/guides/types.d.ts.map +1 -1
  43. package/dist/guides/types.js +7 -2
  44. package/dist/guides/types.js.map +1 -1
  45. package/dist/guides/versionTags.d.ts +3 -0
  46. package/dist/guides/versionTags.d.ts.map +1 -0
  47. package/dist/guides/versionTags.js +17 -0
  48. package/dist/guides/versionTags.js.map +1 -0
  49. package/dist/index.d.ts +1 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guideTreeDiff.d.ts","sourceRoot":"","sources":["../../src/guides/guideTreeDiff.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA6D/C;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAmBlG"}
@@ -0,0 +1,86 @@
1
+ // Compares an installed guide directory with a staged one, for the update preview.
2
+ import { lstat, readFile, readdir, readlink } from 'fs/promises';
3
+ import { join } from 'path';
4
+ import { EXCLUDE_RECORD_FILE, VERSION_MARKER_FILE } from './types.js';
5
+ /** cf's own bookkeeping, written fresh on every extract; never part of the guide content. */
6
+ const BOOKKEEPING_FILES = new Set([VERSION_MARKER_FILE, EXCLUDE_RECORD_FILE]);
7
+ /** Run a filesystem call, naming the path in the error so a failed diff says what it could not read. */
8
+ async function atPath(path, read) {
9
+ try {
10
+ return await read();
11
+ }
12
+ catch (err) {
13
+ const reason = err instanceof Error ? err.message : String(err);
14
+ throw new Error(`Cannot read ${path} while comparing guide trees: ${reason}`, { cause: err });
15
+ }
16
+ }
17
+ /** Whether anything exists at `path`; any error other than "not found" propagates. */
18
+ async function exists(path) {
19
+ try {
20
+ await lstat(path);
21
+ return true;
22
+ }
23
+ catch (err) {
24
+ if (err instanceof Error && 'code' in err && err.code === 'ENOENT')
25
+ return false;
26
+ throw err;
27
+ }
28
+ }
29
+ /** Relative path (forward slashes) to entry for every file and symlink under `root`. */
30
+ async function collectEntries(root, relative = '', into = new Map()) {
31
+ const directory = relative === '' ? root : join(root, relative);
32
+ const children = await atPath(directory, () => readdir(directory, { withFileTypes: true }));
33
+ for (const child of children) {
34
+ const childRelative = relative === '' ? child.name : `${relative}/${child.name}`;
35
+ const childPath = join(root, childRelative);
36
+ if (child.isDirectory()) {
37
+ await collectEntries(root, childRelative, into);
38
+ }
39
+ else if (child.isSymbolicLink()) {
40
+ into.set(childRelative, { kind: 'link', target: await atPath(childPath, () => readlink(childPath)) });
41
+ }
42
+ else {
43
+ const { size } = await atPath(childPath, () => lstat(childPath));
44
+ into.set(childRelative, { kind: 'file', path: childPath, size });
45
+ }
46
+ }
47
+ return into;
48
+ }
49
+ async function entriesDiffer(current, staged) {
50
+ if (current.kind === 'link' || staged.kind === 'link') {
51
+ return current.kind !== staged.kind || (current.kind === 'link' && staged.kind === 'link' && current.target !== staged.target);
52
+ }
53
+ if (current.size !== staged.size)
54
+ return true;
55
+ const [currentBytes, stagedBytes] = await Promise.all([
56
+ atPath(current.path, () => readFile(current.path)),
57
+ atPath(staged.path, () => readFile(staged.path)),
58
+ ]);
59
+ return !currentBytes.equals(stagedBytes);
60
+ }
61
+ /**
62
+ * Count how the staged guide differs from the installed one. A missing
63
+ * `currentDir` (nothing installed yet) is not an error: every staged file is
64
+ * added. A missing `stagingDir` is an error, as is any unreadable path.
65
+ */
66
+ export async function diffGuideTrees(currentDir, stagingDir) {
67
+ const staged = await collectEntries(stagingDir);
68
+ // No installed guide yet (first install): everything staged counts as added.
69
+ const current = (await exists(currentDir)) ? await collectEntries(currentDir) : new Map();
70
+ for (const name of BOOKKEEPING_FILES) {
71
+ staged.delete(name);
72
+ current.delete(name);
73
+ }
74
+ let added = 0;
75
+ let changed = 0;
76
+ for (const [relative, stagedEntry] of staged) {
77
+ const currentEntry = current.get(relative);
78
+ if (!currentEntry)
79
+ added++;
80
+ else if (await entriesDiffer(currentEntry, stagedEntry))
81
+ changed++;
82
+ }
83
+ const removed = [...current.keys()].filter((relative) => !staged.has(relative)).length;
84
+ return { added, removed, changed };
85
+ }
86
+ //# sourceMappingURL=guideTreeDiff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guideTreeDiff.js","sourceRoot":"","sources":["../../src/guides/guideTreeDiff.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAGtE,6FAA6F;AAC7F,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,CAAC,mBAAmB,EAAE,mBAAmB,CAAC,CAAC,CAAC;AAKnG,wGAAwG;AACxG,KAAK,UAAU,MAAM,CAAI,IAAY,EAAE,IAAsB;IAC3D,IAAI,CAAC;QACH,OAAO,MAAM,IAAI,EAAE,CAAC;IACtB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,MAAM,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAChE,MAAM,IAAI,KAAK,CAAC,eAAe,IAAI,iCAAiC,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IAChG,CAAC;AACH,CAAC;AAED,sFAAsF;AACtF,KAA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KAAK,UAAU,cAAc,CAAC,UAAkB,EAAE,UAAkB;IACzE,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;IAChD,6EAA6E;IAC7E,MAAM,OAAO,GAAG,CAAC,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAqB,CAAC;IAC7G,KAAK,MAAM,IAAI,IAAI,iBAAiB,EAAE,CAAC;QACrC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACpB,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAED,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,KAAK,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,IAAI,MAAM,EAAE,CAAC;QAC7C,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC3C,IAAI,CAAC,YAAY;YAAE,KAAK,EAAE,CAAC;aACtB,IAAI,MAAM,aAAa,CAAC,YAAY,EAAE,WAAW,CAAC;YAAE,OAAO,EAAE,CAAC;IACrE,CAAC;IACD,MAAM,OAAO,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;IAEvF,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AACrC,CAAC"}
@@ -1,6 +1,6 @@
1
1
  export { GuideManager } from './GuideManager.js';
2
2
  export { GuideDetector } from './GuideDetector.js';
3
- export { type GuideInfo, type GuideMethod, type InstallResult, type UpdateResult, type DetectionResult, type InstallStrategy, type SubmoduleCheckoutState, type EnsureCheckoutResult, CHECKOUT_STATE_LABELS, GUIDE_INIT_TIMEOUT_MS, GUIDE_MANAGED_NOTICE, GUIDE_METHODS, GUIDE_METHOD_DEPRECATED_ALIASES, normalizeGuideMethod, isDeprecatedGuideMethodAlias, DEFAULT_SOURCE_GIT, DEFAULT_SOURCE_API, GUIDE_RELATIVE_PATH, VERSION_MARKER_FILE, GUIDE_STRATEGIES, DEFAULT_GUIDE_METHOD, describeGuideStrategy, guideMethodDeprecationMessage, guideExcludeNotices, type GuideExcludeNoticeSource, } from './types.js';
3
+ export { type GuideInfo, type GuideMethod, type InstallResult, type UpdateResult, type GuidePreview, type GuideVersionChange, type DetectionResult, type InstallStrategy, type SubmoduleCheckoutState, type EnsureCheckoutResult, CHECKOUT_STATE_LABELS, GUIDE_INIT_TIMEOUT_MS, GUIDE_MANAGED_NOTICE, GUIDE_METHODS, GUIDE_METHOD_DEPRECATED_ALIASES, normalizeGuideMethod, isDeprecatedGuideMethodAlias, DEFAULT_SOURCE_GIT, DEFAULT_SOURCE_API, GUIDE_RELATIVE_PATH, VERSION_MARKER_FILE, GUIDE_STRATEGIES, DEFAULT_GUIDE_METHOD, describeGuideStrategy, guideMethodDeprecationMessage, guideExcludeNotices, type GuideExcludeNoticeSource, } from './types.js';
4
4
  export { GUIDE_OFFLINE_REMEDIATION } from './gitExec.js';
5
5
  export { type BranchGuardVerdict, evaluateBranchGuard, BranchGuardBlockedError, BranchGuardWarnError, } from './branchGuard.js';
6
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/guides/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,EACb,+BAA+B,EAC/B,oBAAoB,EACpB,4BAA4B,EAC5B,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,EACnB,KAAK,wBAAwB,GAC9B,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EACL,KAAK,kBAAkB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/guides/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EACL,KAAK,SAAS,EACd,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,oBAAoB,EACzB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,EACb,+BAA+B,EAC/B,oBAAoB,EACpB,4BAA4B,EAC5B,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,EACnB,KAAK,wBAAwB,GAC9B,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EACL,KAAK,kBAAkB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/guides/index.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EASL,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,EACb,+BAA+B,EAC/B,oBAAoB,EACpB,4BAA4B,EAC5B,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,GAEpB,MAAM,YAAY,CAAC;AACpB,mFAAmF;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAEL,mBAAmB,EACnB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/guides/index.ts"],"names":[],"mappings":"AAAA,oCAAoC;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAWL,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,aAAa,EACb,+BAA+B,EAC/B,oBAAoB,EACpB,4BAA4B,EAC5B,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,qBAAqB,EACrB,6BAA6B,EAC7B,mBAAmB,GAEpB,MAAM,YAAY,CAAC;AACpB,mFAAmF;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAEL,mBAAmB,EACnB,uBAAuB,EACvB,oBAAoB,GACrB,MAAM,kBAAkB,CAAC"}
@@ -1,24 +1,5 @@
1
- import type { InstallStrategy, InstallResult, UpdateResult, DetectionResult } from '../types.js';
2
- /** Names of the proxy variables currently set, so a failure can say which applied. */
3
- export declare function activeProxyEnvVars(env?: NodeJS.ProcessEnv): string[];
4
- /** Minimal header access shared by undici and WHATWG Response objects. */
5
- interface HeaderReader {
6
- get(name: string): string | null;
7
- }
8
- /**
9
- * GitHub signals an exhausted rate limit with 403 (or 429) plus
10
- * x-ratelimit-remaining: 0. Returns a specific message for that case, null
11
- * for any other failure status.
12
- */
13
- export declare function describeRateLimit(status: number, headers: HeaderReader): string | null;
14
- /**
15
- * Parse owner/repo from a GitHub source URL.
16
- * Supports: https://github.com/{owner}/{repo}.git and https://github.com/{owner}/{repo}
17
- */
18
- export declare function parseGitHubOwnerRepo(source: string): {
19
- owner: string;
20
- repo: string;
21
- };
1
+ import type { InstallStrategy, InstallResult, UpdateResult, DetectionResult, TarballUpdateOptions } from '../types.js';
2
+ export { activeProxyEnvVars, describeRateLimit, parseGitHubOwnerRepo } from '../tarballSource.js';
22
3
  /** Whether to drop a raw tarball entry, and which guide.exclude patterns match it. */
23
4
  export interface TarballEntryDecision {
24
5
  skip: boolean;
@@ -46,31 +27,32 @@ export declare class TarballStrategy implements InstallStrategy {
46
27
  /** The parsed guide.exclude list; empty means nothing is excluded. */
47
28
  constructor(exclude?: readonly string[]);
48
29
  detect(_projectPath: string, targetDir: string): Promise<DetectionResult | null>;
49
- install(projectPath: string, source: string, targetDir: string): Promise<InstallResult>;
50
- update(projectPath: string, targetDir: string, source: string): Promise<UpdateResult>;
30
+ install(projectPath: string, source: string, targetDir: string, options?: TarballUpdateOptions): Promise<InstallResult>;
31
+ update(projectPath: string, targetDir: string, source: string, options?: TarballUpdateOptions): Promise<UpdateResult>;
51
32
  private sortedExclude;
52
33
  /** Result fields for the applied and unmatched excludes, each only when not empty. */
53
34
  private excludeFields;
35
+ /** Stage the new guide, then swap it into place (install: nothing to preview). */
36
+ private extractAndSwap;
54
37
  /**
55
- * Build the new guide in a staging directory, then swap it into place. Any
56
- * failure before the swap (network, rate limit, broken archive) leaves the
57
- * existing guide untouched; a failed swap restores it. Returns the
58
- * guide.exclude patterns that matched no archive entry.
38
+ * Build the new guide in a staging directory. Any failure (network, rate
39
+ * limit, broken archive) removes the staging directory and leaves the
40
+ * existing guide untouched. Returns the guide.exclude patterns that
41
+ * matched no archive entry.
59
42
  */
60
- private extractAndSwap;
43
+ private stage;
61
44
  /**
62
- * Move the previous guide back after a failed swap. If that also fails, the
63
- * guide exists only at `previous`: throw an error that says where, keeping
64
- * the swap failure as the cause so the root error is not lost.
45
+ * Diff the staged guide against the installed one and decide whether to
46
+ * swap. The staging directory is removed on every path except `proceed`,
47
+ * including when the diff or the confirm callback throws.
65
48
  */
66
- private restorePrevious;
49
+ private reviewStaged;
67
50
  /**
68
- * Fetch latest tag from remote using git ls-remote. Real failures (network,
69
- * auth, invalid remote) propagate — only a genuinely tag-less remote yields null.
51
+ * Open the resolved archive (remote tag or local file) and extract it into
52
+ * extractDir. A gunzip, tar or read error names the archive. An archive with
53
+ * more than one top-level directory is refused: the extract strips exactly
54
+ * one level, so a second root would land its files loose in the guide.
70
55
  */
71
- private fetchLatestTag;
72
- /** Download tarball from GitHub API and extract into extractDir */
73
- private downloadAndExtract;
56
+ private openAndExtract;
74
57
  }
75
- export {};
76
58
  //# sourceMappingURL=TarballStrategy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"TarballStrategy.d.ts","sourceRoot":"","sources":["../../../src/guides/strategies/TarballStrategy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAYjG,sFAAsF;AACtF,wBAAgB,kBAAkB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,EAAE,CAEjF;AAED,0EAA0E;AAC1E,UAAU,YAAY;IACpB,GAAG,CAAC,IAAI,EAAE,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;IAOrB,kFAAkF;YACpE,cAAc;IAM5B;;;;;OAKG;YACW,KAAK;IAwBnB;;;;OAIG;YACW,YAAY;IAwB1B;;;;;OAKG;YACW,cAAc;CAmC7B"}
@@ -1,52 +1,18 @@
1
1
  // Tarball-based (manual) guide installation strategy
2
- import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, renameSync } from 'fs';
3
- import { basename, dirname, join } from 'path';
2
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
3
+ import { join } from 'path';
4
4
  import { createGunzip } from 'zlib';
5
- import { Readable } from 'stream';
6
5
  import { pipeline } from 'stream/promises';
7
6
  import { extract } from 'tar';
8
- import { fetch as undiciFetch, EnvHttpProxyAgent } from 'undici';
9
7
  import { VERSION_MARKER_FILE, EXCLUDE_RECORD_FILE, DEFAULT_SOURCE_GIT, GUIDE_RELATIVE_PATH } from '../types.js';
10
- import { gitExec, withNetworkErrorHint, commitPathIfChanged } from '../gitExec.js';
8
+ import { commitPathIfChanged } from '../gitExec.js';
9
+ import { resolveTarballSource, openArchive } from '../tarballSource.js';
10
+ import { diffGuideTrees } from '../guideTreeDiff.js';
11
+ import { decideConfigCommit } from '../configExcludeCommit.js';
12
+ import { clearLeftovers, removeStaging, stagingPathFor, swapIntoPlace } from './tarballSwap.js';
11
13
  import { matchingGuidePatterns, sameExcludeList } from '../../config/guideExclude.js';
12
- /**
13
- * Proxy variables honored by the tarball download. Git reads these on its own
14
- * for the ls-remote half; Node's built-in fetch does not, so the download goes
15
- * through undici's EnvHttpProxyAgent, which reads the same set (and NO_PROXY).
16
- */
17
- const PROXY_ENV_VARS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'];
18
- /** Names of the proxy variables currently set, so a failure can say which applied. */
19
- export function activeProxyEnvVars(env = process.env) {
20
- return PROXY_ENV_VARS.filter((name) => Boolean(env[name]));
21
- }
22
- /**
23
- * GitHub signals an exhausted rate limit with 403 (or 429) plus
24
- * x-ratelimit-remaining: 0. Returns a specific message for that case, null
25
- * for any other failure status.
26
- */
27
- export function describeRateLimit(status, headers) {
28
- if (status !== 403 && status !== 429)
29
- return null;
30
- if (headers.get('x-ratelimit-remaining') !== '0')
31
- return null;
32
- const reset = headers.get('x-ratelimit-reset');
33
- const resetAt = reset && /^\d+$/.test(reset)
34
- ? ` Resets at ${new Date(Number(reset) * 1000).toLocaleTimeString()}.`
35
- : '';
36
- return ('GitHub API rate limit exceeded: unauthenticated requests are limited to 60 per hour ' +
37
- `per source IP, shared by everyone behind the same NAT or proxy.${resetAt}`);
38
- }
39
- /**
40
- * Parse owner/repo from a GitHub source URL.
41
- * Supports: https://github.com/{owner}/{repo}.git and https://github.com/{owner}/{repo}
42
- */
43
- export function parseGitHubOwnerRepo(source) {
44
- const match = /github\.com\/([^/]+)\/([^/.]+)/.exec(source);
45
- if (!match) {
46
- throw new Error(`Cannot parse GitHub owner/repo from source URL: ${source}`);
47
- }
48
- return { owner: match[1], repo: match[2] };
49
- }
14
+ // Moved to tarballSource; re-exported so existing importers keep working.
15
+ export { activeProxyEnvVars, describeRateLimit, parseGitHubOwnerRepo } from '../tarballSource.js';
50
16
  /**
51
17
  * Top-level entries dropped from the extracted tarball. A tarball install
52
18
  * promises plain files with no git wiring, and the guide repo has at times
@@ -88,15 +54,15 @@ export function readExcludeRecord(guideDir) {
88
54
  .filter((line) => line !== '')
89
55
  .sort();
90
56
  }
91
- /**
92
- * Suffixes for the sibling directories extractAndSwap uses next to the guide
93
- * directory (e.g. project-documents/.ai-project-guide.staging). Siblings, so
94
- * both renames stay on one filesystem.
95
- */
96
- const STAGING_SUFFIX = '.staging';
97
- const PREVIOUS_SUFFIX = '.previous';
98
- function siblingPath(targetDir, suffix) {
99
- return join(dirname(targetDir), `.${basename(targetDir)}${suffix}`);
57
+ /** The version marker of a guide directory, or null when there is none. */
58
+ function readVersionMarker(guideDir) {
59
+ const markerPath = join(guideDir, VERSION_MARKER_FILE);
60
+ return existsSync(markerPath) ? readFileSync(markerPath, 'utf-8').trim() || null : null;
61
+ }
62
+ /** Whether the installed and staged guides carry the same version marker and exclude record. */
63
+ function bookkeepingMatches(installedDir, stagedDir) {
64
+ return (readVersionMarker(installedDir) === readVersionMarker(stagedDir) &&
65
+ sameExcludeList(readExcludeRecord(installedDir), readExcludeRecord(stagedDir)));
100
66
  }
101
67
  export class TarballStrategy {
102
68
  exclude;
@@ -116,26 +82,27 @@ export class TarballStrategy {
116
82
  return Promise.resolve(null);
117
83
  }
118
84
  }
119
- async install(projectPath, source, targetDir) {
120
- const resolvedSource = source || DEFAULT_SOURCE_GIT;
121
- const latestTag = await this.fetchLatestTag(resolvedSource);
122
- if (!latestTag) {
123
- throw new Error('Could not determine latest version from remote.');
124
- }
125
- const unmatched = await this.extractAndSwap(resolvedSource, latestTag, targetDir);
85
+ async install(projectPath, source, targetDir, options = {}) {
86
+ const resolved = await resolveTarballSource({
87
+ source: source || DEFAULT_SOURCE_GIT,
88
+ version: options.version,
89
+ projectRoot: options.sourceRoot ?? projectPath,
90
+ });
91
+ const tag = resolved.tag;
92
+ const unmatched = await this.extractAndSwap(resolved, targetDir);
126
93
  // Same commit the submodule strategy makes, so a tarball install does not
127
94
  // leave the guide untracked for the user to notice later.
128
- const committed = await commitPathIfChanged(projectPath, GUIDE_RELATIVE_PATH, `docs: install ai-project-guide ${latestTag}`);
95
+ const committed = await commitPathIfChanged(projectPath, GUIDE_RELATIVE_PATH, `docs: install ai-project-guide ${tag}`);
129
96
  return {
130
97
  success: true,
131
- version: latestTag,
98
+ version: tag,
132
99
  method: 'tarball',
133
100
  path: targetDir,
134
101
  committed,
135
102
  ...this.excludeFields(unmatched),
136
103
  };
137
104
  }
138
- async update(projectPath, targetDir, source) {
105
+ async update(projectPath, targetDir, source, options = {}) {
139
106
  const markerPath = join(targetDir, VERSION_MARKER_FILE);
140
107
  let previousVersion = null;
141
108
  try {
@@ -144,26 +111,44 @@ export class TarballStrategy {
144
111
  catch {
145
112
  // No previous version
146
113
  }
147
- const latestTag = await this.fetchLatestTag(source);
148
- if (!latestTag) {
149
- throw new Error('Could not determine latest version from remote.');
150
- }
114
+ const resolved = await resolveTarballSource({
115
+ source,
116
+ version: options.version,
117
+ projectRoot: options.sourceRoot ?? projectPath,
118
+ });
119
+ const tag = resolved.tag;
151
120
  const excludeDiffers = !sameExcludeList(readExcludeRecord(targetDir), this.sortedExclude());
152
- if (previousVersion === latestTag && !excludeDiffers) {
153
- return { success: true, previousVersion, newVersion: latestTag, method: 'tarball' };
121
+ // A local archive always stages: the same 'local' marker can name different archives.
122
+ if (resolved.kind === 'remote' && previousVersion === tag && !excludeDiffers) {
123
+ return { success: true, previousVersion, newVersion: tag, method: 'tarball' };
154
124
  }
155
125
  // Same version but a different exclude list: re-extract the same tag.
156
- const excludeChanged = previousVersion === latestTag;
157
- const unmatched = await this.extractAndSwap(source, latestTag, targetDir);
158
- const committed = await commitPathIfChanged(projectPath, GUIDE_RELATIVE_PATH, excludeChanged
159
- ? `docs: re-extract ai-project-guide ${latestTag} (guide.exclude changed)`
160
- : `docs: update ai-project-guide ${latestTag}`);
126
+ const excludeChanged = previousVersion === tag && excludeDiffers;
127
+ const unmatched = await this.stage(resolved, targetDir);
128
+ const { outcome, preview } = await this.reviewStaged(targetDir, options.confirm, { from: previousVersion, to: tag });
129
+ // Nothing is swapped or committed for either of these; the guide is untouched.
130
+ if (outcome === 'unchanged') {
131
+ return { success: true, previousVersion, newVersion: previousVersion, method: 'tarball', unchanged: true, preview };
132
+ }
133
+ if (outcome === 'cancelled') {
134
+ return { success: false, previousVersion, newVersion: previousVersion, method: 'tarball', cancelled: true, preview };
135
+ }
136
+ swapIntoPlace(targetDir);
137
+ // A changed guide.exclude lives in .context-forge.toml; commit it with the
138
+ // re-extract it caused, when that file holds no other uncommitted edits.
139
+ const configDecision = excludeDiffers ? await decideConfigCommit(projectPath) : { add: false };
140
+ const committed = await commitPathIfChanged(projectPath, configDecision.add ? [GUIDE_RELATIVE_PATH, configDecision.relativePath] : GUIDE_RELATIVE_PATH, excludeChanged
141
+ ? `docs: re-extract ai-project-guide ${tag} (guide.exclude changed)`
142
+ : `docs: update ai-project-guide ${tag}`);
161
143
  return {
162
144
  success: true,
163
145
  previousVersion,
164
- newVersion: latestTag,
146
+ newVersion: tag,
165
147
  method: 'tarball',
166
148
  committed,
149
+ preview,
150
+ ...(excludeDiffers ? { configCommitted: configDecision.add && committed } : {}),
151
+ ...(!configDecision.add && configDecision.notice ? { configNotice: configDecision.notice } : {}),
167
152
  ...this.excludeFields(unmatched),
168
153
  ...(excludeChanged ? { excludeChanged: true } : {}),
169
154
  };
@@ -178,139 +163,101 @@ export class TarballStrategy {
178
163
  ...(unmatched.length > 0 ? { unmatchedExclude: unmatched } : {}),
179
164
  };
180
165
  }
166
+ /** Stage the new guide, then swap it into place (install: nothing to preview). */
167
+ async extractAndSwap(resolved, targetDir) {
168
+ const unmatched = await this.stage(resolved, targetDir);
169
+ swapIntoPlace(targetDir);
170
+ return unmatched;
171
+ }
181
172
  /**
182
- * Build the new guide in a staging directory, then swap it into place. Any
183
- * failure before the swap (network, rate limit, broken archive) leaves the
184
- * existing guide untouched; a failed swap restores it. Returns the
185
- * guide.exclude patterns that matched no archive entry.
173
+ * Build the new guide in a staging directory. Any failure (network, rate
174
+ * limit, broken archive) removes the staging directory and leaves the
175
+ * existing guide untouched. Returns the guide.exclude patterns that
176
+ * matched no archive entry.
186
177
  */
187
- async extractAndSwap(source, tag, targetDir) {
188
- const staging = siblingPath(targetDir, STAGING_SUFFIX);
189
- const previous = siblingPath(targetDir, PREVIOUS_SUFFIX);
190
- // Leftovers from an earlier crash
191
- rmSync(staging, { recursive: true, force: true });
192
- rmSync(previous, { recursive: true, force: true });
178
+ async stage(resolved, targetDir) {
179
+ const staging = stagingPathFor(targetDir);
180
+ clearLeftovers(targetDir);
193
181
  const matched = new Set();
194
182
  try {
195
- await this.downloadAndExtract(source, tag, staging, (entryPath) => {
183
+ await this.openAndExtract(resolved, staging, (entryPath) => {
196
184
  const decision = decideTarballEntry(entryPath, this.exclude);
197
185
  for (const pattern of decision.matchedExclude)
198
186
  matched.add(pattern);
199
187
  return !decision.skip;
200
188
  });
201
- writeFileSync(join(staging, VERSION_MARKER_FILE), tag, 'utf-8');
189
+ writeFileSync(join(staging, VERSION_MARKER_FILE), resolved.tag, 'utf-8');
202
190
  if (this.exclude.length > 0) {
203
191
  writeFileSync(join(staging, EXCLUDE_RECORD_FILE), this.sortedExclude().join('\n') + '\n', 'utf-8');
204
192
  }
205
193
  }
206
194
  catch (err) {
207
195
  // Don't leave a partial staging dir in the user's repo; the guide itself is untouched.
208
- rmSync(staging, { recursive: true, force: true });
196
+ removeStaging(targetDir);
209
197
  throw err;
210
198
  }
211
- const hadGuide = existsSync(targetDir);
212
- if (hadGuide)
213
- renameSync(targetDir, previous);
214
- try {
215
- renameSync(staging, targetDir);
216
- }
217
- catch (err) {
218
- if (hadGuide)
219
- this.restorePrevious(previous, targetDir, err);
220
- throw err;
221
- }
222
- rmSync(previous, { recursive: true, force: true });
223
199
  return this.exclude.filter((pattern) => !matched.has(pattern));
224
200
  }
225
201
  /**
226
- * Move the previous guide back after a failed swap. If that also fails, the
227
- * guide exists only at `previous`: throw an error that says where, keeping
228
- * the swap failure as the cause so the root error is not lost.
202
+ * Diff the staged guide against the installed one and decide whether to
203
+ * swap. The staging directory is removed on every path except `proceed`,
204
+ * including when the diff or the confirm callback throws.
229
205
  */
230
- restorePrevious(previous, targetDir, swapError) {
231
- let restoreFailure = null;
206
+ async reviewStaged(targetDir, confirm, versions) {
207
+ let proceed = false;
232
208
  try {
233
- renameSync(previous, targetDir);
234
- }
235
- catch (restoreError) {
236
- restoreFailure = { reason: restoreError instanceof Error ? restoreError.message : String(restoreError) };
209
+ const preview = await diffGuideTrees(targetDir, stagingPathFor(targetDir));
210
+ if (preview.added + preview.removed + preview.changed === 0) {
211
+ // Identical files. Only a true no-op when cf's own bookkeeping matches
212
+ // too; otherwise swap (no prompt: nothing visible changes) so the
213
+ // marker and exclude record do not go stale.
214
+ if (bookkeepingMatches(targetDir, stagingPathFor(targetDir)))
215
+ return { outcome: 'unchanged', preview };
216
+ proceed = true;
217
+ return { outcome: 'proceed', preview };
218
+ }
219
+ if (confirm && !(await confirm(preview, versions)))
220
+ return { outcome: 'cancelled', preview };
221
+ proceed = true;
222
+ return { outcome: 'proceed', preview };
237
223
  }
238
- // Thrown outside the catch: the cause is the swap failure, not the restore failure.
239
- if (restoreFailure) {
240
- throw new Error(`Installing the new guide failed, and restoring the previous guide also failed (${restoreFailure.reason}). ` +
241
- `The previous guide is at ${previous}; move it back to ${targetDir} by hand.`, { cause: swapError });
224
+ finally {
225
+ if (!proceed)
226
+ removeStaging(targetDir);
242
227
  }
243
228
  }
244
229
  /**
245
- * Fetch latest tag from remote using git ls-remote. Real failures (network,
246
- * auth, invalid remote) propagate — only a genuinely tag-less remote yields null.
230
+ * Open the resolved archive (remote tag or local file) and extract it into
231
+ * extractDir. A gunzip, tar or read error names the archive. An archive with
232
+ * more than one top-level directory is refused: the extract strips exactly
233
+ * one level, so a second root would land its files loose in the guide.
247
234
  */
248
- async fetchLatestTag(source) {
249
- const { stdout } = await gitExec(['ls-remote', '--tags', '--sort=-v:refname', source], process.cwd());
250
- const tagPattern = /refs\/tags\/(v?\d+\.\d+\.\d+)$/;
251
- const tags = [];
252
- for (const line of stdout.split('\n')) {
253
- const match = tagPattern.exec(line.trim());
254
- if (match)
255
- tags.push(match[1]);
256
- }
257
- if (tags.length === 0)
258
- return null;
259
- // Sort descending
260
- tags.sort((a, b) => {
261
- const pa = a.replace(/^v/, '').split('.').map(Number);
262
- const pb = b.replace(/^v/, '').split('.').map(Number);
263
- for (let i = 0; i < 3; i++) {
264
- if (pa[i] !== pb[i])
265
- return pb[i] - pa[i];
266
- }
267
- return 0;
268
- });
269
- return tags[0];
270
- }
271
- /** Download tarball from GitHub API and extract into extractDir */
272
- async downloadAndExtract(source, tag, extractDir, filter) {
273
- const { owner, repo } = parseGitHubOwnerRepo(source);
274
- const url = `https://api.github.com/repos/${owner}/${repo}/tarball/${tag}`;
275
- // The ls-remote half already went through git, which honors the proxy
276
- // variables itself; a failure here is therefore the download specifically.
277
- const proxyVars = activeProxyEnvVars();
278
- const via = proxyVars.length > 0 ? ` via proxy (${proxyVars.join(', ')})` : '';
279
- const failurePrefix = `Downloading guide tarball from ${url}${via} failed`;
280
- // Closed in finally: an open keep-alive socket would otherwise hold the
281
- // CLI process alive until the agent's idle timeout.
282
- const dispatcher = new EnvHttpProxyAgent();
235
+ async openAndExtract(resolved, extractDir, filter) {
236
+ const archive = await openArchive(resolved);
237
+ const roots = new Set();
238
+ const rootGuardedFilter = (entryPath) => {
239
+ const root = entryPath.replace(/^\.\//, '').split('/')[0];
240
+ if (root !== '')
241
+ roots.add(root);
242
+ return roots.size <= 1 && filter(entryPath);
243
+ };
283
244
  try {
284
- let response;
245
+ mkdirSync(extractDir, { recursive: true });
246
+ // GitHub tarballs have a top-level directory like {owner}-{repo}-{hash}/
247
+ // We strip 1 level and extract directly into extractDir
285
248
  try {
286
- response = await undiciFetch(url, {
287
- headers: { Accept: 'application/vnd.github+json' },
288
- redirect: 'follow',
289
- dispatcher,
290
- });
249
+ await pipeline(archive.stream, createGunzip(), extract({ cwd: extractDir, strip: 1, filter: rootGuardedFilter }));
291
250
  }
292
251
  catch (err) {
293
- // undici throws TypeError('fetch failed') with the real DNS/connection
294
- // reason on err.cause.message — surface that, not the generic wrapper text.
295
- const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : undefined;
296
- const message = err instanceof Error ? err.message : String(err);
297
- throw new Error(withNetworkErrorHint(`${failurePrefix}: ${cause ? `${message}: ${cause}` : message}`), { cause: err });
298
- }
299
- if (!response.ok) {
300
- const rateLimit = describeRateLimit(response.status, response.headers);
301
- throw new Error(rateLimit ?? `${failurePrefix}: HTTP ${response.status} ${response.statusText}`);
252
+ const reason = err instanceof Error ? err.message : String(err);
253
+ throw new Error(`Reading guide archive ${archive.label} failed: ${reason}`, { cause: err });
302
254
  }
303
- if (!response.body) {
304
- throw new Error(`${failurePrefix}: empty response body`);
255
+ if (roots.size > 1) {
256
+ throw new Error(`Archive must contain a single top-level directory (${archive.label})`);
305
257
  }
306
- mkdirSync(extractDir, { recursive: true });
307
- // GitHub tarballs have a top-level directory like {owner}-{repo}-{hash}/
308
- // We strip 1 level and extract directly into extractDir
309
- const nodeStream = Readable.fromWeb(response.body);
310
- await pipeline(nodeStream, createGunzip(), extract({ cwd: extractDir, strip: 1, filter }));
311
258
  }
312
259
  finally {
313
- await dispatcher.close();
260
+ await archive.close();
314
261
  }
315
262
  }
316
263
  }