oda-engine 0.0.0-stage → 0.1.1

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +131 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,1018 @@
1
+ const crypto = require('node:crypto')
2
+ const fs = require('node:fs')
3
+ const fsp = require('node:fs/promises')
4
+ const http = require('node:http')
5
+ const https = require('node:https')
6
+ const path = require('node:path')
7
+ const auth = require('./auth.cjs')
8
+ const git = require('./git.cjs')
9
+ const { buildGame } = require('./build.cjs')
10
+
11
+ // Publishing a project as a planet, from the main process. The sequence is
12
+ // SPEC_PUBLISH.md 4.2: session, config, build, gates, budgets, assets, commit,
13
+ // then one multipart POST to the `publish` Edge Function, which runs the same
14
+ // checks again with the verdict that counts (nowhere_engine never writes to
15
+ // Storage itself). On 200 the planet's id and version land in
16
+ // .nowhere/published.json, which is what lights the launcher's lamp.
17
+ //
18
+ // The checks are the shared pre-flight (@nowhere/schema preparePublish): the
19
+ // documents, which files travel (admitUploads) and checkPublish on the
20
+ // request about to go up, which is the function's own check, so `nowhere
21
+ // check` and this button cannot say different things about one project.
22
+ // Before any of it leaves the machine the server and the site's player are
23
+ // asked what they can do (publish contract 3, schema contract.ts): a planet
24
+ // that needs more than either offers stops here, with a sentence, before a
25
+ // byte is uploaded, rather than after the upload as "nowhere refused the
26
+ // request." A side that does not answer is not a refusal; the publish goes
27
+ // on as it did before there was a handshake.
28
+ //
29
+ // Every step reports a state through `onProgress`, and the whole thing answers
30
+ // with the final one; the renderer shows the same object either way. Nothing
31
+ // here throws to the caller: a failure is a state with a sentence.
32
+ //
33
+ // The endpoints are constants so scripts/publish-check.mjs can point them at
34
+ // a local mock through configure().
35
+
36
+ const SUPABASE_FUNCTIONS = 'https://pnbhqecnuyqammdpooec.supabase.co/functions/v1'
37
+ // The region the publish function is asked to run in (Supabase's x-region
38
+ // header): the project's own, where Storage is. Left to itself the function
39
+ // starts at the edge nearest the creator and then sends every file across the
40
+ // ocean a second time, inside its own wall clock.
41
+ const FUNCTION_REGION = 'ap-southeast-2'
42
+ /** Where a published planet lives. Also the one URL the Publish popover may
43
+ * hand to the system browser (main.cjs shell:open-external). */
44
+ const PLANET_URL = 'https://nowhere-psi.vercel.app/'
45
+ // What the site's player plays (PlayerInfo), published beside the player.
46
+ const PLAYER_INFO = 'play/capabilities.json'
47
+ // How long the server and the player get to say what they can do, and a dry
48
+ // run to answer. Neither is the publish: no answer means "not asked".
49
+ const INFO_TIMEOUT_MS = 10 * 1000
50
+ const DRY_RUN_TIMEOUT_MS = 30 * 1000
51
+ // Where project.cjs reads the publish record back for the launcher's lamp
52
+ // (`url` is the field it looks at). Written here, never by the renderer.
53
+ const PUBLISHED_FILE = path.join('.nowhere', 'published.json')
54
+ const PREVIEW_FILE = path.join('.nowhere', 'preview.png')
55
+ // The launcher's card (project.cjs): the tile on nothing. The planet's
56
+ // picture falls back on it only when there is no usable preview.png.
57
+ const CARD_FILE = path.join('.nowhere', 'card.png')
58
+ // The planet's splat, written by the viewport's bake (project:save-splat) the
59
+ // moment before a publish starts.
60
+ const SPLAT_PATH = path.join('.nowhere', 'splat.bin')
61
+ const CONFIG_FILE = 'game.config.json'
62
+ const SCENE_FILE = 'scene.json'
63
+ const ASSET_DIR = 'assets'
64
+ // The asset ledger (schema assets.ts): with it, a planet also carries the
65
+ // files its code loads (textures, HDRIs, sounds, LUTs, models it places in
66
+ // code), each recorded with its licence. Without it, what the scene places
67
+ // and the files the config names (an HDRI sky, a LUT).
68
+ const LEDGER_FILE = 'assets.lock.json'
69
+ // A planet may carry 100 MB of models, all in the one request: on a slow
70
+ // uplink that is minutes, not seconds. The server gives up at its own limit.
71
+ const REQUEST_TIMEOUT_MS = 10 * 60 * 1000
72
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
73
+
74
+ /** States, in the order a publish passes through them. `signin` is the stop
75
+ * before any of it: there is no account to publish as. */
76
+ const STATES = ['idle', 'signin', 'checking', 'committing', 'uploading', 'verifying', 'done', 'failed']
77
+
78
+ // What the module needs from the rest of the studio, swappable for the check
79
+ // script and the CLI: the endpoints (a local mock), the token (a fake one),
80
+ // what this side calls itself in the sentences that say the other side is
81
+ // older ("this studio"; the CLI is "this nowhere CLI"), and how long the
82
+ // other side gets to answer (a check script's mock that never answers should
83
+ // not take ten seconds to say so).
84
+ let deps = {
85
+ endpointBase: SUPABASE_FUNCTIONS,
86
+ siteBase: PLANET_URL,
87
+ getAccessToken: () => auth.getAccessToken(),
88
+ clientName: 'this studio',
89
+ infoTimeoutMs: INFO_TIMEOUT_MS,
90
+ dryRunTimeoutMs: DRY_RUN_TIMEOUT_MS,
91
+ }
92
+
93
+ /** Test seam: { endpointBase?, siteBase?, getAccessToken?, clientName?,
94
+ * infoTimeoutMs?, dryRunTimeoutMs? }. */
95
+ function configure(overrides) {
96
+ deps = { ...deps, ...overrides }
97
+ }
98
+
99
+ // The gates come from @nowhere/schema's built dist, the same code the Edge
100
+ // Function runs as _verifier.js. Loaded once, lazily: the package is ESM and
101
+ // this file is not, and the dist may be missing in a dev checkout that never
102
+ // ran `npm run build:schema`, which should fail the publish, not the studio.
103
+ // `loaded` keeps it for sentenceFor, which answers at once.
104
+ let schemaPromise = null
105
+ let loaded = null
106
+ function schema() {
107
+ if (!schemaPromise) {
108
+ schemaPromise = import(require('node:url').pathToFileURL(require('node:path').join(__dirname, 'schema', 'dist', 'index.js')).href)
109
+ .then((module) => (loaded = module))
110
+ .catch((err) => {
111
+ schemaPromise = null
112
+ throw new Error(`the schema package is not built (${err.code ?? err.message}); run: npm run build:schema`)
113
+ })
114
+ }
115
+ return schemaPromise
116
+ }
117
+
118
+ // ---------------------------------------------------------------- sentences
119
+
120
+ // The server's error codes, as the sentences the popover shows. Findings
121
+ // (schema, contract:*) are appended by the caller as they are.
122
+ const SERVER_SENTENCES = {
123
+ not_signed_in: 'Your Oda session has expired. Sign in again in Settings.',
124
+ bad_request: 'Oda refused the request.',
125
+ budget_exceeded: 'The planet is over budget.',
126
+ schema: 'game.config.json does not satisfy the schema.',
127
+ quota_exceeded: 'You already have 10 planets. Take one down to publish another.',
128
+ rate_limited: 'Planets can be published once a minute. Try again in a minute.',
129
+ daily_limit: 'That is 30 publishes in one day. Try again tomorrow.',
130
+ unchanged: 'Nothing has changed since the last publish.',
131
+ removed: 'This planet was taken down and cannot be published again.',
132
+ storage_failed: 'The files could not be stored. Publish again to retry.',
133
+ ledger: 'The asset ledger refused a file.',
134
+ rpc_failed: 'Oda could not record the planet.',
135
+ internal: 'Oda hit an internal error.',
136
+ contract_mismatch: 'The Oda server cannot take this planet yet. Nothing was published.',
137
+ unknown_fields: 'The Oda server does not know every setting this planet has, and would publish it without them. Nothing was published.',
138
+ id_mismatch: 'Another publish of this planet was recorded at the same moment. Publish again.',
139
+ id_collision: 'The id this planet was to get was taken at the same moment. Publish again.',
140
+ }
141
+
142
+ const strings = (value) => (Array.isArray(value) ? value.filter((v) => typeof v === 'string' && v) : [])
143
+
144
+ function listed(items) {
145
+ return items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`
146
+ }
147
+
148
+ /** One sentence for a server reply: `{ error, detail?, findings? }`. */
149
+ function sentenceFor(status, body) {
150
+ const code = typeof body?.error === 'string' ? body.error : ''
151
+ if (code.startsWith('contract:')) return 'The bundle does not meet the planet contract.'
152
+ // The two refusals of a server older than this side: what it lacks, in the
153
+ // schema's words when the schema is loaded (it is, after any run).
154
+ if (code === 'contract_mismatch') {
155
+ const missing = strings(body.missing)
156
+ if (missing.length > 0 && loaded) return `${loaded.olderSentence('server', missing, { than: deps.clientName, nothingUploaded: false })} Nothing was published.`
157
+ return SERVER_SENTENCES.contract_mismatch
158
+ }
159
+ if (code === 'unknown_fields') {
160
+ const fields = strings(body.fields)
161
+ if (fields.length > 0) {
162
+ return `The Oda server is older than ${deps.clientName}: it does not know ${listed(fields)} yet, and would publish this planet without ${fields.length === 1 ? 'it' : 'them'}. Nothing was published.`
163
+ }
164
+ return SERVER_SENTENCES.unknown_fields
165
+ }
166
+ const known = SERVER_SENTENCES[code]
167
+ if (known) {
168
+ return typeof body.detail === 'string' && body.detail ? `${known} (${body.detail})` : known
169
+ }
170
+ return `Oda answered ${status}${code ? ` (${code})` : ''}.`
171
+ }
172
+
173
+ function findingLines(findings) {
174
+ if (!Array.isArray(findings)) return []
175
+ return findings
176
+ .filter((f) => f && typeof f === 'object')
177
+ .map((f) => ({
178
+ path: typeof f.path === 'string' ? f.path : undefined,
179
+ code: String(f.code ?? ''),
180
+ message: String(f.message ?? ''),
181
+ }))
182
+ }
183
+
184
+ /** The sentence a pre-flight's problems lead with (PublishFinding, schema
185
+ * contract.ts); the popover lists every one of them under it. */
186
+ function leadSentence(findings) {
187
+ const first = findings[0]
188
+ const error = String(first.error ?? '')
189
+ if (error === 'schema') {
190
+ if (first.path?.startsWith(LEDGER_FILE)) return first.message
191
+ return first.path?.startsWith(SCENE_FILE) ? 'scene.json does not satisfy the schema.' : 'game.config.json does not satisfy the schema.'
192
+ }
193
+ if (error.startsWith('contract:')) return 'The bundle does not meet the planet contract.'
194
+ const ledger = findings.filter((f) => f.error === 'ledger')
195
+ if (error === 'ledger' && ledger.length > 1) return `${ledger.length} files cannot be published as they are recorded in ${LEDGER_FILE}.`
196
+ return findings.length === 1 ? first.message : `${first.message} (and ${findings.length - 1} more)`
197
+ }
198
+
199
+ /** What a creator reads when the server or the player is older than this
200
+ * side (missing: { server, player, sdk }, from preparePublish: what each
201
+ * lacks of the planet's needs, and the names the code reads that the
202
+ * player's SDK does not export). Called once the schema is loaded. */
203
+ function olderSentences(missing, { nothingUploaded = true } = {}) {
204
+ const parts = []
205
+ const than = { than: deps.clientName, nothingUploaded: false }
206
+ if (missing.server?.length > 0) parts.push(loaded.olderSentence('server', missing.server, than))
207
+ if (missing.player?.length > 0) parts.push(loaded.olderSentence('player', missing.player, than))
208
+ if (missing.sdk?.length > 0) parts.push(loaded.olderSdkSentence(missing.sdk, than))
209
+ return nothingUploaded ? `${parts.join(' ')} Nothing was uploaded.` : parts.join(' ')
210
+ }
211
+
212
+ /** What to do about KTX2 or meshopt files a side does not take: import them
213
+ * again, which now writes them plain for it (agent/assets/targets.mjs). */
214
+ function decoderHint(missing) {
215
+ const lacking = ['meshopt', 'ktx2'].filter((c) => missing?.server?.includes(c) || missing?.player?.includes(c))
216
+ if (lacking.length === 0) return ''
217
+ return ` Import those ${lacking.length === 2 ? 'models and textures' : lacking[0] === 'ktx2' ? 'textures' : 'models'} again with asset_import (replace: true): it now writes ${lacking.length === 2 ? 'PNG or JPEG textures and plain geometry' : lacking[0] === 'ktx2' ? 'PNG or JPEG textures' : 'plain geometry'} for these sides.`
218
+ }
219
+
220
+ /** Whether a pre-flight found the other side older than the planet. */
221
+ const olderThanPlanet = (missing) => ['server', 'player', 'sdk'].some((side) => missing?.[side]?.length > 0)
222
+
223
+ /** "10 s", or "400 ms" for a deadline under a second. */
224
+ const inWords = (ms) => (ms >= 1000 ? `${Math.round(ms / 1000)} s` : `${ms} ms`)
225
+
226
+ // ---------------------------------------------------------------- what the other side can do
227
+
228
+ /** One GET for a small JSON document, with a deadline: { status, body }, the
229
+ * body null when it is not JSON, and status 0 (with `error`) when nothing
230
+ * answered. Cancelling the publish aborts it. */
231
+ async function getJson(url, { headers = {}, signal, timeoutMs = deps.infoTimeoutMs } = {}) {
232
+ const controller = new AbortController()
233
+ const timer = setTimeout(() => controller.abort(new Error(`no answer in ${inWords(timeoutMs)}`)), timeoutMs)
234
+ const forward = () => controller.abort(signal.reason)
235
+ signal?.addEventListener('abort', forward, { once: true })
236
+ try {
237
+ const res = await fetch(url, { headers, signal: controller.signal })
238
+ const text = await res.text()
239
+ let body = null
240
+ try {
241
+ body = JSON.parse(text)
242
+ } catch {
243
+ // a page instead of a document: read by its status alone
244
+ }
245
+ return { status: res.status, body }
246
+ } catch (err) {
247
+ const why = controller.signal.aborted ? controller.signal.reason : err
248
+ return { status: 0, body: null, error: why?.cause?.message ?? why?.message ?? String(why) }
249
+ } finally {
250
+ clearTimeout(timer)
251
+ signal?.removeEventListener('abort', forward)
252
+ }
253
+ }
254
+
255
+ /**
256
+ * What the live server and the site's player say they can do, asked at once:
257
+ * { server, player }, each an InfoReading (schema contract.ts): 'current'
258
+ * with its info, 'legacy' for a side from before contract 3 (it answered,
259
+ * without info), or 'unknown' with the reason nothing came back. The server
260
+ * is asked with the creator's session, or the public key when there is none:
261
+ * the gateway wants a JWT, and the answer is the same for anyone.
262
+ */
263
+ async function readSides({ token = null, signal } = {}) {
264
+ const s = await schema()
265
+ const urls = infoUrls()
266
+ const [server, player] = await Promise.all([
267
+ getJson(urls.server, { headers: { authorization: `Bearer ${token ?? auth.SUPABASE_ANON_KEY}` }, signal }),
268
+ getJson(urls.player, { signal }),
269
+ ])
270
+ return {
271
+ server: server.status === 0 ? { state: 'unknown', reason: server.error } : s.readPublishInfoReply(server.status, server.body),
272
+ player: player.status === 0 ? { state: 'unknown', reason: player.error } : s.readPlayerInfoReply(player.status, player.body),
273
+ }
274
+ }
275
+
276
+ /** Where readSides asks: the publish function and the player's capabilities. */
277
+ function infoUrls() {
278
+ return { server: `${deps.endpointBase}/publish`, player: new URL(PLAYER_INFO, deps.siteBase).href }
279
+ }
280
+
281
+ /** What a side offers, for preparePublish: its capabilities, or undefined
282
+ * when it was not reached (then it is not compared). */
283
+ const offered = (reading) => (reading && reading.state !== 'unknown' ? reading.capabilities : undefined)
284
+
285
+ /** What the player's @nowhere/sdk exports, for preparePublish (schema
286
+ * playerSdkOf): its list, the one from before contract 3 for a legacy site,
287
+ * or null when that is not known. */
288
+ const sdkExportsOf = (reading) => (loaded ? loaded.playerSdkOf(reading) : null)
289
+
290
+ /**
291
+ * Asks the server whether it would take a planet, without sending it: the
292
+ * documents as a publish would send them, and the files as descriptors
293
+ * (path, bytes, sha256) in a 'files' field instead of their bytes. Nothing is
294
+ * written anywhere, on either side.
295
+ *
296
+ * `prepared` is preflight()'s; `bundle` the code as it ships. Answers
297
+ * { state: 'answered', status, answer } with the server's DryRunAnswer,
298
+ * { state: 'refused', status, error, findings } when it refused the question
299
+ * itself, or { state: 'unknown', reason } when nothing usable came back.
300
+ */
301
+ async function dryRun(prepared, { bundle, token = null, repoKey = null, sha = null, signal } = {}) {
302
+ const s = await schema()
303
+ const form = new FormData()
304
+ form.set('action', 'dry-run')
305
+ form.set('contract', String(s.PUBLISH_CONTRACT))
306
+ form.set('needs', JSON.stringify(prepared.needs))
307
+ form.set('requires', JSON.stringify(prepared.requires))
308
+ if (repoKey) form.set('repoKey', repoKey)
309
+ if (sha) form.set('sha', sha)
310
+ form.set('main.js', new Blob([bundle], { type: 'text/javascript' }), 'main.js')
311
+ form.set(CONFIG_FILE, new Blob([prepared.configText], { type: 'application/json' }), CONFIG_FILE)
312
+ if (prepared.sceneText) form.set(SCENE_FILE, new Blob([prepared.sceneText], { type: 'application/json' }), SCENE_FILE)
313
+ if (prepared.ledgerText) form.set(LEDGER_FILE, new Blob([prepared.ledgerText], { type: 'application/json' }), LEDGER_FILE)
314
+ // A model's descriptor says what it requires (contract 4), which the dry
315
+ // run cannot read from bytes it is not sent; an older server drops it.
316
+ form.set('files', JSON.stringify(prepared.uploads.map((u) => ({ path: u.path, bytes: u.bytes, ...(u.sha256 ? { sha256: u.sha256 } : {}), ...(u.extensionsRequired ? { extensionsRequired: u.extensionsRequired } : {}) }))))
317
+
318
+ const controller = new AbortController()
319
+ const timer = setTimeout(() => controller.abort(new Error(`no answer in ${inWords(deps.dryRunTimeoutMs)}`)), deps.dryRunTimeoutMs)
320
+ const forward = () => controller.abort(signal.reason)
321
+ signal?.addEventListener('abort', forward, { once: true })
322
+ let status = 0
323
+ let body = null
324
+ try {
325
+ const res = await fetch(`${deps.endpointBase}/publish`, {
326
+ method: 'POST',
327
+ headers: { authorization: `Bearer ${token ?? auth.SUPABASE_ANON_KEY}` },
328
+ body: form,
329
+ signal: controller.signal,
330
+ })
331
+ status = res.status
332
+ try {
333
+ body = JSON.parse(await res.text())
334
+ } catch {
335
+ // read by its status alone
336
+ }
337
+ } catch (err) {
338
+ const why = controller.signal.aborted ? controller.signal.reason : err
339
+ return { state: 'unknown', reason: why?.cause?.message ?? why?.message ?? String(why) }
340
+ } finally {
341
+ clearTimeout(timer)
342
+ signal?.removeEventListener('abort', forward)
343
+ }
344
+ const answer = s.parseDryRunAnswer(body)
345
+ if (answer) return { state: 'answered', status, answer }
346
+ // A server from before the dry run: it wants an account, or does not know
347
+ // the action. Neither is a verdict on the planet.
348
+ if (status === 401) return { state: 'unknown', reason: 'the server asked for a signed-in account, so it does not do dry runs' }
349
+ if (status === 400 && typeof body?.detail === 'string' && /unknown action/.test(body.detail)) {
350
+ return { state: 'unknown', reason: 'the server does not know the dry run' }
351
+ }
352
+ if (status >= 400 && status < 500 && typeof body?.error === 'string') {
353
+ return { state: 'refused', status, error: sentenceFor(status, body), findings: findingLines(body.findings) }
354
+ }
355
+ return { state: 'unknown', reason: status ? `the server answered ${status}` : 'no answer' }
356
+ }
357
+
358
+ // ---------------------------------------------------------------- pieces
359
+
360
+ /** Every file under assets/, as project-relative paths. Dotfiles (.DS_Store)
361
+ * are not models. What this finds and the publish does not take is what it
362
+ * leaves behind, so the list is the warning's source. */
363
+ async function listAssets(root) {
364
+ const found = []
365
+ const walk = async (dir, prefix) => {
366
+ let entries
367
+ try {
368
+ entries = await fsp.readdir(dir, { withFileTypes: true })
369
+ } catch (err) {
370
+ if (err.code === 'ENOENT') return
371
+ throw err
372
+ }
373
+ for (const entry of entries) {
374
+ if (entry.name.startsWith('.')) continue
375
+ const rel = `${prefix}/${entry.name}`
376
+ if (entry.isDirectory()) await walk(path.join(dir, entry.name), rel)
377
+ else found.push(rel)
378
+ }
379
+ }
380
+ await walk(path.join(root, ASSET_DIR), ASSET_DIR)
381
+ return found.sort()
382
+ }
383
+
384
+ // What the sides said, kept for asset_import (agent/assets/targets.mjs):
385
+ // whether it writes KTX2 and meshopt depends on it.
386
+ let targetsPromise = null
387
+ function targetsModule() {
388
+ targetsPromise ??= import('./agent/assets/targets.mjs').catch((err) => {
389
+ targetsPromise = null
390
+ throw err
391
+ })
392
+ return targetsPromise
393
+ }
394
+
395
+ // A GLB's header: magic, version, length, then the first chunk's length and
396
+ // type, which a valid one has as its JSON. Only that far is read of a model
397
+ // to know what it requires.
398
+ const GLB_HEADER = 20
399
+ const GLB_MAGIC = 0x46546c67
400
+ const GLB_JSON = 0x4e4f534a
401
+
402
+ /** The glTF extensions a model in the project requires (schema
403
+ * gltfExtensionsRequired), read from its header and JSON chunk alone, or
404
+ * null for a model that is not glTF or cannot be read. */
405
+ async function modelRequires(abs, s) {
406
+ const lower = abs.toLowerCase()
407
+ if (!lower.endsWith('.glb') && !lower.endsWith('.gltf')) return null
408
+ let handle
409
+ try {
410
+ if (lower.endsWith('.gltf')) return s.gltfExtensionsRequired(await fsp.readFile(abs))
411
+ handle = await fsp.open(abs, 'r')
412
+ const head = Buffer.alloc(GLB_HEADER)
413
+ const { bytesRead } = await handle.read(head, 0, GLB_HEADER, 0)
414
+ if (bytesRead < GLB_HEADER || head.readUInt32LE(0) !== GLB_MAGIC || head.readUInt32LE(16) !== GLB_JSON) return null
415
+ const length = head.readUInt32LE(12)
416
+ if (length > s.ASSET_KINDS.model.fileMb * 1024 * 1024) return null
417
+ const whole = Buffer.alloc(GLB_HEADER + length)
418
+ head.copy(whole)
419
+ await handle.read(whole, GLB_HEADER, length, GLB_HEADER)
420
+ return s.gltfExtensionsRequired(whole)
421
+ } catch {
422
+ return null
423
+ } finally {
424
+ await handle?.close()
425
+ }
426
+ }
427
+
428
+ // The asset ledger's writer (agent/assets/ledger.mjs), loaded when a publish
429
+ // has to start the ledger or measure the creator's files again.
430
+ let ledgerPromise = null
431
+ function ledgerModule() {
432
+ ledgerPromise ??= import('./agent/assets/ledger.mjs').catch((err) => {
433
+ ledgerPromise = null
434
+ throw err
435
+ })
436
+ return ledgerPromise
437
+ }
438
+
439
+ /** A project document as JSON: `{ raw }`, `{ absent: true }` when there is
440
+ * no such file, or `{ error }` with the sentence for one that cannot be
441
+ * read. Validating it is the pre-flight's business. */
442
+ async function readDocument(root, name) {
443
+ let text
444
+ try {
445
+ text = await fsp.readFile(path.join(root, name), 'utf8')
446
+ } catch (err) {
447
+ if (err.code === 'ENOENT') return { absent: true }
448
+ return { error: `${name} could not be read (${err.message}).` }
449
+ }
450
+ try {
451
+ return { raw: JSON.parse(text) }
452
+ } catch (err) {
453
+ return { error: `${name} is not valid JSON (${err.message}).` }
454
+ }
455
+ }
456
+
457
+ /** The planet's picture (preview.png: the world under its own sky, taken by
458
+ * the viewport as the publish starts), if it is a PNG within budget; failing
459
+ * that the launcher's card, so a project that has only ever had a card still
460
+ * goes up with a picture. Anything else is left out rather than failing the
461
+ * publish: the preview is optional. */
462
+ async function readPreview(root, limitKb) {
463
+ for (const file of [PREVIEW_FILE, CARD_FILE]) {
464
+ const name = path.basename(file)
465
+ let bytes
466
+ try {
467
+ bytes = await fsp.readFile(path.join(root, file))
468
+ } catch {
469
+ continue
470
+ }
471
+ if (bytes.length > limitKb * 1024) {
472
+ console.warn(`[publish] ${name} is ${kb(bytes.length)} KB, over ${limitKb} KB; leaving it out`)
473
+ continue
474
+ }
475
+ if (bytes.length < PNG_MAGIC.length || !bytes.subarray(0, PNG_MAGIC.length).equals(PNG_MAGIC)) {
476
+ console.warn(`[publish] ${name} is not a PNG; leaving it out`)
477
+ continue
478
+ }
479
+ return bytes
480
+ }
481
+ return null
482
+ }
483
+
484
+ /** Stores the splat for the next publish, or removes the old one. */
485
+ async function writeSplat(root, bytes) {
486
+ const file = path.join(root, SPLAT_PATH)
487
+ if (!bytes) {
488
+ await fsp.rm(file, { force: true })
489
+ return
490
+ }
491
+ await fsp.mkdir(path.dirname(file), { recursive: true })
492
+ await fsp.writeFile(file, Buffer.from(bytes))
493
+ }
494
+
495
+ /** The baked splat, if it is one and within budget. Optional like the still:
496
+ * a planet without it shows its still inside the glass. */
497
+ async function readSplat(root, check) {
498
+ let bytes
499
+ try {
500
+ bytes = await fsp.readFile(path.join(root, SPLAT_PATH))
501
+ } catch {
502
+ return null
503
+ }
504
+ const verdict = check(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength))
505
+ if (!verdict.ok) {
506
+ console.warn(`[publish] splat.bin is ${verdict.error}; publishing without it`)
507
+ return null
508
+ }
509
+ return bytes
510
+ }
511
+
512
+ function kb(bytes) {
513
+ return Math.max(1, Math.ceil(bytes / 1024))
514
+ }
515
+
516
+ async function sha256Of(file) {
517
+ const hash = crypto.createHash('sha256')
518
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk)
519
+ return hash.digest('hex')
520
+ }
521
+
522
+ /** assets.lock.json, validated: `{ lock: null }` when there is none (the
523
+ * project publishes as it did before the ledger), `{ lock }`, or
524
+ * `{ error }` for one that cannot be trusted. */
525
+ async function readLedger(root, AssetLock) {
526
+ let text
527
+ try {
528
+ text = await fsp.readFile(path.join(root, LEDGER_FILE), 'utf8')
529
+ } catch (err) {
530
+ if (err.code === 'ENOENT') return { lock: null }
531
+ return { error: `${LEDGER_FILE} could not be read (${err.message}).` }
532
+ }
533
+ let raw
534
+ try {
535
+ raw = JSON.parse(text)
536
+ } catch (err) {
537
+ return { error: `${LEDGER_FILE} is not valid JSON (${err.message}). Fix it, or import the files again with asset_import.` }
538
+ }
539
+ const parsed = AssetLock.safeParse(raw)
540
+ if (!parsed.success) {
541
+ const first = parsed.error.issues[0]
542
+ return { error: `${LEDGER_FILE} does not satisfy its schema at ${first?.path.join('.') || 'the top'}: ${first?.message}.` }
543
+ }
544
+ return { lock: parsed.data }
545
+ }
546
+
547
+ /** Multipart body and its content-type. Encoded by the platform FormData so
548
+ * the boundary handling is the same one the server's formData() expects. */
549
+ async function encodeForm(parts) {
550
+ const form = new FormData()
551
+ form.set('repoKey', parts.repoKey)
552
+ form.set('sha', parts.sha)
553
+ form.set('requires', JSON.stringify(parts.requires))
554
+ // What this side speaks and what the planet needs of the server (schema
555
+ // contract.ts): a server that cannot do one of them refuses the request
556
+ // with contract_mismatch instead of publishing less of the planet. A server
557
+ // from before contract 3 ignores both.
558
+ form.set('contract', String(parts.contract))
559
+ form.set('needs', JSON.stringify(parts.needs))
560
+ form.set('main.js', new Blob([parts.bundle], { type: 'text/javascript' }), 'main.js')
561
+ form.set(CONFIG_FILE, new Blob([parts.config], { type: 'application/json' }), CONFIG_FILE)
562
+ if (parts.preview) form.set('preview.png', new Blob([parts.preview], { type: 'image/png' }), 'preview.png')
563
+ if (parts.splat) form.set('splat.bin', new Blob([parts.splat], { type: 'application/octet-stream' }), 'splat.bin')
564
+ if (parts.scene) form.set(SCENE_FILE, new Blob([parts.scene], { type: 'application/json' }), SCENE_FILE)
565
+ // The publish view of the ledger (publishLock): what each file is and under
566
+ // which licence, without prompts, costs or sources. The server checks the
567
+ // files against it and does not store it.
568
+ if (parts.ledger) form.set(LEDGER_FILE, new Blob([parts.ledger], { type: 'application/json' }), LEDGER_FILE)
569
+ // Each file is its own part, named by the project-relative path the scene
570
+ // or the code refers to it by, which is also the key it is stored under.
571
+ // They go up as octet-stream so nothing on the storage domain can be served
572
+ // as a document.
573
+ for (const asset of parts.assets ?? []) {
574
+ form.set(asset.path, new Blob([asset.bytes], { type: 'application/octet-stream' }), asset.path)
575
+ }
576
+ const encoded = new Response(form)
577
+ return {
578
+ contentType: encoded.headers.get('content-type'),
579
+ body: Buffer.from(await encoded.arrayBuffer()),
580
+ }
581
+ }
582
+
583
+ /** One POST over node's http(s), not fetch: the request's `finish` event is
584
+ * the moment the last byte has left, which is when "uploading" becomes
585
+ * "verifying" (the server is now checking). A content-length goes with it,
586
+ * so the gateway never sees a chunked upload. */
587
+ function post(url, { headers, body, signal, onSent }) {
588
+ return new Promise((resolve, reject) => {
589
+ const target = new URL(url)
590
+ const lib = target.protocol === 'https:' ? https : http
591
+ const req = lib.request(
592
+ target,
593
+ { method: 'POST', headers: { ...headers, 'content-length': body.length }, signal },
594
+ (res) => {
595
+ const chunks = []
596
+ res.on('data', (chunk) => chunks.push(chunk))
597
+ res.on('error', reject)
598
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }))
599
+ },
600
+ )
601
+ req.on('error', reject)
602
+ req.on('finish', () => onSent?.())
603
+ req.end(body)
604
+ })
605
+ }
606
+
607
+ // ---------------------------------------------------------------- the pre-flight
608
+
609
+ /**
610
+ * The project as a publish reads it, judged by the shared pre-flight
611
+ * (@nowhere/schema preparePublish): the config, the scene, the ledger, which
612
+ * files travel, and the function's own check on the request that would go
613
+ * up, against what the server and the player offer when those are given.
614
+ *
615
+ * The Publish button runs it with `write` (the default): a project whose code
616
+ * loads files only a ledger can carry gets its ledger started here, as its
617
+ * first import would, and the creator's own files that changed since they
618
+ * were recorded are measured again. `nowhere check` runs it with write: false,
619
+ * and the project is left exactly as it was: the same ledger is made in
620
+ * memory and judged, so the check says what the publish would.
621
+ *
622
+ * `code` is the bundle as it ships; `server`, `player` and `playerSdk` what
623
+ * the other side offers (preparePublish's). SHA-256 is read only for the
624
+ * files that travel and the ledger records. Answers { prepared, lock }
625
+ * (preparePublish's verdict, and the ledger it judged, or null), or
626
+ * { error, findings? } for a project whose documents cannot be read.
627
+ */
628
+ async function preflight(root, { code, server, player, playerSdk = null, write = true } = {}) {
629
+ const s = await schema()
630
+ const config = await readDocument(root, CONFIG_FILE)
631
+ if (config.absent) return { error: 'The project has no game.config.json.' }
632
+ if (config.error) return { error: config.error }
633
+ const scene = await readDocument(root, SCENE_FILE)
634
+ if (scene.error) return { error: scene.error }
635
+
636
+ const ledger = await readLedger(root, s.AssetLock)
637
+ if (ledger.error) return { error: ledger.error }
638
+ let lock = ledger.lock
639
+ if (lock) {
640
+ // The creator's own files (their drops, and what sat in assets/ before
641
+ // the ledger) are theirs to change: one re-exported over the same name is
642
+ // measured again rather than refused.
643
+ const refreshed = await (await ledgerModule()).refreshOwn(root, { write })
644
+ if (!refreshed.ok) return { error: refreshed.error }
645
+ if (refreshed.refreshed.length > 0 && refreshed.lock) lock = refreshed.lock
646
+ }
647
+
648
+ const files = []
649
+ for (const rel of await listAssets(root)) {
650
+ try {
651
+ const abs = path.join(root, rel)
652
+ const bytes = (await fsp.stat(abs)).size
653
+ // A model says what it needs of the player by the extensions it
654
+ // requires (contract 4: KTX2 textures, meshopt geometry).
655
+ const required = await modelRequires(abs, s)
656
+ files.push({ path: rel, bytes, ...(required ? { extensionsRequired: required } : {}) })
657
+ } catch {
658
+ // gone between the listing and the stat
659
+ }
660
+ }
661
+ const prepare = (withFiles) =>
662
+ s.preparePublish({ config: config.raw, scene: scene.absent ? undefined : scene.raw, ledger: lock, bundle: code, files: withFiles, server, player, playerSdk })
663
+
664
+ let prepared = prepare(files)
665
+ // The planet serves only what was sent, so a file the code loads and the
666
+ // scene does not place needs the ledger: a project without one starts it,
667
+ // which records every file assets/ holds as the creator's.
668
+ if (prepared.needsLedger) {
669
+ const started = await (await ledgerModule()).startLedger(root, { write })
670
+ if (!started.ok) {
671
+ const named = prepared.findings.find((f) => f.code === 'admit:unrecorded')?.path ?? 'a file'
672
+ return { error: `The game's code loads ${named}, which a planet carries only when ${LEDGER_FILE} records it, and the ledger could not be started: ${started.error}` }
673
+ }
674
+ lock = started.lock
675
+ prepared = prepare(files)
676
+ }
677
+ // Each file the ledger records is compared with its entry by content too.
678
+ if (lock) {
679
+ const recorded = new Set(Object.keys(lock.files ?? {}))
680
+ const hashes = new Map()
681
+ for (const upload of prepared.uploads) {
682
+ if (recorded.has(upload.path)) hashes.set(upload.path, await sha256Of(path.join(root, upload.path)))
683
+ }
684
+ if (hashes.size > 0) prepared = prepare(files.map((f) => (hashes.has(f.path) ? { ...f, sha256: hashes.get(f.path) } : f)))
685
+ }
686
+ // A web reference kept to look at only (the agent's nw_keep_pictures) never
687
+ // goes up, whatever name it was copied to.
688
+ const going = new Set([...prepared.uploads.map((u) => u.path), ...prepared.findings.map((f) => f.path).filter((p) => typeof p === 'string')])
689
+ const web = await (await import('./agent/reference/web.mjs')).webLookOnlyAmong(root, [...going].map((p) => path.join(root, p)))
690
+ if (web) return { error: `${path.relative(root, web.file).split(path.sep).join('/')} is a web reference kept to look at only (${web.why}), so it is not published. Build what it shows, or use a CC0 or public-domain picture.` }
691
+ return { prepared, lock }
692
+ }
693
+
694
+ // ---------------------------------------------------------------- the run
695
+
696
+ // One publish at a time. A second click while one runs is refused, and cancel
697
+ // aborts whatever the current one is doing.
698
+ let current = null
699
+
700
+ // ---------------------------------------------------------------- the agent's publish
701
+ // A planet goes up when a person presses Publish (REFERENCE_LOOP.md 1, 2.8).
702
+ // The creator's own button (main.cjs publish:run) is that press. The agent
703
+ // may only start the same flow after the creator pressed Publish on its
704
+ // approval card in the same run: the card's answer is given a token here
705
+ // (cards.cjs approvalToken, through main.cjs), the agent host hands it back
706
+ // with its publish call, and run() refuses an agent's publish without one,
707
+ // with one from another run or another project, or with one already used.
708
+ // The token is never in the model's hands: the approval tool passes it on.
709
+
710
+ /** How long a pressed Publish stays good for, unused. */
711
+ const APPROVAL_TTL_MS = 30 * 60 * 1000
712
+ /** token -> { runId, root, at } */
713
+ const approvals = new Map()
714
+
715
+ /** A one-use token for an agent run's publish of the project at `root`,
716
+ * issued when the creator pressed Publish on that run's approval card. */
717
+ function issueApproval({ runId, root, now = Date.now() } = {}) {
718
+ if (typeof runId !== 'string' || !runId || typeof root !== 'string' || !root) return null
719
+ const token = crypto.randomBytes(24).toString('hex')
720
+ approvals.set(token, { runId, root: path.resolve(root), at: now })
721
+ return token
722
+ }
723
+
724
+ /** Every token of a run (it ended), or every token. */
725
+ function revokeApprovals(runId) {
726
+ for (const [token, entry] of [...approvals]) if (runId === undefined || entry.runId === runId) approvals.delete(token)
727
+ }
728
+
729
+ /** Whether an agent's publish may go: its token, for this run and this
730
+ * project, unused and fresh. Leaves it as it is (main.cjs asks before it
731
+ * hands the press to the studio window's own publish). */
732
+ function checkApproval({ runId, token, root, now = Date.now() } = {}) {
733
+ const entry = typeof token === 'string' ? approvals.get(token) : undefined
734
+ if (!entry) return { ok: false, error: 'An agent publishes only after the creator pressed Publish on its approval card in this run; there is no such press for this publish.' }
735
+ if (entry.runId !== runId) return { ok: false, error: 'That approval was given in another run.' }
736
+ if (entry.root !== path.resolve(String(root ?? ''))) return { ok: false, error: 'That approval was given for another project.' }
737
+ if (now - entry.at > APPROVAL_TTL_MS) return { ok: false, error: 'That approval is more than 30 minutes old; ask again with the approval card.' }
738
+ return { ok: true }
739
+ }
740
+
741
+ /** checkApproval, then spends the token: a token that was tried is used,
742
+ * whether or not it was good. */
743
+ function takeApproval({ runId, token, root, now = Date.now() } = {}) {
744
+ const checked = checkApproval({ runId, token, root, now })
745
+ if (typeof token === 'string') approvals.delete(token)
746
+ return checked.ok ? { ok: true } : { ok: false, error: checked.error }
747
+ }
748
+
749
+ /**
750
+ * Publishes the project at `root`. Reports every state through `onProgress`
751
+ * and resolves with the final one: `{ state: 'done', result }`,
752
+ * `{ state: 'failed', error, findings? }`, `{ state: 'signin', error }`, or
753
+ * `{ state: 'idle' }` after a cancel. Never rejects.
754
+ */
755
+ async function run({ root, onProgress, agent = null }) {
756
+ // An agent's publish (main.cjs, the agent's 'publish' rpc) needs the
757
+ // creator's press on its approval card; the creator's own button passes
758
+ // no agent and goes as it always has.
759
+ // A publish already running refuses before the token is looked at, so the
760
+ // creator's press is still good for the one after it.
761
+ if (current) return { state: 'failed', error: 'A publish is already running.' }
762
+ if (agent) {
763
+ const taken = takeApproval({ runId: agent.runId, token: agent.token, root })
764
+ if (!taken.ok) return { state: 'failed', error: taken.error, refused: 'approval' }
765
+ }
766
+ const controller = new AbortController()
767
+ current = controller
768
+ const report = (progress) => {
769
+ try {
770
+ onProgress?.(progress)
771
+ } catch (err) {
772
+ console.warn('[publish] progress listener failed:', err?.message ?? err)
773
+ }
774
+ return progress
775
+ }
776
+ // Cancel is checked between steps; during the request it aborts the fetch.
777
+ const cancelled = () => controller.signal.aborted
778
+ const CANCELLED = { state: 'idle' }
779
+
780
+ try {
781
+ const outcome = await pipeline(root, report, controller, cancelled)
782
+ return report(cancelled() && outcome.state !== 'done' ? CANCELLED : outcome)
783
+ } catch (err) {
784
+ if (cancelled()) return report(CANCELLED)
785
+ console.warn('[publish] failed:', err)
786
+ return report({ state: 'failed', error: err?.message ?? String(err) })
787
+ } finally {
788
+ if (current === controller) current = null
789
+ }
790
+ }
791
+
792
+ /** Aborts the running publish, if there is one. A request already answered by
793
+ * the server has published anyway; the record is then only missing here. */
794
+ function cancel() {
795
+ current?.abort()
796
+ return !!current
797
+ }
798
+
799
+ async function pipeline(root, report, controller, cancelled) {
800
+ const failed = (error, findings) => ({ state: 'failed', error, ...(findings ? { findings } : {}) })
801
+
802
+ // 1. Who publishes. No token, no publish: the popover points at Settings.
803
+ const token = await deps.getAccessToken()
804
+ if (!token) return { state: 'signin', error: 'Sign in to nowhere to publish. The account lives in Settings.' }
805
+ if (cancelled()) return { state: 'idle' }
806
+
807
+ // 2. The config, with defaults applied: that is the copy the planet gets.
808
+ // The server and the player are asked what they can do meanwhile, so
809
+ // the answers are in by the time the build says what the planet needs.
810
+ report({ state: 'checking' })
811
+ const s = await schema()
812
+ const asking = readSides({ token, signal: controller.signal })
813
+ const config = await readDocument(root, CONFIG_FILE)
814
+ if (config.absent) return failed('The project has no game.config.json.')
815
+ if (config.error) return failed(config.error)
816
+ const checked = s.validateConfig(config.raw)
817
+ if (!checked.ok || !checked.config) {
818
+ return failed('game.config.json does not satisfy the schema.', findingLines(checked.findings))
819
+ }
820
+ const title = checked.config.title
821
+
822
+ // 3. The bundle, then everything else the function will check on it, as
823
+ // one call (preflight): the gates, the scene, the ledger, which files
824
+ // travel, every size, and what the planet needs of the other side.
825
+ const built = await buildGame(root)
826
+ if (!built.ok) return failed(`The game does not build.\n${built.error}`)
827
+ const sides = await asking
828
+ if (cancelled()) return { state: 'idle' }
829
+ for (const [side, reading] of Object.entries(sides)) {
830
+ if (reading.state === 'unknown') console.warn(`[publish] the ${side} did not say what it can do (${reading.reason}); publishing as before`)
831
+ }
832
+ // Kept for asset_import, which writes KTX2 and meshopt only for sides that
833
+ // take them. A failure to keep it is not the publish's.
834
+ try {
835
+ await (await targetsModule()).rememberSides(root, sides)
836
+ } catch (err) {
837
+ console.warn('[publish] what the server and the player said could not be kept:', err?.message ?? err)
838
+ }
839
+ const pre = await preflight(root, { code: built.code, server: offered(sides.server), player: offered(sides.player), playerSdk: sdkExportsOf(sides.player) })
840
+ if (pre.error) return failed(pre.error, pre.findings)
841
+ const prepared = pre.prepared
842
+ const own = prepared.findings.filter((f) => f.error !== 'contract_mismatch' && f.error !== 'player_mismatch')
843
+ if (own.length > 0) return failed(leadSentence(own), findingLines(prepared.findings))
844
+ // 4. The other side. A server or a player older than this planet (what it
845
+ // takes, what it plays, what its SDK exports) stops it here, before the
846
+ // commit and before a byte is uploaded. Files it cannot decode were
847
+ // written before the sides were known: the next imports write them
848
+ // plain (they read what was just kept), and the sentence says so.
849
+ if (olderThanPlanet(prepared.missing)) return failed(`${olderSentences(prepared.missing)}${decoderHint(prepared.missing)}`)
850
+
851
+ if (prepared.unknownKeys.length > 0) {
852
+ console.warn(`[publish] ${prepared.unknownKeys.join(', ')}: not settings this studio knows; the planet goes up without them`)
853
+ }
854
+ for (const rel of prepared.absent) console.warn(`[publish] ${rel} is in ${LEDGER_FILE} but not in the project; leaving it out`)
855
+ // Whatever else sits in assets/ stays on the machine. Said once, because a
856
+ // folder of rejected imports is normal and not a reason to stop.
857
+ if (prepared.left.length > 0) {
858
+ console.warn(
859
+ `[publish] ${prepared.left.length} file(s) in assets/ are not placed by scene.json, recorded for publishing in ${LEDGER_FILE} or named by the config or the game's code, and will not be uploaded: ${prepared.left.join(', ')}`,
860
+ )
861
+ }
862
+ if (cancelled()) return { state: 'idle' }
863
+
864
+ // 5. The commit this publish deploys. The repo_key is the root commit: the
865
+ // same project on another machine publishes to the same planet.
866
+ report({ state: 'committing' })
867
+ await git.ensureRepo(root, title)
868
+ const commit = await git.autoCommit(root, `publish: ${title}`)
869
+ if (commit.skipped || commit.error) {
870
+ return failed(
871
+ commit.skipped
872
+ ? 'The project could not be committed: another git process holds it. Try again in a moment.'
873
+ : `The project could not be committed (${commit.error}).`,
874
+ )
875
+ }
876
+ const sha = commit.sha
877
+ const repoKey = await git.rootCommitSha(root)
878
+ if (!sha || !repoKey) return failed('The project has no commits to publish.')
879
+ if (cancelled()) return { state: 'idle' }
880
+
881
+ // 6. One request. Uploading until the body has drained, verifying until the
882
+ // server answers.
883
+ report({ state: 'uploading' })
884
+ const preview = await readPreview(root, s.LIMITS.previewKb)
885
+ const splat = await readSplat(root, s.checkSplat)
886
+ // The files are read only now that everything else has passed. The whole
887
+ // body is one buffer, so a planet at the top of its budget is held in memory
888
+ // twice while it is encoded; that is the price of one request with a
889
+ // content-length, and the budget is what keeps the number bounded.
890
+ const assetParts = []
891
+ for (const upload of prepared.uploads) {
892
+ assetParts.push({ path: upload.path, bytes: await fsp.readFile(path.join(root, upload.path)) })
893
+ }
894
+ const { contentType, body } = await encodeForm({
895
+ repoKey,
896
+ sha,
897
+ requires: prepared.requires,
898
+ contract: s.PUBLISH_CONTRACT,
899
+ needs: prepared.needs,
900
+ bundle: built.code,
901
+ config: prepared.configText,
902
+ preview,
903
+ splat,
904
+ scene: prepared.sceneText,
905
+ ledger: prepared.ledgerText,
906
+ assets: assetParts,
907
+ })
908
+
909
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
910
+ let response
911
+ try {
912
+ response = await post(`${deps.endpointBase}/publish`, {
913
+ headers: { authorization: `Bearer ${token}`, 'content-type': contentType, 'x-region': FUNCTION_REGION },
914
+ body,
915
+ signal: controller.signal,
916
+ onSent: () => {
917
+ if (!cancelled()) report({ state: 'verifying' })
918
+ },
919
+ })
920
+ } catch (err) {
921
+ if (cancelled()) return { state: 'idle' }
922
+ return failed(`Oda could not be reached (${err?.cause?.message ?? err?.message ?? err}). Check the connection and try again.`)
923
+ } finally {
924
+ clearTimeout(timeout)
925
+ }
926
+
927
+ let answer = null
928
+ try {
929
+ answer = JSON.parse(response.text)
930
+ } catch {
931
+ // A non-JSON body (a gateway page) is reported by status alone.
932
+ }
933
+
934
+ if (response.status === 401) {
935
+ return { state: 'signin', error: SERVER_SENTENCES.not_signed_in }
936
+ }
937
+ if (response.status < 200 || response.status >= 300) {
938
+ const findings = findingLines(answer?.findings)
939
+ return failed(sentenceFor(response.status, answer), findings.length ? findings : undefined)
940
+ }
941
+ if (!answer || typeof answer.id !== 'string' || typeof answer.version !== 'number') {
942
+ return failed('Oda answered, but not with a planet. Try again.')
943
+ }
944
+
945
+ // 7. The record. `url` is what the launcher reads to light the lamp.
946
+ const result = {
947
+ id: answer.id,
948
+ sha: typeof answer.sha === 'string' ? answer.sha : sha,
949
+ version: answer.version,
950
+ title: typeof answer.title === 'string' ? answer.title : title,
951
+ url: typeof answer.planetUrl === 'string' && isPlanetUrl(answer.planetUrl) ? answer.planetUrl : `${PLANET_URL}?planet=${answer.id}`,
952
+ }
953
+ const record = {
954
+ v: 1,
955
+ id: result.id,
956
+ sha: result.sha,
957
+ version: result.version,
958
+ url: result.url,
959
+ publishedAt: new Date().toISOString(),
960
+ status: 'live',
961
+ }
962
+ const file = path.join(root, PUBLISHED_FILE)
963
+ await fsp.mkdir(path.dirname(file), { recursive: true })
964
+ await fsp.writeFile(file, JSON.stringify(record, null, 2) + '\n', 'utf8')
965
+
966
+ return { state: 'done', result }
967
+ }
968
+
969
+ /** A link to the world, or to one planet in it (`?planet=<id>`, which the
970
+ * world answers by flying the visitor there). The only URLs the Publish
971
+ * popover may hand to the system browser. */
972
+ function isPlanetUrl(url) {
973
+ if (url === PLANET_URL) return true
974
+ return typeof url === 'string' && /^\?planet=[a-z0-9]{10}$/.test(url.slice(PLANET_URL.length)) && url.startsWith(PLANET_URL)
975
+ }
976
+
977
+ /** The last publish record for a project, or null. */
978
+ function readRecord(root) {
979
+ try {
980
+ return JSON.parse(fs.readFileSync(path.join(root, PUBLISHED_FILE), 'utf8'))
981
+ } catch {
982
+ return null
983
+ }
984
+ }
985
+
986
+ module.exports = {
987
+ issueApproval,
988
+ revokeApprovals,
989
+ checkApproval,
990
+ takeApproval,
991
+ PLANET_URL,
992
+ isPlanetUrl,
993
+ SUPABASE_FUNCTIONS,
994
+ FUNCTION_REGION,
995
+ PLAYER_INFO,
996
+ INFO_TIMEOUT_MS,
997
+ STATES,
998
+ SERVER_SENTENCES,
999
+ configure,
1000
+ run,
1001
+ cancel,
1002
+ readRecord,
1003
+ sentenceFor,
1004
+ leadSentence,
1005
+ olderSentences,
1006
+ decoderHint,
1007
+ modelRequires,
1008
+ listAssets,
1009
+ writeSplat,
1010
+ readPreview,
1011
+ preflight,
1012
+ readSides,
1013
+ infoUrls,
1014
+ offered,
1015
+ sdkExportsOf,
1016
+ olderThanPlanet,
1017
+ dryRun,
1018
+ }