@coze-arch/cli 0.1.8 → 0.1.9-alpha.ce005e

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 (49) hide show
  1. package/README.md +18 -0
  2. package/lib/__templates__/expo/.cozeproj/scripts/dev_run.ps1 +2 -2
  3. package/lib/__templates__/expo/.cozeproj/scripts/dev_run.sh +1 -1
  4. package/lib/__templates__/expo/.cozeproj/scripts/prepare-node-modules.sh +178 -10
  5. package/lib/__templates__/expo/client/package.json +1 -1
  6. package/lib/__templates__/nextjs/.coze +1 -1
  7. package/lib/__templates__/nextjs/README.md +18 -0
  8. package/lib/__templates__/nextjs/eslint.config.mjs +1 -1
  9. package/lib/__templates__/nextjs/next.config.ts +0 -9
  10. package/lib/__templates__/nextjs/scripts/build.ps1 +1 -1
  11. package/lib/__templates__/nextjs/scripts/build.sh +2 -2
  12. package/lib/__templates__/nextjs/scripts/dev.ps1 +2 -2
  13. package/lib/__templates__/nextjs/scripts/dev.sh +16 -55
  14. package/lib/__templates__/nextjs/scripts/local-workspace.cjs +302 -0
  15. package/lib/__templates__/nextjs/scripts/prepare.sh +10 -2
  16. package/lib/__templates__/nextjs/scripts/validate.sh +11 -1
  17. package/lib/__templates__/nextjs/src/server.ts +1 -1
  18. package/lib/__templates__/nextjs/template.config.js +20 -6
  19. package/lib/__templates__/nextjs/tsconfig.json +0 -1
  20. package/lib/__templates__/nuxt-vue/.coze +1 -1
  21. package/lib/__templates__/nuxt-vue/README.md +20 -2
  22. package/lib/__templates__/nuxt-vue/scripts/build.sh +1 -1
  23. package/lib/__templates__/nuxt-vue/scripts/dev.sh +10 -4
  24. package/lib/__templates__/nuxt-vue/scripts/local-workspace.cjs +302 -0
  25. package/lib/__templates__/nuxt-vue/scripts/prepare.sh +10 -2
  26. package/lib/__templates__/nuxt-vue/scripts/validate.sh +11 -1
  27. package/lib/__templates__/taro/.coze +2 -2
  28. package/lib/__templates__/taro/.cozeproj/scripts/deploy_build.sh +6 -1
  29. package/lib/__templates__/taro/.cozeproj/scripts/dev_build.sh +10 -1
  30. package/lib/__templates__/taro/.cozeproj/scripts/dev_run.sh +56 -4
  31. package/lib/__templates__/taro/.cozeproj/scripts/local-workspace.cjs +351 -0
  32. package/lib/__templates__/taro/.cozeproj/scripts/pack.sh +16 -6
  33. package/lib/__templates__/taro/.cozeproj/scripts/prepare-node-modules.sh +178 -10
  34. package/lib/__templates__/taro/.cozeproj/scripts/taro-build.cjs +66 -0
  35. package/lib/__templates__/taro/.cozeproj/scripts/validate.sh +3 -0
  36. package/lib/__templates__/taro/package.json +5 -5
  37. package/lib/__templates__/vite/.coze +1 -1
  38. package/lib/__templates__/vite/README.md +20 -0
  39. package/lib/__templates__/vite/scripts/build.sh +1 -1
  40. package/lib/__templates__/vite/scripts/dev.sh +10 -4
  41. package/lib/__templates__/vite/scripts/local-workspace.cjs +302 -0
  42. package/lib/__templates__/vite/scripts/prepare.sh +10 -2
  43. package/lib/__templates__/vite/scripts/validate.sh +7 -1
  44. package/lib/__templates__/vite/template.config.js +20 -6
  45. package/lib/cli.js +377 -184
  46. package/package.json +2 -1
  47. package/lib/__templates__/nextjs/scripts/prepare-node-modules.sh +0 -212
  48. package/lib/__templates__/nuxt-vue/scripts/prepare-node-modules.sh +0 -212
  49. package/lib/__templates__/vite/scripts/prepare-node-modules.sh +0 -212
@@ -0,0 +1,351 @@
1
+ #!/usr/bin/env node
2
+ // Taro source is owned by Drive. Only these wrappers may write to the local workspace.
3
+ /* eslint-disable @typescript-eslint/no-require-imports -- Standalone CommonJS runtime shipped without CLI dependencies. */
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const os = require('node:os');
7
+ const { createHash } = require('node:crypto');
8
+ const { spawn, execFileSync } = require('node:child_process');
9
+ const { setTimeout: delay } = require('node:timers/promises');
10
+
11
+ const scriptRoot = fs.realpathSync(path.resolve(__dirname, '..', '..'));
12
+ const source = fs.realpathSync(
13
+ process.env.COZE_TARO_LOCAL_ACTIVE === scriptRoot && process.env.COZE_TARO_SOURCE_PATH
14
+ ? process.env.COZE_TARO_SOURCE_PATH : scriptRoot,
15
+ );
16
+ const drivePath = path.resolve(process.env.COZE_DRIVE_ROOT || '/Coze/Drive');
17
+ const drive = fs.existsSync(drivePath) ? fs.realpathSync(drivePath) : drivePath;
18
+ const inside = (root, candidate) => candidate === root || candidate.startsWith(`${root}${path.sep}`);
19
+ const onDrive = inside(drive, source);
20
+ const digest = value => createHash('sha256').update(value).digest('hex');
21
+ // Separate from /tmp/nm: older dependency helpers clean unknown entries there.
22
+ const cacheRoot = path.join(os.tmpdir(), `coze-taro-${process.getuid()}`);
23
+ const projectCache = path.join(cacheRoot, digest(source));
24
+ const exclusions = [
25
+ 'node_modules', '.git', '/logs', '.pnpm-store', '.next', '.nuxt', '.output',
26
+ '/dist', '/dist-web', '/dist-tt', '/server/dist', '/dist-server', '.cache', '.turbo', '*.tsbuildinfo',
27
+ '.eslintcache', '.stylelintcache', '/next-env.d.ts',
28
+ ];
29
+ const outputDirs = ['dist', 'dist-web', 'dist-tt', 'server/dist'];
30
+ const taroOutputDirs = {
31
+ web: 'dist-web',
32
+ h5: 'dist-web',
33
+ weapp: 'dist',
34
+ tt: 'dist-tt',
35
+ };
36
+ const installArgs = ['install', '--prefer-frozen-lockfile', '--prefer-offline'];
37
+ let interrupted = false;
38
+ const children = new Set();
39
+
40
+ function stopTree(child) {
41
+ if (!child.pid || child.exitCode !== null) return;
42
+ // Keep descendants in the detached launcher's group so readiness ownership works.
43
+ // Also stop grandchildren when the test/foreground path is signalled directly.
44
+ let rows = [];
45
+ try {
46
+ rows = execFileSync('ps', ['-axo', 'pid=,ppid='], { encoding: 'utf8' })
47
+ .trim().split('\n').map(line => line.trim().split(/\s+/).map(Number));
48
+ } catch { /* The launcher still owns and reaps its process group. */ }
49
+ const pids = [child.pid];
50
+ for (let i = 0; i < pids.length; i++) {
51
+ for (const [pid, parent] of rows) if (parent === pids[i]) pids.push(pid);
52
+ }
53
+ for (const pid of pids.reverse()) {
54
+ try { process.kill(pid, 'SIGTERM'); } catch { /* Already exited. */ }
55
+ }
56
+ const timer = setTimeout(() => {
57
+ for (const pid of pids) {
58
+ try { process.kill(pid, 'SIGKILL'); } catch { /* Already exited. */ }
59
+ }
60
+ }, 2000);
61
+ timer.unref();
62
+ }
63
+
64
+ for (const signal of ['SIGINT', 'SIGTERM']) {
65
+ process.on(signal, () => {
66
+ interrupted = true;
67
+ process.exitCode = signal === 'SIGINT' ? 130 : 143;
68
+ for (const child of children) stopTree(child);
69
+ });
70
+ }
71
+
72
+ function run(command, args, cwd, env = process.env) {
73
+ if (interrupted) return Promise.reject(new Error('Interrupted'));
74
+ return new Promise((resolve, reject) => {
75
+ const child = spawn(command, args, { cwd, env, stdio: 'inherit' });
76
+ children.add(child);
77
+ child.once('error', error => { children.delete(child); reject(error); });
78
+ child.once('exit', (code, signal) => {
79
+ children.delete(child);
80
+ if (code === 0) resolve();
81
+ else reject(new Error(`${command} exited with ${signal || code}`));
82
+ });
83
+ });
84
+ }
85
+
86
+ function ensureCache() {
87
+ for (const dir of [cacheRoot, projectCache]) {
88
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
89
+ if (fs.lstatSync(dir).isSymbolicLink() || fs.statSync(dir).uid !== process.getuid()) {
90
+ throw new Error(`Refusing unmanaged workspace directory: ${dir}`);
91
+ }
92
+ if (inside(drive, fs.realpathSync(dir))) {
93
+ throw new Error(`Local workspace must be outside Coze Drive: ${dir}`);
94
+ }
95
+ }
96
+ }
97
+
98
+ async function locked(action, name = 'sync') {
99
+ const lock = path.join(projectCache, `${name}.lock`);
100
+ const started = Date.now();
101
+ let missingOwner = 0;
102
+ while (true) {
103
+ if (interrupted) throw new Error('Interrupted');
104
+ try { fs.mkdirSync(lock); break; } catch (error) {
105
+ if (error.code !== 'EEXIST') throw error;
106
+ }
107
+ let alive = false;
108
+ try {
109
+ const pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8'));
110
+ if (Number.isInteger(pid) && pid > 0) { process.kill(pid, 0); alive = true; }
111
+ } catch (error) { if (error.code === 'EPERM') alive = true; }
112
+ missingOwner = alive ? 0 : missingOwner + 1;
113
+ if (missingOwner >= 2) {
114
+ const stale = `${lock}.stale-${process.pid}`;
115
+ try {
116
+ fs.renameSync(lock, stale);
117
+ fs.rmSync(stale, { recursive: true });
118
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
119
+ missingOwner = 0;
120
+ continue;
121
+ }
122
+ if (Date.now() - started > 120000) throw new Error(`Timed out waiting for ${lock}`);
123
+ await delay(500);
124
+ }
125
+ fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
126
+ try { return await action(); }
127
+ finally { fs.rmSync(lock, { recursive: true, force: true }); }
128
+ }
129
+
130
+ async function sync(local) {
131
+ if (!fs.existsSync(path.join(source, 'package.json'))) {
132
+ throw new Error(`Source project is unavailable: ${source}`);
133
+ }
134
+ fs.mkdirSync(local, { recursive: true });
135
+ if (fs.realpathSync(local) !== local) throw new Error(`Refusing workspace symlink: ${local}`);
136
+ // Checksums catch same-size edits with unchanged/epoch Drive mtimes. Do not use -t:
137
+ // changed local files get fresh mtimes and unchanged files retain watcher snapshots.
138
+ // Materialize source links so the framework never follows them back onto Drive.
139
+ await run('rsync', [
140
+ '-rLp', '--checksum', '--delete', '--delay-updates',
141
+ ...exclusions.map(entry => `--exclude=${entry}`), `${source}/`, `${local}/`,
142
+ ], source);
143
+ }
144
+
145
+ function readOptional(file) {
146
+ try { return fs.readFileSync(file); }
147
+ catch (error) { if (error.code === 'ENOENT') return Buffer.alloc(0); throw error; }
148
+ }
149
+
150
+ function installInput(root) {
151
+ const hash = createHash('sha256');
152
+ const visit = (dir, all = false) => {
153
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
154
+ if (['node_modules', '.git', 'logs', '.pnpm-store', '.next', '.nuxt', '.output', 'dist', 'dist-web', 'dist-tt', 'dist-server', '.cache', '.turbo'].includes(entry.name)) continue;
155
+ const file = path.join(dir, entry.name);
156
+ // Follow source links just as rsync -L does, while detecting loops explicitly.
157
+ const real = fs.realpathSync(file);
158
+ if (entry.isDirectory() || (entry.isSymbolicLink() && fs.statSync(file).isDirectory())) {
159
+ if (ancestors.has(real)) throw new Error(`Source symlink cycle: ${file}`);
160
+ ancestors.add(real);
161
+ visit(file, all || entry.name === 'patches');
162
+ ancestors.delete(real);
163
+ }
164
+ else if (all || ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', '.pnpmfile.cjs', '.pnpmfile.js'].includes(entry.name)) {
165
+ hash.update(path.relative(root, file)).update('\0').update(readOptional(file)).update('\0');
166
+ }
167
+ }
168
+ };
169
+ const ancestors = new Set([fs.realpathSync(root)]);
170
+ visit(root);
171
+ return hash.digest('hex');
172
+ }
173
+
174
+ function localEnv(local) {
175
+ return {
176
+ ...process.env,
177
+ COZE_TARO_LOCAL_ACTIVE: local,
178
+ COZE_TARO_SOURCE_PATH: source,
179
+ COZE_TARO_LOCAL_MIRROR: onDrive ? '1' : '',
180
+ COZE_WORKSPACE_PATH: local,
181
+ // Keep the existing discoverable log/PID location in the source project.
182
+ COZE_LOG_DIR: process.env.COZE_LOG_DIR || path.join(source, 'logs'),
183
+ PWD: local,
184
+ INIT_CWD: local,
185
+ ...(onDrive ? { npm_config_store_dir: path.join(cacheRoot, 'store') } : {}),
186
+ };
187
+ }
188
+
189
+ async function install(local, mode) {
190
+ const state = path.join(projectCache, `${mode}.install`);
191
+ const version = execFileSync('pnpm', ['--version'], { encoding: 'utf8' }).trim();
192
+ const fingerprint = () => digest([
193
+ installInput(local), version, process.version, process.env.NODE_ENV,
194
+ process.env.npm_config_production, process.env.NPM_CONFIG_PRODUCTION,
195
+ process.env.PNPM_CONFIG_PRODUCTION,
196
+ ].join('\n'));
197
+ // Lifecycle scripts may generate files from arbitrary source, so do not reuse
198
+ // their install based on dependency metadata alone. Read manifests as text here
199
+ // (no executable hooks or private CLI dependencies in the standalone helper).
200
+ const manifest = readOptional(path.join(local, 'package.json')).toString();
201
+ const hasLifecycle = /"(?:install|postinstall|prepare)"\s*:/.test(manifest);
202
+ const hasHooks = ['.pnpmfile.cjs', '.pnpmfile.js'].some(file => fs.existsSync(path.join(local, file))) ||
203
+ /^\s*pnpmfile\s*=/m.test(readOptional(path.join(local, '.npmrc')).toString());
204
+ if (!hasLifecycle && !hasHooks && readOptional(state).toString() === fingerprint() &&
205
+ fs.existsSync(path.join(local, 'node_modules', '.modules.yaml'))) return;
206
+ fs.rmSync(state, { force: true });
207
+ const before = installInput(source);
208
+ if (before !== installInput(local)) {
209
+ throw new Error('Dependency inputs changed during sync; rerun dev_build.sh.');
210
+ }
211
+ await run('pnpm', [...installArgs, '--store-dir', path.join(cacheRoot, 'store')], local, localEnv(local));
212
+ if (before !== installInput(source)) {
213
+ throw new Error('Dependency inputs changed on Drive during installation; rerun dev_build.sh. Lockfile was not overwritten.');
214
+ }
215
+ const lockfile = path.join(local, 'pnpm-lock.yaml');
216
+ if (fs.existsSync(lockfile) && !readOptional(lockfile).equals(readOptional(path.join(source, 'pnpm-lock.yaml')))) {
217
+ const temporary = path.join(source, `.pnpm-lock.yaml.${process.pid}.tmp`);
218
+ try {
219
+ fs.copyFileSync(lockfile, temporary);
220
+ fs.renameSync(temporary, path.join(source, 'pnpm-lock.yaml'));
221
+ } finally { fs.rmSync(temporary, { force: true }); }
222
+ }
223
+ fs.writeFileSync(state, fingerprint());
224
+ }
225
+
226
+ async function watch(args) {
227
+ const local = fs.realpathSync(process.env.COZE_TARO_LOCAL_ACTIVE || path.resolve(__dirname, '..', '..'));
228
+ if (!onDrive) return run(args[0], args.slice(1), local);
229
+ ensureCache();
230
+ if (local !== path.join(fs.realpathSync(projectCache), 'dev')) {
231
+ throw new Error(`Refusing to watch an unmanaged workspace: ${local}`);
232
+ }
233
+ const preparedInput = installInput(local);
234
+ let running = true;
235
+ let syncError;
236
+ const command = run(args[0], args.slice(1), local).finally(() => { running = false; });
237
+ const poll = (async () => {
238
+ while (running && !interrupted) {
239
+ await delay(1000);
240
+ if (!running || interrupted) break;
241
+ try {
242
+ await locked(async () => {
243
+ await sync(local);
244
+ if (installInput(local) !== preparedInput) {
245
+ throw new Error('Dependency inputs changed; rerun dev_build.sh and dev_run.sh before previewing.');
246
+ }
247
+ });
248
+ }
249
+ catch (error) {
250
+ syncError = error;
251
+ for (const child of children) stopTree(child);
252
+ break;
253
+ }
254
+ }
255
+ })();
256
+ const results = await Promise.allSettled([command, poll]);
257
+ if (syncError) throw syncError;
258
+ if (results[0].status === 'rejected') throw results[0].reason;
259
+ }
260
+
261
+ async function syncOutputBack(local, outputs = outputDirs) {
262
+ for (const output of outputs) {
263
+ const localOutput = path.join(local, output);
264
+ const sourceOutput = path.join(source, output);
265
+ if (!fs.existsSync(localOutput)) continue;
266
+ fs.rmSync(sourceOutput, { recursive: true, force: true });
267
+ fs.mkdirSync(path.dirname(sourceOutput), { recursive: true });
268
+ await run('rsync', ['-a', '--delete', `${localOutput}/`, `${sourceOutput}/`], local);
269
+ }
270
+ }
271
+
272
+ function cleanOutputs(local, outputs = outputDirs) {
273
+ for (const output of outputs) {
274
+ fs.rmSync(path.join(local, output), { recursive: true, force: true });
275
+ }
276
+ }
277
+
278
+ function taroBuildOutput(args) {
279
+ const target = args[1] === 'h5' ? 'web' : args[1];
280
+ const output = taroOutputDirs[target];
281
+ if (!output) throw new Error(`Unknown Taro build target: ${args[1] || ''}`);
282
+ return output;
283
+ }
284
+
285
+ function runScript(script, local, args) {
286
+ const scriptPath = path.join(local, '.cozeproj', 'scripts', script);
287
+ if (script.endsWith('.cjs')) {
288
+ return run(process.execPath, [scriptPath, ...args], local, localEnv(local));
289
+ }
290
+ return run('bash', [scriptPath, ...args], local, localEnv(local));
291
+ }
292
+
293
+ async function main() {
294
+ const [action, ...args] = process.argv.slice(2);
295
+ if (action === 'watch') return watch(args);
296
+ if (!['prepare', 'dev', 'build', 'pack', 'validate', 'taro-build'].includes(action)) throw new Error(`Unknown Taro action: ${action}`);
297
+ const scriptByAction = {
298
+ prepare: 'dev_build.sh',
299
+ dev: 'dev_run.sh',
300
+ build: 'deploy_build.sh',
301
+ pack: 'pack.sh',
302
+ validate: 'validate.sh',
303
+ 'taro-build': 'taro-build.cjs',
304
+ };
305
+ if (!onDrive) {
306
+ return runScript(scriptByAction[action], source, args);
307
+ }
308
+ ensureCache();
309
+ const mode = action === 'validate' ? 'check' : action === 'build' || action === 'pack' || action === 'taro-build' ? 'build' : 'dev';
310
+ const local = path.join(fs.realpathSync(projectCache), mode);
311
+ console.log(`[taro] Source: ${source}\n[taro] Local ${mode} workspace: ${local}`);
312
+ if (action === 'taro-build') {
313
+ const output = taroBuildOutput(args);
314
+ return locked(async () => {
315
+ await sync(local);
316
+ await install(local, mode);
317
+ cleanOutputs(local, [output]);
318
+ await runScript(scriptByAction[action], local, args);
319
+ await locked(async () => {
320
+ await syncOutputBack(local, [output]);
321
+ }, 'output');
322
+ }, mode);
323
+ }
324
+ if (action === 'validate') {
325
+ return locked(async () => {
326
+ await locked(async () => {
327
+ await sync(local);
328
+ await install(local, mode);
329
+ });
330
+ await runScript('validate.sh', local, args);
331
+ }, 'check');
332
+ }
333
+ await locked(async () => {
334
+ await sync(local);
335
+ await install(local, mode);
336
+ }, mode);
337
+ if (action === 'build' || action === 'pack') {
338
+ cleanOutputs(local);
339
+ }
340
+ await runScript(scriptByAction[action], local, args);
341
+ if (action === 'build' || action === 'pack') {
342
+ await locked(async () => {
343
+ await syncOutputBack(local);
344
+ }, 'output');
345
+ }
346
+ }
347
+
348
+ main().catch(error => {
349
+ console.error(`[taro] ${error.message}`);
350
+ process.exitCode = process.exitCode || 1;
351
+ });
@@ -1,13 +1,18 @@
1
1
  #!/bin/bash
2
+ set -Eeuo pipefail
2
3
 
3
4
  ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
5
+ if [[ "${COZE_TARO_LOCAL_ACTIVE:-}" != "${ROOT_DIR}" ]]; then
6
+ exec node "$ROOT_DIR/.cozeproj/scripts/local-workspace.cjs" pack "$@"
7
+ fi
4
8
  COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-${ROOT_DIR}}"
5
9
  export COZE_WORKSPACE_PATH
6
10
 
7
11
  cd "${COZE_WORKSPACE_PATH}"
8
12
 
9
- # build_weapp.sh - 通过 PID 文件精确杀掉自己上次的构建进程
10
- PID_FILE="/tmp/coze-build_weapp.pid"
13
+ LOG_DIR="${COZE_LOG_DIR:-/tmp}"
14
+ mkdir -p "$LOG_DIR"
15
+ PID_FILE="$LOG_DIR/coze-build_weapp.pid"
11
16
 
12
17
  # 杀掉上次的构建进程组
13
18
  if [ -f "$PID_FILE" ]; then
@@ -21,11 +26,16 @@ if [ -f "$PID_FILE" ]; then
21
26
  rm -f "$PID_FILE"
22
27
  fi
23
28
 
24
- # 用 setsid 创建新的进程组,方便下次整组杀掉
25
- setsid pnpm build:pack &
26
- echo $! > "$PID_FILE"
29
+ # 用 setsid 创建新的进程组,方便下次整组杀掉;无 setsid 的环境退化为普通后台进程。
30
+ if command -v setsid >/dev/null 2>&1; then
31
+ setsid pnpm build:pack &
32
+ else
33
+ pnpm build:pack &
34
+ fi
35
+ BUILD_PID=$!
36
+ echo "$BUILD_PID" > "$PID_FILE"
27
37
 
28
38
  echo "构建已启动 (PID: $(cat $PID_FILE))"
29
39
 
30
- wait $!
40
+ wait "$BUILD_PID"
31
41
  rm -f "$PID_FILE"
@@ -98,6 +98,7 @@ printf '%s\n' "$$" > "$LOCK_DIR/pid"
98
98
  trap release_lock EXIT
99
99
 
100
100
  mkdir -p "$WORK_DIR"
101
+ INSTALL_STATE_FILE="$WORK_DIR/.install-state"
101
102
 
102
103
  # Previous versions mirrored the whole project into WORK_DIR. That gives pnpm
103
104
  # and framework dev servers two paths for the same source tree, which breaks
@@ -118,12 +119,13 @@ cleanup_legacy_workspace() {
118
119
  done < <(find "$workspace_dir" -mindepth 1 -maxdepth 1 -print0)
119
120
  }
120
121
 
122
+ # Preserve existing project caches during dependency preparation.
121
123
  cleanup_legacy_shadow_project() {
122
124
  local entry name
123
125
  while IFS= read -r -d '' entry; do
124
126
  name="$(basename "$entry")"
125
127
  case "$name" in
126
- node_modules|client|server) continue ;;
128
+ node_modules|client|server|caches|.install-state) continue ;;
127
129
  esac
128
130
  rm -rf "$entry"
129
131
  done < <(find "$WORK_DIR" -mindepth 1 -maxdepth 1 -print0)
@@ -141,6 +143,162 @@ link_install_entry() {
141
143
  fi
142
144
  }
143
145
 
146
+ hash_install_input() {
147
+ if command -v sha256sum >/dev/null 2>&1; then
148
+ sha256sum | awk '{print $1}'
149
+ elif command -v shasum >/dev/null 2>&1; then
150
+ shasum -a 256 | awk '{print $1}'
151
+ else
152
+ cksum | awk '{print $1 "-" $2}'
153
+ fi
154
+ }
155
+
156
+ append_file_to_install_fingerprint() {
157
+ local relative_path="$1"
158
+ local source_path="$PROJECT_ROOT/$relative_path"
159
+ printf 'path=%s\n' "$relative_path"
160
+ if [ -f "$source_path" ]; then
161
+ cat "$source_path"
162
+ else
163
+ printf '<missing>\n'
164
+ fi
165
+ }
166
+
167
+ append_directory_to_install_fingerprint() {
168
+ local relative_path="$1"
169
+ local source_path="$PROJECT_ROOT/$relative_path"
170
+ local file
171
+ printf 'path=%s\n' "$relative_path"
172
+ if [ ! -d "$source_path" ]; then
173
+ printf '<missing>\n'
174
+ return
175
+ fi
176
+
177
+ while IFS= read -r file; do
178
+ printf 'file=%s\n' "${file#"${PROJECT_ROOT}/"}"
179
+ cat "$file"
180
+ done < <(find -P "$source_path" -type f -print | LC_ALL=C sort)
181
+ }
182
+
183
+ # Everything that can change the resolved dependency tree. The leading version marker
184
+ # invalidates every stored state when this scheme itself changes.
185
+ calculate_install_fingerprint() {
186
+ local filename workspace argument
187
+ {
188
+ printf 'prepare-node-modules-install-state=1\n'
189
+ printf 'node-version=%s\n' "$(node --version)"
190
+ printf 'pnpm-version=%s\n' "$(pnpm --version)"
191
+ printf 'node-env=%s\n' "${NODE_ENV:-}"
192
+ printf 'npm-config-production=%s\n' "${npm_config_production:-}"
193
+ printf 'npm-config-production-upper=%s\n' "${NPM_CONFIG_PRODUCTION:-}"
194
+ printf 'pnpm-config-production=%s\n' "${PNPM_CONFIG_PRODUCTION:-}"
195
+ for argument in "$@"; do
196
+ printf 'install-argument=%s\n' "$argument"
197
+ done
198
+ for filename in package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc; do
199
+ append_file_to_install_fingerprint "$filename"
200
+ done
201
+ for workspace in client server; do
202
+ append_file_to_install_fingerprint "$workspace/package.json"
203
+ done
204
+ append_directory_to_install_fingerprint patches
205
+ } | hash_install_input
206
+ }
207
+
208
+ install_requires_refresh() {
209
+ local argument
210
+ for argument in "$@"; do
211
+ case "$argument" in
212
+ --force|-f|--lockfile-only|--fix-lockfile) return 0 ;;
213
+ esac
214
+ done
215
+ return 1
216
+ }
217
+
218
+ # Reuse skips pnpm install entirely, so it must not skip side effects that live outside
219
+ # node_modules. preinstall is exempt: it only guards which package manager may run, and
220
+ # there is no install to guard when the tree is already in place.
221
+ package_has_install_lifecycle() {
222
+ local package_path="$1"
223
+ node - "$package_path" <<'NODE'
224
+ const fs = require('node:fs');
225
+ const [packagePath] = process.argv.slice(2);
226
+
227
+ try {
228
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
229
+ const scripts = packageJson && typeof packageJson.scripts === 'object' && packageJson.scripts
230
+ ? packageJson.scripts
231
+ : {};
232
+ const hasLifecycle = ['install', 'postinstall', 'prepare'].some(
233
+ name => typeof scripts[name] === 'string' && scripts[name].trim() !== '',
234
+ );
235
+
236
+ process.exit(hasLifecycle ? 0 : 1);
237
+ } catch {
238
+ process.exit(0);
239
+ }
240
+ NODE
241
+ }
242
+
243
+ install_reuse_is_safe() {
244
+ local workspace package_path
245
+ for package_path in "$PROJECT_ROOT/.pnpmfile.cjs" "$PROJECT_ROOT/.pnpmfile.js"; do
246
+ if [ -e "$package_path" ]; then
247
+ echo "[node_modules] Reinstalling because pnpm hooks are present: $package_path"
248
+ return 1
249
+ fi
250
+ done
251
+
252
+ if [ -f "$PROJECT_ROOT/.npmrc" ] && grep -Eq '^[[:space:]]*pnpmfile[[:space:]]*=' "$PROJECT_ROOT/.npmrc"; then
253
+ echo "[node_modules] Reinstalling because .npmrc configures a pnpm hook."
254
+ return 1
255
+ fi
256
+
257
+ for workspace in . client server; do
258
+ package_path="$PROJECT_ROOT/$workspace/package.json"
259
+ [ -f "$package_path" ] || continue
260
+ if package_has_install_lifecycle "$package_path"; then
261
+ echo "[node_modules] Reinstalling because $package_path has an install lifecycle script."
262
+ return 1
263
+ fi
264
+ done
265
+ return 0
266
+ }
267
+
268
+ dependencies_are_ready() {
269
+ local workspace
270
+ [ -f "$WORK_DIR/node_modules/.modules.yaml" ] || return 1
271
+ for workspace in client server; do
272
+ if [ -f "$PROJECT_ROOT/$workspace/package.json" ] &&
273
+ [ ! -f "$WORK_DIR/$workspace/node_modules/.modules.yaml" ]; then
274
+ return 1
275
+ fi
276
+ done
277
+ return 0
278
+ }
279
+
280
+ # 判断顺序按代价从小到大排。指纹要读云盘上的 lockfile 和整个 patches/,所以放最后:只有其余
281
+ # 条件都满足、确实可能复用时才付这份开销。build.sh 和 prepare.sh 不设开关,第一行就返回了。
282
+ install_can_be_reused() {
283
+ local installed_fingerprint=""
284
+
285
+ [ "${COZE_REUSE_NODE_MODULES:-}" = "1" ] || return 1
286
+ install_requires_refresh "$@" && return 1
287
+ [ -f "$INSTALL_STATE_FILE" ] || return 1
288
+ IFS= read -r installed_fingerprint < "$INSTALL_STATE_FILE" || return 1
289
+ dependencies_are_ready || return 1
290
+ install_reuse_is_safe || return 1
291
+ [ "$installed_fingerprint" = "$(calculate_install_fingerprint "$@")" ] || return 1
292
+ return 0
293
+ }
294
+
295
+ write_install_state() {
296
+ local fingerprint="$1" temporary_state
297
+ temporary_state="$(mktemp "$WORK_DIR/.install-state.XXXXXX")"
298
+ printf '%s\n' "$fingerprint" > "$temporary_state"
299
+ mv -f "$temporary_state" "$INSTALL_STATE_FILE"
300
+ }
301
+
144
302
  copy_install_metadata() {
145
303
  local filename source_file target_file workspace
146
304
  for filename in pnpm-lock.yaml pnpm-workspace.yaml .npmrc; do
@@ -190,16 +348,26 @@ link_node_modules() {
190
348
  cleanup_legacy_shadow_project
191
349
  copy_install_metadata
192
350
 
193
- echo "[node_modules] Installing dependencies in $WORK_DIR"
194
- if ! (cd "$WORK_DIR" && pnpm install "$@"); then
195
- exit 1
196
- fi
351
+ if install_can_be_reused "$@"; then
352
+ echo "[node_modules] Reusing unchanged dependencies in $WORK_DIR"
353
+ else
354
+ # A stale state file must not survive a failed install.
355
+ rm -f "$INSTALL_STATE_FILE"
356
+ echo "[node_modules] Installing dependencies in $WORK_DIR"
357
+ if ! (cd "$WORK_DIR" && pnpm install "$@"); then
358
+ exit 1
359
+ fi
360
+
361
+ if [ -f "$WORK_DIR/pnpm-lock.yaml" ]; then
362
+ temporary_lockfile="$(mktemp "$PROJECT_ROOT/.pnpm-lock.yaml.XXXXXX")"
363
+ cp "$WORK_DIR/pnpm-lock.yaml" "$temporary_lockfile"
364
+ chmod 0644 "$temporary_lockfile"
365
+ mv -f "$temporary_lockfile" "$PROJECT_ROOT/pnpm-lock.yaml"
366
+ fi
197
367
 
198
- if [ -f "$WORK_DIR/pnpm-lock.yaml" ]; then
199
- temporary_lockfile="$(mktemp "$PROJECT_ROOT/.pnpm-lock.yaml.XXXXXX")"
200
- cp "$WORK_DIR/pnpm-lock.yaml" "$temporary_lockfile"
201
- chmod 0644 "$temporary_lockfile"
202
- mv -f "$temporary_lockfile" "$PROJECT_ROOT/pnpm-lock.yaml"
368
+ # pnpm may have rewritten the lockfile, so record the fingerprint of the tree as it
369
+ # now stands. Otherwise the next run would see a changed input and reinstall.
370
+ write_install_state "$(calculate_install_fingerprint "$@")"
203
371
  fi
204
372
 
205
373
  link_node_modules "$PROJECT_ROOT" "$WORK_DIR/node_modules"
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable @typescript-eslint/no-require-imports -- Standalone CommonJS runtime shipped without CLI dependencies. */
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { spawn } = require('node:child_process');
6
+
7
+ const scriptRoot = fs.realpathSync(path.resolve(__dirname, '..', '..'));
8
+ const [action, target, ...extraArgs] = process.argv.slice(2);
9
+ const normalizedTarget = target === 'h5' ? 'web' : target;
10
+ const taroTypeByTarget = {
11
+ web: 'h5',
12
+ weapp: 'weapp',
13
+ tt: 'tt',
14
+ };
15
+ const validTargets = new Set(['web', 'weapp', 'tt']);
16
+ const validActions = new Set(['build', 'preview']);
17
+
18
+ function run(command, args, options = {}) {
19
+ const child = spawn(command, args, {
20
+ cwd: options.cwd || process.cwd(),
21
+ env: options.env || process.env,
22
+ stdio: 'inherit',
23
+ });
24
+ child.once('exit', (code, signal) => {
25
+ if (signal) {
26
+ process.kill(process.pid, signal);
27
+ return;
28
+ }
29
+ process.exit(code || 0);
30
+ });
31
+ child.once('error', error => {
32
+ console.error(error.message);
33
+ process.exit(1);
34
+ });
35
+ }
36
+
37
+ if (!validActions.has(action) || !validTargets.has(normalizedTarget)) {
38
+ console.error('Usage: taro-build.cjs <build|preview> <web|weapp|tt|h5> [...args]');
39
+ process.exit(1);
40
+ }
41
+
42
+ if (action === 'preview' && normalizedTarget === 'web') {
43
+ console.error('Taro preview is only supported for weapp or tt.');
44
+ process.exit(1);
45
+ }
46
+
47
+ if (process.env.COZE_TARO_LOCAL_ACTIVE !== scriptRoot) {
48
+ run(process.execPath, [
49
+ path.join(scriptRoot, '.cozeproj', 'scripts', 'local-workspace.cjs'),
50
+ 'taro-build',
51
+ action,
52
+ normalizedTarget,
53
+ ...extraArgs,
54
+ ], { cwd: scriptRoot });
55
+ return;
56
+ }
57
+
58
+ const taroArgs = ['exec', 'taro', 'build', '--type', taroTypeByTarget[normalizedTarget]];
59
+ if (action === 'preview') {
60
+ taroArgs.push('--preview');
61
+ }
62
+ taroArgs.push(...extraArgs);
63
+
64
+ run('pnpm', taroArgs, {
65
+ cwd: process.env.COZE_WORKSPACE_PATH || scriptRoot,
66
+ });
@@ -2,6 +2,9 @@
2
2
  set -Eeuo pipefail
3
3
 
4
4
  ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
5
+ if [[ "${COZE_TARO_LOCAL_ACTIVE:-}" != "${ROOT_DIR}" ]]; then
6
+ exec node "$ROOT_DIR/.cozeproj/scripts/local-workspace.cjs" validate "$@"
7
+ fi
5
8
  COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-${ROOT_DIR}}"
6
9
  export COZE_WORKSPACE_PATH
7
10