@playcraft/cli 0.1.22 → 0.1.24

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 (278) hide show
  1. package/README.md +3 -38
  2. package/dist/agent/local-backend.js +1 -1
  3. package/dist/cli-root-help.js +0 -1
  4. package/dist/commands/build.js +4 -9
  5. package/dist/commands/create.js +33 -26
  6. package/dist/commands/image.js +6 -2
  7. package/dist/commands/login.js +42 -84
  8. package/dist/commands/skills.js +0 -2
  9. package/dist/commands/tools-generation.js +4 -2
  10. package/dist/commands/tools.js +0 -2
  11. package/dist/config.js +4 -59
  12. package/dist/index.js +1 -6
  13. package/dist/remix/clone.js +0 -2
  14. package/dist/remix/init-template.js +0 -2
  15. package/dist/remix/pull.js +0 -2
  16. package/dist/remix/push.js +1 -21
  17. package/dist/utils/agent-api-client.js +29 -148
  18. package/dist/utils/playcraft-http-client.js +4 -6
  19. package/package.json +4 -10
  20. package/project-template/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  21. package/project-templates/phaser/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  22. package/project-templates/threejs/.claude/skills/playcraft-image-generation/SKILL.md +61 -23
  23. package/dist/auth/account-activation.js +0 -157
  24. package/dist/auth/messages.js +0 -30
  25. package/dist/commands/platform-skills.generated.js +0 -19
  26. package/dist/commands/tools-batch.js +0 -59
  27. package/dist/commands/workspace-runtime.js +0 -54
  28. package/dist/project-skills/commands.js +0 -72
  29. package/dist/project-skills/lifecycle.js +0 -28
  30. package/dist/project-skills/local-run.js +0 -112
  31. package/dist/project-skills/local-store.js +0 -149
  32. package/dist/project-skills/messages.js +0 -72
  33. package/dist/project-skills/reconcile.js +0 -62
  34. package/dist/project-skills/remote-cache.js +0 -51
  35. package/dist/project-skills/validation.js +0 -19
  36. package/dist/utils/environment-endpoints.js +0 -17
  37. package/dist/utils/tool-operation-journal.js +0 -124
  38. package/dist/workspace-runtime/codex/app-server.js +0 -571
  39. package/dist/workspace-runtime/codex/config-toml.js +0 -108
  40. package/dist/workspace-runtime/codex/jsonrpc-stdio.js +0 -123
  41. package/dist/workspace-runtime/codex/launcher-client.js +0 -163
  42. package/dist/workspace-runtime/codex/loopback.js +0 -143
  43. package/dist/workspace-runtime/codex/model-broker.js +0 -239
  44. package/dist/workspace-runtime/codex/native-adapter.js +0 -9
  45. package/dist/workspace-runtime/main.js +0 -10
  46. package/dist/workspace-runtime/persistence/journal.js +0 -355
  47. package/dist/workspace-runtime/persistence/sqlite-client.js +0 -61
  48. package/dist/workspace-runtime/persistence/sqlite-worker.js +0 -1015
  49. package/dist/workspace-runtime/previews/publish.js +0 -259
  50. package/dist/workspace-runtime/previews/single-file.js +0 -43
  51. package/dist/workspace-runtime/processes/managed-writes.js +0 -69
  52. package/dist/workspace-runtime/production/contracts.js +0 -17
  53. package/dist/workspace-runtime/production/controller.js +0 -207
  54. package/dist/workspace-runtime/production/dependencies.js +0 -60
  55. package/dist/workspace-runtime/production/native.js +0 -70
  56. package/dist/workspace-runtime/production/processes.js +0 -86
  57. package/dist/workspace-runtime/production/save-command.js +0 -20
  58. package/dist/workspace-runtime/production/stages.js +0 -175
  59. package/dist/workspace-runtime/production/storage.js +0 -32
  60. package/dist/workspace-runtime/serve.js +0 -199
  61. package/dist/workspace-runtime/server/auth.js +0 -21
  62. package/dist/workspace-runtime/server/connectivity.js +0 -201
  63. package/dist/workspace-runtime/server/desktop-host.js +0 -429
  64. package/dist/workspace-runtime/server/desktop-preview-config.js +0 -81
  65. package/dist/workspace-runtime/server/desktop-preview-service.js +0 -157
  66. package/dist/workspace-runtime/server/desktop-preview-static.js +0 -53
  67. package/dist/workspace-runtime/server/desktop-preview.js +0 -189
  68. package/dist/workspace-runtime/server/dispatch.js +0 -845
  69. package/dist/workspace-runtime/server/endpoints.js +0 -19
  70. package/dist/workspace-runtime/server/execution-group.js +0 -85
  71. package/dist/workspace-runtime/server/http.js +0 -919
  72. package/dist/workspace-runtime/server/lock.js +0 -53
  73. package/dist/workspace-runtime/server/rfb-watch-gate.js +0 -168
  74. package/dist/workspace-runtime/server/terminal-host.js +0 -294
  75. package/dist/workspace-runtime/server/types.js +0 -1
  76. package/dist/workspace-runtime/workspaces/attachments.js +0 -109
  77. package/dist/workspace-runtime/workspaces/batch-commit.js +0 -142
  78. package/dist/workspace-runtime/workspaces/cli-credentials.js +0 -111
  79. package/dist/workspace-runtime/workspaces/context-error.js +0 -2
  80. package/dist/workspace-runtime/workspaces/dependencies.js +0 -264
  81. package/dist/workspace-runtime/workspaces/developer-command.js +0 -64
  82. package/dist/workspace-runtime/workspaces/directories.js +0 -106
  83. package/dist/workspace-runtime/workspaces/directory-access.js +0 -20
  84. package/dist/workspace-runtime/workspaces/directory-maintenance.js +0 -111
  85. package/dist/workspace-runtime/workspaces/directory-stats.js +0 -49
  86. package/dist/workspace-runtime/workspaces/empty-template.js +0 -32
  87. package/dist/workspace-runtime/workspaces/files.js +0 -113
  88. package/dist/workspace-runtime/workspaces/git-credential-broker.js +0 -312
  89. package/dist/workspace-runtime/workspaces/git-credential-helper.js +0 -68
  90. package/dist/workspace-runtime/workspaces/git-direct-store.js +0 -155
  91. package/dist/workspace-runtime/workspaces/git.js +0 -471
  92. package/dist/workspace-runtime/workspaces/json5-edit.js +0 -170
  93. package/dist/workspace-runtime/workspaces/parameters.js +0 -272
  94. package/dist/workspace-runtime/workspaces/prepare.js +0 -263
  95. package/dist/workspace-runtime/workspaces/registry.js +0 -192
  96. package/dist/workspace-runtime/workspaces/revisions.js +0 -31
  97. package/dist/workspace-runtime/workspaces/skill-artifact-loader.js +0 -46
  98. package/dist/workspace-runtime/workspaces/skills.js +0 -179
  99. package/project-template-v2/.claude/agents/artist.md +0 -82
  100. package/project-template-v2/.claude/agents/developer.md +0 -153
  101. package/project-template-v2/.claude/agents/game-designer.md +0 -264
  102. package/project-template-v2/.claude/agents/refs/artist-art-style-catalog.md +0 -533
  103. package/project-template-v2/.claude/agents/refs/artist-color-audio-recipes.md +0 -153
  104. package/project-template-v2/.claude/agents/refs/artist-dimension-axis.md +0 -27
  105. package/project-template-v2/.claude/agents/refs/artist-master-composite-recipes.md +0 -208
  106. package/project-template-v2/.claude/agents/refs/atom-skill-library.md +0 -81
  107. package/project-template-v2/.claude/agents/refs/developer-impl-cookbook.md +0 -432
  108. package/project-template-v2/.claude/agents/refs/framework-5-component-filter.md +0 -252
  109. package/project-template-v2/.claude/agents/refs/framework-game-feel-juice.md +0 -266
  110. package/project-template-v2/.claude/agents/refs/framework-mda.md +0 -147
  111. package/project-template-v2/.claude/agents/refs/game-designer-gameplay-sufficiency.md +0 -123
  112. package/project-template-v2/.claude/agents/refs/ta-3d-flip-recipe.md +0 -88
  113. package/project-template-v2/.claude/agents/refs/ta-atlas-deliverable-standard.md +0 -67
  114. package/project-template-v2/.claude/agents/refs/ta-batch-pipeline-recipes.md +0 -120
  115. package/project-template-v2/.claude/agents/refs/ta-image-generation-detail.md +0 -300
  116. package/project-template-v2/.claude/agents/refs/ta-image-ops-reference.md +0 -495
  117. package/project-template-v2/.claude/agents/refs/ta-pipeline-cookbook.md +0 -1141
  118. package/project-template-v2/.claude/agents/refs/ta-tools-reference.md +0 -111
  119. package/project-template-v2/.claude/agents/refs/ta-vfx-preset-catalog.md +0 -365
  120. package/project-template-v2/.claude/agents/refs/threejs-cannon-pitfalls.md +0 -412
  121. package/project-template-v2/.claude/agents/reviewer.md +0 -75
  122. package/project-template-v2/.claude/agents/technical-artist.md +0 -86
  123. package/project-template-v2/.claude/hooks/snapshot-milestone.mjs +0 -243
  124. package/project-template-v2/.claude/hooks/user-prompt.mjs +0 -133
  125. package/project-template-v2/.claude/settings.json +0 -33
  126. package/project-template-v2/.claude/skills/brainstorming/SKILL.md +0 -161
  127. package/project-template-v2/.claude/skills/brainstorming/scripts/frame-template.html +0 -270
  128. package/project-template-v2/.claude/skills/brainstorming/scripts/helper.js +0 -177
  129. package/project-template-v2/.claude/skills/brainstorming/scripts/server.cjs +0 -354
  130. package/project-template-v2/.claude/skills/brainstorming/scripts/start-server.sh +0 -148
  131. package/project-template-v2/.claude/skills/brainstorming/scripts/stop-server.sh +0 -56
  132. package/project-template-v2/.claude/skills/brainstorming/scripts/wait-for-selection.sh +0 -62
  133. package/project-template-v2/.claude/skills/brainstorming/spec-document-reviewer-prompt.md +0 -49
  134. package/project-template-v2/.claude/skills/brainstorming/visual-companion.md +0 -309
  135. package/project-template-v2/.claude/skills/playcraft-ad-psychology/SKILL.md +0 -182
  136. package/project-template-v2/.claude/skills/playcraft-art-style-guide/SKILL.md +0 -123
  137. package/project-template-v2/.claude/skills/playcraft-asset-state-sheet/SKILL.md +0 -205
  138. package/project-template-v2/.claude/skills/playcraft-audio-generation/SKILL.md +0 -280
  139. package/project-template-v2/.claude/skills/playcraft-batch-pipeline/SKILL.md +0 -184
  140. package/project-template-v2/.claude/skills/playcraft-build-optimizer/SKILL.md +0 -306
  141. package/project-template-v2/.claude/skills/playcraft-image-generation/SKILL.md +0 -298
  142. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/build-sprite-sheet.template.mjs +0 -123
  143. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/compare-style.template.mjs +0 -254
  144. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +0 -324
  145. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +0 -97
  146. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-edit-variants.template.mjs +0 -118
  147. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +0 -137
  148. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +0 -397
  149. package/project-template-v2/.claude/skills/playcraft-image-generation/reference/validate-sprite-sheet.template.mjs +0 -296
  150. package/project-template-v2/.claude/skills/playcraft-image-ops/SKILL.md +0 -122
  151. package/project-template-v2/.claude/skills/playcraft-image-processing/SKILL.md +0 -219
  152. package/project-template-v2/.claude/skills/playcraft-masking/SKILL.md +0 -373
  153. package/project-template-v2/.claude/skills/playcraft-playable-optimization/SKILL.md +0 -161
  154. package/project-template-v2/.claude/skills/playcraft-research/SKILL.md +0 -215
  155. package/project-template-v2/.claude/skills/playcraft-skill-recommender/SKILL.md +0 -382
  156. package/project-template-v2/.claude/skills/playcraft-sprite-generation/SKILL.md +0 -423
  157. package/project-template-v2/.claude/skills/playcraft-sprite-remix/SKILL.md +0 -158
  158. package/project-template-v2/.claude/skills/playcraft-sprite-sheet/SKILL.md +0 -100
  159. package/project-template-v2/.claude/skills/playcraft-storyboard/SKILL.md +0 -167
  160. package/project-template-v2/.claude/skills/playcraft-style-qa/SKILL.md +0 -270
  161. package/project-template-v2/.claude/skills/playcraft-text-rendering/SKILL.md +0 -236
  162. package/project-template-v2/.claude/skills/playcraft-vfx-animation/SKILL.md +0 -130
  163. package/project-template-v2/.claude/skills/playwright-cli/SKILL.md +0 -390
  164. package/project-template-v2/.claude/skills/playwright-cli/references/element-attributes.md +0 -23
  165. package/project-template-v2/.claude/skills/playwright-cli/references/playwright-tests.md +0 -39
  166. package/project-template-v2/.claude/skills/playwright-cli/references/request-mocking.md +0 -87
  167. package/project-template-v2/.claude/skills/playwright-cli/references/running-code.md +0 -240
  168. package/project-template-v2/.claude/skills/playwright-cli/references/session-management.md +0 -226
  169. package/project-template-v2/.claude/skills/playwright-cli/references/spec-driven-testing.md +0 -308
  170. package/project-template-v2/.claude/skills/playwright-cli/references/storage-state.md +0 -275
  171. package/project-template-v2/.claude/skills/playwright-cli/references/test-generation.md +0 -134
  172. package/project-template-v2/.claude/skills/playwright-cli/references/tracing.md +0 -142
  173. package/project-template-v2/.claude/skills/playwright-cli/references/video-recording.md +0 -153
  174. package/project-template-v2/.claude/skills/session-analyzer/SKILL.md +0 -386
  175. package/project-template-v2/.claude/skills/session-analyzer/scripts/execution-breakdown.mjs +0 -182
  176. package/project-template-v2/.claude/skills/session-analyzer/scripts/find-turns.mjs +0 -72
  177. package/project-template-v2/.claude/skills/session-analyzer/scripts/heavy-output.mjs +0 -121
  178. package/project-template-v2/.claude/skills/session-analyzer/scripts/resolve-session.mjs +0 -102
  179. package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-stats.mjs +0 -127
  180. package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-tool-timeline.mjs +0 -106
  181. package/project-template-v2/.claude/skills/session-analyzer/scripts/time-gaps.mjs +0 -128
  182. package/project-template-v2/.claude/skills/session-analyzer/scripts/turn-timeline.mjs +0 -67
  183. package/project-template-v2/.claude/snapshot.mjs +0 -263
  184. package/project-template-v2/.playcraft/skills.lock.json +0 -152
  185. package/project-template-v2/CLAUDE.md +0 -146
  186. package/project-template-v2/assets/audio/bgm/.gitkeep +0 -0
  187. package/project-template-v2/assets/audio/sfx/.gitkeep +0 -0
  188. package/project-template-v2/assets/bundles/.gitkeep +0 -0
  189. package/project-template-v2/assets/images/bg/.gitkeep +0 -0
  190. package/project-template-v2/assets/images/reference/.gitkeep +0 -0
  191. package/project-template-v2/assets/images/storyboard/.gitkeep +0 -0
  192. package/project-template-v2/assets/images/tiles/.gitkeep +0 -0
  193. package/project-template-v2/assets/images/ui/.gitkeep +0 -0
  194. package/project-template-v2/assets/images/vfx/.gitkeep +0 -0
  195. package/project-template-v2/assets/models/.gitkeep +0 -0
  196. package/project-template-v2/docs/harness/iteration-1/context-flow.md +0 -254
  197. package/project-template-v2/docs/harness/iteration-1/generate-flow.md +0 -91
  198. package/project-template-v2/docs/harness/iteration-1/ideate-flow.md +0 -214
  199. package/project-template-v2/docs/harness/iteration-1/optimize-flow.md +0 -75
  200. package/project-template-v2/docs/harness/iteration-1/wrapup-flow.md +0 -63
  201. package/project-template-v2/docs/harness/iteration-2/context-flow.md +0 -223
  202. package/project-template-v2/docs/harness/iteration-2/generate-flow.md +0 -129
  203. package/project-template-v2/docs/harness/iteration-2/ideate-flow.md +0 -267
  204. package/project-template-v2/docs/harness/iteration-2/optimize-flow.md +0 -164
  205. package/project-template-v2/docs/harness/iteration-2/wrapup-flow.md +0 -115
  206. package/project-template-v2/docs/harness/orchestrator-flow.md +0 -364
  207. package/project-template-v2/docs/project-state.json +0 -60
  208. package/project-template-v2/docs/project-state.md +0 -72
  209. package/project-template-v2/docs/standards/README.md +0 -225
  210. package/project-template-v2/docs/standards/agent-behavior-standards.md +0 -174
  211. package/project-template-v2/docs/standards/artifacts/design-brief.md +0 -19
  212. package/project-template-v2/docs/standards/artifacts/design.md +0 -22
  213. package/project-template-v2/docs/standards/artifacts/game-code.md +0 -41
  214. package/project-template-v2/docs/standards/artifacts/todo-list.md +0 -41
  215. package/project-template-v2/docs/standards/iter1-agent-behavior-standards.md +0 -343
  216. package/project-template-v2/game/index.ts +0 -18
  217. package/project-template-v2/globals.d.ts +0 -51
  218. package/project-template-v2/index.css +0 -34
  219. package/project-template-v2/index.html +0 -18
  220. package/project-template-v2/main.ts +0 -9
  221. package/project-template-v2/package.json +0 -46
  222. package/project-template-v2/skills/_shared/scripts/dispatch-clear.mjs +0 -31
  223. package/project-template-v2/skills/_shared/scripts/dispatch-set.mjs +0 -86
  224. package/project-template-v2/skills/_shared/scripts/dod-check.mjs +0 -153
  225. package/project-template-v2/skills/_shared/scripts/handoff-append.mjs +0 -70
  226. package/project-template-v2/skills/_shared/scripts/lib/validator-artifacts.mjs +0 -91
  227. package/project-template-v2/skills/_shared/scripts/pipeline/dod-config.mjs +0 -131
  228. package/project-template-v2/skills/_shared/scripts/pipeline/index.mjs +0 -80
  229. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-1-core.mjs +0 -90
  230. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-2-wrap.mjs +0 -93
  231. package/project-template-v2/skills/_shared/scripts/pipeline/iteration-3-visual.mjs +0 -23
  232. package/project-template-v2/skills/_shared/scripts/render-project-state.mjs +0 -230
  233. package/project-template-v2/skills/_shared/scripts/state-advance-stage.mjs +0 -58
  234. package/project-template-v2/skills/_shared/scripts/state-get.mjs +0 -339
  235. package/project-template-v2/skills/_shared/scripts/state-handoff.mjs +0 -39
  236. package/project-template-v2/skills/_shared/scripts/state-set.mjs +0 -94
  237. package/project-template-v2/skills/_shared/scripts/state-store.mjs +0 -783
  238. package/project-template-v2/skills/_shared/scripts/todo-add.mjs +0 -88
  239. package/project-template-v2/skills/_shared/scripts/todo-get.mjs +0 -130
  240. package/project-template-v2/skills/_shared/scripts/todo-remove.mjs +0 -33
  241. package/project-template-v2/skills/_shared/scripts/todo-set.mjs +0 -47
  242. package/project-template-v2/skills/_shared/scripts/verify-asset-code-sync.mjs +0 -268
  243. package/project-template-v2/skills/_shared/scripts/verify-env.mjs +0 -285
  244. package/project-template-v2/skills/_shared/scripts/verify-placeholders.mjs +0 -161
  245. package/project-template-v2/skills/playable-autoplay/SKILL.md +0 -176
  246. package/project-template-v2/skills/playable-autoplay/agents/openai.yaml +0 -4
  247. package/project-template-v2/skills/playable-debug/SKILL.md +0 -116
  248. package/project-template-v2/skills/playable-debug/agents/openai.yaml +0 -4
  249. package/project-template-v2/skills/playable-debug/references/debug-config.md +0 -40
  250. package/project-template-v2/skills/playable-record/SKILL.md +0 -140
  251. package/project-template-v2/skills/playable-record/scripts/lib/dev-server.mjs +0 -104
  252. package/project-template-v2/skills/playable-record/scripts/lib/record-audio-bridge.js +0 -141
  253. package/project-template-v2/skills/playable-record/scripts/record-playable.mjs +0 -425
  254. package/project-template-v2/skills/playable-record/scripts/verify-contract.mjs +0 -261
  255. package/project-template-v2/skills/playable-record/scripts/verify-firstwin.mjs +0 -398
  256. package/project-template-v2/skills/playable-record/scripts/verify-fusion.mjs +0 -322
  257. package/project-template-v2/skills/playable-record/scripts/verify-lifecycle.mjs +0 -105
  258. package/project-template-v2/skills/playable-record/scripts/verify-vlm-video.mjs +0 -230
  259. package/project-template-v2/skills/playable-validate/SKILL.md +0 -61
  260. package/project-template-v2/skills/playable-validate/validation-rules.md +0 -14
  261. package/project-template-v2/skills/playable-verify-ui/SKILL.md +0 -63
  262. package/project-template-v2/skills/playable-verify-ui/scripts/lib/__init__.py +0 -1
  263. package/project-template-v2/skills/playable-verify-ui/scripts/lib/config_expr.js +0 -218
  264. package/project-template-v2/skills/playable-verify-ui/scripts/lib/node_utils.js +0 -51
  265. package/project-template-v2/skills/playable-verify-ui/scripts/lib/profile_loader.py +0 -59
  266. package/project-template-v2/skills/playable-verify-ui/scripts/lib/report.py +0 -106
  267. package/project-template-v2/skills/playable-verify-ui/scripts/lib/runtime_contract.js +0 -116
  268. package/project-template-v2/skills/playable-verify-ui/scripts/verify_fetch_antipatterns.py +0 -59
  269. package/project-template-v2/skills/playable-verify-ui/scripts/verify_hardcoded_layout.js +0 -64
  270. package/project-template-v2/skills/playable-verify-ui/scripts/verify_runtime_contract.js +0 -58
  271. package/project-template-v2/skills/playable-verify-ui/scripts/verify_text_overlap.py +0 -333
  272. package/project-template-v2/ta-workspace/scripts/.gitkeep +0 -0
  273. package/project-template-v2/tsconfig.json +0 -20
  274. package/project-template-v2/vite.config.ts +0 -27
  275. package/project-templates/batch-locks/phaser.yaml +0 -922
  276. package/project-templates/batch-locks/threejs.yaml +0 -978
  277. package/project-templates/empty/AGENTS.md +0 -23
  278. package/project-templates/empty/gitignore +0 -31
@@ -1,471 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { excludeFromGit } from './dependencies.js';
3
- import { lstat, readFile, realpath, stat, unlink } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import { basename, dirname, join, relative, resolve, sep } from 'node:path';
6
- import { WORKSPACE_FILE_CONTENT_MAX, gitDiffSchema, gitFileContentSchema, gitGraphSchema, gitStatusSchema, workspaceRelativePathSchema, } from '@playcraft/common/cloud-workspace/runtime';
7
- const GIT_DIFF_MAX_BYTES = 1024 * 1024;
8
- const GIT_PREFIX = [
9
- '-c',
10
- 'core.hooksPath=/dev/null',
11
- '-c',
12
- 'commit.gpgsign=false',
13
- '-c',
14
- 'safe.directory=*',
15
- ];
16
- export class GitWorkspaceError extends Error {
17
- code;
18
- constructor(code, message) {
19
- super(message);
20
- this.code = code;
21
- this.name = 'GitWorkspaceError';
22
- }
23
- }
24
- export async function probeGitBinary() {
25
- try {
26
- const result = await runGitProcess(tmpdir(), ['--version'], 4000);
27
- return result.code === 0;
28
- }
29
- catch (error) {
30
- return error instanceof GitWorkspaceError && error.code === 'git_binary_missing' ? false : false;
31
- }
32
- }
33
- export async function readWorkspaceGitStatus(root) {
34
- const rootReal = await ensureWorkspaceGit(root);
35
- const branchResult = await gitAllowFail(rootReal, ['symbolic-ref', '--short', 'HEAD']);
36
- const branch = branchResult.code === 0 ? branchResult.stdout.trim() || 'HEAD' : 'HEAD';
37
- const upstream = await gitAllowFail(rootReal, ['rev-list', '--left-right', '--count', '@{upstream}...HEAD']);
38
- let ahead = 0;
39
- let behind = 0;
40
- if (upstream.code === 0) {
41
- const [left, right] = upstream.stdout.trim().split(/\s+/);
42
- behind = Number.parseInt(left ?? '0', 10) || 0;
43
- ahead = Number.parseInt(right ?? '0', 10) || 0;
44
- }
45
- const porcelain = await git(rootReal, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
46
- // Line counts are a convenience; a repository without commits still lists its files.
47
- const [staged, unstaged] = await Promise.all([
48
- gitAllowFail(rootReal, ['diff', '--cached', '--numstat', '-z']),
49
- gitAllowFail(rootReal, ['diff', '--numstat', '-z']),
50
- ]);
51
- const stagedCounts = staged.code === 0 ? parseNumstat(staged.stdout) : new Map();
52
- const unstagedCounts = unstaged.code === 0 ? parseNumstat(unstaged.stdout) : new Map();
53
- return gitStatusSchema.parse({
54
- initialized: true,
55
- branch,
56
- ahead,
57
- behind,
58
- hasUpstream: upstream.code === 0,
59
- files: parsePorcelain(porcelain).map((entry) => ({
60
- ...entry,
61
- ...(stagedCounts.has(entry.path) ? { staged: stagedCounts.get(entry.path) } : {}),
62
- ...(unstagedCounts.has(entry.path) ? { unstaged: unstagedCounts.get(entry.path) } : {}),
63
- })),
64
- });
65
- }
66
- /**
67
- * One file as stored in the last commit or in the index. Reads the blob as is, without filters,
68
- * so the browser compares exactly what Git holds.
69
- */
70
- export async function readWorkspaceGitFile(root, path, ref) {
71
- const rootReal = await ensureWorkspaceGit(root);
72
- assertWorkspacePaths([path]);
73
- const object = ref === 'HEAD' ? `HEAD:${path}` : `:${path}`;
74
- const absent = gitFileContentSchema.parse({ path, ref, exists: false, binary: false, content: '' });
75
- const size = await gitAllowFail(rootReal, ['cat-file', '-s', object]);
76
- if (size.code !== 0)
77
- return absent;
78
- if (Number.parseInt(size.stdout.trim(), 10) > WORKSPACE_FILE_CONTENT_MAX) {
79
- throw new GitWorkspaceError('git_file_too_large', path);
80
- }
81
- const blob = await gitAllowFail(rootReal, ['cat-file', 'blob', object]);
82
- if (blob.code !== 0)
83
- return absent;
84
- // Git treats a NUL byte as the mark of binary content; so does the diff view.
85
- const binary = blob.stdout.includes('\0');
86
- return gitFileContentSchema.parse({ path, ref, exists: true, binary, content: binary ? '' : blob.stdout });
87
- }
88
- /** Adds the paths to the index, including deletions. */
89
- export async function stageWorkspaceGit(root, payload) {
90
- const rootReal = await ensureWorkspaceGit(root);
91
- assertWorkspacePaths(payload.paths);
92
- await git(rootReal, ['--literal-pathspecs', 'add', '-A', '--', ...payload.paths]);
93
- }
94
- /** Returns the paths' index entries to the last commit, leaving the work tree alone. */
95
- export async function unstageWorkspaceGit(root, payload) {
96
- const rootReal = await ensureWorkspaceGit(root);
97
- assertWorkspacePaths(payload.paths);
98
- const head = await gitAllowFail(rootReal, ['rev-parse', '--verify', '--quiet', 'HEAD']);
99
- if (head.code === 0) {
100
- await git(rootReal, ['--literal-pathspecs', 'restore', '--staged', '--', ...payload.paths]);
101
- }
102
- else {
103
- // Before the first commit there is nothing to restore from; the entries are simply removed.
104
- await git(rootReal, ['--literal-pathspecs', 'rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', ...payload.paths]);
105
- }
106
- }
107
- /**
108
- * Throws away work-tree changes: tracked files return to their staged content, untracked files are
109
- * deleted. Staged content is never touched, so a staged change survives a discard.
110
- */
111
- export async function discardWorkspaceGit(root, payload) {
112
- const rootReal = await ensureWorkspaceGit(root);
113
- assertWorkspacePaths(payload.paths);
114
- const others = await git(rootReal, ['--literal-pathspecs', 'ls-files', '--others', '--exclude-standard', '-z', '--', ...payload.paths]);
115
- const untracked = new Set(others.split('\0').filter((path) => path.length > 0));
116
- const tracked = payload.paths.filter((path) => !untracked.has(path));
117
- if (tracked.length > 0) {
118
- await git(rootReal, ['--literal-pathspecs', 'restore', '--worktree', '--', ...tracked]);
119
- }
120
- for (const path of untracked) {
121
- const target = resolve(rootReal, path);
122
- // The parent must resolve inside the workspace, so a symlinked directory cannot redirect the delete.
123
- assertInsideRoot(rootReal, join(await realpath(dirname(target)), basename(target)));
124
- if ((await lstat(target)).isDirectory())
125
- throw new GitWorkspaceError('invalid_workspace_path', path);
126
- await unlink(target);
127
- }
128
- }
129
- function assertWorkspacePaths(paths) {
130
- for (const relativePath of paths) {
131
- if (!workspaceRelativePathSchema.safeParse(relativePath).success) {
132
- throw new GitWorkspaceError('invalid_workspace_path', relativePath);
133
- }
134
- }
135
- }
136
- export async function readWorkspaceGitDiff(root) {
137
- const rootReal = await ensureWorkspaceGit(root);
138
- const vsHead = await gitAllowFail(rootReal, ['diff', '--no-color', 'HEAD']);
139
- const patch = vsHead.code === 0
140
- ? vsHead.stdout
141
- : `${(await gitAllowFail(rootReal, ['diff', '--no-color'])).stdout}${(await gitAllowFail(rootReal, ['diff', '--no-color', '--cached'])).stdout}`;
142
- if (Buffer.byteLength(patch, 'utf8') > GIT_DIFF_MAX_BYTES) {
143
- throw new GitWorkspaceError('git_diff_too_large', '1MiB');
144
- }
145
- return gitDiffSchema.parse({ patch });
146
- }
147
- export async function readWorkspaceGitGraph(root) {
148
- const rootReal = await ensureWorkspaceGit(root);
149
- const log = await gitAllowFail(rootReal, ['log', '-n', '20', '--format=%H%x09%s%x09%cI']);
150
- if (log.code !== 0)
151
- return gitGraphSchema.parse({ commits: [] });
152
- const commits = log.stdout
153
- .split('\n')
154
- .map((line) => line.trimEnd())
155
- .filter((line) => line.length > 0)
156
- .map((line) => {
157
- const [sha, subject, committedAt] = splitLogLine(line);
158
- return {
159
- sha,
160
- subject: subject.length > 0 ? subject : '(empty)',
161
- committedAt: committedAt.length > 0 ? committedAt : new Date(0).toISOString(),
162
- };
163
- });
164
- return gitGraphSchema.parse({ commits });
165
- }
166
- function splitLogLine(line) {
167
- const first = line.indexOf('\t');
168
- if (first < 0)
169
- return [line, '', ''];
170
- const second = line.indexOf('\t', first + 1);
171
- if (second < 0)
172
- return [line.slice(0, first), line.slice(first + 1), ''];
173
- return [line.slice(0, first), line.slice(first + 1, second), line.slice(second + 1)];
174
- }
175
- /**
176
- * Commit and push stay on the branch the workspace is bound to. A switch made in a shell or by an
177
- * agent is reported, never followed, so work cannot land on another Remix.
178
- */
179
- async function assertBoundBranch(rootReal, boundBranch) {
180
- if (!boundBranch)
181
- return;
182
- const current = await gitAllowFail(rootReal, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
183
- const branch = current.code === 0 ? current.stdout.trim() : '';
184
- if (branch !== boundBranch) {
185
- throw new GitWorkspaceError('workspace_branch_mismatch', branch || 'detached HEAD');
186
- }
187
- }
188
- /**
189
- * A push the remote refused for this ref is a definite outcome, unlike a lost response. Porcelain
190
- * output marks the ref with "!" and says whether the remote has commits this checkout lacks.
191
- */
192
- function pushRejection(stdout) {
193
- const line = stdout.split('\n').find((item) => item.startsWith('!\t'));
194
- if (!line)
195
- return undefined;
196
- if (/\[rejected\] \((?:non-fast-forward|fetch first)\)/.test(line))
197
- return 'git_push_remote_ahead';
198
- return 'git_push_rejected';
199
- }
200
- export async function commitWorkspaceGit(root, payload, boundBranch) {
201
- const rootReal = await ensureWorkspaceGit(root);
202
- await assertBoundBranch(rootReal, boundBranch);
203
- if (payload.stagedOnly) {
204
- // The index is the commit; nothing is added.
205
- }
206
- else if (payload.paths && payload.paths.length > 0) {
207
- assertWorkspacePaths(payload.paths);
208
- await git(rootReal, ['add', '--', ...payload.paths]);
209
- }
210
- else {
211
- await git(rootReal, ['add', '-A']);
212
- }
213
- const cached = await gitAllowFail(rootReal, ['diff', '--cached', '--quiet']);
214
- if (cached.code === 0) {
215
- throw new GitWorkspaceError('nothing_to_commit', payload.message);
216
- }
217
- await git(rootReal, ['commit', '-m', payload.message], 20000);
218
- return (await git(rootReal, ['rev-parse', 'HEAD'])).trim();
219
- }
220
- export async function pushWorkspaceGit(root, boundBranch) {
221
- const rootReal = await ensureWorkspaceGit(root);
222
- await assertBoundBranch(rootReal, boundBranch);
223
- const origin = await gitAllowFail(rootReal, ['remote', 'get-url', 'origin']);
224
- if (origin.code !== 0) {
225
- throw new GitWorkspaceError('remote_not_configured', 'origin');
226
- }
227
- const ref = (await git(rootReal, ['symbolic-ref', '--quiet', 'HEAD'])).trim();
228
- if (!ref.startsWith('refs/heads/'))
229
- throw new GitWorkspaceError('git_command_failed', 'git_branch_required');
230
- const commit = (await git(rootReal, ['rev-parse', '--verify', 'HEAD^{commit}'])).trim();
231
- let pushed;
232
- try {
233
- pushed = await gitAllowFail(rootReal, ['push', '--porcelain', 'origin', `${commit}:${ref}`], 90000);
234
- }
235
- catch { /* A lost response does not prove the remote rejected the update. */ }
236
- if (pushed?.code === 0)
237
- return;
238
- const rejected = pushed ? pushRejection(pushed.stdout) : undefined;
239
- if (rejected)
240
- throw new GitWorkspaceError(rejected, rejected);
241
- try {
242
- const remote = await gitAllowFail(rootReal, ['ls-remote', '--refs', 'origin', ref], 20000);
243
- if (remote.code === 0 && remote.stdout.trim() === `${commit}\t${ref}`)
244
- return;
245
- }
246
- catch { /* Preserve uncertainty; never replay a write automatically. */ }
247
- throw new GitWorkspaceError('git_push_outcome_unknown', 'git_push_outcome_unknown');
248
- }
249
- /**
250
- * Credential files a save never commits, even when `.gitignore` misses them: env files (their
251
- * `.example` / `.sample` / `.template` stay), SSH keys, netrc and Git credential stores, and key
252
- * or certificate bundles.
253
- */
254
- const CREDENTIAL_FILE = /^(?:\.env(?:\.(?!(?:example|sample|template)$)[^/]+)?|id_(?:rsa|dsa|ecdsa|ed25519)|\.netrc|\.git-credentials|[^/]*\.(?:pem|key|p12|pfx))$/i;
255
- export function isCredentialFile(path) {
256
- return CREDENTIAL_FILE.test(path.split('/').pop() ?? '');
257
- }
258
- /**
259
- * Commits every change in the work tree (`git add -A`, credential files aside) and, when asked,
260
- * pushes the branch. A save with nothing new commits nothing and pushes only what the remote
261
- * lacks, so a commit whose push failed goes out with the next save.
262
- */
263
- export async function saveWorkspaceGit(root, input) {
264
- const rootReal = await ensureWorkspaceGit(root);
265
- await assertBoundBranch(rootReal, input.boundBranch);
266
- await git(rootReal, ['add', '-A'], 60000);
267
- const staged = (await git(rootReal, ['diff', '--cached', '--name-only', '-z'], 60000)).split('\0').filter(Boolean);
268
- const withheld = staged.filter(isCredentialFile);
269
- await unstage(rootReal, withheld);
270
- const cached = await gitAllowFail(rootReal, ['diff', '--cached', '--quiet'], 60000);
271
- if (cached.code !== 0 && cached.code !== 1) {
272
- throw new GitWorkspaceError('git_command_failed', cached.stderr.trim() || 'git_diff_failed');
273
- }
274
- let commit;
275
- if (cached.code === 1) {
276
- await git(rootReal, [...(await commitIdentity(rootReal)), 'commit', '-q', '-m', input.message], 60000);
277
- commit = (await git(rootReal, ['rev-parse', 'HEAD'])).trim();
278
- }
279
- if (!input.push || (await remoteHasHead(rootReal)))
280
- return { ...(commit ? { commit } : {}), pushed: false, withheld };
281
- await pushWorkspaceGit(rootReal, input.boundBranch);
282
- await recordPushedHead(rootReal);
283
- return { ...(commit ? { commit } : {}), pushed: true, withheld };
284
- }
285
- async function unstage(rootReal, paths) {
286
- if (paths.length === 0)
287
- return;
288
- const born = (await gitAllowFail(rootReal, ['rev-parse', '-q', '--verify', 'HEAD'])).code === 0;
289
- for (let start = 0; start < paths.length; start += 100) {
290
- const chunk = paths.slice(start, start + 100);
291
- // Before the first commit there is no HEAD to reset to; dropping the entries does the same.
292
- await git(rootReal, born ? ['reset', '-q', '--', ...chunk] : ['rm', '-q', '--cached', '--', ...chunk]);
293
- }
294
- }
295
- /** A clone carries no committer; the sandbox image sets none either. */
296
- async function commitIdentity(rootReal) {
297
- const email = await gitAllowFail(rootReal, ['config', 'user.email']);
298
- if (email.code === 0 && email.stdout.trim())
299
- return [];
300
- return ['-c', 'user.name=PlayCraft Workspace', '-c', 'user.email=workspace@playcraft.local'];
301
- }
302
- /**
303
- * The remote-tracking ref of the current branch. A fork clone has no fetch refspec for its own
304
- * branch, so the ref is written here after a confirmed push.
305
- */
306
- async function trackingRef(rootReal) {
307
- const branch = (await gitAllowFail(rootReal, ['symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout.trim();
308
- return branch ? `refs/remotes/origin/${branch}` : undefined;
309
- }
310
- async function remoteHasHead(rootReal) {
311
- const ref = await trackingRef(rootReal);
312
- if (!ref)
313
- return false;
314
- const [head, tracked] = await Promise.all([
315
- gitAllowFail(rootReal, ['rev-parse', '-q', '--verify', 'HEAD^{commit}']),
316
- gitAllowFail(rootReal, ['rev-parse', '-q', '--verify', `${ref}^{commit}`]),
317
- ]);
318
- return head.code === 0 && tracked.code === 0 && head.stdout.trim() === tracked.stdout.trim();
319
- }
320
- async function recordPushedHead(rootReal) {
321
- const ref = await trackingRef(rootReal);
322
- if (ref)
323
- await gitAllowFail(rootReal, ['update-ref', ref, 'HEAD']);
324
- }
325
- export async function ensureWorkspaceGit(root) {
326
- const rootReal = await realpath(root);
327
- if (!(await gitMarkerExists(rootReal))) {
328
- const init = await gitAllowFail(rootReal, ['init']);
329
- if (init.code !== 0) {
330
- throw new GitWorkspaceError('git_command_failed', init.stderr.trim() || 'git_init_failed');
331
- }
332
- await git(rootReal, ['config', 'user.name', 'PlayCraft Workspace']);
333
- await git(rootReal, ['config', 'user.email', 'workspace@playcraft.local']);
334
- }
335
- await assertWorkspaceGitRoot(rootReal);
336
- await excludeFromGit(rootReal, '/.tmp/user_uploads/');
337
- return rootReal;
338
- }
339
- async function gitMarkerExists(rootReal) {
340
- try {
341
- await stat(join(rootReal, '.git'));
342
- return true;
343
- }
344
- catch (error) {
345
- if (error.code === 'ENOENT')
346
- return false;
347
- throw error;
348
- }
349
- }
350
- async function assertWorkspaceGitRoot(rootReal) {
351
- const marker = join(rootReal, '.git');
352
- const info = await stat(marker);
353
- if (info.isDirectory()) {
354
- assertInsideRoot(rootReal, await realpath(marker));
355
- return;
356
- }
357
- if (info.isFile()) {
358
- const text = await readFile(marker, 'utf8');
359
- const match = /^gitdir:\s*(.+)$/m.exec(text);
360
- if (!match)
361
- throw new GitWorkspaceError('git_root_escape', 'invalid_gitdir');
362
- const target = resolve(rootReal, match[1].trim());
363
- assertInsideRoot(rootReal, await realpath(target));
364
- return;
365
- }
366
- throw new GitWorkspaceError('git_root_escape', marker);
367
- }
368
- function assertInsideRoot(rootReal, target) {
369
- const rel = relative(rootReal, target);
370
- if (rel === '' || rel.startsWith(`..${sep}`) || rel === '..' || rel.startsWith('..')) {
371
- throw new GitWorkspaceError('git_root_escape', target);
372
- }
373
- }
374
- function parsePorcelain(raw) {
375
- const parts = raw.split('\0').filter((part) => part.length > 0);
376
- const files = [];
377
- for (let i = 0; i < parts.length; i += 1) {
378
- const entry = parts[i] ?? '';
379
- if (entry.length < 3)
380
- continue;
381
- const indexStatus = entry[0] ?? ' ';
382
- const worktreeStatus = entry[1] ?? ' ';
383
- const pathPart = entry.slice(3);
384
- if (indexStatus === 'R' || indexStatus === 'C' || worktreeStatus === 'R' || worktreeStatus === 'C') {
385
- const dest = parts[i + 1] ?? pathPart;
386
- i += 1;
387
- files.push({ path: dest, indexStatus, worktreeStatus });
388
- continue;
389
- }
390
- files.push({ path: pathPart, indexStatus, worktreeStatus });
391
- }
392
- return files;
393
- }
394
- /**
395
- * `diff --numstat -z`: `added<TAB>removed<TAB>path<NUL>`, or for a rename an empty path followed by
396
- * `old<NUL>new<NUL>`. Binary files report `-` and are left out.
397
- */
398
- function parseNumstat(raw) {
399
- const counts = new Map();
400
- const parts = raw.split('\0');
401
- for (let index = 0; index < parts.length; index += 1) {
402
- const match = /^(\d+|-)\t(\d+|-)\t(.*)$/s.exec(parts[index] ?? '');
403
- if (!match)
404
- continue;
405
- let path = match[3];
406
- if (path === '') {
407
- path = parts[index + 2] ?? '';
408
- index += 2;
409
- }
410
- if (match[1] === '-' || !path)
411
- continue;
412
- counts.set(path, { added: Number(match[1]), removed: Number(match[2]) });
413
- }
414
- return counts;
415
- }
416
- async function git(root, args, timeoutMs = 15000) {
417
- const result = await gitAllowFail(root, args, timeoutMs);
418
- if (result.code !== 0) {
419
- throw new GitWorkspaceError('git_command_failed', result.stderr.trim() || `git_exit_${result.code}`);
420
- }
421
- return result.stdout;
422
- }
423
- async function gitAllowFail(root, args, timeoutMs = 15000) {
424
- return runGitProcess(root, [...GIT_PREFIX, `--git-dir=${join(root, '.git')}`, `--work-tree=${root}`, ...args], timeoutMs);
425
- }
426
- function gitEnv() {
427
- const env = { ...process.env };
428
- delete env.GIT_DIR;
429
- delete env.GIT_WORK_TREE;
430
- delete env.GIT_COMMON_DIR;
431
- delete env.GIT_INDEX_FILE;
432
- delete env.GIT_OBJECT_DIRECTORY;
433
- delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
434
- env.GIT_OPTIONAL_LOCKS = '0';
435
- env.GIT_TERMINAL_PROMPT = '0';
436
- return env;
437
- }
438
- function runGitProcess(cwd, args, timeoutMs) {
439
- return new Promise((resolve, reject) => {
440
- const child = spawn('git', args, { cwd, env: gitEnv(), windowsHide: true });
441
- // Chunks are decoded together; a character split across two chunks would otherwise be corrupted.
442
- const stdout = [];
443
- const stderr = [];
444
- const timer = setTimeout(() => {
445
- child.kill('SIGKILL');
446
- reject(new GitWorkspaceError('git_command_failed', 'timeout'));
447
- }, timeoutMs);
448
- child.stdout.on('data', (chunk) => {
449
- stdout.push(Buffer.from(chunk));
450
- });
451
- child.stderr.on('data', (chunk) => {
452
- stderr.push(Buffer.from(chunk));
453
- });
454
- child.on('error', (error) => {
455
- clearTimeout(timer);
456
- if (error.code === 'ENOENT') {
457
- reject(new GitWorkspaceError('git_binary_missing', 'git'));
458
- return;
459
- }
460
- reject(error);
461
- });
462
- child.on('close', (code) => {
463
- clearTimeout(timer);
464
- resolve({
465
- stdout: Buffer.concat(stdout).toString('utf8'),
466
- stderr: Buffer.concat(stderr).toString('utf8'),
467
- code: code ?? 1,
468
- });
469
- });
470
- });
471
- }
@@ -1,170 +0,0 @@
1
- import JSON5 from 'json5';
2
- export class ParameterEditError extends Error {
3
- code;
4
- constructor(code) {
5
- super(code);
6
- this.code = code;
7
- this.name = 'ParameterEditError';
8
- }
9
- }
10
- export function replaceJson5Path(source, fieldPath, value) {
11
- const span = findJson5ValueSpan(source, fieldPath);
12
- if (!span)
13
- throw new ParameterEditError('parameter_field_missing');
14
- const current = skipTrivia(source, span.start, span.end);
15
- if (source[current] === '{' || source[current] === '[') {
16
- throw new ParameterEditError('parameter_value_invalid');
17
- }
18
- return `${source.slice(0, span.start)}${formatJson5Value(value, source.slice(span.start, span.end))}${source.slice(span.end)}`;
19
- }
20
- export function findJson5ValueSpan(source, fieldPath) {
21
- const start = skipTrivia(source, 0, source.length);
22
- if (source[start] !== '{')
23
- throw new ParameterEditError('parameter_document_invalid');
24
- return findInObject(source, start, source.length, fieldPath, 0);
25
- }
26
- function findInObject(source, braceIndex, end, fieldPath, depth) {
27
- let index = skipTrivia(source, braceIndex + 1, end);
28
- while (index < end) {
29
- if (source[index] === '}')
30
- return undefined;
31
- const key = parseKey(source, index, end);
32
- index = skipTrivia(source, key.end, end);
33
- if (source[index] !== ':')
34
- throw new ParameterEditError('parameter_document_invalid');
35
- const value = scanValue(source, index + 1, end);
36
- if (key.name === fieldPath[depth]) {
37
- if (depth === fieldPath.length - 1)
38
- return value;
39
- const nested = skipTrivia(source, value.start, end);
40
- if (source[nested] !== '{')
41
- throw new ParameterEditError('parameter_field_missing');
42
- return findInObject(source, nested, value.end, fieldPath, depth + 1);
43
- }
44
- index = skipTrivia(source, value.end, end);
45
- if (source[index] === ',')
46
- index = skipTrivia(source, index + 1, end);
47
- }
48
- throw new ParameterEditError('parameter_document_invalid');
49
- }
50
- function parseKey(source, start, end) {
51
- const index = skipTrivia(source, start, end);
52
- const first = source[index];
53
- if (first === '"' || first === "'") {
54
- const close = stringEnd(source, index, end);
55
- return { name: JSON5.parse(source.slice(index, close)), end: close };
56
- }
57
- if (!/[A-Za-z_$]/.test(first ?? ''))
58
- throw new ParameterEditError('parameter_document_invalid');
59
- let cursor = index + 1;
60
- while (cursor < end && /[A-Za-z0-9_$]/.test(source[cursor]))
61
- cursor += 1;
62
- return { name: source.slice(index, cursor), end: cursor };
63
- }
64
- function scanValue(source, from, end) {
65
- const start = skipTrivia(source, from, end);
66
- const first = source[start];
67
- if (first === '"' || first === "'")
68
- return { start, end: stringEnd(source, start, end) };
69
- if (first === '{' || first === '[')
70
- return { start, end: balancedEnd(source, start, end) };
71
- let cursor = start;
72
- while (cursor < end) {
73
- const current = source[cursor];
74
- if (/\s/.test(current) || current === ',' || current === '}' || current === ']' || current === '/')
75
- break;
76
- cursor += 1;
77
- }
78
- if (cursor === start)
79
- throw new ParameterEditError('parameter_document_invalid');
80
- return { start, end: cursor };
81
- }
82
- function balancedEnd(source, start, end) {
83
- const open = source[start];
84
- const close = open === '{' ? '}' : ']';
85
- let depth = 0;
86
- let index = start;
87
- while (index < end) {
88
- const current = source[index];
89
- if (current === '"' || current === "'") {
90
- index = stringEnd(source, index, end);
91
- continue;
92
- }
93
- if (current === '/' && source[index + 1] === '/') {
94
- index = skipTrivia(source, index, end);
95
- continue;
96
- }
97
- if (current === '/' && source[index + 1] === '*') {
98
- index = skipTrivia(source, index, end);
99
- continue;
100
- }
101
- if (current === open)
102
- depth += 1;
103
- else if (current === close) {
104
- depth -= 1;
105
- if (depth === 0)
106
- return index + 1;
107
- }
108
- index += 1;
109
- }
110
- throw new ParameterEditError('parameter_document_invalid');
111
- }
112
- function stringEnd(source, start, end) {
113
- const quote = source[start];
114
- let index = start + 1;
115
- while (index < end) {
116
- const current = source[index];
117
- if (current === '\\') {
118
- index += 2;
119
- continue;
120
- }
121
- if (current === quote)
122
- return index + 1;
123
- index += 1;
124
- }
125
- throw new ParameterEditError('parameter_document_invalid');
126
- }
127
- function skipTrivia(source, start, end) {
128
- let index = start;
129
- while (index < end) {
130
- const current = source[index];
131
- if (/\s/.test(current)) {
132
- index += 1;
133
- continue;
134
- }
135
- if (current === '/' && source[index + 1] === '/') {
136
- index += 2;
137
- while (index < end && source[index] !== '\n')
138
- index += 1;
139
- continue;
140
- }
141
- if (current === '/' && source[index + 1] === '*') {
142
- const close = source.indexOf('*/', index + 2);
143
- if (close < 0 || close >= end)
144
- throw new ParameterEditError('parameter_document_invalid');
145
- index = close + 2;
146
- continue;
147
- }
148
- break;
149
- }
150
- return index;
151
- }
152
- function formatJson5Value(value, previous) {
153
- if (typeof value === 'string') {
154
- const trimmed = previous.trim();
155
- if (trimmed.startsWith("'")) {
156
- return `'${value.replaceAll('\\', '\\\\').replaceAll("'", "\\'")}'`;
157
- }
158
- return JSON.stringify(value);
159
- }
160
- if (typeof value === 'boolean' || value === null)
161
- return String(value);
162
- const trimmed = previous.trim();
163
- if (/^[-+]?0x[0-9a-fA-F]+$/.test(trimmed) && Number.isInteger(value)) {
164
- const sign = value < 0 ? '-' : trimmed.startsWith('+') ? '+' : '';
165
- const hex = Math.abs(value).toString(16);
166
- const upper = /[A-F]/.test(trimmed) && !/[a-f]/.test(trimmed);
167
- return `${sign}0x${upper ? hex.toUpperCase() : hex}`;
168
- }
169
- return Number.isInteger(value) ? String(value) : JSON.stringify(value);
170
- }