@intra-mart/accel 0.4.0-dev.202607140628 → 0.4.0-dev.202607210732

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.
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env bash
2
+ # @accel-cli-managed
3
+ #
4
+ # pre-commit:
5
+ # 扫描已暂存到 git 的变更内容中是否包含疑似敏感信息的字符串,
6
+ # 若检测到则阻止本次提交的 hook 脚本。
7
+ #
8
+ # 启用方法:
9
+ # chmod +x .githooks/pre-commit
10
+ # git config core.hooksPath .githooks
11
+ #
12
+ set -euo pipefail
13
+ shopt -s nocasematch
14
+
15
+ # =============================================================================
16
+ # 获取变更差异
17
+ # =============================================================================
18
+
19
+ # 如果按文件数逐个调用 git diff,在变更文件较多时会显著变慢,
20
+ # 因此差异获取统一合并为 1 次。
21
+ # 由于检测范围仅限于以下内容,因此通过 git 的路径规格预先筛选目标文件:
22
+ # - 记载 intra-mart OAuth 客户端密钥的 mcp 配置文件(.json / .toml)
23
+ diff_output=$(git diff --cached -U0 --no-color --diff-filter=ACMR -- '*.json' '*.toml' 2>/dev/null | tr -d '\0' || true)
24
+ if [ -z "$diff_output" ]; then
25
+ exit 0
26
+ fi
27
+
28
+ found=0
29
+ findings=()
30
+
31
+ # =============================================================================
32
+ # base64 解码函数
33
+ # =============================================================================
34
+
35
+ # 在 Git Bash (Windows) 等 fork/exec 成本较高的环境中,若按候选 token
36
+ # 数量逐一启动进程,检查动作将随候选数量增多而变慢,
37
+ # 因此 base64 解码不启动外部进程(base64/tr),仅使用 bash 内置运算完成。
38
+ # 为了在 macOS 系统自带的 /bin/bash 3.2 上也能运行,
39
+ # 不使用关联数组(bash 4.0+),改用字符串检索完成字符到数值的转换。
40
+ B64_ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
41
+
42
+ # 将指定 base64 字符对应的 6bit 数值写入变量 B64_LAST_VAL。
43
+ # 若找不到,则将 B64_LAST_VAL 置空并返回 1。
44
+ _b64_char_value() {
45
+ case "$1" in
46
+ -) B64_LAST_VAL=62; return 0 ;;
47
+ _) B64_LAST_VAL=63; return 0 ;;
48
+ esac
49
+ local idx="${B64_ALPHABET%%"$1"*}"
50
+ if [ "$idx" = "$B64_ALPHABET" ]; then
51
+ B64_LAST_VAL=""
52
+ return 1
53
+ fi
54
+ B64_LAST_VAL=${#idx}
55
+ return 0
56
+ }
57
+
58
+ # 将 token 字符串以 base64(同时兼容 urlsafe 字符集)解码,若解码结果
59
+ # 仅由 intra-mart OAuth 客户端密钥(16进制字符串 + '@' + 租户ID)所使用的
60
+ # 英数字与符号构成,则返回 true。
61
+ decode_contains_at() {
62
+ local token="$1"
63
+ local len=${#token}
64
+ # 为避免循环体内每次都重新执行 local 声明带来的开销,变量统一在循环外一次性声明
65
+ local i=0 has_at=1 c0 c1 c2 c3 v0 v1 v2 v3 nbytes val b1 b2 b3
66
+
67
+ while (( i < len )); do
68
+ # base64 是从「4个字符(6bit×4)」还原「3个字节(8bit×3)」的机制,
69
+ # 因此从头开始每次截取 4 个字符进行处理。
70
+ c0="${token:i:1}"; c1="${token:i+1:1}"; c2="${token:i+2:1}"; c3="${token:i+3:1}"
71
+ [[ -z "$c0" || -z "$c1" ]] && break
72
+
73
+ # 将每个字符转换为其在 base64 字母表中的位置(6bit 数值,0〜63)
74
+ _b64_char_value "$c0" || return 1
75
+ v0=$B64_LAST_VAL
76
+ _b64_char_value "$c1" || return 1
77
+ v1=$B64_LAST_VAL
78
+
79
+ # 若第 3、4 个字符是填充符("=")或不存在,
80
+ # 则该分组能还原的字节数会少于 3。
81
+ # (base64 仅末尾分组可能还原为 2 字节或 1 字节)
82
+ nbytes=3; v2=0; v3=0
83
+ if [[ -z "$c2" || "$c2" == "=" ]]; then
84
+ nbytes=1
85
+ else
86
+ _b64_char_value "$c2" || return 1
87
+ v2=$B64_LAST_VAL
88
+ if [[ -z "$c3" || "$c3" == "=" ]]; then
89
+ nbytes=2
90
+ else
91
+ _b64_char_value "$c3" || return 1
92
+ v3=$B64_LAST_VAL
93
+ fi
94
+ fi
95
+
96
+ # 将 4 个 6bit 数值(v0〜v3,共 24bit)合并为一个整数,
97
+ # 再按 8bit 拆分为 3 个字节,从而还原出原始字节序列。
98
+ # 6bit×4 = [v0][v1][v2][v3] → 8bit×3 = [b1][b2][b3]
99
+ val=$(( (v0 * 262144) + (v1 * 4096) + (v2 * 64) + v3 ))
100
+ b1=$(( (val / 65536) % 256 ))
101
+
102
+ # 若出现 intra-mart OAuth 客户端密钥中不会使用的字节值,
103
+ # 为避免误判,跳过后续判定。
104
+ (( (b1 >= 48 && b1 <= 57) || (b1 >= 65 && b1 <= 90) || (b1 >= 97 && b1 <= 122) || b1 == 64 || b1 == 95 || b1 == 45 )) || return 1
105
+
106
+ # 若第 1 个字节为 "@"(十进制 64),
107
+ # 则可能是 intra-mart OAuth 客户端密钥,
108
+ # 将 has_at 置为 0。
109
+ (( b1 == 64 )) && has_at=0
110
+
111
+ # 第 2、3 个字节也进行与 b1 相同的判定。
112
+ # 但若该分组只能还原 1 个字节(nbytes=1),
113
+ # 则 b2、b3 不存在,因此根据 nbytes 跳过判定本身。
114
+ if (( nbytes >= 2 )); then
115
+ b2=$(( (val / 256) % 256 ))
116
+ (( (b2 >= 48 && b2 <= 57) || (b2 >= 65 && b2 <= 90) || (b2 >= 97 && b2 <= 122) || b2 == 64 || b2 == 95 || b2 == 45 )) || return 1
117
+ (( b2 == 64 )) && has_at=0
118
+ fi
119
+ if (( nbytes >= 3 )); then
120
+ b3=$(( val % 256 ))
121
+ (( (b3 >= 48 && b3 <= 57) || (b3 >= 65 && b3 <= 90) || (b3 >= 97 && b3 <= 122) || b3 == 64 || b3 == 95 || b3 == 45 )) || return 1
122
+ (( b3 == 64 )) && has_at=0
123
+ fi
124
+
125
+ # 一旦出现还原字节数不足 3 的分组,说明该分组即为 token 的末尾(已填充)。
126
+ # 因此退出循环;否则继续处理下 4 个字符。
127
+ (( nbytes < 3 )) && break
128
+ i=$((i + 4))
129
+ done
130
+
131
+ # 能扫描到 token 末尾,说明该字符串仅由英数字与符号构成。
132
+ # 期间若发现 "@",则 has_at=0(成功),并将该值作为返回值返回。
133
+ return "$has_at"
134
+ }
135
+
136
+ # =============================================================================
137
+ # 检查添加行中 base64 风格 token 的函数
138
+ # =============================================================================
139
+
140
+ # 用于避免重复解码同一 token 的判定结果缓存。
141
+ # 以 token 字符串本身为键,缓存传给 decode_contains_at() 后得到的判定结果。
142
+ # 不使用关联数组(bash 4.0+)。
143
+ TOKENS_MATCHED=$'\x01'
144
+ TOKENS_UNMATCHED=$'\x01'
145
+
146
+ # 从每一行添加行中,用正则表达式提取所有 40 个字符以上的 base64 风格 token,
147
+ # 并将每个 token 传给 decode_contains_at() 判定是否为 intra-mart OAuth 客户端密钥格式。
148
+ # 命中则将检测内容追加到 findings 并设置 found=1。
149
+ check_base64_tokens() {
150
+ local file="$1" lineno="$2" content="$3"
151
+ # 不足 40 个字符则不可能存在候选 token,在进入正则循环前直接返回。
152
+ (( ${#content} < 40 )) && return
153
+ local remaining="$content" token is_match
154
+
155
+ # 若按行启动 grep 子进程,在变更文件较多时会显著变慢,
156
+ # 因此仅使用 bash 内置正则匹配提取候选 token。
157
+ while [[ "$remaining" =~ ([A-Za-z0-9+/_-]{40,}={0,2}) ]]; do
158
+ token="${BASH_REMATCH[1]}"
159
+ remaining="${remaining#*"$token"}"
160
+
161
+ # 同一 token 可能出现在多个文件或多行中(例如将同一配置复制到多处),
162
+ # 因此判定结果会复用缓存,但每次出现都会记录到 findings 中。
163
+ if [[ "$TOKENS_MATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
164
+ is_match=0
165
+ elif [[ "$TOKENS_UNMATCHED" == *$'\x01'"$token"$'\x01'* ]]; then
166
+ is_match=1
167
+ elif decode_contains_at "$token"; then
168
+ TOKENS_MATCHED+="$token"$'\x01'
169
+ is_match=0
170
+ else
171
+ TOKENS_UNMATCHED+="$token"$'\x01'
172
+ is_match=1
173
+ fi
174
+
175
+ if (( is_match == 0 )); then
176
+ findings+=("[$file:$lineno] 检测到 intra-mart OAuth 客户端密钥字符串: ${token:0:12}...")
177
+ found=1
178
+ fi
179
+ done
180
+ }
181
+
182
+ # =============================================================================
183
+ # 检查差异中的每一行
184
+ # =============================================================================
185
+
186
+ # 由于检测范围仅限于以下内容,因此仅将下述扩展名作为检测对象。
187
+ # - 记载 intra-mart OAuth 客户端密钥的 mcp 配置文件(.json / .toml)
188
+ INCLUDE_FILE_RE='\.(json|toml)$'
189
+
190
+ # package-lock.json 中包含大量容易被误判为认证密钥的哈希类字符串,
191
+ # 因此从扫描对象中排除。
192
+ EXCLUDE_FILE_RE='(^|/)package-lock\.json$'
193
+
194
+ current_file=""
195
+ current_line=0
196
+ is_binary=0
197
+ skip_file=0
198
+
199
+ while IFS= read -r line; do
200
+ case "$line" in
201
+ "diff --git "*)
202
+ # 例如: diff --git a/path/to/file b/path/to/file
203
+ current_file="${line#diff --git a/}"
204
+ current_file="${current_file%% b/*}"
205
+ is_binary=0
206
+ if [[ "$current_file" =~ $INCLUDE_FILE_RE ]] && [[ ! "$current_file" =~ $EXCLUDE_FILE_RE ]]; then
207
+ skip_file=0
208
+ else
209
+ skip_file=1
210
+ fi
211
+ ;;
212
+ "Binary files "*|"GIT binary patch"*)
213
+ is_binary=1
214
+ ;;
215
+ "@@ "*)
216
+ # 例如: @@ -12,0 +13,2 @@ ... → 获取新文件一侧的起始行号(13)
217
+ if [[ "$line" =~ \+([0-9]+) ]]; then
218
+ current_line="${BASH_REMATCH[1]}"
219
+ fi
220
+ ;;
221
+ "+++ "*|"--- "*)
222
+ : # 忽略 diff 头部行
223
+ ;;
224
+ "+"*)
225
+ if (( is_binary == 1 || skip_file == 1 )); then
226
+ continue
227
+ fi
228
+ content="${line#+}"
229
+ check_base64_tokens "$current_file" "$current_line" "$content"
230
+ current_line=$((current_line + 1))
231
+ ;;
232
+ *)
233
+ : ;;
234
+ esac
235
+ done <<< "$diff_output"
236
+
237
+ # =============================================================================
238
+ # 显示检测结果
239
+ # =============================================================================
240
+
241
+ if [ "$found" -eq 1 ]; then
242
+ echo "----------------------------------------------------------------------"
243
+ echo "🚫 已阻止提交:检测到疑似敏感信息的字符串"
244
+ echo "----------------------------------------------------------------------"
245
+ for msg in "${findings[@]}"; do
246
+ echo " - $msg"
247
+ done
248
+ echo ""
249
+ echo "以上位置可能包含疑似敏感信息的字符串。"
250
+ echo "请在提交前务必确认内容,并按需删除或替换为其他字符串。"
251
+ echo "如确认检测内容没有问题,可使用 git commit --no-verify 跳过本次检查。"
252
+ exit 1
253
+ fi
254
+
255
+ exit 0
@@ -1,5 +1,6 @@
1
1
  export type AssetTree = {
2
- listFiles: () => Promise<string[]>;
2
+ listRootEntries: () => Promise<string[]>;
3
+ listFiles: (underDirs?: string[]) => Promise<string[]>;
3
4
  readFile: (relPath: string) => Promise<string>;
4
5
  };
5
6
  export declare const createFsAssetTree: (rootDir: string) => AssetTree;
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { listFilesUnder } from "../utils/fs-list.js";
4
4
  export const createFsAssetTree = (rootDir) => ({
5
+ listRootEntries: () => listFilesUnder(rootDir),
5
6
  listFiles: () => listFilesUnder(rootDir),
6
7
  readFile: (relPath) => readFile(join(rootDir, relPath), "utf-8"),
7
8
  });
@@ -5,6 +5,7 @@ import { walkAssetRepo } from "./walker.js";
5
5
  import { renderAssetContent } from "./renderer.js";
6
6
  import { runInstallBuild } from "./installer.js";
7
7
  import { computeSha1 } from "../utils/hash.js";
8
+ import { mapWithConcurrency } from "../utils/concurrency.js";
8
9
  import { writeSettings, writeHashsum } from "../utils/settings-io.js";
9
10
  export { getInstallCmds } from "./installer.js";
10
11
  const fileExists = async (path) => {
@@ -16,10 +17,6 @@ const fileExists = async (path) => {
16
17
  return false;
17
18
  }
18
19
  };
19
- const dirnamePosix = (p) => {
20
- const idx = p.lastIndexOf("/");
21
- return idx === -1 ? "" : p.slice(0, idx);
22
- };
23
20
  const isWithinDir = (parentDir, candidate) => {
24
21
  const parent = resolve(parentDir);
25
22
  const target = resolve(candidate);
@@ -43,13 +40,28 @@ const fileLabelOf = (relativePath, section) => {
43
40
  return relativePath;
44
41
  return relativePath.slice(section.length);
45
42
  };
43
+ const DEPLOY_CONCURRENCY = 64;
44
+ const groupSections = (entries) => {
45
+ const groups = new Map();
46
+ for (const entry of entries) {
47
+ const section = sectionOf(entry.relativePath);
48
+ let group = groups.get(section);
49
+ if (!group) {
50
+ group = { section, files: [] };
51
+ groups.set(section, group);
52
+ }
53
+ group.files.push(fileLabelOf(entry.relativePath, section));
54
+ }
55
+ return [...groups.values()];
56
+ };
46
57
  export const deployAssets = async (options) => {
47
58
  const { projectDir, settings, provider, noInstall, skipExistingFiles, onExistingFile, progress, } = options;
48
59
  try {
49
60
  progress?.onFetchStart?.();
50
61
  const repoDir = await provider.fetch();
51
62
  const tree = {
52
- listFiles: () => provider.listFiles(),
63
+ listRootEntries: () => provider.listRootEntries(),
64
+ listFiles: (underDirs) => provider.listFiles(underDirs),
53
65
  readFile: (relPath) => provider.readFile(relPath),
54
66
  };
55
67
  const semver = settings.accelplatformVersion.semver;
@@ -68,29 +80,20 @@ export const deployAssets = async (options) => {
68
80
  });
69
81
  progress?.onDownloadStart?.();
70
82
  await provider.materialize([
71
- ...new Set(entries.map((e) => dirnamePosix(e.sourceRelPath))),
83
+ ...new Set(entries.map((e) => e.sourceRelPath)),
72
84
  ]);
73
- const deployedFiles = [];
74
- const hashEntries = [];
75
- const deployedAssets = {};
85
+ if (progress?.onSectionDeploy) {
86
+ for (const group of groupSections(entries)) {
87
+ progress.onSectionDeploy(group.section, group.files);
88
+ }
89
+ }
90
+ const existsFlags = await mapWithConcurrency(entries, DEPLOY_CONCURRENCY, (entry) => fileExists(join(projectDir, entry.relativePath)));
76
91
  const skippedFiles = [];
77
92
  const overwrittenFiles = [];
78
- let currentSection = null;
79
- for (const entry of entries) {
93
+ const toDeploy = [];
94
+ for (const [index, entry] of entries.entries()) {
80
95
  const targetPath = entry.relativePath;
81
- const destPath = join(projectDir, targetPath);
82
- const section = sectionOf(targetPath);
83
- if (section !== currentSection) {
84
- currentSection = section;
85
- if (progress?.onSectionDeploy) {
86
- const sectionFiles = entries
87
- .filter((e) => sectionOf(e.relativePath) === section)
88
- .map((e) => fileLabelOf(e.relativePath, section));
89
- progress.onSectionDeploy(section, sectionFiles);
90
- }
91
- }
92
- const exists = await fileExists(destPath);
93
- if (exists) {
96
+ if (existsFlags[index]) {
94
97
  let decision = "overwrite";
95
98
  if (skipExistingFiles) {
96
99
  decision = "skip";
@@ -104,15 +107,25 @@ export const deployAssets = async (options) => {
104
107
  }
105
108
  overwrittenFiles.push(targetPath);
106
109
  }
110
+ toDeploy.push(entry);
111
+ }
112
+ const hashEntries = await mapWithConcurrency(toDeploy, DEPLOY_CONCURRENCY, async (entry) => {
113
+ const targetPath = entry.relativePath;
114
+ const destPath = join(projectDir, targetPath);
107
115
  const raw = await tree.readFile(entry.sourceRelPath);
108
116
  const content = renderAssetContent(raw, targetPath, collectReplacements(entry), context);
109
117
  await mkdir(dirname(destPath), { recursive: true });
110
118
  await writeFile(destPath, content, "utf-8");
111
- const sha1 = computeSha1(content);
112
- const version = entry.meta?.version ?? "0.0.0";
113
- hashEntries.push({ filePath: targetPath, version, sha1 });
114
- deployedAssets[targetPath] = version;
115
- deployedFiles.push(targetPath);
119
+ return {
120
+ filePath: targetPath,
121
+ version: entry.meta?.version ?? "0.0.0",
122
+ sha1: computeSha1(content),
123
+ };
124
+ });
125
+ const deployedFiles = hashEntries.map((h) => h.filePath);
126
+ const deployedAssets = {};
127
+ for (const h of hashEntries) {
128
+ deployedAssets[h.filePath] = h.version;
116
129
  }
117
130
  const updatedSettings = {
118
131
  ...settings,
@@ -12,6 +12,7 @@ export const createFileAssetProvider = (sourcePath) => {
12
12
  }
13
13
  return absPath;
14
14
  },
15
+ listRootEntries: () => tree.listRootEntries(),
15
16
  listFiles: () => tree.listFiles(),
16
17
  materialize: async () => { },
17
18
  readFile: (relPath) => tree.readFile(relPath),
@@ -1,8 +1,9 @@
1
1
  import type { AssetProvider } from "../core/types.js";
2
2
  export type CommitTree = {
3
- listFiles: () => Promise<string[]>;
3
+ listRootEntries: () => Promise<string[]>;
4
+ listFiles: (underDirs?: string[]) => Promise<string[]>;
4
5
  readFile: (relPath: string) => Promise<string>;
5
- materialize: (dirs: string[]) => Promise<void>;
6
+ materialize: (files: string[]) => Promise<void>;
6
7
  };
7
8
  export type GitAssetProvider = AssetProvider & {
8
9
  asTree: () => CommitTree;
@@ -1,6 +1,6 @@
1
1
  import { getMessage } from "../i18n/index.js";
2
2
  import { isGitAuthError, isGitObjectMissingError, isGitServerUnsupportedError, } from "../git/errors.js";
3
- import { createObjectStore } from "../git/object-store.js";
3
+ import { createObjectStore, } from "../git/object-store.js";
4
4
  import { assertServerSupported, fetchCapabilities, fetchPack, isValidOid, resolveRef, } from "../git/smart-http.js";
5
5
  const MAX_WANTS_PER_REQUEST = 1000;
6
6
  const META_FILENAME = "_meta.json";
@@ -18,7 +18,6 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
18
18
  let store = null;
19
19
  let commit = null;
20
20
  let packSeq = 0;
21
- const prefetchedMetaDirs = new Map();
22
21
  const withHint = (message, cause) => {
23
22
  if (isGitAuthError(cause)) {
24
23
  return `${message}\n${getMessage("error.gitAuthHint", locale)}`;
@@ -42,7 +41,7 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
42
41
  if (seen.has(oid))
43
42
  continue;
44
43
  seen.add(oid);
45
- if (!(await store.hasObject(oid)))
44
+ if (!store.hasObject(oid))
46
45
  missing.push(oid);
47
46
  }
48
47
  for (let i = 0; i < missing.length; i += MAX_WANTS_PER_REQUEST) {
@@ -50,29 +49,6 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
50
49
  await store.writePack(pack, `blobs-${packSeq++}`);
51
50
  }
52
51
  };
53
- const topDirOf = (relPath) => {
54
- const slash = relPath.indexOf("/");
55
- return slash === -1 ? "" : relPath.slice(0, slash);
56
- };
57
- const ensureMetasPrefetched = async (oid, topDir) => {
58
- let dirs = prefetchedMetaDirs.get(oid);
59
- if (!dirs) {
60
- dirs = new Set();
61
- prefetchedMetaDirs.set(oid, dirs);
62
- }
63
- if (dirs.has(topDir))
64
- return;
65
- const { store } = requireRepo();
66
- const prefix = topDir === "" ? "" : `${topDir}/`;
67
- const entries = await store.listBlobEntries(oid);
68
- const metaOids = entries
69
- .filter((e) => e.path.startsWith(prefix) &&
70
- (e.path === `${prefix}${META_FILENAME}` ||
71
- e.path.endsWith(`/${META_FILENAME}`)))
72
- .map((e) => e.oid);
73
- await fetchMissingBlobs(metaOids);
74
- dirs.add(topDir);
75
- };
76
52
  const readFileAt = async (oid, relPath) => {
77
53
  const { store } = requireRepo();
78
54
  try {
@@ -81,29 +57,35 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
81
57
  catch (err) {
82
58
  if (!isGitObjectMissingError(err))
83
59
  throw err;
84
- if (relPath === META_FILENAME || relPath.endsWith(`/${META_FILENAME}`)) {
85
- await ensureMetasPrefetched(oid, topDirOf(relPath));
86
- return store.readBlobAtPath(oid, relPath);
87
- }
88
60
  throw new Error(`File content is not materialized (materialize() must be called first): ${relPath}`);
89
61
  }
90
62
  };
91
- const materializeAt = async (oid, dirs) => {
92
- if (dirs.length === 0)
63
+ const materializeAt = async (oid, files) => {
64
+ if (files.length === 0)
93
65
  return;
94
66
  const { store } = requireRepo();
95
- const prefixes = [
96
- ...new Set(dirs.map((d) => (d === "" || d === "." ? "" : `${d}/`))),
97
- ];
98
- const entries = await store.listBlobEntries(oid);
99
- const targets = entries
100
- .filter((e) => prefixes.some((p) => e.path.startsWith(p)))
101
- .map((e) => e.oid);
67
+ const targets = [];
68
+ for (const file of files) {
69
+ const blobOid = await store.getBlobOid(oid, file);
70
+ if (blobOid !== undefined)
71
+ targets.push(blobOid);
72
+ }
102
73
  await fetchMissingBlobs(targets);
103
74
  };
104
- const listFilesAt = async (oid) => {
75
+ const metaOidsOf = (entries) => entries
76
+ .filter((e) => e.path === META_FILENAME || e.path.endsWith(`/${META_FILENAME}`))
77
+ .map((e) => e.oid);
78
+ const listRootFilesAt = async (oid) => {
79
+ const { store } = requireRepo();
80
+ const entries = await store.listRootBlobEntries(oid);
81
+ await fetchMissingBlobs(metaOidsOf(entries));
82
+ return entries.map((e) => e.path);
83
+ };
84
+ const listFilesAt = async (oid, underDirs) => {
105
85
  const { store } = requireRepo();
106
- return (await store.listBlobEntries(oid)).map((e) => e.path);
86
+ const entries = await store.listBlobEntries(oid, underDirs);
87
+ await fetchMissingBlobs(metaOidsOf(entries));
88
+ return entries.map((e) => e.path);
107
89
  };
108
90
  const fetchTreesFor = async (oid, label) => {
109
91
  const { store } = requireRepo();
@@ -112,20 +94,25 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
112
94
  filterBlobNone: true,
113
95
  });
114
96
  await store.writePack(pack, label);
115
- const entries = await store.listBlobEntries(oid);
116
- const rootMetaOids = entries
117
- .filter((e) => {
118
- const parts = e.path.split("/");
119
- return ((parts.length === 1 && parts[0] === META_FILENAME) ||
120
- (parts.length === 2 && parts[1] === META_FILENAME));
121
- })
122
- .map((e) => e.oid);
123
- await fetchMissingBlobs(rootMetaOids);
97
+ await listRootFilesAt(oid);
98
+ };
99
+ const rethrowWithServerDiagnosis = async (original) => {
100
+ if (!isGitAuthError(original)) {
101
+ try {
102
+ assertServerSupported(repoUrl, await fetchCapabilities(repoUrl));
103
+ }
104
+ catch (diagErr) {
105
+ if (isGitServerUnsupportedError(diagErr))
106
+ throw diagErr;
107
+ }
108
+ }
109
+ throw original;
124
110
  };
125
111
  const commitTreeOf = (oid) => ({
126
- listFiles: () => listFilesAt(oid),
112
+ listRootEntries: () => listRootFilesAt(oid),
113
+ listFiles: (underDirs) => listFilesAt(oid, underDirs),
127
114
  readFile: (relPath) => readFileAt(oid, relPath),
128
- materialize: (dirs) => materializeAt(oid, dirs),
115
+ materialize: (files) => materializeAt(oid, files),
129
116
  });
130
117
  const provider = {
131
118
  fetch: async () => {
@@ -134,14 +121,17 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
134
121
  }
135
122
  store = await createObjectStore();
136
123
  try {
137
- const caps = await fetchCapabilities(repoUrl);
138
- assertServerSupported(repoUrl, caps);
139
- const resolved = await resolveRef(repoUrl, ref);
140
- if (!resolved) {
141
- throw new Error(`ref not found on server: ${ref}`);
124
+ try {
125
+ const resolved = await resolveRef(repoUrl, ref);
126
+ if (!resolved) {
127
+ throw new Error(`ref not found on server: ${ref}`);
128
+ }
129
+ commit = resolved.oid;
130
+ await fetchTreesFor(commit, "trees-head");
131
+ }
132
+ catch (inner) {
133
+ await rethrowWithServerDiagnosis(inner);
142
134
  }
143
- commit = resolved.oid;
144
- await fetchTreesFor(commit, "trees-head");
145
135
  }
146
136
  catch (err) {
147
137
  const reason = err instanceof Error ? err.message : String(err);
@@ -149,24 +139,27 @@ export const createGitAssetProvider = (repoUrl, ref, options = {}) => {
149
139
  }
150
140
  return store.dir;
151
141
  },
152
- listFiles: () => {
142
+ listRootEntries: () => {
143
+ const { commit: oid } = requireRepo();
144
+ return listRootFilesAt(oid);
145
+ },
146
+ listFiles: (underDirs) => {
153
147
  const { commit: oid } = requireRepo();
154
- return listFilesAt(oid);
148
+ return listFilesAt(oid, underDirs);
155
149
  },
156
150
  readFile: (relPath) => {
157
151
  const { commit: oid } = requireRepo();
158
152
  return readFileAt(oid, relPath);
159
153
  },
160
- materialize: (dirs) => {
154
+ materialize: (files) => {
161
155
  const { commit: oid } = requireRepo();
162
- return materializeAt(oid, dirs);
156
+ return materializeAt(oid, files);
163
157
  },
164
158
  cleanup: async () => {
165
159
  if (store) {
166
160
  await store.cleanup();
167
161
  store = null;
168
162
  commit = null;
169
- prefetchedMetaDirs.clear();
170
163
  }
171
164
  },
172
165
  sourceInfo: () => ({
@@ -8,7 +8,7 @@ export type RenderedAsset = {
8
8
  sha1: string;
9
9
  };
10
10
  export type RenderedPlan = Map<string, RenderedAsset>;
11
- export declare const buildRenderedPlan: (tree: AssetTree, settings: AccelSettings, materialize?: (dirs: string[]) => Promise<void>) => Promise<RenderedPlan>;
11
+ export declare const buildRenderedPlan: (tree: AssetTree, settings: AccelSettings, materialize?: (files: string[]) => Promise<void>) => Promise<RenderedPlan>;
12
12
  export type FileState = {
13
13
  relativePath: string;
14
14
  base: RenderedAsset | null;
@@ -4,10 +4,6 @@ import { buildEvalContext } from "../core/eval-context.js";
4
4
  import { walkAssetRepo } from "./walker.js";
5
5
  import { renderAssetContent } from "./renderer.js";
6
6
  import { computeSha1 } from "../utils/hash.js";
7
- const dirnamePosix = (p) => {
8
- const idx = p.lastIndexOf("/");
9
- return idx === -1 ? "" : p.slice(0, idx);
10
- };
11
7
  const isSafeRelPath = (p) => !p.startsWith("/") && !p.split("/").includes("..");
12
8
  export const buildRenderedPlan = async (tree, settings, materialize) => {
13
9
  const context = buildEvalContext(settings);
@@ -21,7 +17,7 @@ export const buildRenderedPlan = async (tree, settings, materialize) => {
21
17
  });
22
18
  if (materialize) {
23
19
  await materialize([
24
- ...new Set(safeEntries.map((e) => dirnamePosix(e.sourceRelPath))),
20
+ ...new Set(safeEntries.map((e) => e.sourceRelPath)),
25
21
  ]);
26
22
  }
27
23
  const plan = new Map();
@@ -5,4 +5,5 @@ export type AssetEntry = {
5
5
  relativePath: string;
6
6
  meta: MetaJson | null;
7
7
  };
8
+ export declare const walkAssetDir: (tree: AssetTree, context: EvalContext) => Promise<AssetEntry[]>;
8
9
  export declare const walkAssetRepo: (tree: AssetTree, targetSemver: string, context: EvalContext) => Promise<AssetEntry[]>;