@supersdk/supercli 0.3.2 → 0.3.3-staging.45

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 (93) hide show
  1. package/dist/build/artifactIntegrity.js +119 -0
  2. package/dist/build/artifactIntegrity.js.map +1 -0
  3. package/dist/cli.js +22 -11
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/add.js +79 -31
  6. package/dist/commands/add.js.map +1 -1
  7. package/dist/commands/analytics.js +15 -9
  8. package/dist/commands/analytics.js.map +1 -1
  9. package/dist/commands/build.js +231 -0
  10. package/dist/commands/build.js.map +1 -0
  11. package/dist/commands/config.js +170 -0
  12. package/dist/commands/config.js.map +1 -0
  13. package/dist/commands/db.js +24 -19
  14. package/dist/commands/db.js.map +1 -1
  15. package/dist/commands/deploy.js +434 -751
  16. package/dist/commands/deploy.js.map +1 -1
  17. package/dist/commands/env.js +8 -8
  18. package/dist/commands/env.js.map +1 -1
  19. package/dist/commands/image.js +31 -20
  20. package/dist/commands/image.js.map +1 -1
  21. package/dist/commands/init.js +68 -37
  22. package/dist/commands/init.js.map +1 -1
  23. package/dist/commands/logs.js +16 -7
  24. package/dist/commands/logs.js.map +1 -1
  25. package/dist/commands/publishSite.js +28 -943
  26. package/dist/commands/publishSite.js.map +1 -1
  27. package/dist/commands/register.js +51 -30
  28. package/dist/commands/register.js.map +1 -1
  29. package/dist/commands/settings.js +10 -6
  30. package/dist/commands/settings.js.map +1 -1
  31. package/dist/config/appConfig.js +40 -36
  32. package/dist/config/appConfig.js.map +1 -1
  33. package/dist/config/superConfig.js +429 -0
  34. package/dist/config/superConfig.js.map +1 -0
  35. package/dist/deploy/adapterTypes.js +3 -0
  36. package/dist/deploy/adapterTypes.js.map +1 -0
  37. package/dist/deploy/manifest.js +381 -0
  38. package/dist/deploy/manifest.js.map +1 -0
  39. package/dist/deploy/preflight.js +202 -0
  40. package/dist/deploy/preflight.js.map +1 -0
  41. package/dist/deploy/resultWriter.js +178 -0
  42. package/dist/deploy/resultWriter.js.map +1 -0
  43. package/dist/deploy/runAdapter.js +299 -0
  44. package/dist/deploy/runAdapter.js.map +1 -0
  45. package/dist/deploy/siteAdapter.js +182 -0
  46. package/dist/deploy/siteAdapter.js.map +1 -0
  47. package/dist/docker/dockerCli.js +63 -1
  48. package/dist/docker/dockerCli.js.map +1 -1
  49. package/dist/output/envelope.js +5 -1
  50. package/dist/output/envelope.js.map +1 -1
  51. package/dist/output/resultPrinter.js +3 -0
  52. package/dist/output/resultPrinter.js.map +1 -1
  53. package/dist/publish/responseClassifier.js +4 -4
  54. package/dist/publish/responseClassifier.js.map +1 -1
  55. package/dist/publish/runClient.js +11 -11
  56. package/dist/publish/runClient.js.map +1 -1
  57. package/dist/publish/siteZip.js +4 -5
  58. package/dist/publish/siteZip.js.map +1 -1
  59. package/dist/template/README.md +64 -227
  60. package/dist/template/android/app/src/main/java/com/supersdk/simple/EnvironmentStore.java +1 -1
  61. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +2 -2
  62. package/dist/template/android/gradle/supersdk-config-reader.gradle +6 -5
  63. package/dist/template/android/supersdk-default.config.json +3 -2
  64. package/dist/template/ios/Sources/App/AppDelegate.swift +1 -1
  65. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +1 -1
  66. package/dist/template/scripts/build_android.sh +26 -10
  67. package/dist/template/scripts/build_ios.sh +41 -9
  68. package/dist/template/scripts/build_service.sh +89 -0
  69. package/dist/template/scripts/build_site.sh +40 -26
  70. package/dist/template/scripts/lib/workspace.sh +4 -4
  71. package/dist/template/scripts/serve_web.py +2 -4
  72. package/dist/template/scripts/super_build_orchestrator.py +278 -355
  73. package/dist/template/scripts/supersdk_template.py +414 -181
  74. package/dist/template/scripts/web_package.py +9 -8
  75. package/dist/template/service/Dockerfile +2 -0
  76. package/dist/template/{supersdk.json → super.json} +20 -1
  77. package/dist/template/super_build.sh +39 -113
  78. package/dist/template/template_manifest.json +5 -4
  79. package/dist/workspace/config.js +81 -119
  80. package/dist/workspace/config.js.map +1 -1
  81. package/dist/workspace/identity.js +15 -14
  82. package/dist/workspace/identity.js.map +1 -1
  83. package/dist/workspace/inspect.js +1 -0
  84. package/dist/workspace/inspect.js.map +1 -1
  85. package/dist/workspace/projectContext.js +93 -0
  86. package/dist/workspace/projectContext.js.map +1 -0
  87. package/dist/workspace/projectIdentity.js +53 -96
  88. package/dist/workspace/projectIdentity.js.map +1 -1
  89. package/dist/workspace/template.js +5 -8
  90. package/dist/workspace/template.js.map +1 -1
  91. package/package.json +2 -2
  92. package/dist/publish/siteConfig.js +0 -649
  93. package/dist/publish/siteConfig.js.map +0 -1
@@ -7,6 +7,7 @@ import re
7
7
  import shlex
8
8
  import sys
9
9
  import uuid
10
+ import hashlib
10
11
  from pathlib import Path
11
12
  from urllib.parse import urlparse
12
13
 
@@ -19,17 +20,18 @@ from web_host_validator import HostValidationError, normalize_host
19
20
  # `supercli add`,CLI 写出新 schema、仓库自带的老引擎报「schemaVersion 必须是 N」——
20
21
  # 那条错指向用户自己的配置文件,完全指不到真正的原因(工程模板过期了)。
21
22
  # 版本号写进 managed config 纯为溯源;`engine-check` 子命令据此给出可执行的升级提示。
22
- ENGINE_VERSION = "3.0.0"
23
+ ENGINE_VERSION = "4.0.0"
23
24
 
24
25
  MANAGED_BY = "supersdk-template"
25
26
  # 每个项目目录下的 `.supersdk/managed/config.json` 有自己的 snake_case `schema_version`,
26
27
  # 与根配置文件的 `schemaVersion` 是**两份**契约,各自独立演进。
27
- MANAGED_CONFIG_SCHEMA_VERSION = 3
28
+ MANAGED_CONFIG_SCHEMA_VERSION = 4
28
29
  MANAGED_CONFIG_KEYS = (
29
30
  "managed_by",
30
31
  "schema_version",
31
32
  "engine_version",
32
33
  "spid",
34
+ "project_id",
33
35
  "name",
34
36
  "platform",
35
37
  "dir",
@@ -38,38 +40,48 @@ MANAGED_CONFIG_KEYS = (
38
40
  "platform_config",
39
41
  )
40
42
 
41
- # 工作空间根配置:一个 workspace = 一个 spid,`supersdk.json` 所在目录即工作空间根。
42
- CONFIG_FILENAME = "supersdk.json"
43
- CONFIG_SCHEMA_VERSION = 3
44
- LEGACY_CONFIG_FILENAMES = ("supersdk.yaml", "supersdk.yml", "super-site.yml")
43
+ # 工作空间根配置:一个 workspace = 一个 spid,`super.json` 所在目录即工作空间根。
44
+ CONFIG_FILENAME = "super.json"
45
+ CONFIG_SCHEMA_VERSION = 4
46
+ LEGACY_CONFIG_FILENAMES = ("supersdk.json", "supersdk.yaml", "supersdk.yml", "super-site.yml")
45
47
 
46
48
  # 首批项目类型。`type` 是普通字符串字段,加新类型只要加一个 build_<type>.sh 与一段投影,
47
49
  # 不需要动 schema 版本;但**未知类型一律 fail-closed**,否则 plan 会给出一个根本不存在的
48
50
  # helper 路径,直到 build 阶段才炸。
49
- PROJECT_TYPES = ("android", "ios", "site")
51
+ PROJECT_TYPES = ("android", "ios", "site", "service")
50
52
  TYPE_ORDER = {name: index for index, name in enumerate(PROJECT_TYPES)}
51
53
 
52
54
  # 每个项目条目允许的键。身份键(package / bundleId)只出现在项目里:
53
55
  # 永不继承、永不推导,推导出来的身份等于把第三方 App 发到别人的反向域名下。
54
- COMMON_PROJECT_KEYS = {"type", "dir", "name", "version", "sdk"}
56
+ COMMON_PROJECT_KEYS = {"projectId", "type", "dir", "name", "version", "sdk"}
55
57
  TYPE_PROJECT_KEYS = {
56
58
  "android": {"package"},
57
59
  "ios": {"bundleId", "spmMode"},
58
- "site": {"deploy", "offline"},
60
+ "site": {"deploy", "offline", "build"},
61
+ "service": {"deploy", "build"},
59
62
  }
60
63
  # 打错的身份键必须给定向诊断,而不是泛泛的 "unknown key"。
61
64
  PROJECT_KEY_ALIASES = {
62
65
  "ios": {"bundle_id": "bundleId", "bundleID": "bundleId", "bundle-id": "bundleId"},
63
66
  "android": {"applicationId": "package", "package_name": "package", "packageName": "package"},
64
67
  "site": {"host": "offline.host", "sites": "deploy"},
68
+ "service": {},
65
69
  }
66
70
  SITE_OFFLINE_KEYS = {"host"}
71
+ SITE_BUILD_KEYS = {"outputDir"}
72
+ SERVICE_BUILD_KEYS = {"context", "dockerfile", "platform", "argsFromEnv"}
73
+ DEPLOY_COMMON_KEYS = {"envTarget", "slug", "env", "name"}
74
+ SERVICE_DEPLOY_KEYS = {
75
+ "port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection", "runtimeEnvFromEnv", "secretsFromEnv"
76
+ }
77
+ ENV_REFERENCE_KEYS = {"name", "sourceEnv"}
67
78
  VERSION_KEYS = {"name", "code"}
68
79
  SDK_KEYS = {"androidVersion", "iosPackageUrl", "iosVersion"}
69
80
  SDK_PROJECTION = {
70
81
  "android": {"mock": ("androidVersion",), "real": ("androidVersion",)},
71
82
  "ios": {"mock": (), "real": ("iosPackageUrl", "iosVersion")},
72
83
  "site": {"mock": (), "real": ()},
84
+ "service": {"mock": (), "real": ()},
73
85
  }
74
86
 
75
87
  ANDROID_NAMESPACE = "com.supersdk.simple"
@@ -81,6 +93,7 @@ JAVA_PACKAGE_PATTERN = r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+"
81
93
 
82
94
  DEFAULT_VERSION_NAME = "1.0.0"
83
95
  DEFAULT_VERSION_CODE = 1
96
+ MISSING = object()
84
97
 
85
98
  # 退役根键。每一条都给**定向**诊断,而不是被「未知键原样保留」的规则带过去。
86
99
  # v1 关键字先于 schemaVersion 检查(它们的诊断与 schemaVersion 无关);
@@ -94,7 +107,7 @@ RETIRED_ROOT_KEYS = {
94
107
  RETIRED_V2_ROOT_KEYS = {
95
108
  "environment": (
96
109
  "retired key; environment is a runtime init parameter, not build configuration. "
97
- "Delete it from supersdk.json: SuperSDK.init(context, spid, provider) defaults to prod, "
110
+ "Delete it from super.json: SuperSDK.init(context, spid, provider) defaults to prod, "
98
111
  "and the bundled demo apps switch environment at runtime"
99
112
  ),
100
113
  "android": 'retired schema v2 key; it is now an entry in projects[]: {"type": "android", "dir": "android", ...}',
@@ -105,7 +118,7 @@ RETIRED_V2_ROOT_KEYS = {
105
118
 
106
119
  # 每个必填字段都在:少一个字段的迁移提示,对照抄的人就是死路。
107
120
  MIGRATION_TEMPLATE = """{
108
- "schemaVersion": 3,
121
+ "schemaVersion": 4,
109
122
  "spid": "demo0001",
110
123
  "name": "SuperSDK Simple",
111
124
  "version": {
@@ -117,12 +130,14 @@ MIGRATION_TEMPLATE = """{
117
130
  },
118
131
  "projects": [
119
132
  {
133
+ "projectId": "android",
120
134
  "type": "android",
121
135
  "dir": "android",
122
136
  "name": "SuperSDK Simple",
123
137
  "package": "com.example.app"
124
138
  },
125
139
  {
140
+ "projectId": "ios",
126
141
  "type": "ios",
127
142
  "dir": "ios",
128
143
  "name": "SuperSDK Simple",
@@ -130,6 +145,7 @@ MIGRATION_TEMPLATE = """{
130
145
  "spmMode": "mock"
131
146
  },
132
147
  {
148
+ "projectId": "web",
133
149
  "type": "site",
134
150
  "dir": "web",
135
151
  "name": "SuperSDK Simple Web",
@@ -152,13 +168,25 @@ MIGRATION_TEMPLATE = """{
152
168
  # 项目条目键序的语义:先身份(type/dir/name),再平台身份字段,再站点侧的 deploy/offline,
153
169
  # 最后是可覆盖的默认值(version/sdk)。
154
170
  ROOT_KEY_ORDER = ("schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects")
155
- PROJECT_KEY_ORDER = ("type", "dir", "name", "package", "bundleId", "spmMode", "deploy", "offline", "version", "sdk")
171
+ PROJECT_KEY_ORDER = (
172
+ "projectId", "type", "dir", "name", "package", "bundleId", "spmMode", "build", "deploy", "offline", "version", "sdk"
173
+ )
156
174
  NESTED_KEY_ORDER = {
157
175
  "version": ("name", "code"),
158
176
  "sdk": ("androidVersion", "iosPackageUrl", "iosVersion"),
159
177
  "offline": ("host",),
178
+ "build": ("outputDir", "context", "dockerfile", "platform", "argsFromEnv"),
160
179
  }
161
- DEPLOY_KEY_ORDER = ("slug", "name", "env", "dir")
180
+ DEPLOY_KEY_ORDER = (
181
+ "envTarget", "slug", "name", "env", "port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection",
182
+ "runtimeEnvFromEnv", "secretsFromEnv",
183
+ )
184
+ PROJECT_ID_PATTERN = r"[a-z][a-z0-9-]{0,63}"
185
+ ENV_TARGET_PATTERN = r"[a-z][a-z0-9-]{0,31}"
186
+ ENV_NAME_PATTERN = r"[A-Za-z_][A-Za-z0-9_]*"
187
+ DEPLOY_SLUG_PATTERN = r"[a-z0-9]{1,32}"
188
+ DEPLOY_ENV_PATTERN = r"[a-z0-9]{1,10}"
189
+ RESERVED_DEPLOY_SLUGS = {"stg", "site"}
162
190
 
163
191
 
164
192
  class ConfigError(Exception):
@@ -172,10 +200,11 @@ def helper_path():
172
200
  return Path(__file__).resolve()
173
201
 
174
202
 
175
- def migrate_command(config_path=None):
176
- """可照抄执行的迁移命令。路径未知时也给出一条完整命令,而不是半句话。"""
177
- target = shlex.quote(str(config_path)) if config_path is not None else "path/to/supersdk.json"
178
- return f"python3 {shlex.quote(str(helper_path()))} migrate --config {target}"
203
+ def migrate_command(source=None, target=None):
204
+ """Return the real, copy-pasteable v3 -> v4 migration command."""
205
+ source_arg = shlex.quote(str(source)) if source is not None else "supersdk.json"
206
+ target_arg = shlex.quote(str(target)) if target is not None else "super.json"
207
+ return f"python3 {shlex.quote(str(helper_path()))} migrate --from {source_arg} --to {target_arg}"
179
208
 
180
209
 
181
210
  def config_file_state(target_path):
@@ -277,8 +306,6 @@ def load_config(path):
277
306
 
278
307
 
279
308
  def require_mapping(value, field):
280
- if value is None:
281
- return {}
282
309
  if not isinstance(value, dict):
283
310
  raise ConfigError(field, "must be a JSON object")
284
311
  return value
@@ -343,6 +370,8 @@ def validate_ios_version(value, field="sdk.iosVersion"):
343
370
 
344
371
  def validate_sdk_namespace(raw_sdk, field):
345
372
  """只做**形状**校验(键名/标量),值的合法性留给按项目的 scope。"""
373
+ if raw_sdk is MISSING:
374
+ raw_sdk = {}
346
375
  sdk = require_mapping(raw_sdk, field)
347
376
  for key, value in sdk.items():
348
377
  if not isinstance(key, str):
@@ -355,27 +384,32 @@ def validate_sdk_namespace(raw_sdk, field):
355
384
 
356
385
 
357
386
  def validate_version_namespace(raw_version, field):
387
+ if raw_version is MISSING:
388
+ raw_version = {}
358
389
  version = require_mapping(raw_version, field)
359
390
  for key in version:
360
391
  if key not in VERSION_KEYS:
361
392
  raise ConfigError(f"{field}.{key}", "unknown key")
393
+ if "name" in version:
394
+ require_string(version["name"], f"{field}.name")
395
+ if "code" in version:
396
+ validate_version_code(version["code"], f"{field}.code")
362
397
  return version
363
398
 
364
399
 
365
400
  def resolve_version(version, field):
366
401
  """把一份 version 对象归一成 {name, code}。整值替换后的兜底默认值在这里生效。"""
367
402
  version_name = version.get("name", DEFAULT_VERSION_NAME)
368
- if isinstance(version_name, (int, float)) and not isinstance(version_name, bool):
369
- version_name = str(version_name)
370
403
  version_name = require_string(version_name, f"{field}.name")
371
404
  version_code = validate_version_code(version.get("code", DEFAULT_VERSION_CODE), f"{field}.code")
372
405
  return {"name": version_name, "code": version_code}
373
406
 
374
407
 
375
408
  def validate_cli_owned_keys(raw):
376
- # `orgId` 归 supercli。模板只做类型校验,保证站点侧的 schema 变更永远不会打断 App 构建。
377
- if "orgId" in raw and not isinstance(raw["orgId"], str):
378
- raise ConfigError("orgId", "must be a string")
409
+ if "orgId" in raw and (
410
+ not isinstance(raw["orgId"], str) or not re.fullmatch(r"[1-9][0-9]*", raw["orgId"])
411
+ ):
412
+ raise ConfigError("orgId", "must be a positive decimal string")
379
413
 
380
414
 
381
415
  def normalize_project_dir(value, field):
@@ -385,8 +419,8 @@ def normalize_project_dir(value, field):
385
419
  raise ConfigError(field, "must use forward slashes")
386
420
  if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
387
421
  raise ConfigError(field, "must be relative to the workspace root")
388
- parts = [part for part in raw.split("/") if part != ""]
389
- if not parts:
422
+ parts = raw.split("/")
423
+ if not parts or any(part == "" for part in parts):
390
424
  raise ConfigError(field, "must name a subdirectory of the workspace root")
391
425
  for part in parts:
392
426
  if part in (".", ".."):
@@ -420,39 +454,53 @@ def assert_dirs_are_disjoint(entries):
420
454
  )
421
455
 
422
456
 
457
+ def assert_project_ids_unique(shapes):
458
+ seen = {}
459
+ for shape in shapes:
460
+ project_id = shape["projectId"]
461
+ if project_id in seen:
462
+ raise ConfigError(
463
+ f"projects[{shape['index']}].projectId",
464
+ f"duplicates projects[{seen[project_id]}].projectId ({project_id})",
465
+ )
466
+ seen[project_id] = shape["index"]
467
+
468
+
423
469
  def read_project_shape(entry, index):
424
- """只读出选择所需的最小信息(type / dir),其余校验按 selected 分流。"""
470
+ """只读出选择所需的最小信息(projectId / type / dir),其余校验按 selected 分流。"""
425
471
  if not isinstance(entry, dict):
426
472
  raise ConfigError(f"projects[{index}]", "must be a JSON object")
427
473
  project_type = entry.get("type")
428
474
  if project_type is None:
429
475
  raise ConfigError(f"projects[{index}].type", f"is required; one of {', '.join(PROJECT_TYPES)}")
430
476
  project_type = require_string(project_type, f"projects[{index}].type")
477
+ project_id = require_string(entry.get("projectId"), f"projects[{index}].projectId")
478
+ if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
479
+ raise ConfigError(f"projects[{index}].projectId", f"must match ^{PROJECT_ID_PATTERN}$")
431
480
  directory = normalize_project_dir(entry.get("dir"), f"projects[{index}].dir")
432
- return {"index": index, "type": project_type, "dir": directory, "raw": entry}
481
+ return {"index": index, "projectId": project_id, "type": project_type, "dir": directory, "raw": entry}
433
482
 
434
483
 
435
484
  def select_project_shapes(shapes, platform="all", project=None):
436
485
  selected = shapes
437
486
  if project is not None:
438
- # 先按目录挑,再核对类型:否则 `--platform android --project web` 会报
439
- # 「没有这个目录」,而真正的问题是「这个目录不是 android 项目」。
440
- wanted = normalize_project_dir(project, "--project")
441
- selected = [shape for shape in selected if shape["dir"] == wanted]
487
+ wanted = require_string(project, "--project")
488
+ selected = [shape for shape in selected if shape["projectId"] == wanted]
442
489
  if not selected:
443
- known = ", ".join(shape["dir"] for shape in shapes) or "<none>"
444
- raise ConfigError("--project", f"no project with dir {wanted}; configured directories: {known}")
490
+ known = ", ".join(shape["projectId"] for shape in shapes) or "<none>"
491
+ raise ConfigError("--project", f"no project with projectId {wanted}; configured projectIds: {known}")
445
492
  if platform != "all" and selected[0]["type"] != platform:
446
493
  raise ConfigError("--project", f"{wanted} is a {selected[0]['type']} project, not {platform}")
447
494
  if platform != "all":
448
495
  selected = [shape for shape in selected if shape["type"] == platform]
449
- return sorted(selected, key=lambda shape: (TYPE_ORDER.get(shape["type"], len(TYPE_ORDER)), shape["index"]))
496
+ return selected
450
497
 
451
498
 
452
499
  def validate_project(shape, root_name, workspace_version, workspace_sdk):
453
500
  entry = shape["raw"]
454
501
  index = shape["index"]
455
502
  directory = shape["dir"]
503
+ project_id = shape["projectId"]
456
504
  project_type = shape["type"]
457
505
  label = f"projects[{directory}]"
458
506
 
@@ -486,18 +534,26 @@ def validate_project(shape, root_name, workspace_version, workspace_sdk):
486
534
  name = entry.get("name")
487
535
  if name is not None:
488
536
  name = require_string(name, f"{label}.name")
537
+ if name != name.strip():
538
+ raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
539
+ maximum = 50 if project_type in {"site", "service"} else 100
540
+ if len(name) > maximum:
541
+ raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
489
542
 
490
543
  if project_type == "android":
491
544
  platform_config = validate_android_project(label, entry, name, root_name, sdk)
492
545
  elif project_type == "ios":
493
546
  platform_config = validate_ios_project(label, entry, name, root_name, sdk)
494
- else:
547
+ elif project_type == "site":
495
548
  platform_config = validate_site_project(label, entry)
549
+ else:
550
+ platform_config = validate_service_project(label, entry)
496
551
 
497
552
  mode = platform_config.get("spmMode", "mock")
498
553
  projected_sdk = {key: sdk[key] for key in project_sdk(project_type, mode) if key in sdk}
499
554
 
500
555
  return {
556
+ "projectId": project_id,
501
557
  "type": project_type,
502
558
  "dir": directory,
503
559
  "name": name,
@@ -513,6 +569,9 @@ def require_project_name(label, name, root_name, project_type, target):
513
569
  raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
514
570
  if any(ord(char) < 32 for char in name):
515
571
  raise ConfigError(f"{label}.name", f"must be a {target} without control characters")
572
+ maximum = 50 if project_type in {"site", "service"} else 100
573
+ if len(name) > maximum:
574
+ raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
516
575
  return name
517
576
  hint = (
518
577
  "the workspace-level name is a description and is never projected as an App label, "
@@ -560,17 +619,13 @@ def validate_ios_project(label, entry, name, root_name, sdk):
560
619
 
561
620
 
562
621
  def validate_site_project(label, entry):
563
- # deploy[] 归 supercli(每条逐字等于旧 sites[] 条目)。模板只做类型校验后整块忽略,
564
- # 保证站点侧的 schema 变更永远不会打断构建。
565
- deploy = entry.get("deploy")
566
- if deploy is not None:
567
- if not isinstance(deploy, list):
568
- raise ConfigError(f"{label}.deploy", "must be an array")
569
- for position, item in enumerate(deploy):
570
- if not isinstance(item, dict):
571
- raise ConfigError(f"{label}.deploy[{position}]", "must be a JSON object")
572
-
573
- offline = require_mapping(entry.get("offline"), f"{label}.offline")
622
+ validate_deploy_targets(label, entry.get("deploy", MISSING), "site")
623
+
624
+ build = require_mapping(entry.get("build", {}), f"{label}.build")
625
+ reject_unknown_keys(build, SITE_BUILD_KEYS, f"{label}.build")
626
+ output_dir = normalize_project_relative_path(build.get("outputDir", "dist"), f"{label}.build.outputDir")
627
+
628
+ offline = require_mapping(entry.get("offline", {}), f"{label}.offline")
574
629
  for key in offline:
575
630
  if key not in SITE_OFFLINE_KEYS:
576
631
  raise ConfigError(f"{label}.offline.{key}", "unknown key")
@@ -581,7 +636,112 @@ def validate_site_project(label, entry):
581
636
  host = normalize_host(host)
582
637
  except HostValidationError as exc:
583
638
  raise ConfigError(f"{label}.offline.host", str(exc)) from exc
584
- return {"host": host}
639
+ return {"host": host, "outputDir": output_dir}
640
+
641
+
642
+ def reject_unknown_keys(value, allowed, field):
643
+ for key in value:
644
+ if key not in allowed:
645
+ raise ConfigError(f"{field}.{key}", "unknown key")
646
+
647
+
648
+ def normalize_project_relative_path(value, field, allow_dot=False):
649
+ raw = require_string(value, field)
650
+ if raw == "." and allow_dot:
651
+ return raw
652
+ if "\\" in raw or raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
653
+ raise ConfigError(field, "must be a relative POSIX path")
654
+ parts = raw.split("/")
655
+ if not parts or any(part in ("", ".", "..") for part in parts):
656
+ raise ConfigError(field, "must stay within the project directory")
657
+ return "/".join(parts)
658
+
659
+
660
+ def validate_env_references(raw, field):
661
+ if raw is MISSING:
662
+ return []
663
+ if not isinstance(raw, list):
664
+ raise ConfigError(field, "must be an array")
665
+ seen = set()
666
+ result = []
667
+ for index, item in enumerate(raw):
668
+ item_field = f"{field}[{index}]"
669
+ item = require_mapping(item, item_field)
670
+ reject_unknown_keys(item, ENV_REFERENCE_KEYS, item_field)
671
+ name = require_string(item.get("name"), f"{item_field}.name")
672
+ source = require_string(item.get("sourceEnv"), f"{item_field}.sourceEnv")
673
+ if not re.fullmatch(ENV_NAME_PATTERN, name) or not re.fullmatch(ENV_NAME_PATTERN, source):
674
+ raise ConfigError(item_field, "name and sourceEnv must be environment variable names")
675
+ if name in seen:
676
+ raise ConfigError(f"{item_field}.name", "duplicates a platform environment variable name")
677
+ seen.add(name)
678
+ result.append({"name": name, "sourceEnv": source})
679
+ return result
680
+
681
+
682
+ def validate_deploy_targets(label, raw, project_type):
683
+ if raw is MISSING:
684
+ return []
685
+ if not isinstance(raw, list):
686
+ raise ConfigError(f"{label}.deploy", "must be an array")
687
+ result = []
688
+ seen = set()
689
+ for index, target in enumerate(raw):
690
+ field = f"{label}.deploy[{index}]"
691
+ target = require_mapping(target, field)
692
+ allowed = DEPLOY_COMMON_KEYS | (SERVICE_DEPLOY_KEYS if project_type == "service" else set())
693
+ reject_unknown_keys(target, allowed, field)
694
+ env_target = require_string(target.get("envTarget"), f"{field}.envTarget")
695
+ if not re.fullmatch(ENV_TARGET_PATTERN, env_target):
696
+ raise ConfigError(f"{field}.envTarget", f"must match ^{ENV_TARGET_PATTERN}$")
697
+ if env_target in seen:
698
+ raise ConfigError(f"{field}.envTarget", "must be unique within the project")
699
+ seen.add(env_target)
700
+ slug = require_string(target.get("slug"), f"{field}.slug")
701
+ if not re.fullmatch(DEPLOY_SLUG_PATTERN, slug) or slug in RESERVED_DEPLOY_SLUGS:
702
+ raise ConfigError(f"{field}.slug", "must be 1..32 lowercase letters or digits and not a reserved slug")
703
+ env = require_string(target.get("env"), f"{field}.env")
704
+ if not re.fullmatch(DEPLOY_ENV_PATTERN, env):
705
+ raise ConfigError(f"{field}.env", "must be 1..10 lowercase letters or digits")
706
+ if "name" in target:
707
+ target_name = require_string(target["name"], f"{field}.name")
708
+ if target_name != target_name.strip() or len(target_name) > 50:
709
+ raise ConfigError(f"{field}.name", "must be 1..50 characters without surrounding whitespace")
710
+ for key, upper in (("port", 65535), ("cpuMilli", 4000), ("memoryMiB", 8192), ("maxScale", 10)):
711
+ if key in target and (not is_positive_int(target[key]) or target[key] > upper):
712
+ raise ConfigError(f"{field}.{key}", f"must be an integer from 1 to {upper}")
713
+ if "databaseConnection" in target and target["databaseConnection"] is not None:
714
+ require_string(target["databaseConnection"], f"{field}.databaseConnection")
715
+ if project_type == "service":
716
+ runtime_refs = validate_env_references(target.get("runtimeEnvFromEnv", MISSING), f"{field}.runtimeEnvFromEnv")
717
+ secret_refs = validate_env_references(target.get("secretsFromEnv", MISSING), f"{field}.secretsFromEnv")
718
+ runtime_names = {reference["name"] for reference in runtime_refs}
719
+ duplicate_names = sorted(runtime_names & {reference["name"] for reference in secret_refs})
720
+ if duplicate_names:
721
+ raise ConfigError(field, "duplicates platform environment variable name across runtimeEnvFromEnv/secretsFromEnv: " + ", ".join(duplicate_names))
722
+ result.append(target)
723
+ return result
724
+
725
+
726
+ def validate_service_project(label, entry):
727
+ if "build" not in entry:
728
+ raise ConfigError(f"{label}.build", "is required for service projects")
729
+ build = require_mapping(entry["build"], f"{label}.build")
730
+ reject_unknown_keys(build, SERVICE_BUILD_KEYS, f"{label}.build")
731
+ context = normalize_project_relative_path(build.get("context", "."), f"{label}.build.context", allow_dot=True)
732
+ dockerfile = normalize_project_relative_path(build.get("dockerfile", "Dockerfile"), f"{label}.build.dockerfile")
733
+ platform = require_string(build.get("platform", "linux/amd64"), f"{label}.build.platform")
734
+ if platform != "linux/amd64":
735
+ raise ConfigError(f"{label}.build.platform", "must be linux/amd64 for this engine version")
736
+ args_from_env = build.get("argsFromEnv", [])
737
+ if not isinstance(args_from_env, list) or any(
738
+ not isinstance(item, str) or not re.fullmatch(ENV_NAME_PATTERN, item) for item in args_from_env
739
+ ):
740
+ raise ConfigError(f"{label}.build.argsFromEnv", "must be an array of environment variable names")
741
+ if len(set(args_from_env)) != len(args_from_env):
742
+ raise ConfigError(f"{label}.build.argsFromEnv", "must not contain duplicates")
743
+ validate_deploy_targets(label, entry.get("deploy", MISSING), "service")
744
+ return {"context": context, "dockerfile": dockerfile, "platform": platform, "argsFromEnv": args_from_env}
585
745
 
586
746
 
587
747
  def check_root_envelope(raw, config_path=None):
@@ -593,15 +753,18 @@ def check_root_envelope(raw, config_path=None):
593
753
  if key in raw:
594
754
  raise ConfigError(key, reason)
595
755
 
756
+ allowed_root = set(ROOT_KEY_ORDER)
757
+ for key in raw:
758
+ if key not in allowed_root:
759
+ raise ConfigError(key, "unknown key")
760
+
596
761
  schema_version = raw.get("schemaVersion")
597
762
  if isinstance(schema_version, bool) or not isinstance(schema_version, int) or schema_version != CONFIG_SCHEMA_VERSION:
598
763
  message = f"must be {CONFIG_SCHEMA_VERSION}"
599
- if schema_version == 2 and not isinstance(schema_version, bool):
764
+ if schema_version == 3 and not isinstance(schema_version, bool):
600
765
  message += (
601
- f"; this file is schema v2. schemaVersion {CONFIG_SCHEMA_VERSION} is breaking and there is no "
602
- "backward compatibility. Migrate it in place (projects[] replaces android/ios/web/sites, "
603
- "environment is dropped because it is a runtime init parameter):\n"
604
- + migrate_command(config_path)
766
+ f"; this file is schema v3. schemaVersion {CONFIG_SCHEMA_VERSION} is breaking and there is no "
767
+ "backward compatibility. Run `supercli config migrate --from supersdk.json --to super.json`."
605
768
  )
606
769
  raise ConfigError("schemaVersion", message)
607
770
 
@@ -619,6 +782,7 @@ def read_project_shapes(raw):
619
782
  raise ConfigError("projects", "must be an array")
620
783
  shapes = [read_project_shape(entry, index) for index, entry in enumerate(entries)]
621
784
  assert_dirs_are_disjoint([(shape["index"], shape) for shape in shapes])
785
+ assert_project_ids_unique(shapes)
622
786
  return shapes
623
787
 
624
788
 
@@ -665,22 +829,42 @@ def validate_config(raw, selected=None, project=None, config_path=None):
665
829
  root_name = raw.get("name")
666
830
  if root_name is not None:
667
831
  root_name = require_string(root_name, "name")
832
+ if root_name != root_name.strip() or len(root_name) > 100:
833
+ raise ConfigError("name", "must be 1..100 characters without surrounding whitespace")
668
834
 
669
835
  # workspace 级 version/sdk 的**形状**无条件校验(它是工作空间级字段,与选谁无关);
670
836
  # sdk 里各个值的合法性(androidVersion 格式、real 模式的 url/version)因类型而异,
671
837
  # 留给按项目的 scope。
672
- workspace_version = resolve_version(validate_version_namespace(raw.get("version"), "version"), "version")
673
- workspace_sdk = validate_sdk_namespace(raw.get("sdk"), "sdk")
838
+ workspace_version = resolve_version(validate_version_namespace(raw.get("version", MISSING), "version"), "version")
839
+ workspace_sdk = validate_sdk_namespace(raw.get("sdk", MISSING), "sdk")
674
840
 
675
841
  shapes = read_project_shapes(raw)
676
842
  selected_shapes = select_project_shapes(shapes, platform, project)
677
- projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in selected_shapes]
843
+ all_projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in shapes]
844
+ selected_ids = {shape["projectId"] for shape in selected_shapes}
845
+ projects = [item for item in all_projects if item["projectId"] in selected_ids]
846
+
847
+ target_owners = {}
848
+ for index, entry in enumerate(raw["projects"]):
849
+ for target_index, target in enumerate(entry.get("deploy", [])):
850
+ if not isinstance(target, dict) or "slug" not in target or "env" not in target:
851
+ continue
852
+ key = (target["slug"], target["env"])
853
+ if key in target_owners:
854
+ raise ConfigError(
855
+ f"projects[{index}].deploy[{target_index}]",
856
+ f"duplicates platform target slug/env owned by {target_owners[key]}",
857
+ )
858
+ target_owners[key] = f"projects[{index}].deploy[{target_index}]"
678
859
 
679
860
  return {
680
861
  "schemaVersion": CONFIG_SCHEMA_VERSION,
681
862
  "engineVersion": ENGINE_VERSION,
682
863
  "spid": spid,
864
+ "orgId": raw.get("orgId"),
683
865
  "name": root_name,
866
+ "version": workspace_version,
867
+ "sdk": dict(workspace_sdk),
684
868
  "projects": projects,
685
869
  "projectDirs": [shape["dir"] for shape in shapes],
686
870
  }
@@ -714,6 +898,7 @@ def target_content(normalized, project):
714
898
  "schema_version": MANAGED_CONFIG_SCHEMA_VERSION,
715
899
  "engine_version": ENGINE_VERSION,
716
900
  "spid": normalized["spid"],
901
+ "project_id": project["projectId"],
717
902
  "name": project["name"],
718
903
  "platform": project["type"],
719
904
  "dir": project["dir"],
@@ -868,7 +1053,7 @@ def print_plan(root, config, platform, project):
868
1053
  require_selection(normalized, platform, project)
869
1054
  for item in normalized["projects"]:
870
1055
  helper = Path(root) / "scripts" / ("build_" + item["type"] + ".sh")
871
- print(f"platform={item['type']} dir={item['dir']} helper={helper} mode=plan")
1056
+ print(f"projectId={item['projectId']} type={item['type']} dir={item['dir']} helper={helper} mode=plan")
872
1057
 
873
1058
 
874
1059
  def print_resolve(config, platform, project):
@@ -879,10 +1064,10 @@ def print_resolve(config, platform, project):
879
1064
  def resolve_single(config, platform, project):
880
1065
  projects = resolve_shapes(config, platform, project)
881
1066
  if len(projects) > 1:
882
- dirs = ", ".join(item["dir"] for item in projects)
1067
+ ids = ", ".join(item["projectId"] for item in projects)
883
1068
  raise ConfigError(
884
1069
  "--project",
885
- f"{len(projects)} {platform} projects are configured ({dirs}); pass --project <dir> to pick one",
1070
+ f"{len(projects)} {platform} projects are configured ({ids}); pass --project <projectId> to pick one",
886
1071
  )
887
1072
  return projects[0]["dir"]
888
1073
 
@@ -953,143 +1138,190 @@ def serialize_project(entry):
953
1138
  if key in NESTED_KEY_ORDER and isinstance(value, dict):
954
1139
  out[key] = order_keys(value, NESTED_KEY_ORDER[key])
955
1140
  elif key == "deploy" and isinstance(value, list):
956
- out[key] = [order_keys(item, DEPLOY_KEY_ORDER) if isinstance(item, dict) else item for item in value]
1141
+ out[key] = [serialize_deploy_target(item) for item in value]
957
1142
  else:
958
1143
  out[key] = value
959
1144
  return out
960
1145
 
961
1146
 
962
- def migrate_document(raw, config_dir):
963
- """v2 -> v3,零信息损失。
1147
+ def serialize_deploy_target(item):
1148
+ if not isinstance(item, dict):
1149
+ return item
1150
+ ordered = order_keys(item, DEPLOY_KEY_ORDER)
1151
+ for key in ("runtimeEnvFromEnv", "secretsFromEnv"):
1152
+ if isinstance(ordered.get(key), list):
1153
+ ordered[key] = [order_keys(ref, ("name", "sourceEnv")) if isinstance(ref, dict) else ref for ref in ordered[key]]
1154
+ return ordered
964
1155
 
965
- 🔴 结构性事实:v2 的模板目录就是 `android/ ios/ web/`,v3 可以原样保留
966
- (`{"type": "site", "dir": "web"}`)—— **迁移不移动任何文件**,只改配置。
967
- v2 的 `sites[]` 每条 `{slug,name,env,dir}` 逐字搬进 site 项目的 `deploy[]`。
968
- """
1156
+
1157
+ def collect_v3_unknown_paths(raw):
1158
+ """Enumerate every v3 field that cannot be represented by the strict v4 schema."""
1159
+ unknown = []
969
1160
  if not isinstance(raw, dict):
970
- raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
971
- version = raw.get("schemaVersion")
972
- if version == CONFIG_SCHEMA_VERSION:
973
- return None, ["already schemaVersion 3; nothing to migrate"]
974
- if isinstance(version, bool) or not isinstance(version, int) or version != 2:
975
- raise ConfigError("schemaVersion", "migrate reads schemaVersion 2 documents only")
976
-
977
- # 🔴 fail closed:v2 文档里已经带了根级 projects,说明有人手工迁到一半。
978
- # 两份身份来源同时在场,合并语义是未定义的 —— 旧实现更糟:下面「保留未知根键」的
979
- # 循环会把刚算出来的 projects 整个盖掉,exit 0、零告警、身份全丢。所以这里一个字
980
- # 都不写,让用户先删掉一边。
981
- if "projects" in raw:
982
- legacy_sections = [key for key in ("android", "ios", "web", "sites") if key in raw]
983
- if legacy_sections:
984
- raise ConfigError(
985
- "projects",
986
- 'this schemaVersion 2 document carries a root "projects" key next to the v2 sections ('
987
- + ", ".join(legacy_sections)
988
- + "); the two are different identity sources and merging them is undefined, so nothing was "
989
- 'written. Remove one side first: delete "projects" to migrate from the v2 sections, or delete '
990
- "the v2 sections to keep the projects[] you wrote by hand.",
1161
+ return ["$"]
1162
+ root_allowed = {"schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects"}
1163
+ unknown.extend(f"$.{key}" for key in raw if key not in root_allowed)
1164
+ for field, allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
1165
+ value = raw.get(field)
1166
+ if isinstance(value, dict):
1167
+ unknown.extend(f"$.{field}.{key}" for key in value if key not in allowed)
1168
+ projects = raw.get("projects")
1169
+ if not isinstance(projects, list):
1170
+ return unknown
1171
+ for index, project in enumerate(projects):
1172
+ if not isinstance(project, dict):
1173
+ continue
1174
+ project_type = project.get("type")
1175
+ allowed = (COMMON_PROJECT_KEYS - {"projectId", "build"}) | TYPE_PROJECT_KEYS.get(project_type, set())
1176
+ if project_type == "site":
1177
+ allowed -= {"build"}
1178
+ unknown.extend(f"$.projects[{index}].{key}" for key in project if key not in allowed)
1179
+ for field, nested_allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
1180
+ value = project.get(field)
1181
+ if isinstance(value, dict):
1182
+ unknown.extend(
1183
+ f"$.projects[{index}].{field}.{key}" for key in value if key not in nested_allowed
1184
+ )
1185
+ offline = project.get("offline")
1186
+ if isinstance(offline, dict):
1187
+ unknown.extend(f"$.projects[{index}].offline.{key}" for key in offline if key not in SITE_OFFLINE_KEYS)
1188
+ deploy = project.get("deploy")
1189
+ if isinstance(deploy, list):
1190
+ for target_index, target in enumerate(deploy):
1191
+ if isinstance(target, dict):
1192
+ allowed_target = {"slug", "name", "env", "dir"}
1193
+ unknown.extend(
1194
+ f"$.projects[{index}].deploy[{target_index}].{key}"
1195
+ for key in target if key not in allowed_target
1196
+ )
1197
+ build = project.get("build")
1198
+ if "build" in allowed and isinstance(build, dict):
1199
+ nested_allowed = SERVICE_BUILD_KEYS if project_type == "service" else SITE_BUILD_KEYS
1200
+ unknown.extend(
1201
+ f"$.projects[{index}].build.{key}" for key in build if key not in nested_allowed
991
1202
  )
992
- raise ConfigError(
993
- "projects",
994
- 'this schemaVersion 2 document carries a root "projects" key, which is the schemaVersion 3 identity '
995
- "list; migrate will neither merge into it nor drop it, so nothing was written. If that projects[] is "
996
- 'your hand-written v3 list, set "schemaVersion": 3 in the file and run validate instead of migrate; '
997
- "if the key means something else, rename it and re-run migrate.",
998
- )
1203
+ return sorted(unknown)
999
1204
 
1000
- notes = []
1001
- # v2 的 name 是 App label(缺省 "SuperSDK Simple");v3 里根 name 只是描述,
1002
- # 真身份在项目条目上,所以要把**生效值**抄进每个 android/ios 项目。
1003
- app_label = raw.get("name") if isinstance(raw.get("name"), str) and raw.get("name").strip() else "SuperSDK Simple"
1004
1205
 
1005
- migrated = {"schemaVersion": CONFIG_SCHEMA_VERSION}
1206
+ def migrate_document(raw, config_dir=None):
1207
+ """Convert a strict schema-v3 document to schema v4 without guessing identities."""
1208
+ del config_dir
1209
+ if not isinstance(raw, dict):
1210
+ raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
1211
+ version = raw.get("schemaVersion")
1212
+ if isinstance(version, bool) or not isinstance(version, int) or version != 3:
1213
+ raise ConfigError("schemaVersion", "migrate reads schemaVersion 3 documents only")
1214
+ unknown = collect_v3_unknown_paths(raw)
1215
+ if unknown:
1216
+ raise ConfigError("migration", "unknown field(s): " + ", ".join(unknown))
1217
+
1218
+ migrated = {"schemaVersion": 4}
1006
1219
  for key in ("spid", "orgId", "name", "version", "sdk"):
1007
1220
  if key in raw:
1008
1221
  migrated[key] = raw[key]
1009
-
1010
- if "environment" in raw:
1011
- notes.append(
1012
- f"dropped root environment ({raw['environment']!r}): it is a runtime init parameter now. "
1013
- "Pass it to SuperSDK.init at runtime, or use the demo environment switcher."
1014
- )
1015
-
1016
- projects = []
1017
- android = raw.get("android")
1018
- if isinstance(android, dict) or (config_dir / "android").is_dir():
1019
- entry = {"type": "android", "dir": "android", "name": app_label}
1020
- if isinstance(android, dict) and "package" in android:
1021
- entry["package"] = android["package"]
1022
- projects.append(entry)
1023
-
1024
- ios = raw.get("ios")
1025
- if isinstance(ios, dict) or (config_dir / "ios").is_dir():
1026
- entry = {"type": "ios", "dir": "ios", "name": app_label}
1027
- if isinstance(ios, dict):
1028
- for key in ("bundleId", "spmMode"):
1029
- if key in ios:
1030
- entry[key] = ios[key]
1031
- projects.append(entry)
1032
-
1033
- web = raw.get("web")
1034
- sites = raw.get("sites")
1035
- if isinstance(web, dict) or isinstance(sites, list) or (config_dir / "web").is_dir():
1036
- entry = {"type": "site", "dir": "web", "name": app_label}
1037
- if isinstance(sites, list):
1038
- # 逐字搬运:一个字段都不能丢,包括 CLI 以后才认识的键。
1039
- entry["deploy"] = sites
1040
- if isinstance(web, dict) and "host" in web:
1041
- entry["offline"] = {"host": web["host"]}
1042
- else:
1043
- notes.append(
1044
- "site project has no offline.host; offline packaging stays disabled until the site is published "
1045
- "once (the CLI records the server-issued host) or you set projects[].offline.host by hand."
1046
- )
1047
- projects.append(entry)
1048
-
1049
- migrated["projects"] = projects
1050
- # 未知根键原样保留。"projects" 在跳过集里是**纵深防御**:上面的 fail-closed 守卫已经
1051
- # 让带根级 projects 的文档到不了这里,但这行保证「即使守卫被改坏,迁移结果也不会被
1052
- # 输入里的同名键覆盖」—— 这是数据丢失,不是配置问题。
1053
- consumed = {
1054
- "schemaVersion", "spid", "orgId", "name", "version", "sdk",
1055
- "environment", "android", "ios", "web", "sites", "projects",
1056
- }
1057
- for key, value in raw.items():
1058
- if key in consumed:
1059
- continue
1060
- migrated[key] = value
1061
-
1062
- if not projects:
1063
- notes.append("no android/ios/web project was found; projects[] is empty until you run `supercli add`.")
1064
- return migrated, notes
1065
-
1066
-
1067
- def migrate(config, dry_run):
1068
- config_path = Path(config)
1069
- raw = read_config_document(config_path)
1070
- migrated, notes = migrate_document(raw, config_path.parent)
1071
- if migrated is None:
1072
- for note in notes:
1073
- print(note)
1074
- return 0
1222
+ projects = raw.get("projects")
1223
+ if not isinstance(projects, list):
1224
+ raise ConfigError("projects", "must be an array")
1225
+ ids = {}
1226
+ converted = []
1227
+ conflicts = []
1228
+ for index, project in enumerate(projects):
1229
+ if not isinstance(project, dict):
1230
+ raise ConfigError(f"projects[{index}]", "must be a JSON object")
1231
+ directory = normalize_project_dir(project.get("dir"), f"projects[{index}].dir")
1232
+ project_id = Path(directory).name.lower()
1233
+ if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
1234
+ conflicts.append(f"projects[{index}].dir -> invalid projectId {project_id!r}")
1235
+ elif project_id in ids:
1236
+ conflicts.append(f"projects[{index}].dir -> projectId {project_id!r} also from projects[{ids[project_id]}]")
1237
+ ids[project_id] = index
1238
+ entry = {"projectId": project_id}
1239
+ for key, value in project.items():
1240
+ if key != "deploy":
1241
+ entry[key] = value
1242
+ if project.get("type") == "site" and "deploy" in project:
1243
+ deploy = project["deploy"]
1244
+ if not isinstance(deploy, list):
1245
+ raise ConfigError(f"projects[{index}].deploy", "must be an array")
1246
+ targets = []
1247
+ output_dirs = set()
1248
+ env_targets = set()
1249
+ for target_index, target in enumerate(deploy):
1250
+ if not isinstance(target, dict):
1251
+ raise ConfigError(f"projects[{index}].deploy[{target_index}]", "must be a JSON object")
1252
+ env_target = target.get("env")
1253
+ if env_target in env_targets:
1254
+ conflicts.append(f"projects[{index}].deploy[{target_index}].env -> duplicate envTarget {env_target!r}")
1255
+ env_targets.add(env_target)
1256
+ converted_target = {"envTarget": env_target}
1257
+ for key in ("slug", "name", "env"):
1258
+ if key in target:
1259
+ converted_target[key] = target[key]
1260
+ if "dir" in target:
1261
+ output_dirs.add(normalize_project_relative_path(target["dir"], f"projects[{index}].deploy[{target_index}].dir"))
1262
+ targets.append(converted_target)
1263
+ if len(output_dirs) > 1:
1264
+ conflicts.append(f"projects[{index}].deploy[].dir -> multiple site output directories")
1265
+ entry["deploy"] = targets
1266
+ if output_dirs:
1267
+ entry["build"] = {"outputDir": next(iter(output_dirs))}
1268
+ converted.append(entry)
1269
+ if conflicts:
1270
+ raise ConfigError("migration", "ambiguous mapping(s): " + "; ".join(conflicts))
1271
+ migrated["projects"] = converted
1272
+ validate_config(migrated)
1273
+ return migrated, []
1274
+
1275
+
1276
+ def canonical_config_text(document):
1277
+ """The byte-stable semantic representation shared by build and deploy."""
1278
+ validate_config(document)
1279
+ return serialize_config(document)
1280
+
1281
+
1282
+ def canonical_config_sha256(document):
1283
+ return hashlib.sha256(canonical_config_text(document).encode("utf-8")).hexdigest()
1284
+
1285
+
1286
+ def migrate(source, target, dry_run=False):
1287
+ source_path = Path(source).resolve()
1288
+ target_path = Path(target).resolve()
1289
+ if source_path.parent != target_path.parent:
1290
+ raise ConfigError("migration", "--from and --to must be in the same normalized workspace root")
1291
+ if target_path.exists():
1292
+ raise ConfigError("migration", f"target already exists: {target_path}")
1293
+ migrated, _ = migrate_document(read_config_document(source_path), source_path.parent)
1075
1294
  text = serialize_config(migrated)
1076
1295
  if dry_run:
1077
1296
  sys.stdout.write(text)
1078
- else:
1079
- temp = config_path.with_name(f".{config_path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
1080
- temp.write_text(text, encoding="utf-8")
1081
- os.replace(temp, config_path)
1082
- print(f"migrated {config_path} to schemaVersion {CONFIG_SCHEMA_VERSION}")
1083
- for note in notes:
1084
- print(note)
1297
+ return 0
1298
+ temp = target_path.with_name(f".{target_path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
1085
1299
  try:
1086
- # 迁移是**逐字搬运**,不修数据:v2 时就缺的字段(比如从没设过 android.package)
1087
- # 迁移后依然缺。所以校验失败不代表迁移失败 —— 文件已经写好了,这里只是把
1088
- # 「接下来还要你补什么」说清楚,退出码非零是为了不让人以为万事大吉。
1089
- validate_config(migrated, config_path=config_path)
1090
- except ConfigError as exc:
1091
- print(f"post-migration check: the file is now schemaVersion 3 but still needs attention -> {exc}", file=sys.stderr)
1092
- return 1
1300
+ with temp.open("x", encoding="utf-8") as handle:
1301
+ handle.write(text)
1302
+ handle.flush()
1303
+ os.fsync(handle.fileno())
1304
+ # Hard-link install is atomic and no-clobber: unlike os.replace(), it
1305
+ # cannot overwrite a user file created after the exists() preflight.
1306
+ try:
1307
+ os.link(temp, target_path)
1308
+ except FileExistsError as exc:
1309
+ raise ConfigError("migration", f"target already exists: {target_path}") from exc
1310
+ except OSError as exc:
1311
+ raise ConfigError("migration", f"could not install target atomically: {exc}") from exc
1312
+ temp.unlink()
1313
+ try:
1314
+ directory_fd = os.open(str(target_path.parent), os.O_RDONLY)
1315
+ try:
1316
+ os.fsync(directory_fd)
1317
+ finally:
1318
+ os.close(directory_fd)
1319
+ except OSError:
1320
+ pass
1321
+ finally:
1322
+ if temp.exists():
1323
+ temp.unlink()
1324
+ print(f"migrated {source_path} to {target_path} (schemaVersion 4); source was not modified")
1093
1325
  return 0
1094
1326
 
1095
1327
 
@@ -1126,7 +1358,8 @@ def main(argv):
1126
1358
  check.add_argument("--config", required=True)
1127
1359
 
1128
1360
  migrate_cmd = sub.add_parser("migrate")
1129
- migrate_cmd.add_argument("--config", required=True)
1361
+ migrate_cmd.add_argument("--from", dest="source", required=True)
1362
+ migrate_cmd.add_argument("--to", dest="target", required=True)
1130
1363
  migrate_cmd.add_argument("--dry-run", action="store_true")
1131
1364
 
1132
1365
  args = parser.parse_args(argv)
@@ -1150,7 +1383,7 @@ def main(argv):
1150
1383
  elif args.command == "engine-check":
1151
1384
  engine_check(args.root, args.config)
1152
1385
  elif args.command == "migrate":
1153
- return migrate(args.config, args.dry_run)
1386
+ return migrate(args.source, args.target, args.dry_run)
1154
1387
  except ConfigError as exc:
1155
1388
  print(str(exc), file=sys.stderr)
1156
1389
  return 1